atomcode-core 4.23.1

Open-source terminal AI coding agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
//! Tests for TurnRunner, discipline logic, and approval flow.

use anyhow::Result;
use async_trait::async_trait;
use futures::stream;
use futures::Stream;
use std::collections::HashMap;
use std::path::PathBuf;
use std::pin::Pin;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::config::provider::ProviderConfig;
use crate::config::Config;
use crate::conversation::message::Message;
use crate::conversation::Conversation;
use crate::provider::LlmProvider;
use crate::stream::{StreamEvent, TokenUsage};
use crate::tool::{
    ApprovalRequirement, PermissionDecision, Tool, ToolCall, ToolContext, ToolDef, ToolRegistry,
    ToolResult,
};

use super::event::{TurnEvent, TurnResult};
use super::permission::{AutoPermissionDecider, AutoPermissionMode, InteractivePermissionDecider};
use super::runner::TurnRunner;

// ---------------------------------------------------------------------------
// Test helpers: Mock LlmProvider
// ---------------------------------------------------------------------------

/// A mock LLM provider that returns a predefined sequence of StreamEvents.
struct MockProvider {
    events: Vec<StreamEvent>,
}

impl MockProvider {
    fn text_only(text: &str) -> Self {
        Self {
            events: vec![
                StreamEvent::Delta(text.to_string()),
                StreamEvent::Usage(TokenUsage {
                    prompt_tokens: 10,
                    completion_tokens: 5,
                    cached_tokens: 0,
                }),
                StreamEvent::Done { truncated: false },
            ],
        }
    }

    fn with_tool_call(tool_name: &str, args: &str) -> Self {
        Self {
            events: vec![
                StreamEvent::ToolCallStart {
                    id: "call_1".to_string(),
                    name: tool_name.to_string(),
                },
                StreamEvent::ToolCallDelta(args.to_string()),
                StreamEvent::ToolCallDone(ToolCall {
                    id: "call_1".to_string(),
                    name: tool_name.to_string(),
                    arguments: args.to_string(),
                }),
                StreamEvent::Usage(TokenUsage {
                    prompt_tokens: 10,
                    completion_tokens: 8,
                    cached_tokens: 0,
                }),
                StreamEvent::Done { truncated: false },
            ],
        }
    }

    fn with_error(msg: &str) -> Self {
        Self {
            events: vec![StreamEvent::Error(msg.to_string())],
        }
    }

    fn empty() -> Self {
        Self {
            events: vec![StreamEvent::Done { truncated: false }],
        }
    }
}

#[async_trait]
impl LlmProvider for MockProvider {
    fn chat_stream(
        &self,
        _messages: &[Message],
        _tools: Option<&[ToolDef]>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>> {
        let events: Vec<Result<StreamEvent>> = self.events.iter().cloned().map(Ok).collect();
        Ok(Box::pin(stream::iter(events)))
    }

    fn model_name(&self) -> &str {
        "mock-model"
    }
}

// ---------------------------------------------------------------------------
// SequencedMockProvider: Multi-turn provider for SubAgent integration tests
// ---------------------------------------------------------------------------

/// Multi-turn provider: returns the i-th `Vec<StreamEvent>` on the i-th
/// `chat_stream` call. Used to simulate hallucinating agents (turn 0:
/// read_file, turn 1: read_file, ...) and recovery flows (turn 0:
/// timeout error, turn 1: edit success).
struct SequencedMockProvider {
    sequences: std::sync::Mutex<std::collections::VecDeque<Vec<StreamEvent>>>,
}

impl SequencedMockProvider {
    fn new(sequences: Vec<Vec<StreamEvent>>) -> Self {
        Self {
            sequences: std::sync::Mutex::new(sequences.into()),
        }
    }
}

#[async_trait]
impl LlmProvider for SequencedMockProvider {
    fn chat_stream(
        &self,
        _messages: &[Message],
        _tools: Option<&[ToolDef]>,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamEvent>> + Send>>> {
        let next = self
            .sequences
            .lock()
            .unwrap()
            .pop_front()
            .unwrap_or_else(|| vec![StreamEvent::Done { truncated: false }]);
        let events: Vec<Result<StreamEvent>> = next.into_iter().map(Ok).collect();
        Ok(Box::pin(stream::iter(events)))
    }
    fn model_name(&self) -> &str {
        "sequenced-mock"
    }
}

/// Quick builder for a single-tool-call turn (used in sequenced tests).
fn tool_call_events(call_id: &str, name: &str, args: &str) -> Vec<StreamEvent> {
    vec![
        StreamEvent::ToolCallStart {
            id: call_id.into(),
            name: name.into(),
        },
        StreamEvent::ToolCallDelta(args.into()),
        StreamEvent::ToolCallDone(ToolCall {
            id: call_id.into(),
            name: name.into(),
            arguments: args.into(),
        }),
        StreamEvent::Usage(TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 8,
            cached_tokens: 0,
        }),
        StreamEvent::Done { truncated: false },
    ]
}

fn text_only_events(text: &str) -> Vec<StreamEvent> {
    vec![
        StreamEvent::Delta(text.into()),
        StreamEvent::Usage(TokenUsage {
            prompt_tokens: 10,
            completion_tokens: 5,
            cached_tokens: 0,
        }),
        StreamEvent::Done { truncated: false },
    ]
}

fn error_events(msg: &str) -> Vec<StreamEvent> {
    vec![StreamEvent::Error(msg.into())]
}

// ---------------------------------------------------------------------------
// Test helpers: Mock Tools
// ---------------------------------------------------------------------------

/// A simple tool that always succeeds and returns its name.
struct EchoTool {
    name: &'static str,
}

#[async_trait]
impl Tool for EchoTool {
    fn definition(&self) -> ToolDef {
        ToolDef {
            name: self.name,
            description: format!("Echo tool: {}", self.name),
            parameters: serde_json::json!({"type": "object"}),
        }
    }
    fn approval(&self, _args: &str) -> ApprovalRequirement {
        ApprovalRequirement::AutoApprove
    }
    async fn execute(&self, args: &str, _ctx: &ToolContext) -> Result<ToolResult> {
        Ok(ToolResult {
            call_id: String::new(),
            output: format!("executed {} with {}", self.name, args),
            success: true,
        })
    }
}

/// A tool that requires user approval.
struct DangerousTool;

#[async_trait]
impl Tool for DangerousTool {
    fn definition(&self) -> ToolDef {
        ToolDef {
            name: "dangerous",
            description: "Requires approval".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        }
    }
    fn approval(&self, _args: &str) -> ApprovalRequirement {
        ApprovalRequirement::RequireApproval("This is dangerous".to_string())
    }
    async fn execute(&self, _args: &str, _ctx: &ToolContext) -> Result<ToolResult> {
        Ok(ToolResult {
            call_id: String::new(),
            output: "dangerous action done".to_string(),
            success: true,
        })
    }
}

/// A tool that only requires approval when it can inspect the current context.
struct ContextDangerousTool;

#[async_trait]
impl Tool for ContextDangerousTool {
    fn definition(&self) -> ToolDef {
        ToolDef {
            name: "context_dangerous",
            description: "Requires context-aware approval".to_string(),
            parameters: serde_json::json!({"type": "object"}),
        }
    }
    fn approval(&self, _args: &str) -> ApprovalRequirement {
        ApprovalRequirement::AutoApprove
    }
    fn approval_with_context(&self, _args: &str, _ctx: &ToolContext) -> ApprovalRequirement {
        ApprovalRequirement::RequireApproval("Needs context-aware confirmation".to_string())
    }
    async fn execute(&self, _args: &str, _ctx: &ToolContext) -> Result<ToolResult> {
        Ok(ToolResult {
            call_id: String::new(),
            output: "context-aware action done".to_string(),
            success: true,
        })
    }
}

// ---------------------------------------------------------------------------
// Test helpers: Config / Context
// ---------------------------------------------------------------------------

fn test_config() -> Config {
    let mut providers = HashMap::new();
    providers.insert(
        "test".to_string(),
        ProviderConfig {
            provider_type: "mock".to_string(),
            api_key: None,
            model: "mock-model".to_string(),
            base_url: None,
            system_prompt: None,
            user_agent: None,
            context_window: 16000,
            max_tokens: None,
            thinking_type: None,
            thinking_keep: None,
            reasoning_history: None,
            thinking_enabled: None,
            thinking_budget: None,
            skip_tls_verify: false,
            ephemeral: false,

},
    );
    Config {
        default_provider: "test".to_string(),
        default_workdir: None,
        providers,
        datalog: Default::default(),
        notifications: Default::default(),
        auto_update: false,
        telemetry: Default::default(),
        lsp: Default::default(),
        auto_commit: false,
        subagent: Default::default(),
        vision_preprocessor_provider: None,
        language: None,
        ui: Default::default(),
            plugin: Default::default(),
    }
}

fn test_context() -> ToolContext {
    ToolContext::new(PathBuf::from("/tmp/test"))
}

fn make_runner(
    provider: MockProvider,
    tools: ToolRegistry,
    permission: Box<dyn super::permission::PermissionDecider>,
) -> TurnRunner {
    // Tests don't set up real ProviderConfig, so construct a DefaultCtx
    // directly with a generous window (matches test_config's implicit budget).
    let test_provider = crate::config::provider::ProviderConfig {
        provider_type: "test".into(),
        api_key: None,
        model: "test-model".into(),
        base_url: None,
        system_prompt: None,
        user_agent: None,
        context_window: 128_000,
        max_tokens: None,
        thinking_type: None,
        thinking_keep: None,
        reasoning_history: None,
        thinking_enabled: None,
        thinking_budget: None,
        skip_tls_verify: false,
        ephemeral: true,

};
    let test_ctx: std::sync::Arc<dyn crate::ctx::CtxBuilder> =
        std::sync::Arc::new(crate::ctx::DefaultCtx::new(&test_provider));

    TurnRunner {
        provider: std::sync::Arc::new(provider),
        tools: std::sync::Arc::new(tools),
        context: test_context(),
        config: test_config(),
        ctx: test_ctx,
        permission,
        recently_edited_files: Vec::new(),
        hook_executor: std::sync::Arc::new(
            crate::hook::executor::HookExecutor::empty()
        ),
        loop_guard: Default::default(),
    }
}

fn auto_bypass() -> Box<dyn super::permission::PermissionDecider> {
    Box::new(AutoPermissionDecider::new(AutoPermissionMode::BypassAll))
}

fn auto_deny() -> Box<dyn super::permission::PermissionDecider> {
    Box::new(AutoPermissionDecider::new(AutoPermissionMode::DenyAll))
}

// ===========================================================================
// 1. TurnRunner tests
// ===========================================================================

#[tokio::test]
async fn test_turn_runner_text_only_response() {
    let mut runner = make_runner(
        MockProvider::text_only("Hello, world!"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::Responded { text, tokens, .. } => {
            assert_eq!(text, "Hello, world!");
            assert!(tokens > 0);
        }
        other => panic!("Expected Responded, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_empty_response_is_failure() {
    let mut runner = make_runner(MockProvider::empty(), ToolRegistry::new(), auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::Failed(msg) => {
            assert!(msg.contains("empty response"));
        }
        other => panic!("Expected Failed, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_emits_text_delta_events() {
    let mut runner = make_runner(
        MockProvider::text_only("Hello"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, mut rx) = mpsc::unbounded_channel();

    runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    // Collect events
    drop(tx);
    let mut got_text_delta = false;
    while let Some(event) = rx.recv().await {
        if matches!(event, TurnEvent::TextDelta(_)) {
            got_text_delta = true;
        }
    }
    assert!(got_text_delta, "Expected at least one TextDelta event");
}

#[tokio::test]
async fn test_turn_runner_executes_tool_call() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;

    let provider = MockProvider::with_tool_call("grep", r#"{"pattern":"foo"}"#);
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search for foo");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { tool_count, .. } => {
            assert_eq!(tool_count, 1);
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }

    // Verify tool result was added to conversation
    let last = conv.messages.last().unwrap();
    assert!(matches!(
        last.content,
        crate::conversation::message::MessageContent::ToolResult(_)
    ));
}

#[tokio::test]
async fn test_turn_runner_emits_tool_events() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;

    let provider = MockProvider::with_tool_call("grep", r#"{"pattern":"foo"}"#);
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search");
    let (tx, mut rx) = mpsc::unbounded_channel();

    runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    drop(tx);
    let mut got_started = false;
    let mut got_result = false;
    while let Some(event) = rx.recv().await {
        match event {
            TurnEvent::ToolCallStarted { name, .. } if name == "grep" => got_started = true,
            TurnEvent::ToolCallResult { name, success, .. } if name == "grep" => {
                got_result = true;
                assert!(success);
            }
            _ => {}
        }
    }
    assert!(got_started, "Expected ToolCallStarted event");
    assert!(got_result, "Expected ToolCallResult event");
}

#[tokio::test]
async fn test_turn_runner_unknown_tool_returns_error_result() {
    // Provider asks to call a tool that isn't registered
    let provider = MockProvider::with_tool_call("nonexistent", "{}");
    let mut runner = make_runner(provider, ToolRegistry::new(), auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("do something");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { tool_count, .. } => {
            assert_eq!(tool_count, 1);
            // Last message should be a failed tool result
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(!r.success);
                assert!(r.output.contains("unknown tool"));
            } else {
                panic!("Expected ToolResult message");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_loop_guard_blocks_third_identical_call() {
    // Integration-level pin for the cross-batch loop guard wired into
    // `run_with_filter` (see runner.rs). Three sequential `run()`
    // invocations using the same MockProvider produce three identical
    // tool calls (same name + same args) with identical EchoTool
    // output. The first two execute (so the model gets two "maybe
    // this time will differ" chances on real flakes), the third must
    // be short-circuited with a synthetic Loop guard ToolResult — no
    // EchoTool output should appear in the third result.
    let mut tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;
    let provider = MockProvider::with_tool_call("grep", r#"{"pattern":"foo"}"#);
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search");
    let (tx, _rx) = mpsc::unbounded_channel();

    for _ in 0..3 {
        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;
    }

    // Walk the conversation, collect every ToolResult body in order.
    let mut results: Vec<String> = Vec::new();
    for msg in &conv.messages {
        if let crate::conversation::message::MessageContent::ToolResult(r) = &msg.content {
            results.push(r.output.clone());
        }
    }
    assert_eq!(results.len(), 3, "expected 3 tool results, got {}", results.len());
    assert!(
        results[0].contains("executed grep"),
        "1st call should run normally, got: {:?}",
        results[0]
    );
    assert!(
        results[1].contains("executed grep"),
        "2nd call should run normally, got: {:?}",
        results[1]
    );
    assert!(
        results[2].contains("Loop guard"),
        "3rd identical call should be blocked by loop guard, got: {:?}",
        results[2]
    );
}

#[tokio::test]
async fn test_turn_runner_handles_stream_error() {
    let provider = MockProvider::with_error("API rate limit exceeded");
    let mut runner = make_runner(provider, ToolRegistry::new(), auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::Failed(e) => {
            assert!(e.contains("rate limit"), "Error was: {}", e);
        }
        other => panic!("Expected Failed, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_cancellation() {
    let provider = MockProvider::text_only("This should be cancelled");
    let mut runner = make_runner(provider, ToolRegistry::new(), auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, _rx) = mpsc::unbounded_channel();

    let cancel = CancellationToken::new();
    cancel.cancel(); // Cancel immediately

    let result = runner.run(&mut conv, "system", &tx, cancel).await;

    assert!(matches!(result, TurnResult::Cancelled));
}

// ===========================================================================
// 2. Permission / Approval tests
// ===========================================================================

#[tokio::test]
async fn test_turn_runner_auto_deny_blocks_dangerous_tool() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(DangerousTool)).await;

    let provider = MockProvider::with_tool_call("dangerous", "{}");
    let mut runner = make_runner(provider, tools, auto_deny());
    let mut conv = Conversation::new();
    conv.add_user_message("do dangerous thing");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    // Tool should be denied, but turn still returns UsedTools (with denied result)
    match result {
        TurnResult::UsedTools { .. } => {
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(!r.success);
                assert!(r.output.contains("denied"));
            } else {
                panic!("Expected ToolResult");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_auto_bypass_allows_dangerous_tool() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(DangerousTool)).await;

    let provider = MockProvider::with_tool_call("dangerous", "{}");
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("do dangerous thing");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { .. } => {
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(r.success);
                assert!(r.output.contains("dangerous action done"));
            } else {
                panic!("Expected ToolResult");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_interactive_approval_allow() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(DangerousTool)).await;

    let (req_tx, mut req_rx) = mpsc::unbounded_channel();
    let (resp_tx, resp_rx) = mpsc::unbounded_channel();
    let store = std::sync::Arc::new(std::sync::RwLock::new(crate::tool::PermissionStore::new()));
    let permission = Box::new(InteractivePermissionDecider::new(req_tx, resp_rx, store));

    let provider = MockProvider::with_tool_call("dangerous", "{}");
    let mut runner = make_runner(provider, tools, permission);
    let mut conv = Conversation::new();
    conv.add_user_message("do it");
    let (tx, _rx) = mpsc::unbounded_channel();

    // Spawn responder: auto-approve when request arrives
    tokio::spawn(async move {
        if let Some(_req) = req_rx.recv().await {
            resp_tx.send(PermissionDecision::Allow).unwrap();
        }
    });

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { .. } => {
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(r.success, "Tool should have been approved and executed");
            } else {
                panic!("Expected ToolResult");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_interactive_approval_deny() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(DangerousTool)).await;

    let (req_tx, mut req_rx) = mpsc::unbounded_channel();
    let (resp_tx, resp_rx) = mpsc::unbounded_channel();
    let store = std::sync::Arc::new(std::sync::RwLock::new(crate::tool::PermissionStore::new()));
    let permission = Box::new(InteractivePermissionDecider::new(req_tx, resp_rx, store));

    let provider = MockProvider::with_tool_call("dangerous", "{}");
    let mut runner = make_runner(provider, tools, permission);
    let mut conv = Conversation::new();
    conv.add_user_message("do it");
    let (tx, _rx) = mpsc::unbounded_channel();

    // Spawn responder: deny when request arrives
    tokio::spawn(async move {
        if let Some(_req) = req_rx.recv().await {
            resp_tx.send(PermissionDecision::Deny).unwrap();
        }
    });

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { .. } => {
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(!r.success, "Tool should have been denied");
                assert!(r.output.contains("denied"));
            } else {
                panic!("Expected ToolResult");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

#[tokio::test]
async fn test_turn_runner_uses_context_aware_approval() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(ContextDangerousTool)).await;

    let provider = MockProvider::with_tool_call("context_dangerous", "{}");
    let mut runner = make_runner(provider, tools, auto_deny());
    let mut conv = Conversation::new();
    conv.add_user_message("do it");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    match result {
        TurnResult::UsedTools { .. } => {
            let last = conv.messages.last().unwrap();
            if let crate::conversation::message::MessageContent::ToolResult(ref r) = last.content {
                assert!(!r.success, "Tool should have been denied");
                assert!(r.output.contains("denied"));
            } else {
                panic!("Expected ToolResult");
            }
        }
        other => panic!("Expected UsedTools, got {:?}", other),
    }
}

// ===========================================================================
// 3. Discipline logic tests (step limit, reminders)
// ===========================================================================

#[test]
fn test_check_step_limit_under_limit() {
    // step limit = 50 + 5*0 = 50
    assert!(!check_step_limit_impl(30, 0));
}

#[test]
fn test_check_step_limit_at_limit() {
    // step limit = 50 + 5*0 = 50
    assert!(check_step_limit_impl(50, 0));
}

#[test]
fn test_check_step_limit_with_edits_extends() {
    // step limit = 50 + 5*5 = 75
    assert!(!check_step_limit_impl(70, 5));
    assert!(check_step_limit_impl(75, 5));
}

#[test]
fn test_check_step_limit_hard_cap_100() {
    // step limit = 50 + 5*20 = 150, min(150, 100) = 100
    assert!(!check_step_limit_impl(99, 20));
    assert!(check_step_limit_impl(100, 20));
}

/// Standalone reimplementation of check_step_limit logic for unit testing.
fn check_step_limit_impl(tool_call_count: usize, files_edited_count: usize) -> bool {
    let dynamic_limit = 50 + (5 * files_edited_count);
    let hard_limit = dynamic_limit.min(100);
    tool_call_count >= hard_limit
}

// ---------------------------------------------------------------------------
// Turn limit tests (mirror of check_turn_limit in agent/discipline.rs)
// ---------------------------------------------------------------------------

#[test]
fn test_check_turn_limit_none_unbounded() {
    // No cap set → never stops regardless of turn_count.
    assert!(!check_turn_limit_impl(0, None));
    assert!(!check_turn_limit_impl(1, None));
    assert!(!check_turn_limit_impl(1_000_000, None));
}

#[test]
fn test_check_turn_limit_under_limit() {
    // cap = 3: turns 0, 1, 2 all still "under" → loop continues.
    assert!(!check_turn_limit_impl(0, Some(3)));
    assert!(!check_turn_limit_impl(1, Some(3)));
    assert!(!check_turn_limit_impl(2, Some(3)));
}

#[test]
fn test_check_turn_limit_at_or_over_limit() {
    // cap = 3: at turn_count == 3, loop should stop (before running a 4th turn).
    assert!(check_turn_limit_impl(3, Some(3)));
    assert!(check_turn_limit_impl(4, Some(3)));
    assert!(check_turn_limit_impl(100, Some(3)));
}

#[test]
fn test_check_turn_limit_zero_stops_immediately() {
    // Degenerate but valid: cap = 0 means "run zero turns".
    assert!(check_turn_limit_impl(0, Some(0)));
}

/// Standalone reimplementation of check_turn_limit for unit testing.
/// Must match the formula used by AgentLoop::check_turn_limit in
/// agent/discipline.rs. If you change one, change both.
fn check_turn_limit_impl(turn_count: usize, max_turns: Option<usize>) -> bool {
    max_turns.map_or(false, |m| turn_count >= m)
}

#[test]
fn test_discipline_reminder_triggers_every_4_steps() {
    // Reminders should fire at steps 4, 8, 12, 16...
    assert!(should_inject_reminder(4));
    assert!(should_inject_reminder(8));
    assert!(should_inject_reminder(12));
    assert!(!should_inject_reminder(3));
    assert!(!should_inject_reminder(5));
    assert!(!should_inject_reminder(0));
}

fn should_inject_reminder(tool_call_count: usize) -> bool {
    tool_call_count > 0 && tool_call_count % 4 == 0
}

// ===========================================================================
// 4. Token usage tracking
// ===========================================================================

#[tokio::test]
async fn test_turn_runner_reports_token_usage() {
    let mut runner = make_runner(
        MockProvider::text_only("Hello"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, mut rx) = mpsc::unbounded_channel();

    runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    drop(tx);
    let mut got_usage = false;
    while let Some(event) = rx.recv().await {
        if let TurnEvent::TokenUsage { total_tokens, .. } = event {
            assert!(total_tokens > 0);
            got_usage = true;
        }
    }
    assert!(got_usage, "Expected TokenUsage event");
}

// ===========================================================================
// 5. Conversation state correctness
// ===========================================================================

#[tokio::test]
async fn test_turn_runner_adds_assistant_message_on_text_response() {
    let mut runner = make_runner(
        MockProvider::text_only("Hello!"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("Hi");
    let (tx, _rx) = mpsc::unbounded_channel();
    let msg_count_before = conv.messages.len();

    runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    // Should have added an assistant text message
    assert_eq!(conv.messages.len(), msg_count_before + 1);
    let last = conv.messages.last().unwrap();
    assert!(matches!(
        last.role,
        crate::conversation::message::Role::Assistant
    ));
    assert_eq!(last.text(), Some("Hello!"));
}

#[tokio::test]
async fn test_turn_runner_adds_tool_call_and_result_messages() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;

    let provider = MockProvider::with_tool_call("grep", "{}");
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search");
    let (tx, _rx) = mpsc::unbounded_channel();
    let msg_count_before = conv.messages.len();

    runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;

    // Should have: AssistantWithToolCalls + ToolResult = 2 new messages
    assert_eq!(conv.messages.len(), msg_count_before + 2);

    let assistant_msg = &conv.messages[msg_count_before];
    assert!(matches!(
        assistant_msg.content,
        crate::conversation::message::MessageContent::AssistantWithToolCalls { .. }
    ));

    let tool_msg = &conv.messages[msg_count_before + 1];
    assert!(matches!(
        tool_msg.content,
        crate::conversation::message::MessageContent::ToolResult(_)
    ));
}

/// Verify that tool results contain correct content and are properly linked
/// to their tool calls via call_id, so the next LLM turn sees a coherent
/// conversation (AssistantWithToolCalls → matching ToolResult).
#[tokio::test]
async fn test_tool_result_content_in_llm_context() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;

    let provider = MockProvider::with_tool_call("grep", r#"{"pattern":"foo"}"#);
    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search for foo");
    let (tx, _rx) = mpsc::unbounded_channel();

    runner
        .run(&mut conv, "system prompt", &tx, CancellationToken::new())
        .await;

    // Build provider messages as TurnRunner would for the next LLM call.
    let provider_msgs = conv.to_provider_messages("system prompt");

    // Structure: [System, User, AssistantWithToolCalls, ToolResult]
    assert_eq!(provider_msgs.len(), 4);

    // 1. System prompt
    assert!(matches!(
        provider_msgs[0].role,
        crate::conversation::message::Role::System
    ));
    assert_eq!(provider_msgs[0].text(), Some("system prompt"));

    // 2. User message preserved
    assert!(matches!(
        provider_msgs[1].role,
        crate::conversation::message::Role::User
    ));
    assert_eq!(provider_msgs[1].text(), Some("search for foo"));

    // 3. Assistant message with tool call — call_id and arguments preserved
    if let crate::conversation::message::MessageContent::AssistantWithToolCalls {
        text: _,
        ref tool_calls,
        ..
    } = provider_msgs[2].content
    {
        assert_eq!(tool_calls.len(), 1);
        assert_eq!(tool_calls[0].name, "grep");
        assert_eq!(tool_calls[0].arguments, r#"{"pattern":"foo"}"#);
        assert_eq!(tool_calls[0].id, "call_1");
    } else {
        panic!(
            "Expected AssistantWithToolCalls, got {:?}",
            provider_msgs[2].content
        );
    }

    // 4. Tool result — call_id matches, output contains actual tool execution result
    if let crate::conversation::message::MessageContent::ToolResult(ref result) =
        provider_msgs[3].content
    {
        assert_eq!(result.call_id, "call_1", "call_id must match the tool call");
        assert!(result.success);
        assert!(
            result.output.contains("executed grep"),
            "Tool output missing: {}",
            result.output
        );
        assert!(
            result.output.contains(r#"{"pattern":"foo"}"#),
            "Args missing from output: {}",
            result.output
        );
    } else {
        panic!("Expected ToolResult, got {:?}", provider_msgs[3].content);
    }
}

/// Verify that multiple tool calls in one turn each get their own result
/// with correct call_id linkage in the conversation.
#[tokio::test]
async fn test_multiple_tool_calls_results_in_context() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(EchoTool { name: "grep" })).await;
    tools.register(Box::new(EchoTool { name: "read_file" })).await;

    // Provider returns two tool calls in sequence
    let provider = MockProvider {
        events: vec![
            StreamEvent::ToolCallStart {
                id: "c1".into(),
                name: "grep".into(),
            },
            StreamEvent::ToolCallDelta(r#"{"pattern":"foo"}"#.into()),
            StreamEvent::ToolCallDone(ToolCall {
                id: "c1".into(),
                name: "grep".into(),
                arguments: r#"{"pattern":"foo"}"#.into(),
            }),
            StreamEvent::ToolCallStart {
                id: "c2".into(),
                name: "read_file".into(),
            },
            StreamEvent::ToolCallDelta(r#"{"file_path":"/tmp/x"}"#.into()),
            StreamEvent::ToolCallDone(ToolCall {
                id: "c2".into(),
                name: "read_file".into(),
                arguments: r#"{"file_path":"/tmp/x"}"#.into(),
            }),
            StreamEvent::Usage(TokenUsage {
                prompt_tokens: 20,
                completion_tokens: 10,
                cached_tokens: 0,
            }),
            StreamEvent::Done { truncated: false },
        ],
    };

    let mut runner = make_runner(provider, tools, auto_bypass());
    let mut conv = Conversation::new();
    conv.add_user_message("search and read");
    let (tx, _rx) = mpsc::unbounded_channel();

    let result = runner
        .run(&mut conv, "sys", &tx, CancellationToken::new())
        .await;

    // Should report 2 tool calls
    match result {
        TurnResult::UsedTools { tool_count, .. } => assert_eq!(tool_count, 2),
        other => panic!("Expected UsedTools, got {:?}", other),
    }

    // Build provider messages for next turn
    let msgs = conv.to_provider_messages("sys");
    // [System, User, AssistantWithToolCalls, ToolResult(c1), ToolResult(c2)]
    assert_eq!(msgs.len(), 5);

    // Verify AssistantWithToolCalls has both calls
    if let crate::conversation::message::MessageContent::AssistantWithToolCalls {
        ref tool_calls,
        ..
    } = msgs[2].content
    {
        assert_eq!(tool_calls.len(), 2);
        assert_eq!(tool_calls[0].id, "c1");
        assert_eq!(tool_calls[0].name, "grep");
        assert_eq!(tool_calls[1].id, "c2");
        assert_eq!(tool_calls[1].name, "read_file");
    } else {
        panic!("Expected AssistantWithToolCalls");
    }

    // Verify each ToolResult has correct call_id and content
    if let crate::conversation::message::MessageContent::ToolResult(ref r) = msgs[3].content {
        assert_eq!(r.call_id, "c1");
        assert!(r.output.contains("executed grep"));
    } else {
        panic!("Expected ToolResult for c1");
    }

    if let crate::conversation::message::MessageContent::ToolResult(ref r) = msgs[4].content {
        assert_eq!(r.call_id, "c2");
        assert!(r.output.contains("executed read_file"));
    } else {
        panic!("Expected ToolResult for c2");
    }
}

/// Verify that a denied tool call still produces a ToolResult in the context
/// (with success=false), so the LLM knows the tool was denied and can adjust.
#[tokio::test]
async fn test_denied_tool_result_in_llm_context() {
    let tools = ToolRegistry::new();
    tools.register(Box::new(DangerousTool)).await;

    let provider = MockProvider::with_tool_call("dangerous", "{}");
    let mut runner = make_runner(provider, tools, auto_deny());
    let mut conv = Conversation::new();
    conv.add_user_message("do it");
    let (tx, _rx) = mpsc::unbounded_channel();

    runner
        .run(&mut conv, "sys", &tx, CancellationToken::new())
        .await;

    let msgs = conv.to_provider_messages("sys");
    // [System, User, AssistantWithToolCalls, ToolResult(denied)]
    assert_eq!(msgs.len(), 4);

    if let crate::conversation::message::MessageContent::ToolResult(ref r) = msgs[3].content {
        assert_eq!(r.call_id, "call_1");
        assert!(!r.success, "Denied tool should have success=false");
        assert!(
            r.output.contains("denied"),
            "Should indicate denial: {}",
            r.output
        );
    } else {
        panic!("Expected ToolResult for denied call");
    }
}

// ===========================================================================
// Prompt caching tests
// ===========================================================================

/// Turn reminder should be injected into the last user message (copy only),
/// not into the conversation history.
#[tokio::test]
async fn test_turn_reminder_injected_into_last_user_message() {
    let mut runner = make_runner(
        MockProvider::text_only("ok"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("fix the bug");
    let (tx, _rx) = mpsc::unbounded_channel();

    let reminder = "<system-reminder>\nCurrent task: fix the bug\n</system-reminder>";
    runner
        .run_with_filter(
            &mut conv,
            "system",
            reminder,
            &tx,
            CancellationToken::new(),
            None,
        )
        .await;

    // Conversation history should NOT contain the reminder
    for msg in &conv.messages {
        if let crate::conversation::message::MessageContent::Text(ref text) = msg.content {
            assert!(
                !text.contains("system-reminder"),
                "Turn reminder leaked into conversation history: {}",
                text
            );
        }
    }
}

/// Empty turn reminder should not modify messages.
#[tokio::test]
async fn test_empty_turn_reminder_is_noop() {
    let mut runner = make_runner(
        MockProvider::text_only("ok"),
        ToolRegistry::new(),
        auto_bypass(),
    );
    let mut conv = Conversation::new();
    conv.add_user_message("hello");
    let (tx, _rx) = mpsc::unbounded_channel();

    // Empty reminder — should work exactly like run()
    runner
        .run_with_filter(&mut conv, "system", "", &tx, CancellationToken::new(), None)
        .await;

    // Should have completed normally
    assert!(conv.messages.len() >= 2); // user + assistant
}

/// ToolRegistry should return definitions in stable (sorted) order.
#[tokio::test]
async fn test_tool_registry_stable_order() {
    let registry = ToolRegistry::new();
    // Register in reverse alphabetical order
    registry.register(Box::new(EchoTool { name: "write_file" })).await;
    registry.register(Box::new(EchoTool { name: "bash" })).await;
    registry.register(Box::new(EchoTool { name: "read_file" })).await;
    registry.register(Box::new(EchoTool { name: "grep" })).await;
    registry.register(Box::new(EchoTool { name: "edit_file" })).await;

    let defs = registry.get_definitions().await;
    let names: Vec<&str> = defs.iter().map(|d| d.name).collect();

    // BTreeMap should give alphabetical order regardless of insertion order
    assert_eq!(
        names,
        vec!["bash", "edit_file", "grep", "read_file", "write_file"]
    );

    // Call again — order must be identical
    let defs2 = registry.get_definitions().await;
    let names2: Vec<&str> = defs2.iter().map(|d| d.name).collect();
    assert_eq!(names, names2, "Tool order must be stable across calls");
}

/// UNIFIED_PROMPT should not contain tool-specific usage descriptions
/// (those belong in tool definitions, not system prompt).
#[test]
fn test_rules_no_tool_descriptions() {
    let rules = crate::config::prompt_sections::build_rules();

    // Should NOT contain tool usage descriptions (removed for token savings)
    assert!(
        !rules.contains("Search code: grep"),
        "Rules should not describe grep usage"
    );
    assert!(
        !rules.contains("Find files: glob"),
        "Rules should not describe glob usage"
    );
    assert!(
        !rules.contains("Read code: read_file"),
        "Rules should not describe read_file usage"
    );
    assert!(
        !rules.contains("Edit files: edit_file"),
        "Rules should not describe edit_file usage"
    );
    assert!(
        !rules.contains("Create files: write_file"),
        "Rules should not describe write_file usage"
    );
    assert!(
        !rules.contains("Run commands: bash"),
        "Rules should not describe bash usage"
    );

    // SHOULD still contain tool discipline rules
    assert!(
        rules.contains("Call multiple tools in ONE turn"),
        "Rules must contain batch tool call discipline"
    );
}

/// System prompt should not contain dynamic content (date, git status, etc.)
/// that would break prompt caching.
#[test]
fn test_rules_no_dynamic_content() {
    let rules = crate::config::prompt_sections::build_rules();

    assert!(!rules.contains("Date:"), "Rules should not contain date");
    assert!(
        !rules.contains("Git:"),
        "Rules should not contain git status"
    );
    assert!(
        !rules.contains("Recent activity"),
        "Rules should not contain recent activity"
    );
}

// ===========================================================================
// validate_args gate: malformed tool-call args bounce back to the model
// without prompting the user or running execute.
// ===========================================================================

#[tokio::test]
async fn malformed_write_file_args_short_circuit_without_approval() {
    use crate::tool::write::WriteFileTool;
    let mut tools = ToolRegistry::new();
    tools.register(Box::new(WriteFileTool)).await;

    // 2026-05-02 datalog `atomgr/2026-05-02_20-23-21.md` line 330:
    // provider stream truncated mid-args, closing bracket wrong, no
    // `content` field. Pre-fix, this would (a) fail json_repair, (b)
    // fall into write_file's fail-closed approval branch which prompts
    // the user, (c) the user approves, (d) execute() re-parses and
    // returns the same missing-field error. Post-fix the runner's
    // validate_args gate short-circuits to a tool-result error and
    // approval/execute are never reached.
    let bad_args = r#"{"file_path": "/tmp/x.rs"]"#;
    let provider = MockProvider::with_tool_call("write_file", bad_args);
    // Use a permission decider that PANICS if asked — proves no
    // approval round-trip happened.
    struct PanicOnApproval;
    #[async_trait]
    impl super::permission::PermissionDecider for PanicOnApproval {
        async fn decide(
            &self,
            _call: &crate::tool::ToolCall,
            _approval: &crate::tool::ApprovalRequirement,
        ) -> crate::tool::PermissionDecision {
            panic!("validate_args gate must short-circuit before approval is requested");
        }

        fn will_auto_approve(
            &self,
            _call: &crate::tool::ToolCall,
            _approval: &crate::tool::ApprovalRequirement,
        ) -> bool {
            false
        }
    }
    let mut runner = make_runner(provider, tools, Box::new(PanicOnApproval));
    let mut conv = Conversation::new();
    conv.add_user_message("write a file");
    let (tx, mut rx) = mpsc::unbounded_channel();

    let _ = runner
        .run(&mut conv, "system", &tx, CancellationToken::new())
        .await;
    drop(tx);

    let mut got_error_result = false;
    while let Some(event) = rx.recv().await {
        if let TurnEvent::ToolCallResult {
            name,
            success,
            output,
            ..
        } = event
        {
            if name == "write_file" {
                assert!(!success, "validate-fail must surface as success=false");
                assert!(
                    output.to_lowercase().contains("missing field")
                        || output.to_lowercase().contains("re-issue"),
                    "tool result must carry the structured retry hint, got: {output}"
                );
                got_error_result = true;
            }
        }
    }
    assert!(
        got_error_result,
        "validate-fail must still emit a ToolCallResult so the model can retry"
    );
}

#[test]
fn write_file_validate_args_catches_real_datalog_fixtures() {
    use crate::tool::write::WriteFileTool;
    use crate::tool::Tool as _;
    let tool = WriteFileTool;

    // 2026-05-02 datalog 10-37-51.md line 225: stream cut at `{`.
    assert!(
        tool.validate_args("{").is_err(),
        "single-brace truncation must reject"
    );
    // 2026-05-02 datalog 20-23-21.md line 330: closing `]`, no content.
    assert!(
        tool.validate_args(r#"{"file_path": "/tmp/x.rs"]"#).is_err(),
        "closing-bracket-wrong + missing field must reject"
    );
    // Empty args.
    assert!(tool.validate_args("").is_err());
    assert!(tool.validate_args("{}").is_err(), "empty object must reject");
    // Valid call passes.
    assert!(
        tool.validate_args(r#"{"file_path":"/tmp/x.rs","content":"hi"}"#)
            .is_ok()
    );
}

#[test]
fn edit_file_validate_args_rejects_missing_fields() {
    use crate::tool::edit::EditFileTool;
    use crate::tool::Tool as _;
    let tool = EditFileTool;
    assert!(tool.validate_args("{}").is_err());
    assert!(
        tool.validate_args(r#"{"file_path":"/x.rs"}"#).is_err(),
        "missing old_string + new_string must reject"
    );
    assert!(
        tool.validate_args(
            r#"{"file_path":"/x.rs","old_string":"a","new_string":"b"}"#
        )
        .is_ok()
    );
}

#[test]
fn search_replace_validate_args_rejects_missing_fields() {
    use crate::tool::search_replace::SearchReplaceTool;
    use crate::tool::Tool as _;
    let tool = SearchReplaceTool;
    assert!(tool.validate_args("{}").is_err());
    assert!(
        tool.validate_args(r#"{"search":"a","replace":"b"}"#).is_ok()
    );
}

// ===========================================================================
// Telemetry integration tests
// ===========================================================================

#[cfg(test)]
mod telemetry_tests {
    use super::*;
    use crate::tool::ToolContext;
    use atomcode_telemetry::{Event, Telemetry, ToolErrorKind};
    use std::path::PathBuf;

    /// Build a TurnRunner wired to a real in-memory Telemetry handle so we can
    /// assert on the emitted events.
    fn make_runner_with_telemetry(
        provider: MockProvider,
        tools: ToolRegistry,
    ) -> (
        TurnRunner,
        std::sync::Arc<tokio::sync::Mutex<Vec<atomcode_telemetry::Record>>>,
    ) {
        let (tel, captured) = Telemetry::in_memory("test".into());
        let ctx = ToolContext::with_telemetry(PathBuf::from("/tmp/test"), "session-1", tel);

        let test_provider_cfg = crate::config::provider::ProviderConfig {
            provider_type: "test".into(),
            api_key: None,
            model: "test-model".into(),
            base_url: None,
            system_prompt: None,
            user_agent: None,
            context_window: 128_000,
            max_tokens: None,
            thinking_type: None,
            thinking_keep: None,
            reasoning_history: None,
            thinking_enabled: None,
            thinking_budget: None,
            skip_tls_verify: false,
            ephemeral: true,

};
        let test_ctx: std::sync::Arc<dyn crate::ctx::CtxBuilder> =
            std::sync::Arc::new(crate::ctx::DefaultCtx::new(&test_provider_cfg));

        let runner = TurnRunner {
            provider: std::sync::Arc::new(provider),
            tools: std::sync::Arc::new(tools),
            context: ctx,
            config: test_config(),
            ctx: test_ctx,
            permission: Box::new(AutoPermissionDecider::new(AutoPermissionMode::BypassAll)),
            recently_edited_files: Vec::new(),
            hook_executor: std::sync::Arc::new(
                crate::hook::executor::HookExecutor::empty()
            ),
            loop_guard: Default::default(),
        };
        (runner, captured)
    }

    #[tokio::test]
    async fn turn_emits_exactly_one_llm_chat_for_text_only_turn() {
        let (mut runner, captured) =
            make_runner_with_telemetry(MockProvider::text_only("Hello"), ToolRegistry::new());
        let mut conv = Conversation::new();
        conv.add_user_message("Hi");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        // Give the background task a moment to drain the channel.
        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let llm_chats: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::LlmChat { .. }))
            .collect();

        assert_eq!(
            llm_chats.len(),
            1,
            "expected exactly one LlmChat per turn, got {}",
            llm_chats.len()
        );

        // turn_id must be populated by the scope in run_with_filter.
        assert!(
            llm_chats[0].envelope.turn_id.is_some(),
            "LlmChat envelope must carry a turn_id"
        );

        // Basic payload sanity.
        if let Event::LlmChat {
            tool_calls_count,
            had_error,
            output_tokens,
            ..
        } = llm_chats[0].event
        {
            assert_eq!(tool_calls_count, 0, "text-only turn has no tool calls");
            assert!(!had_error, "successful turn must not set had_error");
            assert!(
                output_tokens > 0,
                "output_tokens should be non-zero (usage reported by mock)"
            );
        }
    }

    #[tokio::test]
    async fn turn_emits_llm_chat_with_tool_calls_count() {
        let tools = ToolRegistry::new();
        tools.register(Box::new(EchoTool { name: "echo" })).await;

        let (mut runner, captured) = make_runner_with_telemetry(
            MockProvider::with_tool_call("echo", r#"{"msg":"hi"}"#),
            tools,
        );
        let mut conv = Conversation::new();
        conv.add_user_message("Use echo");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let llm_chats: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::LlmChat { .. }))
            .collect();

        assert_eq!(llm_chats.len(), 1, "expected one LlmChat");

        if let Event::LlmChat {
            tool_calls_count,
            had_error,
            ..
        } = llm_chats[0].event
        {
            assert_eq!(tool_calls_count, 1, "tool turn should report 1 tool call");
            assert!(!had_error);
        }
    }

    #[tokio::test]
    async fn turn_emits_llm_chat_with_had_error_on_failure() {
        let (mut runner, captured) = make_runner_with_telemetry(
            MockProvider::with_error("provider blew up"),
            ToolRegistry::new(),
        );
        let mut conv = Conversation::new();
        conv.add_user_message("Hi");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let llm_chats: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::LlmChat { .. }))
            .collect();

        assert_eq!(llm_chats.len(), 1, "even failed turns emit one LlmChat");
        if let Event::LlmChat { had_error, .. } = llm_chats[0].event {
            assert!(had_error, "failed turn must set had_error=true");
        }
    }

    /// A mock tool that always fails (simulates a command that exits non-zero).
    struct FailingTool;

    #[async_trait]
    impl Tool for FailingTool {
        fn definition(&self) -> ToolDef {
            ToolDef {
                name: "bash",
                description: "Always-failing bash mock".to_string(),
                parameters: serde_json::json!({"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}),
            }
        }
        fn approval(&self, _args: &str) -> ApprovalRequirement {
            ApprovalRequirement::AutoApprove
        }
        async fn execute(&self, _args: &str, _ctx: &ToolContext) -> Result<ToolResult> {
            Ok(ToolResult {
                call_id: String::new(),
                output: "[elapsed: 0.0s, exit: 1]\ncat: /nonexistent_file.txt: No such file or directory\n\n[IMPORTANT: Command failed. Read the error above and fix the root cause. Do NOT retry the same command.]".to_string(),
                success: false,
            })
        }
    }

    /// A mock tool that succeeds but produces stderr (simulates rm on nonexistent file).
    struct WarningTool;

    #[async_trait]
    impl Tool for WarningTool {
        fn definition(&self) -> ToolDef {
            ToolDef {
                name: "bash",
                description: "Warning bash mock (exit 0 + stderr)".to_string(),
                parameters: serde_json::json!({"type": "object", "properties": {"command": {"type": "string"}}, "required": ["command"]}),
            }
        }
        fn approval(&self, _args: &str) -> ApprovalRequirement {
            ApprovalRequirement::AutoApprove
        }
        async fn execute(&self, _args: &str, _ctx: &ToolContext) -> Result<ToolResult> {
            Ok(ToolResult {
                call_id: String::new(),
                output: "[elapsed: 0.0s, exit: 0]\nSTDERR:\nrm: /tmp/test.txt: No such file or directory".to_string(),
                success: true,
            })
        }
    }

    #[tokio::test]
    async fn tool_call_failure_emits_execution_failed_error_kind() {
        let tools = {
            let mut t = ToolRegistry::new();
            t.register(Box::new(FailingTool)).await;
            t
        };

        let (mut runner, captured) = make_runner_with_telemetry(
            MockProvider::with_tool_call("bash", r#"{"command":"cat /nonexistent_file.txt"}"#),
            tools,
        );
        let mut conv = Conversation::new();
        conv.add_user_message("cat a missing file");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let tool_calls: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::ToolCall { .. }))
            .collect();

        assert_eq!(tool_calls.len(), 1, "expected one ToolCall event, got {}", tool_calls.len());

        if let Event::ToolCall { name, success, error_kind, error_data, .. } = &tool_calls[0].event {
            assert_eq!(name, "bash");
            assert!(!success, "ToolCall.success must be false for failing tool");
            assert!(error_kind.is_some(), "error_kind must be Some for failing tool, got None");
            assert_eq!(error_kind.unwrap(), ToolErrorKind::ExecutionFailed,
                "error_kind must be ExecutionFailed for failing tool");

            assert!(error_data.is_some(), "error_data must be Some for failing tool, got None");
            let ed: serde_json::Value = serde_json::from_str(error_data.as_ref().unwrap()).unwrap();
            assert_eq!(ed["reason"], "Tool execution returned an error");
            assert!(ed["output_tail"].as_str().unwrap().contains("No such file"),
                "error_data.output_tail must contain the stderr, got: {}", ed["output_tail"]);
        } else {
            panic!("Expected ToolCall event");
        }
    }

    #[tokio::test]
    async fn tool_call_warning_with_stderr_emits_warning_error_kind() {
        let tools = {
            let mut t = ToolRegistry::new();
            t.register(Box::new(WarningTool)).await;
            t
        };

        let (mut runner, captured) = make_runner_with_telemetry(
            MockProvider::with_tool_call("bash", r#"{"command":"rm -rf /tmp/test.txt"}"#),
            tools,
        );
        let mut conv = Conversation::new();
        conv.add_user_message("rm a missing file");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let tool_calls: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::ToolCall { .. }))
            .collect();

        assert_eq!(tool_calls.len(), 1, "expected one ToolCall event, got {}", tool_calls.len());

        if let Event::ToolCall { name, success, error_kind, error_data, .. } = &tool_calls[0].event {
            assert_eq!(name, "bash");
            assert!(success, "ToolCall.success must be true for warning tool (exit 0)");
            assert!(error_kind.is_some(), "error_kind must be Some for warning tool, got None");
            assert_eq!(error_kind.unwrap(), ToolErrorKind::Warning,
                "error_kind must be Warning when exit 0 + stderr");

            assert!(error_data.is_some(), "error_data must be Some for warning tool, got None");
            let ed: serde_json::Value = serde_json::from_str(error_data.as_ref().unwrap()).unwrap();
            assert_eq!(ed["reason"], "Command succeeded (exit 0) but produced stderr output");
            assert!(ed.get("resolution").is_some(), "warning error_data must contain resolution");
        } else {
            panic!("Expected ToolCall event");
        }
    }

    #[tokio::test]
    async fn tool_call_success_without_stderr_emits_no_error_fields() {
        let tools = {
            let mut t = ToolRegistry::new();
            t.register(Box::new(EchoTool { name: "bash" })).await;
            t
        };

        let (mut runner, captured) = make_runner_with_telemetry(
            MockProvider::with_tool_call("bash", r#"{"command":"echo hello"}"#),
            tools,
        );
        let mut conv = Conversation::new();
        conv.add_user_message("say hello");
        let (tx, _rx) = mpsc::unbounded_channel();

        runner
            .run(&mut conv, "system", &tx, CancellationToken::new())
            .await;

        tokio::time::sleep(std::time::Duration::from_millis(50)).await;

        let events = captured.lock().await;
        let tool_calls: Vec<_> = events
            .iter()
            .filter(|r| matches!(r.event, Event::ToolCall { .. }))
            .collect();

        assert_eq!(tool_calls.len(), 1, "expected one ToolCall event, got {}", tool_calls.len());

        if let Event::ToolCall { name, success, error_kind, error_data, .. } = &tool_calls[0].event {
            assert_eq!(name, "bash");
            assert!(success, "ToolCall.success must be true");
            assert!(error_kind.is_none(), "error_kind must be None for successful tool without stderr, got Some");
            assert!(error_data.is_none(), "error_data must be None for successful tool without stderr, got Some");
        } else {
            panic!("Expected ToolCall event");
        }
    }
}

// ===========================================================================
// SubAgentTask integration tests (Task 9: resilience layer + 7 end-to-end)
// ===========================================================================

#[tokio::test]
async fn sub_agent_normal_path_completes_one_turn() {
    use crate::agent::sub_agent::SubAgentTask;
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("test.rs");
    std::fs::write(&path, "foo\n").unwrap();
    let path_str = path.to_string_lossy().to_string();
    let edit_args = format!(
        r#"{{"file_path":"{}","old_string":"foo","new_string":"bar"}}"#,
        path_str
    );

    let provider = Arc::new(SequencedMockProvider::new(vec![
        tool_call_events("c1", "edit_file", &edit_args),
        text_only_events("Done."),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "foo".into(),
        task_instruction: "Replace foo with bar".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(
            provider as Arc<dyn LlmProvider>,
            tools,
            &test_config(),
            tmp.path(),
            12,
        )
        .await;

    assert!(result.success, "expected success, got: {:?}", result.failures);
    assert!(
        result.diagnostic.edited_files.iter().any(|f| f.contains("test.rs")),
        "expected edit recorded in diagnostic"
    );
}

#[tokio::test]
async fn sub_agent_hallucinating_mock_breaks_after_nudge_unheeded() {
    use crate::agent::sub_agent::{SubAgentFailure, SubAgentTask};
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("halluc.rs");
    std::fs::write(&path, "stub\n").unwrap();
    let path_str = path.to_string_lossy().to_string();
    let read_args = format!(r#"{{"file_path":"{}"}}"#, path_str);

    let provider = Arc::new(SequencedMockProvider::new(vec![
        tool_call_events("c1", "read_file", &read_args),
        tool_call_events("c2", "read_file", &read_args),
        tool_call_events("c3", "read_file", &read_args),
        tool_call_events("c4", "read_file", &read_args),
        tool_call_events("c5", "read_file", &read_args),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "stub".into(),
        task_instruction: "Make changes".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(provider, tools, &test_config(), tmp.path(), 12)
        .await;

    assert!(!result.success);
    assert!(
        result.failures.iter().any(|f| matches!(
            f,
            SubAgentFailure::NoProgress { .. }
                | SubAgentFailure::HallucinationLoop { .. }
                | SubAgentFailure::BudgetExhaustedNoEdits
        )),
        "expected NoProgress, HallucinationLoop, or BudgetExhaustedNoEdits, got: {:?}",
        result.failures
    );
    assert!(
        result.diagnostic.hallucination_nudges_sent >= 1,
        "expected at least one nudge to fire"
    );
}

#[tokio::test]
async fn sub_agent_recovers_from_first_timeout_then_succeeds() {
    use crate::agent::sub_agent::SubAgentTask;
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("recover.rs");
    std::fs::write(&path, "x\n").unwrap();
    let path_str = path.to_string_lossy().to_string();
    let edit_args = format!(
        r#"{{"file_path":"{}","old_string":"x","new_string":"y"}}"#,
        path_str
    );

    let provider = Arc::new(SequencedMockProvider::new(vec![
        error_events("stream timeout after 60s"),
        tool_call_events("c1", "edit_file", &edit_args),
        text_only_events("Done."),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "x".into(),
        task_instruction: "Replace x with y".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(provider, tools, &test_config(), tmp.path(), 12)
        .await;

    assert!(result.success, "retry should recover; got failures: {:?}", result.failures);
    assert_eq!(result.diagnostic.timeouts, 1, "exactly one timeout retry");
}

#[tokio::test]
async fn sub_agent_provider_hard_error_breaks_immediately_no_retry() {
    use crate::agent::sub_agent::{SubAgentFailure, SubAgentTask};
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("h.rs");
    std::fs::write(&path, "x").unwrap();
    let path_str = path.to_string_lossy().to_string();

    let provider = Arc::new(SequencedMockProvider::new(vec![
        error_events("401 Unauthorized"),
        text_only_events("would-be retry"),  // never reached if no-retry works
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "x".into(),
        task_instruction: "".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(provider, tools, &test_config(), tmp.path(), 12)
        .await;

    assert!(!result.success);
    assert!(
        result.failures.iter().any(|f| matches!(f, SubAgentFailure::ProviderError(_))),
        "expected ProviderError, got: {:?}",
        result.failures
    );
    assert_eq!(result.diagnostic.timeouts, 0, "non-timeout errors must not retry");
}

#[tokio::test]
async fn sub_agent_blocked_tool_redirects_via_validate_args() {
    use crate::agent::sub_agent::SubAgentTask;
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("sand.rs");
    std::fs::write(&path, "a\n").unwrap();
    let path_str = path.to_string_lossy().to_string();
    let edit_args = format!(
        r#"{{"file_path":"{}","old_string":"a","new_string":"b"}}"#,
        path_str
    );

    // Turn 0: try bash (blocked by sandbox).
    // Turn 1: receive "tool not available" → fall through to edit_file.
    // Turn 2: done.
    let provider = Arc::new(SequencedMockProvider::new(vec![
        tool_call_events("c1", "bash", r#"{"command":"ls"}"#),
        tool_call_events("c2", "edit_file", &edit_args),
        text_only_events("done"),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "a".into(),
        task_instruction: "".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(provider, tools, &test_config(), tmp.path(), 12)
        .await;

    // Bash was attempted but should not have run (filtered out of registry).
    // Sandbox routed back, edit succeeded on turn 1.
    assert!(result.success, "model recovered after sandbox redirect");
    assert!(!result.diagnostic.edited_files.is_empty());
}

#[tokio::test]
async fn sub_agent_failed_edit_doesnt_burn_progress_signal() {
    use crate::agent::sub_agent::{SubAgentFailure, SubAgentTask};
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let path = tmp.path().join("fail.rs");
    std::fs::write(&path, "actual content\n").unwrap();
    let path_str = path.to_string_lossy().to_string();
    let bad_args = format!(
        r#"{{"file_path":"{}","old_string":"NOT_THERE","new_string":"y"}}"#,
        path_str
    );

    // 5 edit_file calls all with old_string that won't match.
    let provider = Arc::new(SequencedMockProvider::new(vec![
        tool_call_events("c1", "edit_file", &bad_args),
        tool_call_events("c2", "edit_file", &bad_args),
        tool_call_events("c3", "edit_file", &bad_args),
        tool_call_events("c4", "edit_file", &bad_args),
        tool_call_events("c5", "edit_file", &bad_args),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        Arc::new(tools)
    };

    let task = SubAgentTask {
        file_path: path_str,
        file_content: "actual content".into(),
        task_instruction: "".into(),
        contract: "".into(),
        sibling_skeletons: "".into(),
    };

    let result = task
        .execute(provider, tools, &test_config(), tmp.path(), 12)
        .await;

    assert!(!result.success, "no successful edit should land");
    assert!(
        result.failures.iter().any(|f| matches!(
            f,
            SubAgentFailure::NoProgress { .. } | SubAgentFailure::BudgetExhaustedNoEdits
        )),
        "expected NoProgress or BudgetExhausted, got: {:?}",
        result.failures
    );
    assert!(
        result.diagnostic.edited_files.is_empty(),
        "no successful edit means edited_files stays empty"
    );
}

#[tokio::test]
async fn sub_agent_pool_one_failure_doesnt_affect_others() {
    use crate::agent::sub_agent::{SubAgentPool, SubAgentTask};
    use std::sync::Arc;

    let tmp = tempfile::tempdir().unwrap();
    let good_path = tmp.path().join("good.rs");
    let bad_path = tmp.path().join("bad.rs");
    std::fs::write(&good_path, "x\n").unwrap();
    std::fs::write(&bad_path, "y\n").unwrap();
    let good_path_str = good_path.to_string_lossy().to_string();
    let bad_path_str = bad_path.to_string_lossy().to_string();

    let edit_args = format!(
        r#"{{"file_path":"{}","old_string":"x","new_string":"z"}}"#,
        good_path_str
    );

    // max_concurrent=1 forces serial: task A first (succeeds), task B second (401).
    let provider = Arc::new(SequencedMockProvider::new(vec![
        // task A: succeeds
        tool_call_events("a1", "edit_file", &edit_args),
        text_only_events("done"),
        // task B: 401 hard error
        error_events("401 Unauthorized"),
    ]));

    let tools = {
        let mut tools = ToolRegistry::new();
        tools.register(Box::new(crate::tool::edit::EditFileTool)).await;
        tools.register(Box::new(crate::tool::read::ReadFileTool)).await;
        Arc::new(tools)
    };

    let pool = SubAgentPool {
        tasks: vec![
            SubAgentTask {
                file_path: good_path_str,
                file_content: "x".into(),
                task_instruction: "".into(),
                contract: "".into(),
                sibling_skeletons: "".into(),
            },
            SubAgentTask {
                file_path: bad_path_str,
                file_content: "y".into(),
                task_instruction: "".into(),
                contract: "".into(),
                sibling_skeletons: "".into(),
            },
        ],
        max_concurrent: 1, // Force serial so the sequence is deterministic
        timeout_secs: 60,
    };

    let (event_tx, _event_rx) = mpsc::unbounded_channel();
    let results = pool.execute_all(provider, tools, &test_config(), tmp.path(), &event_tx).await;

    assert_eq!(results.len(), 2);
    let succeeded = results.iter().filter(|r| r.success).count();
    let failed = results.iter().filter(|r| !r.success).count();
    assert_eq!(succeeded, 1, "exactly one task should succeed");
    assert_eq!(failed, 1, "exactly one task should fail");
}