codewhale-tui 0.8.61

Terminal UI for open-source and open-weight coding models
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
use super::*;
use crate::worker_profile::ShellPolicy;
use axum::{Json, Router, routing::post};
use std::process::Command;
use std::sync::atomic::{AtomicUsize, Ordering};
use tempfile::tempdir;

fn make_assignment() -> SubAgentAssignment {
    SubAgentAssignment::new("prompt".to_string(), Some("worker".to_string()))
}

fn make_snapshot(status: SubAgentStatus) -> SubAgentResult {
    SubAgentResult {
        name: "agent_test".to_string(),
        agent_id: "agent_test".to_string(),
        context_mode: "fresh".to_string(),
        fork_context: false,
        workspace: None,
        git_branch: None,
        agent_type: SubAgentType::General,
        assignment: make_assignment(),
        model: "deepseek-v4-flash".to_string(),
        nickname: None,
        status,
        worker_status: None,
        result: None,
        steps_taken: 0,
        checkpoint: None,
        needs_input: None,
        duration_ms: 0,
        from_prior_session: false,
    }
}

fn make_worker_spec(worker_id: &str, workspace: PathBuf) -> AgentWorkerSpec {
    let tool_profile =
        AgentWorkerToolProfile::Explicit(vec!["read_file".to_string(), "grep_files".to_string()]);
    let mut runtime_profile = WorkerRuntimeProfile::for_role(SubAgentType::Explore);
    runtime_profile.tools =
        ToolScope::Explicit(vec!["read_file".to_string(), "grep_files".to_string()]);
    runtime_profile.model = ModelRoute::Fixed("deepseek-v4-flash".to_string());
    runtime_profile.max_spawn_depth = DEFAULT_MAX_SPAWN_DEPTH.saturating_sub(1);
    AgentWorkerSpec {
        worker_id: worker_id.to_string(),
        run_id: worker_id.to_string(),
        parent_run_id: None,
        session_name: Some(worker_id.to_string()),
        objective: "inspect the repo".to_string(),
        role: Some("explorer".to_string()),
        agent_type: SubAgentType::Explore,
        model: "deepseek-v4-flash".to_string(),
        workspace,
        git_branch: None,
        context_mode: "fresh".to_string(),
        fork_context: false,
        tool_profile,
        runtime_profile,
        max_steps: 8,
        spawn_depth: 1,
        max_spawn_depth: DEFAULT_MAX_SPAWN_DEPTH,
    }
}

#[test]
fn headless_worker_record_tracks_lifecycle_without_tui_projection() {
    let tmp = tempdir().expect("tempdir");
    let mut manager = SubAgentManager::new(tmp.path().to_path_buf(), 4);
    manager.register_worker(make_worker_spec(
        "agent_worker_contract",
        tmp.path().to_path_buf(),
    ));

    manager.record_worker_event(
        "agent_worker_contract",
        AgentWorkerStatus::Queued,
        Some(SUBAGENT_QUEUED_LAUNCH_REASON.to_string()),
        None,
        None,
    );
    manager.record_worker_progress(
        "agent_worker_contract",
        "step 1: requesting model response".to_string(),
    );
    manager.record_worker_progress(
        "agent_worker_contract",
        "step 1: running tool 'read_file'".to_string(),
    );

    let mut result = make_snapshot(SubAgentStatus::Completed);
    result.agent_id = "agent_worker_contract".to_string();
    result.name = "agent_worker_contract".to_string();
    result.result = Some("worker summary".to_string());
    result.steps_taken = 1;
    manager.complete_worker_from_result("agent_worker_contract", &result);

    let record = manager
        .get_worker_record("agent_worker_contract")
        .expect("worker record");
    assert_eq!(record.status, AgentWorkerStatus::Completed);
    assert_eq!(record.spec.run_id, "agent_worker_contract");
    assert_eq!(record.actor_kind, "subagent");
    assert_eq!(record.spec.agent_type, SubAgentType::Explore);
    assert_eq!(
        record.spec.tool_profile,
        AgentWorkerToolProfile::Explicit(vec!["read_file".to_string(), "grep_files".to_string()])
    );
    assert_eq!(record.spec.runtime_profile.role, SubAgentType::Explore);
    assert!(!record.spec.runtime_profile.permissions.write);
    assert_eq!(
        record.spec.runtime_profile.tools,
        ToolScope::Explicit(vec!["read_file".to_string(), "grep_files".to_string()])
    );
    assert_eq!(
        record.spec.runtime_profile.model,
        ModelRoute::Fixed("deepseek-v4-flash".to_string())
    );
    assert_eq!(record.result_summary.as_deref(), Some("worker summary"));
    assert_eq!(record.steps_taken, 1);
    assert_eq!(record.follow_up.tool, "handle_read");
    assert_eq!(record.follow_up.agent_id.as_str(), "agent_worker_contract");
    assert_eq!(record.recommended_action.action, "verify_self_report");
    assert_eq!(
        record.recommended_action.tool.as_deref(),
        Some("handle_read")
    );
    assert!(record.takeover.supported);
    assert!(
        record
            .takeover
            .instructions
            .contains("transcript_handle with handle_read")
    );
    assert_eq!(record.usage.status, "unknown");
    assert_eq!(record.verification.status, "self_report_only");
    assert!(
        record
            .artifacts
            .iter()
            .any(|artifact| artifact.kind == "transcript")
    );
    let statuses: Vec<_> = record.events.iter().map(|event| event.status).collect();
    assert!(statuses.contains(&AgentWorkerStatus::Queued));
    assert!(statuses.contains(&AgentWorkerStatus::ModelWait));
    assert!(statuses.contains(&AgentWorkerStatus::RunningTool));
    assert!(statuses.contains(&AgentWorkerStatus::Completed));
    assert!(
        record
            .events
            .iter()
            .any(|event| event.tool_name.as_deref() == Some("read_file"))
    );
}

#[test]
fn agent_worker_profile_derives_from_parent_without_escalation() {
    let mut runtime = stub_runtime();
    runtime.worker_profile = WorkerRuntimeProfile::for_role(SubAgentType::Explore);
    runtime.spawn_depth = 1;
    runtime.max_spawn_depth = DEFAULT_MAX_SPAWN_DEPTH;
    let tool_profile =
        AgentWorkerToolProfile::Explicit(vec!["read_file".to_string(), "write_file".to_string()]);

    let profile = worker_profile_for_spawn(
        &runtime,
        &SubAgentType::Implementer,
        &tool_profile,
        "deepseek-v4-pro",
        Some(ModelRoute::Fixed("deepseek-v4-pro".to_string())),
    );

    assert_eq!(profile.role, SubAgentType::Implementer);
    assert!(
        !profile.permissions.write,
        "child cannot gain write permission from a read-only parent profile"
    );
    assert_eq!(profile.shell, ShellPolicy::ReadOnly);
    assert_eq!(profile.max_spawn_depth, DEFAULT_MAX_SPAWN_DEPTH - 1);
    assert_eq!(
        profile.model,
        ModelRoute::Fixed("deepseek-v4-pro".to_string())
    );
    assert_eq!(
        profile.tools,
        ToolScope::Explicit(vec!["read_file".to_string(), "write_file".to_string()])
    );
}

#[test]
fn subagent_progress_displays_shell_tools_as_bash() {
    assert_eq!(subagent_progress_tool_display_name("exec_shell"), "Bash");
    assert_eq!(subagent_progress_tool_display_name("exec_wait"), "Bash");
    assert_eq!(
        subagent_progress_tool_display_name("task_shell_wait"),
        "Bash"
    );
    assert_eq!(
        subagent_progress_tool_display_name("read_file"),
        "read_file"
    );
}

#[test]
fn headless_worker_records_persist_with_subagent_state() {
    let tmp = tempdir().expect("tempdir");
    let state_path = tmp.path().join("subagents.v1.json");
    let mut manager =
        SubAgentManager::new(tmp.path().to_path_buf(), 4).with_state_path(state_path.clone());
    manager.register_worker(make_worker_spec(
        "agent_persisted",
        tmp.path().to_path_buf(),
    ));

    let mut result = make_snapshot(SubAgentStatus::Failed("boom".to_string()));
    result.agent_id = "agent_persisted".to_string();
    result.name = "agent_persisted".to_string();
    result.steps_taken = 3;
    manager.complete_worker_from_result("agent_persisted", &result);
    manager.persist_state().expect("persist state");

    let mut loaded = SubAgentManager::new(tmp.path().to_path_buf(), 4).with_state_path(state_path);
    loaded.load_state().expect("load state");

    let record = loaded.get_worker_record("agent_persisted").expect("record");
    assert_eq!(record.spec.run_id, "agent_persisted");
    assert_eq!(record.follow_up.agent_id, "agent_persisted");
    assert!(record.takeover.supported);
    assert_eq!(record.status, AgentWorkerStatus::Failed);
    assert_eq!(record.error.as_deref(), Some("boom"));
    assert_eq!(record.steps_taken, 3);
    assert!(
        record
            .events
            .iter()
            .any(|event| event.status == AgentWorkerStatus::Failed)
    );
}

fn init_subagent_git_repo() -> tempfile::TempDir {
    let dir = tempdir().expect("tempdir");

    let init = Command::new("git")
        .arg("init")
        .current_dir(dir.path())
        .output()
        .expect("git init should run");
    assert!(
        init.status.success(),
        "git init failed: {}",
        String::from_utf8_lossy(&init.stderr)
    );

    let autocrlf = Command::new("git")
        .args(["config", "core.autocrlf", "false"])
        .current_dir(dir.path())
        .output()
        .expect("git config core.autocrlf should run");
    assert!(
        autocrlf.status.success(),
        "git config core.autocrlf failed: {}",
        String::from_utf8_lossy(&autocrlf.stderr)
    );

    let commit = Command::new("git")
        .args([
            "-c",
            "user.name=codewhale Tests",
            "-c",
            "user.email=tests@example.com",
            "-c",
            "commit.gpgsign=false",
            "commit",
            "--allow-empty",
            "-m",
            "init",
        ])
        .current_dir(dir.path())
        .output()
        .expect("git commit should run");
    assert!(
        commit.status.success(),
        "git commit failed: {}",
        String::from_utf8_lossy(&commit.stderr)
    );

    dir
}

fn git(repo: &Path, args: &[&str]) {
    let output = Command::new("git")
        .args(args)
        .current_dir(repo)
        .output()
        .expect("git command should run");
    assert!(
        output.status.success(),
        "git {args:?} failed: {}",
        String::from_utf8_lossy(&output.stderr)
    );
}

fn text_message(role: &str, text: &str) -> Message {
    Message {
        role: role.to_string(),
        content: vec![ContentBlock::Text {
            text: text.to_string(),
            cache_control: None,
        }],
    }
}

fn make_checkpoint(agent_id: &str, steps_taken: u32, messages: Vec<Message>) -> SubAgentCheckpoint {
    build_subagent_checkpoint(agent_id, "test_checkpoint", &messages, steps_taken, true)
}

fn message_text(message: &Message) -> &str {
    match message.content.first() {
        Some(ContentBlock::Text { text, .. }) => text.as_str(),
        other => panic!("expected text content block, got {other:?}"),
    }
}

async fn delayed_chat_client(
    first_delay: Duration,
    response_text: &str,
) -> (
    DeepSeekClient,
    Arc<AtomicUsize>,
    Arc<std::sync::Mutex<Vec<Value>>>,
) {
    let calls = Arc::new(AtomicUsize::new(0));
    let bodies = Arc::new(std::sync::Mutex::new(Vec::new()));
    let response_text = response_text.to_string();
    let app = Router::new().route(
        "/{*path}",
        post({
            let calls = Arc::clone(&calls);
            let bodies = Arc::clone(&bodies);
            move |Json(body): Json<Value>| {
                let calls = Arc::clone(&calls);
                let bodies = Arc::clone(&bodies);
                let response_text = response_text.clone();
                async move {
                    let attempt = calls.fetch_add(1, Ordering::SeqCst) + 1;
                    bodies
                        .lock()
                        .expect("request body recorder mutex poisoned")
                        .push(body);
                    if attempt == 1 {
                        tokio::time::sleep(first_delay).await;
                    }
                    Json(json!({
                        "id": format!("chatcmpl-test-{attempt}"),
                        "model": "deepseek-v4-flash",
                        "choices": [{
                            "index": 0,
                            "message": {
                                "role": "assistant",
                                "content": response_text
                            },
                            "finish_reason": "stop"
                        }],
                        "usage": {
                            "prompt_tokens": 1,
                            "completion_tokens": 1,
                            "total_tokens": 2
                        }
                    }))
                }
            }
        }),
    );

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
        .await
        .expect("bind fake chat server");
    let addr = listener.local_addr().expect("fake chat server addr");
    tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });

    let config = crate::config::Config {
        api_key: Some("test-key".to_string()),
        base_url: Some(format!("http://{addr}/v1")),
        ..crate::config::Config::default()
    };
    let client = DeepSeekClient::new(&config).expect("fake chat client");
    (client, calls, bodies)
}

fn estimate_tool_description_tokens_conservative(text: &str) -> usize {
    text.chars().count().div_ceil(3)
}

#[test]
fn test_agent_type_from_str() {
    assert_eq!(
        SubAgentType::from_str("general"),
        Some(SubAgentType::General)
    );
    assert_eq!(
        SubAgentType::from_str("explore"),
        Some(SubAgentType::Explore)
    );
    assert_eq!(SubAgentType::from_str("PLAN"), Some(SubAgentType::Plan));
    assert_eq!(
        SubAgentType::from_str("code-review"),
        Some(SubAgentType::Review)
    );
    assert_eq!(
        SubAgentType::from_str("worker"),
        Some(SubAgentType::General)
    );
    assert_eq!(
        SubAgentType::from_str("default"),
        Some(SubAgentType::General)
    );
    assert_eq!(
        SubAgentType::from_str("explorer"),
        Some(SubAgentType::Explore)
    );
    assert_eq!(SubAgentType::from_str("awaiter"), Some(SubAgentType::Plan));
    assert_eq!(SubAgentType::from_str("invalid"), None);
}

#[test]
fn test_agent_type_implementer_aliases() {
    // #404 — Implementer accepts the obvious aliases the model is
    // likely to reach for when the user says "build this".
    for alias in ["implementer", "implement", "implementation", "builder"] {
        assert_eq!(
            SubAgentType::from_str(alias),
            Some(SubAgentType::Implementer),
            "alias {alias} should resolve to Implementer"
        );
    }
    // Case-insensitive.
    assert_eq!(
        SubAgentType::from_str("IMPLEMENTER"),
        Some(SubAgentType::Implementer)
    );
}

#[test]
fn test_agent_type_verifier_aliases() {
    // #404 — Verifier accepts test/validate aliases distinct from
    // Reviewer, which is for *grading* code rather than *running* it.
    for alias in ["verifier", "verify", "verification", "validator", "tester"] {
        assert_eq!(
            SubAgentType::from_str(alias),
            Some(SubAgentType::Verifier),
            "alias {alias} should resolve to Verifier"
        );
    }
    assert_eq!(
        SubAgentType::from_str("VERIFY"),
        Some(SubAgentType::Verifier)
    );
}

#[test]
fn test_agent_type_round_trips_via_as_str() {
    // Every type should serialize to a string that round-trips back
    // through `from_str`. Catches missed variants when adding a new
    // role.
    for t in [
        SubAgentType::General,
        SubAgentType::Explore,
        SubAgentType::Plan,
        SubAgentType::Review,
        SubAgentType::Implementer,
        SubAgentType::Verifier,
        SubAgentType::Custom,
    ] {
        let label = t.as_str();
        let back = SubAgentType::from_str(label)
            .unwrap_or_else(|| panic!("as_str label {label:?} doesn't round-trip via from_str"));
        assert_eq!(back, t, "round-trip failed for {t:?} via {label:?}");
    }
}

#[test]
fn test_implementer_and_verifier_have_distinct_prompts() {
    // The whole point of adding the types is that they carry distinct
    // posture. Defensive guard: catch the easy bug where copy-paste
    // leaves two new variants with the same prompt as `General`.
    let implementer = SubAgentType::Implementer.system_prompt();
    let verifier = SubAgentType::Verifier.system_prompt();
    let general = SubAgentType::General.system_prompt();
    assert_ne!(
        implementer, general,
        "Implementer prompt must differ from General"
    );
    assert_ne!(
        verifier, general,
        "Verifier prompt must differ from General"
    );
    assert_ne!(
        implementer, verifier,
        "Implementer and Verifier must differ"
    );
    // Sanity: each prompt mentions the role's defining verb so the
    // model has clear direction.
    assert!(
        implementer.to_lowercase().contains("implement")
            || implementer.to_lowercase().contains("write the code"),
        "Implementer prompt should reference its role: {implementer}"
    );
    assert!(
        verifier.to_lowercase().contains("verif")
            || verifier.to_lowercase().contains("test suite")
            || verifier.to_lowercase().contains("validation"),
        "Verifier prompt should reference its role: {verifier}"
    );
}

#[test]
fn test_agent_type_prompts_include_shared_output_contract_once() {
    for (agent_type, marker) in [
        (SubAgentType::General, "general-purpose sub-agent"),
        (SubAgentType::Explore, "exploration sub-agent"),
        (SubAgentType::Plan, "planning sub-agent"),
        (SubAgentType::Review, "code review sub-agent"),
        (SubAgentType::Implementer, "implementation sub-agent"),
        (SubAgentType::Verifier, "verification sub-agent"),
        (SubAgentType::Custom, "custom sub-agent"),
    ] {
        let prompt = agent_type.system_prompt();
        assert!(prompt.contains(marker));
        assert_eq!(
            prompt.matches("## Output contract (mandatory)").count(),
            1,
            "{agent_type:?} prompt should include the shared output contract exactly once"
        );
        assert!(prompt.contains("### SUMMARY") && prompt.contains("### BLOCKERS"));
    }
}

#[test]
fn explore_prompt_orients_before_searching() {
    let prompt = SubAgentType::Explore.system_prompt();
    assert!(prompt.contains("role: `explore`"));
    assert!(prompt.contains("AGENTS.md/README"));
    assert!(prompt.contains("workspace/project root"));
    assert!(prompt.contains("compressed reconnaissance"));
}

#[test]
fn agent_description_explains_background_child_and_transcript_handle() {
    let tmp = tempdir().expect("tempdir");
    let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 1);
    let tool = AgentTool::new(manager, stub_runtime());
    let description = tool.description();

    assert!(description.contains("Start one focused child agent task"));
    assert!(description.contains("background"));
    assert!(description.contains("transcript_handle"));
    assert!(
        estimate_tool_description_tokens_conservative(description) <= 1024,
        "agent description exceeds the conservative 1024-token budget"
    );
}

#[test]
fn new_session_tools_use_single_agent_name() {
    let manager = Arc::new(RwLock::new(SubAgentManager::new(PathBuf::from("."), 1)));
    assert_eq!(AgentTool::new(manager, stub_runtime()).name(), "agent");
}

#[test]
fn test_implementer_allowed_tools_include_writes() {
    // Implementer is the write-heavy role; the deprecated
    // `allowed_tools()` advisory list should reflect that the role
    // can write/edit/patch even if today's runtime grants full
    // inheritance.
    #[allow(deprecated)]
    let tools = SubAgentType::Implementer.allowed_tools();
    assert!(tools.contains(&"write_file"));
    assert!(tools.contains(&"edit_file"));
    assert!(tools.contains(&"apply_patch"));
}

#[test]
fn test_verifier_allowed_tools_include_test_runner_but_no_writes() {
    // Verifier runs validation; it should not have write tools in
    // its advisory list. The runtime will still gate writes through
    // approval, but the advisory list signals intent.
    #[allow(deprecated)]
    let tools = SubAgentType::Verifier.allowed_tools();
    assert!(tools.contains(&"run_tests"));
    assert!(tools.contains(&"run_verifiers"));
    assert!(tools.contains(&"diagnostics"));
    assert!(!tools.contains(&"write_file"));
    assert!(!tools.contains(&"apply_patch"));
}

#[test]
fn test_parse_spawn_request_accepts_message_and_agent_type_aliases() {
    let input = json!({
        "message": "Find references to Foo",
        "agent_type": "explorer"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(parsed.prompt, "Find references to Foo");
    assert_eq!(parsed.agent_type, SubAgentType::Explore);
    assert_eq!(parsed.assignment.role.as_deref(), Some("explorer"));
}

#[test]
fn test_parse_spawn_request_accepts_objective_and_role_alias() {
    let input = json!({
        "objective": "Coordinate and wait",
        "role": "awaiter"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(parsed.prompt, "Coordinate and wait");
    assert_eq!(parsed.agent_type, SubAgentType::Plan);
    assert_eq!(parsed.assignment.role.as_deref(), Some("awaiter"));
}

#[test]
fn test_parse_spawn_request_accepts_items_payload() {
    let input = json!({
        "items": [
            {"type": "text", "text": "Analyze module"},
            {"type": "mention", "name": "drive", "path": "app://drive"}
        ],
        "agent_name": "explorer"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert!(parsed.prompt.contains("Analyze module"));
    assert!(parsed.prompt.contains("[mention:$drive](app://drive)"));
    assert_eq!(parsed.agent_type, SubAgentType::Explore);
}

#[test]
fn test_parse_spawn_request_accepts_fork_context() {
    let input = json!({
        "prompt": "continue from here",
        "fork_context": true
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert!(parsed.fork_context);

    let input = json!({
        "prompt": "continue from here",
        "inherit_context": true
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert!(parsed.fork_context);
}

#[test]
fn test_parse_spawn_request_accepts_model_strength() {
    let input = json!({
        "prompt": "scan parser references",
        "type": "explore",
        "model_strength": "faster"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(parsed.agent_type, SubAgentType::Explore);
    assert_eq!(parsed.model_strength, SubAgentModelStrength::Faster);

    let input = json!({
        "prompt": "apply a release fix",
        "modelStrength": "same"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(parsed.model_strength, SubAgentModelStrength::Same);
}

#[test]
fn test_parse_spawn_request_accepts_child_thinking() {
    let input = json!({
        "prompt": "scan parser references",
        "thinking": "off"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(
        parsed.thinking,
        SubAgentThinking::Effort(ReasoningEffort::Off)
    );

    let input = json!({
        "prompt": "design a fix",
        "reasoning_effort": "max"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(
        parsed.thinking,
        SubAgentThinking::Effort(ReasoningEffort::Max)
    );

    let input = json!({
        "prompt": "classify complexity",
        "reasoningEffort": "auto"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(parsed.thinking, SubAgentThinking::Auto);
}

#[test]
fn test_parse_spawn_request_rejects_invalid_model_strength() {
    let input = json!({
        "prompt": "scan parser references",
        "model_strength": "automatic"
    });
    let err = parse_spawn_request(&input).expect_err("invalid model_strength should fail");
    assert!(
        err.to_string()
            .contains("model_strength must be one of: same, faster")
    );
}

#[test]
fn test_parse_spawn_request_rejects_invalid_child_thinking() {
    let input = json!({
        "prompt": "scan parser references",
        "thinking": "forever"
    });
    let err = parse_spawn_request(&input).expect_err("invalid thinking should fail");
    assert!(
        err.to_string()
            .contains("thinking must be one of: inherit, auto, off, low, medium, high, max")
    );
}

#[test]
fn test_parse_spawn_request_accepts_session_name_for_agent() {
    let input = json!({
        "name": "review.parser",
        "prompt": "inspect parser",
        "fork_context": true,
        "max_depth": 0
    });
    let parsed = parse_spawn_request(&input).expect("agent request should parse");
    assert_eq!(parsed.session_name.as_deref(), Some("review.parser"));
    assert!(parsed.fork_context);
    assert_eq!(parsed.max_depth, Some(0));
}

#[test]
fn test_parse_spawn_request_rejects_invalid_session_name() {
    let input = json!({
        "name": "bad name",
        "prompt": "inspect parser"
    });
    let err = parse_spawn_request(&input).expect_err("space in name should fail");
    assert!(err.to_string().contains("name must not contain whitespace"));
}

#[test]
fn test_parse_spawn_request_rejects_out_of_range_max_depth() {
    let input = json!({
        "name": "review.parser",
        "prompt": "inspect parser",
        "max_depth": 4
    });
    let err = parse_spawn_request(&input).expect_err("max_depth should be capped at schema range");
    assert!(
        err.to_string()
            .contains("max_depth must be between 0 and 3")
    );
}

#[tokio::test]
async fn session_projection_exposes_forked_prefix_cache_contract() {
    let mut snapshot = make_snapshot(SubAgentStatus::Running);
    snapshot.name = "fanout_review".to_string();
    snapshot.context_mode = "forked".to_string();
    snapshot.fork_context = true;

    let ctx = ToolContext::new(".");
    let projection = subagent_session_projection(snapshot, false, &ctx, None).await;

    assert_eq!(projection.name, "fanout_review");
    assert_eq!(projection.context_mode, "forked");
    assert_eq!(projection.run_id, "agent_test");
    assert_eq!(projection.follow_up.tool, "handle_read");
    assert_eq!(projection.follow_up.agent_id, "agent_test");
    assert!(projection.takeover.supported);
    assert_eq!(projection.usage.status, "unknown");
    assert_eq!(projection.verification.status, "self_report_only");
    assert!(projection.fork_context);
    assert_eq!(projection.prefix_cache.mode, "forked");
    assert_eq!(
        projection.prefix_cache.parent_prefix,
        "preserved_byte_identical_when_available"
    );
    assert_eq!(projection.transcript_handle.kind, "var_handle");
    assert_eq!(projection.transcript_handle.name, "transcript");
}

#[tokio::test]
async fn terminal_session_projection_prefers_full_transcript_handle() {
    let mut snapshot = make_snapshot(SubAgentStatus::Completed);
    snapshot.result = Some("done".to_string());

    let ctx = ToolContext::new(".");
    let full_handle = {
        let mut store = ctx.runtime.handle_store.lock().await;
        store.insert_json(
            "agent:agent_test",
            "full_transcript",
            json!({
                "kind": "subagent_full_transcript",
                "agent_id": "agent_test",
                "messages": [
                    {
                        "role": "assistant",
                        "content": [
                            { "type": "text", "text": "complete child output" }
                        ]
                    }
                ]
            }),
        )
    };

    let projection = subagent_session_projection(snapshot, false, &ctx, None).await;

    assert_eq!(projection.transcript_handle, full_handle);
    assert_eq!(projection.transcript_handle.name, "full_transcript");
}

#[tokio::test]
async fn interrupted_projection_exposes_checkpoint_metadata_and_messages() {
    let mut snapshot = make_snapshot(SubAgentStatus::Interrupted(
        "API call timed out after 10ms".to_string(),
    ));
    let checkpoint = make_checkpoint(
        &snapshot.agent_id,
        1,
        vec![text_message("user", "inspect checkpoint recovery")],
    );
    snapshot.steps_taken = checkpoint.steps_taken;
    snapshot.checkpoint = Some(checkpoint.clone());

    let ctx = ToolContext::new(".");
    let projection = subagent_session_projection(snapshot, false, &ctx, None).await;

    assert_eq!(projection.status, "waiting_for_user");
    assert!(projection.terminal);
    assert!(projection.continuable);
    assert!(projection.needs_continuation);
    assert!(!projection.timed_out_with_checkpoint);
    assert_eq!(
        projection
            .checkpoint
            .as_ref()
            .expect("checkpoint projected")
            .continuation_handle,
        checkpoint.continuation_handle
    );
    assert_eq!(
        projection
            .snapshot
            .checkpoint
            .as_ref()
            .map(|cp| cp.message_count),
        Some(1)
    );
    assert_eq!(
        projection
            .checkpoint
            .as_ref()
            .and_then(|cp| cp.messages.first())
            .map(message_text),
        Some("inspect checkpoint recovery")
    );

    let timed_out_projection =
        subagent_session_projection(projection.snapshot.clone(), true, &ctx, None).await;
    assert!(timed_out_projection.needs_continuation);
    assert!(timed_out_projection.timed_out);
    assert!(timed_out_projection.timed_out_with_checkpoint);
}

#[test]
fn test_delegate_defaults_to_fork_context() {
    let input = with_default_fork_context(json!({ "prompt": "review current work" }), true);
    let parsed = parse_spawn_request(&input).expect("delegate request should parse");
    assert!(parsed.fork_context);

    let input = with_default_fork_context(
        json!({ "prompt": "fresh exploration", "fork_context": false }),
        true,
    );
    let parsed = parse_spawn_request(&input).expect("delegate override should parse");
    assert!(!parsed.fork_context);
}

#[test]
fn forked_subagent_messages_preserve_parent_prefix_then_append_task() {
    let parent_system = SystemPrompt::Text("parent system".to_string());
    let parent_message = Message {
        role: "user".to_string(),
        content: vec![ContentBlock::Text {
            text: "parent turn".to_string(),
            cache_control: None,
        }],
    };
    let fork_context = SubAgentForkContext {
        system: Some(parent_system.clone()),
        messages: vec![parent_message.clone()],
        structured_state_block: Some("## Fork State\n- Mode: `AGENT`".to_string()),
    };

    let assignment = SubAgentAssignment::new("inspect parser".to_string(), Some("worker".into()));
    let messages = build_initial_subagent_messages(
        "inspect parser",
        &assignment,
        &SubAgentType::General,
        Some(&fork_context),
    );

    assert_eq!(
        subagent_request_system_prompt("child system", Some(&fork_context)),
        parent_system
    );
    assert_eq!(messages.first(), Some(&parent_message));
    assert_eq!(messages.len(), 4);
    assert_eq!(messages[1].role, "system");
    assert!(message_text(&messages[1]).contains("<codewhale:fork_state>"));
    assert_eq!(messages[2].role, "system");
    assert!(message_text(&messages[2]).contains("<codewhale:subagent_context>"));
    assert_eq!(messages[3].role, "user");
    assert!(message_text(&messages[3]).contains("inspect parser"));
}

#[test]
fn fresh_subagent_messages_keep_existing_single_turn_shape() {
    let assignment = SubAgentAssignment::new("list files".to_string(), None);
    let messages =
        build_initial_subagent_messages("list files", &assignment, &SubAgentType::Explore, None);

    assert_eq!(messages.len(), 1);
    assert_eq!(messages[0].role, "user");
    assert!(message_text(&messages[0]).contains("list files"));
}

#[test]
fn test_parse_spawn_request_rejects_text_and_items_together() {
    let input = json!({
        "prompt": "Analyze module",
        "items": [{"type": "text", "text": "dup"}]
    });
    let err = parse_spawn_request(&input).expect_err("text+items should fail");
    assert!(err.to_string().contains("either prompt text or items"));
}

#[test]
fn test_parse_spawn_request_rejects_invalid_role() {
    let input = json!({
        "prompt": "do work",
        "role": "unknown_role"
    });
    let err = parse_spawn_request(&input).expect_err("invalid role should fail");
    assert!(err.to_string().contains("Invalid role alias"));
}

#[test]
fn test_parse_spawn_request_accepts_full_role_vocabulary() {
    // Regression for #2649: roles that `SubAgentType::from_str` accepts must
    // also pass the second `normalize_role_alias` validation pass instead of
    // being rejected with a stale hint.
    for (role, expected_type, expected_role) in [
        ("general", SubAgentType::General, "worker"),
        ("general-purpose", SubAgentType::General, "worker"),
        ("general_purpose", SubAgentType::General, "worker"),
        ("worker", SubAgentType::General, "worker"),
        ("default", SubAgentType::General, "default"),
        ("explore", SubAgentType::Explore, "explorer"),
        ("exploration", SubAgentType::Explore, "explorer"),
        ("explorer", SubAgentType::Explore, "explorer"),
        ("plan", SubAgentType::Plan, "awaiter"),
        ("planning", SubAgentType::Plan, "awaiter"),
        ("planner", SubAgentType::Plan, "awaiter"),
        ("awaiter", SubAgentType::Plan, "awaiter"),
        ("review", SubAgentType::Review, "reviewer"),
        ("code-review", SubAgentType::Review, "reviewer"),
        ("code_review", SubAgentType::Review, "reviewer"),
        ("reviewer", SubAgentType::Review, "reviewer"),
        ("implementer", SubAgentType::Implementer, "implementer"),
        ("implement", SubAgentType::Implementer, "implementer"),
        ("implementation", SubAgentType::Implementer, "implementer"),
        ("builder", SubAgentType::Implementer, "implementer"),
        ("verifier", SubAgentType::Verifier, "verifier"),
        ("verify", SubAgentType::Verifier, "verifier"),
        ("verification", SubAgentType::Verifier, "verifier"),
        ("validator", SubAgentType::Verifier, "verifier"),
        ("tester", SubAgentType::Verifier, "verifier"),
        ("custom", SubAgentType::Custom, "custom"),
    ] {
        assert_eq!(
            SubAgentType::from_str(role),
            Some(expected_type.clone()),
            "from_str should accept role alias {role:?}"
        );
        assert_eq!(
            normalize_role_alias(role),
            Some(expected_role),
            "normalize_role_alias should accept role alias {role:?}"
        );

        let input = json!({ "prompt": "do work", "role": role });
        let parsed = parse_spawn_request(&input)
            .unwrap_or_else(|e| panic!("role {role:?} should parse, got {e}"));
        assert_eq!(parsed.agent_type, expected_type, "type for role {role:?}");
        assert_eq!(
            parsed.assignment.role.as_deref(),
            Some(expected_role),
            "canonical role for {role:?}"
        );
    }
}

#[test]
fn test_invalid_role_error_lists_real_aliases() {
    // The hint must enumerate the actually-accepted vocabulary (#2649).
    let input = json!({ "prompt": "do work", "role": "nonsense" });
    let err = parse_spawn_request(&input)
        .expect_err("invalid role should fail")
        .to_string();
    assert!(err.contains("reviewer"), "hint should list reviewer: {err}");
    assert!(err.contains("verifier"), "hint should list verifier: {err}");
    assert!(err.contains("custom"), "hint should list custom: {err}");
    assert!(
        err.contains("general-purpose"),
        "hint should list general-purpose: {err}"
    );
    assert!(
        err.contains("code_review"),
        "hint should list code_review: {err}"
    );
}

fn schema_property_description<'a>(schema: &'a Value, property: &str) -> &'a str {
    schema["properties"][property]["description"]
        .as_str()
        .unwrap_or_else(|| panic!("missing description for schema property {property:?}"))
}

#[test]
fn subagent_tool_schemas_advertise_real_type_and_role_vocabulary() {
    let tmp = tempdir().expect("tempdir");
    let manager = new_shared_subagent_manager(tmp.path().to_path_buf(), 1);
    let agent_schema = AgentTool::new(manager, stub_runtime()).input_schema();

    let description = schema_property_description(&agent_schema, "type");
    for alias in [
        "general",
        "explore",
        "plan",
        "review",
        "implementer",
        "verifier",
        "custom",
    ] {
        assert!(
            description.contains(alias),
            "type description should list accepted type {alias:?}: {description}"
        );
    }
    assert!(agent_schema["properties"].get("role").is_none());
    assert!(agent_schema["properties"].get("max_depth").is_some());
    let model_strength = schema_property_description(&agent_schema, "model_strength");
    assert!(
        model_strength.contains("type=explore") && model_strength.contains("faster"),
        "model_strength description should teach explore/faster routing: {model_strength}"
    );
    let thinking = schema_property_description(&agent_schema, "thinking");
    assert!(
        thinking.contains("inherit") && thinking.contains("model_strength=faster"),
        "thinking description should teach child thinking control: {thinking}"
    );
    assert!(agent_schema["properties"].get("model").is_some());
}

#[test]
fn test_parse_spawn_request_rejects_conflicting_type_and_role() {
    let input = json!({
        "prompt": "inspect internals",
        "type": "explore",
        "role": "worker"
    });
    let err = parse_spawn_request(&input).expect_err("conflicting type+role should fail");
    assert!(
        err.to_string()
            .contains("Conflicting type/agent_type and role/agent_role")
    );
}

#[test]
fn test_build_allowed_tools_independent_of_allow_shell() {
    // v0.6.6: allow_shell no longer filters at the build_allowed_tools
    // level — the registry builder controls shell-tool registration.
    // Both calls return None (full inheritance) for a default General
    // agent.
    let with_shell = build_allowed_tools(&SubAgentType::General, None, true).unwrap();
    let without_shell = build_allowed_tools(&SubAgentType::General, None, false).unwrap();
    assert!(with_shell.is_none());
    assert!(without_shell.is_none());
}

#[test]
fn test_allowed_tools_are_deduplicated() {
    let tools = build_allowed_tools(
        &SubAgentType::Custom,
        Some(vec![
            "read_file".to_string(),
            "read_file".to_string(),
            "  ".to_string(),
            "grep_files".to_string(),
        ]),
        true,
    )
    .unwrap();
    assert_eq!(
        tools,
        Some(vec!["read_file".to_string(), "grep_files".to_string()])
    );
}

#[test]
fn test_custom_agent_requires_allowed_tools() {
    let err = build_allowed_tools(&SubAgentType::Custom, None, true).unwrap_err();
    assert!(err.to_string().contains("requires"));
}

#[test]
fn role_posture_blocks_writes_and_shell_for_read_only_roles() {
    // #3217: read-only roles may never run write/edit/patch tools, regardless
    // of parent auto-approval, but can always read.
    for role in [
        SubAgentType::Explore,
        SubAgentType::Review,
        SubAgentType::Plan,
        SubAgentType::Verifier,
    ] {
        assert!(
            !role_posture_permits(&role, ApprovalRequirement::Suggest),
            "{role:?} must not run write/edit/patch tools"
        );
        assert!(
            role_posture_permits(&role, ApprovalRequirement::Auto),
            "{role:?} can still read"
        );
    }

    // Write-capable roles keep write access.
    for role in [SubAgentType::Implementer, SubAgentType::General] {
        assert!(
            role_posture_permits(&role, ApprovalRequirement::Suggest),
            "{role:?} writes"
        );
    }

    // Only Full-shell roles may run shell (Required) tools.
    for role in [
        SubAgentType::Verifier,
        SubAgentType::Implementer,
        SubAgentType::General,
    ] {
        assert!(
            role_posture_permits(&role, ApprovalRequirement::Required),
            "{role:?} has full shell"
        );
    }
    for role in [
        SubAgentType::Plan,
        SubAgentType::Explore,
        SubAgentType::Review,
    ] {
        assert!(
            !role_posture_permits(&role, ApprovalRequirement::Required),
            "{role:?} must not run shell tools"
        );
    }

    // Custom is governed by its explicit allowed_tools list, so the posture
    // check permits it (the allowlist is the authority for that role).
    assert!(role_posture_permits(
        &SubAgentType::Custom,
        ApprovalRequirement::Suggest
    ));
    assert!(role_posture_permits(
        &SubAgentType::Custom,
        ApprovalRequirement::Required
    ));
}

#[test]
fn test_build_assignment_prompt_includes_metadata() {
    let assignment = SubAgentAssignment::new(
        "Inspect parser behavior".to_string(),
        Some("explorer".to_string()),
    );
    let prompt = build_assignment_prompt(
        "Inspect parser behavior",
        &assignment,
        &SubAgentType::Explore,
    );
    assert!(prompt.contains("Assignment metadata"));
    assert!(prompt.contains("resolved_type: explore"));
    assert!(prompt.contains("role: explorer"));
}

#[test]
fn subagent_model_strength_defaults_to_parent_even_when_parent_auto_model() {
    let mut runtime = stub_runtime().with_auto_model(true);
    runtime.model = "deepseek-v4-pro".to_string();

    for prompt in ["implement the release fix", "say hello"] {
        let route = fallback_subagent_assignment_route(
            &runtime,
            None,
            ModelRoute::Inherit,
            SubAgentThinking::Inherit,
            prompt,
        );
        assert_eq!(route.model_route, ModelRoute::Inherit);
        assert_eq!(route.model, "deepseek-v4-pro", "prompt {prompt:?}");
    }
}

#[test]
fn subagent_model_strength_faster_uses_known_family_sibling() {
    let mut runtime = stub_runtime().with_auto_model(true);
    runtime.model = "deepseek-v4-pro".to_string();

    let route = fallback_subagent_assignment_route(
        &runtime,
        None,
        ModelRoute::Faster,
        SubAgentThinking::Inherit,
        "inspect one file",
    );
    assert_eq!(route.model_route, ModelRoute::Faster);
    assert_eq!(route.model, "deepseek-v4-flash");
    assert_eq!(route.reasoning_effort.as_deref(), Some("off"));
}

#[test]
fn subagent_model_strength_explicit_model_wins_over_faster() {
    let runtime = stub_runtime().with_auto_model(true);

    let route = fallback_subagent_assignment_route(
        &runtime,
        Some("deepseek-v4-pro".to_string()),
        ModelRoute::Faster,
        SubAgentThinking::Inherit,
        "inspect one file",
    );
    assert_eq!(
        route.model_route,
        ModelRoute::Fixed("deepseek-v4-pro".to_string())
    );
    assert_eq!(route.model, "deepseek-v4-pro");
}

#[test]
fn explicit_child_thinking_overrides_faster_default_off() {
    let mut runtime = stub_runtime().with_reasoning_effort(Some("max".to_string()), false);
    runtime.model = "deepseek-v4-pro".to_string();

    let route = fallback_subagent_assignment_route(
        &runtime,
        None,
        ModelRoute::Faster,
        SubAgentThinking::Effort(ReasoningEffort::High),
        "inspect one file",
    );
    assert_eq!(route.model, "deepseek-v4-flash");
    assert_eq!(route.reasoning_effort.as_deref(), Some("high"));
    assert_eq!(route.tuning.reasoning_effort, Some(ReasoningEffort::High));
}

#[test]
fn explicit_child_auto_thinking_resolves_from_child_prompt() {
    let runtime = stub_runtime().with_reasoning_effort(Some("off".to_string()), false);

    let route = fallback_subagent_assignment_route(
        &runtime,
        None,
        ModelRoute::Inherit,
        SubAgentThinking::Auto,
        "debug this release failure",
    );
    assert_eq!(route.reasoning_effort.as_deref(), Some("max"));
}

#[tokio::test]
async fn route_resolution_matrix_uses_explicit_model_strength_routes() {
    let mut runtime = stub_runtime()
        .with_auto_model(false)
        .with_reasoning_effort(Some("max".to_string()), false);
    runtime.model = "deepseek-v4-pro".to_string();

    struct RouteCase {
        agent_type: SubAgentType,
        configured_model: Option<&'static str>,
        requested_route: ModelRoute,
        prompt: &'static str,
        expected_route: ModelRoute,
        expected_model: &'static str,
        expected_reasoning: Option<&'static str>,
        expected_tuning_effort: Option<ReasoningEffort>,
    }

    let cases = vec![
        RouteCase {
            agent_type: SubAgentType::Explore,
            configured_model: None,
            requested_route: ModelRoute::Inherit,
            prompt: "inspect the parser and report what changed",
            expected_route: ModelRoute::Inherit,
            expected_model: "deepseek-v4-pro",
            expected_reasoning: Some("max"),
            expected_tuning_effort: Some(ReasoningEffort::Max),
        },
        RouteCase {
            agent_type: SubAgentType::Explore,
            configured_model: None,
            requested_route: ModelRoute::Faster,
            prompt: "inspect the parser and report what changed",
            expected_route: ModelRoute::Faster,
            expected_model: "deepseek-v4-flash",
            expected_reasoning: Some("off"),
            expected_tuning_effort: Some(ReasoningEffort::Off),
        },
        RouteCase {
            agent_type: SubAgentType::General,
            configured_model: None,
            requested_route: ModelRoute::Inherit,
            prompt: "synthesize the release blocker fix",
            expected_route: ModelRoute::Inherit,
            expected_model: "deepseek-v4-pro",
            expected_reasoning: Some("max"),
            expected_tuning_effort: Some(ReasoningEffort::Max),
        },
        RouteCase {
            agent_type: SubAgentType::Implementer,
            configured_model: Some("deepseek-v4-flash"),
            requested_route: ModelRoute::Inherit,
            prompt: "apply the narrow code edit",
            expected_route: ModelRoute::Fixed("deepseek-v4-flash".to_string()),
            expected_model: "deepseek-v4-flash",
            expected_reasoning: Some("max"),
            expected_tuning_effort: Some(ReasoningEffort::Max),
        },
    ];

    for case in cases {
        let route = resolve_subagent_assignment_route(
            &runtime,
            case.configured_model.map(str::to_string),
            case.prompt,
            &case.agent_type,
            case.requested_route.clone(),
            SubAgentThinking::Inherit,
        )
        .await;
        assert_eq!(
            route.model_route, case.expected_route,
            "{:?}",
            case.agent_type
        );
        assert_eq!(route.model, case.expected_model, "{:?}", case.agent_type);
        assert_eq!(
            route.reasoning_effort.as_deref(),
            case.expected_reasoning,
            "{:?}",
            case.agent_type
        );
        assert_eq!(
            route.tuning.reasoning_effort, case.expected_tuning_effort,
            "{:?}",
            case.agent_type
        );
        assert_eq!(
            route.tuning.max_output_tokens,
            Some(SUBAGENT_RESPONSE_MAX_TOKENS),
            "{:?}",
            case.agent_type
        );
    }
}

#[test]
fn subagent_auto_reasoning_resolves_to_distinct_v4_tiers() {
    let runtime = stub_runtime().with_reasoning_effort(Some("high".to_string()), true);

    assert_eq!(
        fallback_subagent_assignment_route(
            &runtime,
            None,
            ModelRoute::Inherit,
            SubAgentThinking::Inherit,
            "quick lookup",
        )
        .reasoning_effort,
        Some("high".to_string())
    );
    assert_eq!(
        fallback_subagent_assignment_route(
            &runtime,
            None,
            ModelRoute::Inherit,
            SubAgentThinking::Inherit,
            "debug this release failure"
        )
        .reasoning_effort,
        Some("max".to_string())
    );
}

#[test]
fn test_subagent_tool_registry_reports_unavailable_tools() {
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.allow_shell = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Explore,
        Some(vec!["read_file".to_string(), "missing_tool".to_string()]),
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );
    assert_eq!(
        registry.unavailable_allowed_tools(),
        vec!["missing_tool".to_string()]
    );
}

#[test]
fn test_subagent_tools_respect_nested_agent_depth_budget() {
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.spawn_depth = 1;
    runtime.max_spawn_depth = 2;
    let registry = SubAgentToolRegistry::new(
        runtime.clone(),
        SubAgentType::Explore,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );
    let tools = registry.tools_for_model(&SubAgentType::Explore);
    let names: Vec<_> = tools.iter().map(|t| t.name.as_str()).collect();
    assert!(
        names.contains(&"agent"),
        "child should keep the single agent launcher while depth budget remains; tools: {names:?}"
    );
    assert!(registry.is_tool_allowed("agent"));

    runtime.spawn_depth = 2;
    let capped = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Explore,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );
    let capped_tools = capped.tools_for_model(&SubAgentType::Explore);
    let capped_names: Vec<_> = capped_tools.iter().map(|t| t.name.as_str()).collect();
    assert!(
        !capped_names.contains(&"agent"),
        "child should lose agent launcher at configured depth cap; tools: {capped_names:?}"
    );
    assert!(!capped.is_tool_allowed("agent"));
}

#[tokio::test]
async fn api_timeout_preserves_checkpoint_and_returns_needs_input_without_parking() {
    let tmp = tempdir().expect("tempdir");
    let manager = Arc::new(RwLock::new(SubAgentManager::new(
        tmp.path().to_path_buf(),
        2,
    )));
    let agent_id = "agent_checkpoint_timeout".to_string();
    let (task_input_tx, task_input_rx) = mpsc::unbounded_channel();
    let agent = SubAgent::new(
        agent_id.clone(),
        SubAgentType::General,
        "Inspect checkpoint behavior".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec![]),
        task_input_tx,
        tmp.path().to_path_buf(),
        "boot_test".to_string(),
    );
    {
        let mut manager = manager.write().await;
        manager.agents.insert(agent_id.clone(), agent);
        manager.register_worker(make_worker_spec(&agent_id, tmp.path().to_path_buf()));
    }

    let (client, calls, _bodies) =
        delayed_chat_client(Duration::from_millis(80), "resumed answer").await;
    let mut runtime = stub_runtime().with_step_api_timeout(Duration::from_millis(50));
    runtime.client = client;
    runtime.manager = Arc::clone(&manager);
    runtime.context = ToolContext::new(tmp.path());
    let (mailbox, mut mailbox_rx) =
        crate::tools::subagent::mailbox::Mailbox::new(tokio_util::sync::CancellationToken::new());
    runtime.mailbox = Some(mailbox);

    let task = SubAgentTask {
        manager_handle: Arc::clone(&manager),
        runtime: runtime.clone(),
        agent_id: agent_id.clone(),
        agent_type: SubAgentType::General,
        prompt: "Inspect checkpoint behavior".to_string(),
        assignment: make_assignment(),
        allowed_tools: Some(vec![]),
        fork_context: false,
        started_at: Instant::now(),
        max_steps: 3,
        input_rx: task_input_rx,
        launch_gate: None,
    };
    let task_handle = tokio::spawn(run_subagent_task(task));

    tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            if calls.load(Ordering::SeqCst) >= 1 {
                break;
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("first timed-out API attempt should reach the test server");

    let interrupted_envelope = tokio::time::timeout(Duration::from_secs(5), async {
        loop {
            for env in mailbox_rx.drain() {
                if let MailboxMessage::Interrupted {
                    agent_id: id,
                    reason,
                } = env.message
                {
                    return (id, reason);
                }
            }
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("API timeout should publish an Interrupted mailbox lifecycle event");
    assert_eq!(interrupted_envelope.0, agent_id);
    assert!(
        interrupted_envelope.1.contains("API call timed out"),
        "reason should carry the timeout context: {}",
        interrupted_envelope.1
    );

    tokio::time::timeout(Duration::from_secs(5), task_handle)
        .await
        .expect("sub-agent task must not park waiting for checkpoint input")
        .expect("sub-agent task should finish");
    assert_eq!(
        calls.load(Ordering::SeqCst),
        1,
        "needs-input interruption must not park for continuation or issue a second API request"
    );

    let interrupted = {
        let manager = manager.read().await;
        manager
            .get_result(&agent_id)
            .expect("agent should stay registered")
    };
    assert!(matches!(interrupted.status, SubAgentStatus::Interrupted(_)));
    let checkpoint = interrupted
        .checkpoint
        .as_ref()
        .expect("timeout should preserve checkpoint");
    assert!(checkpoint.continuable);
    assert_eq!(checkpoint.steps_taken, 1);
    assert!(
        checkpoint
            .messages
            .iter()
            .any(|message| message_text(message).contains("Inspect checkpoint behavior")),
        "checkpoint should preserve local child prompt: {checkpoint:?}"
    );
    assert!(interrupted.needs_input.is_some());

    let ctx = runtime.context.clone();
    let worker_record = {
        let manager = manager.read().await;
        manager.get_worker_record(&agent_id)
    };
    let projection =
        subagent_session_projection(interrupted.clone(), false, &ctx, worker_record).await;
    assert_eq!(projection.status, "waiting_for_user");
    assert!(projection.continuable);
    assert!(projection.needs_continuation);
    assert!(projection.checkpoint.is_some());
    assert!(
        projection
            .needs_input
            .as_ref()
            .expect("needs_input should be projected")
            .question
            .contains("Re-dispatch this worker"),
        "projection should tell the parent how to wake/re-dispatch: {:?}",
        projection.needs_input
    );
    assert_eq!(
        projection
            .worker_record
            .as_ref()
            .expect("worker record")
            .status,
        AgentWorkerStatus::WaitingForUser
    );
    assert_eq!(
        projection
            .worker_record
            .as_ref()
            .expect("worker record")
            .recommended_action
            .action,
        "inspect_or_replace"
    );
    assert_eq!(
        calls.load(Ordering::SeqCst),
        1,
        "projection inspection must not respawn the child implicitly"
    );
}

#[tokio::test]
async fn spawn_duplicate_session_name_error_names_conflicting_agent() {
    // #2656: the duplicate-name error must identify the conflicting agent so a
    // model can recover deterministically (reuse the id, or pick a new name).
    let manager = Arc::new(RwLock::new(SubAgentManager::new(PathBuf::from("."), 5)));
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut existing = SubAgent::new(
        "test_agent_existing".to_string(),
        SubAgentType::Explore,
        "scan".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    existing.session_name = "researcher".to_string();
    existing.status = SubAgentStatus::Running;
    let existing_id = existing.id.clone();
    {
        let mut guard = manager.write().await;
        guard.agents.insert(existing_id.clone(), existing);
    }

    let err = {
        let mut guard = manager.write().await;
        guard
            .spawn_background_with_assignment_options(
                manager.clone(),
                stub_runtime(),
                SubAgentType::Explore,
                "new work".to_string(),
                make_assignment(),
                Some(vec!["read_file".to_string()]),
                SubAgentSpawnOptions {
                    name: Some("researcher".to_string()),
                    ..Default::default()
                },
            )
            .expect_err("duplicate session name must error")
    };
    let msg = err.to_string();
    assert!(
        msg.contains(&existing_id),
        "names the conflicting agent_id: {msg}"
    );
    assert!(
        msg.contains("running"),
        "includes the conflicting status: {msg}"
    );
    // #3020: elapsed time lets the parent distinguish a live worker from a
    // stale earlier spawn.
    assert!(
        msg.contains("started ") && msg.contains(" ago"),
        "includes elapsed time since spawn: {msg}"
    );
}

#[tokio::test]
async fn test_running_count_counts_only_agents_with_live_task_handles() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1);
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_3".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.status = SubAgentStatus::Running;
    let handle = tokio::spawn(async {
        tokio::time::sleep(Duration::from_secs(60)).await;
    });
    agent.task_handle = Some(handle);
    let agent_id = agent.id.clone();
    manager.agents.insert(agent.id.clone(), agent);

    assert_eq!(manager.running_count(), 1);
    manager
        .agents
        .get_mut(&agent_id)
        .and_then(|agent| agent.task_handle.take())
        .expect("live task handle")
        .abort();
}

#[test]
fn test_running_count_ignores_running_status_without_task_handle() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1);
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_4".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.status = SubAgentStatus::Running;
    manager.agents.insert(agent.id.clone(), agent);

    assert_eq!(manager.running_count(), 0);
}

#[tokio::test]
async fn test_running_count_counts_running_agents_until_status_reconciles() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1);
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_5".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.status = SubAgentStatus::Running;
    let finished_handle = tokio::spawn(async {});
    while !finished_handle.is_finished() {
        tokio::task::yield_now().await;
    }
    agent.task_handle = Some(finished_handle);
    manager.agents.insert(agent.id.clone(), agent);

    assert_eq!(manager.running_count(), 1);
}

#[tokio::test]
async fn cleanup_auto_cancels_stale_running_agent_and_releases_slot() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1)
        .with_running_heartbeat_timeout(Duration::from_millis(1));
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_stale".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.task_handle = Some(tokio::spawn(async {
        tokio::time::sleep(Duration::from_secs(60)).await;
    }));
    let agent_id = agent.id.clone();
    manager.agents.insert(agent_id.clone(), agent);
    tokio::time::sleep(Duration::from_millis(5)).await;

    assert_eq!(
        manager.running_count(),
        0,
        "stale running agents must not keep the concurrency slot occupied"
    );
    assert_eq!(manager.cleanup(Duration::from_secs(60 * 60)), 1);

    let snapshot = manager
        .get_result(&agent_id)
        .expect("agent should remain inspectable");
    assert_eq!(snapshot.status, SubAgentStatus::Cancelled);
    assert_eq!(manager.running_count(), 0);
    assert!(
        snapshot
            .result
            .as_deref()
            .unwrap_or_default()
            .contains("Auto-cancelled")
    );
}

#[tokio::test]
async fn cleanup_keeps_recent_running_agent() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1)
        .with_running_heartbeat_timeout(Duration::from_secs(300));
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_recent".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.last_activity_at = Instant::now();
    agent.task_handle = Some(tokio::spawn(async {
        tokio::time::sleep(Duration::from_secs(60)).await;
    }));
    let agent_id = agent.id.clone();
    manager.agents.insert(agent_id.clone(), agent);

    assert_eq!(manager.running_count(), 1);
    assert_eq!(manager.cleanup(Duration::from_secs(60 * 60)), 0);
    assert_eq!(
        manager.get_result(&agent_id).expect("agent").status,
        SubAgentStatus::Running
    );
    manager
        .agents
        .get_mut(&agent_id)
        .and_then(|agent| agent.task_handle.take())
        .expect("live task handle")
        .abort();
}

#[tokio::test]
async fn touch_refreshes_stale_running_agent_heartbeat() {
    // Use a heartbeat timeout that is comfortably larger than the synchronous
    // work between `touch()` and the `cleanup()` assertion below. With a 1ms
    // timeout the test was flaky on loaded CI runners (notably Windows, whose
    // scheduler can deschedule this thread for >1ms): the just-touched agent
    // would tip back over the staleness threshold before `cleanup()` ran and
    // get reaped, so `cleanup()` returned 1 instead of 0. A 50ms timeout keeps
    // the staleness logic exercised while removing the timing race.
    let mut manager = SubAgentManager::new(PathBuf::from("."), 1)
        .with_running_heartbeat_timeout(Duration::from_millis(50));
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        "test_agent_touched".to_string(),
        SubAgentType::Explore,
        "prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.task_handle = Some(tokio::spawn(async {
        tokio::time::sleep(Duration::from_secs(60)).await;
    }));
    let agent_id = agent.id.clone();
    manager.agents.insert(agent_id.clone(), agent);
    // Sleep well past the 50ms heartbeat timeout so the agent is reliably stale
    // even if the timer fires early under coarse OS timer granularity.
    tokio::time::sleep(Duration::from_millis(150)).await;

    assert_eq!(manager.running_count(), 0);
    assert!(manager.touch(&agent_id));
    assert_eq!(manager.running_count(), 1);
    assert_eq!(manager.cleanup(Duration::from_secs(60 * 60)), 0);
    manager
        .agents
        .get_mut(&agent_id)
        .and_then(|agent| agent.task_handle.take())
        .expect("live task handle")
        .abort();
}

#[test]
fn test_persist_and_reload_marks_running_agent_as_interrupted() {
    let tmp = tempdir().expect("tempdir");
    let workspace = tmp.path().to_path_buf();
    let state_path = default_state_path(tmp.path());

    let mut manager = SubAgentManager::new(workspace.clone(), 2).with_state_path(state_path);
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let running = SubAgent::new(
        "test_agent_9_running".to_string(),
        SubAgentType::General,
        "work".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    let running_id = running.id.clone();
    manager.agents.insert(running_id.clone(), running);
    manager.persist_state().expect("persist state");

    let mut reloaded =
        SubAgentManager::new(workspace, 2).with_state_path(default_state_path(tmp.path()));
    reloaded.load_state().expect("load state");
    let snapshot = reloaded
        .get_result(&running_id)
        .expect("reloaded agent should exist");
    assert!(matches!(
        snapshot.status,
        SubAgentStatus::Interrupted(ref message)
            if message.contains(SUBAGENT_RESTART_REASON)
    ));
}

#[test]
fn persist_and_reload_preserves_checkpoint_for_interrupted_running_agent() {
    let tmp = tempdir().expect("tempdir");
    let workspace = tmp.path().to_path_buf();
    let state_path = default_state_path(tmp.path());

    let mut manager = SubAgentManager::new(workspace.clone(), 2).with_state_path(state_path);
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut running = SubAgent::new(
        "test_agent_checkpoint_reload".to_string(),
        SubAgentType::General,
        "work".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        Some("Blue".to_string()),
        Some(vec!["read_file".to_string()]),
        input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    running.checkpoint = Some(make_checkpoint(
        &running.id,
        2,
        vec![
            text_message("user", "initial task"),
            text_message("assistant", "partial progress"),
        ],
    ));
    let running_id = running.id.clone();
    manager.agents.insert(running_id.clone(), running);
    manager.persist_state().expect("persist state");

    let mut reloaded =
        SubAgentManager::new(workspace, 2).with_state_path(default_state_path(tmp.path()));
    reloaded.load_state().expect("load state");
    let snapshot = reloaded
        .get_result(&running_id)
        .expect("reloaded agent should exist");

    assert!(matches!(snapshot.status, SubAgentStatus::Interrupted(_)));
    let checkpoint = snapshot.checkpoint.expect("checkpoint should reload");
    assert!(checkpoint.continuable);
    assert_eq!(checkpoint.steps_taken, 2);
    assert_eq!(checkpoint.messages.len(), 2);
    assert_eq!(message_text(&checkpoint.messages[1]), "partial progress");
}

#[test]
fn test_interrupted_status_name_and_summary() {
    let snapshot = make_snapshot(SubAgentStatus::Interrupted(
        SUBAGENT_RESTART_REASON.to_string(),
    ));
    assert_eq!(subagent_status_name(&snapshot.status), "interrupted");
    assert!(summarize_subagent_result(&snapshot).contains(SUBAGENT_RESTART_REASON));
}

// === v0.6.6 — sub-agent authority unification ===

#[test]
fn build_allowed_tools_general_returns_none_for_full_inheritance() {
    // Default behavior: General agent with no explicit list inherits the
    // parent's full registry (None signals no narrowing).
    let result = build_allowed_tools(&SubAgentType::General, None, true).unwrap();
    assert!(
        result.is_none(),
        "General with no explicit_tools should default to full inheritance (None), got {result:?}"
    );
}

#[test]
fn build_allowed_tools_explore_returns_none_for_full_inheritance() {
    // Per-type allowlists are now advisory — Explore also gets the full
    // surface unless an explicit list is passed.
    let result = build_allowed_tools(&SubAgentType::Explore, None, true).unwrap();
    assert!(
        result.is_none(),
        "Explore with no explicit_tools should default to full inheritance"
    );
}

#[test]
fn build_allowed_tools_custom_requires_explicit_list() {
    // Custom is the one type that REQUIRES explicit allowed_tools.
    let err = build_allowed_tools(&SubAgentType::Custom, None, true).unwrap_err();
    assert!(
        err.to_string().contains("Custom sub-agent requires"),
        "got: {err}"
    );
}

#[test]
fn build_allowed_tools_explicit_list_returned_as_some() {
    let explicit = vec!["read_file".to_string(), "list_dir".to_string()];
    let result = build_allowed_tools(&SubAgentType::Custom, Some(explicit.clone()), true).unwrap();
    assert_eq!(result, Some(explicit));
}

#[test]
fn build_allowed_tools_explicit_list_dedupes_and_trims() {
    let explicit = vec![
        "read_file".to_string(),
        "  read_file  ".to_string(), // trim + dedupe
        "list_dir".to_string(),
        "".to_string(), // skip empty
    ];
    let result = build_allowed_tools(&SubAgentType::Custom, Some(explicit), true).unwrap();
    assert_eq!(
        result,
        Some(vec!["read_file".to_string(), "list_dir".to_string()])
    );
}

#[test]
fn parse_spawn_request_extracts_cwd_when_present() {
    let input = json!({
        "prompt": "build feature A",
        "cwd": ".worktrees/feature-a"
    });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert_eq!(
        parsed.cwd.as_ref().map(|p| p.to_string_lossy().to_string()),
        Some(".worktrees/feature-a".to_string())
    );
}

#[test]
fn parse_spawn_request_cwd_absent_yields_none() {
    let input = json!({ "prompt": "no cwd" });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert!(parsed.cwd.is_none());
}

#[test]
fn parse_spawn_request_cwd_empty_string_yields_none() {
    let input = json!({ "prompt": "empty cwd", "cwd": "   " });
    let parsed = parse_spawn_request(&input).expect("spawn request should parse");
    assert!(parsed.cwd.is_none(), "whitespace-only cwd should be None");
}

#[test]
fn build_subagent_system_prompt_appends_role_when_set() {
    let assignment = SubAgentAssignment::new("p".to_string(), Some("worker".to_string()));
    let prompt = build_subagent_system_prompt(&SubAgentType::General, &assignment);
    assert!(
        prompt.contains("You are operating in the role of `worker`."),
        "expected role line present, got: {}",
        &prompt[prompt.len().saturating_sub(160)..]
    );
    // The shared background-worker / caller framing follows the role line.
    assert!(prompt.contains("background sub-agent"));
}

#[test]
fn build_subagent_system_prompt_skips_role_when_none() {
    let assignment = SubAgentAssignment::new("p".to_string(), None);
    let prompt = build_subagent_system_prompt(&SubAgentType::General, &assignment);
    assert!(!prompt.contains("You are operating in the role of"));
}

#[test]
fn build_subagent_system_prompt_skips_role_when_blank() {
    let assignment = SubAgentAssignment::new("p".to_string(), Some("   ".to_string()));
    let prompt = build_subagent_system_prompt(&SubAgentType::General, &assignment);
    assert!(!prompt.contains("You are operating in the role of"));
}

#[test]
fn subagent_done_sentinel_format_is_well_formed() {
    let res = make_snapshot(SubAgentStatus::Completed);
    let sentinel = subagent_done_sentinel("agent_xyz", &res);
    assert!(sentinel.starts_with("<codewhale:subagent.done>"));
    assert!(sentinel.ends_with("</codewhale:subagent.done>"));

    // The inner JSON parses and carries the expected fields.
    let inner = sentinel
        .trim_start_matches("<codewhale:subagent.done>")
        .trim_end_matches("</codewhale:subagent.done>");
    let parsed: serde_json::Value = serde_json::from_str(inner).expect("inner JSON parses");
    assert_eq!(parsed["agent_id"], "agent_xyz");
    assert_eq!(parsed["status"], "completed");
    assert_eq!(parsed["agent_type"], "general");
    assert_eq!(parsed["summary_location"], "previous_line");
    assert!(parsed.get("details").is_none());
    assert!(parsed.get("result_clipped").is_none());
    assert!(parsed.get("summary_complete").is_none());
    assert!(parsed.get("next_action").is_none());
    assert!(parsed.get("summary").is_none());
    assert!(parsed.get("duration_ms").is_none());
    assert!(parsed.get("steps").is_none());
}

#[test]
fn subagent_done_sentinel_keeps_large_result_out_of_metadata() {
    let mut res = make_snapshot(SubAgentStatus::Completed);
    res.result = Some("x".repeat(2048));
    let sentinel = subagent_done_sentinel("agent_big", &res);
    let inner = sentinel
        .trim_start_matches("<codewhale:subagent.done>")
        .trim_end_matches("</codewhale:subagent.done>");
    let parsed: serde_json::Value = serde_json::from_str(inner).expect("inner JSON parses");
    assert_eq!(parsed["agent_id"], "agent_big");
    assert_eq!(parsed["summary_location"], "previous_line");
    assert!(parsed.get("result_clipped").is_none());
    assert!(parsed.get("summary_complete").is_none());
    assert!(parsed.get("next_action").is_none());
    assert!(
        !inner.contains(&"x".repeat(128)),
        "sentinel should not duplicate large result text"
    );
}

#[test]
fn subagent_failed_sentinel_format_is_well_formed() {
    let sentinel = subagent_failed_sentinel("agent_zzz", "boom");
    let inner = sentinel
        .trim_start_matches("<codewhale:subagent.done>")
        .trim_end_matches("</codewhale:subagent.done>");
    let parsed: serde_json::Value = serde_json::from_str(inner).expect("inner JSON parses");
    assert_eq!(parsed["agent_id"], "agent_zzz");
    assert_eq!(parsed["status"], "failed");
    assert_eq!(parsed["error_location"], "previous_line");
    assert!(parsed.get("details").is_none());
    assert!(parsed.get("next_action").is_none());
    // Stays lean — the error text lives on the previous line, not the sentinel.
    assert!(parsed.get("error").is_none());
}

#[test]
fn annotate_child_model_error_adds_actionable_hint() {
    // #2653: a bare provider 403 becomes actionable by naming the model and the
    // recovery path, while unrelated errors pass through unchanged.
    let auth = annotate_child_model_error("403 Forbidden", "kimi-k2");
    assert!(auth.contains("kimi-k2"), "names the model: {auth}");
    assert!(
        auth.contains("child model override"),
        "names the recovery path: {auth}"
    );
    assert!(
        auth.contains("403 Forbidden"),
        "preserves the original: {auth}"
    );

    let unrelated = annotate_child_model_error("connection reset by peer", "kimi-k2");
    assert_eq!(unrelated, "connection reset by peer");

    // #3020: provider rejections that classify as Internal (not
    // Authorization/State) still get the hint via raw-text matching.
    let not_exist = annotate_child_model_error("Model Not Exist", "kimi-k2");
    assert!(
        not_exist.contains("child-agent model config"),
        "DeepSeek-style rejection gets the hint: {not_exist}"
    );

    let openai_style = annotate_child_model_error(
        "The model `gpt-5.5-nano` does not exist or you do not have access to it.",
        "gpt-5.5-nano",
    );
    assert!(
        openai_style.contains("child-agent model config"),
        "OpenAI-style rejection gets the hint: {openai_style}"
    );
}

#[test]
fn subagent_runtime_default_max_depth_is_three() {
    // Sanity-check the constant — bumping it without a test means stale docs.
    assert_eq!(DEFAULT_MAX_SPAWN_DEPTH, 3);
}

#[test]
fn would_exceed_depth_at_boundary() {
    // depth=2, max=3 → next spawn (depth 3) is allowed (allow-equal).
    // depth=3, max=3 → next spawn (depth 4) exceeds.
    let runtime = stub_runtime();
    let mut at_max = runtime.clone();
    at_max.spawn_depth = 3;
    at_max.max_spawn_depth = 3;
    assert!(
        at_max.would_exceed_depth(),
        "depth 3 + max 3 → next would be 4, exceeds"
    );

    let mut below_max = runtime;
    below_max.spawn_depth = 2;
    below_max.max_spawn_depth = 3;
    assert!(
        !below_max.would_exceed_depth(),
        "depth 2 + max 3 → next is 3, allowed"
    );
}

#[test]
fn child_runtime_increments_depth_and_preserves_auto_approve() {
    let mut parent = stub_runtime();
    parent.spawn_depth = 1;
    parent.context.auto_approve = false; // parent in suggest mode
    let child = parent.child_runtime();
    assert_eq!(child.spawn_depth, 2, "child depth = parent + 1");
    assert_eq!(child.step_api_timeout, DEFAULT_STEP_API_TIMEOUT);
    assert!(
        !child.context.auto_approve,
        "child must inherit parent approval state"
    );
    assert!(!parent.context.auto_approve);

    parent.context.auto_approve = true;
    let auto_child = parent.child_runtime();
    assert!(
        auto_child.context.auto_approve,
        "auto-approved parents should still create auto-approved children"
    );
}

#[test]
fn child_and_background_runtimes_preserve_step_api_timeout() {
    let timeout = Duration::from_secs(7);
    let parent = stub_runtime().with_step_api_timeout(timeout);

    let child = parent.child_runtime();
    assert_eq!(child.step_api_timeout, timeout);

    let background = parent.background_runtime();
    assert_eq!(background.step_api_timeout, timeout);
}

#[tokio::test]
async fn subagent_registry_blocks_approval_tools_without_parent_auto_approve() {
    let mut runtime = stub_runtime();
    runtime.context.auto_approve = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::General,
        Some(vec!["exec_shell".to_string()]),
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let err = registry
        .execute("agent_test", "exec_shell", json!({"command": "echo hi"}))
        .await
        .expect_err("approval-gated child tool should be blocked");

    assert!(
        err.to_string().contains("requires approval"),
        "unexpected error: {err}"
    );
}

#[tokio::test]
async fn implementer_delegation_allows_suggest_write_without_parent_auto_approve() {
    // Issue #1828: implementer agents could not write files even when their
    // whole job is to land code changes, because the registry blocked every
    // approval-gated tool when the parent ran in `suggest` mode. The
    // hardened gate (#1833) delegates `Suggest`-level tools (write_file,
    // edit_file, apply_patch) to write-capable roles.
    let tmp = tempdir().expect("tempdir");
    let workspace = tmp.path().to_path_buf();
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(workspace.clone());
    runtime.context.auto_approve = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Implementer,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let result = registry
        .execute(
            "agent_test",
            "write_file",
            json!({"path": "delegated.txt", "content": "hello"}),
        )
        .await
        .expect("delegated write should be allowed for implementer");

    let written = std::fs::read_to_string(workspace.join("delegated.txt"))
        .expect("file should exist after delegated write");
    assert_eq!(written, "hello");
    assert!(
        !result.contains("requires approval"),
        "successful write should not look like an approval error: {result}"
    );
}

#[tokio::test]
async fn general_delegation_still_blocks_suggest_write_without_parent_auto_approve() {
    let tmp = tempdir().expect("tempdir");
    let workspace = tmp.path().to_path_buf();
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(workspace.clone());
    runtime.context.auto_approve = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::General,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let err = registry
        .execute(
            "agent_test",
            "write_file",
            json!({"path": "general.txt", "content": "ok"}),
        )
        .await
        .expect_err("general agent should not silently gain write permission");
    let msg = err.to_string();
    assert!(
        msg.contains("not delegated to general sub-agents"),
        "general writes should be rejected with a role-aware message: {msg}"
    );

    assert!(
        !workspace.join("general.txt").exists(),
        "general write must not land without parent auto-approve"
    );
}

#[tokio::test]
async fn explore_role_still_blocks_suggest_writes_without_parent_auto_approve() {
    // Read-only stances (explore, plan, review, verifier) must not gain
    // write capabilities via delegation — otherwise a parent that asked
    // for "just look at the code" could find files mutated behind its back.
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.context.auto_approve = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Explore,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let err = registry
        .execute(
            "agent_test",
            "write_file",
            json!({"path": "should_not_appear.txt", "content": "denied"}),
        )
        .await
        .expect_err("explore agents must not write");
    let msg = err.to_string();
    assert!(
        msg.contains("explore") && msg.contains("not permitted"),
        "explore writes should be rejected with a role-aware message: {msg}"
    );
    assert!(
        !tmp.path().join("should_not_appear.txt").exists(),
        "file must not have been written"
    );
}

#[tokio::test]
async fn explore_role_blocks_writes_even_under_parent_auto_approve() {
    // #3217: the authoritative per-role posture closes the auto-approve bypass —
    // a read-only role cannot mutate the workspace even when the parent session
    // is auto-approved.
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.context.auto_approve = true;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Explore,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let err = registry
        .execute(
            "agent_test",
            "write_file",
            json!({"path": "nope.txt", "content": "denied"}),
        )
        .await
        .expect_err("explore must not write even under parent auto-approve");
    assert!(
        err.to_string().contains("not permitted"),
        "expected posture rejection, got: {err}"
    );
    assert!(
        !tmp.path().join("nope.txt").exists(),
        "file must not have been written under auto-approve"
    );
}

#[tokio::test]
async fn delegated_write_role_still_blocks_required_tools() {
    // Required-level tools (exec_shell, etc.) remain gated behind parent
    // auto-approve regardless of role. Implementer can write files, but it
    // still can't bypass shell approval just because it's a "write" role.
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.context.auto_approve = false;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::Implementer,
        Some(vec!["exec_shell".to_string()]),
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    let err = registry
        .execute("agent_test", "exec_shell", json!({"command": "echo hi"}))
        .await
        .expect_err("Required-level shell must still need parent auto-approve");
    assert!(
        err.to_string().contains(
            "cannot run inside this sub-agent unless the parent session is auto-approved"
        ),
        "expected Required-level approval message, got: {err}"
    );
}

#[tokio::test]
async fn auto_approved_parent_runs_required_tools_in_subagent() {
    // Baseline: when the parent runtime IS auto-approved, every approval
    // class is permitted (same as before the delegation hardening).
    let tmp = tempdir().expect("tempdir");
    let mut runtime = stub_runtime();
    runtime.context = ToolContext::new(tmp.path().to_path_buf());
    runtime.context.auto_approve = true;
    let registry = SubAgentToolRegistry::new(
        runtime,
        SubAgentType::General,
        None,
        Arc::new(Mutex::new(TodoList::new())),
        Arc::new(Mutex::new(PlanState::default())),
    );

    // Calling exec_shell with interactive=true is what we block via the
    // separate terminal-takeover guard; pick the simpler write-file path
    // to assert that approval gating is off when auto_approve is set.
    registry
        .execute(
            "agent_test",
            "write_file",
            json!({"path": "auto.txt", "content": "auto"}),
        )
        .await
        .expect("auto-approved parent should allow writes");
}

#[test]
fn subagent_request_budget_allows_large_write_file_arguments() {
    assert_eq!(
        SUBAGENT_RESPONSE_MAX_TOKENS, 16_384,
        "non-streaming sub-agent tool calls need enough output budget for large write_file arguments"
    );
}

#[test]
fn truncated_subagent_tool_calls_return_model_visible_errors() {
    let tool_uses = vec![(
        "toolu_write".to_string(),
        "write_file".to_string(),
        json!({"path": "report.md", "content": "partial"}),
    )];

    let results = truncated_response_tool_results(&tool_uses);

    assert_eq!(results.len(), 1);
    match &results[0] {
        ContentBlock::ToolResult {
            tool_use_id,
            content,
            is_error,
            ..
        } => {
            assert_eq!(tool_use_id, "toolu_write");
            assert_eq!(is_error, &Some(true));
            assert!(content.contains("truncated by max_tokens"));
            assert!(content.contains("write_file"));
            assert!(content.contains("smaller writes"));
        }
        other => panic!("expected tool error result, got {other:?}"),
    }
}

#[test]
fn truncated_subagent_text_response_returns_model_visible_error() {
    let results = truncated_response_text_retry_message();

    assert_eq!(results.len(), 1);
    match &results[0] {
        ContentBlock::Text { text, .. } => {
            assert!(text.contains("truncated by max_tokens"));
            assert!(text.contains("No complete tool call was available"));
            assert!(text.contains("Retry with a shorter response"));
        }
        other => panic!("expected text retry message, got {other:?}"),
    }
}

#[test]
fn consecutive_truncated_subagent_responses_are_capped() {
    let mut consecutive = 0;

    for _ in 0..MAX_CONSECUTIVE_TRUNCATED_SUBAGENT_RESPONSES {
        record_truncated_subagent_response(&mut consecutive).expect("within truncation cap");
    }

    let err = record_truncated_subagent_response(&mut consecutive)
        .expect_err("one more truncation should stop the sub-agent");
    assert!(err.to_string().contains("truncated by max_tokens"));
    assert!(err.to_string().contains("consecutive"));

    reset_truncated_subagent_responses(&mut consecutive);
    record_truncated_subagent_response(&mut consecutive).expect("reset should allow recovery");
    assert_eq!(consecutive, 1);
}

#[test]
fn child_cancellation_cascades_from_parent() {
    let parent = stub_runtime();
    let child = parent.child_runtime();
    assert!(!child.cancel_token.is_cancelled());
    parent.cancel_token.cancel();
    assert!(
        child.cancel_token.is_cancelled(),
        "parent cancel() must propagate to child via child_token()"
    );
}

#[test]
fn mailbox_propagates_through_child_runtime_chain() {
    use crate::tools::subagent::mailbox::Mailbox;
    let parent_token = CancellationToken::new();
    let (mailbox, _rx) = Mailbox::new(parent_token.clone());

    let mut parent = stub_runtime();
    parent.cancel_token = parent_token;
    parent.mailbox = Some(mailbox);

    let child = parent.child_runtime();
    let grandchild = child.child_runtime();
    assert!(parent.mailbox.is_some());
    assert!(child.mailbox.is_some(), "child inherits parent mailbox");
    assert!(
        grandchild.mailbox.is_some(),
        "grandchild inherits via the cloned Arc inside Mailbox"
    );
}

#[test]
fn subagent_rejects_interactive_shell_terminal_takeover() {
    let err = reject_subagent_terminal_takeover(
        "exec_shell",
        &serde_json::json!({
            "command": "python3 -i",
            "interactive": true
        }),
    )
    .expect_err("sub-agents must not inherit the parent terminal");

    let msg = err.to_string();
    assert!(msg.contains("cannot use exec_shell with interactive=true"));
    assert!(msg.contains("parent TUI terminal"));

    reject_subagent_terminal_takeover(
        "exec_shell",
        &serde_json::json!({
            "command": "cargo check",
            "interactive": false
        }),
    )
    .expect("non-interactive shell remains allowed");
    reject_subagent_terminal_takeover(
        "exec_shell",
        &serde_json::json!({
            "command": "cargo test",
            "background": true
        }),
    )
    .expect("background shell remains allowed");
}

#[tokio::test]
async fn mailbox_close_as_cancel_propagates_to_grandchild_runtime() {
    use crate::tools::subagent::mailbox::Mailbox;
    let parent_token = CancellationToken::new();
    let (mailbox, _rx) = Mailbox::new(parent_token.clone());

    let mut parent = stub_runtime();
    parent.cancel_token = parent_token;
    parent.mailbox = Some(mailbox.clone());

    let child = parent.child_runtime();
    let grandchild = child.child_runtime();
    assert!(!grandchild.cancel_token.is_cancelled());

    // Close the mailbox via *any* clone — the original or the one stored on
    // the runtime. Cancellation must reach all the way to the grandchild.
    mailbox.close();
    assert!(parent.cancel_token.is_cancelled());
    assert!(child.cancel_token.is_cancelled());
    assert!(
        grandchild.cancel_token.is_cancelled(),
        "close-as-cancel must propagate across max_spawn_depth=3"
    );
}

#[tokio::test]
async fn mailbox_orders_messages_from_parent_and_child_runtimes() {
    use crate::tools::subagent::mailbox::{Mailbox, MailboxMessage};
    let parent_token = CancellationToken::new();
    let (mailbox, mut rx) = Mailbox::new(parent_token.clone());

    let mut parent = stub_runtime();
    parent.cancel_token = parent_token;
    parent.mailbox = Some(mailbox);
    let child = parent.child_runtime();

    // Interleave sends from both runtimes; sequence numbers stay monotonic.
    parent
        .mailbox
        .as_ref()
        .unwrap()
        .send(MailboxMessage::progress("parent_a", "step 1"));
    child
        .mailbox
        .as_ref()
        .unwrap()
        .send(MailboxMessage::progress("child_b", "step 1"));
    parent
        .mailbox
        .as_ref()
        .unwrap()
        .send(MailboxMessage::progress("parent_a", "step 2"));

    let drained = rx.drain();
    assert_eq!(drained.len(), 3);
    assert_eq!(drained[0].seq, 1);
    assert_eq!(drained[1].seq, 2);
    assert_eq!(drained[2].seq, 3);
    // Verify ordering is preserved across publishers.
    match (
        &drained[0].message,
        &drained[1].message,
        &drained[2].message,
    ) {
        (
            MailboxMessage::Progress { agent_id: a, .. },
            MailboxMessage::Progress { agent_id: b, .. },
            MailboxMessage::Progress { agent_id: c, .. },
        ) => {
            assert_eq!(a, "parent_a");
            assert_eq!(b, "child_b");
            assert_eq!(c, "parent_a");
        }
        other => panic!("unexpected message order: {other:?}"),
    }
}

#[test]
fn persisted_empty_allowed_tools_loads_as_full_inheritance() {
    // Backward-compat: a v0.6.5 session that persisted with an empty Vec
    // (or a v0.6.6 session with no narrowing) should load as None on
    // restart, meaning full inheritance.
    let dir = tempdir().unwrap();
    let state_path = dir.path().join("subagents.v1.json");
    let payload = serde_json::json!({
        "schema_version": SUBAGENT_STATE_SCHEMA_VERSION,
        "agents": [{
            "id": "agent_test",
            "agent_type": "general",
            "prompt": "p",
            "assignment": { "objective": "p" },
            "status": "Completed",
            "result": null,
            "steps_taken": 0,
            "duration_ms": 0,
            "allowed_tools": [],
            "updated_at_ms": 0
        }]
    });
    std::fs::write(&state_path, payload.to_string()).unwrap();

    let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 5).with_state_path(state_path);
    manager.load_state().expect("load should succeed");
    let agent = manager.agents.get("agent_test").expect("loaded agent");
    assert!(
        agent.allowed_tools.is_none(),
        "empty Vec on disk → None (full inheritance)"
    );
}

#[test]
fn persisted_non_empty_allowed_tools_loads_as_narrow() {
    // Backward-compat the other way: a v0.6.5 session that persisted with
    // an explicit narrow list keeps that list on reload.
    let dir = tempdir().unwrap();
    let state_path = dir.path().join("subagents.v1.json");
    let payload = serde_json::json!({
        "schema_version": SUBAGENT_STATE_SCHEMA_VERSION,
        "agents": [{
            "id": "agent_narrow",
            "agent_type": "custom",
            "prompt": "p",
            "assignment": { "objective": "p" },
            "status": "Completed",
            "result": null,
            "steps_taken": 0,
            "duration_ms": 0,
            "allowed_tools": ["read_file", "list_dir"],
            "updated_at_ms": 0
        }]
    });
    std::fs::write(&state_path, payload.to_string()).unwrap();

    let mut manager = SubAgentManager::new(dir.path().to_path_buf(), 5).with_state_path(state_path);
    manager.load_state().expect("load should succeed");
    let agent = manager.agents.get("agent_narrow").expect("loaded agent");
    assert_eq!(
        agent.allowed_tools.as_deref(),
        Some(&["read_file".to_string(), "list_dir".to_string()][..]),
        "non-empty Vec → Some(list), narrow scope preserved"
    );
}

/// Build a minimal `SubAgentRuntime` for tests that exercise pure runtime
/// helpers (depth, cancellation, child_runtime). Doesn't construct a real
/// HTTP client — calls that hit `runtime.client` would fail, but the
/// helpers we test here don't.
fn stub_runtime() -> SubAgentRuntime {
    use tokio_util::sync::CancellationToken;

    let workspace = std::env::temp_dir().join("codewhale-test-stub");
    let context = ToolContext::new(workspace.clone());
    SubAgentRuntime {
        client: stub_client(),
        model: "deepseek-v4-flash".to_string(),
        auto_model: false,
        reasoning_effort: None,
        reasoning_effort_auto: false,
        role_models: std::collections::HashMap::new(),
        context,
        allow_shell: true,
        worker_profile: WorkerRuntimeProfile::for_role(SubAgentType::General),
        event_tx: None,
        manager: new_shared_subagent_manager(workspace, 5),
        spawn_depth: 0,
        max_spawn_depth: DEFAULT_MAX_SPAWN_DEPTH,
        cancel_token: CancellationToken::new(),
        mailbox: None,
        parent_completion_tx: None,
        fork_context: None,
        mcp_pool: None,
        step_api_timeout: DEFAULT_STEP_API_TIMEOUT,
        speech_output_dir: None,
    }
}

/// A minimal stub client. Test helpers below only ever check struct fields
/// (depth, cancel_token, context); they don't call the network. We need a
/// *some* `DeepSeekClient` because `SubAgentRuntime.client` isn't
/// `Option<...>`. `Config::default()` is enough — `DeepSeekClient::new`
/// only validates that an API key field exists, not that the key works.
fn stub_runtime_for_provider(provider: &str) -> SubAgentRuntime {
    let mut runtime = stub_runtime();
    runtime.client = stub_client_for_provider(provider);
    runtime
}

fn stub_client_for_provider(provider: &str) -> DeepSeekClient {
    let _ = rustls::crypto::ring::default_provider().install_default();
    let mut providers = crate::config::ProvidersConfig::default();
    match provider {
        "moonshot" => {
            providers.moonshot = crate::config::ProviderConfig {
                api_key: Some("test-key".to_string()),
                ..Default::default()
            };
        }
        "openrouter" => {
            providers.openrouter = crate::config::ProviderConfig {
                api_key: Some("test-key".to_string()),
                ..Default::default()
            };
        }
        "zai" => {
            providers.zai = crate::config::ProviderConfig {
                api_key: Some("test-key".to_string()),
                ..Default::default()
            };
        }
        // Ollama is keyless (local runtime); extend per-provider as needed.
        "ollama" => {}
        other => panic!("extend stub_client_for_provider for provider {other}"),
    }
    let config = crate::config::Config {
        api_key: Some("test-key".to_string()),
        provider: Some(provider.to_string()),
        providers: Some(providers),
        ..crate::config::Config::default()
    };
    DeepSeekClient::new(&config).expect("stub client should construct")
}

fn stub_client() -> DeepSeekClient {
    let _ = rustls::crypto::ring::default_provider().install_default();
    let config = crate::config::Config {
        api_key: Some("test-key".to_string()),
        ..crate::config::Config::default()
    };
    DeepSeekClient::new(&config).expect("stub client should construct")
}

// ---- #405 session-boundary classification ----
//
// Each manager assigns a fresh session_boot_id; agents stamp the id at
// spawn time. After persist + reload by a *new* manager, those agents
// carry the prior boot id and are classified as `from_prior_session`.
// Listings default to current-session only; `include_archived=true` surfaces
// the prior-session records with the flag set.

fn insert_prior_session_agent(
    manager: &mut SubAgentManager,
    id: &str,
    status: SubAgentStatus,
    boot_id: &str,
) {
    let (input_tx, _input_rx) = mpsc::unbounded_channel();
    let mut agent = SubAgent::new(
        id.to_string(),
        SubAgentType::General,
        "old prompt".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        None,
        None,
        input_tx,
        manager.workspace.clone(),
        boot_id.to_string(),
    );
    agent.status = status;
    agent.id = id.to_string();
    manager.agents.insert(id.to_string(), agent);
}

#[test]
fn session_boot_ids_are_unique_per_manager() {
    let a = SubAgentManager::new(PathBuf::from("."), 1);
    let b = SubAgentManager::new(PathBuf::from("."), 1);
    assert_ne!(a.session_boot_id(), b.session_boot_id());
}

#[test]
fn list_filtered_drops_prior_session_terminals_by_default() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 5);
    let current_boot = manager.session_boot_id().to_string();
    insert_prior_session_agent(
        &mut manager,
        "current_running",
        SubAgentStatus::Running,
        &current_boot,
    );
    insert_prior_session_agent(
        &mut manager,
        "prior_completed",
        SubAgentStatus::Completed,
        "boot_old_session",
    );
    insert_prior_session_agent(
        &mut manager,
        "prior_running",
        SubAgentStatus::Running,
        "boot_old_session",
    );

    let listed = manager.list_filtered(false);
    let ids: Vec<&str> = listed.iter().map(|s| s.agent_id.as_str()).collect();
    assert!(ids.contains(&"current_running"), "{ids:?}");
    assert!(
        ids.contains(&"prior_running"),
        "still-running prior-session agents stay visible: {ids:?}"
    );
    assert!(
        !ids.contains(&"prior_completed"),
        "completed prior-session agents are hidden by default: {ids:?}"
    );

    let prior = listed
        .iter()
        .find(|s| s.agent_id == "prior_running")
        .unwrap();
    assert!(prior.from_prior_session);
    let current = listed
        .iter()
        .find(|s| s.agent_id == "current_running")
        .unwrap();
    assert!(!current.from_prior_session);
}

#[test]
fn list_snapshots_refresh_git_branch_from_agent_workspace() {
    let repo = init_subagent_git_repo();
    git(repo.path(), &["checkout", "-b", "feature/agent-old"]);

    let mut manager = SubAgentManager::new(repo.path().to_path_buf(), 5);
    let current_boot = manager.session_boot_id().to_string();
    insert_prior_session_agent(
        &mut manager,
        "current_running",
        SubAgentStatus::Running,
        &current_boot,
    );

    let listed = manager.list_filtered(false);
    let agent = listed
        .iter()
        .find(|agent| agent.agent_id == "current_running")
        .expect("current agent should be listed");
    assert_eq!(agent.git_branch.as_deref(), Some("feature/agent-old"));
    assert_eq!(agent.workspace.as_deref(), Some(repo.path()));

    git(repo.path(), &["checkout", "-b", "feature/agent-new"]);

    let refreshed = manager.list_filtered(false);
    let agent = refreshed
        .iter()
        .find(|agent| agent.agent_id == "current_running")
        .expect("current agent should still be listed");
    assert_eq!(agent.git_branch.as_deref(), Some("feature/agent-new"));
}

#[test]
fn list_filtered_with_include_archived_returns_everything() {
    let mut manager = SubAgentManager::new(PathBuf::from("."), 5);
    let current_boot = manager.session_boot_id().to_string();
    insert_prior_session_agent(
        &mut manager,
        "current_done",
        SubAgentStatus::Completed,
        &current_boot,
    );
    insert_prior_session_agent(
        &mut manager,
        "prior_done",
        SubAgentStatus::Completed,
        "boot_old",
    );
    insert_prior_session_agent(
        &mut manager,
        "prior_failed",
        SubAgentStatus::Failed("boom".to_string()),
        "boot_old",
    );

    let listed = manager.list_filtered(true);
    assert_eq!(listed.len(), 3, "{listed:?}");
    let prior = listed.iter().find(|s| s.agent_id == "prior_done").unwrap();
    assert!(prior.from_prior_session);
    let current = listed
        .iter()
        .find(|s| s.agent_id == "current_done")
        .unwrap();
    assert!(!current.from_prior_session);
}

#[test]
fn agents_with_empty_boot_id_classify_as_prior_session() {
    // Records persisted before #405 land with an empty `session_boot_id`
    // due to `#[serde(default)]`. The manager treats those the same as
    // a non-matching id — i.e. prior session.
    let mut manager = SubAgentManager::new(PathBuf::from("."), 5);
    insert_prior_session_agent(&mut manager, "legacy", SubAgentStatus::Completed, "");

    let listed_default = manager.list_filtered(false);
    assert!(
        listed_default.iter().all(|s| s.agent_id != "legacy"),
        "legacy completed agents are hidden by default"
    );

    let listed_archived = manager.list_filtered(true);
    let legacy = listed_archived
        .iter()
        .find(|s| s.agent_id == "legacy")
        .unwrap();
    assert!(legacy.from_prior_session);
}

#[test]
fn persist_round_trip_preserves_session_boot_id() {
    let dir = tempdir().expect("tempdir");
    let state_path = dir.path().join(SUBAGENT_STATE_FILE);

    let original_boot;
    {
        let mut writer =
            SubAgentManager::new(dir.path().to_path_buf(), 2).with_state_path(state_path.clone());
        original_boot = writer.session_boot_id().to_string();
        insert_prior_session_agent(
            &mut writer,
            "agent_persist",
            SubAgentStatus::Completed,
            &original_boot,
        );
        writer
            .persist_state()
            .expect("persist round-trip should write");
    }

    // A fresh manager comes up with a *different* boot id and reloads
    // the persisted state; the agent should now be classified prior.
    let mut reader =
        SubAgentManager::new(dir.path().to_path_buf(), 2).with_state_path(state_path.clone());
    reader.load_state().expect("reload should succeed");
    assert_ne!(reader.session_boot_id(), original_boot);

    let listed_default = reader.list_filtered(false);
    assert!(
        !listed_default.iter().any(|s| s.agent_id == "agent_persist"),
        "completed prior-session agent hidden after reload: {listed_default:?}"
    );
    let listed_all = reader.list_filtered(true);
    let snap = listed_all
        .iter()
        .find(|s| s.agent_id == "agent_persist")
        .unwrap();
    assert!(snap.from_prior_session);
}

// === Issue #756: parent-completion wakeup ===
//
// When a direct child of the engine finishes, `run_subagent_task` emits
// a `SubAgentCompletion` on the runtime's `parent_completion_tx`. The
// engine's turn loop drains that channel before deciding to end the turn.
// These tests cover the gating logic in `emit_parent_completion` so the
// parent isn't flooded with grandchild completions and so the function
// is safe when no channel is wired.

fn runtime_with_depth(
    spawn_depth: u32,
    parent_completion_tx: Option<mpsc::UnboundedSender<SubAgentCompletion>>,
) -> SubAgentRuntime {
    let mut rt = stub_runtime();
    rt.spawn_depth = spawn_depth;
    rt.parent_completion_tx = parent_completion_tx;
    rt
}

#[test]
fn emit_parent_completion_fires_for_direct_child() {
    let (tx, mut rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    let runtime = runtime_with_depth(1, Some(tx));

    let sent = emit_parent_completion(&runtime, "agent_abc", "summary line\n<sentinel/>");

    assert!(sent, "depth=1 with channel wired should send");
    let received = rx.try_recv().expect("channel should have one message");
    assert_eq!(received.agent_id, "agent_abc");
    assert_eq!(received.payload, "summary line\n<sentinel/>");
    assert!(rx.try_recv().is_err(), "should be exactly one message");
}

#[test]
fn child_runtime_inherits_speech_output_dir() {
    let output_dir = PathBuf::from("configured-speech-output");
    let runtime = stub_runtime().with_speech_output_dir(Some(output_dir.clone()));

    let child = runtime.child_runtime();

    assert_eq!(child.speech_output_dir, Some(output_dir));
}

#[test]
fn emit_parent_completion_skips_grandchildren() {
    let (tx, mut rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    let runtime = runtime_with_depth(2, Some(tx));

    let sent = emit_parent_completion(&runtime, "agent_grandchild", "ignored");

    assert!(
        !sent,
        "depth=2 grandchild must not fire on the parent channel"
    );
    assert!(
        rx.try_recv().is_err(),
        "channel should remain empty for grandchildren"
    );
}

#[test]
fn emit_parent_completion_skips_engine_self() {
    // depth 0 is the engine itself — the engine never spawns a task at
    // depth 0, but defend against accidental misuse.
    let (tx, mut rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    let runtime = runtime_with_depth(0, Some(tx));

    let sent = emit_parent_completion(&runtime, "agent_root", "ignored");

    assert!(
        !sent,
        "depth=0 must not fire (only depth=1 direct children)"
    );
    assert!(rx.try_recv().is_err());
}

#[test]
fn emit_parent_completion_no_channel_is_noop() {
    let runtime = runtime_with_depth(1, None);

    let sent = emit_parent_completion(&runtime, "agent_no_chan", "anything");

    assert!(
        !sent,
        "missing channel should be a silent no-op, not a panic"
    );
}

#[test]
fn emit_parent_completion_dropped_receiver_does_not_panic() {
    let (tx, rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    drop(rx);
    let runtime = runtime_with_depth(1, Some(tx));

    // The send returns an error internally but we discard it — the
    // caller's run_subagent_task does not care whether the engine is
    // still listening (it might be shutting down).
    let sent = emit_parent_completion(&runtime, "agent_orphan", "after-rx-drop");

    assert!(
        sent,
        "we still attempt the send; the engine being gone is not our problem"
    );
}

#[tokio::test]
async fn run_subagent_task_emits_parent_completion_before_terminal_update() {
    let manager = Arc::new(RwLock::new(SubAgentManager::new(PathBuf::from("."), 2)));
    let (task_input_tx, task_input_rx) = mpsc::unbounded_channel();
    let agent_id = "agent_noop".to_string();
    let mut agent = SubAgent::new(
        agent_id.clone(),
        SubAgentType::General,
        "noop".to_string(),
        make_assignment(),
        "deepseek-v4-flash".to_string(),
        None,
        None,
        task_input_tx,
        PathBuf::from("."),
        "boot_test".to_string(),
    );
    agent.status = SubAgentStatus::Running;
    manager.write().await.agents.insert(agent_id.clone(), agent);

    let (completion_tx, mut completion_rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    let mut runtime = runtime_with_depth(1, Some(completion_tx));
    runtime.manager = Arc::clone(&manager);

    let task = SubAgentTask {
        manager_handle: manager.clone(),
        runtime,
        agent_id: agent_id.clone(),
        agent_type: SubAgentType::General,
        prompt: "no-op child run".to_string(),
        assignment: make_assignment(),
        allowed_tools: None,
        fork_context: false,
        started_at: Instant::now(),
        max_steps: 0,
        input_rx: task_input_rx,
        launch_gate: None,
    };

    let manager_lock = manager.write().await;
    let task_handle = tokio::spawn(run_subagent_task(task));

    // While the manager write lock is held, completion can be emitted only if it
    // is sent before the terminal-state manager update (the ordering fixed by
    // issue #1961).
    let completion = tokio::time::timeout(Duration::from_secs(1), completion_rx.recv())
        .await
        .expect("completion should be emitted while manager write lock is still held");
    let completion = completion.expect("completion channel should remain open");
    assert_eq!(completion.agent_id, agent_id);

    drop(manager_lock);
    task_handle
        .await
        .expect("run_subagent_task should complete after lock release");

    let snapshot = {
        let manager = manager.read().await;
        manager
            .get_result(&agent_id)
            .expect("completed agent should be present")
    };
    assert_eq!(snapshot.status, SubAgentStatus::Completed);
}

#[test]
fn child_runtime_propagates_completion_tx_for_gating() {
    // The channel is cloned through `child_runtime()` so descendants carry
    // it. The gate at the send site (`spawn_depth == 1`) is what limits
    // who actually fires — `child_runtime` simply must not strand it.
    let (tx, _rx) = mpsc::unbounded_channel::<SubAgentCompletion>();
    let parent = runtime_with_depth(0, Some(tx));

    let child = parent.child_runtime();

    assert_eq!(child.spawn_depth, 1, "child increments depth");
    assert!(
        child.parent_completion_tx.is_some(),
        "child carries the wakeup channel forward"
    );
}

#[test]
fn subagent_runtime_default_step_api_timeout_is_legacy_120s() {
    // The legacy hardcoded constant is now the default field value so existing
    // call sites and tests that construct a runtime without explicit timeout
    // wiring keep their old behavior (#1806, #1808).
    let runtime = stub_runtime();
    assert_eq!(runtime.step_api_timeout, DEFAULT_STEP_API_TIMEOUT);
    assert_eq!(
        DEFAULT_STEP_API_TIMEOUT,
        std::time::Duration::from_secs(crate::config::DEFAULT_SUBAGENT_API_TIMEOUT_SECS)
    );
}

#[test]
fn with_step_api_timeout_overrides_runtime_field() {
    let runtime = stub_runtime().with_step_api_timeout(std::time::Duration::from_secs(900));
    assert_eq!(runtime.step_api_timeout.as_secs(), 900);
}

#[test]
fn child_runtime_preserves_step_api_timeout() {
    // Real sub-agents spawn through `child_runtime()` / `background_runtime()`;
    // forgetting to clone the timeout would silently drop the user's config
    // override and resurrect the 120 s default for every child step.
    let parent = stub_runtime().with_step_api_timeout(std::time::Duration::from_secs(900));
    let child = parent.child_runtime();
    let background = parent.background_runtime();

    assert_eq!(
        child.step_api_timeout.as_secs(),
        900,
        "child_runtime must preserve parent's per-step timeout"
    );
    assert_eq!(
        background.step_api_timeout.as_secs(),
        900,
        "background_runtime (detached) must also preserve the parent's timeout"
    );
}

#[test]
fn subagent_completion_payload_carries_existing_sentinel_format() {
    // The payload format is the same one already documented in
    // prompts/constitution.md: human summary on line 1, `<codewhale:subagent.done>`
    // sentinel on line 2. This test pins the format so future refactors
    // don't silently break the model's parsing contract.
    let mut snap = make_snapshot(SubAgentStatus::Completed);
    snap.result = Some("Found three errors.".to_string());

    let summary = summarize_subagent_result(&snap);
    let sentinel = subagent_done_sentinel("agent_test", &snap);
    let payload = format!("{summary}\n{sentinel}");

    let mut lines = payload.lines();
    let first = lines.next().expect("first line is summary");
    let second = lines.next().expect("second line is sentinel");
    assert!(
        !first.starts_with("<codewhale:subagent.done>"),
        "summary should not be the sentinel itself"
    );
    assert!(
        second.starts_with("<codewhale:subagent.done>"),
        "second line is the sentinel"
    );
    assert!(second.ends_with("</codewhale:subagent.done>"));
    assert!(
        second.contains("\"agent_id\":\"agent_test\""),
        "sentinel JSON includes agent_id"
    );
    assert!(
        !second.contains("Found three errors."),
        "sentinel should not duplicate the human summary line"
    );
}

/// #2683 — Verify the model-facing tool catalog only advertises canonical
/// subagent tools and never exposes legacy superseded names.
#[test]
fn model_catalog_only_advertises_canonical_subagent_tools() {
    use crate::tools::ToolRegistryBuilder;

    let tmp = tempfile::tempdir().expect("tempdir");
    let runtime = stub_runtime();
    let manager = runtime.manager.clone();
    let ctx = crate::tools::spec::ToolContext::new(tmp.path().to_path_buf());
    let registry = ToolRegistryBuilder::new()
        .with_subagent_tools(manager, runtime)
        .build(ctx);

    let api_names: Vec<String> = registry
        .to_api_tools()
        .into_iter()
        .map(|t| t.name)
        .collect();

    assert_eq!(
        api_names
            .iter()
            .filter(|name| name.as_str() == "agent")
            .count(),
        1,
        "agent should be the only model-facing sub-agent lifecycle tool"
    );
}

// ── #3018: provider-aware auto routing and model validation ─────────────────

#[tokio::test]
async fn faster_route_on_provider_without_known_sibling_stays_on_parent_model() {
    // AC: Ollama must never build a request with a DeepSeek id; even when the
    // model explicitly asks for a faster child, an unknown family stays on the
    // parent model.
    let mut runtime = stub_runtime_for_provider("ollama").with_auto_model(true);
    runtime.model = "qwen3:32b".to_string();

    for prompt in ["hi", "please refactor the whole auth module for security"] {
        let route = resolve_subagent_assignment_route(
            &runtime,
            None,
            prompt,
            &SubAgentType::General,
            ModelRoute::Faster,
            SubAgentThinking::Inherit,
        )
        .await;
        assert_eq!(route.model, "qwen3:32b", "prompt {prompt:?}");
        assert!(
            !route.model.contains("deepseek"),
            "no DeepSeek id may be fabricated: {route:?}"
        );
    }
}

#[test]
fn faster_route_uses_known_deepseek_and_glm_family_siblings() {
    let mut deepseek = stub_runtime();
    deepseek.model = "deepseek-v4-pro".to_string();
    let route = fallback_subagent_assignment_route(
        &deepseek,
        None,
        ModelRoute::Faster,
        SubAgentThinking::Inherit,
        "inspect one file",
    );
    assert_eq!(route.model, "deepseek-v4-flash");

    let mut zai = stub_runtime_for_provider("zai");
    zai.model = "GLM-5.2".to_string();
    let route = fallback_subagent_assignment_route(
        &zai,
        None,
        ModelRoute::Faster,
        SubAgentThinking::Inherit,
        "inspect docs",
    );
    assert_eq!(route.model, "GLM-5.1");

    let mut openrouter = stub_runtime_for_provider("openrouter");
    openrouter.model = "z-ai/glm-5.2".to_string();
    let route = fallback_subagent_assignment_route(
        &openrouter,
        None,
        ModelRoute::Faster,
        SubAgentThinking::Inherit,
        "inspect docs",
    );
    assert_eq!(route.model, "z-ai/glm-5.1");
}

#[test]
fn role_model_validation_accepts_provider_native_ids() {
    // AC: [subagents] worker_model = "kimi-k2.5" on Moonshot must not fail
    // with "Expected a DeepSeek model id".
    let mut runtime = stub_runtime_for_provider("moonshot");
    runtime
        .role_models
        .insert("worker".to_string(), "kimi-k2.5".to_string());

    let model = configured_model_for_role_or_type(&runtime, Some("worker"), &SubAgentType::General)
        .expect("provider-native id is accepted");
    assert_eq!(model.as_deref(), Some("kimi-k2.5"));
}

#[test]
fn role_model_validation_stays_strict_on_official_deepseek() {
    let mut runtime = stub_runtime();
    runtime
        .role_models
        .insert("worker".to_string(), "kimi-k2.5".to_string());

    let err = configured_model_for_role_or_type(&runtime, Some("worker"), &SubAgentType::General)
        .expect_err("non-DeepSeek id is rejected on the official API");
    let msg = err.to_string();
    assert!(msg.contains("kimi-k2.5"), "names the bad id: {msg}");
    assert!(
        msg.contains("deepseek-v4-pro"),
        "lists accepted ids from model_completion_names_for_provider: {msg}"
    );
}

#[test]
fn normalize_requested_subagent_model_is_provider_aware() {
    assert_eq!(
        normalize_requested_subagent_model(
            "kimi-k2.5",
            "model",
            crate::config::ApiProvider::Moonshot
        )
        .expect("Moonshot accepts its own ids"),
        "kimi-k2.5"
    );
    assert_eq!(
        normalize_requested_subagent_model(
            "qwen3:32b",
            "model",
            crate::config::ApiProvider::Ollama
        )
        .expect("Ollama tags pass through"),
        "qwen3:32b"
    );
    assert!(
        normalize_requested_subagent_model(
            "kimi-k2.5",
            "model",
            crate::config::ApiProvider::Deepseek
        )
        .is_err(),
        "official DeepSeek API rejects foreign ids"
    );
}

// ── #3030: step-counter formatting ──────────────────────────────────────────

#[test]
fn format_step_counter_hides_unbounded_sentinel() {
    // DEFAULT_MAX_STEPS is u32::MAX, meaning "unbounded" — rendering the
    // sentinel as a denominator produced "step 16/4294967295".
    assert_eq!(format_step_counter(16, u32::MAX), "step 16");
}

#[test]
fn format_step_counter_keeps_concrete_budgets() {
    assert_eq!(format_step_counter(3, 25), "step 3/25");
    assert_eq!(format_step_counter(0, 1), "step 0/1");
}

// ── #3095: sub-agent launch gate ─────────────────────────────────────────────

#[test]
fn launch_gate_defaults_to_launch_concurrency_capped_by_max_agents() {
    let tmp = tempdir().expect("tempdir");
    let manager = SubAgentManager::new(tmp.path().to_path_buf(), 10);
    // Unset launch concurrency now seeds the gate to the full agent cap.
    assert_eq!(manager.launch_gate.available_permits(), 10);

    let small = SubAgentManager::new(tmp.path().to_path_buf(), 2);
    assert_eq!(small.launch_gate.available_permits(), 2);

    let custom = SubAgentManager::new(tmp.path().to_path_buf(), 10).with_launch_concurrency(0);
    assert_eq!(custom.launch_gate.available_permits(), 1, "clamps up to 1");

    let oversized = SubAgentManager::new(tmp.path().to_path_buf(), 3).with_launch_concurrency(99);
    assert_eq!(
        oversized.launch_gate.available_permits(),
        3,
        "clamps down to max_agents"
    );
}

#[tokio::test]
async fn launch_gate_queues_extra_direct_children() {
    use tokio::sync::Semaphore;
    use tokio_util::sync::CancellationToken;

    let tmp = tempdir().expect("tempdir");
    let manager = Arc::new(RwLock::new(SubAgentManager::new(
        tmp.path().to_path_buf(),
        4,
    )));

    let (client, _calls, _bodies) = delayed_chat_client(Duration::from_millis(150), "done").await;
    let (mailbox, mut mailbox_rx) = Mailbox::new(CancellationToken::new());
    let mut runtime = stub_runtime();
    runtime.client = client;
    runtime.manager = Arc::clone(&manager);
    runtime.context = ToolContext::new(tmp.path());
    runtime.mailbox = Some(mailbox);

    let gate = Arc::new(Semaphore::new(1));
    let spawn = |agent_id: &str, gate: Option<Arc<Semaphore>>| {
        let (input_tx, input_rx) = mpsc::unbounded_channel();
        let agent = SubAgent::new(
            agent_id.to_string(),
            SubAgentType::General,
            "Answer".to_string(),
            make_assignment(),
            "deepseek-v4-flash".to_string(),
            None,
            Some(vec![]),
            input_tx,
            tmp.path().to_path_buf(),
            "boot_test".to_string(),
        );
        let task = SubAgentTask {
            manager_handle: Arc::clone(&manager),
            runtime: runtime.clone(),
            agent_id: agent_id.to_string(),
            agent_type: SubAgentType::General,
            prompt: "Answer".to_string(),
            assignment: make_assignment(),
            allowed_tools: Some(vec![]),
            fork_context: false,
            started_at: Instant::now(),
            max_steps: 1,
            input_rx,
            launch_gate: gate,
        };
        (agent, task)
    };

    let (agent_a, task_a) = spawn("agent_gate_a", Some(Arc::clone(&gate)));
    let (agent_b, task_b) = spawn("agent_gate_b", Some(Arc::clone(&gate)));
    {
        let mut mgr = manager.write().await;
        mgr.agents.insert(agent_a.id.clone(), agent_a);
        mgr.agents.insert(agent_b.id.clone(), agent_b);
    }

    tokio::spawn(run_subagent_task(task_a));
    // Give the first task time to take the only permit before the second
    // task tries; the second must then queue with a visible reason.
    tokio::time::sleep(Duration::from_millis(30)).await;
    tokio::spawn(run_subagent_task(task_b));

    let mut messages = Vec::new();
    let collected = tokio::time::timeout(Duration::from_secs(5), async {
        let mut completed = 0;
        while completed < 2 {
            let Some(envelope) = mailbox_rx.recv().await else {
                break;
            };
            if matches!(envelope.message, MailboxMessage::Completed { .. }) {
                completed += 1;
            }
            messages.push(envelope.message);
        }
    })
    .await;
    assert!(collected.is_ok(), "both gated children should complete");

    let queued_b = messages.iter().position(|m| {
        matches!(
            m,
            MailboxMessage::Progress { agent_id, status }
                if agent_id == "agent_gate_b" && status.contains("queued")
        )
    });
    assert!(
        queued_b.is_some(),
        "second child must publish a visible queued reason: {messages:?}"
    );

    let completed_a = messages
        .iter()
        .position(
            |m| matches!(m, MailboxMessage::Completed { agent_id, .. } if agent_id == "agent_gate_a"),
        )
        .expect("first child completes");
    let started_b = messages
        .iter()
        .position(
            |m| matches!(m, MailboxMessage::Started { agent_id, .. } if agent_id == "agent_gate_b"),
        )
        .expect("second child eventually starts");
    assert!(
        started_b > completed_a,
        "queued child must not start until a permit frees: {messages:?}"
    );
}