1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
|
//! Task lifecycle manager using git worktrees and Claude Code subprocesses.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use base64::Engine;
use rand::Rng;
use tokio::io::AsyncWriteExt;
use tokio::sync::{mpsc, RwLock};
use uuid::Uuid;
use std::collections::HashSet;
use super::completion_gate::{CircuitBreaker, CompletionGate};
use super::state::TaskState;
use crate::daemon::config::CheckpointPatchConfig;
use crate::daemon::error::{DaemonError, TaskError, TaskResult};
use crate::daemon::process::{ClaudeInputMessage, ProcessManager};
use crate::daemon::storage;
use crate::daemon::temp::TempManager;
use crate::daemon::worktree::{is_new_repo_request, ConflictResolution, WorktreeInfo, WorktreeManager};
use crate::daemon::db::local::LocalDb;
use crate::daemon::ws::{BranchInfo, DaemonCommand, DaemonMessage};
/// Generate a secure random API key for orchestrator tool access.
fn generate_tool_key() -> String {
let mut rng = rand::thread_rng();
let bytes: [u8; 32] = rng.r#gen();
hex::encode(bytes)
}
/// Check if output contains an OAuth authentication error.
/// Only checks system/error messages, not assistant responses (which could mention auth errors conversationally).
fn is_oauth_auth_error(output: &str, json_type: Option<&str>, is_stdout: bool) -> bool {
// Only check system messages or stderr output - not assistant messages
// which could mention auth errors in conversation
match json_type {
Some("assistant") | Some("user") | Some("result") => return false,
_ => {}
}
// For stdout JSON messages, only check system/error types
if is_stdout && json_type.is_none() {
// Non-JSON stdout output - could be startup messages, check carefully
// Only match very specific patterns that wouldn't appear in conversation
}
// Match various authentication error patterns from Claude Code
// These patterns are specific enough that they shouldn't appear in normal conversation
if output.contains("Please run /login") && output.contains("authenticate") {
return true;
}
if output.contains("Invalid API key") && output.contains("ANTHROPIC_API_KEY") {
return true;
}
if output.contains("authentication_error")
&& (output.contains("OAuth token has expired")
|| output.contains("Please obtain a new token"))
{
return true;
}
// Check for Claude Code's specific error format
if output.contains("\"type\":\"error\"") && output.contains("authentication") {
return true;
}
false
}
/// Extract OAuth URL from text (looks for claude.ai OAuth URLs).
fn extract_url(text: &str) -> Option<String> {
// Look for claude.ai OAuth URLs - try multiple patterns
let patterns = [
"https://claude.ai/oauth",
"https://console.anthropic.com/oauth",
];
for pattern in patterns {
if let Some(start) = text.find(pattern) {
let remaining = &text[start..];
// Find the end of the URL - stop at:
// - Whitespace, common URL terminators, escape sequences
let end = remaining
.find(|c: char| {
c.is_whitespace() || c == '"' || c == '\'' || c == '>' || c == ')' || c == ']' || c == '\x07' || c == '\x1b'
})
.unwrap_or(remaining.len());
let url = &remaining[..end];
// Also check if there's another https:// within the match (hyperlink duplication)
// Skip first 20 chars to avoid matching the start
let url = if url.len() > 30 {
if let Some(second_https) = url[20..].find("https://") {
&url[..second_https + 20] // Keep only first URL
} else {
url
}
} else {
url
};
if url.len() > 20 {
return Some(url.to_string());
}
}
}
None
}
/// Global storage for pending OAuth flow (only one can be active at a time per daemon)
static PENDING_AUTH_FLOW: std::sync::OnceLock<std::sync::Mutex<Option<std::sync::mpsc::Sender<String>>>> = std::sync::OnceLock::new();
fn get_auth_flow_storage() -> &'static std::sync::Mutex<Option<std::sync::mpsc::Sender<String>>> {
PENDING_AUTH_FLOW.get_or_init(|| std::sync::Mutex::new(None))
}
/// Send an auth code to the pending OAuth flow.
pub fn send_auth_code(code: &str) -> bool {
let storage = get_auth_flow_storage();
if let Ok(mut guard) = storage.lock() {
if let Some(sender) = guard.take() {
if sender.send(code.to_string()).is_ok() {
tracing::info!("Auth code sent to setup-token process");
return true;
}
}
}
tracing::warn!("No pending auth flow to send code to");
false
}
/// Spawn `claude setup-token` to initiate OAuth flow and capture the login URL.
/// This spawns the process in a PTY (required by Ink) and reads output until we find a URL.
/// The process continues running in the background waiting for auth completion.
async fn get_oauth_login_url(claude_command: &str) -> Option<String> {
use portable_pty::{native_pty_system, CommandBuilder, PtySize};
use std::io::{Read, Write};
tracing::info!("Spawning claude setup-token in PTY to get OAuth login URL");
// Create a PTY - Ink requires a real terminal
let pty_system = native_pty_system();
let pair = match pty_system.openpty(PtySize {
rows: 24,
cols: 200, // Wide enough to avoid line wrapping for long URLs/codes
pixel_width: 0,
pixel_height: 0,
}) {
Ok(pair) => pair,
Err(e) => {
tracing::error!(error = %e, "Failed to open PTY");
return None;
}
};
// Build the command
let mut cmd = CommandBuilder::new(claude_command);
cmd.arg("setup-token");
// Set environment variables to prevent browser from opening and disable fancy output
// Use "false" so the browser command fails, forcing setup-token to show URL and wait for manual input
cmd.env("BROWSER", "false");
cmd.env("TERM", "dumb"); // Disable hyperlinks and fancy terminal features
cmd.env("NO_COLOR", "1"); // Disable colors
// Spawn the process in the PTY
let mut child = match pair.slave.spawn_command(cmd) {
Ok(child) => child,
Err(e) => {
tracing::error!(error = %e, "Failed to spawn claude setup-token in PTY");
return None;
}
};
// Get the reader and writer from the master side
let mut reader = match pair.master.try_clone_reader() {
Ok(reader) => reader,
Err(e) => {
tracing::error!(error = %e, "Failed to clone PTY reader");
return None;
}
};
let mut writer = match pair.master.take_writer() {
Ok(writer) => writer,
Err(e) => {
tracing::error!(error = %e, "Failed to take PTY writer");
return None;
}
};
// Create channels for communication
let (code_tx, code_rx) = std::sync::mpsc::channel::<String>();
let (url_tx, url_rx) = std::sync::mpsc::channel::<String>();
// Store the code sender globally so it can be used when AUTH_CODE message arrives
{
let storage = get_auth_flow_storage();
if let Ok(mut guard) = storage.lock() {
*guard = Some(code_tx);
}
}
// Spawn reader thread - reads PTY output and sends URL when found
let reader_handle = std::thread::spawn(move || {
let mut buffer = [0u8; 4096];
let mut accumulated = String::new();
let mut url_sent = false;
let mut read_count = 0;
tracing::info!("setup-token reader thread started");
loop {
match reader.read(&mut buffer) {
Ok(0) => {
tracing::info!("setup-token PTY EOF reached after {} reads", read_count);
break;
}
Ok(n) => {
read_count += 1;
let chunk = String::from_utf8_lossy(&buffer[..n]);
accumulated.push_str(&chunk);
// Process complete lines
while let Some(newline_pos) = accumulated.find('\n') {
let line = accumulated[..newline_pos].to_string();
accumulated = accumulated[newline_pos + 1..].to_string();
let clean_line = strip_ansi_codes(&line);
if !clean_line.trim().is_empty() {
tracing::info!(line = %clean_line, "setup-token output");
}
// Look for OAuth URL if not found yet
if !url_sent {
if let Some(url) = extract_url(&line) {
tracing::info!(url = %url, "Found OAuth login URL");
let _ = url_tx.send(url);
url_sent = true;
}
}
// Check for success/failure messages
if clean_line.contains("successfully") || clean_line.contains("authenticated") || clean_line.contains("Success") {
tracing::info!("Authentication appears successful!");
}
if clean_line.contains("error") || clean_line.contains("failed") || clean_line.contains("invalid") {
tracing::warn!(line = %clean_line, "setup-token may have encountered an error");
}
}
}
Err(e) => {
tracing::warn!(error = %e, "PTY read error after {} reads", read_count);
break;
}
}
}
tracing::info!("setup-token reader thread ended");
});
// Spawn writer thread - waits for auth code and writes it to PTY
std::thread::spawn(move || {
tracing::info!("setup-token writer thread started, waiting for auth code (10 min timeout)");
// Wait for auth code from frontend (with long timeout - user needs time to authenticate)
match code_rx.recv_timeout(std::time::Duration::from_secs(600)) {
Ok(code) => {
tracing::info!(code_len = code.len(), "Received auth code from frontend, writing to PTY");
// Write code followed by carriage return (Enter key in raw terminal mode)
let code_with_enter = format!("{}\r", code);
if let Err(e) = writer.write_all(code_with_enter.as_bytes()) {
tracing::error!(error = %e, "Failed to write auth code to PTY");
} else if let Err(e) = writer.flush() {
tracing::error!(error = %e, "Failed to flush PTY writer");
} else {
tracing::info!("Auth code written to setup-token PTY successfully");
// Give Ink a moment to process, then send another Enter in case first was buffered
std::thread::sleep(std::time::Duration::from_millis(100));
let _ = writer.write_all(b"\r");
let _ = writer.flush();
tracing::info!("Sent additional Enter keypress");
}
}
Err(e) => {
tracing::info!(error = %e, "Auth code receive ended (timeout or channel closed)");
}
}
// Wait for reader thread to finish
tracing::debug!("Waiting for reader thread to finish...");
let _ = reader_handle.join();
// Wait for child to fully exit
tracing::debug!("Waiting for setup-token child process to exit...");
match child.wait() {
Ok(status) => {
tracing::info!(exit_status = ?status, "setup-token process exited");
}
Err(e) => {
tracing::error!(error = %e, "Failed to wait for setup-token process");
}
}
});
// Wait for URL with timeout
match url_rx.recv_timeout(std::time::Duration::from_secs(30)) {
Ok(url) => Some(url),
Err(e) => {
tracing::error!(error = %e, "Timed out waiting for OAuth login URL");
None
}
}
}
/// Strip ANSI escape codes from a string for cleaner logging.
fn strip_ansi_codes(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
if c == '\x1b' {
// Check what type of escape sequence
match chars.peek() {
Some(&'[') => {
// CSI sequence: ESC [ ... letter
chars.next(); // consume '['
while let Some(&next) = chars.peek() {
chars.next();
if next.is_ascii_alphabetic() {
break;
}
}
}
Some(&']') => {
// OSC sequence: ESC ] ... ST (where ST is BEL or ESC \)
chars.next(); // consume ']'
while let Some(&next) = chars.peek() {
if next == '\x07' {
chars.next(); // consume BEL (string terminator)
break;
}
if next == '\x1b' {
chars.next(); // consume ESC
if chars.peek() == Some(&'\\') {
chars.next(); // consume \ (string terminator)
}
break;
}
chars.next();
}
}
_ => {
// Unknown escape, skip just the ESC
}
}
} else if !c.is_control() || c == '\n' {
result.push(c);
}
}
result
}
/// System prompt for regular (non-orchestrator) subtasks.
/// This tells subtasks they share a worktree with the supervisor and other tasks.
const SUBTASK_SYSTEM_PROMPT: &str = r#"You are working in a shared worktree directory with other tasks in this contract.
## IMPORTANT: Shared Worktree
**You share this worktree with the supervisor and other tasks in the contract.**
- Work within your assigned area (files/modules specified in your task plan)
- Be aware other tasks may be modifying other parts of the codebase
- Your changes will be auto-committed when your task completes
- DO NOT make commits yourself - the system handles this
## Directory Restrictions
- DO NOT use `cd` to navigate outside your worktree
- DO NOT use absolute paths pointing outside the worktree
- All file operations should be relative to the current directory
## Your Role
1. Complete the specific task assigned to you
2. Stay focused on your task plan
3. The system will commit and integrate your changes automatically
---
"#;
/// The orchestrator system prompt that tells Claude how to use the helper script.
const ORCHESTRATOR_SYSTEM_PROMPT: &str = r#"You are an orchestrator task. Your job is to coordinate subtasks and integrate their work, NOT to write code directly.
## FIRST STEP
Start by checking if you have existing subtasks:
```bash
# List all subtasks to see what work needs to be done
./.makima/orchestrate.sh list
```
If subtasks exist, start them. If you need additional subtasks or no subtasks exist yet, you can create them.
---
## Creating Subtasks
You can create new subtasks to break down work:
```bash
# Create a new subtask with a name and plan
./.makima/orchestrate.sh create "Subtask Name" "Detailed plan for what the subtask should do..."
# The command returns the new subtask ID - use it to start the subtask
./.makima/orchestrate.sh start <new_subtask_id>
```
Create subtasks when you need to:
- Break down complex work into smaller pieces
- Run multiple tasks in parallel on different parts of the codebase
- Delegate specific implementation work
## Task Continuation (Sequential Dependencies)
When subtasks need to build on each other's work (e.g., Task B depends on Task A's changes), use `--continue-from`:
```bash
# Create Task B that continues from Task A's worktree
./.makima/orchestrate.sh create "Task B" "Build on Task A's work..." --continue-from <task_a_id>
```
This copies all files from Task A's worktree into Task B's worktree, so Task B starts with Task A's changes.
**When to use continuation:**
- Sequential work: Task B needs Task A's output files
- Staged implementation: Building features incrementally
- Fix-and-extend: One task fixes issues, another adds features on top
**When NOT to use continuation:**
- Parallel tasks working on different files
- Independent subtasks that can be merged separately
**Important for merging:** When tasks continue from each other, only merge the FINAL task in the chain. Earlier tasks' changes are already included in later tasks' worktrees.
## Sharing Files with Subtasks
Use `--files` to copy specific files from your orchestrator worktree to subtasks. This is useful for sharing plans, configs, or data files:
```bash
# Create subtask with specific files copied from orchestrator
./.makima/orchestrate.sh create "Implement Feature" "Follow the plan in PLAN.md" --files "PLAN.md"
# Copy multiple files (comma-separated)
./.makima/orchestrate.sh create "API Work" "Use the spec..." --files "PLAN.md,api-spec.yaml,types.ts"
# Combine with --continue-from to share files AND continue from another task
./.makima/orchestrate.sh create "Step 2" "Continue..." --continue-from <task_a_id> --files "requirements.md"
```
**Use cases for --files:**
- Share a PLAN.md with detailed implementation steps
- Distribute configuration or spec files
- Pass generated data or intermediate results
## How Subtasks Work
Each subtask runs in its own **worktree** - a separate directory with a copy of the codebase. When subtasks complete:
- Their work remains in the worktree files (NOT committed to git)
- **Subtasks do NOT auto-merge** - YOU must integrate their work into your worktree
- You can view and copy files from subtask worktrees using their paths
- The worktree path is returned when you get subtask status
**IMPORTANT:** Subtasks never create PRs or merge to the target repository. Only the orchestrator (you) can trigger completion actions like PR creation or merging after integrating all subtask work.
## Subtask Commands
```bash
# List all subtasks and their current status
./.makima/orchestrate.sh list
# Create a new subtask (returns the subtask ID)
./.makima/orchestrate.sh create "Name" "Plan/description"
# Create a subtask that continues from another task's worktree
./.makima/orchestrate.sh create "Name" "Plan" --continue-from <other_task_id>
# Create a subtask with specific files copied from orchestrator worktree
./.makima/orchestrate.sh create "Name" "Plan" --files "file1.md,file2.yaml"
# Start a specific subtask (it will run in its own Claude instance)
./.makima/orchestrate.sh start <subtask_id>
# Stop a running subtask
./.makima/orchestrate.sh stop <subtask_id>
# Get detailed status of a subtask (includes worktree_path when available)
./.makima/orchestrate.sh status <subtask_id>
# Get the output/logs of a subtask
./.makima/orchestrate.sh output <subtask_id>
# Get the worktree path for a subtask
./.makima/orchestrate.sh worktree <subtask_id>
```
## Integrating Subtask Work
When subtasks complete, their changes exist as files in their worktree directories:
- Files are NOT committed to git branches
- You must copy/integrate files from subtask worktrees into your worktree
- Use standard file operations (cp, cat, etc.) to review and integrate changes
### Handling Continuation Chains
**CRITICAL:** When subtasks use `--continue-from`, they form a chain where each task includes all changes from previous tasks. You must ONLY integrate the FINAL task in each chain.
Example chain: Task A → Task B (continues from A) → Task C (continues from B)
- Task C's worktree contains ALL changes from A, B, and C
- You should ONLY integrate Task C's worktree
- DO NOT integrate Task A or Task B separately (their changes are already in C)
**How to track continuation chains:**
1. When you create tasks with `--continue-from`, note which task continues from which
2. Build a mental model: Independent tasks (no continuation) + Continuation chains
3. For each chain, only integrate the LAST task in the chain
**Example with mixed independent and chained tasks:**
```
Independent tasks (integrate all):
- Task X: API endpoints
- Task Y: Database models
Continuation chain (integrate ONLY the last one):
- Task A: Core feature → Task B: Tests (continues from A) → Task C: Docs (continues from B)
Only integrate Task C!
```
### Integration Examples
For independent subtasks (no continuation):
```bash
# Get the worktree path for a completed subtask
SUBTASK_PATH=$(./.makima/orchestrate.sh worktree <subtask_id>)
# View what files were changed
ls -la "$SUBTASK_PATH"
diff -r . "$SUBTASK_PATH" --exclude=.git --exclude=.makima
# Copy specific files from subtask
cp "$SUBTASK_PATH/src/new_file.rs" ./src/
cp "$SUBTASK_PATH/src/modified_file.rs" ./src/
# Or use diff/patch for more control
diff -u ./src/file.rs "$SUBTASK_PATH/src/file.rs" > changes.patch
patch -p0 < changes.patch
```
For continuation chains (only integrate the final task):
```bash
# If you have: Task A → Task B → Task C (each continues from previous)
# ONLY get and integrate Task C's worktree - it has everything!
FINAL_TASK_PATH=$(./.makima/orchestrate.sh worktree <task_c_id>)
# Copy all changes from the final task
rsync -av --exclude='.git' --exclude='.makima' "$FINAL_TASK_PATH/" ./
```
## Completion
```bash
# Mark yourself as complete after integrating all subtask work
./.makima/orchestrate.sh done "Summary of what was accomplished"
```
## Workflow
1. **List existing subtasks**: Run `list` to see current subtasks
2. **Create subtasks if needed**: Use `create` to add new subtasks for the work
- For independent parallel work: create without `--continue-from`
- For sequential dependencies: use `--continue-from <previous_task_id>`
- Track which tasks continue from which (continuation chains)
3. **Start subtasks**: Run `start` for each subtask
4. **Monitor progress**: Check status and output as subtasks run
5. **Integrate work**: When subtasks complete:
- For independent tasks: integrate each one's worktree
- For continuation chains: ONLY integrate the FINAL task (it has all changes)
- Get worktree path with `worktree <subtask_id>`
- Copy or merge files into your worktree
6. **Complete**: Call `done` once all work is integrated
## Important Notes
- Subtask files are in worktrees, NOT committed git branches
- **Subtasks do NOT auto-merge or create PRs** - you must integrate their work
- You can read files from subtask worktrees using their paths
- Use standard file tools (cp, diff, cat, rsync) to integrate changes
- You should NOT edit files directly - that's what subtasks are for
- DO NOT DO THE SUBTASKS' WORK! Your only job is to coordinate, not implement.
- When you call `done`, YOUR worktree may be used for the final PR/merge
"#;
/// System prompt for supervisor tasks (contract orchestrators).
/// Supervisors coordinate work by spawning tasks and responding to user questions.
/// Git operations and phase advancement are handled automatically by the system.
const SUPERVISOR_SYSTEM_PROMPT: &str = r###"You are the SUPERVISOR for this contract. Your job is to coordinate work by spawning tasks and responding to user questions.
## WHAT YOU DO
1. Break down the contract goal into actionable tasks
2. Spawn tasks using `makima supervisor spawn "Task Name" "Detailed plan..."`
3. Wait for tasks to complete using `makima supervisor wait <task_id>`
4. Respond to user questions when asked
## WHAT THE SYSTEM HANDLES AUTOMATICALLY
- **Phase advancement** - When deliverables are complete, the system advances the phase
- **Git commits** - Tasks auto-commit their changes on completion
- **Pull requests** - System auto-creates PR when execute phase completes
- **You will be notified** when phases advance so you know to continue
## CRITICAL RULES
1. **NEVER write code or edit files yourself** - you are a coordinator ONLY
2. **ALWAYS spawn tasks** for ANY work that involves writing or editing code
3. **ALWAYS wait for tasks to complete** - you MUST use `wait` after spawning
## AVAILABLE COMMANDS
### Task Management
```bash
makima supervisor spawn "Task Name" "Detailed plan..." # Create and start a task
makima supervisor wait <task_id> [timeout_seconds] # Wait for task completion
makima supervisor tasks # List all tasks
makima supervisor tree # View task tree
makima supervisor diff <task_id> # View task changes
makima supervisor read-file <task_id> <file_path> # Read file from task
```
### User Interaction
```bash
makima supervisor ask "Your question" [--choices "A,B,C"] # Ask user
makima supervisor status # Contract status (read-only)
```
## WORKFLOW PATTERN
```bash
# 1. Spawn a task
RESULT=$(makima supervisor spawn "Implement feature X" "Details...")
TASK_ID=$(echo "$RESULT" | jq -r '.taskId')
# 2. Wait for it
makima supervisor wait "$TASK_ID"
# 3. Check result
makima supervisor diff "$TASK_ID"
# 4. Repeat for more tasks
# System handles commits, merging, and PR creation automatically
```
## MULTI-PHASE PLANS
When the plan document contains multiple implementation phases (Phase 1, Phase 2, etc.):
1. **Read the plan** to identify ALL phases
2. **Execute phases SEQUENTIALLY** - complete Phase 1 before Phase 2
3. **Track your progress** - keep track of which phases are done
4. **Confirm between phases** - use `ask` to confirm before proceeding
5. The system will auto-create PR when ALL phases are complete
## IMPORTANT NOTES
- DO NOT call advance-phase - the system does this automatically
- DO NOT manage git operations (branch, merge, pr) - the system handles this
- Focus ONLY on spawning tasks and responding to users
- You share a worktree with all tasks - changes are visible immediately
- If you need user input, use `makima supervisor ask`
- When all work is complete, use `makima supervisor complete` to finish
## WHEN TASKS COMPLETE
When a task completes:
1. Check the result with `makima supervisor diff <task_id>`
2. If more work needed, spawn another task
3. The system automatically commits changes
When ALL work is complete:
- Use `makima supervisor complete` to mark the contract done
- The system will auto-create PR (for remote repos)
"###;
/// System prompt for tasks that are part of a contract.
/// This tells the task about contract.sh and how to use it to interact with the contract.
const CONTRACT_INTEGRATION_PROMPT: &str = r##"
## Contract Integration
This task is part of a contract. You have access to contract tools via the `makima contract` CLI.
### Contract Commands
```bash
# Get contract context (name, phase, goals)
makima contract status
# Get phase checklist and deliverables
makima contract checklist
# List contract files
makima contract files
# Read a specific file content
makima contract file <file_id>
# Report progress to the contract
makima contract report "Completed X, working on Y..."
# Create a new contract file (content via stdin)
echo "# New Documentation" | makima contract create-file "New Document"
# Update an existing contract file (content via stdin)
cat updated_content.md | makima contract update-file <file_id>
# Get suggested next action when done
makima contract suggest-action
# Report completion with metrics
makima contract completion-action --files "file1.rs,file2.rs" --code
```
### What You Should Do
**Before starting:**
1. Run `makima contract status` to understand the contract context
2. Run `makima contract checklist` to see phase deliverables
3. Run `makima contract files` to see existing documentation
**While working:**
- Report significant progress with `makima contract report "..."`
**When completing:**
1. If your work should be documented, create or update contract files
2. Run `makima contract completion-action` to see recommended next steps
3. Consider what contract files or phases might need updating
**Important:** Your work should contribute to the contract's goals. Check the contract status to understand what's expected.
---
"##;
/// Tracks merge state for an orchestrator task.
#[derive(Default)]
struct MergeTracker {
/// Subtask branches that have been successfully merged.
merged_subtasks: HashSet<Uuid>,
/// Subtask branches that were explicitly skipped (with reason).
skipped_subtasks: HashMap<Uuid, String>,
}
/// Managed task information.
#[derive(Clone)]
pub struct ManagedTask {
/// Task ID.
pub id: Uuid,
/// Human-readable task name.
pub task_name: String,
/// Current state.
pub state: TaskState,
/// Worktree info if created.
pub worktree: Option<WorktreeInfo>,
/// Task plan.
pub plan: String,
/// Repository URL or path.
pub repo_source: Option<String>,
/// Base branch.
pub base_branch: Option<String>,
/// Target branch to merge into.
pub target_branch: Option<String>,
/// Parent task ID if this is a subtask.
pub parent_task_id: Option<Uuid>,
/// Depth in task hierarchy (0=top-level, 1=subtask, 2=sub-subtask).
pub depth: i32,
/// Whether this task runs as an orchestrator (coordinates subtasks).
pub is_orchestrator: bool,
/// Whether this task is a supervisor (long-running contract orchestrator).
pub is_supervisor: bool,
/// Path to target repository for completion actions.
pub target_repo_path: Option<String>,
/// Completion action: "none", "branch", "merge", "pr".
pub completion_action: Option<String>,
/// Task ID to continue from (copy worktree from this task).
pub continue_from_task_id: Option<Uuid>,
/// Files to copy from parent task's worktree.
pub copy_files: Option<Vec<String>>,
/// Contract ID if this task is associated with a contract.
pub contract_id: Option<Uuid>,
/// Key used for concurrency tracking (contract_id or task_id for standalone).
pub concurrency_key: Uuid,
/// Whether to run in autonomous loop mode.
pub autonomous_loop: bool,
/// Whether the contract is in local-only mode (skips automatic completion actions).
pub local_only: bool,
/// Whether to auto-merge to target branch locally when local_only mode is enabled.
pub auto_merge_local: bool,
/// If set, merge this task's changes to the supervisor's worktree on completion (cross-daemon case).
pub merge_to_supervisor_task_id: Option<Uuid>,
/// If set, this task shares the worktree of the specified supervisor task.
pub supervisor_worktree_task_id: Option<Uuid>,
/// Time task was created.
pub created_at: Instant,
/// Time task started running.
pub started_at: Option<Instant>,
/// Time task completed.
pub completed_at: Option<Instant>,
/// Error message if failed.
pub error: Option<String>,
}
/// Configuration for task execution.
#[derive(Clone)]
pub struct TaskConfig {
/// Maximum concurrent tasks (global cap).
pub max_concurrent_tasks: u32,
/// Maximum concurrent tasks per contract/supervisor.
pub max_tasks_per_contract: u32,
/// Base directory for worktrees.
pub worktree_base_dir: PathBuf,
/// Environment variables to pass to Claude.
pub env_vars: HashMap<String, String>,
/// Claude command path.
pub claude_command: String,
/// Additional arguments to pass to Claude Code.
pub claude_args: Vec<String>,
/// Arguments to pass before defaults.
pub claude_pre_args: Vec<String>,
/// Enable Claude's permission system.
pub enable_permissions: bool,
/// Disable verbose output.
pub disable_verbose: bool,
/// Bubblewrap sandbox configuration.
pub bubblewrap: Option<crate::daemon::config::BubblewrapConfig>,
/// API URL for spawned tasks (HTTP endpoint for makima CLI).
pub api_url: String,
/// API key for making authenticated API calls.
pub api_key: String,
/// Interval in seconds between heartbeat commits (WIP checkpoints).
/// Set to 0 to disable. Default: 300 (5 minutes).
pub heartbeat_commit_interval_secs: u64,
/// Checkpoint patch storage configuration.
pub checkpoint_patches: CheckpointPatchConfig,
}
impl Default for TaskConfig {
fn default() -> Self {
Self {
max_concurrent_tasks: 10,
max_tasks_per_contract: 10,
worktree_base_dir: WorktreeManager::default_base_dir(),
env_vars: HashMap::new(),
claude_command: "claude".to_string(),
claude_args: Vec::new(),
claude_pre_args: Vec::new(),
enable_permissions: false,
disable_verbose: false,
bubblewrap: None,
api_url: "https://api.makima.jp".to_string(),
api_key: String::new(),
heartbeat_commit_interval_secs: 300, // 5 minutes
checkpoint_patches: CheckpointPatchConfig::default(),
}
}
}
/// Task manager for handling task lifecycle.
pub struct TaskManager {
/// Worktree manager.
worktree_manager: Arc<WorktreeManager>,
/// Process manager.
process_manager: Arc<ProcessManager>,
/// Temp directory manager.
temp_manager: Arc<TempManager>,
/// Task configuration.
config: TaskConfig,
/// Active tasks.
tasks: Arc<RwLock<HashMap<Uuid, ManagedTask>>>,
/// Channel to send messages to server.
ws_tx: mpsc::Sender<DaemonMessage>,
/// Tracks running task count per contract (or per standalone task).
/// Key is contract_id for contract tasks, or task_id for standalone tasks.
contract_task_counts: Arc<RwLock<HashMap<Uuid, usize>>>,
/// Channels for sending input to running tasks.
/// Each sender allows sending messages to the stdin of a running Claude process.
task_inputs: Arc<RwLock<HashMap<Uuid, mpsc::Sender<String>>>>,
/// Tracks merge state per orchestrator task (for completion gate).
merge_trackers: Arc<RwLock<HashMap<Uuid, MergeTracker>>>,
/// Active process PIDs for graceful shutdown.
active_pids: Arc<RwLock<HashMap<Uuid, u32>>>,
/// Inherited git user.email for worktrees.
git_user_email: Arc<RwLock<Option<String>>>,
/// Inherited git user.name for worktrees.
git_user_name: Arc<RwLock<Option<String>>>,
/// Local SQLite database for crash recovery.
local_db: Arc<std::sync::Mutex<LocalDb>>,
}
impl TaskManager {
/// Create a new task manager with local database for crash recovery.
pub fn new(
config: TaskConfig,
ws_tx: mpsc::Sender<DaemonMessage>,
local_db: Arc<std::sync::Mutex<LocalDb>>,
) -> Self {
let worktree_manager = Arc::new(WorktreeManager::new(config.worktree_base_dir.clone()));
let process_manager = Arc::new(
ProcessManager::with_command(config.claude_command.clone())
.with_args(config.claude_args.clone())
.with_pre_args(config.claude_pre_args.clone())
.with_permissions_enabled(config.enable_permissions)
.with_verbose_disabled(config.disable_verbose)
.with_env(config.env_vars.clone())
.with_bubblewrap(config.bubblewrap.clone()),
);
let temp_manager = Arc::new(TempManager::new());
Self {
worktree_manager,
process_manager,
temp_manager,
config,
tasks: Arc::new(RwLock::new(HashMap::new())),
ws_tx,
contract_task_counts: Arc::new(RwLock::new(HashMap::new())),
task_inputs: Arc::new(RwLock::new(HashMap::new())),
merge_trackers: Arc::new(RwLock::new(HashMap::new())),
active_pids: Arc::new(RwLock::new(HashMap::new())),
git_user_email: Arc::new(RwLock::new(None)),
git_user_name: Arc::new(RwLock::new(None)),
local_db,
}
}
/// Persist task state to local SQLite database for crash recovery.
fn persist_task_to_local_db(&self, task: &ManagedTask) {
use crate::daemon::db::local::LocalTask;
let local_task = LocalTask {
id: task.id,
server_task_id: task.id, // Same as task id
state: task.state.clone(),
container_id: None,
overlay_path: task.worktree.as_ref().map(|w| w.path.to_string_lossy().to_string()),
repo_url: task.repo_source.clone(),
base_branch: task.base_branch.clone(),
plan: task.plan.clone(),
created_at: chrono::Utc::now(),
started_at: task.started_at.map(|_| chrono::Utc::now()),
completed_at: task.completed_at.map(|_| chrono::Utc::now()),
error_message: task.error.clone(),
};
if let Ok(db) = self.local_db.lock() {
if let Err(e) = db.save_task(&local_task) {
tracing::warn!(task_id = %task.id, error = %e, "Failed to persist task to local database");
} else {
tracing::debug!(task_id = %task.id, state = ?task.state, "Persisted task to local database");
}
}
}
/// Remove completed/failed task from local database.
fn remove_task_from_local_db(&self, task_id: Uuid) {
if let Ok(db) = self.local_db.lock() {
if let Err(e) = db.delete_task(task_id) {
tracing::warn!(task_id = %task_id, error = %e, "Failed to remove task from local database");
} else {
tracing::debug!(task_id = %task_id, "Removed task from local database");
}
}
}
/// Recover orphaned tasks from local database after daemon restart.
/// Returns list of task IDs that have worktrees and can potentially be recovered.
pub async fn recover_orphaned_tasks(&self) -> Vec<Uuid> {
tracing::info!("=== STARTING ORPHANED TASK RECOVERY ===");
let active_tasks = {
let db = match self.local_db.lock() {
Ok(db) => db,
Err(e) => {
tracing::error!(error = %e, "Failed to lock local database for recovery");
return Vec::new();
}
};
match db.get_active_tasks() {
Ok(tasks) => tasks,
Err(e) => {
tracing::error!(error = %e, "Failed to load active tasks from local database");
return Vec::new();
}
}
};
if active_tasks.is_empty() {
tracing::info!("No orphaned tasks found in local database");
return Vec::new();
}
tracing::info!(count = active_tasks.len(), "Found orphaned tasks in local database");
let mut recoverable_task_ids = Vec::new();
for local_task in active_tasks {
tracing::info!(
task_id = %local_task.id,
state = ?local_task.state,
overlay_path = ?local_task.overlay_path,
"Checking orphaned task"
);
// Check if worktree exists on filesystem
let worktree_exists = if let Some(ref path) = local_task.overlay_path {
let path = std::path::PathBuf::from(path);
path.exists() && path.join(".git").exists()
} else {
// Try to find worktree by task ID pattern (scan worktrees directory)
let short_id = &local_task.id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
let mut found = false;
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
if path.join(".git").exists() {
found = true;
break;
}
}
}
}
found
};
if worktree_exists {
tracing::info!(
task_id = %local_task.id,
"Found worktree for orphaned task - can be recovered"
);
recoverable_task_ids.push(local_task.id);
// Send structured recovery notification to server
let msg = DaemonMessage::task_recovery_detected(
local_task.id,
local_task.state.as_str(),
true, // worktree intact
local_task.overlay_path.clone(),
false, // doesn't need patch since worktree is intact
);
let _ = self.ws_tx.send(msg).await;
} else {
tracing::warn!(
task_id = %local_task.id,
"Worktree missing for orphaned task - marking as lost"
);
// Update local db to mark as failed
if let Ok(db) = self.local_db.lock() {
let _ = db.update_task_state(local_task.id, TaskState::Failed);
}
}
}
tracing::info!(
recoverable = recoverable_task_ids.len(),
"=== ORPHANED TASK RECOVERY COMPLETE ==="
);
recoverable_task_ids
}
/// Check worktree health for all running tasks.
/// If a worktree is missing, marks the task as interrupted and notifies the server.
/// This allows the retry orchestrator to pick up the task and restore it from checkpoint.
pub async fn check_worktree_health(&self) -> Vec<Uuid> {
let mut affected_task_ids = Vec::new();
// Get all running tasks with their worktree info and supervisor worktree task ID
let tasks_snapshot: Vec<(Uuid, Option<PathBuf>, Option<Uuid>)> = {
let tasks = self.tasks.read().await;
tasks
.iter()
.filter(|(_, t)| matches!(t.state, TaskState::Running | TaskState::Starting))
.map(|(id, t)| (*id, t.worktree.as_ref().map(|w| w.path.clone()), t.supervisor_worktree_task_id))
.collect()
};
if tasks_snapshot.is_empty() {
return affected_task_ids;
}
for (task_id, worktree_path, supervisor_worktree_task_id) in tasks_snapshot {
let worktree_exists = if let Some(ref path) = worktree_path {
path.exists() && path.join(".git").exists()
} else if let Some(supervisor_task_id) = supervisor_worktree_task_id {
// Task uses shared supervisor worktree - check the supervisor's worktree
// First try to get from in-memory tasks
let supervisor_worktree_path: Option<PathBuf> = {
let tasks = self.tasks.read().await;
tasks.get(&supervisor_task_id)
.and_then(|t| t.worktree.as_ref().map(|w| w.path.clone()))
};
if let Some(path) = supervisor_worktree_path {
path.exists() && path.join(".git").exists()
} else {
// Supervisor not in memory - scan worktrees directory
let short_id = &supervisor_task_id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
let mut found = false;
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
if path.join(".git").exists() {
found = true;
break;
}
}
}
}
found
}
} else {
// No worktree set - scan by task ID
let short_id = &task_id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
let mut found = false;
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
if path.join(".git").exists() {
found = true;
break;
}
}
}
}
found
};
if !worktree_exists {
tracing::warn!(
task_id = %task_id,
worktree_path = ?worktree_path,
"Worktree missing for running task - marking as interrupted for retry"
);
affected_task_ids.push(task_id);
// Update task state to interrupted
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Interrupted;
task.error = Some("Worktree directory was deleted".to_string());
task.completed_at = Some(Instant::now());
}
}
// Notify server - task needs recovery/retry
let msg = DaemonMessage::task_complete(
task_id,
false,
Some("Worktree deleted - task interrupted for recovery".to_string()),
);
let _ = self.ws_tx.send(msg).await;
// Remove from local db since server will handle retry
self.remove_task_from_local_db(task_id);
}
}
if !affected_task_ids.is_empty() {
tracing::info!(
count = affected_task_ids.len(),
"Worktree health check found missing worktrees"
);
}
affected_task_ids
}
/// Check if a task can be spawned given contract-based concurrency limits.
/// Returns the concurrency key to use (contract_id or task_id for standalone).
async fn try_acquire_concurrency_slot(
&self,
contract_id: Option<Uuid>,
task_id: Uuid,
) -> TaskResult<Uuid> {
let mut counts = self.contract_task_counts.write().await;
// Determine the concurrency key:
// - For contract tasks: use contract_id
// - For standalone tasks: use task_id (each standalone task is its own "contract")
let concurrency_key = contract_id.unwrap_or(task_id);
// Check global cap
let total: usize = counts.values().sum();
if total >= self.config.max_concurrent_tasks as usize {
tracing::warn!(
task_id = %task_id,
total_running = total,
max = self.config.max_concurrent_tasks,
"Global concurrency limit reached, cannot spawn task"
);
return Err(TaskError::ConcurrencyLimit);
}
// Check per-contract cap
let contract_count = counts.get(&concurrency_key).copied().unwrap_or(0);
if contract_count >= self.config.max_tasks_per_contract as usize {
tracing::warn!(
task_id = %task_id,
contract_id = ?contract_id,
concurrency_key = %concurrency_key,
contract_running = contract_count,
max_per_contract = self.config.max_tasks_per_contract,
"Contract concurrency limit reached, cannot spawn task"
);
return Err(TaskError::ContractConcurrencyLimit);
}
// Increment count for this contract
*counts.entry(concurrency_key).or_insert(0) += 1;
tracing::debug!(
task_id = %task_id,
concurrency_key = %concurrency_key,
new_count = counts.get(&concurrency_key).copied().unwrap_or(0),
total = total + 1,
"Acquired concurrency slot"
);
Ok(concurrency_key)
}
/// Gracefully shutdown all running Claude processes and their children.
///
/// This sends SIGTERM to all active process groups, waits for them to exit gracefully,
/// and then sends SIGKILL to any that don't exit within the timeout.
/// Uses process groups to ensure all child processes (bash commands, etc.) are also killed.
#[cfg(unix)]
pub async fn shutdown_all_processes(&self, timeout: std::time::Duration) {
use nix::sys::signal::{killpg, Signal};
use nix::unistd::Pid;
let pids: Vec<(Uuid, u32)> = {
let guard = self.active_pids.read().await;
guard.iter().map(|(k, v)| (*k, *v)).collect()
};
if pids.is_empty() {
tracing::info!("No active Claude processes to shutdown");
return;
}
tracing::info!(count = pids.len(), "Sending SIGTERM to all Claude process groups");
// Send SIGTERM to all process groups (each Claude process is its own group leader)
for (task_id, pid) in &pids {
match killpg(Pid::from_raw(*pid as i32), Signal::SIGTERM) {
Ok(()) => {
tracing::debug!(task_id = %task_id, pid = pid, "Sent SIGTERM to process group");
}
Err(nix::errno::Errno::ESRCH) => {
tracing::debug!(task_id = %task_id, pid = pid, "Process group already exited");
}
Err(e) => {
tracing::warn!(task_id = %task_id, pid = pid, error = %e, "Failed to send SIGTERM to process group");
}
}
}
// Wait for processes to exit with timeout
let start = std::time::Instant::now();
let check_interval = std::time::Duration::from_millis(100);
while start.elapsed() < timeout {
let remaining: Vec<u32> = {
let guard = self.active_pids.read().await;
guard.values().copied().collect()
};
if remaining.is_empty() {
tracing::info!("All Claude processes exited gracefully");
return;
}
tokio::time::sleep(check_interval).await;
}
// Send SIGKILL to any remaining process groups
let remaining: Vec<(Uuid, u32)> = {
let guard = self.active_pids.read().await;
guard.iter().map(|(k, v)| (*k, *v)).collect()
};
if !remaining.is_empty() {
tracing::warn!(
count = remaining.len(),
"Some process groups did not exit gracefully, sending SIGKILL"
);
for (task_id, pid) in &remaining {
match killpg(Pid::from_raw(*pid as i32), Signal::SIGKILL) {
Ok(()) => {
tracing::debug!(task_id = %task_id, pid = pid, "Sent SIGKILL to process group");
}
Err(e) => {
tracing::warn!(task_id = %task_id, pid = pid, error = %e, "Failed to send SIGKILL to process group");
}
}
}
}
}
/// Gracefully shutdown all running Claude processes (no-op on non-Unix).
#[cfg(not(unix))]
pub async fn shutdown_all_processes(&self, _timeout: std::time::Duration) {
tracing::warn!("Graceful shutdown not supported on this platform");
}
/// Pause a running task by sending SIGSTOP to its process.
#[cfg(unix)]
pub async fn pause_task(&self, task_id: Uuid) -> TaskResult<()> {
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
// Check if task exists and is running
let current_state = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).map(|t| t.state)
};
match current_state {
Some(TaskState::Running) => {}
Some(TaskState::Paused) => {
tracing::debug!(task_id = %task_id, "Task already paused");
return Ok(());
}
Some(state) => {
tracing::warn!(task_id = %task_id, state = ?state, "Cannot pause task in state");
return Err(TaskError::InvalidStateTransition {
from: format!("{:?}", state),
to: "Paused".to_string(),
});
}
None => {
tracing::warn!(task_id = %task_id, "Task not found");
return Err(TaskError::NotFound(task_id));
}
}
// Get the process PID
let pid = {
let pids = self.active_pids.read().await;
pids.get(&task_id).copied()
};
let Some(pid) = pid else {
tracing::warn!(task_id = %task_id, "No PID found for task");
return Err(TaskError::ExecutionFailed(
"No active process for task".to_string(),
));
};
// Send SIGSTOP to pause the process
match kill(Pid::from_raw(pid as i32), Signal::SIGSTOP) {
Ok(()) => {
tracing::info!(task_id = %task_id, pid = pid, "Sent SIGSTOP to pause process");
}
Err(nix::errno::Errno::ESRCH) => {
tracing::warn!(task_id = %task_id, pid = pid, "Process not found");
return Err(TaskError::ExecutionFailed("Process not found".to_string()));
}
Err(e) => {
tracing::error!(task_id = %task_id, pid = pid, error = %e, "Failed to send SIGSTOP");
return Err(TaskError::ExecutionFailed(format!(
"Failed to pause: {}",
e
)));
}
}
// Update task state to Paused
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Paused;
}
}
// Notify server of state change
let msg = DaemonMessage::task_status_change(task_id, "running", "paused");
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Pause a task (no-op on non-Unix).
#[cfg(not(unix))]
pub async fn pause_task(&self, task_id: Uuid) -> TaskResult<()> {
tracing::warn!(task_id = %task_id, "Pause not supported on this platform");
Err(TaskError::ExecutionFailed(
"Pause not supported on this platform".to_string(),
))
}
/// Resume a paused task by sending SIGCONT to its process.
#[cfg(unix)]
pub async fn resume_task(&self, task_id: Uuid) -> TaskResult<()> {
use nix::sys::signal::{kill, Signal};
use nix::unistd::Pid;
// Check if task exists and is paused
let current_state = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).map(|t| t.state)
};
match current_state {
Some(TaskState::Paused) => {}
Some(TaskState::Running) => {
tracing::debug!(task_id = %task_id, "Task already running");
return Ok(());
}
Some(state) => {
tracing::warn!(task_id = %task_id, state = ?state, "Cannot resume task in state");
return Err(TaskError::InvalidStateTransition {
from: format!("{:?}", state),
to: "Running".to_string(),
});
}
None => {
tracing::warn!(task_id = %task_id, "Task not found");
return Err(TaskError::NotFound(task_id));
}
}
// Get the process PID
let pid = {
let pids = self.active_pids.read().await;
pids.get(&task_id).copied()
};
let Some(pid) = pid else {
tracing::warn!(task_id = %task_id, "No PID found for task");
return Err(TaskError::ExecutionFailed(
"No active process for task".to_string(),
));
};
// Send SIGCONT to resume the process
match kill(Pid::from_raw(pid as i32), Signal::SIGCONT) {
Ok(()) => {
tracing::info!(task_id = %task_id, pid = pid, "Sent SIGCONT to resume process");
}
Err(nix::errno::Errno::ESRCH) => {
tracing::warn!(task_id = %task_id, pid = pid, "Process not found");
return Err(TaskError::ExecutionFailed("Process not found".to_string()));
}
Err(e) => {
tracing::error!(task_id = %task_id, pid = pid, error = %e, "Failed to send SIGCONT");
return Err(TaskError::ExecutionFailed(format!(
"Failed to resume: {}",
e
)));
}
}
// Update task state to Running
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Running;
}
}
// Notify server of state change
let msg = DaemonMessage::task_status_change(task_id, "paused", "running");
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Resume a task (no-op on non-Unix).
#[cfg(not(unix))]
pub async fn resume_task(&self, task_id: Uuid) -> TaskResult<()> {
tracing::warn!(task_id = %task_id, "Resume not supported on this platform");
Err(TaskError::ExecutionFailed(
"Resume not supported on this platform".to_string(),
))
}
/// Handle a command from the server.
pub async fn handle_command(&self, command: DaemonCommand) -> Result<(), DaemonError> {
tracing::info!("Received command from server: {:?}", command);
match command {
DaemonCommand::SpawnTask {
task_id,
task_name,
plan,
repo_url,
base_branch,
target_branch,
parent_task_id,
depth,
is_orchestrator,
target_repo_path,
completion_action,
continue_from_task_id,
copy_files,
contract_id,
is_supervisor,
autonomous_loop,
resume_session,
conversation_history,
patch_data,
patch_base_sha,
local_only,
auto_merge_local,
supervisor_worktree_task_id,
directive_id,
} => {
tracing::info!(
task_id = %task_id,
task_name = %task_name,
repo_url = ?repo_url,
base_branch = ?base_branch,
target_branch = ?target_branch,
parent_task_id = ?parent_task_id,
depth = depth,
is_orchestrator = is_orchestrator,
is_supervisor = is_supervisor,
autonomous_loop = autonomous_loop,
resume_session = resume_session,
target_repo_path = ?target_repo_path,
completion_action = ?completion_action,
continue_from_task_id = ?continue_from_task_id,
copy_files = ?copy_files,
contract_id = ?contract_id,
directive_id = ?directive_id,
supervisor_worktree_task_id = ?supervisor_worktree_task_id,
plan_len = plan.len(),
"Spawning new task"
);
self.spawn_task(
task_id, task_name, plan, repo_url, base_branch, target_branch,
parent_task_id, depth, is_orchestrator, is_supervisor,
target_repo_path, completion_action, continue_from_task_id,
copy_files, contract_id, autonomous_loop, resume_session,
conversation_history, patch_data, patch_base_sha, local_only, auto_merge_local,
supervisor_worktree_task_id, directive_id,
).await?;
}
DaemonCommand::PauseTask { task_id } => {
tracing::info!(task_id = %task_id, "Pausing task");
if let Err(e) = self.pause_task(task_id).await {
tracing::warn!(task_id = %task_id, error = %e, "Failed to pause task");
}
}
DaemonCommand::ResumeTask { task_id } => {
tracing::info!(task_id = %task_id, "Resuming task");
if let Err(e) = self.resume_task(task_id).await {
tracing::warn!(task_id = %task_id, error = %e, "Failed to resume task");
}
}
DaemonCommand::InterruptTask { task_id, graceful: _ } => {
tracing::info!(task_id = %task_id, "Interrupting task");
self.interrupt_task(task_id).await?;
}
DaemonCommand::SendMessage { task_id, message } => {
// Check if this is an auth code message
if message.starts_with("AUTH_CODE:") {
let code = message.strip_prefix("AUTH_CODE:").unwrap_or("").trim();
tracing::info!(task_id = %task_id, "Received auth code from frontend");
if send_auth_code(code) {
tracing::info!(task_id = %task_id, "Auth code forwarded to setup-token");
} else {
tracing::warn!(task_id = %task_id, "No pending auth flow to receive code");
}
} else {
// Check if task is paused - auto-resume before sending message
let task_state = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).map(|t| t.state)
};
if task_state == Some(TaskState::Paused) {
tracing::info!(task_id = %task_id, "Auto-resuming paused task before sending message");
if let Err(e) = self.resume_task(task_id).await {
tracing::warn!(task_id = %task_id, error = %e, "Failed to auto-resume task");
}
}
// Regular message - send to task's stdin
tracing::info!(task_id = %task_id, message_len = message.len(), "Sending message to task");
// Send message to the task's stdin via the input channel
let inputs = self.task_inputs.read().await;
if let Some(sender) = inputs.get(&task_id) {
if let Err(e) = sender.send(message).await {
tracing::warn!(task_id = %task_id, error = %e, "Failed to send message to task input channel");
} else {
tracing::info!(task_id = %task_id, "Message sent to task successfully");
}
} else {
drop(inputs); // Release read lock before checking if we need to respawn
// Check if this is a supervisor that needs to be respawned
let task_info = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).cloned()
};
if let Some(task) = task_info {
if task.is_supervisor {
tracing::info!(
task_id = %task_id,
"Supervisor has no active Claude process, respawning with message"
);
// Respawn the supervisor with the new message as the plan
// Claude Code will use --continue to maintain conversation history
let inner = self.clone_inner();
let task_name = task.task_name.clone();
let repo_source = task.repo_source.clone();
let base_branch = task.base_branch.clone();
let target_branch = task.target_branch.clone();
let target_repo_path = task.target_repo_path.clone();
let completion_action = task.completion_action.clone();
let contract_id = task.contract_id;
let local_only = task.local_only;
let auto_merge_local = task.auto_merge_local;
// Spawn in background to not block the command handler
tokio::spawn(async move {
if let Err(e) = inner.run_task(
task_id,
task_name,
message, // Use the message as the new prompt
repo_source,
base_branch,
target_branch,
false, // is_orchestrator
true, // is_supervisor
target_repo_path,
completion_action,
None, // continue_from_task_id
None, // copy_files
contract_id,
false, // autonomous_loop - supervisors don't use this
false, // resume_session - respawning from scratch
None, // conversation_history - not needed for fresh respawn
None, // patch_data - not available for respawn
None, // patch_base_sha - not available for respawn
local_only,
auto_merge_local,
None, // supervisor_worktree_task_id - supervisors use their own worktree
None, // directive_id
).await {
tracing::error!(
task_id = %task_id,
error = %e,
"Failed to respawn supervisor"
);
}
});
} else {
tracing::warn!(task_id = %task_id, "No input channel for task (task may not be running)");
}
} else {
tracing::warn!(task_id = %task_id, "Task not found");
}
}
}
}
DaemonCommand::InjectSiblingContext { task_id, .. } => {
tracing::debug!(task_id = %task_id, "Sibling context injection not supported for subprocess tasks");
}
DaemonCommand::Authenticated { daemon_id } => {
tracing::debug!(daemon_id = %daemon_id, "Authenticated command (handled by WS client)");
}
DaemonCommand::Error { code, message } => {
tracing::warn!(code = %code, message = %message, "Error command from server");
}
// =========================================================================
// Merge Commands
// =========================================================================
DaemonCommand::ListBranches { task_id } => {
tracing::info!(task_id = %task_id, "Listing task branches");
self.handle_list_branches(task_id).await?;
}
DaemonCommand::MergeStart { task_id, source_branch } => {
tracing::info!(task_id = %task_id, source_branch = %source_branch, "Starting merge");
self.handle_merge_start(task_id, source_branch).await?;
}
DaemonCommand::MergeStatus { task_id } => {
tracing::info!(task_id = %task_id, "Getting merge status");
self.handle_merge_status(task_id).await?;
}
DaemonCommand::MergeResolve { task_id, file, strategy } => {
tracing::info!(task_id = %task_id, file = %file, strategy = %strategy, "Resolving conflict");
self.handle_merge_resolve(task_id, file, strategy).await?;
}
DaemonCommand::MergeCommit { task_id, message } => {
tracing::info!(task_id = %task_id, "Committing merge");
self.handle_merge_commit(task_id, message).await?;
}
DaemonCommand::MergeAbort { task_id } => {
tracing::info!(task_id = %task_id, "Aborting merge");
self.handle_merge_abort(task_id).await?;
}
DaemonCommand::MergeSkip { task_id, subtask_id, reason } => {
tracing::info!(task_id = %task_id, subtask_id = %subtask_id, reason = %reason, "Skipping subtask merge");
self.handle_merge_skip(task_id, subtask_id, reason).await?;
}
DaemonCommand::CheckMergeComplete { task_id } => {
tracing::info!(task_id = %task_id, "Checking merge completion");
self.handle_check_merge_complete(task_id).await?;
}
// =========================================================================
// Completion Action Commands
// =========================================================================
DaemonCommand::RetryCompletionAction {
task_id,
task_name,
action,
target_repo_path,
target_branch,
} => {
tracing::info!(
task_id = %task_id,
task_name = %task_name,
action = %action,
target_repo_path = %target_repo_path,
target_branch = ?target_branch,
"Retrying completion action"
);
self.handle_retry_completion_action(task_id, task_name, action, target_repo_path, target_branch).await?;
}
DaemonCommand::CloneWorktree { task_id, target_dir } => {
tracing::info!(
task_id = %task_id,
target_dir = %target_dir,
"Cloning worktree to target directory"
);
self.handle_clone_worktree(task_id, target_dir).await?;
}
DaemonCommand::CheckTargetExists { task_id, target_dir } => {
tracing::debug!(
task_id = %task_id,
target_dir = %target_dir,
"Checking if target directory exists"
);
self.handle_check_target_exists(task_id, target_dir).await?;
}
// =========================================================================
// Contract File Commands
// =========================================================================
DaemonCommand::ReadRepoFile {
request_id,
contract_id,
file_path,
repo_path,
} => {
tracing::info!(
request_id = %request_id,
contract_id = %contract_id,
file_path = %file_path,
repo_path = %repo_path,
"Reading file from repository"
);
self.handle_read_repo_file(request_id, file_path, repo_path).await?;
}
DaemonCommand::CreateBranch {
task_id,
branch_name,
from_ref,
} => {
tracing::info!(
task_id = %task_id,
branch_name = %branch_name,
from_ref = ?from_ref,
"Creating branch"
);
self.handle_create_branch(task_id, branch_name, from_ref).await?;
}
DaemonCommand::MergeTaskToTarget {
task_id,
target_branch,
squash,
} => {
tracing::info!(
task_id = %task_id,
target_branch = ?target_branch,
squash = squash,
"Merging task to target branch"
);
self.handle_merge_task_to_target(task_id, target_branch, squash).await?;
}
DaemonCommand::CreatePR {
task_id,
title,
body,
base_branch,
branch,
} => {
tracing::info!(
task_id = %task_id,
title = %title,
base_branch = ?base_branch,
branch = %branch,
"Creating pull request"
);
self.handle_create_pr(task_id, title, body, base_branch, branch).await?;
}
DaemonCommand::GetTaskDiff {
task_id,
} => {
tracing::info!(task_id = %task_id, "Getting task diff");
self.handle_get_task_diff(task_id).await?;
}
DaemonCommand::GetWorktreeInfo {
task_id,
} => {
tracing::info!(task_id = %task_id, "Getting worktree info");
self.handle_get_worktree_info(task_id).await?;
}
DaemonCommand::CreateCheckpoint {
task_id,
message,
} => {
tracing::info!(task_id = %task_id, "Creating checkpoint");
self.handle_create_checkpoint(task_id, message).await?;
}
DaemonCommand::CleanupWorktree {
task_id,
delete_branch,
} => {
tracing::info!(
task_id = %task_id,
delete_branch = delete_branch,
"Cleaning up worktree"
);
self.handle_cleanup_worktree(task_id, delete_branch).await?;
}
DaemonCommand::InheritGitConfig { source_dir } => {
tracing::info!(source_dir = ?source_dir, "Inheriting git config");
self.handle_inherit_git_config(source_dir).await?;
}
DaemonCommand::CreateExportPatch { task_id, base_sha } => {
tracing::info!(task_id = %task_id, base_sha = ?base_sha, "Creating export patch");
self.handle_create_export_patch(task_id, base_sha).await?;
}
DaemonCommand::RestartDaemon => {
tracing::info!("Received restart command from server, initiating daemon restart...");
// Shutdown all running tasks gracefully
self.shutdown_all_processes(std::time::Duration::from_secs(5)).await;
// Exit the process - the daemon should be restarted by a process manager
// or the user can restart it manually
tracing::info!("Daemon restart: exiting process with code 42 (restart requested)");
std::process::exit(42);
}
DaemonCommand::ApplyPatchToWorktree {
target_task_id,
source_task_id,
patch_data,
base_sha,
} => {
tracing::info!(
target_task_id = %target_task_id,
source_task_id = %source_task_id,
base_sha = %base_sha,
"Applying patch from cross-daemon task to worktree"
);
self.handle_apply_patch_to_worktree(target_task_id, source_task_id, patch_data, base_sha).await?;
}
}
Ok(())
}
/// Spawn a new task.
#[allow(clippy::too_many_arguments)]
pub async fn spawn_task(
&self,
task_id: Uuid,
task_name: String,
plan: String,
repo_url: Option<String>,
base_branch: Option<String>,
target_branch: Option<String>,
parent_task_id: Option<Uuid>,
depth: i32,
is_orchestrator: bool,
is_supervisor: bool,
target_repo_path: Option<String>,
completion_action: Option<String>,
continue_from_task_id: Option<Uuid>,
copy_files: Option<Vec<String>>,
contract_id: Option<Uuid>,
autonomous_loop: bool,
resume_session: bool,
conversation_history: Option<serde_json::Value>,
patch_data: Option<String>,
patch_base_sha: Option<String>,
local_only: bool,
auto_merge_local: bool,
supervisor_worktree_task_id: Option<Uuid>,
directive_id: Option<Uuid>,
) -> TaskResult<()> {
tracing::info!(task_id = %task_id, is_orchestrator = is_orchestrator, is_supervisor = is_supervisor, depth = depth, patch_available = patch_data.is_some(), "=== SPAWN_TASK START ===");
// Check if task already exists - allow re-spawning if in terminal state
// or if resuming a supervisor (supervisors stay in Running state after Claude exits)
{
let mut tasks = self.tasks.write().await;
if let Some(existing) = tasks.get(&task_id) {
let can_respawn = existing.state.is_terminal()
|| (resume_session && existing.is_supervisor);
if can_respawn {
// Task exists but can be re-spawned (terminal state or supervisor resume)
tracing::info!(task_id = %task_id, old_state = ?existing.state, resume_session = resume_session, is_supervisor = existing.is_supervisor, "Removing task to allow re-spawn");
tasks.remove(&task_id);
} else {
// Task is still active, reject
tracing::warn!(task_id = %task_id, state = ?existing.state, "Task already exists and is active, rejecting spawn");
return Err(TaskError::AlreadyExists(task_id));
}
}
}
// Acquire concurrency slot (contract-based concurrency)
tracing::info!(task_id = %task_id, contract_id = ?contract_id, "Acquiring concurrency slot...");
let concurrency_key = self.try_acquire_concurrency_slot(contract_id, task_id).await?;
tracing::info!(task_id = %task_id, concurrency_key = %concurrency_key, "Concurrency slot acquired");
// Create task entry
tracing::info!(task_id = %task_id, "Creating task entry in state: Initializing");
let task = ManagedTask {
id: task_id,
task_name: task_name.clone(),
state: TaskState::Initializing,
worktree: None,
plan: plan.clone(),
repo_source: repo_url.clone(),
base_branch: base_branch.clone(),
target_branch: target_branch.clone(),
parent_task_id,
depth,
is_orchestrator,
is_supervisor,
target_repo_path: target_repo_path.clone(),
completion_action: completion_action.clone(),
continue_from_task_id,
copy_files: copy_files.clone(),
contract_id,
concurrency_key,
autonomous_loop,
local_only,
auto_merge_local,
merge_to_supervisor_task_id: None, // Set later if cross-daemon
supervisor_worktree_task_id,
created_at: Instant::now(),
started_at: None,
completed_at: None,
error: None,
};
// Persist task to local database for crash recovery
self.persist_task_to_local_db(&task);
self.tasks.write().await.insert(task_id, task);
tracing::info!(task_id = %task_id, "Task entry created and stored");
// Notify server of status change
tracing::info!(task_id = %task_id, "Notifying server: pending -> initializing");
self.send_status_change(task_id, "pending", "initializing").await;
// Spawn task in background
tracing::info!(task_id = %task_id, "Spawning background task runner");
let inner = self.clone_inner();
tokio::spawn(async move {
tracing::info!(task_id = %task_id, "Background task runner started");
if let Err(e) = inner.run_task(
task_id, task_name, plan, repo_url, base_branch, target_branch,
is_orchestrator, is_supervisor, target_repo_path, completion_action,
continue_from_task_id, copy_files, contract_id, autonomous_loop, resume_session,
conversation_history, patch_data, patch_base_sha, local_only, auto_merge_local,
supervisor_worktree_task_id, directive_id,
).await {
tracing::error!(task_id = %task_id, error = %e, "Task execution failed");
inner.mark_failed(task_id, &e.to_string()).await;
}
// Release concurrency slot
inner.release_concurrency_slot(concurrency_key).await;
tracing::info!(task_id = %task_id, concurrency_key = %concurrency_key, "Background task runner completed, concurrency slot released");
});
tracing::info!(task_id = %task_id, "=== SPAWN_TASK END (task running in background) ===");
Ok(())
}
/// Clone inner state for spawned tasks.
fn clone_inner(&self) -> TaskManagerInner {
TaskManagerInner {
worktree_manager: self.worktree_manager.clone(),
process_manager: self.process_manager.clone(),
temp_manager: self.temp_manager.clone(),
tasks: self.tasks.clone(),
ws_tx: self.ws_tx.clone(),
task_inputs: self.task_inputs.clone(),
active_pids: self.active_pids.clone(),
git_user_email: self.git_user_email.clone(),
git_user_name: self.git_user_name.clone(),
api_url: self.config.api_url.clone(),
api_key: self.config.api_key.clone(),
heartbeat_commit_interval_secs: self.config.heartbeat_commit_interval_secs,
contract_task_counts: self.contract_task_counts.clone(),
checkpoint_patches: self.config.checkpoint_patches.clone(),
local_db: self.local_db.clone(),
}
}
/// Interrupt a task.
pub async fn interrupt_task(&self, task_id: Uuid) -> TaskResult<()> {
let mut tasks = self.tasks.write().await;
let task = tasks.get_mut(&task_id).ok_or(TaskError::NotFound(task_id))?;
if task.state.is_terminal() {
return Ok(()); // Already done
}
let old_state = task.state;
task.state = TaskState::Interrupted;
task.completed_at = Some(Instant::now());
// Notify server
drop(tasks);
self.send_status_change(task_id, old_state.as_str(), "interrupted").await;
// Note: The process will be killed when the ClaudeProcess is dropped
// Worktrees are kept until explicitly deleted
Ok(())
}
/// Get list of active task IDs.
pub async fn active_task_ids(&self) -> Vec<Uuid> {
self.tasks
.read()
.await
.iter()
.filter(|(_, t)| t.state.is_active())
.map(|(id, _)| *id)
.collect()
}
/// Get task state.
pub async fn get_task_state(&self, task_id: Uuid) -> Option<TaskState> {
self.tasks.read().await.get(&task_id).map(|t| t.state)
}
/// Send status change notification to server.
async fn send_status_change(&self, task_id: Uuid, old_status: &str, new_status: &str) {
let msg = DaemonMessage::task_status_change(task_id, old_status, new_status);
let _ = self.ws_tx.send(msg).await;
}
// =========================================================================
// Merge Handler Methods
// =========================================================================
/// Get worktree path for a task, or return error if not found.
/// First checks in-memory tasks, then scans the worktrees directory.
async fn get_task_worktree_path(&self, task_id: Uuid) -> Result<std::path::PathBuf, DaemonError> {
// First try to get from in-memory tasks
{
let tasks = self.tasks.read().await;
if let Some(task) = tasks.get(&task_id) {
if let Some(ref worktree) = task.worktree {
return Ok(worktree.path.clone());
}
}
}
// Task not in memory - scan worktrees directory for matching task ID
let short_id = &task_id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
// Verify it's a valid git directory
if path.join(".git").exists() {
tracing::info!(
task_id = %task_id,
worktree_path = %path.display(),
"Found worktree by scanning directory"
);
return Ok(path);
}
}
}
}
Err(DaemonError::Task(TaskError::SetupFailed(
format!("No worktree found for task {}. The worktree may have been cleaned up.", task_id)
)))
}
/// Handle ListBranches command.
async fn handle_list_branches(&self, task_id: Uuid) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
match self.worktree_manager.list_task_branches(&worktree_path).await {
Ok(branches) => {
let branch_infos: Vec<BranchInfo> = branches
.into_iter()
.map(|b| BranchInfo {
name: b.name,
task_id: b.task_id,
is_merged: b.is_merged,
last_commit: b.last_commit,
last_commit_message: b.last_commit_message,
})
.collect();
let msg = DaemonMessage::BranchList {
task_id,
branches: branch_infos,
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to list branches");
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: e.to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeStart command.
async fn handle_merge_start(&self, task_id: Uuid, source_branch: String) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
match self.worktree_manager.merge_branch(&worktree_path, &source_branch).await {
Ok(None) => {
// Merge succeeded without conflicts
let msg = DaemonMessage::MergeResult {
task_id,
success: true,
message: "Merge completed without conflicts".to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
Ok(Some(conflicts)) => {
// Merge has conflicts
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: format!("Merge has {} conflicts", conflicts.len()),
commit_sha: None,
conflicts: Some(conflicts),
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: e.to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeStatus command.
async fn handle_merge_status(&self, task_id: Uuid) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
match self.worktree_manager.get_merge_state(&worktree_path).await {
Ok(state) => {
let msg = DaemonMessage::MergeStatusResponse {
task_id,
in_progress: state.in_progress,
source_branch: if state.in_progress { Some(state.source_branch) } else { None },
conflicted_files: state.conflicted_files,
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to get merge status");
let msg = DaemonMessage::MergeStatusResponse {
task_id,
in_progress: false,
source_branch: None,
conflicted_files: vec![],
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeResolve command.
async fn handle_merge_resolve(&self, task_id: Uuid, file: String, strategy: String) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
let resolution = match strategy.to_lowercase().as_str() {
"ours" => ConflictResolution::Ours,
"theirs" => ConflictResolution::Theirs,
_ => {
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: format!("Invalid strategy '{}', must be 'ours' or 'theirs'", strategy),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
match self.worktree_manager.resolve_conflict(&worktree_path, &file, resolution).await {
Ok(()) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: true,
message: format!("Resolved conflict in {}", file),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: e.to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeCommit command.
async fn handle_merge_commit(&self, task_id: Uuid, message: String) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
match self.worktree_manager.commit_merge(&worktree_path, &message).await {
Ok(commit_sha) => {
// Track this merge as completed (extract subtask ID from branch if possible)
// For now, we'll track it when MergeSkip is called or based on branch names
let msg = DaemonMessage::MergeResult {
task_id,
success: true,
message: "Merge committed successfully".to_string(),
commit_sha: Some(commit_sha),
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: e.to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeAbort command.
async fn handle_merge_abort(&self, task_id: Uuid) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
match self.worktree_manager.abort_merge(&worktree_path).await {
Ok(()) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: true,
message: "Merge aborted".to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
let msg = DaemonMessage::MergeResult {
task_id,
success: false,
message: e.to_string(),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
}
}
Ok(())
}
/// Handle MergeSkip command.
async fn handle_merge_skip(&self, task_id: Uuid, subtask_id: Uuid, reason: String) -> Result<(), DaemonError> {
// Record that this subtask was skipped
{
let mut trackers = self.merge_trackers.write().await;
let tracker = trackers.entry(task_id).or_insert_with(MergeTracker::default);
tracker.skipped_subtasks.insert(subtask_id, reason.clone());
}
let msg = DaemonMessage::MergeResult {
task_id,
success: true,
message: format!("Subtask {} skipped: {}", subtask_id, reason),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CheckMergeComplete command.
async fn handle_check_merge_complete(&self, task_id: Uuid) -> Result<(), DaemonError> {
let worktree_path = self.get_task_worktree_path(task_id).await?;
// Get all task branches
let branches = match self.worktree_manager.list_task_branches(&worktree_path).await {
Ok(b) => b,
Err(e) => {
let msg = DaemonMessage::MergeCompleteCheck {
task_id,
can_complete: false,
unmerged_branches: vec![format!("Error listing branches: {}", e)],
merged_count: 0,
skipped_count: 0,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Get tracker state
let trackers = self.merge_trackers.read().await;
let empty_merged: HashSet<Uuid> = HashSet::new();
let empty_skipped: HashMap<Uuid, String> = HashMap::new();
let tracker = trackers.get(&task_id);
let merged_set = tracker.map(|t| &t.merged_subtasks).unwrap_or(&empty_merged);
let skipped_set = tracker.map(|t| &t.skipped_subtasks).unwrap_or(&empty_skipped);
let mut merged_count = 0u32;
let mut skipped_count = 0u32;
let mut unmerged_branches = Vec::new();
for branch in &branches {
if branch.is_merged {
merged_count += 1;
} else if let Some(subtask_id) = branch.task_id {
if merged_set.contains(&subtask_id) {
merged_count += 1;
} else if skipped_set.contains_key(&subtask_id) {
skipped_count += 1;
} else {
unmerged_branches.push(branch.name.clone());
}
} else {
// Branch without task ID - check if it's merged
unmerged_branches.push(branch.name.clone());
}
}
let can_complete = unmerged_branches.is_empty();
let msg = DaemonMessage::MergeCompleteCheck {
task_id,
can_complete,
unmerged_branches,
merged_count,
skipped_count,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Mark a subtask as merged in the tracker.
#[allow(dead_code)]
pub async fn mark_subtask_merged(&self, orchestrator_task_id: Uuid, subtask_id: Uuid) {
let mut trackers = self.merge_trackers.write().await;
let tracker = trackers.entry(orchestrator_task_id).or_insert_with(MergeTracker::default);
tracker.merged_subtasks.insert(subtask_id);
}
// =========================================================================
// Completion Action Handler Methods
// =========================================================================
/// Handle RetryCompletionAction command.
async fn handle_retry_completion_action(
&self,
task_id: Uuid,
task_name: String,
action: String,
target_repo_path: String,
target_branch: Option<String>,
) -> Result<(), DaemonError> {
// Get the task's worktree path
let worktree_path = self.get_task_worktree_path(task_id).await?;
// Execute the completion action
let inner = self.clone_inner();
let result = inner.execute_completion_action(
task_id,
&task_name,
&worktree_path,
&action,
Some(target_repo_path.as_str()),
target_branch.as_deref(),
).await;
// Send result back to server
let msg = match result {
Ok(pr_url) => DaemonMessage::CompletionActionResult {
task_id,
success: true,
message: match action.as_str() {
"branch" => format!("Branch pushed to {}", target_repo_path),
"merge" => format!("Merged into {}", target_branch.as_deref().unwrap_or("main")),
"pr" => format!("Pull request created"),
_ => format!("Completion action '{}' executed", action),
},
pr_url,
},
Err(e) => DaemonMessage::CompletionActionResult {
task_id,
success: false,
message: e,
pr_url: None,
},
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CloneWorktree command.
async fn handle_clone_worktree(
&self,
task_id: Uuid,
target_dir: String,
) -> Result<(), DaemonError> {
// Get the task's worktree path
let worktree_path = self.get_task_worktree_path(task_id).await?;
// Expand tilde in target path
let target_path = crate::daemon::worktree::expand_tilde(&target_dir);
// Clone the worktree to target directory
let result = self.worktree_manager.clone_worktree_to_directory(
&worktree_path,
&target_path,
).await;
// Send result back to server
let msg = match result {
Ok(message) => DaemonMessage::CloneWorktreeResult {
task_id,
success: true,
message,
target_dir: Some(target_path.to_string_lossy().to_string()),
},
Err(e) => DaemonMessage::CloneWorktreeResult {
task_id,
success: false,
message: e.to_string(),
target_dir: None,
},
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CheckTargetExists command.
async fn handle_check_target_exists(
&self,
task_id: Uuid,
target_dir: String,
) -> Result<(), DaemonError> {
// Expand tilde in target path
let target_path = crate::daemon::worktree::expand_tilde(&target_dir);
// Check if target exists
let exists = self.worktree_manager.target_directory_exists(&target_path).await;
// Send result back to server
let msg = DaemonMessage::CheckTargetExistsResult {
task_id,
exists,
target_dir: target_path.to_string_lossy().to_string(),
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CleanupWorktree command.
///
/// Removes a task's worktree and optionally its branch.
/// Used when a contract is completed or deleted to clean up associated task worktrees.
async fn handle_cleanup_worktree(
&self,
task_id: Uuid,
delete_branch: bool,
) -> Result<(), DaemonError> {
// Try to get the worktree path, but don't fail if not found
let worktree_result = self.get_task_worktree_path(task_id).await;
let (success, message) = match worktree_result {
Ok(worktree_path) => {
// Remove the worktree
match self.worktree_manager.remove_worktree(&worktree_path, delete_branch).await {
Ok(()) => {
tracing::info!(
task_id = %task_id,
worktree_path = %worktree_path.display(),
delete_branch = delete_branch,
"Worktree cleaned up successfully"
);
// Also remove task from in-memory tracking
self.tasks.write().await.remove(&task_id);
self.task_inputs.write().await.remove(&task_id);
self.merge_trackers.write().await.remove(&task_id);
self.active_pids.write().await.remove(&task_id);
(true, format!("Worktree cleaned up: {}", worktree_path.display()))
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
worktree_path = %worktree_path.display(),
error = %e,
"Failed to remove worktree"
);
(false, format!("Failed to remove worktree: {}", e))
}
}
}
Err(_) => {
// Worktree not found - this is OK, it may have already been cleaned up
tracing::debug!(
task_id = %task_id,
"No worktree found for task, may have already been cleaned up"
);
// Still remove from in-memory tracking
self.tasks.write().await.remove(&task_id);
self.task_inputs.write().await.remove(&task_id);
self.merge_trackers.write().await.remove(&task_id);
self.active_pids.write().await.remove(&task_id);
(true, "No worktree found, task tracking cleaned up".to_string())
}
};
// Send result back to server
let msg = DaemonMessage::CleanupWorktreeResult {
task_id,
success,
message,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CreateExportPatch command.
///
/// Creates an uncompressed, human-readable git patch for export.
async fn handle_create_export_patch(
&self,
task_id: Uuid,
base_sha: Option<String>,
) -> Result<(), DaemonError> {
// Get task's worktree path
let worktree_result = self.get_task_worktree_path(task_id).await;
let msg = match worktree_result {
Ok(worktree_path) => {
// Create the export patch
match storage::create_export_patch(&worktree_path, base_sha.as_deref()).await {
Ok(result) => {
tracing::info!(
task_id = %task_id,
files_count = result.files_count,
lines_added = result.lines_added,
lines_removed = result.lines_removed,
base_commit_sha = %result.base_commit_sha,
"Export patch created successfully"
);
DaemonMessage::ExportPatchCreated {
task_id,
success: true,
patch_content: Some(result.patch_content),
files_count: Some(result.files_count),
lines_added: Some(result.lines_added),
lines_removed: Some(result.lines_removed),
base_commit_sha: Some(result.base_commit_sha),
error: None,
}
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
error = %e,
"Failed to create export patch"
);
DaemonMessage::ExportPatchCreated {
task_id,
success: false,
patch_content: None,
files_count: None,
lines_added: None,
lines_removed: None,
base_commit_sha: None,
error: Some(e.to_string()),
}
}
}
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
error = %e,
"Failed to get worktree path for export patch"
);
DaemonMessage::ExportPatchCreated {
task_id,
success: false,
patch_content: None,
files_count: None,
lines_added: None,
lines_removed: None,
base_commit_sha: None,
error: Some(format!("Task not found or has no worktree: {}", e)),
}
}
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle ReadRepoFile command.
///
/// Reads a file from a repository on the daemon's filesystem and sends
/// the content back to the server for syncing contract files.
async fn handle_read_repo_file(
&self,
request_id: Uuid,
file_path: String,
repo_path: String,
) -> Result<(), DaemonError> {
// Expand tilde in repo path
let repo_path_expanded = crate::daemon::worktree::expand_tilde(&repo_path);
// Construct full file path
let full_path = repo_path_expanded.join(&file_path);
// Try to read the file
let (content, success, error) = match tokio::fs::read_to_string(&full_path).await {
Ok(content) => (Some(content), true, None),
Err(e) => {
tracing::warn!(
request_id = %request_id,
file_path = %file_path,
repo_path = %repo_path,
full_path = %full_path.display(),
error = %e,
"Failed to read repo file"
);
(None, false, Some(e.to_string()))
}
};
// Send result back to server
let msg = DaemonMessage::RepoFileContent {
request_id,
file_path,
content,
success,
error,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CreateBranch command - create a new branch in a task's worktree.
async fn handle_create_branch(
&self,
task_id: Uuid,
branch_name: String,
from_ref: Option<String>,
) -> Result<(), DaemonError> {
// Get task's worktree path
let worktree_path = {
let tasks = self.tasks.read().await;
tasks.get(&task_id)
.and_then(|t| t.worktree.as_ref())
.map(|w| w.path.clone())
};
let (success, message) = if let Some(path) = worktree_path {
// Build git checkout command
let mut cmd = tokio::process::Command::new("git");
cmd.current_dir(&path);
cmd.arg("checkout").arg("-b").arg(&branch_name);
if let Some(ref from) = from_ref {
cmd.arg(from);
}
match cmd.output().await {
Ok(output) => {
if output.status.success() {
(true, format!("Branch '{}' created successfully", branch_name))
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
(false, format!("Failed to create branch: {}", stderr))
}
}
Err(e) => (false, format!("Failed to execute git: {}", e)),
}
} else {
(false, format!("Task {} not found or has no worktree", task_id))
};
let msg = DaemonMessage::BranchCreated {
task_id,
success,
branch_name,
message,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle MergeTaskToTarget command - merge a task's changes to a target branch.
async fn handle_merge_task_to_target(
&self,
task_id: Uuid,
target_branch: Option<String>,
squash: bool,
) -> Result<(), DaemonError> {
// Get worktree path - this works even for completed tasks by scanning worktrees directory
let worktree_path = match self.get_task_worktree_path(task_id).await {
Ok(path) => path,
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to find worktree for merge");
let msg = DaemonMessage::MergeToTargetResult {
task_id,
success: false,
message: format!("Task {} not found or has no worktree: {}", task_id, e),
commit_sha: None,
conflicts: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Get base_branch from in-memory tasks if available (for fallback target branch)
let base_branch = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).and_then(|t| t.base_branch.clone())
};
let target = target_branch.unwrap_or_else(|| base_branch.unwrap_or_else(|| "main".to_string()));
tracing::info!(
task_id = %task_id,
worktree_path = %worktree_path.display(),
target_branch = %target,
squash = squash,
"Starting merge operation"
);
// First, stage and commit any uncommitted changes
let add_result = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["add", "-A"])
.output()
.await;
let (success, message, commit_sha, conflicts) = if let Err(e) = add_result {
(false, format!("Failed to stage changes: {}", e), None, None)
} else {
// Commit if there are staged changes
let commit_result = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["commit", "-m", "Task completion checkpoint", "--allow-empty"])
.output()
.await;
if let Err(e) = commit_result {
tracing::warn!(task_id = %task_id, error = %e, "Commit failed (may be empty)");
}
// Get current branch name
let branch_output = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.output()
.await;
let source_branch = branch_output
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.unwrap_or_else(|_| "unknown".to_string());
// Checkout target branch
let checkout = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["checkout", &target])
.output()
.await;
match checkout {
Ok(output) if output.status.success() => {
// Merge the source branch
let mut merge_cmd = tokio::process::Command::new("git");
merge_cmd.current_dir(&worktree_path);
merge_cmd.arg("merge");
if squash {
merge_cmd.arg("--squash");
}
merge_cmd.arg(&source_branch);
merge_cmd.arg("-m").arg(format!("Merge task {} into {}", task_id, target));
match merge_cmd.output().await {
Ok(output) if output.status.success() => {
// Get the commit SHA
let sha_output = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["rev-parse", "HEAD"])
.output()
.await;
let sha = sha_output
.ok()
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string());
if squash {
// For squash merge, we need to commit
let _ = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["commit", "-m", &format!("Squashed merge of task {}", task_id)])
.output()
.await;
}
(true, format!("Merged {} into {}", source_branch, target), sha, None)
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
// Check for merge conflicts
if stderr.contains("CONFLICT") {
let conflict_files = stderr
.lines()
.filter(|l| l.contains("CONFLICT"))
.map(|l| l.to_string())
.collect::<Vec<_>>();
(false, "Merge conflicts detected".to_string(), None, Some(conflict_files))
} else {
(false, format!("Merge failed: {}", stderr), None, None)
}
}
Err(e) => (false, format!("Failed to merge: {}", e), None, None),
}
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
(false, format!("Failed to checkout target branch: {}", stderr), None, None)
}
Err(e) => (false, format!("Failed to checkout: {}", e), None, None),
}
};
let msg = DaemonMessage::MergeToTargetResult {
task_id,
success,
message,
commit_sha,
conflicts,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CreatePR command - create a pull request for a task's changes.
async fn handle_create_pr(
&self,
task_id: Uuid,
title: String,
body: Option<String>,
base_branch: Option<String>,
branch: String,
) -> Result<(), DaemonError> {
// Get worktree path - this works even for completed tasks by scanning worktrees directory
let worktree_path = match self.get_task_worktree_path(task_id).await {
Ok(path) => path,
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to find worktree for PR creation");
let msg = DaemonMessage::PRCreated {
task_id,
success: false,
message: format!("Task {} not found or has no worktree: {}", task_id, e),
pr_url: None,
pr_number: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Detect base branch if not provided
let base_branch = match base_branch {
Some(b) => b,
None => {
match self.worktree_manager.detect_default_branch(&worktree_path).await {
Ok(detected) => {
tracing::info!(task_id = %task_id, detected_branch = %detected, "Auto-detected base branch");
detected
}
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to detect default branch");
let msg = DaemonMessage::PRCreated {
task_id,
success: false,
message: format!("Failed to detect default branch: {}", e),
pr_url: None,
pr_number: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
}
}
};
tracing::info!(
task_id = %task_id,
base_branch = %base_branch,
branch = %branch,
worktree_path = %worktree_path.display(),
"Creating PR"
);
// Push the branch to origin
let push_refspec = format!("HEAD:refs/heads/{}", branch);
let push_result = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["push", "-u", "origin", &push_refspec])
.output()
.await;
let (success, message, pr_url, pr_number) = match push_result {
Err(e) => {
tracing::error!(error = %e, "Failed to execute git push");
(false, format!("Failed to push branch: {}", e), None, None)
}
Ok(output) if !output.status.success() => {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!(stderr = %stderr, "git push failed");
(false, format!("Failed to push branch: {}", stderr), None, None)
}
Ok(_) => {
tracing::info!("Branch pushed successfully, creating PR");
// Create PR using gh CLI
let mut pr_cmd = tokio::process::Command::new("gh");
pr_cmd.current_dir(&worktree_path);
pr_cmd.args(["pr", "create", "--title", &title, "--base", &base_branch, "--head", &branch]);
if let Some(ref body_text) = body {
pr_cmd.args(["--body", body_text]);
} else {
pr_cmd.args(["--body", ""]);
}
match pr_cmd.output().await {
Ok(output) if output.status.success() => {
let stdout = String::from_utf8_lossy(&output.stdout);
// gh pr create outputs the PR URL
let url = stdout.lines().last().map(|s| s.trim().to_string());
// Extract PR number from URL
let number = url.as_ref().and_then(|u| {
u.split('/').last().and_then(|n| n.parse::<i32>().ok())
});
tracing::info!(pr_url = ?url, pr_number = ?number, "PR created successfully");
(true, "Pull request created".to_string(), url, number)
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!(stderr = %stderr, "gh pr create failed");
(false, format!("Failed to create PR: {}", stderr), None, None)
}
Err(e) => {
tracing::error!(error = %e, "Failed to execute gh command");
(false, format!("Failed to run gh: {}", e), None, None)
}
}
}
};
tracing::info!(
task_id = %task_id,
success = success,
message = %message,
pr_url = ?pr_url,
"PR creation completed"
);
let msg = DaemonMessage::PRCreated {
task_id,
success,
message,
pr_url,
pr_number,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle GetTaskDiff command - get the diff for a task's changes.
async fn handle_get_task_diff(
&self,
task_id: Uuid,
) -> Result<(), DaemonError> {
// Get task's worktree path
let worktree_path = {
let tasks = self.tasks.read().await;
tasks.get(&task_id)
.and_then(|t| t.worktree.as_ref())
.map(|w| w.path.clone())
};
let (success, diff, error) = if let Some(path) = worktree_path {
// Get diff of all changes (staged and unstaged)
let diff_result = tokio::process::Command::new("git")
.current_dir(&path)
.args(["diff", "HEAD"])
.output()
.await;
match diff_result {
Ok(output) if output.status.success() => {
let diff_text = String::from_utf8_lossy(&output.stdout).to_string();
if diff_text.is_empty() {
// No uncommitted changes, show diff from base
let base_diff = tokio::process::Command::new("git")
.current_dir(&path)
.args(["log", "-p", "--reverse", "HEAD~10..HEAD", "--"])
.output()
.await;
match base_diff {
Ok(o) => (true, Some(String::from_utf8_lossy(&o.stdout).to_string()), None),
Err(e) => (false, None, Some(format!("Failed to get diff: {}", e))),
}
} else {
(true, Some(diff_text), None)
}
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
(false, None, Some(format!("Git diff failed: {}", stderr)))
}
Err(e) => (false, None, Some(format!("Failed to run git: {}", e))),
}
} else {
(false, None, Some(format!("Task {} not found or has no worktree", task_id)))
};
let msg = DaemonMessage::TaskDiff {
task_id,
success,
diff,
error,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle GetWorktreeInfo command - get worktree files, stats, branch info.
async fn handle_get_worktree_info(
&self,
task_id: Uuid,
) -> Result<(), DaemonError> {
// Get task's worktree path, branch, and base_branch
// If the task shares a supervisor's worktree, use the supervisor's worktree info
let task_info = {
let tasks = self.tasks.read().await;
if let Some(task) = tasks.get(&task_id) {
// Check if this task shares a supervisor's worktree
if let Some(supervisor_task_id) = task.supervisor_worktree_task_id {
// Use the supervisor's worktree
tasks.get(&supervisor_task_id).map(|supervisor| (
supervisor.worktree.as_ref().map(|w| w.path.clone()),
supervisor.worktree.as_ref().map(|w| w.branch.clone()),
supervisor.base_branch.clone(),
))
} else {
// Use the task's own worktree
Some((
task.worktree.as_ref().map(|w| w.path.clone()),
task.worktree.as_ref().map(|w| w.branch.clone()),
task.base_branch.clone(),
))
}
} else {
None
}
};
let (worktree_path, branch, base_branch) = match task_info {
Some((Some(path), branch, base_branch)) => (Some(path), branch, base_branch),
Some((None, _, _)) => (None, None, None),
None => (None, None, None),
};
if worktree_path.is_none() {
let msg = DaemonMessage::WorktreeInfoResult {
task_id,
success: true,
worktree_path: None,
exists: false,
files_changed: 0,
insertions: 0,
deletions: 0,
files: None,
branch: None,
head_sha: None,
error: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
let path = worktree_path.unwrap();
let path_str = path.to_string_lossy().to_string();
// Check if worktree exists
if !path.exists() {
let msg = DaemonMessage::WorktreeInfoResult {
task_id,
success: true,
worktree_path: Some(path_str),
exists: false,
files_changed: 0,
insertions: 0,
deletions: 0,
files: None,
branch,
head_sha: None,
error: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
// Get HEAD SHA
let head_sha = match tokio::process::Command::new("git")
.current_dir(&path)
.args(["rev-parse", "HEAD"])
.output()
.await
{
Ok(output) if output.status.success() => {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
_ => None,
};
// Get changed files with status using git status --porcelain
let status_output = tokio::process::Command::new("git")
.current_dir(&path)
.args(["status", "--porcelain"])
.output()
.await;
let uncommitted_status_lines: Vec<(String, String)> = match status_output {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| {
if line.len() < 3 {
return None;
}
let status = line[0..2].trim().to_string();
let file_path = line[3..].to_string();
Some((file_path, status))
})
.collect()
}
_ => vec![],
};
// If there are uncommitted changes, use them. Otherwise, compare against base branch.
// Track effective_base_branch for reuse in numstat query
let (status_lines, effective_base_for_diff) = if !uncommitted_status_lines.is_empty() {
(uncommitted_status_lines, None)
} else {
// No uncommitted changes - try to get committed changes vs base branch
// First, try to detect the base branch if not provided
let effective_base_branch = if let Some(ref base) = base_branch {
Some(base.clone())
} else {
// Auto-detect the default branch
self.worktree_manager.detect_default_branch(&path).await.ok()
};
if let Some(ref base) = effective_base_branch {
// Get committed changes using git diff --name-status
let diff_base = format!("origin/{}...HEAD", base);
let name_status_output = tokio::process::Command::new("git")
.current_dir(&path)
.args(["diff", "--name-status", &diff_base])
.output()
.await;
let committed_status_lines: Vec<(String, String)> = match name_status_output {
Ok(output) if output.status.success() => {
String::from_utf8_lossy(&output.stdout)
.lines()
.filter_map(|line| {
let parts: Vec<&str> = line.splitn(2, '\t').collect();
if parts.len() >= 2 {
let status = parts[0].trim().to_string();
let file_path = parts[1].to_string();
Some((file_path, status))
} else {
None
}
})
.collect()
}
_ => vec![],
};
if !committed_status_lines.is_empty() {
(committed_status_lines, Some(base.clone()))
} else {
(vec![], None)
}
} else {
(vec![], None)
}
};
// Get numstat for line counts
// If we have effective_base_for_diff, compare against origin/{base_branch}
// Otherwise compare against HEAD for uncommitted changes
let mut file_stats: std::collections::HashMap<String, (i32, i32)> = std::collections::HashMap::new();
let numstat_output = if let Some(ref base) = effective_base_for_diff {
let diff_base = format!("origin/{}...HEAD", base);
tokio::process::Command::new("git")
.current_dir(&path)
.args(["diff", "--numstat", &diff_base])
.output()
.await
} else {
tokio::process::Command::new("git")
.current_dir(&path)
.args(["diff", "HEAD", "--numstat"])
.output()
.await
};
if let Ok(output) = numstat_output {
if output.status.success() {
for line in String::from_utf8_lossy(&output.stdout).lines() {
let parts: Vec<&str> = line.split('\t').collect();
if parts.len() >= 3 {
let added = parts[0].parse::<i32>().unwrap_or(0);
let removed = parts[1].parse::<i32>().unwrap_or(0);
let file = parts[2].to_string();
file_stats.insert(file, (added, removed));
}
}
}
}
// Build file list with stats
let mut files_json = Vec::new();
let mut total_insertions = 0;
let mut total_deletions = 0;
for (file_path, status) in &status_lines {
let (lines_added, lines_removed) = file_stats.get(file_path).copied().unwrap_or((0, 0));
total_insertions += lines_added;
total_deletions += lines_removed;
files_json.push(serde_json::json!({
"path": file_path,
"status": status,
"linesAdded": lines_added,
"linesRemoved": lines_removed,
}));
}
let msg = DaemonMessage::WorktreeInfoResult {
task_id,
success: true,
worktree_path: Some(path_str),
exists: true,
files_changed: status_lines.len() as i32,
insertions: total_insertions,
deletions: total_deletions,
files: Some(serde_json::Value::Array(files_json)),
branch,
head_sha,
error: None,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Handle CreateCheckpoint command - stage all changes, commit, and get stats.
async fn handle_create_checkpoint(
&self,
task_id: Uuid,
message: String,
) -> Result<(), DaemonError> {
// Get task's worktree path and branch name
let task_info = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).map(|t| (
t.worktree.as_ref().map(|w| w.path.clone()),
t.worktree.as_ref().map(|w| w.branch.clone()),
))
};
let (worktree_path, branch_name) = match task_info {
Some((Some(path), Some(branch))) => (path, branch),
Some((Some(path), None)) => {
// Try to get current branch from git
let branch = self.get_current_branch(&path).await.unwrap_or_else(|| "unknown".to_string());
(path, branch)
}
_ => {
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: false,
commit_sha: None,
branch_name: None,
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: Some(format!("Task {} not found or has no worktree", task_id)),
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Step 1: Check if there are changes to commit
let status_output = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["status", "--porcelain"])
.output()
.await;
let has_changes = match &status_output {
Ok(output) => !output.stdout.is_empty(),
Err(_) => false,
};
if !has_changes {
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: false,
commit_sha: None,
branch_name: Some(branch_name),
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: Some("No changes to checkpoint".to_string()),
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
// Step 2: Stage all changes
let add_result = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["add", "-A"])
.output()
.await;
if let Err(e) = add_result {
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: false,
commit_sha: None,
branch_name: Some(branch_name),
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: Some(format!("Failed to stage changes: {}", e)),
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
// Step 3: Get diff stats before commit
let (lines_added, lines_removed, files_changed) = self.get_staged_diff_stats(&worktree_path).await;
// Step 4: Create commit
let commit_result = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["commit", "-m", &message])
.output()
.await;
let commit_sha = match commit_result {
Ok(output) if output.status.success() => {
// Get the commit SHA
let sha_output = tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["rev-parse", "HEAD"])
.output()
.await;
match sha_output {
Ok(o) => Some(String::from_utf8_lossy(&o.stdout).trim().to_string()),
Err(_) => None,
}
}
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: false,
commit_sha: None,
branch_name: Some(branch_name),
checkpoint_number: None,
files_changed: Some(files_changed),
lines_added: Some(lines_added),
lines_removed: Some(lines_removed),
error: Some(format!("Commit failed: {}", stderr)),
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
Err(e) => {
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: false,
commit_sha: None,
branch_name: Some(branch_name),
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: Some(format!("Failed to execute git commit: {}", e)),
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Success - send response (checkpoint_number will be assigned by server on DB insert)
// Note: Manual checkpoints don't include patches (only heartbeat commits do)
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: true,
commit_sha,
branch_name: Some(branch_name),
checkpoint_number: None, // Server will assign from DB
files_changed: Some(files_changed),
lines_added: Some(lines_added),
lines_removed: Some(lines_removed),
error: None,
message,
patch_data: None,
patch_base_sha: None,
patch_files_count: None,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Get the current branch name from a worktree.
async fn get_current_branch(&self, worktree_path: &std::path::PathBuf) -> Option<String> {
let output = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["branch", "--show-current"])
.output()
.await
.ok()?;
if output.status.success() {
Some(String::from_utf8_lossy(&output.stdout).trim().to_string())
} else {
None
}
}
/// Get diff stats for staged changes.
async fn get_staged_diff_stats(&self, worktree_path: &std::path::PathBuf) -> (i32, i32, serde_json::Value) {
// Get numstat for lines added/removed
let numstat = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["diff", "--cached", "--numstat"])
.output()
.await;
let (mut total_added, mut total_removed) = (0i32, 0i32);
if let Ok(output) = numstat {
for line in String::from_utf8_lossy(&output.stdout).lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 2 {
if let Ok(added) = parts[0].parse::<i32>() {
total_added += added;
}
if let Ok(removed) = parts[1].parse::<i32>() {
total_removed += removed;
}
}
}
}
// Get name-status for file changes
let name_status = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["diff", "--cached", "--name-status"])
.output()
.await;
let mut files = Vec::new();
if let Ok(output) = name_status {
for line in String::from_utf8_lossy(&output.stdout).lines() {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() >= 2 {
files.push(serde_json::json!({
"action": parts[0],
"path": parts[1]
}));
}
}
}
(total_added, total_removed, serde_json::json!(files))
}
/// Find worktree path for a task ID.
/// First checks in-memory tasks, then scans the worktrees directory.
async fn find_worktree_for_task_tm(&self, task_id: Uuid) -> Result<PathBuf, String> {
// First try to get from in-memory tasks
{
let tasks = self.tasks.read().await;
if let Some(task) = tasks.get(&task_id) {
if let Some(ref worktree) = task.worktree {
return Ok(worktree.path.clone());
}
}
}
// Task not in memory - scan worktrees directory for matching task ID
let short_id = &task_id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
// Verify it's a valid git directory
if path.join(".git").exists() {
tracing::info!(
task_id = %task_id,
worktree_path = %path.display(),
"Found worktree by scanning directory"
);
return Ok(path);
}
}
}
}
Err(format!(
"No worktree found for task {}. The worktree may have been cleaned up.",
task_id
))
}
/// Handle ApplyPatchToWorktree command - apply a patch from a cross-daemon task to a supervisor's worktree.
async fn handle_apply_patch_to_worktree(
&self,
target_task_id: Uuid,
source_task_id: Uuid,
patch_data: String,
base_sha: String,
) -> Result<(), DaemonError> {
// Find the target task's worktree
let worktree_path = match self.find_worktree_for_task_tm(target_task_id).await {
Ok(path) => path,
Err(e) => {
tracing::error!(
target_task_id = %target_task_id,
error = %e,
"Failed to find worktree for patch application"
);
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: worktree not found - {}\n", source_task_id, e),
true,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
tracing::info!(
target_task_id = %target_task_id,
source_task_id = %source_task_id,
worktree = %worktree_path.display(),
"Applying cross-daemon patch to worktree"
);
// Decode the base64-gzipped patch data
let patch_bytes = match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, &patch_data) {
Ok(bytes) => bytes,
Err(e) => {
tracing::error!(error = %e, "Failed to decode patch base64");
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: base64 decode error - {}\n", source_task_id, e),
true,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Decompress the gzipped patch
let patch_content = {
use std::io::Read;
let mut decoder = flate2::read::GzDecoder::new(&patch_bytes[..]);
let mut content = String::new();
match decoder.read_to_string(&mut content) {
Ok(_) => content,
Err(e) => {
tracing::error!(error = %e, "Failed to decompress patch");
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: decompress error - {}\n", source_task_id, e),
true,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
}
};
// Check if patch is empty
if patch_content.trim().is_empty() {
tracing::info!(
target_task_id = %target_task_id,
source_task_id = %source_task_id,
"Cross-daemon task had no changes to merge"
);
let msg = DaemonMessage::task_output(
target_task_id,
format!("Cross-daemon task {} completed with no changes to merge\n", source_task_id),
false,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
// Apply the patch using git apply
let mut child = match tokio::process::Command::new("git")
.current_dir(&worktree_path)
.args(["apply", "--3way", "-"])
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
{
Ok(child) => child,
Err(e) => {
tracing::error!(error = %e, "Failed to spawn git apply");
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: spawn error - {}\n", source_task_id, e),
true,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
// Write patch to stdin
if let Some(mut stdin) = child.stdin.take() {
use tokio::io::AsyncWriteExt;
if let Err(e) = stdin.write_all(patch_content.as_bytes()).await {
tracing::error!(error = %e, "Failed to write patch to git apply stdin");
}
}
// Wait for completion
let output = match child.wait_with_output().await {
Ok(output) => output,
Err(e) => {
tracing::error!(error = %e, "Failed to wait for git apply");
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: wait error - {}\n", source_task_id, e),
true,
);
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
};
if output.status.success() {
tracing::info!(
target_task_id = %target_task_id,
source_task_id = %source_task_id,
base_sha = %base_sha,
"Successfully applied cross-daemon patch"
);
let msg = DaemonMessage::task_output(
target_task_id,
format!("Successfully merged changes from cross-daemon task {} (base: {})\n", source_task_id, &base_sha[..8]),
false,
);
let _ = self.ws_tx.send(msg).await;
} else {
let stderr = String::from_utf8_lossy(&output.stderr);
tracing::error!(
target_task_id = %target_task_id,
source_task_id = %source_task_id,
stderr = %stderr,
"Failed to apply cross-daemon patch"
);
let msg = DaemonMessage::task_output(
target_task_id,
format!("Failed to apply patch from task {}: {}\n", source_task_id, stderr),
true,
);
let _ = self.ws_tx.send(msg).await;
}
Ok(())
}
/// Handle InheritGitConfig command - read git config from a directory and store it.
async fn handle_inherit_git_config(
&self,
source_dir: Option<String>,
) -> Result<(), DaemonError> {
// Use provided directory or current working directory
let dir = source_dir
.map(std::path::PathBuf::from)
.unwrap_or_else(|| std::env::current_dir().unwrap_or_else(|_| std::path::PathBuf::from(".")));
tracing::info!(dir = ?dir, "Reading git config from directory");
// Read user.email
let email_output = tokio::process::Command::new("git")
.current_dir(&dir)
.args(["config", "user.email"])
.output()
.await;
let user_email = match email_output {
Ok(output) if output.status.success() => {
let email = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !email.is_empty() {
Some(email)
} else {
None
}
}
_ => None,
};
// Read user.name
let name_output = tokio::process::Command::new("git")
.current_dir(&dir)
.args(["config", "user.name"])
.output()
.await;
let user_name = match name_output {
Ok(output) if output.status.success() => {
let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !name.is_empty() {
Some(name)
} else {
None
}
}
_ => None,
};
// Check if we got at least one value
if user_email.is_none() && user_name.is_none() {
let msg = DaemonMessage::GitConfigInherited {
success: false,
user_email: None,
user_name: None,
error: Some("No git config found in the specified directory".to_string()),
};
let _ = self.ws_tx.send(msg).await;
return Ok(());
}
// Store the config
if let Some(ref email) = user_email {
*self.git_user_email.write().await = Some(email.clone());
tracing::info!(email = %email, "Inherited git user.email");
}
if let Some(ref name) = user_name {
*self.git_user_name.write().await = Some(name.clone());
tracing::info!(name = %name, "Inherited git user.name");
}
// Send success response
let msg = DaemonMessage::GitConfigInherited {
success: true,
user_email,
user_name,
error: None,
};
let _ = self.ws_tx.send(msg).await;
Ok(())
}
/// Apply inherited git config to a worktree directory.
pub async fn apply_git_config(&self, worktree_path: &std::path::Path) -> Result<(), DaemonError> {
let email = self.git_user_email.read().await.clone();
let name = self.git_user_name.read().await.clone();
if let Some(email) = email {
let result = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["config", "user.email", &email])
.output()
.await;
if let Err(e) = result {
tracing::warn!(error = %e, "Failed to set git user.email in worktree");
}
}
if let Some(name) = name {
let result = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["config", "user.name", &name])
.output()
.await;
if let Err(e) = result {
tracing::warn!(error = %e, "Failed to set git user.name in worktree");
}
}
Ok(())
}
}
/// Inner state for spawned tasks (cloneable).
struct TaskManagerInner {
worktree_manager: Arc<WorktreeManager>,
process_manager: Arc<ProcessManager>,
temp_manager: Arc<TempManager>,
tasks: Arc<RwLock<HashMap<Uuid, ManagedTask>>>,
ws_tx: mpsc::Sender<DaemonMessage>,
task_inputs: Arc<RwLock<HashMap<Uuid, mpsc::Sender<String>>>>,
active_pids: Arc<RwLock<HashMap<Uuid, u32>>>,
git_user_email: Arc<RwLock<Option<String>>>,
git_user_name: Arc<RwLock<Option<String>>>,
api_url: String,
api_key: String,
heartbeat_commit_interval_secs: u64,
/// Shared contract task counts for releasing concurrency slots.
contract_task_counts: Arc<RwLock<HashMap<Uuid, usize>>>,
/// Checkpoint patch storage configuration.
checkpoint_patches: CheckpointPatchConfig,
/// Local SQLite database for crash recovery.
local_db: Arc<std::sync::Mutex<LocalDb>>,
}
impl TaskManagerInner {
/// Release a concurrency slot when a task completes.
async fn release_concurrency_slot(&self, concurrency_key: Uuid) {
let mut counts = self.contract_task_counts.write().await;
if let Some(count) = counts.get_mut(&concurrency_key) {
*count = count.saturating_sub(1);
let new_count = *count;
if new_count == 0 {
counts.remove(&concurrency_key);
}
tracing::debug!(
concurrency_key = %concurrency_key,
new_count = new_count,
"Released concurrency slot (from TaskManagerInner)"
);
}
}
/// Remove completed/failed task from local database.
fn remove_task_from_local_db(&self, task_id: Uuid) {
if let Ok(db) = self.local_db.lock() {
if let Err(e) = db.delete_task(task_id) {
tracing::warn!(task_id = %task_id, error = %e, "Failed to remove task from local database");
} else {
tracing::debug!(task_id = %task_id, "Removed task from local database");
}
}
}
/// Fetch the latest checkpoint patch from the server and restore a worktree.
async fn fetch_and_restore_patch(
&self,
task_id: Uuid,
task_name: &str,
repo_source: Option<&str>,
) -> Result<Option<std::path::PathBuf>, DaemonError> {
use crate::daemon::api::client::ApiClient;
if self.api_key.is_empty() {
tracing::debug!(task_id = %task_id, "No API key configured, skipping patch fetch");
return Ok(None);
}
let client = match ApiClient::new(self.api_url.clone(), self.api_key.clone()) {
Ok(c) => c,
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to create API client for patch fetch");
return Ok(None);
}
};
let path = format!("/api/v1/mesh/tasks/{}/patch-data", task_id);
#[derive(serde::Deserialize)]
#[serde(rename_all = "camelCase")]
struct PatchDataResponse {
patch_data: String,
base_commit_sha: String,
repository_url: Option<String>,
}
let resp: PatchDataResponse = match client.get(&path).await {
Ok(r) => r,
Err(crate::daemon::api::client::ApiError::Api { status: 404, .. }) => {
tracing::debug!(task_id = %task_id, "No checkpoint patch found on server");
return Ok(None);
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to fetch patch data from server");
return Ok(None);
}
};
// Determine repo source: prefer the one from run_task args, fall back to server response
let source = repo_source
.map(|s| s.to_string())
.or(resp.repository_url);
let source = match source {
Some(s) => s,
None => {
tracing::warn!(task_id = %task_id, "No repository URL available to restore patch");
return Ok(None);
}
};
tracing::info!(
task_id = %task_id,
base_sha = %resp.base_commit_sha,
"Fetched checkpoint patch from server, attempting restore"
);
// Decode base64 patch data
let patch_bytes = match base64::Engine::decode(
&base64::engine::general_purpose::STANDARD,
&resp.patch_data,
) {
Ok(b) => b,
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to decode fetched patch data");
return Ok(None);
}
};
match self.worktree_manager.restore_from_patch(
&source,
task_id,
task_name,
&resp.base_commit_sha,
&patch_bytes,
).await {
Ok(worktree_info) => {
tracing::info!(
task_id = %task_id,
path = %worktree_info.path.display(),
"Successfully restored worktree from fetched patch"
);
Ok(Some(worktree_info.path))
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to restore worktree from fetched patch");
Ok(None)
}
}
}
/// Run a task to completion.
#[allow(clippy::too_many_arguments)]
async fn run_task(
&self,
task_id: Uuid,
task_name: String,
plan: String,
repo_source: Option<String>,
base_branch: Option<String>,
target_branch: Option<String>,
is_orchestrator: bool,
is_supervisor: bool,
target_repo_path: Option<String>,
completion_action: Option<String>,
continue_from_task_id: Option<Uuid>,
copy_files: Option<Vec<String>>,
contract_id: Option<Uuid>,
autonomous_loop: bool,
resume_session: bool,
conversation_history: Option<serde_json::Value>,
patch_data: Option<String>,
patch_base_sha: Option<String>,
local_only: bool,
auto_merge_local: bool,
supervisor_worktree_task_id: Option<Uuid>,
directive_id: Option<Uuid>,
) -> Result<(), DaemonError> {
tracing::info!(task_id = %task_id, is_orchestrator = is_orchestrator, is_supervisor = is_supervisor, resume_session = resume_session, has_patch = patch_data.is_some(), "=== RUN_TASK START ===");
// If resuming session, try to find existing worktree first
let existing_worktree = if resume_session {
match self.find_worktree_for_task(task_id).await {
Ok(path) => {
tracing::info!(task_id = %task_id, path = %path.display(), "Found existing worktree for session resume");
Some(path)
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "No existing worktree found for resume, will create new");
None
}
}
} else {
None
};
// Try to restore from patch if worktree is missing but we have patch data
let restored_from_patch = if existing_worktree.is_none() {
if let (Some(patch_str), Some(base_sha), Some(source)) = (&patch_data, &patch_base_sha, &repo_source) {
tracing::info!(
task_id = %task_id,
base_sha = %base_sha,
patch_len = patch_str.len(),
"Attempting to restore worktree from patch"
);
let msg = DaemonMessage::task_output(
task_id,
format!("Restoring worktree from checkpoint patch...\n"),
false,
);
let _ = self.ws_tx.send(msg).await;
// Decode base64 patch data
match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, patch_str) {
Ok(patch_bytes) => {
match self.worktree_manager.restore_from_patch(
source,
task_id,
&task_name,
base_sha,
&patch_bytes,
).await {
Ok(worktree_info) => {
tracing::info!(
task_id = %task_id,
path = %worktree_info.path.display(),
"Successfully restored worktree from patch"
);
// Store worktree info
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.worktree = Some(worktree_info.clone());
}
}
let msg = DaemonMessage::task_output(
task_id,
format!("Worktree restored at {}\n", worktree_info.path.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
Some(worktree_info.path)
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to restore from patch, will clone fresh");
let msg = DaemonMessage::task_output(
task_id,
format!("Warning: Failed to restore from patch ({}), starting fresh\n", e),
false,
);
let _ = self.ws_tx.send(msg).await;
None
}
}
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to decode patch data");
None
}
}
} else {
None
}
} else {
None
};
// If resuming but no local worktree and no inline patch, try fetching from server
let restored_from_patch = if restored_from_patch.is_none() && existing_worktree.is_none() && resume_session {
tracing::info!(task_id = %task_id, "No local worktree or inline patch for resume, trying server fetch");
let msg = DaemonMessage::task_output(
task_id,
"Fetching checkpoint patch from server...\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
match self.fetch_and_restore_patch(task_id, &task_name, repo_source.as_deref()).await {
Ok(Some(path)) => {
// Store worktree info in tasks map
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.worktree = Some(WorktreeInfo {
path: path.clone(),
branch: format!("task/{}", task_id),
source_repo: repo_source.clone().unwrap_or_default().into(),
});
}
}
let msg = DaemonMessage::task_output(
task_id,
format!("Worktree restored from server patch at {}\n", path.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
Some(path)
}
Ok(None) => {
tracing::info!(task_id = %task_id, "No server patch available, falling through to conversation-only resume");
let msg = DaemonMessage::task_output(
task_id,
"No checkpoint patch available on server, resuming with conversation history only\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
None
}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Failed to fetch/restore patch from server");
None
}
}
} else {
restored_from_patch
};
// Determine working directory
// First check if we should share a supervisor's worktree
// Track if we need to merge to supervisor on completion (cross-daemon case)
let mut merge_to_supervisor_on_completion: Option<Uuid> = None;
let shared_supervisor_worktree = if let Some(supervisor_task_id) = supervisor_worktree_task_id {
match self.find_worktree_for_task(supervisor_task_id).await {
Ok(path) => {
tracing::info!(
task_id = %task_id,
supervisor_task_id = %supervisor_task_id,
path = %path.display(),
"Using shared worktree from supervisor"
);
let msg = DaemonMessage::task_output(
task_id,
format!("Using shared worktree from supervisor: {}\n", path.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
Some(path)
}
Err(_) => {
// Supervisor worktree not on this daemon (cross-daemon case)
// Will create own worktree and merge to supervisor on completion
tracing::info!(
task_id = %task_id,
supervisor_task_id = %supervisor_task_id,
"Supervisor worktree not on this daemon, will create own and merge on completion"
);
let msg = DaemonMessage::task_output(
task_id,
format!("Supervisor on different daemon, will merge changes on completion\n"),
false,
);
let _ = self.ws_tx.send(msg).await;
// Mark for merge on completion
merge_to_supervisor_on_completion = Some(supervisor_task_id);
None
}
}
} else {
None
};
let has_existing_worktree = existing_worktree.is_some() || restored_from_patch.is_some() || shared_supervisor_worktree.is_some();
let working_dir = if let Some(shared_path) = shared_supervisor_worktree {
// Use supervisor's worktree directly (no copy, no new branch)
shared_path
} else if let Some(existing) = existing_worktree {
// Reuse existing worktree for session resume
let msg = DaemonMessage::task_output(
task_id,
format!("Resuming session in existing worktree: {}\n", existing.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
existing
} else if let Some(restored_path) = restored_from_patch {
// Already restored from patch above
restored_path
} else if let Some(ref source) = repo_source {
if is_new_repo_request(source) {
// Explicit new repo request: new:// or new://project-name
tracing::info!(
task_id = %task_id,
source = %source,
"Creating new git repository"
);
let msg = DaemonMessage::task_output(
task_id,
format!("Initializing new git repository...\n"),
false,
);
let _ = self.ws_tx.send(msg).await;
let worktree_info = self.worktree_manager
.init_new_repo(task_id, source)
.await
.map_err(|e| DaemonError::Task(TaskError::SetupFailed(e.to_string())))?;
tracing::info!(
task_id = %task_id,
path = %worktree_info.path.display(),
"New repository created"
);
// Apply inherited git config to the new repo (overrides defaults)
self.apply_git_config(&worktree_info.path).await;
// Store worktree info
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.worktree = Some(worktree_info.clone());
}
}
let msg = DaemonMessage::task_output(
task_id,
format!("Repository ready at {}\n", worktree_info.path.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
worktree_info.path
} else {
// Send progress message
let msg = DaemonMessage::task_output(
task_id,
format!("Setting up worktree from {}...\n", source),
false,
);
let _ = self.ws_tx.send(msg).await;
// Ensure source repo exists (clone if URL, verify if path)
let source_repo = self.worktree_manager.ensure_repo(source).await
.map_err(|e| DaemonError::Task(TaskError::SetupFailed(e.to_string())))?;
// Detect or use provided base branch
let branch = if let Some(ref b) = base_branch {
b.clone()
} else {
self.worktree_manager.detect_default_branch(&source_repo).await
.map_err(|e| DaemonError::Task(TaskError::SetupFailed(e.to_string())))?
};
tracing::info!(
task_id = %task_id,
source = %source,
branch = %branch,
continue_from_task_id = ?continue_from_task_id,
"Setting up worktree"
);
// Create worktree - either from scratch or copying from another task
let task_name = format!("task-{}", &task_id.to_string()[..8]);
let worktree_info = if let Some(from_task_id) = continue_from_task_id {
// Try to find the source task's worktree path
match self.find_worktree_for_task(from_task_id).await {
Ok(source_worktree) => {
let msg = DaemonMessage::task_output(
task_id,
format!("Continuing from task {} worktree...\n", &from_task_id.to_string()[..8]),
false,
);
let _ = self.ws_tx.send(msg).await;
// Create worktree by copying from source task
self.worktree_manager
.create_worktree_from_task(&source_worktree, task_id, &task_name)
.await
.map_err(|e| DaemonError::Task(TaskError::SetupFailed(e.to_string())))?
}
Err(worktree_err) => {
// Source worktree not found - try to recover using patch data
if let (Some(patch_str), Some(base_sha)) = (&patch_data, &patch_base_sha) {
tracing::info!(
task_id = %task_id,
from_task_id = %from_task_id,
base_sha = %base_sha,
patch_len = patch_str.len(),
"Source worktree not found, attempting to restore from patch"
);
let msg = DaemonMessage::task_output(
task_id,
format!("Source worktree unavailable, restoring from checkpoint patch...\n"),
false,
);
let _ = self.ws_tx.send(msg).await;
// Decode base64 patch data
match base64::Engine::decode(&base64::engine::general_purpose::STANDARD, patch_str) {
Ok(patch_bytes) => {
match self.worktree_manager.restore_from_patch(
source,
task_id,
&task_name,
base_sha,
&patch_bytes,
).await {
Ok(worktree_info) => {
tracing::info!(
task_id = %task_id,
path = %worktree_info.path.display(),
"Successfully restored worktree from patch"
);
worktree_info
}
Err(e) => {
return Err(DaemonError::Task(TaskError::SetupFailed(
format!("Cannot continue from task {}: {} (patch restore also failed: {})", from_task_id, worktree_err, e)
)));
}
}
}
Err(e) => {
return Err(DaemonError::Task(TaskError::SetupFailed(
format!("Cannot continue from task {}: {} (patch decode failed: {})", from_task_id, worktree_err, e)
)));
}
}
} else {
// No patch data available - fail with original error
return Err(DaemonError::Task(TaskError::SetupFailed(
format!("Cannot continue from task {}: {}", from_task_id, worktree_err)
)));
}
}
}
} else {
// Create fresh worktree from repo
self.worktree_manager
.create_worktree(&source_repo, task_id, &task_name, &branch)
.await
.map_err(|e| DaemonError::Task(TaskError::SetupFailed(e.to_string())))?
};
tracing::info!(
task_id = %task_id,
worktree_path = %worktree_info.path.display(),
branch = %worktree_info.branch,
continued_from = ?continue_from_task_id,
"Worktree created"
);
// Apply inherited git config to the worktree
self.apply_git_config(&worktree_info.path).await;
// Store worktree info
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.worktree = Some(worktree_info.clone());
}
}
let msg = DaemonMessage::task_output(
task_id,
format!("Worktree ready at {}\n", worktree_info.path.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
worktree_info.path
}
} else {
// No repo specified - use managed temp directory in ~/.makima/temp/
tracing::info!(task_id = %task_id, "Creating managed temp directory (no repo)");
let msg = DaemonMessage::task_output(
task_id,
"Creating temporary working directory...\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
let temp_dir = self.temp_manager.create_task_dir(task_id).await?;
let msg = DaemonMessage::task_output(
task_id,
format!("Working directory ready at {}\n", temp_dir.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
temp_dir
};
// Store merge target if cross-daemon (will merge to supervisor on completion)
if let Some(supervisor_task_id) = merge_to_supervisor_on_completion {
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.merge_to_supervisor_task_id = Some(supervisor_task_id);
tracing::info!(
task_id = %task_id,
supervisor_task_id = %supervisor_task_id,
"Task marked for merge to supervisor on completion"
);
}
}
// Copy files from parent task's worktree if specified
if let Some(ref files) = copy_files {
if !files.is_empty() {
// Get the parent task ID to find its worktree
let parent_task_id = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).and_then(|t| t.parent_task_id)
};
if let Some(parent_id) = parent_task_id {
match self.find_worktree_for_task(parent_id).await {
Ok(parent_worktree) => {
let msg = DaemonMessage::task_output(
task_id,
format!("Copying {} files from orchestrator...\n", files.len()),
false,
);
let _ = self.ws_tx.send(msg).await;
for file_path in files {
let source = parent_worktree.join(file_path);
let dest = working_dir.join(file_path);
// Create parent directories if needed
if let Some(parent) = dest.parent() {
if let Err(e) = tokio::fs::create_dir_all(parent).await {
tracing::warn!(
task_id = %task_id,
file = %file_path,
error = %e,
"Failed to create parent directory for file"
);
continue;
}
}
// Copy the file
match tokio::fs::copy(&source, &dest).await {
Ok(_) => {
tracing::info!(
task_id = %task_id,
source = %source.display(),
dest = %dest.display(),
"Copied file from orchestrator"
);
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
source = %source.display(),
dest = %dest.display(),
error = %e,
"Failed to copy file from orchestrator"
);
// Notify but don't fail - the file might be optional
let msg = DaemonMessage::task_output(
task_id,
format!("Warning: Could not copy {}: {}\n", file_path, e),
false,
);
let _ = self.ws_tx.send(msg).await;
}
}
}
let msg = DaemonMessage::task_output(
task_id,
"Files copied from orchestrator.\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
parent_id = %parent_id,
error = %e,
"Could not find parent task worktree for file copying"
);
}
}
} else {
tracing::warn!(
task_id = %task_id,
"copy_files specified but no parent_task_id"
);
}
}
}
// Update state to Starting
tracing::info!(task_id = %task_id, "Updating state: Initializing -> Starting");
self.update_state(task_id, TaskState::Starting).await;
self.send_status_change(task_id, "initializing", "starting").await;
// Check Claude is available
match self.process_manager.check_claude_available().await {
Ok(version) => {
tracing::info!(task_id = %task_id, version = %version, "Claude Code available");
let msg = DaemonMessage::task_output(
task_id,
format!("Claude Code {} ready\n", version),
false,
);
let _ = self.ws_tx.send(msg).await;
}
Err(e) => {
let err_msg = format!("Claude Code not available: {}", e);
tracing::error!(task_id = %task_id, error = %err_msg);
return Err(DaemonError::Task(TaskError::SetupFailed(err_msg)));
}
}
// Set up supervisor, orchestrator, or subtask mode
let (extra_env, full_plan, system_prompt) = if is_supervisor {
// Supervisor mode: long-running contract orchestrator
tracing::info!(task_id = %task_id, working_dir = %working_dir.display(), "Setting up supervisor mode");
let msg = DaemonMessage::task_output(
task_id,
"Setting up supervisor environment...\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
// Generate tool key for API access
let tool_key = generate_tool_key();
tracing::info!(task_id = %task_id, tool_key_len = tool_key.len(), "Generated tool key for supervisor");
// Register tool key with server
let register_msg = DaemonMessage::register_tool_key(task_id, tool_key.clone());
if self.ws_tx.send(register_msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to register tool key");
} else {
tracing::info!(task_id = %task_id, "Tool key registration message sent to server");
}
// Set up environment variables for makima CLI
let mut env = HashMap::new();
env.insert("MAKIMA_API_URL".to_string(), self.api_url.clone());
env.insert("MAKIMA_API_KEY".to_string(), tool_key.clone());
env.insert("MAKIMA_TASK_ID".to_string(), task_id.to_string());
// Supervisor needs contract ID for its tools
if let Some(cid) = contract_id {
env.insert("MAKIMA_CONTRACT_ID".to_string(), cid.to_string());
}
tracing::info!(
task_id = %task_id,
api_url = %self.api_url,
tool_key_preview = &tool_key[..8.min(tool_key.len())],
"Set supervisor environment variables"
);
// For supervisor, pass instructions as SYSTEM PROMPT (not user message)
// This ensures Claude treats them as behavioral constraints
let supervisor_user_plan = format!(
"Contract goal:\n{}",
plan
);
let msg = DaemonMessage::task_output(
task_id,
"Supervisor environment ready (makima CLI available)\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
// Return system prompt separately - it will be passed via --system-prompt flag
(Some(env), supervisor_user_plan, Some(SUPERVISOR_SYSTEM_PROMPT.to_string()))
} else if is_orchestrator {
tracing::info!(task_id = %task_id, working_dir = %working_dir.display(), "Setting up orchestrator mode");
let msg = DaemonMessage::task_output(
task_id,
"Setting up orchestrator environment...\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
// Generate tool key for API access
let tool_key = generate_tool_key();
tracing::info!(task_id = %task_id, tool_key_len = tool_key.len(), "Generated tool key for orchestrator");
// Register tool key with server
let register_msg = DaemonMessage::register_tool_key(task_id, tool_key.clone());
if self.ws_tx.send(register_msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to register tool key");
} else {
tracing::info!(task_id = %task_id, "Tool key registration message sent to server");
}
// Set up environment variables for makima CLI
let mut env = HashMap::new();
env.insert("MAKIMA_API_URL".to_string(), self.api_url.clone());
env.insert("MAKIMA_API_KEY".to_string(), tool_key.clone());
env.insert("MAKIMA_TASK_ID".to_string(), task_id.to_string());
tracing::info!(
task_id = %task_id,
api_url = %self.api_url,
tool_key_preview = &tool_key[..8.min(tool_key.len())],
"Set orchestrator environment variables"
);
// For orchestrator, pass instructions as SYSTEM PROMPT
let orchestrator_user_plan = format!(
"Your task:\n{}",
plan
);
let msg = DaemonMessage::task_output(
task_id,
"Orchestrator environment ready (makima CLI available)\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
(Some(env), orchestrator_user_plan, Some(ORCHESTRATOR_SYSTEM_PROMPT.to_string()))
} else {
tracing::info!(task_id = %task_id, "Running as regular subtask (not orchestrator)");
// For subtasks, pass worktree isolation instructions as system prompt
let subtask_user_plan = format!(
"Your task:\n{}",
plan
);
(None, subtask_user_plan, Some(SUBTASK_SYSTEM_PROMPT.to_string()))
};
// Add contract environment if task has contract_id (skip for supervisors - they already have it)
let (extra_env, full_plan, system_prompt) = if let Some(cid) = contract_id {
if is_supervisor {
// Supervisors already have contract ID and API access set up
tracing::info!(task_id = %task_id, contract_id = %cid, "Supervisor already has contract integration");
(extra_env, full_plan, system_prompt)
} else {
tracing::info!(task_id = %task_id, contract_id = %cid, "Setting up contract integration");
// Set up environment variables for makima CLI
let mut env = extra_env.unwrap_or_default();
env.insert("MAKIMA_CONTRACT_ID".to_string(), cid.to_string());
// If not already an orchestrator, we need API access for makima CLI
if !is_orchestrator {
// Generate tool key for API access
let tool_key = generate_tool_key();
tracing::info!(task_id = %task_id, "Generated tool key for contract access");
// Register tool key with server
let register_msg = DaemonMessage::register_tool_key(task_id, tool_key.clone());
if self.ws_tx.send(register_msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to register contract tool key");
}
env.insert("MAKIMA_API_URL".to_string(), self.api_url.clone());
env.insert("MAKIMA_API_KEY".to_string(), tool_key);
env.insert("MAKIMA_TASK_ID".to_string(), task_id.to_string());
}
let msg = DaemonMessage::task_output(
task_id,
"Contract integration ready (makima CLI available)\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
// Prepend contract integration prompt to the plan so the task knows to use makima CLI
let contract_plan = format!(
"{}{}",
CONTRACT_INTEGRATION_PROMPT,
full_plan
);
(Some(env), contract_plan, system_prompt)
}
} else {
(extra_env, full_plan, system_prompt)
};
// Add directive environment if task has directive_id
let (extra_env, full_plan, system_prompt) = if let Some(did) = directive_id {
tracing::info!(task_id = %task_id, directive_id = %did, "Setting up directive integration");
let mut env = extra_env.unwrap_or_default();
env.insert("MAKIMA_DIRECTIVE_ID".to_string(), did.to_string());
// If not already an orchestrator/supervisor, we need API access for makima CLI
if !is_orchestrator && !is_supervisor && !env.contains_key("MAKIMA_API_KEY") {
let tool_key = generate_tool_key();
tracing::info!(task_id = %task_id, "Generated tool key for directive access");
let register_msg = DaemonMessage::register_tool_key(task_id, tool_key.clone());
if self.ws_tx.send(register_msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to register directive tool key");
}
env.insert("MAKIMA_API_URL".to_string(), self.api_url.clone());
env.insert("MAKIMA_API_KEY".to_string(), tool_key);
env.insert("MAKIMA_TASK_ID".to_string(), task_id.to_string());
}
let msg = DaemonMessage::task_output(
task_id,
"Directive integration ready (makima CLI available)\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
(Some(env), full_plan, system_prompt)
} else {
(extra_env, full_plan, system_prompt)
};
// Spawn Claude process
let plan_bytes = full_plan.len();
let plan_chars = full_plan.chars().count();
// Rough token estimate: ~4 chars per token for English
let estimated_tokens = plan_chars / 4;
tracing::info!(
task_id = %task_id,
working_dir = %working_dir.display(),
is_orchestrator = is_orchestrator,
plan_bytes = plan_bytes,
plan_chars = plan_chars,
estimated_tokens = estimated_tokens,
"Spawning Claude process"
);
// Warn if plan is very large (Claude's context is typically 100k-200k tokens)
if estimated_tokens > 50_000 {
tracing::warn!(task_id = %task_id, estimated_tokens = estimated_tokens, "Plan is very large - may hit context limits!");
let msg = DaemonMessage::task_output(
task_id,
format!("Warning: Plan is very large (~{} tokens). This may cause issues.\n", estimated_tokens),
false,
);
let _ = self.ws_tx.send(msg).await;
}
let msg = DaemonMessage::task_output(
task_id,
if is_orchestrator {
format!("Starting Claude Code (orchestrator mode, ~{} tokens)...\n", estimated_tokens)
} else {
format!("Starting Claude Code (~{} tokens)...\n", estimated_tokens)
},
false,
);
let _ = self.ws_tx.send(msg).await;
// Clone extra_env for use in autonomous loop iterations
let extra_env_for_loop = extra_env.clone();
tracing::debug!(task_id = %task_id, has_system_prompt = system_prompt.is_some(), resume_session = resume_session, "Calling process_manager.spawn()...");
let mut process = if resume_session {
// Use --continue flag to resume from previous session
// Build continuation prompt based on whether worktree exists
let continuation_prompt = if has_existing_worktree {
// Worktree exists: Claude's session state should work
format!(
"Resuming previous session. Continue from where you left off.\n\n{}",
full_plan
)
} else if let Some(ref history) = conversation_history {
// Worktree missing: inject conversation history as context
let history_str = serde_json::to_string_pretty(history).unwrap_or_default();
format!(
"Resuming previous session. Here is the conversation history from the previous session:\n\n\
<previous_conversation>\n{}\n</previous_conversation>\n\n\
Continue from where you left off with this task:\n\n{}",
history_str,
full_plan
)
} else {
// No history available: just the plan
format!("Resuming with plan:\n\n{}", full_plan)
};
let resume_msg = if has_existing_worktree {
"Using --continue to resume previous conversation...\n"
} else if conversation_history.is_some() {
"Worktree not found. Resuming with injected conversation history...\n"
} else {
"Resuming without conversation history (worktree not found)...\n"
};
let msg = DaemonMessage::task_output(
task_id,
resume_msg.to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
self.process_manager
.spawn_continue(&working_dir, &continuation_prompt, extra_env, system_prompt.as_deref())
.await
.map_err(|e| {
tracing::error!(task_id = %task_id, error = %e, "Failed to spawn Claude process with --continue");
DaemonError::Task(TaskError::SetupFailed(e.to_string()))
})?
} else {
self.process_manager
.spawn_with_system_prompt(&working_dir, &full_plan, extra_env, system_prompt.as_deref())
.await
.map_err(|e| {
tracing::error!(task_id = %task_id, error = %e, "Failed to spawn Claude process");
DaemonError::Task(TaskError::SetupFailed(e.to_string()))
})?
};
// Register the process PID for graceful shutdown tracking
if let Some(pid) = process.id() {
self.active_pids.write().await.insert(task_id, pid);
tracing::info!(task_id = %task_id, pid = pid, "Claude process spawned successfully, PID registered");
} else {
tracing::info!(task_id = %task_id, "Claude process spawned successfully (no PID available)");
}
// Set up input channel for this task so we can send messages to its stdin
tracing::debug!(task_id = %task_id, "Setting up input channel...");
let (input_tx, mut input_rx) = mpsc::channel::<String>(100);
tracing::debug!(task_id = %task_id, "Acquiring task_inputs write lock...");
self.task_inputs.write().await.insert(task_id, input_tx);
tracing::debug!(task_id = %task_id, "Input channel registered");
// Get stdin handle for input forwarding and completion signaling
let stdin_handle = process.stdin_handle();
let mut stdin_handle_for_completion = stdin_handle.clone();
tracing::info!(task_id = %task_id, "Setting up stdin forwarder for task input (JSON protocol)");
tokio::spawn(async move {
tracing::info!(task_id = %task_id, "Stdin forwarder task started, waiting for messages...");
while let Some(msg) = input_rx.recv().await {
tracing::info!(task_id = %task_id, msg_len = msg.len(), msg_preview = %if msg.len() > 50 { &msg[..50] } else { &msg }, "Received message from input channel");
// Format as JSON user message for stream-json input protocol
let json_msg = ClaudeInputMessage::user(&msg);
let json_line = match json_msg.to_json_line() {
Ok(line) => line,
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to serialize input message");
continue;
}
};
tracing::debug!(task_id = %task_id, json_line = %json_line.trim(), "Formatted JSON line for stdin");
let mut stdin_guard = stdin_handle.lock().await;
if let Some(ref mut stdin) = *stdin_guard {
tracing::debug!(task_id = %task_id, "Acquired stdin lock, writing...");
if stdin.write_all(json_line.as_bytes()).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to write to stdin, breaking");
break;
}
if stdin.flush().await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to flush stdin, breaking");
break;
}
tracing::info!(task_id = %task_id, json_len = json_line.len(), "Successfully wrote user message to Claude stdin");
} else {
tracing::warn!(task_id = %task_id, "Stdin is None (already closed), cannot send message");
break;
}
}
tracing::info!(task_id = %task_id, "Stdin forwarder task ended (channel closed or stdin unavailable)");
});
// Update state to Running
{
tracing::debug!(task_id = %task_id, "Acquiring tasks write lock for Running state update");
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Running;
task.started_at = Some(Instant::now());
}
tracing::debug!(task_id = %task_id, "Released tasks write lock");
}
tracing::info!(task_id = %task_id, "Updating state: Starting -> Running");
self.send_status_change(task_id, "starting", "running").await;
tracing::debug!(task_id = %task_id, "Sent status change notification");
// Stream output with startup timeout check
tracing::info!(task_id = %task_id, "Starting output stream - waiting for Claude output...");
tracing::debug!(task_id = %task_id, "Output will be forwarded via WebSocket to server");
let ws_tx = self.ws_tx.clone();
// For auth error detection
let claude_command = self.process_manager.claude_command().to_string();
let daemon_hostname = hostname::get().ok().and_then(|h| h.into_string().ok());
let mut auth_error_handled = false;
// For autonomous loop mode: track accumulated output for COMPLETION_GATE detection
let mut accumulated_output = String::new();
let mut circuit_breaker = CircuitBreaker::new();
let mut iteration_count = 0u32;
let mut final_exit_code: i64 = -1; // Track the final exit code across iterations
// Autonomous loop: we may run multiple iterations
'autonomous_loop: loop {
iteration_count += 1;
if autonomous_loop && iteration_count > 1 {
tracing::info!(
task_id = %task_id,
iteration = iteration_count,
"Starting autonomous loop iteration"
);
let msg = DaemonMessage::task_output(
task_id,
format!("\n[Autonomous Loop] Starting iteration {} (--continue mode)\n", iteration_count),
false,
);
let _ = self.ws_tx.send(msg).await;
// For subsequent iterations, spawn with --continue flag
let continuation_prompt = "Continue working on the task. Review your previous output and progress. When you are completely done, output a COMPLETION_GATE block with ready: true.";
process = self.process_manager
.spawn_continue(&working_dir, continuation_prompt, extra_env_for_loop.clone(), system_prompt.as_deref())
.await
.map_err(|e| {
tracing::error!(task_id = %task_id, error = %e, "Failed to spawn Claude process for continuation");
DaemonError::Task(TaskError::SetupFailed(e.to_string()))
})?;
// Register the new process PID
if let Some(pid) = process.id() {
self.active_pids.write().await.insert(task_id, pid);
tracing::info!(task_id = %task_id, pid = pid, iteration = iteration_count, "Claude continue process spawned");
}
// Reset stdin handle for the new process
stdin_handle_for_completion = process.stdin_handle();
}
// Clear output for this iteration (we'll check for COMPLETION_GATE in the new output)
let mut iteration_output = String::new();
let mut output_count = 0u64;
let mut output_bytes = 0usize;
let startup_timeout = tokio::time::Duration::from_secs(30);
let mut startup_check = tokio::time::interval(tokio::time::Duration::from_secs(5));
startup_check.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let startup_deadline = tokio::time::Instant::now() + startup_timeout;
// Heartbeat commit interval (only active if configured and we have a git repo)
let heartbeat_enabled = self.heartbeat_commit_interval_secs > 0 && repo_source.is_some();
let mut heartbeat_interval = tokio::time::interval(
tokio::time::Duration::from_secs(
if heartbeat_enabled { self.heartbeat_commit_interval_secs } else { u64::MAX }
)
);
heartbeat_interval.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
// Skip the first immediate tick
heartbeat_interval.tick().await;
loop {
tokio::select! {
maybe_line = process.next_output() => {
match maybe_line {
Some(line) => {
output_count += 1;
output_bytes += line.content.len();
// Accumulate output for COMPLETION_GATE detection in autonomous loop mode
if autonomous_loop {
iteration_output.push_str(&line.content);
iteration_output.push('\n');
}
if output_count == 1 {
tracing::info!(task_id = %task_id, "Received first output line from Claude");
}
if output_count % 100 == 0 {
tracing::debug!(task_id = %task_id, output_count = output_count, output_bytes = output_bytes, "Output progress");
}
// Log output details for debugging
tracing::trace!(
task_id = %task_id,
line_num = output_count,
content_len = line.content.len(),
is_stdout = line.is_stdout,
json_type = ?line.json_type,
"Forwarding output to WebSocket"
);
// Check if this is a "result" message indicating task completion
// With --input-format=stream-json, Claude waits for more input after completion
// We close stdin to signal EOF and let the process exit
if line.json_type.as_deref() == Some("result") {
tracing::info!(task_id = %task_id, "Received result message, closing stdin to signal completion");
let mut stdin_guard = stdin_handle_for_completion.lock().await;
if let Some(mut stdin) = stdin_guard.take() {
let _ = stdin.shutdown().await;
}
}
// Check for OAuth auth error before sending output
let content_for_auth_check = line.content.clone();
let json_type_for_auth_check = line.json_type.clone();
let is_stdout_for_auth_check = line.is_stdout;
let msg = DaemonMessage::task_output(task_id, line.content, false);
if ws_tx.send(msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to send output, channel closed");
break;
}
// Detect OAuth token expiration and trigger remote login flow
if !auth_error_handled && is_oauth_auth_error(&content_for_auth_check, json_type_for_auth_check.as_deref(), is_stdout_for_auth_check) {
auth_error_handled = true;
tracing::warn!(task_id = %task_id, "OAuth authentication error detected, initiating remote login flow");
// Spawn claude setup-token to get login URL
if let Some(login_url) = get_oauth_login_url(&claude_command).await {
tracing::info!(task_id = %task_id, login_url = %login_url, "Got OAuth login URL");
let auth_msg = DaemonMessage::AuthenticationRequired {
task_id: Some(task_id),
login_url,
hostname: daemon_hostname.clone(),
};
if ws_tx.send(auth_msg).await.is_err() {
tracing::warn!(task_id = %task_id, "Failed to send auth required message");
}
} else {
tracing::error!(task_id = %task_id, "Failed to get OAuth login URL from setup-token");
let fallback_msg = DaemonMessage::task_output(
task_id,
format!("Authentication required on daemon{}. Please run 'claude /login' on the daemon machine.\n",
daemon_hostname.as_ref().map(|h| format!(" ({})", h)).unwrap_or_default()),
false,
);
let _ = ws_tx.send(fallback_msg).await;
}
}
}
None => {
tracing::info!(task_id = %task_id, output_count = output_count, output_bytes = output_bytes, "Output stream ended");
break;
}
}
}
_ = startup_check.tick(), if output_count == 0 => {
// Check if process is still alive
match process.try_wait() {
Ok(Some(exit_code)) => {
tracing::error!(task_id = %task_id, exit_code = exit_code, "Claude process exited before producing output!");
let msg = DaemonMessage::task_output(
task_id,
format!("Error: Claude process exited unexpectedly with code {}\n", exit_code),
false,
);
let _ = ws_tx.send(msg).await;
break;
}
Ok(None) => {
// Still running but no output
if tokio::time::Instant::now() > startup_deadline {
tracing::warn!(task_id = %task_id, "Claude process not producing output after 30s - may be stuck");
let msg = DaemonMessage::task_output(
task_id,
"Warning: Claude Code is taking longer than expected to start. It may be waiting for authentication or network access.\n".to_string(),
false,
);
let _ = ws_tx.send(msg).await;
} else {
tracing::debug!(task_id = %task_id, "Claude process still running, waiting for output...");
}
}
Err(e) => {
tracing::error!(task_id = %task_id, error = %e, "Failed to check Claude process status");
}
}
}
_ = heartbeat_interval.tick(), if heartbeat_enabled => {
// Create periodic ephemeral patch to preserve work-in-progress
match self.create_ephemeral_patch(task_id, &working_dir).await {
Ok(files_count) => {
let msg = DaemonMessage::task_output(
task_id,
format!("[Heartbeat] Patch saved ({} files)\n", files_count),
false,
);
let _ = ws_tx.send(msg).await;
}
Err(e) => {
// No changes to patch or error - this is fine, just log at debug level
tracing::debug!(task_id = %task_id, error = %e, "Heartbeat patch skipped");
}
}
}
}
}
// Wait for process to exit
let exit_code = process.wait().await.unwrap_or(-1);
final_exit_code = exit_code; // Store for use after the loop
// Unregister the process PID (process has exited)
self.active_pids.write().await.remove(&task_id);
tracing::debug!(task_id = %task_id, "Unregistered process PID");
// Clean up input channel for this task
self.task_inputs.write().await.remove(&task_id);
tracing::debug!(task_id = %task_id, "Removed task input channel");
// Accumulate this iteration's output
accumulated_output.push_str(&iteration_output);
// === AUTONOMOUS LOOP LOGIC ===
// Check if we should continue or complete
if autonomous_loop && exit_code == 0 {
// Check for COMPLETION_GATE in the output
let completion_gate = CompletionGate::parse_last(&iteration_output);
match completion_gate {
Some(gate) if gate.ready => {
tracing::info!(
task_id = %task_id,
iteration = iteration_count,
reason = ?gate.reason,
"COMPLETION_GATE ready=true detected, task complete"
);
let msg = DaemonMessage::task_output(
task_id,
format!("\n[Autonomous Loop] Task completed after {} iteration(s). Reason: {}\n",
iteration_count,
gate.reason.unwrap_or_else(|| "Task complete".to_string())
),
false,
);
let _ = self.ws_tx.send(msg).await;
break 'autonomous_loop;
}
Some(gate) => {
// COMPLETION_GATE found but not ready
tracing::info!(
task_id = %task_id,
iteration = iteration_count,
reason = ?gate.reason,
blockers = ?gate.blockers,
"COMPLETION_GATE ready=false, will continue"
);
// Check circuit breaker
// For now, we consider output_bytes > 0 as "progress"
let had_progress = output_bytes > 0;
let error = gate.blockers.as_ref().and_then(|b| b.first()).map(|s| s.as_str());
if !circuit_breaker.record_iteration(had_progress, error) {
// Circuit breaker tripped
tracing::warn!(
task_id = %task_id,
reason = ?circuit_breaker.open_reason,
"Circuit breaker tripped, stopping autonomous loop"
);
let msg = DaemonMessage::task_output(
task_id,
format!("\n[Autonomous Loop] Circuit breaker tripped: {}\n",
circuit_breaker.open_reason.as_deref().unwrap_or("Unknown reason")
),
false,
);
let _ = self.ws_tx.send(msg).await;
break 'autonomous_loop;
}
let msg = DaemonMessage::task_output(
task_id,
format!("\n[Autonomous Loop] COMPLETION_GATE ready=false. Reason: {}. Restarting...\n",
gate.reason.unwrap_or_else(|| "Not complete".to_string())
),
false,
);
let _ = self.ws_tx.send(msg).await;
// Continue to next iteration
continue 'autonomous_loop;
}
None => {
// No COMPLETION_GATE found - check circuit breaker and continue
tracing::info!(
task_id = %task_id,
iteration = iteration_count,
"No COMPLETION_GATE found, will restart with continuation prompt"
);
let had_progress = output_bytes > 0;
if !circuit_breaker.record_iteration(had_progress, None) {
tracing::warn!(
task_id = %task_id,
reason = ?circuit_breaker.open_reason,
"Circuit breaker tripped (no COMPLETION_GATE), stopping"
);
let msg = DaemonMessage::task_output(
task_id,
format!("\n[Autonomous Loop] Circuit breaker tripped: {}\n",
circuit_breaker.open_reason.as_deref().unwrap_or("Unknown reason")
),
false,
);
let _ = self.ws_tx.send(msg).await;
break 'autonomous_loop;
}
let msg = DaemonMessage::task_output(
task_id,
"\n[Autonomous Loop] No COMPLETION_GATE found. Restarting with --continue...\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
continue 'autonomous_loop;
}
}
} else {
// Not in autonomous loop mode or process failed - exit normally
break 'autonomous_loop;
}
} // end 'autonomous_loop
// Update state based on exit code
let success = final_exit_code == 0;
let new_state = if success {
TaskState::Completed
} else {
TaskState::Failed
};
tracing::info!(
task_id = %task_id,
exit_code = final_exit_code,
success = success,
new_state = ?new_state,
"Claude process exited, updating task state"
);
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = new_state;
task.completed_at = Some(Instant::now());
if !success {
task.error = Some(format!("Process exited with code {}", final_exit_code));
}
}
}
// Execute completion action if task succeeded (skip in local_only mode unless auto_merge_local is enabled)
let completion_result = if success {
if local_only {
if auto_merge_local {
// In local_only mode with auto_merge_local enabled, merge locally
tracing::info!(
task_id = %task_id,
"Local-only mode with auto_merge_local - executing local merge"
);
self.execute_completion_action(
task_id,
&task_name,
&working_dir,
"merge", // Use merge action (not pr)
target_repo_path.as_deref(),
target_branch.as_deref(),
).await
} else {
tracing::info!(
task_id = %task_id,
"Skipping completion action - contract is in local_only mode"
);
Ok(None)
}
} else if let Some(ref action) = completion_action {
if action != "none" {
self.execute_completion_action(
task_id,
&task_name,
&working_dir,
action,
target_repo_path.as_deref(),
target_branch.as_deref(),
).await
} else {
Ok(None)
}
} else {
Ok(None)
}
} else {
Ok(None)
};
// Log completion action result
match &completion_result {
Ok(Some(pr_url)) => {
tracing::info!(task_id = %task_id, pr_url = %pr_url, "Completion action created PR");
}
Ok(None) => {}
Err(e) => {
tracing::warn!(task_id = %task_id, error = %e, "Completion action failed (task still marked as done)");
}
}
// If this task needs to merge to supervisor (cross-daemon case), generate and send patch
let merge_to_supervisor = {
let tasks = self.tasks.read().await;
tasks.get(&task_id).and_then(|t| t.merge_to_supervisor_task_id)
};
if let Some(supervisor_task_id) = merge_to_supervisor {
if success {
tracing::info!(
task_id = %task_id,
supervisor_task_id = %supervisor_task_id,
"Task completed on cross-daemon, generating patch to merge to supervisor"
);
// Get base SHA from the worktree's initial commit or parent
match crate::daemon::storage::get_parent_sha(&working_dir).await {
Ok(base_sha) => {
// Generate patch
match crate::daemon::storage::create_patch(&working_dir, &base_sha).await {
Ok((patch_bytes, files_count)) => {
// Base64 encode the patch
let patch_data = base64::Engine::encode(
&base64::engine::general_purpose::STANDARD,
&patch_bytes,
);
tracing::info!(
task_id = %task_id,
supervisor_task_id = %supervisor_task_id,
files_count = files_count,
patch_size = patch_bytes.len(),
"Sending patch to supervisor"
);
// Send MergePatchToSupervisor message to server
let msg = DaemonMessage::MergePatchToSupervisor {
task_id,
supervisor_task_id,
patch_data,
base_sha,
};
let _ = self.ws_tx.send(msg).await;
let output_msg = DaemonMessage::task_output(
task_id,
format!("Sent {} file(s) to supervisor for merge\n", files_count),
false,
);
let _ = self.ws_tx.send(output_msg).await;
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
error = %e,
"Failed to create patch for supervisor merge"
);
}
}
}
Err(e) => {
tracing::warn!(
task_id = %task_id,
error = %e,
"Failed to get base SHA for supervisor merge"
);
}
}
}
}
// Notify server - but NOT for supervisors which should never complete
if is_supervisor {
tracing::info!(
task_id = %task_id,
exit_code = final_exit_code,
"Supervisor Claude process exited - NOT marking as complete"
);
// Update local state to reflect it's paused/waiting for input
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Running; // Keep it as running, not completed
task.completed_at = None;
}
}
// Send a status message to let the frontend know supervisor is ready for more input
let msg = DaemonMessage::task_output(
task_id,
"\n[Supervisor ready for next instruction]\n".to_string(),
false,
);
let _ = self.ws_tx.send(msg).await;
} else {
// Create completion patch before notifying server
if let Err(e) = self.create_completion_patch(task_id, &working_dir).await {
tracing::debug!(task_id = %task_id, error = %e, "No completion patch created");
}
let error = if success {
None
} else {
Some(format!("Exit code: {}", final_exit_code))
};
tracing::info!(task_id = %task_id, success = success, "Notifying server of task completion");
let msg = DaemonMessage::task_complete(task_id, success, error);
let _ = self.ws_tx.send(msg).await;
// Remove completed task from local database (no longer needs crash recovery)
self.remove_task_from_local_db(task_id);
}
// Note: Worktrees are kept until explicitly deleted (per user preference)
// This allows inspection, PR creation, etc.
tracing::info!(task_id = %task_id, "=== RUN_TASK END ===");
Ok(())
}
/// Execute the completion action for a task.
async fn execute_completion_action(
&self,
task_id: Uuid,
task_name: &str,
worktree_path: &std::path::Path,
action: &str,
target_repo_path: Option<&str>,
target_branch: Option<&str>,
) -> Result<Option<String>, String> {
// For PR action, we can use the worktree's origin directly if target_repo_path is not set
let target_repo = match target_repo_path {
Some(path) => Some(crate::daemon::worktree::expand_tilde(path)),
None => {
if action == "pr" || action == "branch" {
// For PR/branch action without target_repo, use origin directly
None
} else {
tracing::warn!(task_id = %task_id, "No target_repo_path configured, skipping completion action");
return Ok(None);
}
}
};
// Validate target_repo exists if provided
if let Some(ref repo) = target_repo {
if !repo.exists() {
return Err(format!("Target repo not found: {} (expanded from {:?})", repo.display(), target_repo_path));
}
}
// Get the branch name: makima/{task-name-with-dashes}-{short-id}
let branch_name = format!(
"makima/{}-{}",
crate::daemon::worktree::sanitize_name(task_name),
crate::daemon::worktree::short_uuid(task_id)
);
// Determine target branch - use provided value or detect default branch
let target_branch = match target_branch {
Some(branch) => branch.to_string(),
None => {
// Detect default branch from target_repo if available, otherwise from worktree
let detect_path = target_repo.as_ref().map(|p| p.as_path()).unwrap_or(worktree_path);
self.worktree_manager
.detect_default_branch(detect_path)
.await
.unwrap_or_else(|_| "master".to_string())
}
};
let msg = DaemonMessage::task_output(
task_id,
format!("Executing completion action: {}...\n", action),
false,
);
let _ = self.ws_tx.send(msg).await;
match action {
"branch" => {
match target_repo {
Some(target_repo) => {
// Push branch to local target repo
self.worktree_manager
.push_to_target_repo(worktree_path, &target_repo, &branch_name, task_name)
.await
.map_err(|e| e.to_string())?;
let msg = DaemonMessage::task_output(
task_id,
format!("Branch '{}' pushed to {}\n", branch_name, target_repo.display()),
false,
);
let _ = self.ws_tx.send(msg).await;
}
None => {
// Push branch to origin (GitHub)
self.worktree_manager
.push_branch_to_origin(worktree_path, &branch_name, task_name)
.await
.map_err(|e| e.to_string())?;
let msg = DaemonMessage::task_output(
task_id,
format!("Branch '{}' pushed to origin\n", branch_name),
false,
);
let _ = self.ws_tx.send(msg).await;
}
}
Ok(None)
}
"merge" => {
let target_repo = target_repo.ok_or_else(|| "No target_repo_path configured for merge action".to_string())?;
// Push and merge into target branch
let commit_sha = self.worktree_manager
.merge_to_target(worktree_path, &target_repo, &branch_name, &target_branch, task_name)
.await
.map_err(|e| e.to_string())?;
let msg = DaemonMessage::task_output(
task_id,
format!("Branch merged into {} (commit: {})\n", target_branch, commit_sha),
false,
);
let _ = self.ws_tx.send(msg).await;
Ok(None)
}
"pr" => {
// Push and create PR
// For PR, we can use target_repo if provided, or create PR directly from worktree
let title = task_name.to_string();
let body = format!(
"Automated PR from makima task.\n\nTask ID: `{}`",
task_id
);
let pr_url = self.worktree_manager
.create_pull_request(
worktree_path,
target_repo.as_deref(),
&branch_name,
&target_branch,
&title,
&body,
)
.await
.map_err(|e| e.to_string())?;
let msg = DaemonMessage::task_output(
task_id,
format!("Pull request created: {}\n", pr_url),
false,
);
let _ = self.ws_tx.send(msg).await;
Ok(Some(pr_url))
}
_ => {
tracing::warn!(task_id = %task_id, action = %action, "Unknown completion action");
Ok(None)
}
}
}
/// Find worktree path for a task ID.
/// First checks in-memory tasks, then scans the worktrees directory.
async fn find_worktree_for_task(&self, task_id: Uuid) -> Result<PathBuf, String> {
// First try to get from in-memory tasks
{
let tasks = self.tasks.read().await;
if let Some(task) = tasks.get(&task_id) {
if let Some(ref worktree) = task.worktree {
return Ok(worktree.path.clone());
}
}
}
// Task not in memory - scan worktrees directory for matching task ID
let short_id = &task_id.to_string()[..8];
let worktrees_dir = self.worktree_manager.base_dir();
if let Ok(mut entries) = tokio::fs::read_dir(worktrees_dir).await {
while let Ok(Some(entry)) = entries.next_entry().await {
let name = entry.file_name();
let name_str = name.to_string_lossy();
if name_str.starts_with(short_id) {
let path = entry.path();
// Verify it's a valid git directory
if path.join(".git").exists() {
tracing::info!(
task_id = %task_id,
worktree_path = %path.display(),
"Found worktree by scanning directory"
);
return Ok(path);
}
}
}
}
Err(format!(
"No worktree found for task {}. The worktree may have been cleaned up.",
task_id
))
}
async fn update_state(&self, task_id: Uuid, state: TaskState) {
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = state;
}
}
async fn send_status_change(&self, task_id: Uuid, old_status: &str, new_status: &str) {
let msg = DaemonMessage::task_status_change(task_id, old_status, new_status);
let _ = self.ws_tx.send(msg).await;
}
/// Mark task as failed.
async fn mark_failed(&self, task_id: Uuid, error: &str) {
{
let mut tasks = self.tasks.write().await;
if let Some(task) = tasks.get_mut(&task_id) {
task.state = TaskState::Failed;
task.error = Some(error.to_string());
task.completed_at = Some(Instant::now());
}
}
// Notify server
let msg = DaemonMessage::task_complete(task_id, false, Some(error.to_string()));
let _ = self.ws_tx.send(msg).await;
// Remove failed task from local database
self.remove_task_from_local_db(task_id);
}
/// Apply inherited git config to a worktree directory.
async fn apply_git_config(&self, worktree_path: &std::path::Path) {
let email = self.git_user_email.read().await.clone();
let name = self.git_user_name.read().await.clone();
if email.is_none() && name.is_none() {
return; // No inherited config to apply
}
if let Some(email) = email {
let result = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["config", "user.email", &email])
.output()
.await;
match result {
Ok(output) if output.status.success() => {
tracing::debug!(email = %email, path = ?worktree_path, "Applied git user.email to worktree");
}
Ok(output) => {
tracing::warn!(
path = ?worktree_path,
stderr = %String::from_utf8_lossy(&output.stderr),
"Failed to set git user.email in worktree"
);
}
Err(e) => {
tracing::warn!(error = %e, "Failed to run git config user.email");
}
}
}
if let Some(name) = name {
let result = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["config", "user.name", &name])
.output()
.await;
match result {
Ok(output) if output.status.success() => {
tracing::debug!(name = %name, path = ?worktree_path, "Applied git user.name to worktree");
}
Ok(output) => {
tracing::warn!(
path = ?worktree_path,
stderr = %String::from_utf8_lossy(&output.stderr),
"Failed to set git user.name in worktree"
);
}
Err(e) => {
tracing::warn!(error = %e, "Failed to run git config user.name");
}
}
}
}
/// Create an ephemeral patch of all changes (committed + uncommitted) since the
/// merge-base with main/master and send to the server.
/// Stages and commits any uncommitted changes, then diffs against the merge-base.
/// Returns the number of files changed on success, or an error message if nothing to patch.
async fn create_ephemeral_patch(
&self,
task_id: Uuid,
worktree_path: &std::path::Path,
) -> Result<i32, String> {
if !self.checkpoint_patches.enabled {
return Err("Checkpoint patches disabled".into());
}
// 1. Find merge-base with main/master (the fork point)
let base_sha = storage::get_merge_base_sha(worktree_path)
.await
.map_err(|e| format!("Failed to get merge-base: {}", e))?;
// 2. Stage and commit any uncommitted changes so they're included in the diff
let _ = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["add", "-A"])
.output()
.await;
// Check if there are staged changes to commit
let staged_check = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["diff", "--cached", "--quiet"])
.output()
.await;
if let Ok(output) = staged_check {
if !output.status.success() {
// There are staged changes - commit them
let _ = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["commit", "-m", "WIP: heartbeat checkpoint"])
.output()
.await;
}
}
// 3. Create patch (diff merge-base..HEAD captures all work)
match storage::create_patch(worktree_path, &base_sha).await {
Ok((compressed_patch, patch_files_count)) => {
// Check size limit
if compressed_patch.len() > self.checkpoint_patches.max_patch_size_bytes {
tracing::warn!(
task_id = %task_id,
patch_size = compressed_patch.len(),
max_size = self.checkpoint_patches.max_patch_size_bytes,
"Patch exceeds size limit"
);
return Err("Patch exceeds size limit".into());
}
// Encode as base64 for JSON transport
let patch_data = base64::engine::general_purpose::STANDARD.encode(&compressed_patch);
tracing::debug!(
task_id = %task_id,
base_sha = %base_sha,
patch_size = compressed_patch.len(),
files_count = patch_files_count,
"Created ephemeral patch"
);
// Send CheckpointCreated message to server (patch-only, no commit)
let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: true,
commit_sha: None,
branch_name: None,
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: None,
message: format!("Ephemeral patch - {}", timestamp),
patch_data: Some(patch_data),
patch_base_sha: Some(base_sha),
patch_files_count: Some(patch_files_count as i32),
};
let _ = self.ws_tx.send(msg).await;
Ok(patch_files_count as i32)
}
Err(e) => {
Err(format!("Failed to create patch: {}", e))
}
}
}
/// Create a completion patch capturing all changes (committed + uncommitted) since
/// the merge-base with main/master. Sent before TaskComplete so the server always
/// has a recoverable patch. All errors are non-fatal (logged, not propagated).
async fn create_completion_patch(
&self,
task_id: Uuid,
worktree_path: &std::path::Path,
) -> Result<(), String> {
// 1. Stage all changes
let _ = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["add", "-A"])
.output()
.await;
// 2. Commit any staged changes so HEAD contains everything
let staged_check = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["diff", "--cached", "--quiet"])
.output()
.await;
if let Ok(output) = staged_check {
if !output.status.success() {
let _ = tokio::process::Command::new("git")
.current_dir(worktree_path)
.args(["commit", "-m", "WIP: task completion checkpoint"])
.output()
.await;
}
}
// 3. Find merge-base with main/master
let base_sha = storage::get_merge_base_sha(worktree_path)
.await
.map_err(|e| format!("Failed to get merge-base: {}", e))?;
// 4. Create patch (diff merge-base..HEAD)
let (compressed_patch, patch_files_count) = storage::create_patch(worktree_path, &base_sha)
.await
.map_err(|e| format!("Failed to create patch: {}", e))?;
// 5. Check size limit
if compressed_patch.len() > self.checkpoint_patches.max_patch_size_bytes {
return Err(format!(
"Patch too large: {} bytes (max: {})",
compressed_patch.len(),
self.checkpoint_patches.max_patch_size_bytes
));
}
// 6. Send to server
let patch_data = base64::engine::general_purpose::STANDARD.encode(&compressed_patch);
let timestamp = chrono::Utc::now().format("%Y-%m-%d %H:%M:%S UTC");
let msg = DaemonMessage::CheckpointCreated {
task_id,
success: true,
commit_sha: None,
branch_name: None,
checkpoint_number: None,
files_changed: None,
lines_added: None,
lines_removed: None,
error: None,
message: format!("Completion patch - {}", timestamp),
patch_data: Some(patch_data),
patch_base_sha: Some(base_sha),
patch_files_count: Some(patch_files_count as i32),
};
let _ = self.ws_tx.send(msg).await;
tracing::info!(
task_id = %task_id,
files_count = patch_files_count,
"Created completion patch"
);
Ok(())
}
}
impl Clone for TaskManagerInner {
fn clone(&self) -> Self {
Self {
worktree_manager: self.worktree_manager.clone(),
process_manager: self.process_manager.clone(),
temp_manager: self.temp_manager.clone(),
tasks: self.tasks.clone(),
ws_tx: self.ws_tx.clone(),
task_inputs: self.task_inputs.clone(),
active_pids: self.active_pids.clone(),
git_user_email: self.git_user_email.clone(),
git_user_name: self.git_user_name.clone(),
api_url: self.api_url.clone(),
api_key: self.api_key.clone(),
heartbeat_commit_interval_secs: self.heartbeat_commit_interval_secs,
contract_task_counts: self.contract_task_counts.clone(),
checkpoint_patches: self.checkpoint_patches.clone(),
local_db: self.local_db.clone(),
}
}
}
|