tmai 1.5.0

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

use axum::{
    extract::{Path, State},
    http::StatusCode,
    response::Json,
};
use serde::{Deserialize, Serialize};
use std::sync::Arc;

use tmai_core::api::{AgentSnapshot, ApiError, TmaiCore};

/// Helper to create JSON error responses
fn json_error(status: StatusCode, message: &str) -> (StatusCode, Json<serde_json::Value>) {
    (status, Json(serde_json::json!({"error": message})))
}

/// Shell-quote a string for safe embedding in tmux send-keys commands.
/// Wraps in single quotes and escapes any embedded single quotes.
/// Control characters (bytes < 0x20 except \n) are stripped before quoting.
fn shell_quote(s: &str) -> String {
    // Strip control characters (bytes < 0x20) except newline (\n = 0x0A)
    let sanitized: String = s
        .chars()
        .filter(|&c| c as u32 >= 0x20 || c == '\n')
        .collect();
    // If it contains no shell-special characters, return as-is
    if sanitized
        .bytes()
        .all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_' || b == b'.' || b == b'/')
    {
        return sanitized;
    }
    // Wrap in single quotes, escaping embedded single quotes: ' → '\''
    format!("'{}'", sanitized.replace('\'', "'\\''"))
}

/// Check whether a canonical path falls within the user's HOME directory
/// or any registered project directory. Returns true if allowed.
fn is_path_within_allowed_scope(path: &std::path::Path, core: Option<&TmaiCore>) -> bool {
    let canonical = match path.canonicalize() {
        Ok(p) => p,
        // If the path doesn't exist yet, try canonicalizing the parent
        Err(_) => {
            if let Some(parent) = path.parent() {
                match parent.canonicalize() {
                    Ok(p) => p.join(path.file_name().unwrap_or_default()),
                    Err(_) => return false,
                }
            } else {
                return false;
            }
        }
    };

    // Allow anything under HOME
    if let Some(home) = dirs::home_dir() {
        if let Ok(home_canonical) = home.canonicalize() {
            if canonical.starts_with(&home_canonical) {
                return true;
            }
        }
    }

    // Allow anything under registered project directories
    if let Some(core) = core {
        for project in core.list_projects() {
            let project_path = std::path::Path::new(&project);
            if let Ok(proj_canonical) = project_path.canonicalize() {
                if canonical.starts_with(&proj_canonical) {
                    return true;
                }
            }
        }
    }

    false
}

/// Convert ApiError to HTTP status + JSON error
fn api_error_to_http(err: ApiError) -> (StatusCode, Json<serde_json::Value>) {
    let status = match &err {
        ApiError::AgentNotFound { .. } | ApiError::TeamNotFound { .. } => StatusCode::NOT_FOUND,
        ApiError::NoCommandSender | ApiError::CommandError(_) => StatusCode::INTERNAL_SERVER_ERROR,
        ApiError::VirtualAgent { .. } | ApiError::InvalidInput { .. } | ApiError::NoSelection => {
            StatusCode::BAD_REQUEST
        }
        ApiError::WorktreeError(e) => match e {
            tmai_core::worktree::WorktreeOpsError::NotFound(_) => StatusCode::NOT_FOUND,
            tmai_core::worktree::WorktreeOpsError::AlreadyExists(_)
            | tmai_core::worktree::WorktreeOpsError::InvalidName(_)
            | tmai_core::worktree::WorktreeOpsError::UncommittedChanges(_)
            | tmai_core::worktree::WorktreeOpsError::AgentStillRunning(_)
            | tmai_core::worktree::WorktreeOpsError::AgentPendingDetection(_) => {
                StatusCode::BAD_REQUEST
            }
            tmai_core::worktree::WorktreeOpsError::GitError(_) => StatusCode::INTERNAL_SERVER_ERROR,
        },
    };
    json_error(status, &err.to_string())
}

/// Text input request body
#[derive(Debug, Deserialize)]
pub struct TextInputRequest {
    pub text: String,
}

/// Special key request body
#[derive(Debug, Deserialize)]
pub struct KeyRequest {
    pub key: String,
}

/// Passthrough request body — sends raw input to an agent's terminal
#[derive(Debug, Deserialize)]
pub struct PassthroughRequest {
    /// For character input: the literal text to send
    #[serde(default)]
    pub chars: Option<String>,
    /// For special keys: tmux key name (e.g. "Enter", "Up", "C-c")
    #[serde(default)]
    pub key: Option<String>,
}

/// Prompt request body
#[derive(Debug, Deserialize)]
pub struct PromptRequest {
    pub prompt: String,
}

/// Per-agent auto-approve override request
#[derive(Debug, Deserialize)]
pub struct AutoApproveOverrideRequest {
    /// None = follow global, Some(true) = force enable, Some(false) = force disable
    pub enabled: Option<bool>,
}

/// Preview response
#[derive(Debug, Serialize)]
pub struct PreviewResponse {
    pub content: String,
    pub lines: usize,
    /// Terminal cursor column (0-indexed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor_x: Option<u32>,
    /// Terminal cursor row (0-indexed, absolute within full capture output)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor_y: Option<u32>,
}

/// Summary of a task for API response
#[derive(Debug, Serialize)]
pub struct TaskSummaryResponse {
    pub id: String,
    pub subject: String,
    pub status: String,
}

/// Team overview information for API response
#[derive(Debug, Serialize)]
pub(crate) struct TeamInfoResponse {
    name: String,
    description: Option<String>,
    task_summary: TaskSummaryOverview,
    members: Vec<TeamMemberResponse>,
    /// Worktree names used by this team's members
    #[serde(skip_serializing_if = "Vec::is_empty")]
    worktree_names: Vec<String>,
}

/// Task progress summary for API response
#[derive(Debug, Serialize)]
pub(crate) struct TaskSummaryOverview {
    total: usize,
    completed: usize,
    in_progress: usize,
    pending: usize,
}

/// Team member information for API response
#[derive(Debug, Serialize)]
pub(crate) struct TeamMemberResponse {
    name: String,
    agent_type: Option<String>,
    is_lead: bool,
    pane_target: Option<String>,
    current_task: Option<TaskSummaryResponse>,
    /// Agent definition description (from `.claude/agents/*.md`)
    #[serde(skip_serializing_if = "Option::is_none")]
    description: Option<String>,
    /// Agent definition model (from `.claude/agents/*.md`)
    #[serde(skip_serializing_if = "Option::is_none")]
    model: Option<String>,
}

/// Detailed team task information for API response
#[derive(Debug, Serialize)]
pub(crate) struct TeamTaskResponse {
    id: String,
    subject: String,
    description: String,
    active_form: Option<String>,
    status: String,
    owner: Option<String>,
    blocks: Vec<String>,
    blocked_by: Vec<String>,
}

/// Build a TeamInfoResponse from a TeamSnapshot
///
/// Shared helper used by both the REST API and SSE events.
pub(super) fn build_team_info(
    snapshot: &tmai_core::state::TeamSnapshot,
    app_state: &tmai_core::state::AppState,
) -> TeamInfoResponse {
    let total = snapshot.task_total;
    let completed = snapshot.task_done;
    let in_progress = snapshot.task_in_progress;
    let pending = snapshot.task_pending;

    let members: Vec<TeamMemberResponse> = snapshot
        .config
        .members
        .iter()
        .map(|member| {
            let pane_target = snapshot.member_panes.get(&member.name).cloned();

            // Find this member's current task from agent info
            let current_task = pane_target
                .as_ref()
                .and_then(|target| app_state.agents.get(target))
                .and_then(|agent| agent.team_info.as_ref())
                .and_then(|ti| ti.current_task.as_ref())
                .map(|t| TaskSummaryResponse {
                    id: t.id.clone(),
                    subject: t.subject.clone(),
                    status: t.status.to_string(),
                });

            // Check if this member is the lead (first member is typically lead)
            let is_lead = snapshot
                .config
                .members
                .first()
                .map(|first| first.name == member.name)
                .unwrap_or(false);

            // Look up agent definition for description/model
            let agent_def = app_state
                .agent_definitions
                .iter()
                .find(|d| d.name == member.name);

            TeamMemberResponse {
                name: member.name.clone(),
                agent_type: member.agent_type.clone(),
                is_lead,
                pane_target,
                current_task,
                description: agent_def.and_then(|d| d.description.clone()),
                model: agent_def.and_then(|d| d.model.clone()),
            }
        })
        .collect();

    TeamInfoResponse {
        name: snapshot.config.team_name.clone(),
        description: snapshot.config.description.clone(),
        task_summary: TaskSummaryOverview {
            total,
            completed,
            in_progress,
            pending,
        },
        members,
        worktree_names: snapshot.worktree_names.clone(),
    }
}

/// Selection request body
#[derive(Debug, Deserialize)]
pub struct SelectRequest {
    pub choice: usize,
}

/// Submit multi-select request body
#[derive(Debug, Deserialize)]
pub struct SubmitRequest {
    #[serde(default)]
    pub selected_choices: Vec<usize>,
}

/// Get all agents
pub async fn get_agents(State(core): State<Arc<TmaiCore>>) -> Json<Vec<AgentSnapshot>> {
    Json(core.list_agents())
}

/// Approve an agent action (send approval keys)
pub async fn approve_agent(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: approve agent_id={}", id);
    core.approve(&id)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: approve failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Select a choice for UserQuestion
pub async fn select_choice(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<SelectRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: select choice={} agent_id={}", req.choice, id);
    core.select_choice(&id, req.choice)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: select failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Submit multi-select choices
pub async fn submit_selection(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    body: Option<Json<SubmitRequest>>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: submit agent_id={}", id);
    let selected = body.map(|b| b.0.selected_choices).unwrap_or_default();
    core.submit_selection(&id, &selected)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: submit failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Send text input to an agent
pub async fn send_text(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<TextInputRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: input agent_id={}", id);
    core.send_text(&id, &req.text)
        .await
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: input failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Send a prompt to an agent with status-aware behavior (queue if Processing)
pub async fn send_prompt(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<PromptRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: send_prompt agent_id={}", id);
    core.send_prompt(&id, &req.prompt)
        .await
        .map(|result| Json(serde_json::json!({"status": "ok", "action": result.action, "queue_size": result.queue_size})))
        .map_err(|e| {
            tracing::warn!("API: send_prompt failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Send a special key to an agent
pub async fn send_key(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<KeyRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: send_key key={} agent_id={}", req.key, id);
    core.send_key(&id, &req.key)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: send_key failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// PUT /api/agents/{id}/auto-approve — set per-agent auto-approve override
///
/// Body: `{"enabled": true}` to force enable, `{"enabled": false}` to force disable,
/// `{"enabled": null}` to follow global setting.
pub async fn set_auto_approve(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<AutoApproveOverrideRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    core.set_auto_approve_override(&id, req.enabled)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(api_error_to_http)
}

/// POST /api/agents/{id}/passthrough — send raw input to agent terminal
///
/// Uses tmux send-keys directly for reliable passthrough. Falls back to
/// CommandSender for non-tmux agents.
/// Accepts either `chars` (literal text) or `key` (tmux key name).
#[allow(deprecated)]
pub async fn passthrough_input(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
    Json(req): Json<PassthroughRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Resolve the user-supplied ID to internal key, then find tmux target
    let tmux_target = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        tmai_core::api::TmaiCore::resolve_agent_key_in_state(&state, &id)
            .ok()
            .and_then(|key| state.agents.get(&key).map(|a| a.target.clone()))
            .filter(|t| !t.starts_with("hook:") && !t.starts_with("discovered:"))
    };

    // Use CommandSender (which goes through RuntimeAdapter) for all agents.
    // This handles IPC -> tmux send-keys -> PTY inject fallback chain automatically.
    let send_target = tmux_target.as_deref().unwrap_or(&id);
    let cmd = core
        .raw_command_sender()
        .ok_or_else(|| json_error(StatusCode::INTERNAL_SERVER_ERROR, "No command sender"))?;
    if let Some(ref chars) = req.chars {
        cmd.send_keys_literal(send_target, chars)
            .map_err(|e| json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
    }
    if let Some(ref key) = req.key {
        cmd.send_keys(send_target, key)
            .map_err(|e| json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
    }

    Ok(Json(serde_json::json!({"status": "ok"})))
}

/// Kill an agent (terminate PTY session or tmux pane)
pub async fn kill_agent(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    tracing::info!("API: kill agent_id={}", id);
    core.kill_pane(&id)
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| {
            tracing::warn!("API: kill failed agent_id={}: {}", id, e);
            api_error_to_http(e)
        })
}

/// Get preview content (pane capture) for an agent.
///
/// Returns ANSI-colored output when capture-pane is available (tmux runtime),
/// falling back to plain text from last_content or activity log.
#[allow(deprecated)]
pub async fn get_preview(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
) -> Result<Json<PreviewResponse>, StatusCode> {
    let show_cursor = core.settings().web.show_cursor;

    // Resolve the user-supplied ID to internal key
    let resolved_key = {
        let state = core.raw_state().read();
        tmai_core::api::TmaiCore::resolve_agent_key_in_state(&state, &id).ok()
    };

    // Look up agent target for capture-pane (id may differ from tmux target)
    let (agent_target, agent_content, agent_cursor) = {
        let state = core.raw_state().read();
        match resolved_key.as_deref().and_then(|k| state.agents.get(k)) {
            Some(a) => (
                Some(a.target.clone()),
                Some(a.last_content.clone()),
                (a.cursor_x, a.cursor_y),
            ),
            None => (None, None, (None, None)),
        }
    };

    // Try capture-pane with ANSI colors first (via tmux target).
    // Query cursor BEFORE capture to reduce race conditions: if new content
    // appears between the two calls, the cursor position still references a
    // valid line in the (larger) captured output.
    if let Some(ref target) = agent_target {
        if let Some(cmd) = core.raw_command_sender() {
            // Pre-query cursor position
            let pre_cursor = if show_cursor {
                let cursor_result = cmd.runtime().get_cursor_position(target);
                tracing::debug!("cursor query for {}: {:?}", target, cursor_result);
                cursor_result.ok().flatten()
            } else {
                None
            };

            if let Ok(content) = cmd.runtime().capture_pane_full(target) {
                if !content.trim().is_empty() {
                    let lines = content.lines().count();
                    // Clamp cursor_y to captured content bounds
                    let (cursor_x, cursor_y) = match pre_cursor {
                        Some((x, y)) if lines > 0 => {
                            let clamped_y = y.min((lines - 1) as u32);
                            (Some(x), Some(clamped_y))
                        }
                        _ => (None, None),
                    };
                    return Ok(Json(PreviewResponse {
                        content,
                        lines,
                        cursor_x,
                        cursor_y,
                    }));
                }
            }
        }
    }

    // Fallback: plain text from last_content (use cached cursor from IPC)
    if let Some(content) = agent_content.filter(|c| !c.trim().is_empty()) {
        let lines = content.lines().count();
        return Ok(Json(PreviewResponse {
            content,
            lines,
            cursor_x: if show_cursor { agent_cursor.0 } else { None },
            cursor_y: if show_cursor { agent_cursor.1 } else { None },
        }));
    }

    // Agent exists check
    if core.get_agent(&id).is_err() {
        return Err(StatusCode::NOT_FOUND);
    }

    // Fallback: try capture_pane directly with the id as target
    let cmd = core
        .raw_command_sender()
        .ok_or(StatusCode::INTERNAL_SERVER_ERROR)?;

    match cmd.runtime().capture_pane(&id) {
        Ok(content) => {
            let display_content = if content.trim().is_empty() {
                // Fallback: try activity log from hooks via pane_id mapping
                let pane_id = {
                    let state = core.raw_state().read();
                    state.target_to_pane_id.get(&id).cloned()
                };
                let hook_reg = core.hook_registry().read();
                let activity_content = pane_id
                    .as_ref()
                    .and_then(|pid| hook_reg.get(pid))
                    .filter(|hs| !hs.activity_log.is_empty())
                    .map(|hs| tmai_core::hooks::handler::format_activity_log(&hs.activity_log));
                drop(hook_reg);

                activity_content
                    .filter(|s| !s.is_empty())
                    .unwrap_or_else(|| "(waiting for agent activity...)".to_string())
            } else {
                content
            };
            let lines = display_content.lines().count();
            Ok(Json(PreviewResponse {
                content: display_content,
                lines,
                cursor_x: None,
                cursor_y: None,
            }))
        }
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

// =========================================================
// Transcript
// =========================================================

/// Response for GET /api/agents/{id}/transcript
#[derive(Debug, Serialize)]
pub struct TranscriptResponse {
    pub records: Vec<tmai_core::transcript::TranscriptRecord>,
}

/// Get transcript records for an agent (hybrid scrollback preview).
///
/// Returns parsed JSONL conversation records for rendering above
/// the live capture-pane output.
pub async fn get_transcript(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
) -> Result<Json<TranscriptResponse>, StatusCode> {
    match core.get_transcript(&id) {
        Ok(records) => Ok(Json(TranscriptResponse { records })),
        Err(tmai_core::api::ApiError::AgentNotFound { .. }) => Err(StatusCode::NOT_FOUND),
        Err(_) => Err(StatusCode::INTERNAL_SERVER_ERROR),
    }
}

/// Get all teams with their task summaries and member info
#[allow(deprecated)]
pub async fn get_teams(State(core): State<Arc<TmaiCore>>) -> Json<Vec<TeamInfoResponse>> {
    let state = core.raw_state().read();

    let teams: Vec<TeamInfoResponse> = state
        .teams
        .values()
        .map(|snapshot| build_team_info(snapshot, &state))
        .collect();

    Json(teams)
}

/// Validate team name to prevent path traversal
///
/// Only allows alphanumeric characters, `-`, and `_`.
fn is_valid_team_name(name: &str) -> bool {
    !name.is_empty()
        && name
            .chars()
            .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
}

/// Get tasks for a specific team
#[allow(deprecated)]
pub async fn get_team_tasks(
    State(core): State<Arc<TmaiCore>>,
    Path(name): Path<String>,
) -> Result<Json<Vec<TeamTaskResponse>>, (StatusCode, Json<serde_json::Value>)> {
    // Validate team name to prevent path traversal
    if !is_valid_team_name(&name) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid team name"));
    }

    let state = core.raw_state().read();

    let snapshot = state
        .teams
        .get(&name)
        .ok_or_else(|| json_error(StatusCode::NOT_FOUND, "Team not found"))?;

    let tasks: Vec<TeamTaskResponse> = snapshot
        .tasks
        .iter()
        .map(|task| TeamTaskResponse {
            id: task.id.clone(),
            subject: task.subject.clone(),
            description: task.description.clone(),
            active_form: task.active_form.clone(),
            status: task.status.to_string(),
            owner: task.owner.clone(),
            blocks: task.blocks.clone(),
            blocked_by: task.blocked_by.clone(),
        })
        .collect();

    Ok(Json(tasks))
}

// =========================================================
// Worktree endpoints
// =========================================================

/// Default agent type for launch
fn default_agent_type() -> String {
    "claude".to_string()
}

/// Get all worktrees
pub async fn get_worktrees(
    State(core): State<Arc<TmaiCore>>,
) -> Json<Vec<tmai_core::api::WorktreeSnapshot>> {
    Json(core.list_worktrees())
}

/// Worktree delete request body (uses repo_path for unambiguous identification)
#[derive(Debug, Deserialize)]
pub struct WorktreeDeleteRequestBody {
    pub repo_path: String,
    pub worktree_name: String,
    #[serde(default)]
    pub force: bool,
}

/// Delete a worktree
pub async fn delete_worktree(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<WorktreeDeleteRequestBody>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate worktree name to prevent path traversal
    if !tmai_core::git::is_valid_worktree_name(&req.worktree_name) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid worktree name"));
    }

    // Verify the repo_path is a valid directory
    let repo_dir = strip_git_suffix(&req.repo_path);
    if !std::path::Path::new(repo_dir).is_dir() {
        return Err(json_error(StatusCode::NOT_FOUND, "Repository not found"));
    }

    // Verify repo_path is among known projects or worktrees
    {
        let repo_canonical = std::path::Path::new(repo_dir)
            .canonicalize()
            .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid repository path"))?;
        let projects = core.list_projects();
        #[allow(deprecated)]
        let worktree_paths: Vec<String> = {
            let state = core.raw_state().read();
            state.agents.values().map(|a| a.cwd.clone()).collect()
        };
        let is_known = projects.iter().chain(worktree_paths.iter()).any(|p| {
            std::path::Path::new(tmai_core::git::strip_git_suffix(p))
                .canonicalize()
                .map(|c| c == repo_canonical)
                .unwrap_or(false)
        });
        if !is_known {
            return Err(json_error(
                StatusCode::FORBIDDEN,
                "Repository path is not a known project or worktree",
            ));
        }
    }

    let del_req = tmai_core::worktree::WorktreeDeleteRequest {
        repo_path: strip_git_suffix(&req.repo_path).to_string(),
        worktree_name: req.worktree_name,
        force: req.force,
    };

    core.delete_worktree(&del_req)
        .await
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(api_error_to_http)
}

/// Worktree move request body — move an existing branch into a worktree
#[derive(Debug, Deserialize)]
pub struct WorktreeMoveRequestBody {
    pub repo_path: String,
    pub branch_name: String,
    #[serde(default)]
    pub dir_name: Option<String>,
    pub default_branch: String,
}

/// Move a branch into a worktree
pub async fn move_to_worktree(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<WorktreeMoveRequestBody>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate branch name
    if !tmai_core::git::is_valid_worktree_name(&req.branch_name) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid branch name"));
    }
    if !tmai_core::git::is_safe_git_ref(&req.default_branch) {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            "Invalid default branch name",
        ));
    }

    // Verify the repo_path is a valid directory
    let repo_dir = strip_git_suffix(&req.repo_path);
    if !std::path::Path::new(repo_dir).is_dir() {
        return Err(json_error(StatusCode::NOT_FOUND, "Repository not found"));
    }

    // Verify repo_path is among known projects
    {
        let repo_canonical = std::path::Path::new(repo_dir)
            .canonicalize()
            .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Invalid repository path"))?;
        let projects = core.list_projects();
        #[allow(deprecated)]
        let worktree_paths: Vec<String> = {
            let state = core.raw_state().read();
            state.agents.values().map(|a| a.cwd.clone()).collect()
        };
        let is_known = projects.iter().chain(worktree_paths.iter()).any(|p| {
            std::path::Path::new(tmai_core::git::strip_git_suffix(p))
                .canonicalize()
                .map(|c| c == repo_canonical)
                .unwrap_or(false)
        });
        if !is_known {
            return Err(json_error(
                StatusCode::FORBIDDEN,
                "Repository path is not a known project or worktree",
            ));
        }
    }

    let move_req = tmai_core::worktree::WorktreeMoveRequest {
        repo_path: strip_git_suffix(&req.repo_path).to_string(),
        branch_name: req.branch_name,
        dir_name: req.dir_name,
        default_branch: req.default_branch,
    };

    core.move_to_worktree(&move_req)
        .await
        .map(|result| {
            Json(serde_json::json!({
                "status": "ok",
                "path": result.path,
                "branch": result.branch,
            }))
        })
        .map_err(api_error_to_http)
}

/// Worktree launch request body (uses repo_path for unambiguous identification)
#[derive(Debug, Deserialize)]
pub struct WorktreeLaunchRequestBody {
    pub repo_path: String,
    pub worktree_name: String,
    #[serde(default = "default_agent_type")]
    pub agent_type: String,
    /// Optional initial prompt to pass as the first argument to the agent CLI.
    #[serde(default)]
    pub initial_prompt: Option<String>,
    /// Unused — kept for backward compatibility with older frontends.
    #[serde(default)]
    #[allow(dead_code)]
    pub session: Option<String>,
}

/// Launch an agent in a worktree.
///
/// Resolves the worktree path, then delegates to the same spawn pipeline
/// used by `/api/spawn` so it works in both tmux and standalone modes.
pub async fn launch_agent_in_worktree(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<WorktreeLaunchRequestBody>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate worktree name
    if !tmai_core::git::is_valid_worktree_name(&req.worktree_name) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid worktree name"));
    }

    // Find worktree path from state by repo_path + worktree_name
    let wt_path = {
        let worktrees = core.list_worktrees();
        worktrees
            .iter()
            .find(|wt| {
                (wt.repo_path == req.repo_path || strip_git_suffix(&wt.repo_path) == req.repo_path)
                    && wt.name == req.worktree_name
            })
            .map(|wt| wt.path.clone())
    };

    let wt_path = match wt_path {
        Some(p) => p,
        None => return Err(json_error(StatusCode::NOT_FOUND, "Worktree not found")),
    };

    // Map agent_type string to command name
    let command = match req.agent_type.as_str() {
        "claude" | "claude_code" => "claude",
        "codex" | "codex_cli" => "codex",
        "gemini" | "gemini_cli" => "gemini",
        "opencode" | "open_code" => "opencode",
        other => {
            return Err(json_error(
                StatusCode::BAD_REQUEST,
                &format!("Unknown agent type: {}", other),
            ))
        }
    };

    // Build args — pass initial prompt as first positional argument if provided
    let args = match req.initial_prompt {
        Some(ref prompt) if !prompt.is_empty() => vec![prompt.clone()],
        _ => vec![],
    };

    // Worktree already exists — just cd into it and launch the agent
    let spawn_req = SpawnRequest {
        command: command.to_string(),
        args,
        cwd: wt_path,
        rows: default_rows(),
        cols: default_cols(),
        force_pty: false,
    };

    let use_tmux = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        state.spawn_in_tmux
    };
    let tmux_avail = is_tmux_available();

    let result = if use_tmux && tmux_avail {
        spawn_in_tmux(&core, &spawn_req).await
    } else {
        spawn_in_pty(&core, &spawn_req).await
    };

    result.map(|Json(resp)| {
        Json(serde_json::json!({
            "status": "ok",
            "target": resp.session_id,
        }))
    })
}

/// Worktree diff request body
#[derive(Debug, Deserialize)]
pub struct WorktreeDiffRequestBody {
    pub worktree_path: String,
    #[serde(default = "default_base_branch")]
    pub base_branch: String,
}

/// Default base branch for diff
fn default_base_branch() -> String {
    "main".to_string()
}

/// Get diff for a worktree
pub async fn get_worktree_diff(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<WorktreeDiffRequestBody>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate base_branch
    if !tmai_core::git::is_safe_git_ref(&req.base_branch) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid base branch"));
    }

    // Verify the worktree_path belongs to a known worktree
    let known = core
        .list_worktrees()
        .iter()
        .any(|wt| wt.path == req.worktree_path);
    if !known {
        return Err(json_error(StatusCode::NOT_FOUND, "Worktree not found"));
    }

    match core
        .get_worktree_diff(&req.worktree_path, &req.base_branch)
        .await
    {
        Ok((diff, summary)) => {
            let summary_json = summary.map(|s| {
                serde_json::json!({
                    "files_changed": s.files_changed,
                    "insertions": s.insertions,
                    "deletions": s.deletions,
                })
            });
            Ok(Json(serde_json::json!({
                "diff": diff,
                "summary": summary_json,
            })))
        }
        Err(e) => Err(api_error_to_http(e)),
    }
}

// =========================================================
// Project management endpoints
// =========================================================

/// List registered project directories
pub async fn get_projects(State(core): State<Arc<TmaiCore>>) -> Json<Vec<String>> {
    Json(core.list_projects())
}

/// Add project request body
#[derive(Debug, Deserialize)]
pub struct AddProjectRequest {
    pub path: String,
}

/// Register a new project directory
pub async fn add_project(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<AddProjectRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    match core.add_project(&req.path) {
        Ok(()) => Ok(Json(serde_json::json!({"ok": true}))),
        Err(e) => Err(api_error_to_http(e)),
    }
}

/// Remove project request body
#[derive(Debug, Deserialize)]
pub struct RemoveProjectRequest {
    pub path: String,
}

/// Directory entry for the tree browser
#[derive(Debug, Serialize)]
pub struct DirEntry {
    pub name: String,
    pub path: String,
    pub is_git: bool,
}

/// List subdirectories at a given path for the directory tree browser.
/// Query param: ?path=/some/dir (defaults to home directory)
pub async fn list_directories(
    State(core): State<Arc<TmaiCore>>,
    axum::extract::Query(params): axum::extract::Query<std::collections::HashMap<String, String>>,
) -> Result<Json<Vec<DirEntry>>, (StatusCode, Json<serde_json::Value>)> {
    let home = dirs::home_dir().unwrap_or_default();
    let base = params
        .get("path")
        .filter(|p| !p.is_empty())
        .map(std::path::PathBuf::from)
        .unwrap_or(home);

    // Path traversal protection: must be within HOME or a registered project
    if !is_path_within_allowed_scope(&base, Some(&core)) {
        return Err(json_error(
            StatusCode::FORBIDDEN,
            "Path is outside allowed scope",
        ));
    }

    if !base.is_dir() {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Not a directory: {}", base.display()),
        ));
    }

    let mut entries = Vec::new();
    let Ok(read_dir) = std::fs::read_dir(&base) else {
        return Err(json_error(
            StatusCode::FORBIDDEN,
            &format!("Cannot read directory: {}", base.display()),
        ));
    };

    for entry in read_dir.flatten() {
        let Ok(ft) = entry.file_type() else {
            continue;
        };
        if !ft.is_dir() {
            continue;
        }
        let name = entry.file_name().to_string_lossy().to_string();
        // Skip hidden dirs except common ones
        if name.starts_with('.') {
            continue;
        }
        let path = entry.path();
        let is_git = path.join(".git").exists();
        entries.push(DirEntry {
            name,
            path: path.to_string_lossy().to_string(),
            is_git,
        });
    }

    entries.sort_by(|a, b| a.name.to_lowercase().cmp(&b.name.to_lowercase()));
    Ok(Json(entries))
}

/// Remove a registered project directory
pub async fn remove_project(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<RemoveProjectRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    match core.remove_project(&req.path) {
        Ok(()) => Ok(Json(serde_json::json!({"ok": true}))),
        Err(e) => Err(api_error_to_http(e)),
    }
}

// =========================================================
// Spawn settings endpoint
// =========================================================

/// Response body for spawn settings
#[derive(Debug, Serialize)]
pub struct SpawnSettingsResponse {
    /// Whether to spawn in tmux windows (vs internal PTY)
    pub use_tmux_window: bool,
    /// Whether tmux is available as a runtime
    pub tmux_available: bool,
    /// Window name for tmux-spawned agents
    pub tmux_window_name: String,
}

/// Request body for updating spawn settings
#[derive(Debug, Deserialize)]
pub struct UpdateSpawnSettingsRequest {
    /// Whether to spawn in tmux windows
    pub use_tmux_window: bool,
    /// Window name for tmux-spawned agents (optional, keeps current if omitted)
    #[serde(default)]
    pub tmux_window_name: Option<String>,
}

/// GET /api/settings/spawn — get spawn settings
pub async fn get_spawn_settings(State(core): State<Arc<TmaiCore>>) -> Json<SpawnSettingsResponse> {
    let (use_tmux_window, tmux_window_name) = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        (state.spawn_in_tmux, state.spawn_tmux_window_name.clone())
    };
    let tmux_available = is_tmux_available();

    Json(SpawnSettingsResponse {
        use_tmux_window,
        tmux_available,
        tmux_window_name,
    })
}

/// PUT /api/settings/spawn — update spawn settings
pub async fn update_spawn_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<UpdateSpawnSettingsRequest>,
) -> Json<serde_json::Value> {
    {
        #[allow(deprecated)]
        let state = core.raw_state();
        let mut s = state.write();
        s.spawn_in_tmux = req.use_tmux_window;
        if let Some(ref name) = req.tmux_window_name {
            if !name.is_empty() {
                s.spawn_tmux_window_name = name.clone();
            }
        }
    }
    // Persist to config.toml
    tmai_core::config::Settings::save_toml_value(
        "spawn",
        "use_tmux_window",
        toml_edit::Value::from(req.use_tmux_window),
    );
    if let Some(ref name) = req.tmux_window_name {
        if !name.is_empty() {
            tmai_core::config::Settings::save_toml_value(
                "spawn",
                "tmux_window_name",
                toml_edit::Value::from(name.as_str()),
            );
        }
    }

    // Reload live settings from config.toml
    core.reload_settings();

    tracing::info!(
        "Spawn settings updated: use_tmux_window={} window_name={:?}",
        req.use_tmux_window,
        req.tmux_window_name
    );
    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Orchestrator settings endpoints
// =========================================================

/// Query param for per-project orchestrator endpoints
#[derive(Debug, Deserialize)]
pub struct OrchestratorProjectQuery {
    /// Project path. If omitted, returns/updates global settings.
    #[serde(default)]
    pub project: Option<String>,
}

/// Response body for orchestrator settings
#[derive(Debug, Serialize)]
pub struct OrchestratorSettingsResponse {
    pub enabled: bool,
    pub role: String,
    pub rules: OrchestratorRulesResponse,
    /// Whether this is a per-project override (true) or global fallback (false)
    pub is_project_override: bool,
}

/// Rules sub-object in orchestrator settings response
#[derive(Debug, Serialize)]
pub struct OrchestratorRulesResponse {
    pub branch: String,
    pub merge: String,
    pub review: String,
    pub custom: String,
}

/// Request body for updating orchestrator settings
#[derive(Debug, Deserialize)]
pub struct UpdateOrchestratorSettingsRequest {
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub role: Option<String>,
    #[serde(default)]
    pub rules: Option<UpdateOrchestratorRulesRequest>,
}

/// Rules sub-object in orchestrator settings update request
#[derive(Debug, Deserialize)]
pub struct UpdateOrchestratorRulesRequest {
    #[serde(default)]
    pub branch: Option<String>,
    #[serde(default)]
    pub merge: Option<String>,
    #[serde(default)]
    pub review: Option<String>,
    #[serde(default)]
    pub custom: Option<String>,
}

/// GET /api/settings/orchestrator — get orchestrator settings
/// Accepts `?project=/path` for per-project override; omit for global.
pub async fn get_orchestrator_settings(
    State(core): State<Arc<TmaiCore>>,
    axum::extract::Query(q): axum::extract::Query<OrchestratorProjectQuery>,
) -> Json<OrchestratorSettingsResponse> {
    let settings = core.settings();
    let is_override = q
        .project
        .as_deref()
        .and_then(|p| settings.find_project(p))
        .is_some_and(|proj| proj.orchestrator.is_some());
    let orch = settings.resolve_orchestrator(q.project.as_deref());
    Json(OrchestratorSettingsResponse {
        enabled: orch.enabled,
        role: orch.role.clone(),
        rules: OrchestratorRulesResponse {
            branch: orch.rules.branch.clone(),
            merge: orch.rules.merge.clone(),
            review: orch.rules.review.clone(),
            custom: orch.rules.custom.clone(),
        },
        is_project_override: is_override,
    })
}

/// PUT /api/settings/orchestrator — update orchestrator settings (persisted to config.toml)
/// Accepts `?project=/path` for per-project override; omit for global.
pub async fn update_orchestrator_settings(
    State(core): State<Arc<TmaiCore>>,
    axum::extract::Query(q): axum::extract::Query<OrchestratorProjectQuery>,
    Json(req): Json<UpdateOrchestratorSettingsRequest>,
) -> Json<serde_json::Value> {
    let settings = core.settings();

    // Build the updated OrchestratorSettings from current + request
    let current = settings.resolve_orchestrator(q.project.as_deref());
    let updated = tmai_core::config::OrchestratorSettings {
        enabled: req.enabled.unwrap_or(current.enabled),
        role: req.role.unwrap_or_else(|| current.role.clone()),
        rules: tmai_core::config::OrchestratorRules {
            branch: req
                .rules
                .as_ref()
                .and_then(|r| r.branch.clone())
                .unwrap_or_else(|| current.rules.branch.clone()),
            merge: req
                .rules
                .as_ref()
                .and_then(|r| r.merge.clone())
                .unwrap_or_else(|| current.rules.merge.clone()),
            review: req
                .rules
                .as_ref()
                .and_then(|r| r.review.clone())
                .unwrap_or_else(|| current.rules.review.clone()),
            custom: req
                .rules
                .as_ref()
                .and_then(|r| r.custom.clone())
                .unwrap_or_else(|| current.rules.custom.clone()),
        },
    };
    drop(settings);

    tmai_core::config::Settings::save_project_orchestrator(q.project.as_deref(), &updated);
    core.reload_settings();
    tracing::info!(
        project = ?q.project,
        "Orchestrator settings updated"
    );
    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Auto-approve settings endpoint
// =========================================================

/// Response body for auto-approve settings
#[derive(Debug, Serialize)]
pub struct AutoApproveSettingsResponse {
    /// Current effective mode
    pub mode: String,
    /// Whether the service is running
    pub running: bool,
    /// Rule presets
    pub rules: RuleSettingsResponse,
}

/// Rule presets included in the auto-approve response
#[derive(Debug, Serialize)]
pub struct RuleSettingsResponse {
    pub allow_read: bool,
    pub allow_tests: bool,
    pub allow_fetch: bool,
    pub allow_git_readonly: bool,
    pub allow_format_lint: bool,
    pub allow_patterns: Vec<String>,
}

/// Request body for updating auto-approve settings
#[derive(Debug, Deserialize)]
pub struct UpdateAutoApproveRequest {
    /// Mode: "off", "rules", "ai", "hybrid"
    #[serde(default)]
    pub mode: Option<String>,
    /// Rule preset updates (partial)
    #[serde(default)]
    pub rules: Option<UpdateRuleSettingsRequest>,
}

/// Partial update for rule presets
#[derive(Debug, Deserialize)]
pub struct UpdateRuleSettingsRequest {
    pub allow_read: Option<bool>,
    pub allow_tests: Option<bool>,
    pub allow_fetch: Option<bool>,
    pub allow_git_readonly: Option<bool>,
    pub allow_format_lint: Option<bool>,
    pub allow_patterns: Option<Vec<String>>,
}

/// GET /api/settings/auto-approve — get current auto-approve settings
pub async fn get_auto_approve_settings(
    State(core): State<Arc<TmaiCore>>,
) -> Json<AutoApproveSettingsResponse> {
    let aa = &core.settings().auto_approve;
    let mode = serde_json::to_value(aa.effective_mode())
        .ok()
        .and_then(|v| v.as_str().map(String::from))
        .unwrap_or_else(|| format!("{:?}", aa.effective_mode()).to_lowercase());
    let running = aa.effective_mode() != tmai_core::auto_approve::types::AutoApproveMode::Off;

    let rules = RuleSettingsResponse {
        allow_read: aa.rules.allow_read,
        allow_tests: aa.rules.allow_tests,
        allow_fetch: aa.rules.allow_fetch,
        allow_git_readonly: aa.rules.allow_git_readonly,
        allow_format_lint: aa.rules.allow_format_lint,
        allow_patterns: aa.rules.allow_patterns.clone(),
    };

    Json(AutoApproveSettingsResponse {
        mode,
        running,
        rules,
    })
}

/// PUT /api/settings/auto-approve — update auto-approve settings (persisted to config.toml)
pub async fn update_auto_approve_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<UpdateAutoApproveRequest>,
) -> Json<serde_json::Value> {
    // Persist mode change (normalize to lowercase for serde compat)
    if let Some(ref mode) = req.mode {
        let mode_lower = mode.to_lowercase();
        tmai_core::config::Settings::save_toml_value(
            "auto_approve",
            "mode",
            toml_edit::Value::from(mode_lower.as_str()),
        );
        tracing::info!("Auto-approve mode updated to '{mode_lower}' (restart to apply)");
    }

    // Persist rule preset changes
    if let Some(ref rules) = req.rules {
        if let Some(v) = rules.allow_read {
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_read",
                toml_edit::Value::from(v),
            );
        }
        if let Some(v) = rules.allow_tests {
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_tests",
                toml_edit::Value::from(v),
            );
        }
        if let Some(v) = rules.allow_fetch {
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_fetch",
                toml_edit::Value::from(v),
            );
        }
        if let Some(v) = rules.allow_git_readonly {
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_git_readonly",
                toml_edit::Value::from(v),
            );
        }
        if let Some(v) = rules.allow_format_lint {
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_format_lint",
                toml_edit::Value::from(v),
            );
        }
        if let Some(ref patterns) = rules.allow_patterns {
            let arr = patterns
                .iter()
                .map(|s| toml_edit::Value::from(s.as_str()))
                .collect::<toml_edit::Array>();
            tmai_core::config::Settings::save_toml_nested_value(
                "auto_approve",
                "rules",
                "allow_patterns",
                toml_edit::Value::Array(arr),
            );
        }
        tracing::info!("Auto-approve rules updated (restart to apply)");
    }

    // Reload live settings from config.toml
    core.reload_settings();

    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Agent spawn endpoint
// =========================================================

/// Spawn request body
#[derive(Debug, Deserialize)]
pub struct SpawnRequest {
    pub command: String,
    #[serde(default)]
    pub args: Vec<String>,
    #[serde(default = "default_cwd")]
    pub cwd: String,
    #[serde(default = "default_rows")]
    pub rows: u16,
    #[serde(default = "default_cols")]
    pub cols: u16,
    /// Force PTY spawn even when tmux mode is enabled (e.g., for worktree)
    #[serde(default)]
    pub force_pty: bool,
}

/// Default working directory for spawn
fn default_cwd() -> String {
    std::env::current_dir()
        .map(|p| p.to_string_lossy().to_string())
        .unwrap_or_else(|_| "/tmp".to_string())
}

/// Default terminal rows
fn default_rows() -> u16 {
    24
}

/// Default terminal cols
fn default_cols() -> u16 {
    80
}

/// Spawn response body
#[derive(Debug, Serialize)]
pub struct SpawnResponse {
    pub session_id: String,
    pub pid: u32,
    pub command: String,
}

/// POST /api/spawn — spawn an agent (tmux window or PTY session)
pub async fn spawn_agent(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<SpawnRequest>,
) -> Result<Json<SpawnResponse>, (StatusCode, Json<serde_json::Value>)> {
    // Validate command (whitelist to prevent arbitrary execution)
    let allowed_commands = ["claude", "codex", "gemini", "bash", "sh", "zsh"];
    let base_command = req.command.split('/').next_back().unwrap_or(&req.command);
    if !allowed_commands.contains(&base_command) {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!(
                "Command not allowed: {}. Allowed: {:?}",
                req.command, allowed_commands
            ),
        ));
    }

    // Validate cwd exists
    if !std::path::Path::new(&req.cwd).is_dir() {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Directory does not exist: {}", req.cwd),
        ));
    }

    // Check if we should spawn in tmux
    let use_tmux = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        state.spawn_in_tmux
    };
    let tmux_avail = is_tmux_available();

    if use_tmux && tmux_avail && !req.force_pty {
        spawn_in_tmux(&core, &req).await
    } else {
        spawn_in_pty(&core, &req).await
    }
}

/// Check if tmux is available (running inside tmux and tmux command exists)
fn is_tmux_available() -> bool {
    std::env::var("TMUX").is_ok()
        && std::process::Command::new("tmux")
            .arg("list-sessions")
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .status()
            .map(|s| s.success())
            .unwrap_or(false)
}

/// Get the current tmux session name from $TMUX environment variable
fn current_tmux_session() -> Option<String> {
    // $TMUX format: /path/to/socket,pid,session_index
    // We need to ask tmux for the session name
    let output = std::process::Command::new("tmux")
        .args(["display-message", "-p", "#{session_name}"])
        .output()
        .ok()?;
    let name = String::from_utf8_lossy(&output.stdout).trim().to_string();
    if name.is_empty() {
        None
    } else {
        Some(name)
    }
}

/// Find an existing tmux window by name in a session.
/// Returns the window target (e.g., "session-1:2") if found.
fn find_tmux_window(session: &str, window_name: &str) -> Option<String> {
    let output = std::process::Command::new("tmux")
        .args([
            "list-windows",
            "-t",
            session,
            "-F",
            "#{window_index}:#{window_name}",
        ])
        .output()
        .ok()?;
    let stdout = String::from_utf8_lossy(&output.stdout);
    for line in stdout.lines() {
        if let Some((idx, name)) = line.split_once(':') {
            if name == window_name {
                return Some(format!("{}:{}", session, idx));
            }
        }
    }
    None
}

/// Spawn an agent in a tmux window (detected by poller like a normal pane)
async fn spawn_in_tmux(
    core: &Arc<TmaiCore>,
    req: &SpawnRequest,
) -> Result<Json<SpawnResponse>, (StatusCode, Json<serde_json::Value>)> {
    let tmux = tmai_core::tmux::TmuxClient::new();

    // Determine the tmux session to use.
    // Prefer current_tmux_session() since it always returns the real tmux session.
    // AppState.current_session or agent.session may be "hook"/"pty" (non-tmux).
    let session_name = current_tmux_session()
        .or_else(|| {
            #[allow(deprecated)]
            let state = core.raw_state().read();
            state.current_session.clone().or_else(|| {
                state
                    .agent_order
                    .iter()
                    .filter_map(|key| state.agents.get(key))
                    .find(|a| a.session != "hook" && a.session != "pty")
                    .map(|a| a.session.clone())
            })
        })
        .unwrap_or_else(|| "main".to_string());

    let window_name = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        state.spawn_tmux_window_name.clone()
    };

    // Reuse existing window with the same name, or create a new one
    let pane_target = find_tmux_window(&session_name, &window_name)
        .and_then(|target| {
            // Split existing window with tiled layout for balanced pane sizes
            tmux.split_window_tiled(&target, &req.cwd).ok()
        })
        .or_else(|| {
            // No existing window — create a new one
            tmux.new_window(&session_name, &req.cwd, Some(&window_name))
                .ok()
        })
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to create tmux window or split pane",
            )
        })?;

    // For Codex: start app-server first, add --remote to command
    let codex_ws_url = if req.command == "codex" {
        start_codex_app_server_sync(&req.cwd).await
    } else {
        None
    };

    // Build command with args (shell-quote each arg to prevent splitting)
    let mut all_args: Vec<String> = req.args.iter().map(|a| shell_quote(a)).collect();
    if let Some(ref url) = codex_ws_url {
        all_args.push("--remote".to_string());
        all_args.push(shell_quote(url));
    }
    let quoted_command = shell_quote(&req.command);
    let full_command = if all_args.is_empty() {
        quoted_command
    } else {
        format!("{} {}", quoted_command, all_args.join(" "))
    };

    // Shell commands don't need tmai wrap — the tmux pane already starts a shell
    let is_shell = matches!(req.command.as_str(), "bash" | "sh" | "zsh");
    if !is_shell {
        // Run AI agent commands via tmai wrap for monitoring
        tmux.run_command_wrapped(&pane_target, &full_command)
            .map_err(|e| {
                json_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    &format!("Failed to run command: {}", e),
                )
            })?;
    }

    tracing::info!(
        "API: spawned in tmux window '{}' target={} command={}",
        window_name,
        pane_target,
        req.command
    );

    // Connect WS client to the running app-server
    if let Some(ref ws_url) = codex_ws_url {
        connect_codex_ws(core, &pane_target, ws_url);
    }

    // The agent will be discovered by the poller on the next cycle.
    Ok(Json(SpawnResponse {
        session_id: pane_target,
        pid: 0, // poller will discover the actual PID
        command: req.command.clone(),
    }))
}

/// Spawn an agent in an internal PTY session (with WebSocket streaming)
async fn spawn_in_pty(
    core: &Arc<TmaiCore>,
    req: &SpawnRequest,
) -> Result<Json<SpawnResponse>, (StatusCode, Json<serde_json::Value>)> {
    let mut extra_args: Vec<String> = Vec::new();
    let rows = if req.rows > 0 { req.rows } else { 24 };
    let cols = if req.cols > 0 { req.cols } else { 80 };

    // For Codex: start app-server first, then launch codex with --remote
    let codex_ws_url = if req.command == "codex" {
        start_codex_app_server_sync(&req.cwd).await
    } else {
        None
    };
    if let Some(ref url) = codex_ws_url {
        extra_args.push("--remote".to_string());
        extra_args.push(url.clone());
    }

    let mut all_args: Vec<&str> = req.args.iter().map(|s| s.as_str()).collect();
    for a in &extra_args {
        all_args.push(a.as_str());
    }

    // Build environment variables so spawned agents can call tmai CLI
    let (api_token, api_port) = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        (state.web.token.clone().unwrap_or_default(), state.web.port)
    };
    let api_url = format!("http://127.0.0.1:{}", api_port);
    let env: Vec<(&str, &str)> = vec![
        ("TMAI_API_URL", api_url.as_str()),
        ("TMAI_TOKEN", api_token.as_str()),
    ];

    match core
        .pty_registry()
        .spawn_session(&req.command, &all_args, &req.cwd, rows, cols, &env)
    {
        Ok(session) => {
            let session_id = session.id.clone();
            let response = SpawnResponse {
                session_id: session_id.clone(),
                pid: session.pid,
                command: session.command.clone(),
            };

            // Fetch git info for the cwd so spawned agent groups with same-repo agents
            let git_info = tmai_core::git::GitCache::new().get_info(&req.cwd).await;

            // Register as a MonitoredAgent in AppState so the Poller won't discard it
            {
                #[allow(deprecated)]
                let state = core.raw_state();
                let mut s = state.write();
                let agent_type = match req.command.as_str() {
                    "claude" => tmai_core::agents::AgentType::ClaudeCode,
                    "codex" => tmai_core::agents::AgentType::CodexCli,
                    "gemini" => tmai_core::agents::AgentType::GeminiCli,
                    other => tmai_core::agents::AgentType::Custom(other.to_string()),
                };
                let mut agent = tmai_core::agents::MonitoredAgent::new(
                    session_id.clone(),
                    agent_type,
                    req.command.clone(),
                    req.cwd.clone(),
                    session.pid,
                    "pty".to_string(),
                    req.command.clone(),
                    0,
                    0,
                );
                agent.status = tmai_core::agents::AgentStatus::Processing {
                    activity: "Starting...".to_string(),
                };
                agent.stable_id = session_id.clone();
                agent.pty_session_id = Some(session_id.clone());
                if let Some(ref info) = git_info {
                    agent.git_branch = Some(info.branch.clone());
                    agent.git_dirty = Some(info.dirty);
                    agent.is_worktree = Some(info.is_worktree);
                    agent.git_common_dir = info.common_dir.clone();
                    agent.worktree_name = tmai_core::git::extract_claude_worktree_name(&req.cwd);
                }
                s.agents.insert(session_id.clone(), agent);
                s.agent_order.push(session_id.clone());
            }
            core.notify_agents_updated();

            // For Codex: connect WS client to the already-running app-server
            if let Some(ref ws_url) = codex_ws_url {
                connect_codex_ws(core, &session_id, ws_url);
            }

            tracing::info!(
                "API: spawned PTY session_id={} pid={}",
                response.session_id,
                response.pid
            );
            Ok(Json(response))
        }
        Err(e) => {
            tracing::error!("API: spawn failed: {}", e);
            Err(json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                &format!("Failed to spawn: {}", e),
            ))
        }
    }
}

/// Request body for spawning an orchestrator agent
#[derive(Debug, Deserialize)]
pub struct SpawnOrchestratorRequest {
    /// Project path (required). Orchestrator is spawned in this directory.
    pub project: String,
    /// Additional instructions appended to the composed prompt
    #[serde(default)]
    pub additional_instructions: Option<String>,
}

/// POST /api/orchestrator/spawn — spawn an orchestrator agent with composed prompt
pub async fn spawn_orchestrator(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<SpawnOrchestratorRequest>,
) -> Result<Json<SpawnResponse>, (StatusCode, Json<serde_json::Value>)> {
    let cwd = req.project.clone();

    if !std::path::Path::new(&cwd).is_dir() {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Directory does not exist: {}", cwd),
        ));
    }

    // Compose orchestrator prompt from settings (with per-project override)
    let mut prompt = core.compose_orchestrator_prompt(Some(&cwd));
    if let Some(ref extra) = req.additional_instructions {
        if !extra.is_empty() {
            prompt.push_str("\n\n");
            prompt.push_str(extra);
        }
    }

    // Spawn as a regular claude agent with the composed prompt as the initial argument
    let spawn_req = SpawnRequest {
        command: "claude".to_string(),
        args: vec![prompt],
        cwd: cwd.clone(),
        rows: default_rows(),
        cols: default_cols(),
        force_pty: true, // orchestrator always uses PTY for reliable monitoring
    };

    // Use spawn_in_pty directly (orchestrator always uses PTY)
    let result = spawn_in_pty(&core, &spawn_req).await?;

    // Mark the newly spawned agent as an orchestrator
    let session_id = &result.session_id;
    {
        #[allow(deprecated)]
        let state = core.raw_state();
        let mut s = state.write();
        if let Some(agent) = s.agents.get_mut(session_id) {
            agent.is_orchestrator = true;
        }
    }
    core.notify_agents_updated();

    tracing::info!("API: spawned orchestrator agent session_id={}", session_id);
    Ok(result)
}

/// Start a Codex app-server and return its WebSocket URL.
///
/// Launches `codex app-server --listen ws://127.0.0.1:0`, reads the actual
/// port from stderr, and returns the URL. The process keeps running in the
/// background for the lifetime of the codex session.
async fn start_codex_app_server_sync(cwd: &str) -> Option<String> {
    use tokio::io::{AsyncBufReadExt, BufReader};

    // Use process_group(0) to detach app-server from tmai's process group,
    // so it survives tmai restarts. Codex --remote depends on app-server staying alive.
    let mut child = match tokio::process::Command::new("codex")
        .args(["app-server", "--listen", "ws://127.0.0.1:0"])
        .current_dir(cwd)
        .stdin(std::process::Stdio::null())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::piped())
        .process_group(0)
        .spawn()
    {
        Ok(c) => c,
        Err(e) => {
            tracing::warn!("Failed to start Codex app-server: {}", e);
            return None;
        }
    };

    let stderr = child.stderr.take()?;
    let mut reader = BufReader::new(stderr).lines();
    let deadline = tokio::time::Instant::now() + std::time::Duration::from_secs(5);

    for _ in 0..10 {
        let line = tokio::select! {
            result = reader.next_line() => match result {
                Ok(Some(l)) => l,
                _ => break,
            },
            _ = tokio::time::sleep_until(deadline) => break,
        };
        if let Some(url) = line.strip_prefix("  listening on: ") {
            let url = url.trim().to_string();
            tracing::info!(url = %url, "Codex app-server started");
            // Record URL for reconnection after tmai restart
            save_codex_ws_url(&url);
            return Some(url);
        }
    }

    tracing::warn!("Codex app-server did not report listening URL");
    let _ = child.kill().await;
    None
}

/// Save codex app-server URL to state dir for reconnection after restart.
fn save_codex_ws_url(url: &str) {
    let state_dir = tmai_core::ipc::protocol::state_dir();
    let ws_dir = state_dir.join("codex-ws");
    let _ = std::fs::create_dir_all(&ws_dir);
    // Use port as filename for dedup
    if let Some(port) = url.rsplit(':').next() {
        let _ = std::fs::write(ws_dir.join(format!("{}.url", port)), url);
    }
}

/// Load previously recorded codex app-server URLs and connect to any that are still alive.
pub async fn reconnect_codex_ws(core: &Arc<TmaiCore>) {
    let state_dir = tmai_core::ipc::protocol::state_dir();
    let ws_dir = state_dir.join("codex-ws");
    let entries = match std::fs::read_dir(&ws_dir) {
        Ok(e) => e,
        Err(_) => return,
    };

    for entry in entries.flatten() {
        let path = entry.path();
        if path.extension().and_then(|e| e.to_str()) != Some("url") {
            continue;
        }
        let url = match std::fs::read_to_string(&path) {
            Ok(u) => u.trim().to_string(),
            Err(_) => continue,
        };

        // Check if the app-server is still reachable (quick TCP connect)
        let reachable = if let Some(addr) = url.strip_prefix("ws://") {
            tokio::time::timeout(
                std::time::Duration::from_secs(1),
                tokio::net::TcpStream::connect(addr),
            )
            .await
            .map(|r| r.is_ok())
            .unwrap_or(false)
        } else {
            false
        };

        if reachable {
            tracing::info!(url = %url, "Reconnecting to existing Codex app-server");
            // Use a synthetic pane_id — will be matched via target fallback
            let pane_id = format!(
                "codex-ws-reconnect-{}",
                path.file_stem().unwrap_or_default().to_string_lossy()
            );
            connect_codex_ws(core, &pane_id, &url);
        } else {
            // App-server is dead, clean up the URL file
            tracing::debug!(url = %url, "Codex app-server no longer reachable, removing");
            let _ = std::fs::remove_file(&path);
        }
    }
}

/// Connect a WebSocket client to an already-running Codex app-server.
fn connect_codex_ws(core: &Arc<TmaiCore>, pane_id: &str, ws_url: &str) {
    let config = tmai_core::codex_ws::client::CodexWsClientConfig {
        url: ws_url.to_string(),
        pane_id: Some(pane_id.to_string()),
    };
    let registry = core.hook_registry().clone();
    let event_tx = core.event_sender();
    #[allow(deprecated)]
    let state = core.raw_state().clone();

    tracing::info!(
        pane_id,
        url = ws_url,
        "Connecting WS client to Codex app-server"
    );
    tokio::spawn(async move {
        tmai_core::codex_ws::client::run(config, registry, event_tx, state).await;
    });
}

// =========================================================
// Git branch listing endpoint
// =========================================================

/// Query params for branch listing
#[derive(Debug, Deserialize)]
pub struct BranchQueryParams {
    pub repo: String,
}

/// GET /api/git/branches — list branches for a repository
pub async fn list_branches(
    axum::extract::Query(params): axum::extract::Query<BranchQueryParams>,
) -> Result<Json<tmai_core::git::BranchListResult>, (StatusCode, Json<serde_json::Value>)> {
    if !std::path::Path::new(&params.repo).is_dir() {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Directory does not exist: {}", params.repo),
        ));
    }

    tmai_core::git::list_branches(&params.repo)
        .await
        .ok_or_else(|| json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to list branches"))
        .map(Json)
}

/// Commit log query params
#[derive(Debug, Deserialize)]
pub struct CommitLogParams {
    pub repo: String,
    pub base: String,
    pub branch: String,
}

/// Query params for diff stat endpoint
#[derive(Debug, Deserialize)]
pub struct DiffStatParams {
    pub repo: String,
    pub branch: String,
    pub base: String,
}

/// GET /api/git/diff-stat — get diff statistics between two branches
pub async fn git_diff_stat(
    axum::extract::Query(params): axum::extract::Query<DiffStatParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = tmai_core::git::strip_git_suffix(&params.repo);
    let result =
        tmai_core::git::fetch_branch_diff_stat(repo_dir, &params.branch, &params.base).await;
    match result {
        Some(s) => Ok(Json(serde_json::json!({
            "files_changed": s.files_changed,
            "insertions": s.insertions,
            "deletions": s.deletions,
        }))),
        None => Ok(Json(serde_json::json!(null))),
    }
}

/// GET /api/git/diff — get full diff between two branches
pub async fn git_branch_diff(
    axum::extract::Query(params): axum::extract::Query<DiffStatParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = tmai_core::git::strip_git_suffix(&params.repo);
    if !tmai_core::git::is_safe_git_ref(&params.branch)
        || !tmai_core::git::is_safe_git_ref(&params.base)
    {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid branch name"));
    }
    let diff_spec = format!("{}...{}", params.base, params.branch);
    let output = tokio::process::Command::new("git")
        .args(["-C", repo_dir, "diff", &diff_spec])
        .output()
        .await
        .map_err(|e| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                &format!("git diff failed: {}", e),
            )
        })?;
    let raw = &output.stdout;
    const MAX_DIFF_BYTES: usize = 1_048_576; // 1MB
    let truncated = raw.len() > MAX_DIFF_BYTES;
    let diff_bytes = if truncated {
        &raw[..MAX_DIFF_BYTES]
    } else {
        raw.as_slice()
    };
    let diff = String::from_utf8_lossy(diff_bytes).to_string();
    let summary =
        tmai_core::git::fetch_branch_diff_stat(repo_dir, &params.branch, &params.base).await;
    Ok(Json(serde_json::json!({
        "diff": if diff.is_empty() { None } else { Some(diff) },
        "truncated": truncated,
        "summary": summary.map(|s| serde_json::json!({
            "files_changed": s.files_changed,
            "insertions": s.insertions,
            "deletions": s.deletions,
        })),
    })))
}

/// Get commit log between two branches
pub async fn git_log(
    axum::extract::Query(params): axum::extract::Query<CommitLogParams>,
) -> Result<Json<Vec<tmai_core::git::CommitEntry>>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    let commits = tmai_core::git::log_commits(&repo_dir, &params.base, &params.branch, 20).await;
    Ok(Json(commits))
}

/// Graph query params
#[derive(Debug, Deserialize)]
pub struct GraphQueryParams {
    pub repo: String,
    #[serde(default = "default_graph_limit")]
    pub limit: usize,
}

/// Default limit for graph commits
fn default_graph_limit() -> usize {
    100
}

/// GET /api/git/graph — get full commit graph for lane visualization
pub async fn git_graph(
    axum::extract::Query(params): axum::extract::Query<GraphQueryParams>,
) -> Result<Json<tmai_core::git::GraphData>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::git::log_graph(&repo_dir, params.limit)
        .await
        .ok_or_else(|| json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to get graph"))
        .map(Json)
}

/// Delete branch request body
#[derive(Debug, Deserialize)]
pub struct DeleteBranchRequest {
    pub repo_path: String,
    pub branch: String,
    #[serde(default)]
    pub force: bool,
    #[serde(default)]
    pub delete_remote: bool,
}

/// Delete a local git branch
///
/// When force is not requested, automatically uses force-delete (`-D`) for
/// branches whose PR has been squash-merged — `git branch -d` would reject
/// them because the original commits don't exist on the target branch.
pub async fn delete_branch(
    Json(req): Json<DeleteBranchRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    if !tmai_core::git::is_safe_git_ref(&req.branch) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid branch name"));
    }

    let repo_dir = validate_repo(&req.repo_path)?;

    // Auto-force for squash-merged branches: git branch -d fails because the
    // original commits don't appear in the target branch after squash merge.
    let force = if req.force {
        true
    } else {
        tmai_core::github::has_merged_pr(&repo_dir, &req.branch).await
    };

    tmai_core::git::delete_branch(&repo_dir, &req.branch, force, req.delete_remote)
        .await
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

/// Bulk delete branches request body
#[derive(Debug, Deserialize)]
pub struct BulkDeleteBranchesRequest {
    pub repo_path: String,
    pub branches: Vec<String>,
    #[serde(default)]
    pub delete_remote: bool,
}

/// Result of a single branch deletion attempt
#[derive(Debug, Serialize)]
struct BranchDeleteResult {
    branch: String,
    status: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    error: Option<String>,
}

/// Bulk-delete local branches that have been merged
///
/// For each branch, auto-detects squash-merged PRs and uses force-delete
/// accordingly. Returns per-branch success/failure results so the caller
/// can report partial failures.
pub async fn bulk_delete_branches(
    Json(req): Json<BulkDeleteBranchesRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    if req.branches.is_empty() {
        return Err(json_error(StatusCode::BAD_REQUEST, "No branches specified"));
    }

    let repo_dir = validate_repo(&req.repo_path)?;

    let mut results: Vec<BranchDeleteResult> = Vec::new();

    for branch in &req.branches {
        if !tmai_core::git::is_safe_git_ref(branch) {
            results.push(BranchDeleteResult {
                branch: branch.clone(),
                status: "error".to_string(),
                error: Some("Invalid branch name".to_string()),
            });
            continue;
        }

        // Auto-force for squash-merged branches
        let force = tmai_core::github::has_merged_pr(&repo_dir, branch).await;

        match tmai_core::git::delete_branch(&repo_dir, branch, force, req.delete_remote).await {
            Ok(()) => {
                results.push(BranchDeleteResult {
                    branch: branch.clone(),
                    status: "ok".to_string(),
                    error: None,
                });
            }
            Err(e) => {
                results.push(BranchDeleteResult {
                    branch: branch.clone(),
                    status: "error".to_string(),
                    error: Some(e),
                });
            }
        }
    }

    let succeeded = results.iter().filter(|r| r.status == "ok").count();
    let failed = results.iter().filter(|r| r.status == "error").count();

    Ok(Json(serde_json::json!({
        "results": results,
        "succeeded": succeeded,
        "failed": failed,
    })))
}

/// Checkout branch request body
#[derive(Debug, Deserialize)]
pub struct CheckoutRequest {
    pub repo_path: String,
    pub branch: String,
}

/// Checkout (switch to) a branch
pub async fn checkout_branch(
    Json(req): Json<CheckoutRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate branch name to prevent command injection
    if !tmai_core::git::is_safe_git_ref(&req.branch) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid branch name"));
    }
    let repo_dir = validate_repo(&req.repo_path)?;

    tmai_core::git::checkout_branch(&repo_dir, &req.branch)
        .await
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

/// Create branch request body
#[derive(Debug, Deserialize)]
pub struct CreateBranchRequest {
    pub repo_path: String,
    pub name: String,
    pub base: Option<String>,
}

/// Create a new local branch (without checking it out)
pub async fn create_branch(
    Json(req): Json<CreateBranchRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Validate branch name to prevent command injection
    if !tmai_core::git::is_safe_git_ref(&req.name) {
        return Err(json_error(StatusCode::BAD_REQUEST, "Invalid branch name"));
    }
    if let Some(ref base) = req.base {
        if !tmai_core::git::is_safe_git_ref(base) {
            return Err(json_error(
                StatusCode::BAD_REQUEST,
                "Invalid base branch name",
            ));
        }
    }
    let repo_dir = validate_repo(&req.repo_path)?;

    tmai_core::git::create_branch(&repo_dir, &req.name, req.base.as_deref())
        .await
        .map(|()| Json(serde_json::json!({"status": "ok"})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

/// Fetch request body
#[derive(Debug, Deserialize)]
pub struct FetchRequest {
    pub repo_path: String,
    pub remote: Option<String>,
}

/// Fetch from a remote
pub async fn git_fetch(
    Json(req): Json<FetchRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&req.repo_path)?;

    tmai_core::git::fetch_remote(&repo_dir, req.remote.as_deref())
        .await
        .map(|output| Json(serde_json::json!({"status": "ok", "output": output})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

/// Pull request body
#[derive(Debug, Deserialize)]
pub struct PullRequest {
    pub repo_path: String,
}

/// Pull from upstream (fast-forward only)
pub async fn git_pull(
    Json(req): Json<PullRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&req.repo_path)?;

    tmai_core::git::pull(&repo_dir)
        .await
        .map(|output| Json(serde_json::json!({"status": "ok", "output": output})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

/// Merge request body
#[derive(Debug, Deserialize)]
pub struct MergeRequest {
    pub repo_path: String,
    pub branch: String,
}

/// Merge a branch into the current branch
pub async fn git_merge(
    Json(req): Json<MergeRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&req.repo_path)?;

    tmai_core::git::merge_branch(&repo_dir, &req.branch)
        .await
        .map(|output| Json(serde_json::json!({"status": "ok", "output": output})))
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e))
}

// =========================================================
// Worktree spawn endpoint
// =========================================================

/// Request body for worktree spawn
#[derive(Debug, Deserialize)]
pub struct WorktreeSpawnRequest {
    /// Worktree name (optional if issue_number is provided — auto-generated from issue title)
    #[serde(default)]
    pub name: Option<String>,
    /// GitHub issue number. When set, fetches issue title/body to auto-generate the
    /// worktree name (if not given) and compose a resolve prompt with issue context.
    #[serde(default)]
    pub issue_number: Option<u64>,
    /// Repository path
    pub cwd: String,
    /// Base branch to create worktree from (defaults to current HEAD)
    #[serde(default)]
    pub base_branch: Option<String>,
    /// Optional initial prompt to send to the agent on launch
    #[serde(default)]
    pub initial_prompt: Option<String>,
    /// Extra instructions appended after the auto-generated issue prompt.
    /// Only used when issue_number is set and initial_prompt is absent.
    #[serde(default)]
    pub additional_instructions: Option<String>,
    #[serde(default = "default_rows")]
    pub rows: u16,
    #[serde(default = "default_cols")]
    pub cols: u16,
}

/// POST /api/spawn/worktree — create git worktree then spawn claude in it
pub async fn spawn_worktree(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<WorktreeSpawnRequest>,
) -> Result<Json<SpawnResponse>, (StatusCode, Json<serde_json::Value>)> {
    // Validate cwd
    if !std::path::Path::new(&req.cwd).is_dir() {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Directory does not exist: {}", req.cwd),
        ));
    }

    // Resolve worktree name and initial prompt from issue context if provided
    let (resolved_name, resolved_prompt) = resolve_issue_context(&req).await?;

    // Validate worktree name
    if !tmai_core::git::is_valid_worktree_name(&resolved_name) {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            &format!("Invalid worktree name: {}", resolved_name),
        ));
    }

    // Create git worktree using tmai-core
    let wt_req = tmai_core::worktree::WorktreeCreateRequest {
        repo_path: req.cwd.clone(),
        branch_name: resolved_name.clone(),
        dir_name: None,
        base_branch: req.base_branch.clone(),
    };

    let wt_result = tmai_core::worktree::create_worktree(&wt_req)
        .await
        .map_err(|e| json_error(StatusCode::BAD_REQUEST, &e.to_string()))?;

    tracing::info!(
        "API: created worktree '{}' at {} (branch: {})",
        resolved_name,
        wt_result.path,
        wt_result.branch
    );

    // Build args — pass resolved prompt as first positional argument if provided
    let args = if !resolved_prompt.is_empty() {
        vec![resolved_prompt]
    } else {
        vec![]
    };

    // Spawn claude in the worktree directory
    let worktree_path = wt_result.path.clone();
    let spawn_req = SpawnRequest {
        command: "claude".to_string(),
        args,
        cwd: wt_result.path,
        rows: req.rows,
        cols: req.cols,
        force_pty: false,
    };

    // Resolve the effective base branch for metadata
    let effective_base = req.base_branch.clone();

    // Use tmux if available, otherwise PTY
    let use_tmux = {
        #[allow(deprecated)]
        let state = core.raw_state().read();
        state.spawn_in_tmux
    };
    let result = if use_tmux && is_tmux_available() {
        spawn_in_tmux(&core, &spawn_req).await
    } else {
        spawn_in_pty(&core, &spawn_req).await
    };

    // Record pending agent state to prevent premature worktree deletion
    if let Ok(ref resp) = result {
        #[allow(deprecated)]
        let state = core.raw_state();
        let mut s = state.write();
        // Set worktree_base_branch on the spawned agent
        if let Some(agent) = s.agents.get_mut(&resp.session_id) {
            agent.worktree_base_branch = effective_base;
        }
        s.pending_agent_worktrees
            .insert(worktree_path, std::time::Instant::now());
    }

    result
}

/// Resolve worktree name and initial prompt from issue context.
///
/// When `issue_number` is provided, fetches the issue via `gh` and:
/// - auto-generates a worktree name from `{issue_number}-{slugified-title}` if `name` is absent
/// - composes an initial prompt with the issue context (title + body) if `initial_prompt` is absent
async fn resolve_issue_context(
    req: &WorktreeSpawnRequest,
) -> Result<(String, String), (StatusCode, Json<serde_json::Value>)> {
    match req.issue_number {
        Some(issue_number) => {
            let issue = tmai_core::github::get_issue_detail(&req.cwd, issue_number)
                .await
                .ok_or_else(|| {
                    json_error(
                        StatusCode::BAD_REQUEST,
                        &format!("Failed to fetch GitHub issue #{issue_number}. Is `gh` authenticated and is this a GitHub repository?"),
                    )
                })?;

            // Auto-generate name: {issue_number}-{slugified-title}
            let name = match &req.name {
                Some(n) if !n.is_empty() => n.clone(),
                _ => {
                    // Max slug portion: 64 (worktree name limit) - issue_number digits - 1 (hyphen)
                    let prefix = format!("{}-", issue_number);
                    let max_slug = 64_usize.saturating_sub(prefix.len());
                    let slug =
                        tmai_core::utils::namegen::slugify_for_branch(&issue.title, max_slug);
                    if slug.is_empty() {
                        return Err(json_error(
                            StatusCode::BAD_REQUEST,
                            &format!("Could not generate valid worktree name from issue #{issue_number} title"),
                        ));
                    }
                    format!("{prefix}{slug}")
                }
            };

            // Compose initial prompt with issue context if not explicitly provided
            let prompt = match &req.initial_prompt {
                Some(p) if !p.is_empty() => p.clone(),
                _ => {
                    let body_section = if issue.body.is_empty() {
                        String::new()
                    } else {
                        format!("\n\n## Issue Body\n{}", issue.body)
                    };
                    let base = format!(
                        "Resolve GitHub issue #{number}: {title}{body}\n\nCreate PR: \"{title} (#{number})\"",
                        number = issue_number,
                        title = issue.title,
                        body = body_section,
                    );
                    match &req.additional_instructions {
                        Some(extra) if !extra.is_empty() => {
                            format!("{base}\n\n## Additional Instructions\n{extra}")
                        }
                        _ => base,
                    }
                }
            };

            Ok((name, prompt))
        }
        None => {
            let name = req.name.clone().ok_or_else(|| {
                json_error(
                    StatusCode::BAD_REQUEST,
                    "Either 'name' or 'issue_number' must be provided",
                )
            })?;
            let prompt = req.initial_prompt.clone().unwrap_or_default();
            Ok((name, prompt))
        }
    }
}

// =========================================================
// Inter-agent communication endpoints
// =========================================================

/// GET /api/agents/{id}/output — get PTY scrollback output as text
pub async fn get_agent_output(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<String>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Resolve stable_id/pane_id to internal key, then try PTY lookup by key
    let resolved = core.resolve_agent_key(&id).unwrap_or_else(|_| id.clone());
    let session = core
        .pty_registry()
        .get(&resolved)
        .ok_or_else(|| json_error(StatusCode::NOT_FOUND, "PTY session not found"))?;

    let snapshot = session.scrollback_snapshot();
    let text = String::from_utf8_lossy(&snapshot).to_string();

    Ok(Json(serde_json::json!({
        "session_id": id,
        "output": text,
        "bytes": snapshot.len(),
    })))
}

/// Request body for sending text between agents
#[derive(Debug, Deserialize)]
pub struct SendToRequest {
    /// Text to send as input to the target agent
    pub text: String,
}

/// POST /api/agents/{from}/send-to/{to} — send text from one agent to another
pub async fn send_to_agent(
    State(core): State<Arc<TmaiCore>>,
    Path((from, to)): Path<(String, String)>,
    Json(req): Json<SendToRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    // Resolve both agent IDs
    let from_key = core
        .resolve_agent_key(&from)
        .map_err(|_| json_error(StatusCode::NOT_FOUND, "Source agent not found"))?;
    let to_key = core
        .resolve_agent_key(&to)
        .map_err(|_| json_error(StatusCode::NOT_FOUND, "Target agent not found"))?;

    // Validate text length
    if req.text.len() > 10240 {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            "Text too long (max 10KB)",
        ));
    }
    let _ = &from_key; // ensure source is valid

    // Try PTY write first (for PTY-spawned targets)
    if let Some(target_session) = core.pty_registry().get(&to_key) {
        target_session
            .write_input(req.text.as_bytes())
            .map_err(|e| {
                json_error(
                    StatusCode::INTERNAL_SERVER_ERROR,
                    &format!("Failed to write to target PTY: {}", e),
                )
            })?;
        // Send Enter after the text
        target_session.write_input(b"\r").map_err(|e| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                &format!("Failed to send Enter: {}", e),
            )
        })?;

        tracing::info!(
            "API: sent {} bytes from {} to {} (PTY)",
            req.text.len(),
            from,
            to
        );
        return Ok(Json(serde_json::json!({
            "status": "ok",
            "method": "pty",
        })));
    }

    // Fall back to regular send_text for non-PTY agents
    core.send_text(&to, &req.text).await.map_err(|e| {
        let status = match &e {
            tmai_core::api::ApiError::AgentNotFound { .. } => StatusCode::NOT_FOUND,
            _ => StatusCode::INTERNAL_SERVER_ERROR,
        };
        json_error(status, &e.to_string())
    })?;

    tracing::info!(
        "API: sent {} bytes from {} to {} (command_sender)",
        req.text.len(),
        from,
        to
    );
    Ok(Json(serde_json::json!({
        "status": "ok",
        "method": "command_sender",
    })))
}

// =========================================================
// Config audit endpoints
// =========================================================

/// POST /api/config-audit/run — run a config audit and return results
pub async fn config_audit(
    State(core): State<Arc<TmaiCore>>,
) -> Json<tmai_core::security::ScanResult> {
    Json(core.config_audit())
}

/// GET /api/config-audit/last — return cached audit result (no new audit)
pub async fn last_config_audit(
    State(core): State<Arc<TmaiCore>>,
) -> Json<Option<tmai_core::security::ScanResult>> {
    Json(core.last_config_audit())
}

// ── Usage ──

/// GET /api/usage — return cached usage snapshot
pub async fn get_usage(State(core): State<Arc<TmaiCore>>) -> Json<tmai_core::usage::UsageSnapshot> {
    Json(core.get_usage())
}

/// POST /api/usage/fetch — trigger a background usage fetch
pub async fn trigger_usage_fetch(State(core): State<Arc<TmaiCore>>) -> StatusCode {
    core.fetch_usage();
    StatusCode::ACCEPTED
}

/// Usage settings response
#[derive(Debug, Serialize)]
pub struct UsageSettingsResponse {
    pub enabled: bool,
    pub auto_refresh_min: u32,
}

/// Usage settings update request
#[derive(Debug, Deserialize)]
pub struct UsageSettingsRequest {
    #[serde(default)]
    pub enabled: Option<bool>,
    #[serde(default)]
    pub auto_refresh_min: Option<u32>,
}

/// GET /api/settings/usage — get usage settings
pub async fn get_usage_settings(State(core): State<Arc<TmaiCore>>) -> Json<UsageSettingsResponse> {
    let s = core.settings();
    Json(UsageSettingsResponse {
        enabled: s.usage.enabled,
        auto_refresh_min: s.usage.auto_refresh_min,
    })
}

/// PUT /api/settings/usage — update usage settings and persist
pub async fn update_usage_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<UsageSettingsRequest>,
) -> Json<serde_json::Value> {
    if let Some(enabled) = req.enabled {
        tmai_core::config::Settings::save_toml_value(
            "usage",
            "enabled",
            toml_edit::Value::from(enabled),
        );
    }
    if let Some(interval) = req.auto_refresh_min {
        tmai_core::config::Settings::save_toml_value(
            "usage",
            "auto_refresh_min",
            toml_edit::Value::from(interval as i64),
        );
    }

    // Reload live settings from config.toml
    core.reload_settings();

    Json(serde_json::json!({"ok": true}))
}

/// Query params for PR listing
#[derive(Debug, Deserialize)]
pub struct PrQueryParams {
    pub repo: String,
}

/// GET /api/github/prs — list open and merged PRs for a repository
///
/// Returns both open PRs and recently merged PRs whose head branch still
/// exists locally. Merged PRs include `merge_commit_sha` for drawing
/// merge lines in the git graph.
pub async fn list_prs(
    axum::extract::Query(params): axum::extract::Query<PrQueryParams>,
) -> Result<
    Json<std::collections::HashMap<String, tmai_core::github::PrInfo>>,
    (StatusCode, Json<serde_json::Value>),
> {
    let repo_dir = validate_repo(&params.repo)?;

    let mut map = tmai_core::github::list_open_prs(&repo_dir)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to list PRs (is gh CLI authenticated?)",
            )
        })?;

    // Fetch merged PRs for local branches (best-effort, don't fail if unavailable)
    if let Some(branch_list) = tmai_core::git::list_branches(&repo_dir).await {
        let local_branches: Vec<String> = branch_list
            .branches
            .iter()
            .filter(|b| !map.contains_key(b.as_str()))
            .cloned()
            .collect();
        if let Some(merged) = tmai_core::github::list_merged_prs(&repo_dir, &local_branches).await {
            map.extend(merged);
        }
    }

    Ok(Json(map))
}

/// Query params for CI checks
#[derive(Debug, Deserialize)]
pub struct ChecksQueryParams {
    pub repo: String,
    pub branch: String,
}

/// GET /api/github/checks — list CI checks for a branch
pub async fn list_checks(
    axum::extract::Query(params): axum::extract::Query<ChecksQueryParams>,
) -> Result<Json<tmai_core::github::CiSummary>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::list_checks(&repo_dir, &params.branch)
        .await
        .ok_or_else(|| json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to list checks"))
        .map(Json)
}

/// GET /api/github/issues — list open issues for a repository
pub async fn list_issues(
    axum::extract::Query(params): axum::extract::Query<PrQueryParams>,
) -> Result<Json<Vec<tmai_core::github::IssueInfo>>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::list_issues(&repo_dir)
        .await
        .ok_or_else(|| json_error(StatusCode::INTERNAL_SERVER_ERROR, "Failed to list issues"))
        .map(Json)
}

/// Query params for issue detail endpoint
#[derive(Debug, Deserialize)]
pub struct IssueDetailParams {
    pub repo: String,
    pub issue_number: u64,
}

/// GET /api/github/issue/detail — fetch detailed info for a single issue
pub async fn get_issue_detail(
    axum::extract::Query(params): axum::extract::Query<IssueDetailParams>,
) -> Result<Json<tmai_core::github::IssueDetail>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::get_issue_detail(&repo_dir, params.issue_number)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to fetch issue detail",
            )
        })
        .map(Json)
}

/// Query params for PR detail endpoints
#[derive(Debug, Deserialize)]
pub struct PrDetailParams {
    pub repo: String,
    pub pr_number: u64,
}

/// Query params for CI log endpoint
#[derive(Debug, Deserialize)]
pub struct CiLogParams {
    pub repo: String,
    pub run_id: u64,
}

/// GET /api/github/pr/comments — fetch comments and reviews for a PR
pub async fn get_pr_comments(
    axum::extract::Query(params): axum::extract::Query<PrDetailParams>,
) -> Result<Json<Vec<tmai_core::github::PrComment>>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::get_pr_comments(&repo_dir, params.pr_number)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to fetch PR comments",
            )
        })
        .map(Json)
}

/// GET /api/github/pr/files — fetch changed files for a PR
pub async fn get_pr_files(
    axum::extract::Query(params): axum::extract::Query<PrDetailParams>,
) -> Result<Json<Vec<tmai_core::github::PrChangedFile>>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::get_pr_files(&repo_dir, params.pr_number)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to fetch PR files",
            )
        })
        .map(Json)
}

/// GET /api/github/pr/merge-status — fetch merge readiness status for a PR
pub async fn get_pr_merge_status(
    axum::extract::Query(params): axum::extract::Query<PrDetailParams>,
) -> Result<Json<tmai_core::github::PrMergeStatus>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::get_pr_merge_status(&repo_dir, params.pr_number)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to fetch PR merge status",
            )
        })
        .map(Json)
}

/// POST /api/github/ci/rerun — re-run failed CI checks
pub async fn rerun_failed_checks(
    Json(body): Json<CiLogParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&body.repo)?;

    tmai_core::github::rerun_failed_checks(&repo_dir, body.run_id)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to re-run checks (may lack actions:write permission)",
            )
        })
        .map(|()| Json(serde_json::json!({"status": "ok"})))
}

/// GET /api/github/ci/failure-log — fetch failure log for a CI run
pub async fn get_ci_failure_log(
    axum::extract::Query(params): axum::extract::Query<CiLogParams>,
) -> Result<Json<tmai_core::github::CiFailureLog>, (StatusCode, Json<serde_json::Value>)> {
    let repo_dir = validate_repo(&params.repo)?;

    tmai_core::github::get_ci_failure_log(&repo_dir, params.run_id)
        .await
        .ok_or_else(|| {
            json_error(
                StatusCode::INTERNAL_SERVER_ERROR,
                "Failed to fetch CI failure log",
            )
        })
        .map(Json)
}

// =========================================================
// File read/write/tree endpoints
// =========================================================

/// Query params for file read
#[derive(Debug, Deserialize)]
pub struct FileReadParams {
    pub path: String,
}

/// GET /api/files/read — read any text file's content
pub async fn read_file(
    State(core): State<Arc<TmaiCore>>,
    axum::extract::Query(params): axum::extract::Query<FileReadParams>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let path = std::path::Path::new(&params.path);
    // Path traversal protection: must be within HOME or a registered project
    if !is_path_within_allowed_scope(path, Some(&core)) {
        return Err(json_error(
            StatusCode::FORBIDDEN,
            "Path is outside allowed scope",
        ));
    }
    if !path.is_file() {
        return Err(json_error(StatusCode::NOT_FOUND, "File not found"));
    }
    // Limit file size to 1MB
    let metadata = std::fs::metadata(path)
        .map_err(|e| json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
    if metadata.len() > 1_048_576 {
        return Err(json_error(
            StatusCode::BAD_REQUEST,
            "File too large (max 1MB)",
        ));
    }
    let content = std::fs::read_to_string(path)
        .map_err(|_| json_error(StatusCode::BAD_REQUEST, "Not a text file (binary content)"))?;
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    let editable = OPENABLE_EXTENSIONS.contains(&ext);
    Ok(Json(
        serde_json::json!({ "path": params.path, "content": content, "editable": editable }),
    ))
}

/// Request body for file write
#[derive(Debug, Deserialize)]
pub struct FileWriteRequest {
    pub path: String,
    pub content: String,
}

/// POST /api/files/write — write content to a file
pub async fn write_file(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<FileWriteRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let path = std::path::Path::new(&req.path);
    // Path traversal protection: must be within HOME or a registered project
    if !is_path_within_allowed_scope(path, Some(&core)) {
        return Err(json_error(
            StatusCode::FORBIDDEN,
            "Path is outside allowed scope",
        ));
    }
    // Security: only allow writing .md, .json, .toml, .txt, .yaml, .yml files
    let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
    if !matches!(ext, "md" | "json" | "toml" | "txt" | "yaml" | "yml") {
        return Err(json_error(StatusCode::FORBIDDEN, "File type not allowed"));
    }
    // Must be an existing file (no creating new files via this endpoint)
    if !path.is_file() {
        return Err(json_error(StatusCode::NOT_FOUND, "File not found"));
    }
    std::fs::write(path, &req.content)
        .map_err(|e| json_error(StatusCode::INTERNAL_SERVER_ERROR, &e.to_string()))?;
    Ok(Json(serde_json::json!({ "status": "ok" })))
}

/// Query params for markdown file tree
#[derive(Debug, Deserialize)]
pub struct MdTreeParams {
    pub root: String,
}

/// Entry in the file tree
#[derive(Debug, Serialize)]
pub struct MdTreeEntry {
    pub name: String,
    pub path: String,
    pub is_dir: bool,
    pub openable: bool,
    pub children: Option<Vec<MdTreeEntry>>,
}

/// File extensions that can be opened (read/write) in the markdown panel
const OPENABLE_EXTENSIONS: &[&str] = &["md", "json", "toml", "txt", "yaml", "yml"];

/// GET /api/files/md-tree — list markdown files in a directory tree
pub async fn md_tree(
    State(core): State<Arc<TmaiCore>>,
    axum::extract::Query(params): axum::extract::Query<MdTreeParams>,
) -> Result<Json<Vec<MdTreeEntry>>, (StatusCode, Json<serde_json::Value>)> {
    let root = std::path::Path::new(&params.root);
    // Path traversal protection: must be within HOME or a registered project
    if !is_path_within_allowed_scope(root, Some(&core)) {
        return Err(json_error(
            StatusCode::FORBIDDEN,
            "Path is outside allowed scope",
        ));
    }
    if !root.is_dir() {
        return Err(json_error(StatusCode::NOT_FOUND, "Directory not found"));
    }
    let entries =
        scan_md_tree(root, 0).map_err(|e| json_error(StatusCode::INTERNAL_SERVER_ERROR, &e))?;
    Ok(Json(entries))
}

/// Recursively scan a directory for all files (max depth 5)
fn scan_md_tree(dir: &std::path::Path, depth: usize) -> Result<Vec<MdTreeEntry>, String> {
    if depth > 5 {
        return Ok(Vec::new());
    }
    let mut entries = Vec::new();
    let read_dir = std::fs::read_dir(dir).map_err(|e| e.to_string())?;

    let mut items: Vec<_> = read_dir.filter_map(|e| e.ok()).collect();
    items.sort_by_key(|e| e.file_name());

    for entry in items {
        let path = entry.path();
        let name = entry.file_name().to_string_lossy().to_string();

        // Skip hidden directories (except .claude)
        if name.starts_with('.') && name != ".claude" {
            continue;
        }
        // Skip bulky directories
        if matches!(name.as_str(), "node_modules" | "target" | "dist" | ".git") {
            continue;
        }

        if path.is_dir() {
            let children = scan_md_tree(&path, depth + 1)?;
            if !children.is_empty() {
                entries.push(MdTreeEntry {
                    name,
                    path: path.to_string_lossy().to_string(),
                    is_dir: true,
                    openable: false,
                    children: Some(children),
                });
            }
        } else {
            let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");
            let openable = OPENABLE_EXTENSIONS.contains(&ext);
            entries.push(MdTreeEntry {
                name,
                path: path.to_string_lossy().to_string(),
                is_dir: false,
                openable,
                children: None,
            });
        }
    }
    Ok(entries)
}

/// Validate that a repo path points to an existing directory, returning the
/// path with any `.git` suffix stripped. Used by endpoints that accept a repo
/// path parameter.
fn validate_repo(repo: &str) -> Result<String, (StatusCode, Json<serde_json::Value>)> {
    let dir = tmai_core::git::strip_git_suffix(repo);
    if !std::path::Path::new(dir).is_dir() {
        return Err(json_error(StatusCode::NOT_FOUND, "Repository not found"));
    }
    Ok(dir.to_string())
}

/// Re-export for convenience
fn strip_git_suffix(path: &str) -> &str {
    tmai_core::git::strip_git_suffix(path)
}

// =========================================================
// Preview settings
// =========================================================

/// Response for GET /api/settings/preview
#[derive(Debug, Serialize)]
pub struct PreviewSettingsResponse {
    pub show_cursor: bool,
}

/// Request for PUT /api/settings/preview
#[derive(Debug, Deserialize)]
pub struct PreviewSettingsRequest {
    pub show_cursor: Option<bool>,
}

/// GET /api/settings/preview
pub async fn get_preview_settings(
    State(core): State<Arc<TmaiCore>>,
) -> Json<PreviewSettingsResponse> {
    Json(PreviewSettingsResponse {
        show_cursor: core.settings().web.show_cursor,
    })
}

/// PUT /api/settings/preview — update preview settings and persist
pub async fn update_preview_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<PreviewSettingsRequest>,
) -> Json<serde_json::Value> {
    if let Some(v) = req.show_cursor {
        tmai_core::config::Settings::save_toml_value(
            "web",
            "show_cursor",
            toml_edit::Value::from(v),
        );
    }

    // Reload live settings from config.toml
    core.reload_settings();

    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Notification settings
// =========================================================

/// Response for GET /api/settings/notification
#[derive(Debug, Serialize)]
pub struct NotificationSettingsResponse {
    pub notify_on_idle: bool,
    pub notify_idle_threshold_secs: u64,
}

/// Request for PUT /api/settings/notification
#[derive(Debug, Deserialize)]
pub struct NotificationSettingsRequest {
    pub notify_on_idle: Option<bool>,
    pub notify_idle_threshold_secs: Option<u64>,
}

/// GET /api/settings/notification
pub async fn get_notification_settings(
    State(core): State<Arc<TmaiCore>>,
) -> Json<NotificationSettingsResponse> {
    let web = &core.settings().web;
    Json(NotificationSettingsResponse {
        notify_on_idle: web.notify_on_idle,
        notify_idle_threshold_secs: web.notify_idle_threshold_secs,
    })
}

/// PUT /api/settings/notification — update notification settings and persist
pub async fn update_notification_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<NotificationSettingsRequest>,
) -> Json<serde_json::Value> {
    if let Some(v) = req.notify_on_idle {
        tmai_core::config::Settings::save_toml_value(
            "web",
            "notify_on_idle",
            toml_edit::Value::from(v),
        );
    }
    if let Some(v) = req.notify_idle_threshold_secs {
        tmai_core::config::Settings::save_toml_value(
            "web",
            "notify_idle_threshold_secs",
            toml_edit::Value::from(v as i64),
        );
    }

    // Reload live settings from config.toml
    core.reload_settings();

    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Theme settings
// =========================================================

/// Response for GET /api/settings/theme
#[derive(Debug, Serialize)]
pub struct ThemeSettingsResponse {
    pub theme: String,
}

/// Request for PUT /api/settings/theme
#[derive(Debug, Deserialize)]
pub struct ThemeSettingsRequest {
    pub theme: Option<String>,
}

/// GET /api/settings/theme
pub async fn get_theme_settings(State(core): State<Arc<TmaiCore>>) -> Json<ThemeSettingsResponse> {
    Json(ThemeSettingsResponse {
        theme: core.settings().web.theme.clone(),
    })
}

/// PUT /api/settings/theme — update theme preference and persist
pub async fn update_theme_settings(
    State(core): State<Arc<TmaiCore>>,
    Json(req): Json<ThemeSettingsRequest>,
) -> Json<serde_json::Value> {
    if let Some(ref v) = req.theme {
        // Validate value
        if v == "dark" || v == "light" || v == "system" {
            tmai_core::config::Settings::save_toml_value(
                "web",
                "theme",
                toml_edit::Value::from(v.as_str()),
            );
        }
    }

    // Reload live settings from config.toml
    core.reload_settings();

    Json(serde_json::json!({"ok": true}))
}

// =========================================================
// Deferred tool call endpoints
// =========================================================

/// Request body for resolving a deferred tool call
#[derive(Debug, Deserialize)]
pub struct ResolveDeferRequest {
    /// "allow" or "deny"
    pub decision: String,
    /// Optional reason for the decision
    #[serde(default)]
    pub reason: String,
}

/// GET /api/defer — list pending deferred tool calls
pub async fn list_deferred(State(core): State<Arc<TmaiCore>>) -> Json<serde_json::Value> {
    let pending = core.defer_registry().list_pending();
    Json(serde_json::json!({
        "pending": pending,
        "count": pending.len()
    }))
}

/// POST /api/defer/{id}/resolve — approve or reject a deferred tool call
pub async fn resolve_deferred(
    State(core): State<Arc<TmaiCore>>,
    Path(id): Path<u64>,
    Json(req): Json<ResolveDeferRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
    let decision = match req.decision.as_str() {
        "allow" => tmai_core::auto_approve::PermissionDecision::Allow,
        "deny" => tmai_core::auto_approve::PermissionDecision::Deny,
        other => {
            return Err(json_error(
                StatusCode::BAD_REQUEST,
                &format!("Invalid decision '{}': must be 'allow' or 'deny'", other),
            ));
        }
    };

    let reason = if req.reason.is_empty() {
        format!("Manually {} via UI", req.decision)
    } else {
        req.reason
    };

    let resolution = tmai_core::auto_approve::DeferResolution {
        decision,
        reason,
        resolved_by: "human".into(),
    };

    if core.defer_registry().resolve(id, resolution) {
        tracing::info!(defer_id = id, decision = %req.decision, "Deferred call resolved via API");
        Ok(Json(serde_json::json!({"status": "ok", "defer_id": id})))
    } else {
        Err(json_error(
            StatusCode::NOT_FOUND,
            &format!("Deferred call {} not found or already resolved", id),
        ))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::routing::{get, post};
    use axum::Router;
    use http::Request;
    use http_body_util::BodyExt;
    use tmai_core::agents::AgentStatus;
    use tmai_core::api::{has_checkbox_format, TmaiCoreBuilder};
    use tmai_core::command_sender::CommandSender;
    use tmai_core::state::SharedState;
    use tower::ServiceExt;

    /// Create a fresh shared AppState for tests
    fn test_app_state() -> SharedState {
        tmai_core::state::AppState::shared()
    }

    /// Build a Router with all API routes but NO auth middleware
    fn test_router_with_state(app_state: SharedState) -> Router {
        let runtime: Arc<dyn tmai_core::runtime::RuntimeAdapter> =
            Arc::new(tmai_core::runtime::StandaloneAdapter::new());
        let cmd = CommandSender::new(None, runtime, app_state.clone());
        let core = Arc::new(
            TmaiCoreBuilder::new(tmai_core::config::Settings::default())
                .with_state(app_state)
                .with_command_sender(Arc::new(cmd))
                .build(),
        );
        Router::new()
            .route("/agents", get(get_agents))
            .route("/agents/{id}/approve", post(approve_agent))
            .route("/agents/{id}/select", post(select_choice))
            .route("/agents/{id}/submit", post(submit_selection))
            .route("/agents/{id}/input", post(send_text))
            .route("/agents/{id}/key", post(send_key))
            .route("/agents/{id}/preview", get(get_preview))
            .route("/agents/{id}/transcript", get(get_transcript))
            .route("/teams", get(get_teams))
            .route("/teams/{name}/tasks", get(get_team_tasks))
            .route("/config-audit/run", post(config_audit))
            .route("/config-audit/last", get(last_config_audit))
            .with_state(core)
    }

    /// Build a Router with default empty state
    fn test_router() -> Router {
        test_router_with_state(test_app_state())
    }

    /// Add an idle agent to the shared state
    fn add_idle_agent(state: &SharedState, id: &str) {
        let mut s = state.write();
        let mut agent = tmai_core::agents::MonitoredAgent::new(
            id.to_string(),
            tmai_core::agents::AgentType::ClaudeCode,
            "Test".to_string(),
            "/tmp".to_string(),
            1234,
            "main".to_string(),
            "window".to_string(),
            0,
            0,
        );
        agent.status = AgentStatus::Idle;
        s.agents.insert(id.to_string(), agent);
        s.agent_order.push(id.to_string());
    }

    #[tokio::test]
    async fn test_get_agents_empty() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let agents: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
        assert!(agents.is_empty());
    }

    #[tokio::test]
    async fn test_approve_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/nonexistent/approve")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_select_choice_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/nonexistent/select")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"choice":1}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_submit_selection_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/nonexistent/submit")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_send_text_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/nonexistent/input")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"text":"hello"}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_get_preview_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents/nonexistent/preview")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_get_teams_empty() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/teams")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let teams: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
        assert!(teams.is_empty());
    }

    #[tokio::test]
    async fn test_get_team_tasks_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/teams/nonexistent/tasks")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_get_team_tasks_path_traversal() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/teams/..%2Fevil/tasks")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_approve_idle_agent_returns_ok() {
        // With the new Facade, approving an idle agent returns Ok (idempotent)
        let state = test_app_state();
        add_idle_agent(&state, "main:0.0");
        let app = test_router_with_state(state);

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/main:0.0/approve")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
    }

    #[tokio::test]
    async fn test_get_agents_with_agent() {
        let state = test_app_state();
        add_idle_agent(&state, "main:0.0");
        let app = test_router_with_state(state);

        let response = app
            .oneshot(
                Request::builder()
                    .uri("/agents")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let agents: Vec<serde_json::Value> = serde_json::from_slice(&body).unwrap();
        assert_eq!(agents.len(), 1);
        assert_eq!(agents[0]["id"].as_str().unwrap().len(), 8); // stable UUID short hash
        assert_eq!(agents[0]["pane_id"], "main:0.0");
        // AgentStatus uses serde externally tagged: unit variants serialize as strings
        assert_eq!(agents[0]["status"], "Idle");
    }

    #[tokio::test]
    async fn test_send_key_not_found() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/nonexistent/key")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"key":"Enter"}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_send_key_invalid_key() {
        let state = test_app_state();
        add_idle_agent(&state, "main:0.0");
        let app = test_router_with_state(state);

        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/agents/main:0.0/key")
                    .header("content-type", "application/json")
                    .body(Body::from(r#"{"key":"Delete"}"#))
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::BAD_REQUEST);
    }

    #[test]
    fn test_is_valid_team_name() {
        assert!(is_valid_team_name("my-team"));
        assert!(is_valid_team_name("team_1"));
        assert!(is_valid_team_name("TeamAlpha"));
        assert!(!is_valid_team_name(""));
        assert!(!is_valid_team_name("../evil"));
        assert!(!is_valid_team_name("team/name"));
        assert!(!is_valid_team_name("team name"));
    }

    #[tokio::test]
    async fn test_config_audit_last_initially_null() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .uri("/config-audit/last")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let result: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(result.is_null());
    }

    #[tokio::test]
    async fn test_config_audit_returns_ok() {
        let app = test_router();
        let response = app
            .oneshot(
                Request::builder()
                    .method("POST")
                    .uri("/config-audit/run")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(response.status(), StatusCode::OK);
        let body = response.into_body().collect().await.unwrap().to_bytes();
        let result: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert!(result["risks"].is_array());
        assert!(result["scanned_at"].is_string());
        assert!(result["files_scanned"].is_number());
    }

    #[test]
    fn test_has_checkbox_format() {
        assert!(has_checkbox_format(&[
            "[ ] Option A".to_string(),
            "[ ] Option B".to_string(),
        ]));
        assert!(!has_checkbox_format(&[
            "Option A".to_string(),
            "Option B".to_string(),
        ]));
    }

    #[test]
    fn test_shell_quote_strips_control_chars() {
        // Normal strings pass through
        assert_eq!(shell_quote("hello"), "hello");
        // Control chars (e.g. \x01, \x1b) are stripped
        assert_eq!(shell_quote("he\x01llo"), "hello");
        assert_eq!(shell_quote("ab\x1bcd"), "abcd");
        // Newlines are preserved
        assert_eq!(shell_quote("a\nb"), "'a\nb'");
        // Tab (0x09) is a control char and stripped
        assert_eq!(shell_quote("a\tb"), "ab");
        // Shell-special chars get quoted
        assert_eq!(shell_quote("hello world"), "'hello world'");
        // Single quotes are escaped
        assert_eq!(shell_quote("it's"), "'it'\\''s'");
    }

    #[test]
    fn test_is_path_within_allowed_scope() {
        // HOME directory should be allowed
        if let Some(home) = dirs::home_dir() {
            let test_path = home.join("some_file.txt");
            assert!(is_path_within_allowed_scope(&test_path, None));
        }
        // Root paths outside HOME should be rejected
        let outside = std::path::Path::new("/etc/passwd");
        assert!(!is_path_within_allowed_scope(outside, None));
    }

    #[tokio::test]
    async fn test_bulk_delete_branches_empty_list() {
        let req = BulkDeleteBranchesRequest {
            repo_path: "/tmp".to_string(),
            branches: vec![],
            delete_remote: false,
        };
        let result = bulk_delete_branches(Json(req)).await;
        assert!(result.is_err());
        let (status, _body) = result.unwrap_err();
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn test_bulk_delete_branches_invalid_repo() {
        let req = BulkDeleteBranchesRequest {
            repo_path: "/nonexistent/repo".to_string(),
            branches: vec!["feature-a".to_string()],
            delete_remote: false,
        };
        let result = bulk_delete_branches(Json(req)).await;
        assert!(result.is_err());
        let (status, _body) = result.unwrap_err();
        assert_eq!(status, StatusCode::NOT_FOUND);
    }

    #[tokio::test]
    async fn test_bulk_delete_branches_invalid_branch_name() {
        // Create a temp git repo so repo_path validation passes
        let tmp = tempfile::tempdir().unwrap();
        let dir = tmp.path().to_str().unwrap();
        std::process::Command::new("git")
            .args(["init", dir])
            .output()
            .unwrap();

        let req = BulkDeleteBranchesRequest {
            repo_path: dir.to_string(),
            branches: vec!["--exec=evil".to_string(), "valid-name".to_string()],
            delete_remote: false,
        };
        let result = bulk_delete_branches(Json(req)).await;
        assert!(result.is_ok());
        let body = result.unwrap().0;
        let results = body["results"].as_array().unwrap();
        // First branch should fail validation (starts with -)
        assert_eq!(results[0]["status"], "error");
        assert!(results[0]["error"]
            .as_str()
            .unwrap()
            .contains("Invalid branch name"));
    }
}