vtcode-core 0.154.0

Core library for VT Code - a Rust-based terminal coding agent
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
use super::*;
use crate::config::constants::models;
use crate::config::constants::tools;
use crate::config::models::{ModelId, Provider};
use crate::llm::provider::ToolDefinition;
use crate::tools::exec_session::ExecSessionManager;
use crate::tools::registry::PtySessionManager;
use anyhow::{Result, anyhow};
use std::collections::BTreeMap;
use std::collections::VecDeque;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
use tempfile::TempDir;
use tokio::sync::Notify;
use vtcode_config::core::permissions::{AgentPermissionsConfig, PermissionDefault};
use vtcode_config::{
    HookCommandConfig, HookGroupConfig, HooksConfig, IsolationMode, SubagentMcpServer, SubagentMemoryScope,
    SubagentSource, SubagentSpec,
};

fn readonly_agent_permissions() -> AgentPermissionsConfig {
    let mut permissions = AgentPermissionsConfig::new(PermissionDefault::Deny);
    permissions.allow = vec![tools::READ_FILE.to_string()];
    permissions
}

fn test_controller_config(workspace_root: PathBuf, vt_cfg: VTCodeConfig) -> SubagentControllerConfig {
    let pty_sessions = PtySessionManager::new(workspace_root.clone(), vt_cfg.pty.clone());
    let exec_sessions = ExecSessionManager::new(workspace_root.clone(), pty_sessions.clone());
    SubagentControllerConfig {
        workspace_root,
        parent_session_id: "parent-session".to_string(),
        parent_model: models::openai::GPT_5_6_SOL.to_string(),
        parent_provider: "openai".to_string(),
        parent_reasoning_effort: ReasoningEffortLevel::Medium,
        api_key: "test-key".to_string(),
        vt_cfg,
        openai_chatgpt_auth: None,
        depth: 0,
        workspace_gated: false,
        exec_sessions,
        pty_manager: pty_sessions.manager().clone(),
        managed_background_runtime: false,
    }
}

fn test_child_record(
    id: &str,
    session_id: &str,
    parent_thread_id: &str,
    spec: &SubagentSpec,
    status: SubagentStatus,
    depth: usize,
    child_controller: Option<Arc<SubagentController>>,
) -> ChildRecord {
    ChildRecord {
        id: id.to_string(),
        session_id: session_id.to_string(),
        parent_thread_id: parent_thread_id.to_string(),
        spec: spec.clone(),
        display_label: subagent_display_label(spec),
        status,
        background: false,
        depth,
        created_at: Utc::now(),
        updated_at: Utc::now(),
        completed_at: status.is_terminal().then_some(Utc::now()),
        summary: None,
        error: None,
        archive_metadata: None,
        archive_path: None,
        transcript_path: None,
        effective_config: Some(VTCodeConfig::default()),
        stored_messages: Vec::new(),
        last_prompt: Some(format!("prompt-{id}")),
        queued_prompts: VecDeque::new(),
        max_turns: None,
        model_override: None,
        reasoning_override: None,
        thread_handle: None,
        handle: None,
        notify: Arc::new(Notify::new()),
        worktree_path: None,
        child_controller,
    }
}

fn write_test_background_subagent(workspace_root: &std::path::Path) {
    let agent_dir = workspace_root.join(".vtcode/agents");
    std::fs::create_dir_all(&agent_dir).expect("agent dir");
    std::fs::write(
        agent_dir.join("background-demo.md"),
        r#"---
name: background-demo
description: Minimal demo agent for the managed background subprocess flow.
tools:
  - command_session
background: true
maxTurns: 2
initialPrompt: Report readiness once.
---

Run the managed background demo.
"#,
    )
    .expect("write background agent");
}

fn write_test_primary_agent(workspace_root: &std::path::Path) {
    let agent_dir = workspace_root.join(".vtcode/agents");
    std::fs::create_dir_all(&agent_dir).expect("agent dir");
    std::fs::write(
        agent_dir.join("duck.md"),
        r#"---
name: duck
description: Discussion controller.
mode: primary
permissions:
  default: ask
---

Discuss before implementation.
"#,
    )
    .expect("write primary agent");
}

fn write_test_read_only_subagent(workspace_root: &std::path::Path) {
    let agent_dir = workspace_root.join(".vtcode/agents");
    std::fs::create_dir_all(&agent_dir).expect("agent dir");
    std::fs::write(
        agent_dir.join("readonly-demo.md"),
        r#"---
name: readonly-demo
description: Read-only test child agent.
tools:
  - code_search
permissions:
  default: ask
---

Inspect the repository.
"#,
    )
    .expect("write read-only agent");
}

#[test]
fn request_prompt_prefers_message() {
    let request = SpawnAgentRequest {
        message: Some("hello".to_string()),
        ..SpawnAgentRequest::default()
    };
    assert_eq!(request_prompt(&request.message, &request.items).as_deref(), Some("hello"));
}

#[test]
fn delegated_task_requires_clarification_for_vague_prompt() {
    assert!(delegated_task_requires_clarification("report"));
    assert!(delegated_task_requires_clarification("report findings"));
    assert!(!delegated_task_requires_clarification("review current code changes"));
}

#[test]
fn resolve_subagent_model_maps_aliases() {
    let cfg = VTCodeConfig::default();
    let resolved =
        resolve_subagent_model(&cfg, models::anthropic::CLAUDE_SONNET_5, "anthropic", Some("haiku"), "explorer")
            .expect("resolve model");
    assert_eq!(resolved.as_str(), models::anthropic::CLAUDE_SONNET_5);
}

#[test]
fn resolve_subagent_model_defaults_to_parent_when_omitted() {
    let cfg = VTCodeConfig::default();
    let resolved = resolve_subagent_model(&cfg, models::ollama::GPT_OSS_120B_CLOUD, "ollama", None, "worker")
        .expect("resolve model");
    assert_eq!(resolved.as_str(), models::ollama::GPT_OSS_120B_CLOUD);
}

#[test]
fn resolve_subagent_model_accepts_dotted_claude_aliases_for_anthropic() {
    let cfg = VTCodeConfig::default();
    let resolved =
        resolve_subagent_model(&cfg, "claude-haiku-4.5", "anthropic", None, "worker").expect("resolve model");
    assert_eq!(resolved.as_str(), models::anthropic::CLAUDE_SONNET_5);
}

#[test]
fn resolve_subagent_model_falls_back_to_copilot_default_for_unsupported_inherit_model() {
    let cfg = VTCodeConfig::default();
    let resolved = resolve_subagent_model(&cfg, "claude-haiku-4.5", "copilot", None, "worker").expect("resolve model");
    assert_eq!(resolved, ModelId::default_orchestrator_for_provider(Provider::Copilot));
}

#[test]
fn resolve_effective_subagent_model_uses_explicit_inherit_override() {
    let cfg = VTCodeConfig::default();
    let resolved = resolve_effective_subagent_model(
        &cfg,
        models::anthropic::CLAUDE_SONNET_5,
        "anthropic",
        Some("inherit"),
        Some("haiku"),
        "worker",
    )
    .expect("resolve model");
    assert_eq!(resolved.as_str(), models::anthropic::CLAUDE_SONNET_5);
}

#[test]
fn resolve_effective_subagent_model_falls_back_to_parent_on_invalid_override() {
    // For non-local providers, an unrecognized override must fall back to the
    // parent model rather than being accepted as a custom identifier.
    let cfg = VTCodeConfig::default();
    let resolved = resolve_effective_subagent_model(
        &cfg,
        models::openai::GPT_5_6_SOL,
        "openai",
        Some("not-a-real-model"),
        None,
        "rust-engineer",
    )
    .expect("resolve model");
    assert_eq!(resolved.as_str(), models::openai::GPT_5_6_SOL);
}

#[test]
fn resolve_subagent_model_inherits_local_custom_model() {
    // Local providers expose arbitrary model IDs not in the built-in catalog;
    // inheriting such a model must succeed as a custom identifier.
    let cfg = VTCodeConfig::default();
    let resolved = resolve_subagent_model(&cfg, "qwen3.5-9b-sushi-coder-rl", "lmstudio", None, "wiki-assistant")
        .expect("resolve local inherit model");
    assert_eq!(resolved.as_str(), "qwen3.5-9b-sushi-coder-rl");
    assert_eq!(resolved.provider(), Provider::LmStudio);
}

#[test]
fn resolve_subagent_model_honors_explicit_local_model() {
    let cfg = VTCodeConfig::default();
    let resolved =
        resolve_subagent_model(&cfg, "qwen3.5-9b-sushi-coder-rl", "lmstudio", Some("ornith-1.0-9b"), "wiki-assistant")
            .expect("resolve explicit local model");
    assert_eq!(resolved.as_str(), "ornith-1.0-9b");
    assert_eq!(resolved.provider(), Provider::LmStudio);
}

#[test]
fn resolve_subagent_model_honors_provider_override_model() {
    use vtcode_config::core::ProviderOverrideConfig;

    let mut cfg = VTCodeConfig::default();
    cfg.provider_overrides.insert(
        "openai".to_string(),
        ProviderOverrideConfig {
            models: vec!["my-fine-tuned-gpt".to_string()],
            ..ProviderOverrideConfig::default()
        },
    );
    let resolved =
        resolve_subagent_model(&cfg, models::openai::GPT_5_6_SOL, "openai", Some("my-fine-tuned-gpt"), "reviewer")
            .expect("resolve override model");
    assert_eq!(resolved.as_str(), "my-fine-tuned-gpt");
}

#[test]
fn resolve_effective_subagent_model_ignores_cross_provider_override_model() {
    use vtcode_config::core::ProviderOverrideConfig;

    // An override belonging to a DIFFERENT provider must not be accepted for the
    // active provider; resolution must fall back to the parent model instead.
    let mut cfg = VTCodeConfig::default();
    cfg.provider_overrides.insert(
        "anthropic".to_string(),
        ProviderOverrideConfig {
            models: vec!["not-a-real-model".to_string()],
            ..ProviderOverrideConfig::default()
        },
    );
    let resolved = resolve_effective_subagent_model(
        &cfg,
        models::openai::GPT_5_6_SOL,
        "openai",
        Some("not-a-real-model"),
        None,
        "reviewer",
    )
    .expect("resolve model");
    assert_eq!(resolved.as_str(), models::openai::GPT_5_6_SOL);
}

#[test]
fn resolve_subagent_model_honors_custom_provider_model() {
    use vtcode_config::core::CustomProviderConfig;

    let mut cfg = VTCodeConfig::default();
    cfg.custom_providers.push(CustomProviderConfig {
        name: "mycorp".to_string(),
        display_name: "MyCorp".to_string(),
        base_url: "https://llm.corp.example/v1".to_string(),
        model: "mycorp-special-coder".to_string(),
        ..CustomProviderConfig::default()
    });
    let resolved = resolve_subagent_model(&cfg, "mycorp-special-coder", "mycorp", None, "wiki-assistant")
        .expect("resolve custom provider model");
    assert_eq!(resolved.as_str(), "mycorp-special-coder");
}

#[test]
fn resolve_subagent_small_model_rejects_cross_provider_configured_lightweight_model() {
    let mut cfg = VTCodeConfig::default();
    cfg.agent.small_model.model = models::anthropic::CLAUDE_SONNET_5.to_string();

    let resolved = resolve_subagent_model(&cfg, models::openai::GPT_5_6_SOL, "openai", Some("small"), "worker")
        .expect("resolve model");

    assert_eq!(resolved, ModelId::GPT56Terra);
}

#[test]
fn resolve_effective_subagent_model_falls_back_to_spec_model_on_invalid_override() {
    let cfg = VTCodeConfig::default();
    let resolved = resolve_effective_subagent_model(
        &cfg,
        models::anthropic::CLAUDE_SONNET_5,
        "anthropic",
        Some("not-a-real-model"),
        Some("haiku"),
        "reviewer",
    )
    .expect("resolve model");
    assert_eq!(resolved.as_str(), models::anthropic::CLAUDE_SONNET_5);
}

#[test]
fn background_record_ids_are_stable_and_sanitized() {
    assert_eq!(background_record_id("Rust Engineer"), "background-Rust-Engineer");
    assert_eq!(background_record_id("plugin:reviewer/default"), "background-plugin-reviewer-default");
}

#[test]
fn background_subagent_command_includes_expected_flags() {
    let workspace = std::env::current_dir().expect("workspace");
    let command = build_background_subagent_command(
        &workspace,
        "rust-engineer",
        "session-parent",
        "session-child",
        "Inspect the repo",
        Some(7),
        Some("gpt-5.6-luna"),
        Some("high"),
    )
    .expect("background command");

    assert!(command.len() >= 15);
    assert_eq!(command[1], "background-subagent");
    assert!(command.windows(2).any(|pair| pair == ["--agent-name", "rust-engineer"]));
    assert!(command.windows(2).any(|pair| pair == ["--parent-session-id", "session-parent"]));
    assert!(command.windows(2).any(|pair| pair == ["--session-id", "session-child"]));
    assert!(command.windows(2).any(|pair| pair == ["--prompt", "Inspect the repo"]));
    assert!(command.windows(2).any(|pair| pair == ["--max-turns", "7"]));
    assert!(command.windows(2).any(|pair| pair == ["--model-override", "gpt-5.6-luna"]));
    assert!(command.windows(2).any(|pair| pair == ["--reasoning-override", "high"]));
}

#[test]
fn resolve_effective_subagent_model_still_errors_on_invalid_spec_model() {
    let cfg = VTCodeConfig::default();
    let err = resolve_effective_subagent_model(
        &cfg,
        models::anthropic::CLAUDE_SONNET_5,
        "anthropic",
        None,
        Some("not-a-real-model"),
        "reviewer",
    )
    .expect_err("invalid spec model should fail");
    assert!(err.to_string().contains("Failed to resolve model"));
}

async fn wait_for_effective_model(controller: &SubagentController, target: &str) -> Result<String> {
    for _ in 0..50 {
        if let Ok(snapshot) = controller.snapshot_for_thread(target).await {
            return Ok(snapshot.effective_config.agent.default_model);
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    Err(anyhow!("Subagent {target} did not capture an effective runtime configuration in time"))
}

fn read_only_test_spec(name: &str) -> SubagentSpec {
    SubagentSpec {
        name: name.to_string(),
        description: "test".to_string(),
        prompt: String::new(),
        tools: Some(vec![tools::READ_FILE.to_string()]),
        disallowed_tools: Vec::new(),
        model: None,
        color: None,
        reasoning_effort: None,
        permissions: readonly_agent_permissions(),
        skills: Vec::new(),
        mcp_servers: Vec::new(),
        hooks: None,
        background: false,
        mode: vtcode_config::AgentMode::Subagent,
        max_turns: None,
        nickname_candidates: Vec::new(),
        initial_prompt: None,
        memory: None,
        isolation: None,
        aliases: Vec::new(),
        source: SubagentSource::Builtin,
        file_path: None,
        warnings: Vec::new(),
        tool_policy_overrides: BTreeMap::new(),
    }
}

#[test]
fn filter_child_tools_keeps_public_read_tools_and_removes_mutation_tools() {
    let defs = vec![
        ToolDefinition::function(
            tools::SPAWN_AGENT.to_string(),
            "Spawn".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::CODE_SEARCH.to_string(),
            "Search".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::EXEC_COMMAND.to_string(),
            "Exec".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::APPLY_PATCH.to_string(),
            "Patch".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::WRITE_STDIN.to_string(),
            "Continue".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::REQUEST_USER_INPUT.to_string(),
            "Ask".to_string(),
            serde_json::json!({"type": "object"}),
        ),
    ];
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");
    let filtered = filter_child_tools(&spec, defs, true, false);
    let names = filtered.iter().map(ToolDefinition::function_name).collect::<Vec<_>>();
    assert_eq!(names, vec![tools::CODE_SEARCH]);
}

#[test]
fn filter_child_tools_keeps_delegation_tools_when_nested_delegation_allowed() {
    let defs = vec![
        ToolDefinition::function(tools::AGENT.to_string(), "Agent".to_string(), serde_json::json!({"type": "object"})),
        ToolDefinition::function(
            tools::SPAWN_AGENT.to_string(),
            "Spawn".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::SEND_INPUT.to_string(),
            "Send".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::WAIT_AGENT.to_string(),
            "Wait".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::SPAWN_BACKGROUND_SUBPROCESS.to_string(),
            "Bg".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::CODE_SEARCH.to_string(),
            "Search".to_string(),
            serde_json::json!({"type": "object"}),
        ),
    ];
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");

    let filtered = filter_child_tools(&spec, defs, false, true);
    let names = filtered.iter().map(ToolDefinition::function_name).collect::<Vec<_>>();

    assert!(names.contains(&tools::AGENT), "agent tool stays exposed when nested delegation is allowed");
    assert!(names.contains(&tools::SPAWN_AGENT));
    assert!(names.contains(&tools::SEND_INPUT));
    assert!(names.contains(&tools::WAIT_AGENT));
    assert!(
        !names.contains(&tools::SPAWN_BACKGROUND_SUBPROCESS),
        "background subprocess alias stays blocked for children"
    );
    assert!(names.contains(&tools::CODE_SEARCH));
}

#[test]
fn filter_child_tools_removes_delegation_tools_by_default() {
    let defs = vec![
        ToolDefinition::function(tools::AGENT.to_string(), "Agent".to_string(), serde_json::json!({"type": "object"})),
        ToolDefinition::function(
            tools::SPAWN_AGENT.to_string(),
            "Spawn".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::CODE_SEARCH.to_string(),
            "Search".to_string(),
            serde_json::json!({"type": "object"}),
        ),
    ];
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");

    let filtered = filter_child_tools(&spec, defs, false, false);
    let names = filtered.iter().map(ToolDefinition::function_name).collect::<Vec<_>>();
    assert_eq!(names, vec![tools::CODE_SEARCH]);
}

#[test]
fn filter_child_tools_keeps_command_session_for_shell_capable_agents() {
    let defs = vec![
        ToolDefinition::function(
            tools::UNIFIED_EXEC.to_string(),
            "Exec".to_string(),
            serde_json::json!({"type": "object"}),
        ),
        ToolDefinition::function(
            tools::CODE_SEARCH.to_string(),
            "Search".to_string(),
            serde_json::json!({"type": "object"}),
        ),
    ];
    let spec = SubagentSpec {
        name: "shell-demo".to_string(),
        description: "test".to_string(),
        prompt: String::new(),
        tools: Some(vec![tools::UNIFIED_EXEC.to_string(), tools::CODE_SEARCH.to_string()]),
        disallowed_tools: Vec::new(),
        model: None,
        color: None,
        reasoning_effort: None,
        permissions: AgentPermissionsConfig::new(PermissionDefault::Ask),
        skills: Vec::new(),
        mcp_servers: Vec::new(),
        hooks: None,
        background: false,
        mode: vtcode_config::AgentMode::Subagent,
        max_turns: None,
        nickname_candidates: Vec::new(),
        initial_prompt: None,
        memory: None,
        isolation: None,
        aliases: Vec::new(),
        source: SubagentSource::Builtin,
        file_path: None,
        warnings: Vec::new(),
        tool_policy_overrides: BTreeMap::new(),
    };

    let filtered = filter_child_tools(&spec, defs, spec.is_read_only(), false);
    assert_eq!(filtered.len(), 2);
    assert_eq!(filtered[0].function_name(), tools::UNIFIED_EXEC);
    assert_eq!(filtered[1].function_name(), tools::CODE_SEARCH);
}

#[test]
fn build_child_config_intersects_allowed_tools_and_preserves_global_denies() {
    let mut parent = VTCodeConfig::default();
    parent.permissions.allow = vec![tools::READ_FILE.to_string(), tools::CODE_SEARCH.to_string()];
    parent.permissions.deny = vec![tools::UNIFIED_EXEC.to_string()];

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.permissions = AgentPermissionsConfig {
        auto: vec!["Bash(*)".to_string()],
        ..AgentPermissionsConfig::new(PermissionDefault::Auto)
    };
    spec.tools = Some(vec![
        tools::SPAWN_AGENT.to_string(),
        tools::CODE_SEARCH.to_string(),
        tools::READ_FILE.to_string(),
    ]);

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);
    assert_eq!(child.runtime_agent_permissions.as_ref(), Some(&spec.permissions));
    assert_eq!(child.permissions.allow, vec![tools::READ_FILE.to_string(), tools::CODE_SEARCH.to_string()]);
    assert!(child.permissions.deny.contains(&tools::UNIFIED_EXEC.to_string()));
    assert!(child.permissions.deny.contains(&tools::SPAWN_AGENT.to_string()));
}

#[test]
fn build_child_config_allows_nested_delegation_keeps_agent_tools_out_of_deny() {
    let mut parent = VTCodeConfig::default();
    parent.permissions.allow = vec![
        tools::SPAWN_AGENT.to_string(),
        tools::WAIT_AGENT.to_string(),
        tools::CODE_SEARCH.to_string(),
    ];

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.tools = Some(parent.permissions.allow.clone());

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, true);

    assert_eq!(
        child.permissions.allow,
        vec![
            tools::SPAWN_AGENT.to_string(),
            tools::WAIT_AGENT.to_string(),
            tools::CODE_SEARCH.to_string()
        ],
        "nested delegation keeps delegation tools in the allow-list"
    );
    assert!(
        !child.permissions.deny.contains(&tools::SPAWN_AGENT.to_string()),
        "spawn_agent must not be denied when nested delegation is allowed"
    );
    assert!(
        !child.permissions.deny.contains(&tools::AGENT.to_string()),
        "agent must not be denied when nested delegation is allowed"
    );
    assert!(
        child.permissions.deny.contains(&tools::SPAWN_BACKGROUND_SUBPROCESS.to_string()),
        "background subprocess alias stays blocked for children"
    );
}

#[test]
fn build_child_config_default_denies_all_subagent_tools() {
    let parent = VTCodeConfig::default();
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);

    assert!(child.permissions.deny.contains(&tools::SPAWN_AGENT.to_string()));
    assert!(child.permissions.deny.contains(&tools::AGENT.to_string()));
    assert!(child.permissions.deny.contains(&tools::SEND_INPUT.to_string()));
    assert!(child.permissions.deny.contains(&tools::WAIT_AGENT.to_string()));
    assert!(child.permissions.deny.contains(&tools::RESUME_AGENT.to_string()));
    assert!(child.permissions.deny.contains(&tools::CLOSE_AGENT.to_string()));
    assert!(child.permissions.deny.contains(&tools::SPAWN_BACKGROUND_SUBPROCESS.to_string()));
}

#[test]
fn build_child_config_preserves_subagent_lifecycle_stripping_and_hook_merging() {
    let mut parent = VTCodeConfig::default();
    parent.permissions.allow = vec![
        tools::SPAWN_AGENT.to_string(),
        tools::CODE_SEARCH.to_string(),
        tools::UNIFIED_EXEC.to_string(),
    ];

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.tools = Some(parent.permissions.allow.clone());
    let mut hooks = HooksConfig::default();
    hooks.lifecycle.pre_tool_use.push(HookGroupConfig {
        matcher: Some("*".to_string()),
        hooks: vec![HookCommandConfig {
            command: "echo child".to_string(),
            ..HookCommandConfig::default()
        }],
    });
    spec.hooks = Some(hooks);

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);

    assert_eq!(child.permissions.allow, vec![tools::CODE_SEARCH.to_string(), tools::UNIFIED_EXEC.to_string()]);
    assert!(child.permissions.deny.contains(&tools::SPAWN_AGENT.to_string()));
    assert_eq!(child.hooks.lifecycle.pre_tool_use.len(), 1);
    assert_eq!(child.hooks.lifecycle.pre_tool_use[0].hooks[0].command, "echo child");
}

#[test]
fn prepare_child_runtime_config_uses_shared_view_for_model_and_reasoning() {
    let parent = VTCodeConfig::default();
    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.model = Some(models::openai::GPT_5_6_LUNA.to_string());
    spec.reasoning_effort = Some(ReasoningEffortLevel::High);

    let (resolved_model, child_reasoning_effort, child_cfg) = prepare_child_runtime_config(
        &parent,
        &spec,
        models::openai::GPT_5_6_SOL,
        "openai",
        ReasoningEffortLevel::Low,
        None,
        None,
        None,
        false,
        |_, parent_model, parent_provider, model_override, spec_model, agent_name| {
            assert_eq!(parent_model, models::openai::GPT_5_6_SOL);
            assert_eq!(parent_provider, "openai");
            assert_eq!(model_override, None);
            assert_eq!(spec_model, Some(models::openai::GPT_5_6_LUNA));
            assert_eq!(agent_name, "worker");
            Ok(models::openai::GPT_5_6_LUNA.parse::<ModelId>().expect("valid model"))
        },
    )
    .expect("prepared child runtime config");

    assert_eq!(resolved_model.as_str(), models::openai::GPT_5_6_LUNA);
    assert_eq!(child_cfg.agent.default_model, models::openai::GPT_5_6_LUNA);
    assert_eq!(child_reasoning_effort, ReasoningEffortLevel::High);
    assert_eq!(child_cfg.agent.reasoning_effort, ReasoningEffortLevel::High);
}

#[test]
fn subagent_instruction_composition_uses_shared_runtime_prompt_and_skill_appendix() {
    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.prompt = "Worker instructions".to_string();
    spec.skills = vec!["rust".to_string(), "repo".to_string()];

    let instructions = compose_subagent_instructions(&spec, Some("Memory appendix".to_string()));

    assert!(instructions.contains("Worker instructions"));
    assert!(instructions.contains("Preloaded skill names: rust, repo."));
    assert!(instructions.contains("Memory appendix"));
    assert!(instructions.contains("Return your final response using this exact Markdown contract"));
}

#[test]
fn build_child_config_preserves_matching_rule_and_exact_tool_ids() {
    let mut parent = VTCodeConfig::default();
    parent.permissions.allow = vec![
        "Read(/docs/**)".to_string(),
        "mcp::context7::search".to_string(),
        tools::READ_FILE.to_string(),
    ];

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.tools = Some(vec![
        "mcp::context7::search".to_string(),
        tools::UNIFIED_EXEC.to_string(),
        tools::READ_FILE.to_string(),
    ]);

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);

    assert_eq!(
        child.permissions.allow,
        vec![
            "Read(/docs/**)".to_string(),
            "mcp::context7::search".to_string(),
            tools::READ_FILE.to_string()
        ]
    );
}

#[test]
fn build_child_config_preserves_parent_rule_shaped_allowlist() {
    let mut parent = VTCodeConfig::default();
    parent.permissions.allow = vec!["Read".to_string()];

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");
    spec.tools = Some(vec![
        tools::READ_FILE.to_string(),
        tools::CODE_SEARCH.to_string(),
        tools::UNIFIED_EXEC.to_string(),
    ]);

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);

    assert_eq!(child.permissions.allow, vec!["Read".to_string()]);
}

#[test]
fn build_child_config_promotes_single_turn_budget_to_recovery_budget() {
    let parent = VTCodeConfig::default();
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, Some(1), false);

    assert_eq!(child.automation.full_auto.max_turns, SUBAGENT_MIN_MAX_TURNS);
}

#[test]
fn background_children_get_a_higher_turn_floor() {
    assert_eq!(normalize_background_child_max_turns(Some(2), true), Some(4));
    assert_eq!(normalize_background_child_max_turns(Some(3), true), Some(4));
    assert_eq!(normalize_background_child_max_turns(Some(4), true), Some(4));
}

#[test]
fn foreground_children_keep_the_existing_turn_floor() {
    assert_eq!(normalize_background_child_max_turns(Some(1), false), Some(SUBAGENT_MIN_MAX_TURNS));
    assert_eq!(normalize_background_child_max_turns(Some(2), false), Some(2));
    assert_eq!(normalize_background_child_max_turns(None, true), None);
}

#[test]
fn build_child_config_merges_inline_mcp_provider() {
    let parent = VTCodeConfig::default();
    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "default")
        .expect("default");
    spec.mcp_servers = vec![SubagentMcpServer::Inline(BTreeMap::from([(
        "playwright".to_string(),
        serde_json::json!({
            "type": "stdio",
            "command": "npx",
            "args": ["-y", "@playwright/mcp@latest"],
        }),
    )]))];

    let child = build_child_config(&parent, &spec, models::openai::GPT_5_6_SOL, None, false);
    let provider = child
        .mcp
        .providers
        .iter()
        .find(|provider| provider.name == "playwright")
        .expect("playwright provider");
    assert_eq!(provider.name, "playwright");
}

#[test]
fn explicit_delegation_request_detects_mentions_and_keywords() {
    let direct_mentions = extract_explicit_agent_mentions("@agent-worker fix the issue", &[]);
    assert!(contains_explicit_delegation_request("@agent-worker fix the issue", direct_mentions.as_slice()));
    let no_mentions = extract_explicit_agent_mentions("delegate this in parallel", &[]);
    assert!(contains_explicit_delegation_request("delegate this in parallel", no_mentions.as_slice()));
    let empty_mentions = extract_explicit_agent_mentions("review the repository", &[]);
    assert!(!contains_explicit_delegation_request("review the repository", empty_mentions.as_slice()));
}

#[test]
fn explicit_agent_mentions_detect_natural_language_selection() {
    let rust_engineer = read_only_test_spec("rust-engineer");
    assert_eq!(
        extract_explicit_agent_mentions("use rust-engineer agent to review current code", &[rust_engineer]),
        vec!["rust-engineer".to_string()]
    );
}

#[test]
fn explicit_agent_mentions_detect_looser_subagent_selection() {
    let background_demo = read_only_test_spec("background-demo");
    assert_eq!(
        extract_explicit_agent_mentions("use background-demo and run the subagent", &[background_demo]),
        vec!["background-demo".to_string()]
    );
}

#[test]
fn explicit_agent_mentions_detect_run_subagent_selection() {
    let rust_engineer = read_only_test_spec("rust-engineer");
    assert_eq!(
        extract_explicit_agent_mentions("run rust-engineer subagent and review changes", &[rust_engineer]),
        vec!["rust-engineer".to_string()]
    );
}

#[test]
fn explicit_agent_mentions_ignore_primary_only_agents() {
    let mut duck = read_only_test_spec("duck");
    duck.mode = vtcode_config::AgentMode::Primary;

    assert_eq!(
        extract_explicit_agent_mentions("@agent-duck discuss the task", &[duck.clone()]),
        Vec::<String>::new()
    );
    assert_eq!(
        extract_explicit_agent_mentions("run duck agent and discuss the task", &[duck]),
        Vec::<String>::new()
    );
}

#[test]
fn explicit_model_request_detects_aliases_and_full_ids() {
    assert!(contains_explicit_model_request("delegate this using gpt-5.6-luna", "gpt-5.6-luna"));
    assert!(contains_explicit_model_request("use the worker subagent with haiku", "haiku"));
    assert!(contains_explicit_model_request("run this with the small model", "small"));
    assert!(!contains_explicit_model_request("delegate this small cleanup task", "small"));
    assert!(!contains_explicit_model_request("delegate this task", "gpt-5.6-luna"));
}

#[test]
fn normalize_requested_model_override_drops_default_like_values() {
    assert_eq!(normalize_requested_model_override(Some("default".to_string()), "delegate this task"), None);
    assert_eq!(normalize_requested_model_override(Some(" inherit ".to_string()), "delegate this task"), None);
    assert_eq!(
        normalize_requested_model_override(Some(" inherit ".to_string()), "delegate this task using inherit"),
        Some("inherit".to_string())
    );
}

#[test]
fn sanitize_subagent_input_items_drops_empty_fields() {
    let mut items = vec![
        SubagentInputItem {
            item_type: Some("text".to_string()),
            text: Some("  Workspace: /tmp/repo  ".to_string()),
            path: Some(String::new()),
            name: Some(" ".to_string()),
            image_url: None,
        },
        SubagentInputItem {
            item_type: Some("text".to_string()),
            text: Some("   ".to_string()),
            path: Some(String::new()),
            name: None,
            image_url: None,
        },
    ];

    sanitize_subagent_input_items(&mut items);

    assert_eq!(items.len(), 1);
    assert_eq!(items[0].text.as_deref(), Some("Workspace: /tmp/repo"));
    assert!(items[0].path.is_none());
    assert!(items[0].name.is_none());
}

#[tokio::test]
async fn controller_exposes_builtin_specs() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");
    let specs = controller.effective_specs().await;
    assert!(specs.iter().any(|spec| spec.name == "explorer"));
    assert!(specs.iter().any(|spec| spec.name == "worker"));
}

#[tokio::test]
async fn spawn_defaults_to_single_explicit_mention() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("@agent-explorer inspect the codebase")
        .await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            message: Some("Inspect the codebase.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    assert_eq!(spawned.agent_name, "explorer");
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_defaults_to_single_natural_language_selection() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let mentions = controller
        .set_turn_delegation_hints_from_input("use explorer agent to inspect the codebase")
        .await;
    assert_eq!(mentions, vec!["explorer".to_string()]);

    let spawned = controller
        .spawn(SpawnAgentRequest {
            message: Some("Inspect the codebase.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    assert_eq!(spawned.agent_name, "explorer");
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_rejects_mismatched_explicit_mention() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("@agent-explorer inspect the codebase")
        .await;

    let err = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement a change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("mismatched mention should fail");

    assert!(err.to_string().contains("user explicitly selected 'explorer'"));
}

#[tokio::test]
async fn spawn_rejects_write_capable_agent_without_explicit_request_or_agent_type() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let err = controller
        .spawn(SpawnAgentRequest {
            message: Some("Implement a change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("write-capable agent should require explicit request or agent_type");

    assert!(err.to_string().contains("cannot launch write-capable agent"));
}

#[tokio::test]
async fn spawn_allows_write_capable_agent_with_explicit_agent_type() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement a change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("explicit agent_type should allow write-capable agent");

    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_rejects_primary_only_agent_as_child() {
    let temp = TempDir::new().expect("tempdir");
    write_test_primary_agent(temp.path());
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let mentions = controller
        .set_turn_delegation_hints_from_input("@agent-duck discuss the task")
        .await;
    assert!(mentions.is_empty());

    let err = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("duck".to_string()),
            message: Some("Discuss the task.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("primary-only agent should not spawn as child");

    assert!(err.to_string().contains("Unknown subagent type duck"));
}

#[tokio::test]
async fn spawn_accepts_background_flag_outside_managed_background_runtime() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect the codebase.".to_string()),
            background: true,
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("background child spawn should succeed");

    assert!(spawned.background);
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_allows_background_capable_spec_as_foreground_child() {
    let temp = TempDir::new().expect("tempdir");
    write_test_background_subagent(temp.path());
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("run background-demo subagent and demo")
        .await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("background-demo".to_string()),
            message: Some("Run the demo.".to_string()),
            background: false,
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("foreground background-capable spawn should succeed");

    assert_eq!(spawned.agent_name, "background-demo");
    assert!(!spawned.background);
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_rejects_vague_task_even_with_explicit_request() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("run worker subagent and report")
        .await;

    let err = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("report".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("vague task should require clarification");

    assert!(err.to_string().contains("too vague ('report')"));
}

#[tokio::test]
async fn spawn_defaults_to_write_capable_run_subagent_selection() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let mentions = controller
        .set_turn_delegation_hints_from_input("run worker subagent and implement the change")
        .await;
    assert_eq!(mentions, vec!["worker".to_string()]);

    let spawned = controller
        .spawn(SpawnAgentRequest {
            message: Some("Implement the change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    assert_eq!(spawned.agent_name, "worker");
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_rejects_read_only_agent_when_auto_delegate_is_disabled() {
    let temp = TempDir::new().expect("tempdir");
    write_test_read_only_subagent(temp.path());
    let mut cfg = VTCodeConfig::default();
    cfg.subagents.auto_delegate_read_only = false;
    let controller = SubagentController::new(test_controller_config(temp.path().to_path_buf(), cfg))
        .await
        .expect("controller");

    let err = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("readonly-demo".to_string()),
            message: Some("Inspect the repository.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("read-only agent should require explicit delegation");

    assert!(
        err.to_string()
            .contains("cannot proactively launch read-only agent 'readonly-demo'")
    );
}

#[test]
fn load_memory_appendix_renders_compact_summary() {
    let temp = TempDir::new().expect("tempdir");
    let memory_dir = temp.path().join(".vtcode/agent-memory/reviewer");
    std::fs::create_dir_all(&memory_dir).expect("memory dir");
    std::fs::write(
            memory_dir.join("MEMORY.md"),
            "# Reviewer Memory\n\n## Preferences\n- Keep diffs surgical.\n- Run focused tests before broad checks.\n- Prefer repo docs for orientation.\n- Ask only when a decision is materially blocked.\n- Additional long-form notes that should stay out of the prompt body.\n",
        )
        .expect("write memory");

    let appendix = load_memory_appendix(temp.path(), "reviewer", Some(SubagentMemoryScope::Project))
        .expect("appendix")
        .expect("memory appendix");

    assert!(appendix.contains("Persistent memory file:"));
    assert!(appendix.contains("Key points:"));
    assert!(appendix.contains("Keep diffs surgical."));
    assert!(appendix.contains("Open `MEMORY.md` when exact wording or more detail matters."));
    assert!(!appendix.contains("Current MEMORY.md excerpt"));
    assert!(!appendix.contains("## Preferences"));
}

#[tokio::test]
async fn async_load_memory_appendix_matches_sync_output() {
    let temp = TempDir::new().expect("tempdir");
    let memory_dir = temp.path().join(".vtcode/agent-memory/reviewer");
    std::fs::create_dir_all(&memory_dir).expect("memory dir");
    std::fs::write(
        memory_dir.join("MEMORY.md"),
        "# Reviewer Memory\n\n- Keep the patch focused.\n- Run nextest before the workspace gate.\n",
    )
    .expect("write memory");

    let sync =
        load_memory_appendix(temp.path(), "reviewer", Some(SubagentMemoryScope::Project)).expect("sync appendix");
    let asynchronous = load_memory_appendix_async(temp.path(), "reviewer", Some(SubagentMemoryScope::Project))
        .await
        .expect("async appendix");

    assert_eq!(asynchronous, sync);
}

#[test]
fn load_primary_memory_appendix_reads_existing_memory_without_write_guidance() {
    let temp = TempDir::new().expect("tempdir");
    let memory_dir = temp.path().join(".vtcode/agent-memory/reviewer");
    std::fs::create_dir_all(&memory_dir).expect("memory dir");
    std::fs::write(
        memory_dir.join("MEMORY.md"),
        "# Reviewer Memory\n\n## Preferences\n- Keep diffs surgical.\n- Run focused tests before broad checks.\n",
    )
    .expect("write memory");

    let appendix = load_primary_memory_appendix(temp.path(), "reviewer", Some(SubagentMemoryScope::Project))
        .expect("appendix")
        .expect("memory appendix");

    assert!(appendix.contains("Primary-agent memory file:"));
    assert!(appendix.contains("Loaded read-only for this request."));
    assert!(appendix.contains("Key points:"));
    assert!(appendix.contains("Keep diffs surgical."));
    assert!(!appendix.contains("Read and maintain `MEMORY.md`"));
    assert!(!appendix.contains("Create or update `MEMORY.md`"));
    assert!(!appendix.contains("Open `MEMORY.md` when exact wording or more detail matters."));
}

#[test]
fn load_primary_memory_appendix_missing_memory_is_noop_without_directory_creation() {
    let temp = TempDir::new().expect("tempdir");
    let memory_dir = temp.path().join(".vtcode/agent-memory/reviewer");

    let appendix =
        load_primary_memory_appendix(temp.path(), "reviewer", Some(SubagentMemoryScope::Project)).expect("appendix");

    assert!(appendix.is_none());
    assert!(!memory_dir.exists());
}

#[tokio::test]
async fn spawn_honors_model_override_when_user_explicitly_requests_it() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("delegate this task using gpt-5.4-mini")
        .await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement the change.".to_string()),
            model: Some(models::openai::GPT_5_6_LUNA.to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    let effective_model = wait_for_effective_model(&controller, &spawned.id)
        .await
        .expect("effective model");
    assert_eq!(effective_model, models::openai::GPT_5_6_LUNA);
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_background_subprocess_rejects_non_background_agent() {
    let temp = TempDir::new().expect("tempdir");
    let mut cfg = VTCodeConfig::default();
    cfg.subagents.background.enabled = true;
    let controller = SubagentController::new(test_controller_config(temp.path().to_path_buf(), cfg))
        .await
        .expect("controller");

    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let err = controller
        .spawn_background_subprocess(SpawnBackgroundSubprocessRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement a change.".to_string()),
            ..SpawnBackgroundSubprocessRequest::default()
        })
        .await
        .expect_err("non-background agent should be rejected");

    assert!(err.to_string().contains("background: true"));
    assert!(err.to_string().contains("Use spawn_agent instead"));
}

#[tokio::test]
async fn spawn_background_subprocess_returns_active_record_when_settings_match() {
    let temp = TempDir::new().expect("tempdir");
    write_test_background_subagent(temp.path());
    let mut cfg = VTCodeConfig::default();
    cfg.subagents.background.enabled = true;
    let controller = SubagentController::new(test_controller_config(temp.path().to_path_buf(), cfg))
        .await
        .expect("controller");

    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let spec = controller.resolve_requested_spec(Some("background-demo")).await.expect("spec");
    let record_id = background_record_id(spec.name.as_str());
    let created_at = Utc::now();
    {
        let mut state = controller.state.write().await;
        state.background_children.insert(
            record_id.clone(),
            BackgroundRecord {
                id: record_id.clone(),
                agent_name: spec.name.clone(),
                display_label: subagent_display_label(&spec),
                description: spec.description.clone(),
                source: spec.source.label(),
                color: spec.color.clone(),
                session_id: "session-background-demo".to_string(),
                exec_session_id: "exec-session-background-demo".to_string(),
                desired_enabled: true,
                status: BackgroundSubprocessStatus::Running,
                created_at,
                updated_at: created_at,
                started_at: Some(created_at),
                ended_at: None,
                pid: Some(42),
                prompt: "Report readiness once.".to_string(),
                summary: Some("ready".to_string()),
                error: None,
                archive_path: None,
                transcript_path: None,
                max_turns: Some(4),
                model_override: None,
                reasoning_override: None,
                restart_attempts: 0,
            },
        );
    }

    let entry = controller
        .spawn_background_subprocess(SpawnBackgroundSubprocessRequest {
            agent_type: Some("background-demo".to_string()),
            ..SpawnBackgroundSubprocessRequest::default()
        })
        .await
        .expect("matching active record should be returned");

    assert_eq!(entry.id, record_id);
    assert_eq!(entry.status, BackgroundSubprocessStatus::Running);
    assert_eq!(entry.pid, Some(42));
}

#[tokio::test]
async fn spawn_background_subprocess_rejects_conflicting_active_record_settings() {
    let temp = TempDir::new().expect("tempdir");
    write_test_background_subagent(temp.path());
    let mut cfg = VTCodeConfig::default();
    cfg.subagents.background.enabled = true;
    let controller = SubagentController::new(test_controller_config(temp.path().to_path_buf(), cfg))
        .await
        .expect("controller");

    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let spec = controller.resolve_requested_spec(Some("background-demo")).await.expect("spec");
    let record_id = background_record_id(spec.name.as_str());
    let created_at = Utc::now();
    {
        let mut state = controller.state.write().await;
        state.background_children.insert(
            record_id,
            BackgroundRecord {
                id: background_record_id(spec.name.as_str()),
                agent_name: spec.name.clone(),
                display_label: subagent_display_label(&spec),
                description: spec.description.clone(),
                source: spec.source.label(),
                color: spec.color.clone(),
                session_id: "session-background-demo".to_string(),
                exec_session_id: "exec-session-background-demo".to_string(),
                desired_enabled: true,
                status: BackgroundSubprocessStatus::Running,
                created_at,
                updated_at: created_at,
                started_at: Some(created_at),
                ended_at: None,
                pid: Some(42),
                prompt: "Report readiness once.".to_string(),
                summary: Some("ready".to_string()),
                error: None,
                archive_path: None,
                transcript_path: None,
                max_turns: Some(4),
                model_override: None,
                reasoning_override: None,
                restart_attempts: 0,
            },
        );
    }

    let err = controller
        .spawn_background_subprocess(SpawnBackgroundSubprocessRequest {
            agent_type: Some("background-demo".to_string()),
            message: Some("Run a different task.".to_string()),
            ..SpawnBackgroundSubprocessRequest::default()
        })
        .await
        .expect_err("conflicting active record should be rejected");

    assert!(err.to_string().contains("different prompt"));
    assert!(err.to_string().contains("Stop or restart"));
}

#[tokio::test]
async fn resume_preserves_captured_runtime_overrides() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller
        .set_turn_delegation_hints_from_input("delegate this task using gpt-5.4-mini")
        .await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement the change.".to_string()),
            model: Some(models::openai::GPT_5_6_LUNA.to_string()),
            max_turns: Some(2),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    let initial_model = wait_for_effective_model(&controller, &spawned.id)
        .await
        .expect("initial effective model");
    assert_eq!(initial_model, models::openai::GPT_5_6_LUNA);

    let closed = controller.close(&spawned.id).await.expect("close");
    assert_eq!(closed.status, SubagentStatus::Closed);

    controller.resume(&spawned.id).await.expect("resume");

    for _ in 0..100 {
        let status = controller.status_for(&spawned.id).await.expect("status");
        if status.updated_at > closed.updated_at && status.status != SubagentStatus::Closed {
            let snapshot = controller.snapshot_for_thread(&spawned.id).await.expect("snapshot");
            assert_eq!(snapshot.effective_config.agent.default_model, models::openai::GPT_5_6_LUNA);
            controller.close(&spawned.id).await.expect("final close");
            return;
        }
        tokio::time::sleep(Duration::from_millis(10)).await;
    }

    panic!("resumed subagent did not capture runtime config in time");
}

#[tokio::test]
async fn spawn_captures_runtime_config_before_first_child_turn() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement the change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    let snapshot = controller.snapshot_for_thread(&spawned.id).await.expect("snapshot");

    assert_eq!(snapshot.id, spawned.id);
    assert!(!snapshot.effective_config.agent.default_model.trim().is_empty());

    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_custom_uses_explicit_spec_without_delegation_hints() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let mut spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");
    spec.name = "init-grounding-explorer".to_string();
    spec.description = "VT Code /init grounding explorer.".to_string();
    spec.source = SubagentSource::ProjectVtcode;

    let spawned = controller
        .spawn_custom(
            spec,
            SpawnAgentRequest {
                message: Some("Inspect the repository and report agent-facing findings.".to_string()),
                max_turns: Some(2),
                ..SpawnAgentRequest::default()
            },
        )
        .await
        .expect("spawn");

    assert_eq!(spawned.agent_name, "init-grounding-explorer");
    assert_eq!(spawned.source, SubagentSource::ProjectVtcode.label());
    controller.close(&spawned.id).await.expect("close");
}

#[tokio::test]
async fn spawn_custom_rejects_write_capable_spec() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "worker")
        .expect("worker");

    let err = controller
        .spawn_custom(
            spec,
            SpawnAgentRequest {
                message: Some("Implement a change.".to_string()),
                ..SpawnAgentRequest::default()
            },
        )
        .await
        .expect_err("write-capable custom spec should be rejected");

    assert!(err.to_string().contains("custom subagent spawn only supports read-only specs"));
}

#[tokio::test]
async fn spawn_custom_rejects_primary_only_spec() {
    let temp = TempDir::new().expect("tempdir");
    write_test_primary_agent(temp.path());
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let spec = controller
        .effective_specs()
        .await
        .into_iter()
        .find(|spec| spec.name == "duck")
        .expect("duck primary agent");

    let err = controller
        .spawn_custom(
            spec,
            SpawnAgentRequest {
                message: Some("Discuss the task.".to_string()),
                ..SpawnAgentRequest::default()
            },
        )
        .await
        .expect_err("primary-only custom spec should be rejected");

    assert!(
        err.to_string()
            .contains("custom subagent spawn only supports subagent-capable specs")
    );
}

#[tokio::test]
async fn close_marks_child_closed() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");
    controller.set_turn_delegation_hints_from_input("delegate this task").await;
    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("default".to_string()),
            message: Some("Summarize the repository.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");
    let closed = controller.close(&spawned.id).await.expect("close");
    assert_eq!(closed.status, SubagentStatus::Closed);
}

#[tokio::test]
async fn close_is_idempotent_for_closed_agents() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");
    controller.set_turn_delegation_hints_from_input("delegate this task").await;
    let spawned = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("default".to_string()),
            message: Some("Summarize the repository.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn");

    let closed = controller.close(&spawned.id).await.expect("first close");
    let closed_again = controller.close(&spawned.id).await.expect("second close");

    assert_eq!(closed_again.status, SubagentStatus::Closed);
    assert_eq!(closed_again.updated_at, closed.updated_at);
    assert_eq!(closed_again.completed_at, closed.completed_at);
}

#[tokio::test]
async fn close_and_resume_cascade_through_spawn_tree() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");

    {
        let mut state = controller.state.write().await;
        state.children.insert(
            "parent".to_string(),
            test_child_record("parent", "session-parent", "session-root", &spec, SubagentStatus::Running, 1, None),
        );
        state.children.insert(
            "child".to_string(),
            test_child_record("child", "session-child", "parent", &spec, SubagentStatus::Running, 2, None),
        );
        state.children.insert(
            "grandchild".to_string(),
            test_child_record("grandchild", "session-grandchild", "child", &spec, SubagentStatus::Running, 3, None),
        );
    }

    let closed = controller.close("parent").await.expect("close");
    assert_eq!(closed.status, SubagentStatus::Closed);
    assert_eq!(controller.status_for("child").await.expect("child").status, SubagentStatus::Closed);
    assert_eq!(controller.status_for("grandchild").await.expect("grandchild").status, SubagentStatus::Closed);

    let subtree_ids = controller.collect_spawn_subtree_ids("parent").await.expect("collect subtree");
    assert_eq!(subtree_ids, vec!["parent".to_string(), "child".to_string(), "grandchild".to_string()]);

    let mut restart_ids = Vec::new();
    for node_id in subtree_ids {
        if controller.reopen_single(node_id.as_str()).await.expect("reopen subtree node") {
            restart_ids.push(node_id);
        }
    }

    assert_eq!(restart_ids, vec!["parent".to_string(), "child".to_string(), "grandchild".to_string()]);
    assert_eq!(controller.status_for("parent").await.expect("parent").status, SubagentStatus::Queued);
    assert_eq!(controller.status_for("child").await.expect("child").status, SubagentStatus::Queued);
    assert_eq!(controller.status_for("grandchild").await.expect("grandchild").status, SubagentStatus::Queued);
}

#[tokio::test]
async fn spawn_rejects_fourth_active_subagent() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");
    controller.set_turn_delegation_hints_from_input("delegate this task").await;

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");

    {
        let mut state = controller.state.write().await;
        for idx in 0..SUBAGENT_HARD_CONCURRENCY_LIMIT {
            let id = format!("active-{idx}");
            state.children.insert(
                id.clone(),
                ChildRecord {
                    id: id.clone(),
                    session_id: format!("session-{id}"),
                    parent_thread_id: "parent-session".to_string(),
                    spec: spec.clone(),
                    display_label: subagent_display_label(&spec),
                    status: SubagentStatus::Running,
                    background: false,
                    depth: 1,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                    completed_at: None,
                    summary: None,
                    error: None,
                    archive_metadata: None,
                    archive_path: None,
                    transcript_path: None,
                    effective_config: None,
                    stored_messages: Vec::new(),
                    last_prompt: Some("Inspect the codebase.".to_string()),
                    queued_prompts: VecDeque::new(),
                    max_turns: None,
                    model_override: None,
                    reasoning_override: None,
                    thread_handle: None,
                    handle: None,
                    notify: Arc::new(Notify::new()),
                    worktree_path: None,
                    child_controller: None,
                },
            );
        }
    }

    let err = controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect another codepath.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("fourth active subagent should be rejected");

    assert!(err.to_string().contains(&format!(
            "Subagent concurrency limit reached (max_concurrent={})",
            controller.config.vt_cfg.subagents.max_concurrent.min(
                SUBAGENT_HARD_CONCURRENCY_LIMIT
            )
        )));
}

#[tokio::test]
async fn spawn_from_child_controller_respects_depth_limit() {
    let temp = TempDir::new().expect("tempdir");
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.subagents.max_depth = 2;

    // Child controller runs at depth 1: it may spawn a grandchild (depth 2),
    // but the grandchild itself (depth 2) may not spawn further.
    let mut child_config = test_controller_config(temp.path().to_path_buf(), vt_cfg.clone());
    child_config.depth = 1;
    let child_controller = SubagentController::new(child_config).await.expect("child controller");

    child_controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect the codebase.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("grandchild spawn should be allowed at depth 1 with max_depth=2");

    // Now a controller at depth 2 must refuse another spawn.
    let mut grandchild_config = test_controller_config(temp.path().to_path_buf(), vt_cfg);
    grandchild_config.depth = 2;
    let grandchild_controller = SubagentController::new(grandchild_config).await.expect("grandchild controller");

    let err = grandchild_controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect yet more.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("spawn at depth == max_depth should hit the depth limit");

    assert!(err.to_string().contains("Subagent depth limit reached (max_depth=2)"));

    // Abort queued child tasks so they cannot run provider work after the
    // temp workspace is removed.
    child_controller.signal_shutdown().await;
    grandchild_controller.signal_shutdown().await;
}

#[tokio::test]
async fn nested_spawn_rejects_worktree_isolation() {
    let temp = TempDir::new().expect("tempdir");
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.subagents.max_depth = 2;
    let mut child_config = test_controller_config(temp.path().to_path_buf(), vt_cfg);
    child_config.depth = 1;
    let child_controller = SubagentController::new(child_config).await.expect("child controller");
    child_controller
        .set_turn_delegation_hints_from_input("delegate this task")
        .await;

    // Force the discovered "worker" spec to request worktree isolation so the
    // nested-spawn guard can be exercised.
    {
        let mut state = child_controller.state.write().await;
        if let Some(spec) = state.discovered.effective.iter_mut().find(|spec| spec.name == "worker") {
            spec.isolation = Some(IsolationMode::Worktree);
        }
    }

    let err = child_controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("worker".to_string()),
            message: Some("Implement a change.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("nested worktree isolation should be rejected");

    assert!(err.to_string().contains("nested worktree isolation is not supported"));
}

#[tokio::test]
async fn close_cascades_to_child_scoped_grandchildren() {
    let temp = TempDir::new().expect("tempdir");
    let parent = SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
        .await
        .expect("parent controller");

    // Child-scoped controller that already has a grandchild tracked under the
    // child's session id.
    let child_controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("child controller");
    let child_session_id = "child-session".to_string();
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");
    {
        let mut state = child_controller.state.write().await;
        state.children.insert(
            "grandchild".to_string(),
            test_child_record(
                "grandchild",
                "session-grandchild",
                &child_session_id,
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let child_controller = std::sync::Arc::new(child_controller);

    // Register the child on the parent controller with the child-scoped
    // controller attached, then close it and assert the grandchild is closed.
    {
        let mut state = parent.state.write().await;
        state.children.insert(
            "child".to_string(),
            test_child_record(
                "child",
                &child_session_id,
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(child_controller.clone()),
            ),
        );
    }

    let closed = parent.close("child").await.expect("close child");
    assert!(closed.status.is_terminal());

    let grandchild_status = child_controller.status_for("grandchild").await.expect("grandchild status");
    assert_eq!(
        grandchild_status.status,
        SubagentStatus::Closed,
        "closing the child must cascade to its grandchildren"
    );
}

#[tokio::test]
async fn close_does_not_affect_sibling_grandchildren() {
    let temp = TempDir::new().expect("tempdir");
    let parent = SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
        .await
        .expect("parent controller");

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");

    // Two siblings each with their own child-scoped controller and a grandchild.
    let controller_a =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller a");
    {
        let mut state = controller_a.state.write().await;
        state.children.insert(
            "a-grandchild".to_string(),
            test_child_record(
                "a-grandchild",
                "session-a-grandchild",
                "session-a",
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let controller_b =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller b");
    {
        let mut state = controller_b.state.write().await;
        state.children.insert(
            "b-grandchild".to_string(),
            test_child_record(
                "b-grandchild",
                "session-b-grandchild",
                "session-b",
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let controller_a = std::sync::Arc::new(controller_a);
    let controller_b = std::sync::Arc::new(controller_b);

    {
        let mut state = parent.state.write().await;
        state.children.insert(
            "a".to_string(),
            test_child_record(
                "a",
                "session-a",
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(controller_a.clone()),
            ),
        );
        state.children.insert(
            "b".to_string(),
            test_child_record(
                "b",
                "session-b",
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(controller_b.clone()),
            ),
        );
    }

    parent.close("a").await.expect("close a");

    let b_grandchild = controller_b.status_for("b-grandchild").await.expect("b-grandchild status");
    assert_eq!(
        b_grandchild.status,
        SubagentStatus::Running,
        "closing sibling 'a' must not affect sibling 'b''s grandchildren"
    );
    let a_grandchild = controller_a.status_for("a-grandchild").await.expect("a-grandchild status");
    assert_eq!(a_grandchild.status, SubagentStatus::Closed, "closing 'a' must cascade to its own grandchildren");
}

#[tokio::test]
async fn spawn_is_rejected_after_close_begins() {
    let temp = TempDir::new().expect("tempdir");
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.subagents.max_depth = 2;
    let mut child_config = test_controller_config(temp.path().to_path_buf(), vt_cfg);
    child_config.depth = 1;
    let child_controller = SubagentController::new(child_config).await.expect("child controller");
    child_controller
        .set_turn_delegation_hints_from_input("delegate this task")
        .await;

    // Mark the controller as closing: this is exactly what `close_tree` does
    // to a child-scoped controller before aborting its subtree, so a still-
    // running child cannot spawn a grandchild after the descendant snapshot.
    child_controller.begin_close().await;

    let err = child_controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect the codebase.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect_err("spawn after close began must be rejected");

    assert!(err.to_string().contains("shutting down"));

    // Reopening the subtree clears the transient close flag, so a resumed
    // child can delegate again. Permanent `shutdown_requested` stays set only
    // for real shutdown, not for a subtree close.
    child_controller.end_close().await;
    child_controller
        .spawn(SpawnAgentRequest {
            agent_type: Some("explorer".to_string()),
            message: Some("Inspect the codebase.".to_string()),
            ..SpawnAgentRequest::default()
        })
        .await
        .expect("spawn after end_close must be allowed again");

    // Abort the queued child task so it cannot run provider work after the
    // temp workspace is removed.
    child_controller.signal_shutdown().await;
}

#[tokio::test]
async fn resume_rejected_after_shutdown() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");

    controller.signal_shutdown().await;

    let err = controller
        .resume("some-agent")
        .await
        .expect_err("resume after shutdown must be rejected");

    assert!(err.to_string().contains("shutting down"));
}

#[tokio::test]
async fn resume_restores_closed_grandchildren() {
    let temp = TempDir::new().expect("tempdir");
    let parent = SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
        .await
        .expect("parent controller");

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");

    // Child-scoped controller that has a grandchild under the child session id.
    let child_controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("child controller");
    let child_session_id = "child-session".to_string();
    {
        let mut state = child_controller.state.write().await;
        state.children.insert(
            "grandchild".to_string(),
            test_child_record(
                "grandchild",
                "session-grandchild",
                &child_session_id,
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let child_controller = std::sync::Arc::new(child_controller);
    {
        let mut state = parent.state.write().await;
        state.children.insert(
            "child".to_string(),
            test_child_record(
                "child",
                &child_session_id,
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(child_controller.clone()),
            ),
        );
    }

    // Closing the child cascades to the grandchild...
    parent.close("child").await.expect("close child");
    let closed_grandchild = child_controller.status_for("grandchild").await.expect("grandchild status");
    assert_eq!(closed_grandchild.status, SubagentStatus::Closed, "grandchild must be closed with the child");

    // ...and resuming the child must reopen the grandchild too, not just clear
    // the close gate.
    parent.resume("child").await.expect("resume child");
    let resumed_grandchild = child_controller.status_for("grandchild").await.expect("grandchild status");
    assert!(
        matches!(resumed_grandchild.status, SubagentStatus::Queued | SubagentStatus::Running),
        "resumed grandchild must be re-queued, got {:?}",
        resumed_grandchild.status
    );

    // Abort restarted child tasks so they cannot run provider work after the
    // temp workspace is removed.
    parent.signal_shutdown().await;
}

#[tokio::test]
async fn resume_does_not_affect_sibling_grandchildren() {
    let temp = TempDir::new().expect("tempdir");
    let parent = SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
        .await
        .expect("parent controller");

    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "explorer")
        .expect("explorer");

    // Two siblings each with their own child-scoped controller and a grandchild.
    let controller_a =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller a");
    {
        let mut state = controller_a.state.write().await;
        state.children.insert(
            "a-grandchild".to_string(),
            test_child_record(
                "a-grandchild",
                "session-a-grandchild",
                "session-a",
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let controller_b =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller b");
    {
        let mut state = controller_b.state.write().await;
        state.children.insert(
            "b-grandchild".to_string(),
            test_child_record(
                "b-grandchild",
                "session-b-grandchild",
                "session-b",
                &spec,
                SubagentStatus::Running,
                2,
                None,
            ),
        );
    }
    let controller_a = std::sync::Arc::new(controller_a);
    let controller_b = std::sync::Arc::new(controller_b);
    {
        let mut state = parent.state.write().await;
        state.children.insert(
            "a".to_string(),
            test_child_record(
                "a",
                "session-a",
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(controller_a.clone()),
            ),
        );
        state.children.insert(
            "b".to_string(),
            test_child_record(
                "b",
                "session-b",
                "parent-session",
                &spec,
                SubagentStatus::Running,
                1,
                Some(controller_b.clone()),
            ),
        );
    }

    // Close both siblings' grandchildren, then resume only "a": "b"'s
    // grandchild must stay closed (resume_tree must respect subtree isolation).
    parent.close("a").await.expect("close a");
    parent.close("b").await.expect("close b");

    parent.resume("a").await.expect("resume a");

    let a_grandchild = controller_a.status_for("a-grandchild").await.expect("a-grandchild status");
    assert!(
        matches!(a_grandchild.status, SubagentStatus::Queued | SubagentStatus::Running),
        "resumed 'a''s grandchild must be re-queued, got {:?}",
        a_grandchild.status
    );
    let b_grandchild = controller_b.status_for("b-grandchild").await.expect("b-grandchild status");
    assert_eq!(
        b_grandchild.status,
        SubagentStatus::Closed,
        "resuming sibling 'a' must not reopen sibling 'b''s grandchildren"
    );

    // Abort restarted child tasks so they cannot run provider work after the
    // temp workspace is removed.
    parent.signal_shutdown().await;
}

#[tokio::test]
async fn wait_returns_first_terminal_child() {
    let temp = TempDir::new().expect("tempdir");
    let controller =
        SubagentController::new(test_controller_config(temp.path().to_path_buf(), VTCodeConfig::default()))
            .await
            .expect("controller");
    let spec = vtcode_config::builtin_subagents()
        .into_iter()
        .find(|spec| spec.name == "default")
        .expect("default");

    {
        let mut state = controller.state.write().await;
        for id in ["first", "second"] {
            state.children.insert(
                id.to_string(),
                ChildRecord {
                    id: id.to_string(),
                    session_id: format!("session-{id}"),
                    parent_thread_id: "parent-session".to_string(),
                    spec: spec.clone(),
                    display_label: subagent_display_label(&spec),
                    status: SubagentStatus::Running,
                    background: false,
                    depth: 1,
                    created_at: Utc::now(),
                    updated_at: Utc::now(),
                    completed_at: None,
                    summary: None,
                    error: None,
                    archive_metadata: None,
                    archive_path: None,
                    transcript_path: None,
                    effective_config: None,
                    stored_messages: Vec::new(),
                    last_prompt: None,
                    queued_prompts: VecDeque::new(),
                    max_turns: None,
                    model_override: None,
                    reasoning_override: None,
                    thread_handle: None,
                    handle: None,
                    notify: Arc::new(Notify::new()),
                    worktree_path: None,
                    child_controller: None,
                },
            );
        }
    }

    let controller_clone = controller.clone();
    tokio::spawn(async move {
        tokio::time::sleep(Duration::from_millis(20)).await;
        let mut state = controller_clone.state.write().await;
        let record = state.children.get_mut("second").expect("second child");
        record.status = SubagentStatus::Completed;
        record.summary = Some("done".to_string());
        record.completed_at = Some(Utc::now());
        record.updated_at = Utc::now();
        record.notify.notify_waiters();
    });

    let result = controller
        .wait(&["first".to_string(), "second".to_string()], Some(500))
        .await
        .expect("wait result")
        .expect("terminal child");
    assert_eq!(result.id, "second");
    assert_eq!(result.status, SubagentStatus::Completed);
}