forge-orchestrator 1.8.0

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

const OUTPUT_BUFFER_CAP: usize = 200;
const EVENT_BUFFER_CAP: usize = 50;

/// Number of agent/summary panes in the 2x2 grid.
pub const PANE_COUNT: usize = 4;

/// Maximum rate-limit backoff attempts before marking task as permanently failed.
pub const MAX_BACKOFF_ATTEMPTS: u32 = 5;

/// Rate limit patterns to detect in agent output (provider-specific + generic).
const RATE_LIMIT_PATTERNS: &[&str] = &[
    // Provider-specific (DX-034)
    "usage_limit_reached",
    "no capacity available",
    "rate_limit_error",
    // Generic patterns
    "rate limit",
    "rate_limit",
    "429",
    "quota exceeded",
    "too many requests",
    "resource exhausted",
    "resource_exhausted",
];

/// Builder Mode: tracks when an agent is awaiting task completion (ready-pattern reappearance).
pub struct AwaitingCompletion {
    pub task_id: String,
    pub dispatched_at: Instant,
    pub last_output_at: Instant,
    /// The ready-pattern must disappear (agent started working) before reappearance
    /// counts as completion. Prevents false positives when prompt text sits unsubmitted.
    pub pattern_disappeared: bool,
}

/// Per-agent rate limit backoff tracking.
pub struct BackoffState {
    pub attempt: u32,
    pub next_retry: Option<Instant>,
    pub task_id: String,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DashboardPhase {
    Build,
    Verify,
    Complete,
    Ship,
}

impl std::fmt::Display for DashboardPhase {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DashboardPhase::Build => write!(f, "BUILD"),
            DashboardPhase::Verify => write!(f, "VERIFY"),
            DashboardPhase::Complete => write!(f, "COMPLETE"),
            DashboardPhase::Ship => write!(f, "SHIP"),
        }
    }
}

pub enum AgentEvent {
    Output {
        task_id: String,
        agent: AgentType,
        line: String,
    },
    Completed {
        task_id: String,
        agent: AgentType,
        success: bool,
        exit_code: i32,
    },
    Error {
        task_id: String,
        agent: AgentType,
        message: String,
    },
}

/// Focus target: task board or one of the 4 panes (Claude/Codex/Gemini/Summary).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusArea {
    TaskBoard,
    /// Pane index: 0=Claude, 1=Codex, 2=Gemini, 3=Summary
    Pane(usize),
}

/// Map pane index to agent type (pane 3 = Summary, has no agent).
pub fn pane_agent(index: usize) -> Option<AgentType> {
    match index {
        0 => Some(AgentType::Claude),
        1 => Some(AgentType::Codex),
        2 => Some(AgentType::Gemini),
        _ => None,
    }
}

/// Pane labels for display.
pub fn pane_label(index: usize) -> &'static str {
    match index {
        0 => "Claude",
        1 => "Codex",
        2 => "Antigravity (agy)",
        3 => "Summary",
        _ => "?",
    }
}

pub struct App {
    pub forge_dir: PathBuf,
    pub project_root: PathBuf,
    pub tasks: Vec<Task>,
    pub completed_task_ids: Vec<String>,
    pub agent_outputs: HashMap<AgentType, VecDeque<String>>,
    pub events: VecDeque<String>,
    pub running_task_ids: HashSet<String>,
    /// Maps agent type to the task ID it's currently running
    pub agent_running_task: HashMap<AgentType, String>,
    pub selected_index: usize,
    pub focus: FocusArea,
    pub parallel_limit: usize,
    pub watch_mode: bool,
    pub should_quit: bool,
    pub all_complete: bool,
    /// Current dashboard lifecycle phase (Build → Verify → Complete).
    pub phase: DashboardPhase,
    pub completed_at: Option<Instant>,
    pub started_at: Instant,
    /// Per-pane scroll offset (lines from bottom; 0 = latest output visible).
    pub pane_scroll: [usize; PANE_COUNT],
    /// Per-pane pin: true = user scrolled up, don't auto-scroll on new output.
    pub pane_pinned: [bool; PANE_COUNT],
    /// If Some(i), pane i is expanded to full screen.
    pub expanded_pane: Option<usize>,
    /// Per-agent rate limit backoff tracking.
    pub agent_backoff: HashMap<AgentType, BackoffState>,
    /// Throttle: last time we reloaded task JSONs from disk.
    pub last_task_reload: Instant,
    /// Project name from .forge/state.json for display in header.
    pub project_name: String,
    /// Per-agent pacing: earliest time the next task can be dispatched (subscription mode only).
    pub agent_pacing: HashMap<AgentType, Instant>,
    /// User shell process active (replaces Summary pane when true).
    pub shell_active: bool,
    /// Output buffer for the user shell.
    pub shell_output: VecDeque<String>,
    /// Channel to send keystrokes to the shell's stdin.
    pub shell_input_tx: Option<mpsc::UnboundedSender<String>>,
    /// Per-provider task dispatch count for quota monitoring (DX-037).
    /// Key: AgentType, Value: (dispatched_count, window_start)
    pub provider_quota: HashMap<AgentType, (u32, Instant)>,
    /// DX-024 Stargate: Per-agent PTY session (replaces piped output).
    pub pty_sessions: HashMap<AgentType, PtySession>,
    /// DX-024: Whether Stargate PTY mode is active.
    pub pty_mode: bool,
    /// DX-024: Which pane index is attached for interactive input forwarding.
    pub attached_pane: Option<usize>,
    /// DX-024: PTY session for the user shell (pane 3).
    pub shell_pty: Option<PtySession>,
    /// Terminal dimensions (cols, rows) for PTY resize propagation.
    pub terminal_size: (u16, u16),
    /// DX-050 Builder Mode: tracks which agents are awaiting task completion.
    pub awaiting_completion: HashMap<AgentType, AwaitingCompletion>,
    /// DX-050: Spinner animation frame counter (cycles 0..9 on each tick).
    pub spinner_frame: usize,
    /// DX-052: Quality gate results receiver (from background thread).
    pub quality_gate_rx: Option<std::sync::mpsc::Receiver<Vec<GateResult>>>,
    /// DX-052: True while quality gates are running in background.
    pub quality_gate_pending: bool,
    /// DX-052: Number of gate retry attempts (max 3 before force-transition).
    pub quality_gate_attempts: u32,
    /// W2-C: show the fleet ctx% budget strip (toggle with `b`). Off by default — purely additive.
    pub show_budget: bool,
    /// Cached fleet ctx% rows; refreshed on a throttle so render never spawns tmux subprocesses.
    pub fleet_rows: Vec<crate::fleet::HudRow>,
    /// Throttle: last time the fleet strip was refreshed.
    pub last_fleet_refresh: Instant,
}

impl App {
    pub fn new(
        forge_dir: PathBuf,
        project_root: PathBuf,
        parallel_limit: usize,
        watch_mode: bool,
    ) -> (
        Self,
        mpsc::UnboundedReceiver<AgentEvent>,
        mpsc::UnboundedSender<AgentEvent>,
    ) {
        let (tx, rx) = mpsc::unbounded_channel();

        let mut agent_outputs = HashMap::new();
        agent_outputs.insert(AgentType::Claude, VecDeque::new());
        agent_outputs.insert(AgentType::Codex, VecDeque::new());
        agent_outputs.insert(AgentType::Gemini, VecDeque::new());

        let project_name = {
            let state_mgr = StateManager::new(&forge_dir);
            state_mgr
                .load()
                .map(|s| s.project_name.clone())
                .unwrap_or_default()
        };

        let app = Self {
            forge_dir,
            project_root,
            tasks: Vec::new(),
            completed_task_ids: Vec::new(),
            agent_outputs,
            events: VecDeque::new(),
            running_task_ids: HashSet::new(),
            agent_running_task: HashMap::new(),
            selected_index: 0,
            focus: FocusArea::TaskBoard,
            parallel_limit,
            watch_mode,
            should_quit: false,
            all_complete: false,
            phase: DashboardPhase::Build,
            completed_at: None,
            started_at: Instant::now(),
            pane_scroll: [0; PANE_COUNT],
            pane_pinned: [false; PANE_COUNT],
            expanded_pane: None,
            agent_backoff: HashMap::new(),
            agent_pacing: HashMap::new(),
            last_task_reload: Instant::now(),
            project_name,
            shell_active: false,
            shell_output: VecDeque::new(),
            shell_input_tx: None,
            provider_quota: HashMap::new(),
            pty_sessions: HashMap::new(),
            pty_mode: false,
            attached_pane: None,
            shell_pty: None,
            terminal_size: crossterm::terminal::size().unwrap_or((80, 24)),
            awaiting_completion: HashMap::new(),
            spinner_frame: 0,
            quality_gate_rx: None,
            quality_gate_pending: false,
            quality_gate_attempts: 0,
            show_budget: false,
            fleet_rows: Vec::new(),
            last_fleet_refresh: Instant::now(),
        };

        (app, rx, tx)
    }

    /// W2-C: read the fleet ctx% gauges (read-only, gauge-only) into the cached strip rows.
    pub fn refresh_fleet(&mut self) {
        self.fleet_rows = crate::fleet::read_fleet();
        self.last_fleet_refresh = Instant::now();
    }

    pub fn reload_tasks(&mut self) -> anyhow::Result<()> {
        let task_mgr = TaskManager::new(&self.forge_dir);
        let raw_tasks = task_mgr.list_tasks()?;
        // Sort hierarchically so self.tasks matches the display order in the UI.
        // This ensures selected_index always points to the visually highlighted row.
        self.tasks = crate::tui::ui::hierarchical_sort(&raw_tasks);
        self.completed_task_ids = task_mgr.get_completed_task_ids()?;
        // Keep state.json task_summary in sync with actual task files.
        let state_mgr = StateManager::new(&self.forge_dir);
        state_mgr.refresh_task_summary().ok();
        Ok(())
    }

    /// Persist the current dashboard phase to state.json.
    fn persist_phase(&self) {
        let state_mgr = StateManager::new(&self.forge_dir);
        if let Ok(mut state) = state_mgr.load() {
            state.current_phase = Some(format!("{:?}", self.phase).to_lowercase());
            state.updated_at = chrono::Utc::now();
            state_mgr.save(&state).ok();
        }
    }

    pub fn schedule_unblocked_tasks(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        if self.watch_mode {
            return;
        }

        let slots = self
            .parallel_limit
            .saturating_sub(self.running_task_ids.len());
        if slots == 0 {
            return;
        }

        // Load scheduler config for pacing
        let state_mgr = StateManager::new(&self.forge_dir);
        let scheduler = state_mgr.load().map(|s| s.scheduler).unwrap_or_default();

        let now = Instant::now();

        // In PTY mode, each agent can only run 1 task at a time (TUI is single-threaded).
        // Track which agents are already busy or claimed this scheduling round.
        let mut agents_busy: HashSet<AgentType> = if self.pty_mode {
            self.agent_running_task.keys().cloned().collect()
        } else {
            HashSet::new()
        };

        let candidates: Vec<Task> = self
            .tasks
            .iter()
            .filter(|t| {
                t.status == TaskStatus::Pending
                    && !t.is_blocked(&self.completed_task_ids)
                    && !self.running_task_ids.contains(&t.id)
                    && t.phase != Some(TaskPhase::Uat) // UAT tasks are human-only
            })
            .filter(|t| {
                // Skip tasks whose agent is in backoff
                let agent = t.assigned_to.clone().unwrap_or(AgentType::Claude);
                let agent = if agent == AgentType::Any {
                    AgentType::Claude
                } else {
                    agent
                };
                !self.is_agent_in_backoff(&agent)
            })
            .filter(|t| {
                // DX-033: Skip tasks whose agent is in subscription pacing cooldown
                let agent = t.assigned_to.clone().unwrap_or(AgentType::Claude);
                let agent = if agent == AgentType::Any {
                    AgentType::Claude
                } else {
                    agent
                };
                let agent_name = agent.to_string().to_lowercase();
                let auth_mode = state_mgr
                    .get_agent_auth(&agent_name)
                    .unwrap_or_else(|_| "subscription".to_string());
                if auth_mode == "api" {
                    return true; // API mode = no pacing
                }
                // Check if agent is still in pacing cooldown
                if let Some(ready_at) = self.agent_pacing.get(&agent)
                    && now < *ready_at
                {
                    return false; // Still cooling down
                }
                true
            })
            .filter(|t| {
                // PTY mode: 1 task per agent — skip if agent already busy or claimed
                if !self.pty_mode {
                    return true;
                }
                let agent = t.assigned_to.clone().unwrap_or(AgentType::Claude);
                let agent = if agent == AgentType::Any {
                    AgentType::Claude
                } else {
                    agent
                };
                if agents_busy.contains(&agent) {
                    return false;
                }
                // Claim this agent for this scheduling round
                agents_busy.insert(agent);
                true
            })
            .take(slots)
            .cloned()
            .collect();

        for task in candidates {
            let agent = task.assigned_to.clone().unwrap_or(AgentType::Claude);
            let agent = if agent == AgentType::Any {
                AgentType::Claude
            } else {
                agent
            };

            // DX-033: Set pacing cooldown for subscription-mode agents
            let agent_name = agent.to_string().to_lowercase();
            let auth_mode = state_mgr
                .get_agent_auth(&agent_name)
                .unwrap_or_else(|_| "subscription".to_string());
            if auth_mode == "subscription" {
                let delay_secs =
                    rand::rng().random_range(scheduler.pacing_min_secs..=scheduler.pacing_max_secs);
                self.agent_pacing.insert(
                    agent.clone(),
                    Instant::now() + std::time::Duration::from_secs(delay_secs),
                );
                self.push_event(&format!(
                    "Pacing {}: next task in {}s (subscription mode)",
                    agent, delay_secs
                ));
            }

            self.spawn_task(&task, tx);
        }
    }

    pub fn handle_agent_event(
        &mut self,
        event: AgentEvent,
        tx: &mpsc::UnboundedSender<AgentEvent>,
    ) -> anyhow::Result<()> {
        match event {
            AgentEvent::Output {
                ref task_id,
                ref agent,
                ref line,
            } if task_id == "__shell__" => {
                self.shell_output.push_back(line.clone());
                while self.shell_output.len() > OUTPUT_BUFFER_CAP {
                    self.shell_output.pop_front();
                }
                return Ok(());
            }
            AgentEvent::Output { agent, line, .. } => {
                // DX-024: In PTY mode, skip agent_outputs insertion —
                // output is captured by the PTY session's vt100 terminal emulator.
                // The empty sentinel line just wakes the event loop to redraw.
                if self.pty_mode && self.pty_sessions.contains_key(&agent) {
                    // DX-050: Update last_output_at for completion detection
                    if let Some(awaiting) = self.awaiting_completion.get_mut(&agent) {
                        awaiting.last_output_at = Instant::now();
                    }
                    return Ok(());
                }

                let buf = self.agent_outputs.entry(agent.clone()).or_default();
                if buf.len() >= OUTPUT_BUFFER_CAP {
                    buf.pop_front();
                }
                buf.push_back(line);

                // If the pane for this agent is pinned, keep scroll offset stable.
                // If not pinned, auto-scroll stays at 0 (no-op needed).
                // When pinned and buffer overflows, the removed front line means
                // the scroll offset should decrease by 1 to keep the same view.
                if let Some(idx) = agent_pane_index(&agent)
                    && self.pane_pinned[idx]
                    && self.pane_scroll[idx] > 0
                {
                    self.pane_scroll[idx] = self.pane_scroll[idx].saturating_sub(1);
                }
            }
            AgentEvent::Completed { ref task_id, .. } if task_id == "__shell__" => {
                self.shell_active = false;
                self.shell_input_tx = None;
                self.shell_pty = None;
                // Clear attached if we were attached to shell pane
                if self.attached_pane == Some(3) {
                    self.attached_pane = None;
                }
                self.push_event("User shell closed");
                return Ok(());
            }
            AgentEvent::Completed {
                task_id,
                agent,
                success,
                exit_code,
            } => {
                self.running_task_ids.remove(&task_id);
                self.agent_running_task.remove(&agent);

                // DX-024/DX-050: Only remove PTY session if the process truly exited.
                // In Builder Mode, check_pty_completion sends synthetic Completed events
                // while the TUI process is still alive. Keep the PTY so it can accept
                // the next task dispatch.
                let process_exited = self
                    .pty_sessions
                    .get_mut(&agent)
                    .map(|s| s.try_wait().is_some())
                    .unwrap_or(true);

                // Capture PTY output before removing session — helps debug
                // crashes like Codex exiting immediately with no visible error.
                // Capture PTY output before session cleanup — used for
                // results/ saving (success) and crash diagnosis (failure).
                let crash_output = if process_exited {
                    self.pty_sessions.get(&agent).map(|s| {
                        let lines = s.snapshot();
                        lines
                            .iter()
                            .map(|l| {
                                l.spans
                                    .iter()
                                    .map(|sp| sp.text.as_str())
                                    .collect::<String>()
                            })
                            .filter(|l| !l.trim().is_empty())
                            .collect::<Vec<_>>()
                            .join("\n")
                    })
                } else {
                    None
                };

                if process_exited {
                    self.pty_sessions.remove(&agent);
                    if let Some(pane_idx) = agent_pane_index(&agent)
                        && self.attached_pane == Some(pane_idx)
                    {
                        self.attached_pane = None;
                    }
                }

                tracing::debug!(
                    task_id = %task_id, agent = %agent,
                    success = success, exit_code = exit_code,
                    "Task completed"
                );

                let task_mgr = TaskManager::new(&self.forge_dir);
                let state_mgr = StateManager::new(&self.forge_dir);
                let event_logger = EventLogger::new(&self.forge_dir);

                // Compute task duration from dispatch time
                let duration_ms = self
                    .awaiting_completion
                    .get(&agent)
                    .map(|a| a.dispatched_at.elapsed().as_millis() as u64);

                // Save agent output to .forge/results/ (PTY or piped mode)
                let output_text = if let Some(ref text) = crash_output {
                    text.clone()
                } else {
                    // Piped mode: flush agent_outputs buffer
                    self.agent_outputs
                        .get(&agent)
                        .map(|buf| buf.iter().cloned().collect::<Vec<_>>().join("\n"))
                        .unwrap_or_default()
                };
                if !output_text.is_empty() {
                    save_pty_result(&self.forge_dir, &task_id, &output_text);
                }

                if success {
                    // Reset backoff on success
                    self.agent_backoff.remove(&agent);

                    if let Ok(task) = task_mgr.get_task(&task_id) {
                        let mut updated = task;
                        updated.status = TaskStatus::Completed;
                        updated.completed_at = Some(chrono::Utc::now());
                        updated.completed_by = Some(agent.clone());
                        updated.completed_by_source = Some(CompletedBySource::Engine);
                        updated.updated_at = chrono::Utc::now();
                        task_mgr.update_task(&updated).ok();
                        state_mgr.unlock_files(&task_id).ok();

                        // Cross-agent verification: when V-xxx completes,
                        // stamp verified_by/verified_at on its parent T-xxx.
                        if updated.phase == Some(TaskPhase::Verify)
                            && let Some(ref parent_id) = updated.parent_task
                            && let Ok(mut parent) = task_mgr.get_task(parent_id)
                        {
                            parent.verified_by = updated.assigned_to.clone();
                            parent.verified_at = Some(chrono::Utc::now());
                            parent.updated_at = chrono::Utc::now();
                            task_mgr.update_task(&parent).ok();
                        }

                        // DX-028: Auto-commit after task completion
                        self.git_auto_commit(&updated, &agent);

                        // Auto-capture knowledge from completed task
                        let knowledge_mgr = KnowledgeManager::new(&self.forge_dir);
                        let knowledge_content = format!(
                            "Task {} ({}) completed by {}.\n\nDescription: {}",
                            updated.id, updated.title, agent, updated.description,
                        );
                        let entry = KnowledgeEntry::new(
                            format!("{}: {}", updated.id, updated.title),
                            knowledge_content,
                            &crate::brain::KnowledgeCategory::Learning,
                        )
                        .with_task(&task_id)
                        .with_agent(agent.to_string());
                        knowledge_mgr.capture(&entry).ok();

                        let dur_str = duration_ms
                            .map(|ms| format!("{}s", ms / 1000))
                            .unwrap_or_else(|| "?s".to_string());
                        let event_msg = format!(
                            "{} completed by {} (exit {}, {})",
                            task_id, agent, exit_code, dur_str
                        );
                        self.push_event(&event_msg);
                        let mut event = ForgeEvent::new(EventType::TaskCompleted, event_msg)
                            .with_task(&task_id)
                            .with_agent(agent)
                            .with_exit_code(exit_code);
                        if let Some(ms) = duration_ms {
                            event = event.with_duration_ms(ms);
                        }
                        event_logger.log(&event).ok();
                    }
                } else {
                    // Check if failure is due to rate limiting
                    let rate_limited = self.agent_outputs.get(&agent).is_some_and(is_rate_limited);

                    if rate_limited {
                        let attempt = {
                            let backoff =
                                self.agent_backoff
                                    .entry(agent.clone())
                                    .or_insert(BackoffState {
                                        attempt: 0,
                                        next_retry: None,
                                        task_id: String::new(),
                                    });
                            backoff.attempt += 1;
                            backoff.attempt
                        };

                        if attempt >= MAX_BACKOFF_ATTEMPTS {
                            // Max retries exhausted — permanent failure
                            self.agent_backoff.remove(&agent);

                            if let Ok(task) = task_mgr.get_task(&task_id) {
                                let mut updated = task;
                                updated.status = TaskStatus::Failed;
                                updated.updated_at = chrono::Utc::now();
                                task_mgr.update_task(&updated).ok();
                                state_mgr.unlock_files(&task_id).ok();
                            }

                            let event_msg = format!(
                                "{} failed after {} rate limit retries by {}",
                                task_id, MAX_BACKOFF_ATTEMPTS, agent
                            );
                            self.push_event(&event_msg);
                            let mut ev = ForgeEvent::new(EventType::TaskFailed, event_msg)
                                .with_task(&task_id)
                                .with_agent(agent)
                                .with_exit_code(exit_code);
                            if let Some(ms) = duration_ms {
                                ev = ev.with_duration_ms(ms);
                            }
                            event_logger.log(&ev).ok();
                        } else {
                            // Reset task to pending and apply backoff delay
                            if let Ok(task) = task_mgr.get_task(&task_id) {
                                let mut updated = task;
                                updated.status = TaskStatus::Pending;
                                updated.updated_at = chrono::Utc::now();
                                task_mgr.update_task(&updated).ok();
                                state_mgr.unlock_files(&task_id).ok();
                            }

                            let delay = compute_backoff_delay(attempt);
                            let delay_secs = delay.as_secs();
                            let backoff = self.agent_backoff.get_mut(&agent).unwrap();
                            backoff.next_retry = Some(Instant::now() + delay);
                            backoff.task_id = task_id.clone();

                            let event_msg = format!(
                                "{} rate limited. Retrying in {}s (attempt {}/{})",
                                task_id, delay_secs, attempt, MAX_BACKOFF_ATTEMPTS
                            );
                            self.push_event(&event_msg);
                            let mut ev = ForgeEvent::new(EventType::TaskFailed, event_msg)
                                .with_task(&task_id)
                                .with_agent(agent)
                                .with_exit_code(exit_code);
                            if let Some(ms) = duration_ms {
                                ev = ev.with_duration_ms(ms);
                            }
                            event_logger.log(&ev).ok();
                        }
                    } else {
                        // Normal failure (not rate limited)
                        let failed_task = if let Ok(task) = task_mgr.get_task(&task_id) {
                            let mut updated = task;
                            updated.status = TaskStatus::Failed;
                            updated.updated_at = chrono::Utc::now();
                            task_mgr.update_task(&updated).ok();
                            state_mgr.unlock_files(&task_id).ok();
                            Some(updated)
                        } else {
                            None
                        };

                        let event_msg =
                            format!("{} failed by {} (exit {})", task_id, agent, exit_code);
                        self.push_event(&event_msg);
                        // Log captured PTY output for crash diagnosis
                        if let Some(ref output) = crash_output {
                            let truncated = if output.len() > 200 {
                                &output[..200]
                            } else {
                                output
                            };
                            if !truncated.is_empty() {
                                self.push_event(&format!("  PTY output: {}", truncated));
                            }
                        }
                        {
                            let mut ev = ForgeEvent::new(EventType::TaskFailed, event_msg)
                                .with_task(&task_id)
                                .with_agent(agent)
                                .with_exit_code(exit_code);
                            if let Some(ms) = duration_ms {
                                ev = ev.with_duration_ms(ms);
                            }
                            event_logger.log(&ev).ok();
                        }

                        // Test/fix loop: generate fix + re-verify for failed verify tasks
                        if let Some(failed) = &failed_task {
                            self.handle_verify_failure(failed);
                        }
                    }
                }

                self.reload_tasks()?;
                self.check_phase_transition();
                self.schedule_unblocked_tasks(tx);
            }
            AgentEvent::Error {
                task_id,
                agent,
                message,
            } => {
                self.running_task_ids.remove(&task_id);
                self.agent_running_task.remove(&agent);

                let task_mgr = TaskManager::new(&self.forge_dir);
                let state_mgr = StateManager::new(&self.forge_dir);

                if let Ok(task) = task_mgr.get_task(&task_id) {
                    let mut updated = task;
                    updated.status = TaskStatus::Failed;
                    updated.updated_at = chrono::Utc::now();
                    task_mgr.update_task(&updated).ok();
                    state_mgr.unlock_files(&task_id).ok();
                }

                let event_msg = format!("{} error ({}): {}", task_id, agent, message);
                self.push_event(&event_msg);

                self.reload_tasks()?;
                self.check_phase_transition();
                self.schedule_unblocked_tasks(tx);
            }
        }
        Ok(())
    }

    pub fn handle_key(&mut self, key: KeyEvent, tx: &mpsc::UnboundedSender<AgentEvent>) {
        use crossterm::event::KeyModifiers;
        // DX-024: Attached mode — forward ALL keys (except Esc/Ctrl+F) to the PTY
        if let Some(pane_idx) = self.attached_pane {
            if key.code == KeyCode::Esc {
                self.attached_pane = None;
                return;
            }
            // Ctrl+F: toggle expand/collapse while attached
            if key.code == KeyCode::Char('f') && key.modifiers.contains(KeyModifiers::CONTROL) {
                if self.expanded_pane.is_some() {
                    self.expanded_pane = None;
                } else {
                    self.expanded_pane = Some(pane_idx);
                }
                self.resize_pty_for_pane(pane_idx);
                return;
            }
            let bytes = key_event_to_bytes(&key);
            if !bytes.is_empty() {
                if pane_idx == 3 {
                    // Shell PTY
                    if let Some(ref session) = self.shell_pty {
                        session.write(&bytes);
                    }
                } else if let Some(agent) = pane_agent(pane_idx)
                    && let Some(session) = self.pty_sessions.get(&agent)
                {
                    session.write(&bytes);
                }
            }
            return;
        }

        // In expanded pane mode, Esc or Enter collapses back to grid
        if self.expanded_pane.is_some() {
            match key.code {
                KeyCode::Esc | KeyCode::Enter => {
                    let was_expanded = self.expanded_pane;
                    self.expanded_pane = None;
                    // Resize PTY back to small pane dimensions
                    if let Some(idx) = was_expanded {
                        self.resize_pty_for_pane(idx);
                    }
                    return;
                }
                KeyCode::Char('q') => {
                    self.should_quit = true;
                    return;
                }
                // Allow scrolling in expanded mode
                KeyCode::Up => {
                    if let Some(idx) = self.expanded_pane {
                        self.scroll_pane_up(idx);
                    }
                    return;
                }
                KeyCode::Down => {
                    if let Some(idx) = self.expanded_pane {
                        self.scroll_pane_down(idx);
                    }
                    return;
                }
                KeyCode::Home => {
                    if let Some(idx) = self.expanded_pane {
                        self.scroll_pane_to_top(idx);
                    }
                    return;
                }
                KeyCode::End => {
                    if let Some(idx) = self.expanded_pane {
                        self.scroll_pane_to_bottom(idx);
                    }
                    return;
                }
                // Allow 'i' to fall through to attach handler in expanded mode
                KeyCode::Char('i') => {}
                _ => return,
            }
        }

        // Route keystrokes to shell when pane 3 is focused and shell is active
        if self.focus == FocusArea::Pane(3)
            && self.shell_active
            && let Some(shell_tx) = &self.shell_input_tx
        {
            match key.code {
                KeyCode::Char('d') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    let _ = shell_tx.send("exit\n".to_string());
                    return;
                }
                KeyCode::Char('c') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                    let _ = shell_tx.send("\x03".to_string());
                    return;
                }
                KeyCode::Char('q') => {
                    // q in shell types 'q', doesn't quit dashboard
                    let _ = shell_tx.send("q".to_string());
                    return;
                }
                KeyCode::Char(c) => {
                    let _ = shell_tx.send(c.to_string());
                    return;
                }
                KeyCode::Enter => {
                    let _ = shell_tx.send("\n".to_string());
                    return;
                }
                KeyCode::Backspace => {
                    let _ = shell_tx.send("\x7f".to_string());
                    return;
                }
                KeyCode::Tab => {
                    let _ = shell_tx.send("\t".to_string());
                    return;
                }
                // Esc exits shell focus — falls through to normal handling
                KeyCode::Esc => {}
                _ => return,
            }
        }

        match key.code {
            KeyCode::Char('q') => {
                self.should_quit = true;
            }
            KeyCode::Esc => {
                // Esc from a pane returns to task board; from task board quits
                match self.focus {
                    FocusArea::Pane(_) => self.focus = FocusArea::TaskBoard,
                    FocusArea::TaskBoard => self.should_quit = true,
                }
            }
            KeyCode::Tab => {
                self.focus = match self.focus {
                    FocusArea::TaskBoard => FocusArea::Pane(0),
                    FocusArea::Pane(i) if i + 1 < PANE_COUNT => FocusArea::Pane(i + 1),
                    FocusArea::Pane(_) => FocusArea::TaskBoard,
                };
            }
            KeyCode::BackTab => {
                // Shift+Tab: reverse cycle
                self.focus = match self.focus {
                    FocusArea::TaskBoard => FocusArea::Pane(PANE_COUNT - 1),
                    FocusArea::Pane(0) => FocusArea::TaskBoard,
                    FocusArea::Pane(i) => FocusArea::Pane(i - 1),
                };
            }
            KeyCode::Up => match self.focus {
                FocusArea::TaskBoard => {
                    if self.selected_index > 0 {
                        self.selected_index -= 1;
                    }
                }
                FocusArea::Pane(idx) => self.scroll_pane_up(idx),
            },
            KeyCode::Down => match self.focus {
                FocusArea::TaskBoard => {
                    if self.selected_index + 1 < self.tasks.len() {
                        self.selected_index += 1;
                    }
                }
                FocusArea::Pane(idx) => self.scroll_pane_down(idx),
            },
            KeyCode::Home => match self.focus {
                FocusArea::TaskBoard => self.selected_index = 0,
                FocusArea::Pane(idx) => self.scroll_pane_to_top(idx),
            },
            KeyCode::End => match self.focus {
                FocusArea::TaskBoard => {
                    if !self.tasks.is_empty() {
                        self.selected_index = self.tasks.len() - 1;
                    }
                }
                FocusArea::Pane(idx) => self.scroll_pane_to_bottom(idx),
            },
            KeyCode::PageUp if self.focus == FocusArea::TaskBoard => {
                self.selected_index = self.selected_index.saturating_sub(10);
            }
            KeyCode::PageDown if self.focus == FocusArea::TaskBoard && !self.tasks.is_empty() => {
                self.selected_index = (self.selected_index + 10).min(self.tasks.len() - 1);
            }
            KeyCode::Enter | KeyCode::Char('f') => {
                if let FocusArea::Pane(idx) = self.focus {
                    self.expanded_pane = Some(idx);
                    self.resize_pty_for_pane(idx);
                }
            }
            KeyCode::Char('a') if self.pty_mode && self.focus == FocusArea::TaskBoard => {
                self.dispatch_to_tui(tx);
            }
            KeyCode::Char('c') if self.focus == FocusArea::TaskBoard => {
                self.cycle_agent_assignment();
            }
            // W2-C: toggle the fleet ctx% budget strip; refresh immediately on enable.
            KeyCode::Char('b') => {
                self.show_budget = !self.show_budget;
                if self.show_budget {
                    self.refresh_fleet();
                }
            }
            KeyCode::Char('r') if self.focus == FocusArea::TaskBoard => {
                self.retry_selected_task(tx);
            }
            KeyCode::Char('s') | KeyCode::Char('+')
                if self.focus == FocusArea::TaskBoard
                    || matches!(self.focus, FocusArea::Pane(0..=2)) =>
            {
                if !self.shell_active {
                    self.spawn_shell(tx);
                }
                self.focus = FocusArea::Pane(3);
            }
            // DX-024: 'i' attaches to focused PTY pane for interactive input
            KeyCode::Char('i') => {
                if self.pty_mode
                    && let FocusArea::Pane(idx) = self.focus
                {
                    let has_pty = if idx == 3 {
                        self.shell_pty.is_some()
                    } else {
                        pane_agent(idx)
                            .map(|a| self.pty_sessions.contains_key(&a))
                            .unwrap_or(false)
                    };
                    if has_pty {
                        self.attached_pane = Some(idx);
                    }
                }
            }
            _ => {}
        }
    }

    fn scroll_pane_up(&mut self, idx: usize) {
        let max = self.pane_buffer_len(idx);
        if self.pane_scroll[idx] < max.saturating_sub(1) {
            self.pane_scroll[idx] += 1;
            self.pane_pinned[idx] = true;
        }
    }

    fn scroll_pane_down(&mut self, idx: usize) {
        if self.pane_scroll[idx] > 0 {
            self.pane_scroll[idx] -= 1;
            if self.pane_scroll[idx] == 0 {
                self.pane_pinned[idx] = false;
            }
        }
    }

    fn scroll_pane_to_top(&mut self, idx: usize) {
        let max = self.pane_buffer_len(idx);
        self.pane_scroll[idx] = max.saturating_sub(1);
        if self.pane_scroll[idx] > 0 {
            self.pane_pinned[idx] = true;
        }
    }

    fn scroll_pane_to_bottom(&mut self, idx: usize) {
        self.pane_scroll[idx] = 0;
        self.pane_pinned[idx] = false;
    }

    /// Get the number of lines in a pane's buffer.
    pub fn pane_buffer_len(&self, idx: usize) -> usize {
        match pane_agent(idx) {
            Some(agent) => {
                if self.pty_mode {
                    // In PTY mode, read line count from the PTY session
                    self.pty_sessions
                        .get(&agent)
                        .map(|s| s.line_count())
                        .unwrap_or(0)
                } else {
                    self.agent_outputs.get(&agent).map(|b| b.len()).unwrap_or(0)
                }
            }
            None => {
                // Pane 3: shell PTY line count
                if self.pty_mode && idx == 3 {
                    self.shell_pty.as_ref().map(|s| s.line_count()).unwrap_or(0)
                } else {
                    0
                }
            }
        }
    }

    /// Check if an agent is currently in backoff (waiting to retry after rate limit).
    pub fn is_agent_in_backoff(&self, agent: &AgentType) -> bool {
        self.agent_backoff
            .get(agent)
            .and_then(|state| state.next_retry)
            .is_some_and(|t| Instant::now() < t)
    }

    /// Check backoff timers and re-schedule when expired.
    pub fn check_backoff_timers(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let now = Instant::now();
        let mut expired = Vec::new();

        for (agent, state) in &mut self.agent_backoff {
            if state.next_retry.is_some_and(|t| now >= t) {
                state.next_retry = None;
                expired.push((agent.clone(), state.task_id.clone()));
            }
        }

        for (agent, task_id) in &expired {
            self.push_event(&format!(
                "Backoff expired for {}. Re-scheduling {}...",
                agent, task_id
            ));
        }

        if !expired.is_empty() {
            self.schedule_unblocked_tasks(tx);
        }
    }

    /// DX-050 Builder Mode: detect task completion in full TUI mode.
    /// Two detection methods (checked in priority order):
    /// 1. **Signal file** (reliable): agent creates `.forge/signals/T-XXX.complete`
    /// 2. **Heuristic** (fallback): ready-pattern reappears + 10s min work + 3s quiet
    fn check_pty_completion(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let now = Instant::now();
        let mut completed: Vec<AgentType> = Vec::new();
        let signals_dir = self.forge_dir.join("signals");

        for (agent, awaiting) in &mut self.awaiting_completion {
            // Method 1: Check for signal file (instant, no timing requirements)
            let signal_file = signals_dir.join(format!("{}.complete", awaiting.task_id));
            if signal_file.exists() {
                // Clean up signal file
                std::fs::remove_file(&signal_file).ok();
                completed.push(agent.clone());
                continue;
            }

            // Get the agent's ready pattern
            let pattern = match agent {
                AgentType::Claude | AgentType::Any => ClaudeAdapter.ready_pattern(),
                AgentType::Codex => CodexAdapter.ready_pattern(),
                AgentType::Gemini => GeminiAdapter.ready_pattern(),
            };

            // Track pattern disappearance — agent started working when prompt vanishes
            if !awaiting.pattern_disappeared {
                if let Some(session) = self.pty_sessions.get(agent)
                    && let Some(pat) = pattern
                    && !session.has_pattern_in_last_n(pat, 10)
                {
                    awaiting.pattern_disappeared = true;
                }
                // Can't complete until pattern has disappeared and reappeared
                continue;
            }

            // Method 2: Heuristic — ready-pattern REAPPEARANCE + timing
            // Must have been working for at least 10s
            if now.duration_since(awaiting.dispatched_at) < Duration::from_secs(10) {
                continue;
            }
            // Output must have been quiet for at least 3s
            if now.duration_since(awaiting.last_output_at) < Duration::from_secs(3) {
                continue;
            }
            // Check if ready-pattern reappears (agent returned to prompt)
            if let Some(session) = self.pty_sessions.get(agent)
                && let Some(pat) = pattern
                && session.has_pattern_in_last_n(pat, 10)
            {
                completed.push(agent.clone());
            }
        }

        // Process completions
        for agent in completed {
            if let Some(awaiting) = self.awaiting_completion.remove(&agent) {
                let duration = now.duration_since(awaiting.dispatched_at);
                let secs = duration.as_secs();
                self.push_event(&format!(
                    "{} completed by {} ({}s, builder mode)",
                    awaiting.task_id, agent, secs
                ));
                // Send synthetic Completed event
                let _ = tx.send(AgentEvent::Completed {
                    task_id: awaiting.task_id,
                    agent,
                    success: true,
                    exit_code: 0,
                });
            }
        }
    }

    /// Build the completion signal instruction to append to task prompts.
    fn completion_signal_instruction(forge_dir: &std::path::Path, task_id: &str) -> String {
        let signals_dir = forge_dir.join("signals");
        format!(
            " When you have fully completed this task, run this bash command: mkdir -p {} && touch {}/{}.complete",
            signals_dir.display(),
            signals_dir.display(),
            task_id
        )
    }

    /// Handle a tick event: throttled task reload, backoff checks, completion detection.
    pub fn handle_tick(
        &mut self,
        agent_tx: &mpsc::UnboundedSender<AgentEvent>,
    ) -> anyhow::Result<()> {
        if self.last_task_reload.elapsed() > std::time::Duration::from_secs(2) {
            self.reload_tasks()?;
            self.last_task_reload = Instant::now();
            // Check phase transitions on each reload
            self.check_phase_transition();
        }
        // W2-C: refresh the fleet ctx% strip on a throttle, and ONLY while it is shown — so the
        // dashboard spawns tmux capture subprocesses at most every 10s, and not at all by default.
        if self.show_budget
            && self.last_fleet_refresh.elapsed() > std::time::Duration::from_secs(10)
        {
            self.refresh_fleet();
        }
        self.check_backoff_timers(agent_tx);
        if self.pty_mode {
            self.check_pty_completion(agent_tx);
        }
        // Periodic scheduling: pick up tasks that were delayed by pacing cooldowns.
        // schedule_unblocked_tasks() is normally only called on completion/error events,
        // so pacing-delayed tasks would never get dispatched without this.
        if !self.watch_mode && !self.all_complete {
            self.schedule_unblocked_tasks(agent_tx);
        }
        self.spinner_frame = (self.spinner_frame + 1) % 10;
        // Ship phase can fire even with empty tasks (after clean_state)
        if !self.watch_mode
            && !self.all_complete
            && self.running_task_ids.is_empty()
            && self.phase == DashboardPhase::Ship
        {
            self.all_complete = true;
            self.completed_at = Some(Instant::now());
        }
        if !self.watch_mode
            && !self.all_complete
            && self.running_task_ids.is_empty()
            && !self.tasks.is_empty()
            && self.is_all_done()
        {
            // All tasks done but phase hasn't transitioned yet — trigger it
            self.check_phase_transition();
            if self.phase == DashboardPhase::Ship {
                self.all_complete = true;
                self.completed_at = Some(Instant::now());
            }
        }
        Ok(())
    }

    /// DX-024: Handle terminal resize — propagate dimensions to all active PTYs.
    pub fn handle_resize(&mut self, cols: u16, rows: u16) {
        self.terminal_size = (cols, rows);
        if !self.pty_mode {
            return;
        }
        let (pane_cols, pane_rows) = self.estimate_pane_size();
        for session in self.pty_sessions.values() {
            let _ = session.resize(pane_cols, pane_rows);
        }
        if let Some(ref shell) = self.shell_pty {
            let _ = shell.resize(pane_cols, pane_rows);
        }
    }

    /// DX-024: Estimate the inner dimensions of a single pane from terminal size.
    /// Layout: 2x2 grid occupying ~50% of terminal height, each pane is half width.
    pub fn estimate_pane_size(&self) -> (u16, u16) {
        let (cols, rows) = self.terminal_size;
        // Each pane: half the terminal width minus borders (2)
        let pane_cols = (cols / 2).saturating_sub(2).max(10);
        // Agent pane area is ~50% of terminal, split into 2 rows, minus borders
        let pane_rows = (rows / 4).saturating_sub(2).max(5);
        (pane_cols, pane_rows)
    }

    /// Estimate expanded pane size (nearly full terminal).
    fn estimate_expanded_pane_size(&self) -> (u16, u16) {
        let (cols, rows) = self.terminal_size;
        // Full width minus borders, nearly full height minus header/footer
        let pane_cols = cols.saturating_sub(4).max(10);
        let pane_rows = rows.saturating_sub(8).max(10);
        (pane_cols, pane_rows)
    }

    /// Resize the PTY for a pane based on current expand state.
    fn resize_pty_for_pane(&self, pane_idx: usize) {
        if !self.pty_mode {
            return;
        }
        let (cols, rows) = if self.expanded_pane.is_some() {
            self.estimate_expanded_pane_size()
        } else {
            self.estimate_pane_size()
        };

        // Map pane index to agent type
        let agent = match pane_idx {
            0 => Some(AgentType::Claude),
            1 => Some(AgentType::Codex),
            2 => Some(AgentType::Gemini),
            3 => None, // Shell pane
            _ => None,
        };

        if pane_idx == 3 {
            if let Some(ref shell) = self.shell_pty {
                let _ = shell.resize(cols, rows);
            }
        } else if let Some(agent) = agent
            && let Some(session) = self.pty_sessions.get(&agent)
        {
            let _ = session.resize(cols, rows);
        }
    }

    /// Spawn a user shell in pane 3 (replaces Summary).
    pub fn spawn_shell(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        if self.shell_active {
            return;
        }

        let shell = default_shell(
            cfg!(windows),
            std::env::var("SHELL").ok(),
            std::env::var("COMSPEC").ok(),
        );

        // DX-024: PTY mode — spawn shell with a real PTY
        if self.pty_mode {
            self.spawn_shell_pty(&shell, tx);
            return;
        }

        self.spawn_shell_piped(&shell, tx);
    }

    /// Spawn shell using PTY (Stargate mode).
    fn spawn_shell_pty(&mut self, shell: &str, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let mut cmd = CommandBuilder::new(shell);
        cmd.cwd(&self.project_root);
        cmd.env("TERM", "xterm-256color");

        let (pane_cols, pane_rows) = self.estimate_pane_size();
        let size = PtySize {
            rows: pane_rows,
            cols: pane_cols,
            pixel_width: 0,
            pixel_height: 0,
        };

        match PtySession::spawn(
            cmd,
            size,
            tx.clone(),
            "__shell__".to_string(),
            AgentType::Any,
            500,
        ) {
            Ok(session) => {
                self.shell_pty = Some(session);
                self.shell_active = true;
                self.shell_output.clear();
                self.push_event("PTY shell opened (i:Attach | Esc:Detach)");
            }
            Err(e) => {
                self.push_event(&format!("PTY shell failed, falling back: {}", e));
                self.spawn_shell_piped(shell, tx);
            }
        }
    }

    /// Spawn shell using piped I/O (legacy mode).
    fn spawn_shell_piped(&mut self, shell: &str, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let mut cmd = TokioCommand::new(shell);
        cmd.current_dir(&self.project_root)
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());

        match cmd.spawn() {
            Ok(mut child) => {
                let (input_tx, mut input_rx) = mpsc::unbounded_channel::<String>();
                self.shell_input_tx = Some(input_tx);

                if let Some(mut stdin) = child.stdin.take() {
                    tokio::spawn(async move {
                        use tokio::io::AsyncWriteExt;
                        while let Some(text) = input_rx.recv().await {
                            if stdin.write_all(text.as_bytes()).await.is_err() {
                                break;
                            }
                            let _ = stdin.flush().await;
                        }
                    });
                }

                if let Some(stdout) = child.stdout.take() {
                    let tx_out = tx.clone();
                    tokio::spawn(async move {
                        let mut lines = tokio::io::BufReader::new(stdout).lines();
                        while let Ok(Some(line)) = lines.next_line().await {
                            if tx_out
                                .send(AgentEvent::Output {
                                    task_id: "__shell__".to_string(),
                                    agent: AgentType::Any,
                                    line,
                                })
                                .is_err()
                            {
                                break;
                            }
                        }
                    });
                }

                if let Some(stderr) = child.stderr.take() {
                    let tx_err = tx.clone();
                    tokio::spawn(async move {
                        let mut lines = tokio::io::BufReader::new(stderr).lines();
                        while let Ok(Some(line)) = lines.next_line().await {
                            if tx_err
                                .send(AgentEvent::Output {
                                    task_id: "__shell__".to_string(),
                                    agent: AgentType::Any,
                                    line,
                                })
                                .is_err()
                            {
                                break;
                            }
                        }
                    });
                }

                let tx_done = tx.clone();
                tokio::spawn(async move {
                    let _ = child.wait().await;
                    let _ = tx_done.send(AgentEvent::Completed {
                        task_id: "__shell__".to_string(),
                        agent: AgentType::Any,
                        success: true,
                        exit_code: 0,
                    });
                });

                self.shell_active = true;
                self.shell_output.clear();
                self.shell_output.push_back(format!("$ {}", shell));
                self.push_event("User shell opened (Ctrl+D to close)");
            }
            Err(e) => {
                self.push_event(&format!("Failed to spawn shell: {}", e));
            }
        }
    }

    /// Auto-commit working tree changes after a task completes successfully.
    fn git_auto_commit(&mut self, task: &Task, agent: &AgentType) {
        let state_mgr = StateManager::new(&self.forge_dir);
        let enabled = state_mgr.load().map(|s| s.git.auto_commit).unwrap_or(true);

        if !enabled {
            return;
        }

        if !self.project_root.join(".git").exists() {
            return;
        }

        let commit_type = commit_type_for_task(task.task_type.as_deref());
        let message = format!("{}({}): {}", commit_type, task.id, task.title);

        // Visual indicator in agent pane
        if let Some(buffer) = self.agent_outputs.get_mut(agent) {
            buffer.push_back(format!(
                "--- Auto-committing: {}({}) ---",
                commit_type, task.id
            ));
        }
        self.push_event(&format!("{} auto-committed ({})", task.id, commit_type));

        let project_root = self.project_root.clone();
        let task_id = task.id.clone();
        tokio::task::spawn_blocking(move || {
            let add_result = std::process::Command::new("git")
                .args(["add", "-A"])
                .current_dir(&project_root)
                .output();

            if let Err(e) = add_result {
                eprintln!("git add failed for {}: {}", task_id, e);
                return;
            }

            let commit_result = std::process::Command::new("git")
                .args(["commit", "--no-gpg-sign", "-m", &message])
                .current_dir(&project_root)
                .output();

            match commit_result {
                Ok(output) => {
                    if !output.status.success() {
                        let stderr = String::from_utf8_lossy(&output.stderr);
                        if !stderr.contains("nothing to commit") {
                            eprintln!("git commit warning for {}: {}", task_id, stderr.trim());
                        }
                    }
                }
                Err(e) => {
                    eprintln!("git commit failed for {}: {}", task_id, e);
                }
            }
        });
    }

    /// DX-050 Builder Mode: dispatch the selected task to the agent's running TUI.
    fn dispatch_to_tui(&mut self, _tx: &mpsc::UnboundedSender<AgentEvent>) {
        if self.selected_index >= self.tasks.len() {
            return;
        }
        let task = &self.tasks[self.selected_index];

        // Guard: task must be Pending
        if task.status != TaskStatus::Pending {
            self.push_event(&format!("{} is not pending ({:?})", task.id, task.status));
            return;
        }

        // Resolve agent
        let agent = task.assigned_to.clone().unwrap_or(AgentType::Claude);
        let agent = if agent == AgentType::Any {
            AgentType::Claude
        } else {
            agent
        };

        // Guard: TUI must be running
        if !self.pty_sessions.contains_key(&agent) {
            self.push_event(&format!("{} TUI not running — cannot dispatch", agent));
            return;
        }

        // Guard: TUI must be idle (not already running a task)
        if self.agent_running_task.contains_key(&agent) {
            self.push_event(&format!(
                "{} is busy with {} — wait for completion",
                agent,
                self.agent_running_task.get(&agent).unwrap()
            ));
            return;
        }

        // Build prompt via adapter's initial_input
        let (initial, pattern) = match agent {
            AgentType::Claude | AgentType::Any => (
                ClaudeAdapter.initial_input(task),
                ClaudeAdapter.ready_pattern().map(String::from),
            ),
            AgentType::Codex => (
                CodexAdapter.initial_input(task),
                CodexAdapter.ready_pattern().map(String::from),
            ),
            AgentType::Gemini => (
                GeminiAdapter.initial_input(task),
                GeminiAdapter.ready_pattern().map(String::from),
            ),
        };

        let Some(mut text) = initial else {
            self.push_event(&format!(
                "No prompt for {} — adapter returned None",
                task.id
            ));
            return;
        };

        // Inject completion signal instruction before the trailing \r
        let signal = Self::completion_signal_instruction(&self.forge_dir, &task.id);
        if text.ends_with('\r') {
            text.insert_str(text.len() - 1, &signal);
        } else {
            text.push_str(&signal);
        }

        // Type the prompt into the TUI.
        // schedule_input_when_ready() polls for the ready-pattern with its own timeout,
        // so we don't need a hard pre-check here — just dispatch and let it wait.
        let session = self.pty_sessions.get(&agent).unwrap();
        if let Some(pat) = pattern {
            session.schedule_input_when_ready(text, pat, 10000);
        } else {
            session.schedule_input(text, 300);
        }

        // Mark task InProgress
        let task_mgr = TaskManager::new(&self.forge_dir);
        let state_mgr = StateManager::new(&self.forge_dir);
        if let Ok(mut t) = task_mgr.get_task(&task.id) {
            t.status = TaskStatus::InProgress;
            t.assigned_to = Some(agent.clone());
            t.updated_at = chrono::Utc::now();
            task_mgr.update_task(&t).ok();
            if !t.locked_files.is_empty() {
                state_mgr
                    .lock_files(&t.id, agent.clone(), t.locked_files.clone())
                    .ok();
            }
        }

        let task_id = task.id.clone();
        self.running_task_ids.insert(task_id.clone());
        self.agent_running_task
            .insert(agent.clone(), task_id.clone());

        // DX-037: Track quota usage
        let now = Instant::now();
        let quota = self.provider_quota.entry(agent.clone()).or_insert((0, now));
        if quota.1.elapsed() > Duration::from_secs(5 * 3600) {
            *quota = (0, now);
        }
        quota.0 += 1;

        // Track completion detection — pattern must disappear then reappear
        self.awaiting_completion.insert(
            agent.clone(),
            AwaitingCompletion {
                task_id: task_id.clone(),
                dispatched_at: now,
                last_output_at: now,
                pattern_disappeared: false,
            },
        );

        self.push_event(&format!("Dispatched {} to {}", task_id, agent));
        self.reload_tasks().ok();
    }

    /// Cycle the agent assignment on the selected task: Claude → Codex → Gemini → Claude.
    fn cycle_agent_assignment(&mut self) {
        if self.selected_index >= self.tasks.len() {
            return;
        }
        let task = &self.tasks[self.selected_index];

        // Only allow reassignment on Pending or Failed tasks
        if !matches!(task.status, TaskStatus::Pending | TaskStatus::Failed) {
            self.push_event(&format!(
                "{} is {:?} — can only reassign pending/failed tasks",
                task.id, task.status
            ));
            return;
        }

        let current = task.assigned_to.clone().unwrap_or(AgentType::Any);
        let next = match current {
            AgentType::Claude => AgentType::Codex,
            AgentType::Codex => AgentType::Gemini,
            AgentType::Gemini => AgentType::Claude,
            AgentType::Any => AgentType::Claude,
        };

        let task_id = task.id.clone();
        let task_mgr = TaskManager::new(&self.forge_dir);
        if let Ok(mut t) = task_mgr.get_task(&task_id) {
            t.assigned_to = Some(next.clone());
            t.updated_at = chrono::Utc::now();
            task_mgr.update_task(&t).ok();
        }
        self.push_event(&format!("{} reassigned to {}", task_id, next));
        self.reload_tasks().ok();
    }

    fn retry_selected_task(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        if self.selected_index >= self.tasks.len() {
            return;
        }
        let task = &self.tasks[self.selected_index];
        let task_id = task.id.clone();

        match task.status {
            TaskStatus::Failed => {
                let task_mgr = TaskManager::new(&self.forge_dir);
                if let Ok(mut t) = task_mgr.get_task(&task_id) {
                    t.status = TaskStatus::Pending;
                    t.updated_at = chrono::Utc::now();
                    task_mgr.update_task(&t).ok();
                }
                self.push_event(&format!("Retrying {} (was failed)", task_id));
                self.reload_tasks().ok();
                self.schedule_unblocked_tasks(tx);
            }
            TaskStatus::InProgress => {
                self.running_task_ids.remove(&task_id);
                self.agent_running_task.retain(|_, v| *v != task_id);

                let task_mgr = TaskManager::new(&self.forge_dir);
                let state_mgr = StateManager::new(&self.forge_dir);
                if let Ok(mut t) = task_mgr.get_task(&task_id) {
                    t.status = TaskStatus::Pending;
                    t.updated_at = chrono::Utc::now();
                    task_mgr.update_task(&t).ok();
                    state_mgr.unlock_files(&task_id).ok();
                }
                self.push_event(&format!("Retrying {} (was in-progress)", task_id));
                self.reload_tasks().ok();
                self.schedule_unblocked_tasks(tx);
            }
            _ => {}
        }
    }

    pub fn is_all_done(&self) -> bool {
        // ALL tasks must be complete — including UAT and verify subtasks.
        // Previously this filtered out UAT tasks, causing premature completion
        // while U-xxx tasks were still pending.
        self.tasks
            .iter()
            .all(|t| t.status == TaskStatus::Completed || t.status == TaskStatus::Failed)
    }

    /// Check if all build-phase tasks are done and transition to Verify phase.
    /// Returns true if a phase transition occurred.
    fn check_phase_transition(&mut self) -> bool {
        match self.phase {
            DashboardPhase::Build => {
                // DX-052: Check for pending quality gate results first
                if self.quality_gate_pending {
                    if let Some(ref rx) = self.quality_gate_rx
                        && let Ok(results) = rx.try_recv()
                    {
                        return self.handle_gate_results(results);
                    }
                    return false; // Still waiting for gate results
                }

                // Build tasks: phase is None or Build
                let build_tasks: Vec<&Task> = self
                    .tasks
                    .iter()
                    .filter(|t| t.phase.is_none() || t.phase == Some(TaskPhase::Build))
                    .collect();

                if build_tasks.is_empty() {
                    return false;
                }

                let all_build_done = build_tasks
                    .iter()
                    .all(|t| t.status == TaskStatus::Completed || t.status == TaskStatus::Failed);

                if all_build_done {
                    // DX-052: Run quality gates before transitioning to Verify
                    let gates = quality_gate::detect_gates(&self.project_root);
                    if gates.is_empty() {
                        self.push_event("No quality gates detected — skipping gate check");
                        return self.transition_to_verify();
                    }

                    self.push_event(&format!("Running {} quality gate(s)...", gates.len()));
                    for g in &gates {
                        self.push_event(&format!("  Gate: {}", g.name));
                    }

                    let project_root = self.project_root.clone();
                    let (tx, rx) = std::sync::mpsc::channel();
                    std::thread::spawn(move || {
                        let results = quality_gate::run_gates(&project_root, &gates);
                        let _ = tx.send(results);
                    });
                    self.quality_gate_rx = Some(rx);
                    self.quality_gate_pending = true;
                    return false; // Wait for results on next tick
                }
                false
            }
            DashboardPhase::Verify => {
                // Verify/fix tasks: phase is Verify or Fix
                let verify_fix_tasks: Vec<&Task> = self
                    .tasks
                    .iter()
                    .filter(|t| {
                        t.phase == Some(TaskPhase::Verify) || t.phase == Some(TaskPhase::Fix)
                    })
                    .collect();

                if verify_fix_tasks.is_empty() {
                    // No verify tasks were generated — go straight to Complete
                    self.phase = DashboardPhase::Complete;
                    self.persist_phase();
                    self.push_event("Phase 2 (VERIFY) complete — no verify tasks found");
                    self.generate_uat_tasks();
                    return true;
                }

                let all_verify_done = verify_fix_tasks
                    .iter()
                    .all(|t| t.status == TaskStatus::Completed || t.status == TaskStatus::Failed);

                if all_verify_done {
                    self.phase = DashboardPhase::Complete;
                    self.persist_phase();
                    self.push_event("Phase 2 (VERIFY) complete — all verification done");
                    self.generate_uat_tasks();
                    return true;
                }
                false
            }
            DashboardPhase::Complete => {
                // Complete→Ship: wait for ALL tasks (including UAT) to finish
                if self.is_all_done() {
                    self.phase = DashboardPhase::Ship;
                    self.persist_phase();
                    self.push_event("All tasks complete — entering SHIP phase");
                    self.run_ship_phase();
                    return true;
                }
                false
            }
            DashboardPhase::Ship => false,
        }
    }

    /// DX-052: Execute the Build→Verify transition (generate verify subtasks + reload).
    fn transition_to_verify(&mut self) -> bool {
        self.phase = DashboardPhase::Verify;
        self.persist_phase();
        self.push_event("Phase 1 (BUILD) complete — transitioning to VERIFY");

        let task_mgr = TaskManager::new(&self.forge_dir);
        match task_mgr.generate_verify_subtasks() {
            Ok(generated) => {
                if generated.is_empty() {
                    self.push_event("No verify subtasks needed");
                } else {
                    self.push_event(&format!("Generated {} verify subtask(s)", generated.len()));
                }
            }
            Err(e) => {
                self.push_event(&format!("Failed to generate verify subtasks: {e}"));
            }
        }
        self.reload_tasks().ok();
        true
    }

    /// DX-052: Process quality gate results — either transition or generate fix tasks.
    fn handle_gate_results(&mut self, results: Vec<GateResult>) -> bool {
        self.quality_gate_pending = false;
        self.quality_gate_rx = None;
        self.quality_gate_attempts += 1;

        let failed: Vec<&GateResult> = results.iter().filter(|r| !r.passed).collect();
        let passed: Vec<&GateResult> = results.iter().filter(|r| r.passed).collect();

        // Log event for the audit trail
        let event_logger = EventLogger::new(&self.forge_dir);
        for r in &passed {
            self.push_event(&format!(
                "✓ Gate passed: {} ({}ms)",
                r.gate_name, r.duration_ms
            ));
            let _ = event_logger.log(&ForgeEvent::new(
                EventType::QualityGatePassed,
                format!("{} passed", r.gate_name),
            ));
        }

        if failed.is_empty() {
            self.push_event("All quality gates passed!");
            return self.transition_to_verify();
        }

        for r in &failed {
            self.push_event(&format!(
                "✗ Gate FAILED: {} (exit {})",
                r.gate_name, r.exit_code
            ));
            let _ = event_logger.log(&ForgeEvent::new(
                EventType::QualityGateFailed,
                format!("{} failed (exit {})", r.gate_name, r.exit_code),
            ));
        }

        if self.quality_gate_attempts >= 3 {
            self.push_event("Quality gates failed 3 times — force-transitioning to VERIFY");
            return self.transition_to_verify();
        }

        // Generate fix tasks for each failed gate
        let task_mgr = TaskManager::new(&self.forge_dir);
        let fail_vec: Vec<GateResult> = results.into_iter().filter(|r| !r.passed).collect();
        match task_mgr.generate_gate_fix_tasks(&fail_vec) {
            Ok(fix_tasks) => {
                self.push_event(&format!(
                    "Generated {} fix task(s) for failed gates (attempt {}/3)",
                    fix_tasks.len(),
                    self.quality_gate_attempts
                ));
            }
            Err(e) => {
                self.push_event(&format!("Failed to generate fix tasks: {e}"));
            }
        }
        self.reload_tasks().ok();
        false // Stay in Build — fix tasks will be dispatched
    }

    /// Generate UAT subtasks for user-facing T-xxx tasks during Verify→Complete transition.
    fn generate_uat_tasks(&mut self) {
        let task_mgr = TaskManager::new(&self.forge_dir);
        match task_mgr.generate_uat_subtasks() {
            Ok(generated) => {
                if generated.is_empty() {
                    self.push_event("No UAT tasks generated (no user-facing tasks)");
                } else {
                    self.push_event(&format!(
                        "Generated {} UAT task(s) — run `forge uat`",
                        generated.len()
                    ));
                }
            }
            Err(e) => {
                self.push_event(&format!("Failed to generate UAT tasks: {e}"));
            }
        }
        self.reload_tasks().ok();
    }

    /// Run the SHIP phase: changelog, archive, clean state.
    fn run_ship_phase(&mut self) {
        use crate::core::ship;

        // Generate changelog
        match ship::generate_changelog(&self.forge_dir) {
            Ok(cl) => {
                if cl.contains("No completed tasks") {
                    self.push_event("SHIP: No changelog entries (no completed T-tasks)");
                } else {
                    let lines = cl.lines().count();
                    self.push_event(&format!("SHIP: Changelog generated ({lines} lines)"));
                    // Write to project CHANGELOG.md if it exists
                    let changelog_path = self.project_root.join("CHANGELOG.md");
                    if changelog_path.exists()
                        && let Ok(existing) = std::fs::read_to_string(&changelog_path)
                        && let Some(pos) = existing.find("\n## ")
                    {
                        let mut new = existing[..pos].to_string();
                        new.push('\n');
                        new.push_str(&cl);
                        new.push_str(&existing[pos..]);
                        std::fs::write(&changelog_path, new).ok();
                        self.push_event("SHIP: Updated CHANGELOG.md");
                    }
                }
            }
            Err(e) => self.push_event(&format!("SHIP: Changelog error: {e}")),
        }

        // Suggest version bump
        let bump = ship::suggest_version_bump(&self.forge_dir);
        self.push_event(&format!("SHIP: Suggested version bump: {bump}"));

        // Archive
        match ship::archive_cycle(&self.forge_dir) {
            Ok((count, path)) => {
                self.push_event(&format!(
                    "SHIP: Archived {count} artifacts to {}",
                    path.file_name().unwrap_or_default().to_string_lossy()
                ));
            }
            Err(e) => self.push_event(&format!("SHIP: Archive error: {e}")),
        }

        // Clean state
        match ship::clean_state(&self.forge_dir) {
            Ok(()) => self.push_event("SHIP: State cleaned — ready for next cycle"),
            Err(e) => self.push_event(&format!("SHIP: Clean error: {e}")),
        }

        self.push_event("SHIP phase complete. Run `forge ship` for interactive mode.");
        self.reload_tasks().ok();
    }

    /// When a verify task fails, generate fix + re-verify pair (up to 3 retries).
    fn handle_verify_failure(&mut self, task: &Task) {
        if task.phase != Some(TaskPhase::Verify) {
            return;
        }

        if task.retry_count >= 3 {
            self.push_event(&format!(
                "{} failed after 3 retries — needs human attention",
                task.id
            ));
            return;
        }

        let task_mgr = TaskManager::new(&self.forge_dir);

        // Generate a fix subtask
        let fix_num = match task_mgr.next_task_number() {
            Ok(n) => n,
            Err(_) => return,
        };
        let fix_id = format!("T-{fix_num:03}");
        let mut fix_task = Task::new(
            &fix_id,
            format!(
                "Fix: {} (retry {})",
                task.title.trim_start_matches("Verify: "),
                task.retry_count + 1
            ),
            format!(
                "Fix failures from verify task {}.\nRetry attempt {}/3.\nOriginal verify: {}",
                task.id,
                task.retry_count + 1,
                task.description
            ),
        );
        fix_task.phase = Some(TaskPhase::Fix);
        fix_task.task_type = Some("implement".to_string());
        fix_task.parent_task = task.parent_task.clone();
        fix_task.depends_on = vec![task.id.clone()];
        fix_task.assigned_to = Some(AgentType::Claude);
        fix_task.locked_files = task.locked_files.clone();

        // Generate a re-verify subtask
        let verify_num = match task_mgr.next_verify_number() {
            Ok(n) => n,
            Err(_) => return,
        };
        let re_verify_id = format!("V-{verify_num:03}");
        let mut re_verify = Task::new(
            &re_verify_id,
            format!(
                "Re-verify: {}",
                task.title
                    .trim_start_matches("Verify: ")
                    .trim_start_matches("Re-verify: ")
            ),
            format!(
                "Re-run verification after fix {}.\nRetry attempt {}/3.",
                fix_id,
                task.retry_count + 1
            ),
        );
        re_verify.phase = Some(TaskPhase::Verify);
        re_verify.task_type = Some("review".to_string());
        re_verify.parent_task = task.parent_task.clone();
        re_verify.depends_on = vec![fix_id.clone()];
        re_verify.assigned_to = task.assigned_to.clone();
        re_verify.locked_files = task.locked_files.clone();
        re_verify.retry_count = task.retry_count + 1;

        if task_mgr.create_task(&fix_task).is_ok() && task_mgr.create_task(&re_verify).is_ok() {
            self.push_event(&format!(
                "Auto-generated {} + {} to fix failures (retry {}/3)",
                fix_id,
                re_verify_id,
                task.retry_count + 1
            ));
        }
    }

    fn spawn_task(&mut self, task: &Task, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let agent = task.assigned_to.clone().unwrap_or(AgentType::Claude);

        let agent = if agent == AgentType::Any {
            AgentType::Claude
        } else {
            agent
        };

        if self.pty_mode {
            self.spawn_task_pty(task, &agent, tx);
        } else {
            self.spawn_task_piped(task, &agent, tx);
        }
    }

    /// Dispatch a task's prompt into an already-running TUI session.
    fn dispatch_task_to_existing_tui(
        &mut self,
        task: &Task,
        agent: &AgentType,
        tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        let (initial, timeout, pattern) = match agent {
            AgentType::Claude | AgentType::Any => (
                ClaudeAdapter.initial_input(task),
                ClaudeAdapter.initial_input_delay_ms(),
                ClaudeAdapter.ready_pattern().map(String::from),
            ),
            AgentType::Codex => (
                CodexAdapter.initial_input(task),
                CodexAdapter.initial_input_delay_ms(),
                CodexAdapter.ready_pattern().map(String::from),
            ),
            AgentType::Gemini => (
                GeminiAdapter.initial_input(task),
                GeminiAdapter.initial_input_delay_ms(),
                GeminiAdapter.ready_pattern().map(String::from),
            ),
        };

        if let Some(mut text) = initial {
            // Inject completion signal instruction
            let signal = Self::completion_signal_instruction(&self.forge_dir, &task.id);
            if text.ends_with('\r') {
                text.insert_str(text.len() - 1, &signal);
            } else {
                text.push_str(&signal);
            }

            let session = self.pty_sessions.get(agent).unwrap();
            if let Some(pat) = pattern {
                session.schedule_input_when_ready(text, pat, timeout);
            } else {
                session.schedule_input(text, timeout);
            }
        }

        // Track for completion detection
        let now = Instant::now();
        self.awaiting_completion.insert(
            agent.clone(),
            AwaitingCompletion {
                task_id: task.id.clone(),
                dispatched_at: now,
                last_output_at: now,
                pattern_disappeared: false,
            },
        );

        self.finalize_task_spawn(task, agent, tx);
    }

    /// DX-050: Ensure all 3 agent TUIs are running in PTY mode.
    /// Spawns idle TUI sessions for agents that don't already have a PTY session.
    /// Called on startup so users can manually dispatch tasks via `a` key.
    pub fn spawn_idle_tuis(&mut self, tx: &mpsc::UnboundedSender<AgentEvent>) {
        if !self.pty_mode {
            return;
        }
        let agents = [AgentType::Claude, AgentType::Codex, AgentType::Gemini];
        for agent in &agents {
            if self.pty_sessions.contains_key(agent) {
                continue; // Already has a TUI from task dispatch
            }
            self.spawn_idle_tui(agent, tx);
        }
    }

    /// Spawn an idle TUI for an agent (no task, just launch the interactive CLI).
    fn spawn_idle_tui(&mut self, agent: &AgentType, tx: &mpsc::UnboundedSender<AgentEvent>) {
        let state_mgr = StateManager::new(&self.forge_dir);
        let agent_name = agent.to_string().to_lowercase();
        let auth_mode = state_mgr
            .get_agent_auth(&agent_name)
            .unwrap_or_else(|_| "subscription".to_string());
        let permissions = state_mgr
            .get_agent_permissions(&agent_name)
            .unwrap_or_else(|_| "safe".to_string());

        // Build a dummy task just for the command builder (no prompt will be typed)
        let now = chrono::Utc::now();
        let dummy = Task {
            id: String::new(),
            title: String::new(),
            description: String::new(),
            status: TaskStatus::Pending,
            assigned_to: Some(agent.clone()),
            task_type: None,
            depends_on: Vec::new(),
            locked_files: Vec::new(),
            acceptance_criteria: Vec::new(),
            created_at: now,
            updated_at: now,
            completed_at: None,
            plan_version: None,
            parent_task: None,
            phase: None,
            retry_count: 0,
            verified_by: None,
            verified_at: None,
            result_summary: None,
            completed_by: None,
            completed_by_source: None,
        };

        let std_cmd = match agent {
            AgentType::Claude | AgentType::Any => ClaudeAdapter.build_command_interactive(
                &dummy,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
            AgentType::Codex => CodexAdapter.build_command_interactive(
                &dummy,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
            AgentType::Gemini => GeminiAdapter.build_command_interactive(
                &dummy,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
        };

        let program = std_cmd.get_program().to_string_lossy().to_string();
        let mut pty_cmd = CommandBuilder::new(&program);
        for arg in std_cmd.get_args() {
            pty_cmd.arg(arg.to_string_lossy().as_ref());
        }
        if let Some(dir) = std_cmd.get_current_dir() {
            pty_cmd.cwd(dir);
        }
        pty_cmd.env("TERM", "xterm-256color");
        for (key, val) in std_cmd.get_envs() {
            if let Some(v) = val {
                pty_cmd.env(key.to_string_lossy().as_ref(), v.to_string_lossy().as_ref());
            } else {
                // Forward env_remove() calls — without this, vars the adapter
                // wanted removed (e.g. API keys in subscription mode) leak through.
                pty_cmd.env_remove(key.to_string_lossy().as_ref());
            }
        }

        let (pane_cols, pane_rows) = self.estimate_pane_size();
        let size = PtySize {
            rows: pane_rows,
            cols: pane_cols,
            pixel_width: 0,
            pixel_height: 0,
        };

        // Use a placeholder task_id for the PTY reader thread
        let placeholder_id = format!("idle-{}", agent_name);

        match PtySession::spawn(
            pty_cmd,
            size,
            tx.clone(),
            placeholder_id,
            agent.clone(),
            OUTPUT_BUFFER_CAP,
        ) {
            Ok(session) => {
                self.pty_sessions.insert(agent.clone(), session);
                self.push_event(&format!("{} TUI launched (idle)", agent));
            }
            Err(e) => {
                self.push_event(&format!("Failed to launch {} TUI: {}", agent, e));
            }
        }
    }

    /// DX-024: Spawn task with PTY allocation (Stargate mode).
    /// If an idle TUI already exists for this agent, reuse it (type prompt into it).
    /// Otherwise, spawn a new PTY process.
    fn spawn_task_pty(
        &mut self,
        task: &Task,
        agent: &AgentType,
        tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        tracing::debug!(task_id = %task.id, agent = %agent, "Spawning PTY for task");
        // Reuse existing idle TUI if available
        if self.pty_sessions.contains_key(agent) {
            self.dispatch_task_to_existing_tui(task, agent, tx);
            return;
        }

        let state_mgr = StateManager::new(&self.forge_dir);
        let agent_name = agent.to_string().to_lowercase();
        let auth_mode = state_mgr
            .get_agent_auth(&agent_name)
            .unwrap_or_else(|_| "subscription".to_string());
        let permissions = state_mgr
            .get_agent_permissions(&agent_name)
            .unwrap_or_else(|_| "safe".to_string());

        // Use interactive command for Claude (no stream-json), standard for others
        let std_cmd = match agent {
            AgentType::Claude | AgentType::Any => ClaudeAdapter.build_command_interactive(
                task,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
            AgentType::Codex => CodexAdapter.build_command_interactive(
                task,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
            AgentType::Gemini => GeminiAdapter.build_command_interactive(
                task,
                &self.project_root,
                &auth_mode,
                &permissions,
            ),
        };

        // Convert std::process::Command to portable_pty::CommandBuilder
        let program = std_cmd.get_program().to_string_lossy().to_string();
        let mut pty_cmd = CommandBuilder::new(&program);
        for arg in std_cmd.get_args() {
            pty_cmd.arg(arg.to_string_lossy().as_ref());
        }
        if let Some(dir) = std_cmd.get_current_dir() {
            pty_cmd.cwd(dir);
        }
        pty_cmd.env("TERM", "xterm-256color");
        // Forward environment from the std command
        for (key, val) in std_cmd.get_envs() {
            if let Some(v) = val {
                pty_cmd.env(key.to_string_lossy().as_ref(), v.to_string_lossy().as_ref());
            } else {
                // Forward env_remove() calls — without this, vars the adapter
                // wanted removed (e.g. API keys in subscription mode) leak through.
                pty_cmd.env_remove(key.to_string_lossy().as_ref());
            }
        }

        let (pane_cols, pane_rows) = self.estimate_pane_size();
        let size = PtySize {
            rows: pane_rows,
            cols: pane_cols,
            pixel_width: 0,
            pixel_height: 0,
        };

        match PtySession::spawn(
            pty_cmd,
            size,
            tx.clone(),
            task.id.clone(),
            agent.clone(),
            OUTPUT_BUFFER_CAP,
        ) {
            Ok(session) => {
                // Check if adapter wants to type initial input into the TUI
                let (initial, timeout, pattern) = match agent {
                    AgentType::Claude | AgentType::Any => (
                        ClaudeAdapter.initial_input(task),
                        ClaudeAdapter.initial_input_delay_ms(),
                        ClaudeAdapter.ready_pattern().map(String::from),
                    ),
                    AgentType::Codex => (
                        CodexAdapter.initial_input(task),
                        CodexAdapter.initial_input_delay_ms(),
                        CodexAdapter.ready_pattern().map(String::from),
                    ),
                    AgentType::Gemini => (
                        GeminiAdapter.initial_input(task),
                        GeminiAdapter.initial_input_delay_ms(),
                        GeminiAdapter.ready_pattern().map(String::from),
                    ),
                };

                // Schedule initial input: pattern-based (instant) or fixed delay (fallback)
                if let Some(mut text) = initial {
                    // Inject completion signal instruction before the trailing \r
                    let signal = Self::completion_signal_instruction(&self.forge_dir, &task.id);
                    if text.ends_with('\r') {
                        text.insert_str(text.len() - 1, &signal);
                    } else {
                        text.push_str(&signal);
                    }

                    if let Some(pat) = pattern {
                        session.schedule_input_when_ready(text, pat, timeout);
                    } else {
                        session.schedule_input(text, timeout);
                    }
                }

                self.pty_sessions.insert(agent.clone(), session);

                // Track for completion detection — full TUI processes don't exit after task.
                self.awaiting_completion.insert(
                    agent.clone(),
                    AwaitingCompletion {
                        task_id: task.id.clone(),
                        dispatched_at: Instant::now(),
                        last_output_at: Instant::now(),
                        pattern_disappeared: false,
                    },
                );

                self.finalize_task_spawn(task, agent, tx);
            }
            Err(e) => {
                self.push_event(&format!(
                    "PTY spawn failed for {}, falling back to piped: {}",
                    task.id, e
                ));
                self.spawn_task_piped(task, agent, tx);
            }
        }
    }

    /// Spawn task with piped I/O (legacy mode).
    fn spawn_task_piped(
        &mut self,
        task: &Task,
        agent: &AgentType,
        tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        let state_mgr = StateManager::new(&self.forge_dir);
        let agent_name = agent.to_string().to_lowercase();
        let auth_mode = state_mgr
            .get_agent_auth(&agent_name)
            .unwrap_or_else(|_| "subscription".to_string());
        let permissions = state_mgr
            .get_agent_permissions(&agent_name)
            .unwrap_or_else(|_| "safe".to_string());

        let std_cmd = match agent {
            AgentType::Claude | AgentType::Any => {
                ClaudeAdapter.build_command(task, &self.project_root, &auth_mode, &permissions)
            }
            AgentType::Codex => {
                CodexAdapter.build_command(task, &self.project_root, &auth_mode, &permissions)
            }
            AgentType::Gemini => {
                GeminiAdapter.build_command(task, &self.project_root, &auth_mode, &permissions)
            }
        };

        let mut tokio_cmd = TokioCommand::from(std_cmd);
        tokio_cmd
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped());

        match tokio_cmd.spawn() {
            Ok(mut child) => {
                let task_id = task.id.clone();
                let task_id2 = task.id.clone();
                let task_id3 = task.id.clone();
                let agent2 = agent.clone();
                let agent3 = agent.clone();
                let tx2 = tx.clone();
                let tx3 = tx.clone();

                if let Some(stdout) = child.stdout.take() {
                    let tx_out = tx.clone();
                    let tid = task_id.clone();
                    let ag = agent.clone();
                    // Use JSON parser for Claude (stream-json output), plain lines for others
                    match agent {
                        AgentType::Claude | AgentType::Any => {
                            tokio::spawn(stream_claude_json(stdout, tid, ag, tx_out));
                        }
                        _ => {
                            tokio::spawn(stream_lines(stdout, tid, ag, tx_out));
                        }
                    }
                }

                if let Some(stderr) = child.stderr.take() {
                    tokio::spawn(stream_lines(stderr, task_id2, agent2, tx2));
                }

                tokio::spawn(async move {
                    match child.wait().await {
                        Ok(status) => {
                            let code = status.code().unwrap_or(-1);
                            let _ = tx3.send(AgentEvent::Completed {
                                task_id: task_id3,
                                agent: agent3,
                                success: status.success(),
                                exit_code: code,
                            });
                        }
                        Err(e) => {
                            let _ = tx3.send(AgentEvent::Error {
                                task_id: task_id3,
                                agent: agent3,
                                message: e.to_string(),
                            });
                        }
                    }
                });

                self.finalize_task_spawn(task, agent, tx);
            }
            Err(e) => {
                self.push_event(&format!("Failed to spawn {}: {}", task.id, e));
                let _ = tx.send(AgentEvent::Error {
                    task_id: task.id.clone(),
                    agent: agent.clone(),
                    message: e.to_string(),
                });
            }
        }
    }

    /// Common post-spawn bookkeeping for both PTY and piped modes.
    fn finalize_task_spawn(
        &mut self,
        task: &Task,
        agent: &AgentType,
        _tx: &mpsc::UnboundedSender<AgentEvent>,
    ) {
        let task_mgr = TaskManager::new(&self.forge_dir);
        let state_mgr = StateManager::new(&self.forge_dir);
        let mut updated = task.clone();
        updated.status = TaskStatus::InProgress;
        updated.assigned_to = Some(agent.clone());
        updated.updated_at = chrono::Utc::now();
        task_mgr.update_task(&updated).ok();

        if !task.locked_files.is_empty() {
            state_mgr
                .lock_files(&task.id, agent.clone(), task.locked_files.clone())
                .ok();
        }

        self.running_task_ids.insert(task.id.clone());
        self.agent_running_task
            .insert(agent.clone(), task.id.clone());

        // DX-037: Track quota usage
        let quota = self
            .provider_quota
            .entry(agent.clone())
            .or_insert((0, Instant::now()));
        // Reset counter if 5-hour window has elapsed
        if quota.1.elapsed() > std::time::Duration::from_secs(5 * 3600) {
            *quota = (0, Instant::now());
        }
        quota.0 += 1;

        self.push_event(&format!("Started {} on {}", task.id, agent));
    }

    pub fn cleanup_running_tasks(&mut self) {
        // DX-024: Kill all active PTY sessions
        for (_agent, mut session) in self.pty_sessions.drain() {
            session.kill();
        }
        if let Some(mut shell) = self.shell_pty.take() {
            shell.kill();
        }
        self.attached_pane = None;
        self.awaiting_completion.clear();

        let task_mgr = TaskManager::new(&self.forge_dir);
        let state_mgr = StateManager::new(&self.forge_dir);
        let event_logger = EventLogger::new(&self.forge_dir);

        for task_id in self.running_task_ids.drain() {
            if let Ok(mut task) = task_mgr.get_task(&task_id) {
                task.status = TaskStatus::Pending;
                task.updated_at = chrono::Utc::now();
                task_mgr.update_task(&task).ok();
                state_mgr.unlock_files(&task_id).ok();

                event_logger
                    .log(&ForgeEvent::new(
                        EventType::TaskStarted,
                        format!("Reset {} to pending (dashboard exiting)", task_id),
                    ))
                    .ok();
            }
        }
        self.agent_running_task.clear();
    }

    pub fn reset_orphaned_tasks(&mut self) -> anyhow::Result<()> {
        let task_mgr = TaskManager::new(&self.forge_dir);
        let state_mgr = StateManager::new(&self.forge_dir);
        let event_logger = EventLogger::new(&self.forge_dir);

        let tasks = task_mgr.list_tasks()?;
        for task in tasks {
            if task.status == TaskStatus::InProgress {
                let mut updated = task.clone();
                updated.status = TaskStatus::Pending;
                updated.updated_at = chrono::Utc::now();
                task_mgr.update_task(&updated)?;
                state_mgr.unlock_files(&task.id).ok();

                let msg = format!("Reset orphaned task {} to pending", task.id);
                self.push_event(&msg);
                event_logger
                    .log(&ForgeEvent::new(EventType::TaskStarted, msg))
                    .ok();
            }
        }
        Ok(())
    }

    fn push_event(&mut self, msg: &str) {
        let ts = chrono::Local::now().format("%H:%M:%S");
        let entry = format!("[{}] {}", ts, msg);
        if self.events.len() >= EVENT_BUFFER_CAP {
            self.events.pop_front();
        }
        self.events.push_back(entry);
    }
}

/// Map task type to conventional commit type prefix.
pub fn commit_type_for_task(task_type: Option<&str>) -> &'static str {
    match task_type {
        Some("test") => "test",
        Some("document") => "docs",
        Some("review") => "refactor",
        Some("design") => "docs",
        Some("implement") => "feat",
        _ => "feat",
    }
}

/// Check if recent agent output contains rate limit indicators.
/// The shell the dashboard's shell pane runs: `$SHELL` when set, else the platform default.
/// Native Windows usually has no `SHELL`, so it gets `%COMSPEC%` (else `cmd.exe`) instead of
/// /bin/bash, which does not exist there.
fn default_shell(is_windows: bool, shell: Option<String>, comspec: Option<String>) -> String {
    let nonempty = |v: Option<String>| v.filter(|v| !v.trim().is_empty());
    if let Some(shell) = nonempty(shell) {
        return shell;
    }
    if is_windows {
        nonempty(comspec).unwrap_or_else(|| "cmd.exe".to_string())
    } else {
        "/bin/bash".to_string()
    }
}

fn is_rate_limited(output: &VecDeque<String>) -> bool {
    output.iter().rev().take(20).any(|line| {
        let lower = line.to_lowercase();
        RATE_LIMIT_PATTERNS.iter().any(|p| lower.contains(p))
    })
}

/// Compute exponential backoff delay with jitter for a given attempt.
/// Matches DX-035 spec: 60s → 120s → 240s → 480s → 600s (max 10 min).
fn compute_backoff_delay(attempt: u32) -> std::time::Duration {
    let base_secs: u64 = match attempt {
        1 => 60,
        2 => 120,
        3 => 240,
        4 => 480,
        _ => 600,
    };
    let jitter = rand::rng().random_range(0..=30u64);
    std::time::Duration::from_secs(base_secs + jitter)
}

/// Save PTY output to .forge/results/{task_id}.txt for cross-agent verification.
fn save_pty_result(forge_dir: &std::path::Path, task_id: &str, output: &str) {
    let results_dir = forge_dir.join("results");
    if std::fs::create_dir_all(&results_dir).is_ok() {
        std::fs::write(results_dir.join(format!("{task_id}.txt")), output).ok();
    }
}

/// Map an agent type to its pane index.
fn agent_pane_index(agent: &AgentType) -> Option<usize> {
    match agent {
        AgentType::Claude | AgentType::Any => Some(0),
        AgentType::Codex => Some(1),
        AgentType::Gemini => Some(2),
    }
}

async fn stream_lines(
    reader: impl tokio::io::AsyncRead + Unpin,
    task_id: String,
    agent: AgentType,
    tx: mpsc::UnboundedSender<AgentEvent>,
) {
    let mut lines = tokio::io::BufReader::new(reader).lines();
    while let Ok(Some(line)) = lines.next_line().await {
        if tx
            .send(AgentEvent::Output {
                task_id: task_id.clone(),
                agent: agent.clone(),
                line,
            })
            .is_err()
        {
            break;
        }
    }
}

/// Parse Claude's stream-json NDJSON output into human-readable lines for TUI display.
async fn stream_claude_json(
    reader: impl tokio::io::AsyncRead + Unpin,
    task_id: String,
    agent: AgentType,
    tx: mpsc::UnboundedSender<AgentEvent>,
) {
    let mut lines = tokio::io::BufReader::new(reader).lines();
    while let Ok(Some(line)) = lines.next_line().await {
        let display_lines = parse_stream_json_line(&line);
        for display_line in display_lines {
            if tx
                .send(AgentEvent::Output {
                    task_id: task_id.clone(),
                    agent: agent.clone(),
                    line: display_line,
                })
                .is_err()
            {
                return;
            }
        }
    }
}

/// Parse a single NDJSON line from Claude's stream-json output.
/// Returns zero or more human-readable display lines.
fn parse_stream_json_line(line: &str) -> Vec<String> {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(line) else {
        // Not valid JSON — show raw line as fallback
        return if line.trim().is_empty() {
            vec![]
        } else {
            vec![line.to_string()]
        };
    };

    let event_type = value.get("type").and_then(|v| v.as_str()).unwrap_or("");

    match event_type {
        "init" => {
            vec!["[session started]".to_string()]
        }
        "message" => {
            let mut result = Vec::new();
            if let Some(content) = value.get("content").and_then(|c| c.as_array()) {
                for item in content {
                    let item_type = item.get("type").and_then(|v| v.as_str()).unwrap_or("");
                    match item_type {
                        "text" => {
                            if let Some(text) = item.get("text").and_then(|v| v.as_str()) {
                                for text_line in text.lines() {
                                    let trimmed = text_line.trim();
                                    if !trimmed.is_empty() {
                                        result.push(trimmed.to_string());
                                    }
                                }
                            }
                        }
                        "tool_use" => {
                            let name = item.get("name").and_then(|v| v.as_str()).unwrap_or("?");
                            let input_summary = summarize_tool_input(name, item.get("input"));
                            result.push(format!("[{}] {}", name, input_summary));
                        }
                        _ => {}
                    }
                }
            }
            result
        }
        "result" => {
            let status = value
                .get("status")
                .and_then(|v| v.as_str())
                .unwrap_or("unknown");
            let duration = value.get("duration_ms").and_then(|v| v.as_u64());
            match duration {
                Some(ms) => vec![format!("[done] {} in {:.1}s", status, ms as f64 / 1000.0)],
                None => vec![format!("[done] {}", status)],
            }
        }
        // Skip tool_result (too verbose) and unknown types
        _ => vec![],
    }
}

/// Extract a short summary from tool input for display.
fn summarize_tool_input(tool_name: &str, input: Option<&serde_json::Value>) -> String {
    let Some(input) = input else {
        return String::new();
    };

    match tool_name {
        "Read" | "Edit" | "Write" => input
            .get("file_path")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "Bash" => {
            let cmd = input.get("command").and_then(|v| v.as_str()).unwrap_or("");
            truncate_str(cmd, 60)
        }
        "Glob" => input
            .get("pattern")
            .and_then(|v| v.as_str())
            .unwrap_or("")
            .to_string(),
        "Grep" => {
            let pattern = input.get("pattern").and_then(|v| v.as_str()).unwrap_or("");
            truncate_str(pattern, 40)
        }
        "Task" => {
            let desc = input
                .get("description")
                .and_then(|v| v.as_str())
                .unwrap_or("subagent");
            truncate_str(desc, 50)
        }
        _ => {
            // Generic: show first string value found
            if let Some(obj) = input.as_object() {
                for (_key, val) in obj.iter().take(1) {
                    if let Some(s) = val.as_str() {
                        return truncate_str(s, 50);
                    }
                }
            }
            String::new()
        }
    }
}

fn truncate_str(s: &str, max: usize) -> String {
    if s.chars().count() <= max {
        s.to_string()
    } else {
        let truncated: String = s.chars().take(max.saturating_sub(3)).collect();
        format!("{truncated}...")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// DIRECTIVE-NXTG-20261014-07: native Windows has no `SHELL`; the pane must open the user's
    /// shell (`%COMSPEC%`, else `cmd.exe`), not /bin/bash. Unix is unchanged.
    #[test]
    fn test_default_shell_per_platform() {
        let s = |v: &str| Some(v.to_string());
        // Windows, SHELL unset: COMSPEC, else cmd.exe.
        assert_eq!(
            default_shell(true, None, s(r"C:\Windows\system32\cmd.exe")),
            r"C:\Windows\system32\cmd.exe"
        );
        assert_eq!(default_shell(true, None, None), "cmd.exe");
        // Windows, SHELL set (Git Bash, MSYS2): honour it.
        assert_eq!(
            default_shell(true, s("/usr/bin/bash"), s("cmd.exe")),
            "/usr/bin/bash"
        );
        // Unix, SHELL unset: /bin/bash, as before; COMSPEC is ignored.
        assert_eq!(default_shell(false, None, s("cmd.exe")), "/bin/bash");
        // Unix, SHELL set.
        assert_eq!(default_shell(false, s("/bin/zsh"), None), "/bin/zsh");
    }

    fn make_task(id: &str, status: TaskStatus, deps: Vec<String>) -> Task {
        Task {
            id: id.to_string(),
            title: format!("Task {}", id),
            description: String::new(),
            status,
            assigned_to: Some(AgentType::Claude),
            task_type: None,
            depends_on: deps,
            locked_files: Vec::new(),
            acceptance_criteria: Vec::new(),
            created_at: chrono::Utc::now(),
            updated_at: chrono::Utc::now(),
            completed_at: None,
            plan_version: None,
            parent_task: None,
            phase: None,
            retry_count: 0,
            verified_by: None,
            verified_at: None,
            result_summary: None,
            completed_by: None,
            completed_by_source: None,
        }
    }

    #[test]
    fn test_is_all_done_empty() {
        let (app, _rx, _tx) = App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert!(app.is_all_done());
    }

    #[test]
    fn budget_strip_toggles_off_by_default_and_on_with_b() {
        // Isolate the fleet read behind a nonexistent private socket, so the toggle test never
        // touches the operator's live tmux server (advisor's live-surface discipline).
        // SAFETY: single-threaded test; the env var is restored immediately after.
        unsafe {
            std::env::set_var(
                crate::fleet::TMUX_SOCKET_ENV,
                "forge-fleet-test-nonexistent",
            )
        };
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert!(
            !app.show_budget,
            "the strip is OFF by default — purely additive"
        );

        app.handle_key(KeyEvent::from(KeyCode::Char('b')), &tx);
        assert!(app.show_budget, "`b` enables the strip");
        // Enabling refreshed against the empty private socket → no panes, no panic.
        assert!(app.fleet_rows.is_empty());

        app.handle_key(KeyEvent::from(KeyCode::Char('b')), &tx);
        assert!(!app.show_budget, "`b` toggles it back off");
        unsafe { std::env::remove_var(crate::fleet::TMUX_SOCKET_ENV) };
    }

    #[test]
    fn test_is_all_done_with_completed_tasks() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![
            make_task("T-001", TaskStatus::Completed, vec![]),
            make_task("T-002", TaskStatus::Failed, vec![]),
        ];
        assert!(app.is_all_done());
    }

    #[test]
    fn test_is_all_done_with_pending() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![
            make_task("T-001", TaskStatus::Completed, vec![]),
            make_task("T-002", TaskStatus::Pending, vec![]),
        ];
        assert!(!app.is_all_done());
    }

    #[test]
    fn test_is_all_done_includes_uat_tasks() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        let mut uat = make_task("U-001", TaskStatus::Pending, vec![]);
        uat.phase = Some(TaskPhase::Uat);
        app.tasks = vec![
            make_task("T-001", TaskStatus::Completed, vec![]),
            make_task("V-001", TaskStatus::Completed, vec![]),
            uat,
        ];
        // Pending UAT tasks MUST prevent is_all_done from returning true.
        // This was the bug: UAT tasks were filtered out, causing premature
        // phase completion while U-tasks were still pending.
        assert!(!app.is_all_done());
    }

    #[test]
    fn test_is_all_done_uat_completed() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        let mut uat = make_task("U-001", TaskStatus::Completed, vec![]);
        uat.phase = Some(TaskPhase::Uat);
        app.tasks = vec![make_task("T-001", TaskStatus::Completed, vec![]), uat];
        assert!(app.is_all_done());
    }

    #[test]
    fn test_schedule_respects_parallel_limit() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 2, false);
        app.running_task_ids.insert("T-001".to_string());
        app.running_task_ids.insert("T-002".to_string());
        app.tasks = vec![make_task("T-003", TaskStatus::Pending, vec![])];
        app.schedule_unblocked_tasks(&tx);
        assert!(!app.running_task_ids.contains("T-003"));
    }

    #[test]
    fn test_blocked_tasks_not_scheduled() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![make_task(
            "T-002",
            TaskStatus::Pending,
            vec!["T-001".to_string()],
        )];
        app.completed_task_ids = vec![];
        app.schedule_unblocked_tasks(&tx);
        assert!(!app.running_task_ids.contains("T-002"));
    }

    #[test]
    fn test_watch_mode_no_schedule() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, true);
        app.tasks = vec![make_task("T-001", TaskStatus::Pending, vec![])];
        app.schedule_unblocked_tasks(&tx);
        assert!(!app.running_task_ids.contains("T-001"));
    }

    #[test]
    fn test_handle_key_quit() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.handle_key(KeyEvent::from(KeyCode::Char('q')), &tx);
        assert!(app.should_quit);
    }

    #[test]
    fn test_tab_cycles_through_panes_and_back() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert_eq!(app.focus, FocusArea::TaskBoard);

        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(0));

        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(1));

        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(2));

        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(3));

        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.focus, FocusArea::TaskBoard);
    }

    #[test]
    fn test_backtab_reverse_cycles() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert_eq!(app.focus, FocusArea::TaskBoard);

        app.handle_key(KeyEvent::from(KeyCode::BackTab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(3));

        app.handle_key(KeyEvent::from(KeyCode::BackTab), &tx);
        assert_eq!(app.focus, FocusArea::Pane(2));
    }

    #[test]
    fn test_task_board_navigation() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![
            make_task("T-001", TaskStatus::Pending, vec![]),
            make_task("T-002", TaskStatus::Pending, vec![]),
            make_task("T-003", TaskStatus::Pending, vec![]),
        ];

        assert_eq!(app.selected_index, 0);
        app.handle_key(KeyEvent::from(KeyCode::Down), &tx);
        assert_eq!(app.selected_index, 1);
        app.handle_key(KeyEvent::from(KeyCode::Down), &tx);
        assert_eq!(app.selected_index, 2);
        app.handle_key(KeyEvent::from(KeyCode::Down), &tx);
        assert_eq!(app.selected_index, 2); // clamped

        app.handle_key(KeyEvent::from(KeyCode::Up), &tx);
        assert_eq!(app.selected_index, 1);
    }

    #[test]
    fn test_pane_scroll_up_down() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        // Fill Claude pane (index 0) with 20 lines
        let buf = app.agent_outputs.get_mut(&AgentType::Claude).unwrap();
        for i in 0..20 {
            buf.push_back(format!("line {}", i));
        }

        // Focus on pane 0
        app.focus = FocusArea::Pane(0);

        // Scroll up
        app.handle_key(KeyEvent::from(KeyCode::Up), &tx);
        assert_eq!(app.pane_scroll[0], 1);
        assert!(app.pane_pinned[0]);

        app.handle_key(KeyEvent::from(KeyCode::Up), &tx);
        assert_eq!(app.pane_scroll[0], 2);

        // Scroll down
        app.handle_key(KeyEvent::from(KeyCode::Down), &tx);
        assert_eq!(app.pane_scroll[0], 1);
        assert!(app.pane_pinned[0]); // still pinned

        app.handle_key(KeyEvent::from(KeyCode::Down), &tx);
        assert_eq!(app.pane_scroll[0], 0);
        assert!(!app.pane_pinned[0]); // unpinned at bottom
    }

    #[test]
    fn test_pane_home_end() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        let buf = app.agent_outputs.get_mut(&AgentType::Claude).unwrap();
        for i in 0..50 {
            buf.push_back(format!("line {}", i));
        }

        app.focus = FocusArea::Pane(0);

        // Home = scroll to top
        app.handle_key(KeyEvent::from(KeyCode::Home), &tx);
        assert_eq!(app.pane_scroll[0], 49); // 50 lines - 1
        assert!(app.pane_pinned[0]);

        // End = scroll to bottom
        app.handle_key(KeyEvent::from(KeyCode::End), &tx);
        assert_eq!(app.pane_scroll[0], 0);
        assert!(!app.pane_pinned[0]);
    }

    #[test]
    fn test_enter_expands_pane() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);

        app.focus = FocusArea::Pane(2);
        app.handle_key(KeyEvent::from(KeyCode::Enter), &tx);
        assert_eq!(app.expanded_pane, Some(2));

        // Esc collapses
        app.handle_key(KeyEvent::from(KeyCode::Esc), &tx);
        assert_eq!(app.expanded_pane, None);
    }

    #[test]
    fn test_expanded_pane_blocks_other_keys() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.expanded_pane = Some(0);

        // Tab should not change focus while expanded
        app.handle_key(KeyEvent::from(KeyCode::Tab), &tx);
        assert_eq!(app.expanded_pane, Some(0)); // still expanded
    }

    #[test]
    fn test_esc_from_pane_returns_to_board() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.focus = FocusArea::Pane(1);
        app.handle_key(KeyEvent::from(KeyCode::Esc), &tx);
        assert_eq!(app.focus, FocusArea::TaskBoard);
        assert!(!app.should_quit);
    }

    #[test]
    fn test_esc_from_board_quits() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.handle_key(KeyEvent::from(KeyCode::Esc), &tx);
        assert!(app.should_quit);
    }

    #[test]
    fn test_push_event_caps_at_limit() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        for i in 0..60 {
            app.push_event(&format!("event {}", i));
        }
        assert_eq!(app.events.len(), EVENT_BUFFER_CAP);
    }

    #[test]
    fn test_cleanup_running_tasks_resets_tracking() {
        let (mut app, _rx, _tx) = App::new(
            PathBuf::from("/tmp/test-cleanup"),
            PathBuf::from("/tmp"),
            3,
            false,
        );
        app.running_task_ids.insert("T-001".to_string());
        app.running_task_ids.insert("T-002".to_string());
        app.agent_running_task
            .insert(AgentType::Claude, "T-001".to_string());
        app.agent_running_task
            .insert(AgentType::Codex, "T-002".to_string());

        app.cleanup_running_tasks();

        assert!(app.running_task_ids.is_empty());
        assert!(app.agent_running_task.is_empty());
    }

    #[test]
    fn test_all_complete_defaults_false() {
        let (app, _rx, _tx) = App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert!(!app.all_complete);
        assert!(app.completed_at.is_none());
    }

    #[test]
    fn test_retry_key_on_non_retryable_status_is_noop() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![make_task("T-001", TaskStatus::Pending, vec![])];
        app.selected_index = 0;
        let events_before = app.events.len();
        app.handle_key(KeyEvent::from(KeyCode::Char('r')), &tx);
        assert_eq!(app.events.len(), events_before);
    }

    #[test]
    fn test_r_key_ignored_when_pane_focused() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![make_task("T-001", TaskStatus::Failed, vec![])];
        app.focus = FocusArea::Pane(0);
        let events_before = app.events.len();
        app.handle_key(KeyEvent::from(KeyCode::Char('r')), &tx);
        // r should only work on task board
        assert_eq!(app.events.len(), events_before);
    }

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

        let mut task = Task::new("T-099", "Orphan", "Was in-progress");
        task.status = TaskStatus::InProgress;
        task.assigned_to = Some(AgentType::Claude);
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-099.json"), &json).unwrap();
        std::fs::write(tasks_dir.join("T-099.md"), "# T-099").unwrap();

        let (mut app, _rx, _tx) = App::new(forge_dir.clone(), tmp.path().to_path_buf(), 3, false);

        app.reset_orphaned_tasks().unwrap();

        let task_mgr = TaskManager::new(&forge_dir);
        let reloaded = task_mgr.get_task("T-099").unwrap();
        assert_eq!(reloaded.status, TaskStatus::Pending);
        assert!(app.events.iter().any(|e| e.contains("orphaned")));
    }

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

        let mut task = Task::new("T-050", "Failed task", "It failed");
        task.status = TaskStatus::Failed;
        task.assigned_to = Some(AgentType::Claude);
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-050.json"), json).unwrap();
        std::fs::write(tasks_dir.join("T-050.md"), "# T-050").unwrap();

        let (mut app, _rx, tx) = App::new(forge_dir.clone(), tmp.path().to_path_buf(), 3, true);
        app.reload_tasks().unwrap();
        app.selected_index = 0;

        app.handle_key(KeyEvent::from(KeyCode::Char('r')), &tx);

        let task_mgr = TaskManager::new(&forge_dir);
        let reloaded = task_mgr.get_task("T-050").unwrap();
        assert_eq!(reloaded.status, TaskStatus::Pending);
        assert!(app.events.iter().any(|e| e.contains("Retrying T-050")));
    }

    #[test]
    fn test_f_key_expands_pane() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.focus = FocusArea::Pane(1);
        app.handle_key(KeyEvent::from(KeyCode::Char('f')), &tx);
        assert_eq!(app.expanded_pane, Some(1));
    }

    #[test]
    fn test_scroll_in_expanded_mode() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        let buf = app.agent_outputs.get_mut(&AgentType::Claude).unwrap();
        for i in 0..30 {
            buf.push_back(format!("line {}", i));
        }
        app.expanded_pane = Some(0);

        app.handle_key(KeyEvent::from(KeyCode::Up), &tx);
        assert_eq!(app.pane_scroll[0], 1);

        app.handle_key(KeyEvent::from(KeyCode::End), &tx);
        assert_eq!(app.pane_scroll[0], 0);
    }

    // ── DX-018: Rate limit backoff tests ─────────────────────────

    #[test]
    fn test_is_rate_limited_detects_429() {
        let mut buf = VecDeque::new();
        buf.push_back("Starting task...".to_string());
        buf.push_back("Error: 429 Too Many Requests".to_string());
        assert!(is_rate_limited(&buf));
    }

    #[test]
    fn test_is_rate_limited_detects_patterns() {
        for pattern in &[
            "rate limit exceeded",
            "RESOURCE_EXHAUSTED",
            "quota exceeded for project",
            "too many requests, please slow down",
        ] {
            let mut buf = VecDeque::new();
            buf.push_back(pattern.to_string());
            assert!(is_rate_limited(&buf), "should detect: {}", pattern);
        }
    }

    #[test]
    fn test_is_rate_limited_false_for_normal_output() {
        let mut buf = VecDeque::new();
        buf.push_back("Compiling project...".to_string());
        buf.push_back("Error: syntax error on line 42".to_string());
        buf.push_back("Build failed with exit code 1".to_string());
        assert!(!is_rate_limited(&buf));
    }

    #[test]
    fn test_is_rate_limited_only_checks_last_20_lines() {
        let mut buf = VecDeque::new();
        // Rate limit pattern buried in old output (> 20 lines ago)
        buf.push_back("Error: 429 Too Many Requests".to_string());
        for i in 0..25 {
            buf.push_back(format!("normal output line {}", i));
        }
        assert!(!is_rate_limited(&buf));
    }

    #[test]
    fn test_backoff_delay_attempt_1() {
        let delay = compute_backoff_delay(1);
        // Attempt 1: 60s base + 0-30s jitter = 60-90s
        assert!(delay.as_secs() >= 60 && delay.as_secs() <= 90);
    }

    #[test]
    fn test_backoff_delay_attempt_2() {
        let delay = compute_backoff_delay(2);
        // Attempt 2: 120s base + 0-30s jitter = 120-150s
        assert!(delay.as_secs() >= 120 && delay.as_secs() <= 150);
    }

    #[test]
    fn test_backoff_delay_attempt_4() {
        let delay = compute_backoff_delay(4);
        // Attempt 4: 480s base + 0-30s jitter = 480-510s
        assert!(delay.as_secs() >= 480 && delay.as_secs() <= 510);
    }

    #[test]
    fn test_is_agent_in_backoff_true() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.agent_backoff.insert(
            AgentType::Gemini,
            BackoffState {
                attempt: 1,
                next_retry: Some(Instant::now() + std::time::Duration::from_secs(60)),
                task_id: "T-001".to_string(),
            },
        );
        assert!(app.is_agent_in_backoff(&AgentType::Gemini));
        assert!(!app.is_agent_in_backoff(&AgentType::Claude));
    }

    #[test]
    fn test_is_agent_in_backoff_false_when_expired() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        // Set next_retry in the past
        app.agent_backoff.insert(
            AgentType::Gemini,
            BackoffState {
                attempt: 1,
                next_retry: Some(Instant::now() - std::time::Duration::from_secs(1)),
                task_id: "T-001".to_string(),
            },
        );
        assert!(!app.is_agent_in_backoff(&AgentType::Gemini));
    }

    #[test]
    fn test_schedule_skips_agent_in_backoff() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.tasks = vec![make_task("T-001", TaskStatus::Pending, vec![])];
        // Claude is in backoff (T-001 is assigned to Claude via make_task)
        app.agent_backoff.insert(
            AgentType::Claude,
            BackoffState {
                attempt: 1,
                next_retry: Some(Instant::now() + std::time::Duration::from_secs(60)),
                task_id: "T-001".to_string(),
            },
        );
        app.schedule_unblocked_tasks(&tx);
        // Should NOT have scheduled T-001
        assert!(!app.running_task_ids.contains("T-001"));
    }

    #[test]
    fn test_check_backoff_timers_clears_expired() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        // Set Gemini backoff that's already expired
        app.agent_backoff.insert(
            AgentType::Gemini,
            BackoffState {
                attempt: 2,
                next_retry: Some(Instant::now() - std::time::Duration::from_secs(1)),
                task_id: "T-005".to_string(),
            },
        );
        app.check_backoff_timers(&tx);
        // next_retry should be cleared
        assert!(
            app.agent_backoff
                .get(&AgentType::Gemini)
                .unwrap()
                .next_retry
                .is_none()
        );
        // attempt should be preserved (for escalation if it fails again)
        assert_eq!(
            app.agent_backoff.get(&AgentType::Gemini).unwrap().attempt,
            2
        );
        // Event should be logged
        assert!(app.events.iter().any(|e| e.contains("Backoff expired")));
    }

    #[test]
    fn test_backoff_reset_on_success_tracking() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.agent_backoff.insert(
            AgentType::Claude,
            BackoffState {
                attempt: 3,
                next_retry: None,
                task_id: "T-001".to_string(),
            },
        );
        assert!(app.agent_backoff.contains_key(&AgentType::Claude));
        // Simulate what handle_agent_event does on success
        app.agent_backoff.remove(&AgentType::Claude);
        assert!(!app.agent_backoff.contains_key(&AgentType::Claude));
    }

    // ── DX-026: Key event starvation fix tests ──────────────────

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

        let (mut app, _rx, tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);

        // First handle_tick should reload (last_task_reload was just set)
        // But since < 2s have elapsed, reload should be skipped
        let before = app.last_task_reload;
        app.handle_tick(&tx).unwrap();
        assert_eq!(app.last_task_reload, before, "should not reload within 2s");

        // Force last_task_reload to 3 seconds ago
        app.last_task_reload = Instant::now() - std::time::Duration::from_secs(3);
        let before = app.last_task_reload;
        app.handle_tick(&tx).unwrap();
        assert_ne!(
            app.last_task_reload, before,
            "should reload after 2s elapsed"
        );
    }

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

        // Create a completed internal task (skipped by verify + UAT generation)
        let mut task = Task::new("T-001", "Refactor internal module", "Internal refactoring");
        task.status = TaskStatus::Completed;
        task.assigned_to = Some(AgentType::Claude);
        task.task_type = Some("document".to_string());
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-001.json"), json).unwrap();

        let (mut app, _rx, tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        app.reload_tasks().unwrap();
        assert!(!app.all_complete);

        // Force reload so handle_tick updates
        // Build→Verify→Complete (first tick), Complete→Ship (second tick)
        app.last_task_reload = Instant::now() - std::time::Duration::from_secs(3);
        app.handle_tick(&tx).unwrap();
        // Second tick for Complete→Ship transition
        app.last_task_reload = Instant::now() - std::time::Duration::from_secs(3);
        app.handle_tick(&tx).unwrap();

        assert_eq!(app.phase, DashboardPhase::Ship);
        assert!(app.all_complete);
        assert!(app.completed_at.is_some());
    }

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

        let mut task = Task::new("T-001", "Done task", "It's done");
        task.status = TaskStatus::Completed;
        task.assigned_to = Some(AgentType::Claude);
        task.task_type = Some("document".to_string());
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-001.json"), json).unwrap();

        let (mut app, _rx, tx) = App::new(
            forge_dir,
            tmp.path().to_path_buf(),
            3,
            true, // watch mode
        );
        app.reload_tasks().unwrap();
        app.last_task_reload = Instant::now() - std::time::Duration::from_secs(3);
        app.handle_tick(&tx).unwrap();

        assert!(!app.all_complete, "watch mode should not auto-complete");
    }

    // ── DX-028: Auto-commit per task tests ──────────────────────

    #[test]
    fn test_commit_type_mapping() {
        assert_eq!(commit_type_for_task(Some("implement")), "feat");
        assert_eq!(commit_type_for_task(Some("test")), "test");
        assert_eq!(commit_type_for_task(Some("document")), "docs");
        assert_eq!(commit_type_for_task(Some("review")), "refactor");
        assert_eq!(commit_type_for_task(Some("design")), "docs");
        assert_eq!(commit_type_for_task(None), "feat");
        assert_eq!(commit_type_for_task(Some("unknown")), "feat");
    }

    #[test]
    fn test_git_auto_commit_skips_when_disabled() {
        let tmp = tempfile::tempdir().unwrap();
        let forge_dir = tmp.path().join(".forge");
        std::fs::create_dir_all(&forge_dir).unwrap();

        // Write state.json with auto_commit = false
        let mut state = crate::core::state::ForgeState::default();
        state.git.auto_commit = false;
        let state_mgr = StateManager::new(&forge_dir);
        state_mgr.save(&state).unwrap();

        // Create a fake .git dir so the git-repo check passes
        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();

        let (mut app, _rx, _tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        let task = Task::new("T-001", "Test task", "desc");

        // Should not push any event because auto_commit is false
        let events_before = app.events.len();
        app.git_auto_commit(&task, &AgentType::Claude);
        assert_eq!(app.events.len(), events_before);
    }

    #[test]
    fn test_git_auto_commit_skips_when_not_git_repo() {
        let tmp = tempfile::tempdir().unwrap();
        let forge_dir = tmp.path().join(".forge");
        std::fs::create_dir_all(&forge_dir).unwrap();

        // No .git directory — not a git repo

        let (mut app, _rx, _tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        let task = Task::new("T-001", "Test task", "desc");

        let events_before = app.events.len();
        app.git_auto_commit(&task, &AgentType::Claude);
        assert_eq!(app.events.len(), events_before);
    }

    #[tokio::test]
    async fn test_git_auto_commit_pushes_event_when_enabled() {
        let tmp = tempfile::tempdir().unwrap();
        let forge_dir = tmp.path().join(".forge");
        std::fs::create_dir_all(&forge_dir).unwrap();

        // Default state has auto_commit = true
        let state = crate::core::state::ForgeState::default();
        let state_mgr = StateManager::new(&forge_dir);
        state_mgr.save(&state).unwrap();

        // Create .git so it's recognized as a git repo
        std::fs::create_dir_all(tmp.path().join(".git")).unwrap();

        let (mut app, _rx, _tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        let mut task = Task::new("T-005", "Add caching layer", "desc");
        task.task_type = Some("implement".to_string());

        app.git_auto_commit(&task, &AgentType::Codex);

        // Should have pushed an event and added to agent output
        assert!(
            app.events
                .iter()
                .any(|e| e.contains("T-005 auto-committed (feat)"))
        );
        let codex_buf = app.agent_outputs.get(&AgentType::Codex).unwrap();
        assert!(
            codex_buf
                .iter()
                .any(|l| l.contains("Auto-committing: feat(T-005)"))
        );
    }

    // ── DX-027: User-spawnable shell pane tests ─────────────────

    #[test]
    fn test_shell_defaults_inactive() {
        let (app, _rx, _tx) = App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert!(!app.shell_active);
        assert!(app.shell_output.is_empty());
        assert!(app.shell_input_tx.is_none());
    }

    #[test]
    fn test_shell_output_routes_to_shell_buffer() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.shell_active = true;

        // Simulate shell output via handle_agent_event
        let event = AgentEvent::Output {
            task_id: "__shell__".to_string(),
            agent: AgentType::Any,
            line: "hello world".to_string(),
        };
        // Need a tx for handle_agent_event
        let (tx, _rx2) = mpsc::unbounded_channel();
        app.handle_agent_event(event, &tx).unwrap();

        assert_eq!(app.shell_output.len(), 1);
        assert_eq!(app.shell_output[0], "hello world");
        // Should NOT be in agent_outputs
        assert!(
            app.agent_outputs.get(&AgentType::Any).is_none()
                || app.agent_outputs.get(&AgentType::Any).unwrap().is_empty()
        );
    }

    #[test]
    fn test_shell_completion_resets_state() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.shell_active = true;
        app.shell_input_tx = Some(mpsc::unbounded_channel().0);

        let event = AgentEvent::Completed {
            task_id: "__shell__".to_string(),
            agent: AgentType::Any,
            success: true,
            exit_code: 0,
        };
        let (tx, _rx2) = mpsc::unbounded_channel();
        app.handle_agent_event(event, &tx).unwrap();

        assert!(!app.shell_active);
        assert!(app.shell_input_tx.is_none());
        assert!(app.events.iter().any(|e| e.contains("shell closed")));
    }

    #[test]
    fn test_esc_in_shell_pane_returns_to_taskboard() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.shell_active = true;
        app.shell_input_tx = Some(mpsc::unbounded_channel().0);
        app.focus = FocusArea::Pane(3);

        app.handle_key(KeyEvent::from(KeyCode::Esc), &tx);
        // Esc should move focus back to task board, not send to shell
        assert_eq!(app.focus, FocusArea::TaskBoard);
        assert!(app.shell_active); // Shell still running
    }

    #[test]
    fn test_s_key_focuses_shell_pane() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        // Manually set shell_active to simulate it was already spawned
        // (can't actually spawn_shell without tokio runtime)
        app.shell_active = true;

        app.focus = FocusArea::TaskBoard;
        app.handle_key(KeyEvent::from(KeyCode::Char('s')), &tx);
        assert_eq!(app.focus, FocusArea::Pane(3));
    }

    #[test]
    fn test_shell_not_double_spawnable() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.shell_active = true;
        app.shell_output.push_back("existing output".to_string());

        let (_tx, _rx2) = mpsc::unbounded_channel::<AgentEvent>();
        // spawn_shell should be a no-op when already active
        // We can't call it without tokio, but we test the guard:
        assert!(app.shell_active);
        // Calling spawn_shell would just return early due to shell_active check
        // so test that the output buffer is NOT cleared
        assert_eq!(app.shell_output.len(), 1);
    }

    // ── Part 2: Dashboard phase tests ────────────────────────────

    #[test]
    fn test_phase_starts_as_build() {
        let (app, _rx, _tx) = App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert_eq!(app.phase, DashboardPhase::Build);
    }

    #[test]
    fn test_phase_transitions_build_to_verify() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        // All build tasks completed → should transition to Verify
        let mut t1 = make_task("T-001", TaskStatus::Completed, vec![]);
        t1.phase = None; // build phase (None = build)
        let mut t2 = make_task("T-002", TaskStatus::Completed, vec![]);
        t2.phase = None;
        app.tasks = vec![t1, t2];

        assert!(app.check_phase_transition());
        assert_eq!(app.phase, DashboardPhase::Verify);
        assert!(app.events.iter().any(|e| e.contains("BUILD")));
    }

    #[test]
    fn test_phase_does_not_transition_with_pending() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        let mut t1 = make_task("T-001", TaskStatus::Completed, vec![]);
        t1.phase = None;
        let mut t2 = make_task("T-002", TaskStatus::Pending, vec![]);
        t2.phase = None;
        app.tasks = vec![t1, t2];

        assert!(!app.check_phase_transition());
        assert_eq!(app.phase, DashboardPhase::Build);
    }

    #[test]
    fn test_phase_transitions_verify_to_complete() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.phase = DashboardPhase::Verify;

        let mut v1 = make_task("V-001", TaskStatus::Completed, vec![]);
        v1.phase = Some(TaskPhase::Verify);
        let mut v2 = make_task("V-002", TaskStatus::Completed, vec![]);
        v2.phase = Some(TaskPhase::Verify);
        // Include a build task (already done) — it shouldn't block verify completion
        let t1 = make_task("T-001", TaskStatus::Completed, vec![]);
        app.tasks = vec![t1, v1, v2];

        assert!(app.check_phase_transition());
        assert_eq!(app.phase, DashboardPhase::Complete);
        assert!(app.events.iter().any(|e| e.contains("VERIFY")));
    }

    #[test]
    fn test_verify_to_complete_with_no_verify_tasks() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.phase = DashboardPhase::Verify;
        // No verify or fix tasks → should go straight to Complete
        let t1 = make_task("T-001", TaskStatus::Completed, vec![]);
        app.tasks = vec![t1];

        assert!(app.check_phase_transition());
        assert_eq!(app.phase, DashboardPhase::Complete);
    }

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

        // Create a parent task
        let mut parent = Task::new("T-001", "Auth module", "Implement auth");
        parent.status = TaskStatus::Completed;
        parent.task_type = Some("implement".to_string());
        let json = serde_json::to_string_pretty(&parent).unwrap();
        std::fs::write(tasks_dir.join("T-001.json"), &json).unwrap();
        std::fs::write(tasks_dir.join("T-001.md"), "# T-001").unwrap();

        // Create a failed verify task
        let mut verify = Task::new("V-001", "Verify: Auth module", "Run tests");
        verify.phase = Some(TaskPhase::Verify);
        verify.parent_task = Some("T-001".to_string());
        verify.retry_count = 0;
        verify.status = TaskStatus::Failed;
        verify.assigned_to = Some(AgentType::Codex);
        let json = serde_json::to_string_pretty(&verify).unwrap();
        std::fs::write(tasks_dir.join("V-001.json"), &json).unwrap();
        std::fs::write(tasks_dir.join("V-001.md"), "# V-001").unwrap();

        let (mut app, _rx, _tx) = App::new(forge_dir.clone(), tmp.path().to_path_buf(), 3, false);
        app.phase = DashboardPhase::Verify;

        app.handle_verify_failure(&verify);

        // Should have generated a fix task and a re-verify task
        let task_mgr = TaskManager::new(&forge_dir);
        let tasks = task_mgr.list_tasks().unwrap();

        // Should have T-001, V-001, T-002 (fix), V-002 (re-verify)
        assert_eq!(tasks.len(), 4);

        let fix = tasks.iter().find(|t| t.id == "T-002").unwrap();
        assert_eq!(fix.phase, Some(TaskPhase::Fix));
        assert!(fix.title.contains("Fix:"));

        let re_verify = tasks.iter().find(|t| t.id == "V-002").unwrap();
        assert_eq!(re_verify.phase, Some(TaskPhase::Verify));
        assert_eq!(re_verify.retry_count, 1);
        assert_eq!(re_verify.depends_on, vec!["T-002".to_string()]);

        assert!(app.events.iter().any(|e| e.contains("retry 1/3")));
    }

    #[test]
    fn test_verify_failure_stops_after_3_retries() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.phase = DashboardPhase::Verify;

        let mut verify = Task::new("V-001", "Verify: Auth", "Run tests");
        verify.phase = Some(TaskPhase::Verify);
        verify.retry_count = 3; // Already at max
        verify.status = TaskStatus::Failed;

        app.handle_verify_failure(&verify);

        assert!(
            app.events
                .iter()
                .any(|e| e.contains("needs human attention"))
        );
        // No fix task should be generated — we can't easily test TaskManager
        // without a real forge_dir, but the event message confirms the path
    }

    #[test]
    fn test_dashboard_phase_display() {
        assert_eq!(DashboardPhase::Build.to_string(), "BUILD");
        assert_eq!(DashboardPhase::Verify.to_string(), "VERIFY");
        assert_eq!(DashboardPhase::Complete.to_string(), "COMPLETE");
        assert_eq!(DashboardPhase::Ship.to_string(), "SHIP");
    }

    // ── DX-029: Stream-JSON parser tests ─────────────────────────

    #[test]
    fn test_parse_stream_json_init() {
        let lines = parse_stream_json_line(r#"{"type":"init","session_id":"abc"}"#);
        assert_eq!(lines, vec!["[session started]"]);
    }

    #[test]
    fn test_parse_stream_json_text_message() {
        let lines = parse_stream_json_line(
            r#"{"type":"message","role":"assistant","content":[{"type":"text","text":"Hello world"}]}"#,
        );
        assert_eq!(lines, vec!["Hello world"]);
    }

    #[test]
    fn test_parse_stream_json_tool_use() {
        let lines = parse_stream_json_line(
            r#"{"type":"message","content":[{"type":"tool_use","name":"Read","input":{"file_path":"src/main.rs"}}]}"#,
        );
        assert_eq!(lines, vec!["[Read] src/main.rs"]);
    }

    #[test]
    fn test_parse_stream_json_tool_use_bash() {
        let lines = parse_stream_json_line(
            r#"{"type":"message","content":[{"type":"tool_use","name":"Bash","input":{"command":"npm test"}}]}"#,
        );
        assert_eq!(lines, vec!["[Bash] npm test"]);
    }

    #[test]
    fn test_parse_stream_json_result() {
        let lines =
            parse_stream_json_line(r#"{"type":"result","status":"success","duration_ms":45000}"#);
        assert_eq!(lines, vec!["[done] success in 45.0s"]);
    }

    #[test]
    fn test_parse_stream_json_tool_result_skipped() {
        let lines = parse_stream_json_line(r#"{"type":"tool_result","output":"lots of stuff"}"#);
        assert!(lines.is_empty());
    }

    #[test]
    fn test_parse_stream_json_invalid_json_fallback() {
        let lines = parse_stream_json_line("not json at all");
        assert_eq!(lines, vec!["not json at all"]);
    }

    #[test]
    fn test_parse_stream_json_empty_line() {
        let lines = parse_stream_json_line("");
        assert!(lines.is_empty());
    }

    #[test]
    fn test_summarize_tool_input_read() {
        let input: serde_json::Value = serde_json::json!({"file_path": "src/main.rs"});
        assert_eq!(summarize_tool_input("Read", Some(&input)), "src/main.rs");
    }

    #[test]
    fn test_summarize_tool_input_bash_truncate() {
        let long_cmd = "a".repeat(100);
        let input: serde_json::Value = serde_json::json!({"command": long_cmd});
        let result = summarize_tool_input("Bash", Some(&input));
        assert!(result.len() <= 63); // 60 + "..."
        assert!(result.ends_with("..."));
    }

    #[test]
    fn test_truncate_str_short() {
        assert_eq!(truncate_str("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_str_long() {
        assert_eq!(truncate_str("hello world this is long", 10), "hello w...");
    }

    // ── DX-037: Quota monitoring tests ──────────────────────────────

    #[test]
    fn test_quota_counter_increments() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);

        // Simulate quota increments
        let quota = app
            .provider_quota
            .entry(AgentType::Claude)
            .or_insert((0, Instant::now()));
        quota.0 += 1;
        assert_eq!(app.provider_quota[&AgentType::Claude].0, 1);

        app.provider_quota.get_mut(&AgentType::Claude).unwrap().0 += 1;
        assert_eq!(app.provider_quota[&AgentType::Claude].0, 2);
    }

    #[test]
    fn test_quota_window_resets_after_5h() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);

        // Insert a quota entry with a stale window (pretend it started 6 hours ago)
        let old_start = Instant::now() - std::time::Duration::from_secs(6 * 3600);
        app.provider_quota
            .insert(AgentType::Claude, (42, old_start));

        // Simulate the reset logic from spawn_task
        let quota = app
            .provider_quota
            .entry(AgentType::Claude)
            .or_insert((0, Instant::now()));
        if quota.1.elapsed() > std::time::Duration::from_secs(5 * 3600) {
            *quota = (0, Instant::now());
        }
        quota.0 += 1;

        assert_eq!(app.provider_quota[&AgentType::Claude].0, 1);
    }

    #[test]
    fn test_quota_separate_per_agent() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);

        app.provider_quota
            .insert(AgentType::Claude, (5, Instant::now()));
        app.provider_quota
            .insert(AgentType::Codex, (10, Instant::now()));
        app.provider_quota
            .insert(AgentType::Gemini, (15, Instant::now()));

        assert_eq!(app.provider_quota[&AgentType::Claude].0, 5);
        assert_eq!(app.provider_quota[&AgentType::Codex].0, 10);
        assert_eq!(app.provider_quota[&AgentType::Gemini].0, 15);
    }

    // ── DX-024: Stargate PTY mode tests ─────────────────────────

    // ── DX-050: Builder Mode tests ─────────────────────────────

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

        // Create a pending task assigned to Claude
        let mut task = Task::new("T-010", "Build auth", "Implement auth module");
        task.status = TaskStatus::Pending;
        task.assigned_to = Some(AgentType::Claude);
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-010.json"), &json).unwrap();
        std::fs::write(tasks_dir.join("T-010.md"), "# T-010").unwrap();

        let (mut app, _rx, tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        app.reload_tasks().unwrap();
        app.pty_mode = true;
        app.selected_index = 0;

        // Simulate a running PTY session for Claude with a ready prompt
        // We can't easily create a real PtySession in tests, but we can test
        // the guards: dispatch should fail without a PTY session
        app.handle_key(KeyEvent::from(KeyCode::Char('a')), &tx);
        // Should log "TUI not running" since no pty_sessions
        assert!(app.events.iter().any(|e| e.contains("not running")));
    }

    #[test]
    fn test_dispatch_to_tui_busy_agent() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.pty_mode = true;
        app.focus = FocusArea::TaskBoard;

        let mut task = make_task("T-001", TaskStatus::Pending, vec![]);
        task.assigned_to = Some(AgentType::Claude);
        app.tasks = vec![task];
        app.selected_index = 0;

        // Claude is already running a task
        app.agent_running_task
            .insert(AgentType::Claude, "T-999".to_string());

        app.dispatch_to_tui(&tx);
        // Should log "busy" since agent already running
        // Note: this will first fail on "TUI not running" since no pty_sessions
        assert!(
            app.events
                .iter()
                .any(|e| e.contains("not running") || e.contains("busy")),
            "Expected dispatch guard message, got: {:?}",
            app.events
        );
    }

    #[test]
    fn test_completion_detection_too_early() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.pty_mode = true;

        // Insert awaiting completion that was just dispatched (now)
        app.awaiting_completion.insert(
            AgentType::Claude,
            AwaitingCompletion {
                task_id: "T-001".to_string(),
                dispatched_at: Instant::now(),
                last_output_at: Instant::now(),
                pattern_disappeared: false,
            },
        );

        // Should NOT fire completion — less than 10s elapsed
        app.check_pty_completion(&tx);
        assert!(
            app.awaiting_completion.contains_key(&AgentType::Claude),
            "Should not complete before 10s minimum"
        );
    }

    #[test]
    fn test_completion_detection_quiet_period() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.pty_mode = true;

        // Insert awaiting completion that was dispatched 15s ago, output quiet 5s
        let now = Instant::now();
        app.awaiting_completion.insert(
            AgentType::Claude,
            AwaitingCompletion {
                task_id: "T-001".to_string(),
                dispatched_at: now - Duration::from_secs(15),
                last_output_at: now - Duration::from_secs(5),
                pattern_disappeared: true,
            },
        );

        // No PTY session — check_pty_completion should skip (no session to check pattern)
        app.check_pty_completion(&tx);
        assert!(
            app.awaiting_completion.contains_key(&AgentType::Claude),
            "Should not complete without PTY session"
        );
    }

    #[test]
    fn test_awaiting_completion_cleared_on_cleanup() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.awaiting_completion.insert(
            AgentType::Claude,
            AwaitingCompletion {
                task_id: "T-001".to_string(),
                dispatched_at: Instant::now(),
                last_output_at: Instant::now(),
                pattern_disappeared: false,
            },
        );
        assert!(!app.awaiting_completion.is_empty());
        app.cleanup_running_tasks();
        assert!(app.awaiting_completion.is_empty());
    }

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

        let (mut app, _rx, tx) = App::new(forge_dir, tmp.path().to_path_buf(), 3, false);
        assert_eq!(app.spinner_frame, 0);
        app.handle_tick(&tx).unwrap();
        assert_eq!(app.spinner_frame, 1);
        // Cycle through
        for _ in 0..9 {
            app.handle_tick(&tx).unwrap();
        }
        assert_eq!(app.spinner_frame, 0); // wrapped around
    }

    #[test]
    fn test_pty_mode_defaults_off() {
        let (app, _rx, _tx) = App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        assert!(!app.pty_mode);
        assert!(app.pty_sessions.is_empty());
        assert!(app.attached_pane.is_none());
        assert!(app.shell_pty.is_none());
    }

    #[test]
    fn test_estimate_pane_size() {
        let (mut app, _rx, _tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.terminal_size = (120, 40);
        let (cols, rows) = app.estimate_pane_size();
        // Half of 120 = 60, minus 2 borders = 58
        assert_eq!(cols, 58);
        // 40 / 4 = 10, minus 2 borders = 8
        assert_eq!(rows, 8);
    }

    #[test]
    fn test_attached_pane_detach() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.attached_pane = Some(0);

        // Esc should detach
        app.handle_key(KeyEvent::from(KeyCode::Esc), &tx);
        assert!(app.attached_pane.is_none());
    }

    #[test]
    fn test_i_key_attaches_in_pty_mode() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.pty_mode = true;
        app.focus = FocusArea::Pane(0);

        // No PTY session yet — 'i' should not attach
        app.handle_key(KeyEvent::from(KeyCode::Char('i')), &tx);
        assert!(app.attached_pane.is_none());

        // 'i' in non-PTY mode should also not attach
        app.pty_mode = false;
        app.handle_key(KeyEvent::from(KeyCode::Char('i')), &tx);
        assert!(app.attached_pane.is_none());
    }

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

        let mut task = Task::new("T-020", "Test cycle", "Test agent cycling");
        task.status = TaskStatus::Pending;
        task.assigned_to = Some(AgentType::Claude);
        let json = serde_json::to_string_pretty(&task).unwrap();
        std::fs::write(tasks_dir.join("T-020.json"), &json).unwrap();
        std::fs::write(tasks_dir.join("T-020.md"), "# T-020").unwrap();

        let (mut app, _rx, tx) = App::new(forge_dir.clone(), tmp.path().to_path_buf(), 3, false);
        app.reload_tasks().unwrap();
        app.focus = FocusArea::TaskBoard;
        app.selected_index = 0;

        // Claude → Codex
        app.handle_key(KeyEvent::from(KeyCode::Char('c')), &tx);
        app.reload_tasks().unwrap();
        assert_eq!(app.tasks[0].assigned_to, Some(AgentType::Codex));

        // Codex → Gemini
        app.handle_key(KeyEvent::from(KeyCode::Char('c')), &tx);
        app.reload_tasks().unwrap();
        assert_eq!(app.tasks[0].assigned_to, Some(AgentType::Gemini));

        // Gemini → Claude
        app.handle_key(KeyEvent::from(KeyCode::Char('c')), &tx);
        app.reload_tasks().unwrap();
        assert_eq!(app.tasks[0].assigned_to, Some(AgentType::Claude));
    }

    #[test]
    fn test_cycle_agent_blocked_on_running_task() {
        let (mut app, _rx, tx) =
            App::new(PathBuf::from("/tmp/test"), PathBuf::from("/tmp"), 3, false);
        app.focus = FocusArea::TaskBoard;

        let mut task = make_task("T-021", TaskStatus::InProgress, vec![]);
        task.assigned_to = Some(AgentType::Claude);
        app.tasks = vec![task];
        app.selected_index = 0;

        app.handle_key(KeyEvent::from(KeyCode::Char('c')), &tx);
        // Should not cycle — task is InProgress
        assert!(app.events.iter().any(|e| e.contains("can only reassign")));
    }
}