vtcode 0.99.1

A Rust-based terminal coding agent with modular architecture supporting multiple LLM providers
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
use super::{
    CompactionContext, CompactionState, GroundedFactRecord, SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION,
    SessionMemoryEnvelope, build_server_compaction_context_management,
    build_summarized_fork_history, compact_history_for_recovery_in_place,
    compact_history_from_index_in_place, compact_history_in_place,
    compact_history_in_place_with_events, inject_latest_memory_envelope,
    latest_memory_envelope_path_for_session, manual_openai_compact_history_in_place,
    maybe_auto_compact_history, resolve_compaction_threshold,
};
use crate::agent::runloop::unified::context_manager::ContextManager;
use crate::agent::runloop::unified::inline_events::harness::HarnessEventEmitter;
use crate::agent::runloop::unified::state::SessionStats;
use async_trait::async_trait;
use hashbrown::HashMap;
use serde_json::json;
use std::fs;
use std::sync::Arc;
use tempfile::tempdir;
use tokio::sync::RwLock;
use vtcode_commons::llm::Usage;
use vtcode_core::config::constants::tools as tool_names;
use vtcode_core::config::loader::VTCodeConfig;
use vtcode_core::llm::provider::{
    LLMError, LLMProvider, LLMRequest, LLMResponse, Message, MessageRole,
    ResponsesCompactionOptions, ToolCall,
};

struct LocalCompactionProvider;

struct ProviderCompactionProvider;

struct NoOpProviderCompactionProvider;

struct FailingProviderCompactionProvider;

struct RecordingProviderCompactionProvider {
    seen_history: Arc<RwLock<Vec<Message>>>,
}

#[async_trait]
impl LLMProvider for LocalCompactionProvider {
    fn name(&self) -> &str {
        "stub"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        Ok(LLMResponse::new("stub-model", "summary"))
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["stub-model".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }

    fn effective_context_size(&self, _model: &str) -> usize {
        1_000
    }
}

#[async_trait]
impl LLMProvider for ProviderCompactionProvider {
    fn name(&self) -> &str {
        "provider-stub"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        Ok(LLMResponse::new("stub-model", "summary"))
    }

    async fn compact_history(
        &self,
        _model: &str,
        history: &[Message],
    ) -> Result<Vec<Message>, LLMError> {
        let mut compacted = Vec::new();
        compacted.push(Message::system(
            "Previous conversation summary:\nProvider compacted history".to_string(),
        ));
        compacted.extend(history.iter().rev().take(2).cloned().collect::<Vec<_>>());
        compacted.reverse();
        Ok(compacted)
    }

    async fn compact_history_with_options(
        &self,
        model: &str,
        history: &[Message],
        _options: &ResponsesCompactionOptions,
    ) -> Result<Vec<Message>, LLMError> {
        self.compact_history(model, history).await
    }

    fn supports_responses_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supports_manual_openai_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["stub-model".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }

    fn effective_context_size(&self, _model: &str) -> usize {
        1_000
    }
}

#[async_trait]
impl LLMProvider for NoOpProviderCompactionProvider {
    fn name(&self) -> &str {
        "noop-provider-stub"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        Ok(LLMResponse::new("stub-model", "summary"))
    }

    async fn compact_history(
        &self,
        _model: &str,
        history: &[Message],
    ) -> Result<Vec<Message>, LLMError> {
        Ok(history.to_vec())
    }

    async fn compact_history_with_options(
        &self,
        _model: &str,
        history: &[Message],
        _options: &ResponsesCompactionOptions,
    ) -> Result<Vec<Message>, LLMError> {
        Ok(history.to_vec())
    }

    fn supports_responses_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supports_manual_openai_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["stub-model".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }

    fn effective_context_size(&self, _model: &str) -> usize {
        1_000
    }
}

#[async_trait]
impl LLMProvider for FailingProviderCompactionProvider {
    fn name(&self) -> &str {
        "failing-provider-stub"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        Ok(LLMResponse::new("stub-model", "summary"))
    }

    async fn compact_history(
        &self,
        _model: &str,
        _history: &[Message],
    ) -> Result<Vec<Message>, LLMError> {
        Err(LLMError::Provider {
            message: "provider compaction failed".to_string(),
            metadata: None,
        })
    }

    fn supports_responses_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["stub-model".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }

    fn effective_context_size(&self, _model: &str) -> usize {
        1_000
    }
}

#[async_trait]
impl LLMProvider for RecordingProviderCompactionProvider {
    fn name(&self) -> &str {
        "recording-provider-stub"
    }

    async fn generate(&self, _request: LLMRequest) -> Result<LLMResponse, LLMError> {
        Ok(LLMResponse::new("stub-model", "summary"))
    }

    async fn compact_history(
        &self,
        _model: &str,
        history: &[Message],
    ) -> Result<Vec<Message>, LLMError> {
        *self.seen_history.write().await = history.to_vec();
        Ok(history.to_vec())
    }

    async fn compact_history_with_options(
        &self,
        _model: &str,
        history: &[Message],
        _options: &ResponsesCompactionOptions,
    ) -> Result<Vec<Message>, LLMError> {
        self.compact_history("stub-model", history).await
    }

    fn supports_responses_compaction(&self, _model: &str) -> bool {
        true
    }

    fn supported_models(&self) -> Vec<String> {
        vec!["stub-model".to_string()]
    }

    fn validate_request(&self, _request: &LLMRequest) -> Result<(), LLMError> {
        Ok(())
    }

    fn effective_context_size(&self, _model: &str) -> usize {
        1_000
    }
}

fn test_history() -> Vec<Message> {
    vec![
        Message::user("message-0".to_string()),
        Message::assistant("assistant-0".to_string()),
        Message::tool_response("call-0".to_string(), "tool-0".to_string()),
        Message::user("message-1".to_string()),
        Message::assistant("assistant-1".to_string()),
        Message::tool_response("call-1".to_string(), "tool-1".to_string()),
        Message::user("message-2".to_string()),
        Message::assistant("assistant-2".to_string()),
        Message::tool_response("call-2".to_string(), "tool-2".to_string()),
        Message::user("message-3".to_string()),
        Message::assistant("assistant-3".to_string()),
        Message::tool_response("call-3".to_string(), "tool-3".to_string()),
    ]
}

fn test_history_with_memory_envelope() -> Vec<Message> {
    let mut history = vec![Message::system(
        "[Session Memory Envelope]\nSummary:\nExisting summary".to_string(),
    )];
    history.extend(test_history());
    history
}

fn assert_local_compaction_history(history: &[Message], envelope_index: usize) {
    assert_local_compaction_history_with_user_count(history, envelope_index, 4);
}

fn assert_local_compaction_history_with_user_count(
    history: &[Message],
    envelope_index: usize,
    retained_user_messages: usize,
) {
    assert_eq!(history.len(), retained_user_messages + 2);
    assert!(
        history[envelope_index]
            .content
            .as_text()
            .contains("[Session Memory Envelope]")
    );
    assert_eq!(
        history.len(),
        history
            .iter()
            .filter(|message| {
                message.role == MessageRole::System || message.role == MessageRole::User
            })
            .count()
    );
    assert!(history.iter().any(|message| {
        message.role == MessageRole::System
            && message
                .content
                .as_text()
                .contains("Previous conversation summary")
    }));
    assert_eq!(
        history
            .iter()
            .filter(|message| message.role == MessageRole::User)
            .count(),
        retained_user_messages
    );
}

fn read_file_tool_call(id: &str, path: &str) -> ToolCall {
    ToolCall::function(
        id.to_string(),
        tool_names::READ_FILE.to_string(),
        json!({ "path": path }).to_string(),
    )
}

fn unified_file_read_tool_call(id: &str, path: &str) -> ToolCall {
    ToolCall::function(
        id.to_string(),
        tool_names::UNIFIED_FILE.to_string(),
        json!({ "action": "read", "path": path }).to_string(),
    )
}

fn assistant_with_tool_call(tool_call: ToolCall) -> Message {
    let mut message = Message::assistant(String::new());
    message.tool_calls = Some(vec![tool_call]);
    message
}

fn test_context_manager() -> ContextManager {
    ContextManager::new(
        "You are VT Code.".to_string(),
        (),
        std::sync::Arc::new(RwLock::new(HashMap::new())),
        None,
    )
}

#[tokio::test]
async fn manual_compaction_succeeds_without_server_side_support() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    session_stats.set_previous_response_chain("stub", "stub-model", Some("resp_123"), &[]);
    let mut context_manager = test_context_manager();
    context_manager.update_token_usage(&Some(Usage {
        prompt_tokens: 900,
        completion_tokens: 10,
        total_tokens: 910,
        ..Usage::default()
    }));

    let outcome = compact_history_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &mut history,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("manual compaction succeeds")
    .expect("history should compact");

    assert_eq!(outcome.original_len, 12);
    assert_eq!(outcome.compacted_len, 5);
    assert_local_compaction_history(&history, 0);
    assert_eq!(
        session_stats.previous_response_id_for("stub", "stub-model"),
        None
    );
    assert!(context_manager.current_token_usage() < 900);
    assert!(latest_memory_envelope_path_for_session(temp.path(), "session-alpha").is_some());
}

#[tokio::test]
async fn manual_compaction_emits_local_compaction_boundary_event() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let harness_path = temp.path().join("harness.jsonl");
    let harness_emitter = HarnessEventEmitter::new(harness_path.clone()).expect("emitter");
    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_in_place_with_events(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            Some(&harness_emitter),
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        vtcode_core::exec::events::CompactionTrigger::Manual,
    )
    .await
    .expect("compaction succeeds")
    .expect("history should compact");

    assert_eq!(
        outcome.mode,
        vtcode_core::exec::events::CompactionMode::Local
    );
    let content = fs::read_to_string(harness_path).expect("read harness log");
    assert!(content.contains("\"type\":\"thread.compact_boundary\""));
    assert!(content.contains("\"mode\":\"local\""));
}

#[tokio::test]
async fn provider_compaction_emits_provider_boundary_event() {
    let temp = tempdir().expect("tempdir");
    let provider = ProviderCompactionProvider;
    let harness_path = temp.path().join("provider-harness.jsonl");
    let harness_emitter = HarnessEventEmitter::new(harness_path.clone()).expect("emitter");
    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_in_place_with_events(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            Some(&harness_emitter),
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        vtcode_core::exec::events::CompactionTrigger::Manual,
    )
    .await
    .expect("compaction succeeds")
    .expect("history should compact");

    assert_eq!(
        outcome.mode,
        vtcode_core::exec::events::CompactionMode::Provider
    );
    let content = fs::read_to_string(harness_path).expect("read harness log");
    assert!(content.contains("\"type\":\"thread.compact_boundary\""));
    assert!(content.contains("\"mode\":\"provider\""));
}

#[tokio::test]
async fn manual_openai_compaction_clears_previous_response_chain() {
    let temp = tempdir().expect("tempdir");
    let provider = ProviderCompactionProvider;
    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    session_stats.set_previous_response_chain("provider-stub", "stub-model", Some("resp_123"), &[]);
    let mut context_manager = test_context_manager();

    let outcome = manual_openai_compact_history_in_place(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        &ResponsesCompactionOptions::default(),
    )
    .await
    .expect("manual OpenAI compaction succeeds")
    .expect("history should compact");

    assert_eq!(
        outcome.mode,
        vtcode_core::exec::events::CompactionMode::Provider
    );
    assert_eq!(
        session_stats.previous_response_id_for("provider-stub", "stub-model"),
        None
    );
}

#[tokio::test]
async fn manual_openai_compaction_rejects_unsupported_provider_without_local_fallback() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut history = test_history();
    let original_history = history.clone();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let err = manual_openai_compact_history_in_place(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        &ResponsesCompactionOptions::default(),
    )
    .await
    .expect_err("unsupported provider should fail");

    assert!(err.to_string().contains(
        "Manual `/compact` is available only for the native OpenAI provider on api.openai.com"
    ));
    assert_eq!(history, original_history);
}

#[tokio::test]
async fn manual_openai_compaction_noop_preserves_existing_history() {
    let temp = tempdir().expect("tempdir");
    let provider = NoOpProviderCompactionProvider;
    let mut history = test_history_with_memory_envelope();
    let original_history = history.clone();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = manual_openai_compact_history_in_place(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        &ResponsesCompactionOptions::default(),
    )
    .await
    .expect("noop compaction succeeds");

    assert!(outcome.is_none());
    assert_eq!(history, original_history);
}

#[tokio::test]
async fn provider_compaction_noop_preserves_existing_history() {
    let temp = tempdir().expect("tempdir");
    let provider = NoOpProviderCompactionProvider;
    let mut history = test_history_with_memory_envelope();
    let original_history = history.clone();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_in_place_with_events(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        vtcode_core::exec::events::CompactionTrigger::Manual,
    )
    .await
    .expect("noop compaction succeeds");

    assert!(outcome.is_none());
    assert_eq!(history, original_history);
}

#[tokio::test]
async fn provider_compaction_preserves_original_repeated_file_reads() {
    let temp = tempdir().expect("tempdir");
    let seen_history = Arc::new(RwLock::new(Vec::new()));
    let provider = RecordingProviderCompactionProvider {
        seen_history: Arc::clone(&seen_history),
    };
    let mut history = vec![
        assistant_with_tool_call(read_file_tool_call("call-1", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-1".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "older contents"
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
        assistant_with_tool_call(read_file_tool_call("call-2", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-2".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "newer contents"
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
    ];
    history.extend(test_history());
    let original_history = history.clone();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_in_place_with_events(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        vtcode_core::exec::events::CompactionTrigger::Manual,
    )
    .await
    .expect("provider compaction succeeds");

    assert!(outcome.is_none());
    assert_eq!(history, original_history);

    let seen = seen_history.read().await.clone();
    assert_eq!(seen.len(), original_history.len());
    assert!(seen[1].content.as_text().contains("older contents"));
    assert!(!seen[1].content.as_text().contains("deduped_read"));
}

#[test]
fn dedup_repeated_file_reads_rewrites_only_older_exact_matches() {
    let history = vec![
        assistant_with_tool_call(read_file_tool_call("call-1", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-1".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "older contents"
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
        assistant_with_tool_call(unified_file_read_tool_call("call-2", "src/lib.rs")),
        Message::tool_response(
            "call-2".to_string(),
            json!({
                "path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "newer contents"
            })
            .to_string(),
        ),
    ];

    let deduped = super::dedup_repeated_file_reads_for_local_compaction(&history);

    let older_payload: serde_json::Value =
        serde_json::from_str(deduped[1].content.as_text().as_ref()).expect("json payload");
    assert_eq!(
        older_payload
            .get("deduped_read")
            .and_then(serde_json::Value::as_bool),
        Some(true)
    );
    assert_eq!(
        older_payload
            .get("note")
            .and_then(serde_json::Value::as_str),
        Some(super::DEDUPED_FILE_READ_NOTE)
    );
    assert_eq!(
        older_payload
            .get("file_path")
            .and_then(serde_json::Value::as_str),
        Some("src/lib.rs")
    );
    assert!(deduped[3].content.as_text().contains("newer contents"));
    assert!(!deduped[3].content.as_text().contains("deduped_read"));
}

#[test]
fn dedup_repeated_file_reads_keeps_different_slices_and_chunked_reads() {
    let different_slice_history = vec![
        assistant_with_tool_call(read_file_tool_call("call-1", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-1".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 20,
                "result": "slice one"
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
        assistant_with_tool_call(read_file_tool_call("call-2", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-2".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 21,
                "end_line": 40,
                "result": "slice two"
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
    ];
    let chunked_history = vec![
        assistant_with_tool_call(read_file_tool_call("call-3", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-3".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "first chunk",
                "spool_chunked": true,
                "has_more": true
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
        assistant_with_tool_call(read_file_tool_call("call-4", "src/lib.rs")),
        Message::tool_response_with_origin(
            "call-4".to_string(),
            json!({
                "file_path": "src/lib.rs",
                "start_line": 1,
                "end_line": 40,
                "result": "second chunk",
                "spool_chunked": true,
                "has_more": false
            })
            .to_string(),
            tool_names::READ_FILE.to_string(),
        ),
    ];

    assert_eq!(
        super::dedup_repeated_file_reads_for_local_compaction(&different_slice_history),
        different_slice_history
    );
    assert_eq!(
        super::dedup_repeated_file_reads_for_local_compaction(&chunked_history),
        chunked_history
    );
}

#[test]
fn recovery_context_previews_include_latest_user_request_and_recent_distinct_tool_outputs() {
    let history = vec![
        Message::user("first request".to_string()),
        Message::tool_response("call-1".to_string(), "duplicate output".to_string()),
        Message::tool_response("call-2".to_string(), "distinct output".to_string()),
        Message::tool_response("call-3".to_string(), "duplicate output".to_string()),
        Message::user("latest request".to_string()),
    ];

    let previews = super::build_recovery_context_previews_with_workspace(&history, None);

    assert_eq!(previews[0], "Latest user request: latest request");
    assert_eq!(previews[1], "Tool output 1: duplicate output");
    assert_eq!(previews[2], "Tool output 2: distinct output");
    assert_eq!(previews.len(), 3);
}

#[test]
fn recovery_context_previews_fall_back_to_latest_assistant_text_when_needed() {
    let history = vec![Message::assistant("assistant summary".to_string())];

    let previews = super::build_recovery_context_previews_with_workspace(&history, None);

    assert_eq!(previews, vec!["Latest assistant text: assistant summary"]);
}

#[test]
fn recovery_context_previews_extract_structured_tool_guidance() {
    let history = vec![
        Message::user("use structured search".to_string()),
        Message::tool_response(
            "call-1".to_string(),
            json!({
                "backend": "ast-grep",
                "matches": [],
                "path": "src/agent",
                "is_recoverable": true,
                "hint": "Pattern looks like a code fragment.",
                "next_action": "Retry with a larger parseable pattern.",
                "fallback_tool": "unified_search",
                "fallback_tool_args": {"action": "structural", "path": "src/agent"}
            })
            .to_string(),
        ),
    ];

    let previews = super::build_recovery_context_previews_with_workspace(&history, None);

    assert_eq!(previews[0], "Latest user request: use structured search");
    assert!(previews[1].contains("No matches found in src/agent"));
    assert!(previews[1].contains("Pattern looks like a code fragment."));
    assert!(previews[1].contains("Next action: Retry with a larger parseable pattern."));
    assert!(previews[1].contains("Fallback tool: unified_search"));
}

#[test]
fn recovery_context_previews_extract_nested_error_guidance_and_spool_excerpt() {
    let temp = tempdir().expect("tempdir");
    let spool_dir = temp.path().join(".vtcode/context/tool_outputs");
    fs::create_dir_all(&spool_dir).expect("spool dir");
    let spool_path = spool_dir.join("read_1.txt");
    fs::write(
        &spool_path,
        (1..=40)
            .map(|idx| format!("spooled-line-{idx}"))
            .collect::<Vec<_>>()
            .join("\n"),
    )
    .expect("spool file");

    let history = vec![
        Message::user("review the read failure".to_string()),
        Message::tool_response(
            "call-1".to_string(),
            json!({
                "path": "src/main.rs",
                "spool_path": ".vtcode/context/tool_outputs/read_1.txt",
                "error": {
                    "message": "Read failed",
                    "hint": "Inspect the spooled content.",
                    "next_action": "Retry with a smaller slice."
                }
            })
            .to_string(),
        ),
    ];

    let previews =
        super::build_recovery_context_previews_with_workspace(&history, Some(temp.path()));

    assert_eq!(previews[0], "Latest user request: review the read failure");
    assert!(previews[1].contains("Read failed"));
    assert!(previews[1].contains("Inspect the spooled content."));
    assert!(previews[1].contains("Next action: Retry with a smaller slice."));
    assert!(previews[1].contains("source_path: src/main.rs"));
    assert!(previews[1].contains("Spool excerpt:"));
    assert!(previews[1].contains("spooled-line-1"));
}

#[test]
fn recovery_context_previews_prefer_substantive_reads_over_recent_low_signal_outputs() {
    let history = vec![
        Message::user("tell me more".to_string()),
        Message::tool_response(
            "call-1".to_string(),
            json!({
                "path": "README.md",
                "content": "VT Code is an open-source coding agent with LLM-native code understanding."
            })
            .to_string(),
        ),
        Message::tool_response(
            "call-2".to_string(),
            json!({
                "path": "docs/ARCHITECTURE.md",
                "content": "VT Code follows a modular architecture designed for maintainability and extensibility."
            })
            .to_string(),
        ),
        Message::tool_response(
            "call-3".to_string(),
            json!({
                "count": 20,
                "items": [{"path": "docs/ide"}]
            })
            .to_string(),
        ),
        Message::tool_response(
            "call-4".to_string(),
            json!({
                "error": "Repeated reads of 'docs/ARCHITECTURE.md' with limited progress detected.",
                "next_action": "Try an alternative tool or narrower scope."
            })
            .to_string(),
        ),
    ];

    let previews = super::build_recovery_context_previews_with_workspace(&history, None);

    assert_eq!(previews[0], "Latest user request: tell me more");
    assert!(previews[1].contains("VT Code follows a modular architecture"));
    assert!(previews[2].contains("VT Code is an open-source coding agent"));
    assert!(previews[3].contains("Repeated reads of 'docs/ARCHITECTURE.md'"));
    assert!(
        previews
            .iter()
            .all(|preview| !preview.contains("Listed 20 items")),
        "low-signal listing should be dropped when richer previews exist: {previews:?}"
    );
}

#[test]
fn legacy_memory_envelope_deserializes_with_new_fields_defaulted() {
    let envelope: super::SessionMemoryEnvelope = serde_json::from_value(json!({
        "session_id": "session-alpha",
        "summary": "Persisted summary",
        "task_summary": "Task tracker",
        "spec_summary": null,
        "evaluation_summary": null,
        "grounded_facts": [{
            "fact": "fact",
            "source": "tool:read_file"
        }],
        "touched_files": ["src/lib.rs"],
        "history_artifact_path": ".vtcode/history/session-alpha.jsonl",
        "generated_at": "2026-03-14T00:00:00Z"
    }))
    .expect("legacy envelope should deserialize");

    assert_eq!(envelope.schema_version, None);
    assert_eq!(envelope.objective, None);
    assert!(envelope.constraints.is_empty());
    assert!(envelope.open_questions.is_empty());
    assert!(envelope.verification_todo.is_empty());
    assert!(envelope.delegation_notes.is_empty());
}

#[test]
fn refresh_session_memory_envelope_merges_existing_continuity_fields() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");
    fs::create_dir_all(temp.path().join(".vtcode").join("tasks")).expect("tasks dir");
    fs::write(
        temp.path()
            .join(".vtcode")
            .join("tasks")
            .join("current_task.md"),
        "# Ship compaction cleanup\n- [ ] Run cargo nextest\n- [x] Wire in config\n",
    )
    .expect("write task");
    fs::write(
        temp.path()
            .join(".vtcode")
            .join("tasks")
            .join("current_spec.md"),
        "# Spec\nKeep local compaction aligned with summarized forks.\n",
    )
    .expect("write spec");
    fs::write(
        temp.path()
            .join(".vtcode")
            .join("tasks")
            .join("current_evaluation.md"),
        "# Eval\nNeed a regression test for repeated reads.\n",
    )
    .expect("write eval");

    let prior_envelope = super::SessionMemoryEnvelope {
        session_id: "session-alpha".to_string(),
        schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
        summary: "Prior summary".to_string(),
        objective: Some("Keep continuity".to_string()),
        task_summary: Some("Older task summary".to_string()),
        spec_summary: None,
        evaluation_summary: None,
        constraints: vec!["Do not redesign the harness".to_string()],
        grounded_facts: vec![GroundedFactRecord {
            fact: "Existing grounded fact".to_string(),
            source: "tool:read_file".to_string(),
        }],
        touched_files: vec!["src/old.rs".to_string()],
        open_questions: vec!["What should summarized forks retain?".to_string()],
        verification_todo: vec!["Confirm refresh runs at turn boundaries.".to_string()],
        delegation_notes: vec!["explorer: looked at compaction flow".to_string()],
        history_artifact_path: Some(".vtcode/history/session-alpha_0001.jsonl".to_string()),
        generated_at: "2026-03-14T00:00:00Z".to_string(),
    };
    fs::write(
        history_dir.join("session-alpha.memory.json"),
        serde_json::to_string_pretty(&prior_envelope).expect("serialize envelope"),
    )
    .expect("write envelope");

    let mut history = vec![
        Message::user("Continue the compaction work.".to_string()),
        Message::assistant("I will update the local compaction path.".to_string()),
    ];
    let mut session_stats = SessionStats::default();
    session_stats.record_touched_files(["src/new.rs".to_string()]);

    let update = super::SessionMemoryEnvelopeUpdate {
        grounded_facts: vec![GroundedFactRecord {
            fact: "Child agent confirmed the parser contract.".to_string(),
            source: "subagent:reviewer".to_string(),
        }],
        touched_files: vec!["src/child.rs".to_string()],
        open_questions: vec!["Should dedup cover batch reads?".to_string()],
        verification_todo: vec!["Run cargo check".to_string()],
        delegation_notes: vec!["reviewer: parser contract validated".to_string()],
        ..Default::default()
    };

    let envelope = super::refresh_session_memory_envelope(
        temp.path(),
        "session-alpha",
        Some(&VTCodeConfig::default()),
        &mut history,
        &session_stats,
        Some(&update),
    )
    .expect("refresh succeeds")
    .expect("envelope should be refreshed");

    assert_eq!(
        envelope.objective.as_deref(),
        Some("Ship compaction cleanup")
    );
    assert!(
        envelope
            .constraints
            .contains(&"Do not redesign the harness".to_string())
    );
    assert!(
        envelope
            .spec_summary
            .as_deref()
            .is_some_and(|summary| summary.contains("Keep local compaction aligned"))
    );
    assert!(
        envelope
            .evaluation_summary
            .as_deref()
            .is_some_and(|summary| summary.contains("Need a regression test"))
    );
    assert!(
        envelope
            .open_questions
            .contains(&"Should dedup cover batch reads?".to_string())
    );
    assert!(
        envelope
            .verification_todo
            .iter()
            .any(|item| item.contains("Run cargo nextest"))
    );
    assert!(
        envelope
            .verification_todo
            .contains(&"Run cargo check".to_string())
    );
    assert!(
        envelope
            .delegation_notes
            .contains(&"reviewer: parser contract validated".to_string())
    );
    assert!(envelope.touched_files.contains(&"src/new.rs".to_string()));
    assert!(envelope.touched_files.contains(&"src/child.rs".to_string()));
    assert!(
        history[0]
            .content
            .as_text()
            .contains("[Session Memory Envelope]")
    );
}

#[tokio::test]
async fn provider_compaction_error_preserves_existing_history() {
    let temp = tempdir().expect("tempdir");
    let provider = FailingProviderCompactionProvider;
    let mut history = test_history_with_memory_envelope();
    let original_history = history.clone();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let err = compact_history_in_place_with_events(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        vtcode_core::exec::events::CompactionTrigger::Manual,
    )
    .await
    .expect_err("failing provider should fail");

    assert!(!err.to_string().is_empty());
    assert_eq!(history, original_history);
}

#[tokio::test]
async fn auto_compaction_replaces_history_and_clears_response_chain() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.agent.harness.auto_compaction_enabled = true;
    vt_cfg.agent.harness.auto_compaction_threshold_tokens = Some(700);

    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    session_stats.set_previous_response_chain("stub", "stub-model", Some("resp_123"), &[]);
    let mut context_manager = test_context_manager();
    context_manager.update_token_usage(&Some(Usage {
        prompt_tokens: 900,
        completion_tokens: 10,
        total_tokens: 910,
        ..Usage::default()
    }));

    let outcome = maybe_auto_compact_history(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&vt_cfg),
            None,
            None,
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
    )
    .await
    .expect("auto compaction succeeds")
    .expect("history should compact");

    assert_eq!(outcome.original_len, 12);
    assert_eq!(outcome.compacted_len, 5);
    assert_local_compaction_history(&history, 4);
    assert!(
        history[0]
            .content
            .as_text()
            .contains("Previous conversation summary")
    );
    assert_eq!(history[5].role, MessageRole::User);
    assert_eq!(
        session_stats.previous_response_id_for("stub", "stub-model"),
        None
    );
    assert!(context_manager.current_token_usage() < 700);
    assert!(latest_memory_envelope_path_for_session(temp.path(), "session-alpha").is_some());
}

#[tokio::test]
async fn targeted_compaction_preserves_prefix_and_replaces_suffix() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut history = test_history();
    let preserved_prefix = history[..1].to_vec();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();
    context_manager.update_token_usage(&Some(Usage {
        prompt_tokens: 900,
        completion_tokens: 10,
        total_tokens: 910,
        ..Usage::default()
    }));

    let outcome = compact_history_from_index_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &mut history,
        1,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("targeted compaction succeeds")
    .expect("history should compact");

    assert_eq!(&history[..1], preserved_prefix.as_slice());
    assert_eq!(outcome.original_len, 12);
    assert_eq!(outcome.compacted_len, 5);
    assert_eq!(history.len(), 6);
    assert!(
        history[1]
            .content
            .as_text()
            .contains("[Session Memory Envelope]")
    );
    assert!(
        history[2]
            .content
            .as_text()
            .contains("Previous conversation summary")
    );
    assert!(latest_memory_envelope_path_for_session(temp.path(), "session-alpha").is_none());
}

#[tokio::test]
async fn recovery_compaction_preserves_current_turn_suffix_and_emits_event() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let harness_path = temp.path().join("recovery-harness.jsonl");
    let harness_emitter = HarnessEventEmitter::new(harness_path.clone()).expect("emitter");
    let mut history = test_history();
    history.push(Message::system("Previous turn already completed tool execution. Reuse the latest tool outputs in history instead of rerunning the same exploration. If those tool outputs include `critical_note`, `hint`, `next_action`, `fallback_tool`, `fallback_tool_args`, or `rerun_hint`, follow that guidance first.".to_string()));
    history.push(Message::system("Model follow-up failed after tool activity. Tools are disabled on the next pass; provide a direct textual response from the current context and reuse the latest tool outputs already in history.".to_string()));
    history.push(Message::user("current-turn".to_string()));
    history.push(Message::assistant("".to_string()));
    history.push(Message::tool_response(
        "call-current".to_string(),
        "{\"ok\":true}".to_string(),
    ));
    let preserved_suffix = history[12..].to_vec();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_for_recovery_in_place(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            Some(&harness_emitter),
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        12,
    )
    .await
    .expect("recovery compaction succeeds")
    .expect("history should compact");

    assert_eq!(
        history[history.len() - preserved_suffix.len()..],
        preserved_suffix
    );
    assert!(outcome.compacted_len < outcome.original_len);

    let content = fs::read_to_string(harness_path).expect("read harness log");
    assert!(content.contains("\"type\":\"thread.compact_boundary\""));
    assert!(content.contains("\"trigger\":\"recovery\""));
    assert!(content.contains("\"mode\":\"local\""));
}

#[tokio::test]
async fn recovery_compaction_uses_provider_mode_when_supported() {
    let temp = tempdir().expect("tempdir");
    let provider = ProviderCompactionProvider;
    let harness_path = temp.path().join("provider-recovery-harness.jsonl");
    let harness_emitter = HarnessEventEmitter::new(harness_path.clone()).expect("emitter");
    let mut history = test_history();
    history.push(Message::user("current-turn".to_string()));
    history.push(Message::assistant("".to_string()));
    history.push(Message::tool_response(
        "call-current".to_string(),
        "{\"ok\":true}".to_string(),
    ));
    let preserved_suffix = history[12..].to_vec();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_for_recovery_in_place(
        CompactionContext::new(
            &provider,
            "stub-model",
            "session-alpha",
            "thread-alpha",
            temp.path(),
            Some(&VTCodeConfig::default()),
            None,
            Some(&harness_emitter),
        ),
        CompactionState::new(&mut history, &mut session_stats, &mut context_manager),
        12,
    )
    .await
    .expect("provider recovery compaction succeeds")
    .expect("history should compact");

    assert_eq!(
        outcome.mode,
        vtcode_core::exec::events::CompactionMode::Provider
    );
    assert_eq!(
        history[history.len() - preserved_suffix.len()..],
        preserved_suffix
    );

    let content = fs::read_to_string(harness_path).expect("read harness log");
    assert!(content.contains("\"trigger\":\"recovery\""));
    assert!(content.contains("\"mode\":\"provider\""));
}

#[test]
fn inject_latest_memory_envelope_rehydrates_resume_history() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");
    let envelope_path = history_dir.join("resume-session_001.memory.json");
    let envelope = super::SessionMemoryEnvelope {
        session_id: "resume-session".to_string(),
        schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
        summary: "Persisted summary".to_string(),
        objective: None,
        task_summary: Some("Tracker: - [ ] Follow up".to_string()),
        spec_summary: None,
        evaluation_summary: None,
        constraints: Vec::new(),
        grounded_facts: vec![GroundedFactRecord {
            fact: "Cargo.toml declares vtcode-core".to_string(),
            source: "tool:read_file".to_string(),
        }],
        touched_files: vec!["Cargo.toml".to_string()],
        open_questions: Vec::new(),
        verification_todo: Vec::new(),
        delegation_notes: Vec::new(),
        history_artifact_path: Some(".vtcode/history/resume-session_001.jsonl".to_string()),
        generated_at: "2026-03-14T00:00:00Z".to_string(),
    };
    fs::write(
        &envelope_path,
        serde_json::to_string_pretty(&envelope).expect("serialize envelope"),
    )
    .expect("write envelope");

    let mut history = vec![Message::user("resume".to_string())];
    assert!(inject_latest_memory_envelope(
        temp.path(),
        "resume-session",
        &mut history
    ));
    assert!(history[0].content.as_text().contains("Persisted summary"));
    assert!(history[0].content.as_text().contains("Cargo.toml"));
}

#[test]
fn inject_latest_memory_envelope_is_session_scoped() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");

    for (session_id, summary) in [
        ("session-alpha", "Alpha summary"),
        ("session-beta", "Beta summary"),
    ] {
        let envelope_path = history_dir.join(format!("{session_id}_0001.memory.json"));
        let envelope = super::SessionMemoryEnvelope {
            session_id: session_id.to_string(),
            schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
            summary: summary.to_string(),
            objective: None,
            task_summary: None,
            spec_summary: None,
            evaluation_summary: None,
            constraints: Vec::new(),
            grounded_facts: Vec::new(),
            touched_files: Vec::new(),
            open_questions: Vec::new(),
            verification_todo: Vec::new(),
            delegation_notes: Vec::new(),
            history_artifact_path: None,
            generated_at: "2026-03-14T00:00:00Z".to_string(),
        };
        fs::write(
            envelope_path,
            serde_json::to_string_pretty(&envelope).expect("serialize envelope"),
        )
        .expect("write envelope");
    }

    let mut history = vec![Message::user("resume".to_string())];
    assert!(inject_latest_memory_envelope(
        temp.path(),
        "session-beta",
        &mut history
    ));
    assert!(history[0].content.as_text().contains("Beta summary"));
    assert!(!history[0].content.as_text().contains("Alpha summary"));
}

#[test]
fn inject_latest_memory_envelope_requires_exact_session_prefix_match() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");

    for (file_name, summary) in [
        ("session-a_0001.memory.json", "Exact summary"),
        ("session-alpha_0002.memory.json", "Wrong summary"),
    ] {
        let envelope = super::SessionMemoryEnvelope {
            session_id: "session-a".to_string(),
            schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
            summary: summary.to_string(),
            objective: None,
            task_summary: None,
            spec_summary: None,
            evaluation_summary: None,
            constraints: Vec::new(),
            grounded_facts: Vec::new(),
            touched_files: Vec::new(),
            open_questions: Vec::new(),
            verification_todo: Vec::new(),
            delegation_notes: Vec::new(),
            history_artifact_path: None,
            generated_at: "2026-03-14T00:00:00Z".to_string(),
        };
        fs::write(
            history_dir.join(file_name),
            serde_json::to_string_pretty(&envelope).expect("serialize envelope"),
        )
        .expect("write envelope");
    }

    let mut history = vec![Message::user("resume".to_string())];
    assert!(inject_latest_memory_envelope(
        temp.path(),
        "session-a",
        &mut history
    ));
    assert!(history[0].content.as_text().contains("Exact summary"));
    assert!(!history[0].content.as_text().contains("Wrong summary"));
}

#[tokio::test]
async fn no_envelope_written_when_dynamic_history_is_disabled() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.context.dynamic.enabled = false;

    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    compact_history_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&vt_cfg),
        &mut history,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("compaction succeeds");

    assert!(latest_memory_envelope_path_for_session(temp.path(), "session-alpha").is_none());
    assert!(
        history[0]
            .content
            .as_text()
            .contains("Previous conversation summary")
    );
}

#[tokio::test]
async fn persisted_envelope_uses_recorded_touched_files_only() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut history = test_history();
    history.push(Message::user(
        "Mentioning docs/example.md in prose should not populate touched files.".to_string(),
    ));
    let mut session_stats = SessionStats::default();
    session_stats.record_touched_files(["src/main.rs".to_string(), "Cargo.toml".to_string()]);
    let mut context_manager = test_context_manager();

    compact_history_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &mut history,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("compaction succeeds");

    let envelope_path = latest_memory_envelope_path_for_session(temp.path(), "session-alpha")
        .expect("envelope path");
    let envelope: super::SessionMemoryEnvelope =
        serde_json::from_str(&fs::read_to_string(envelope_path).expect("read envelope"))
            .expect("parse envelope");

    assert_eq!(
        envelope.touched_files,
        vec!["src/main.rs".to_string(), "Cargo.toml".to_string()]
    );
    assert_eq!(envelope.session_id, "session-alpha");
}

#[test]
fn inject_latest_memory_envelope_uses_exact_session_id_when_prefixes_collide() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");

    let session_alpha = "01234567890123456789012345678901-alpha";
    let session_beta = "01234567890123456789012345678901-beta";

    for (session_id, summary, suffix) in [
        (session_alpha, "Alpha summary", "0001"),
        (session_beta, "Beta summary", "0002"),
    ] {
        let envelope = super::SessionMemoryEnvelope {
            session_id: session_id.to_string(),
            schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
            summary: summary.to_string(),
            objective: None,
            task_summary: None,
            spec_summary: None,
            evaluation_summary: None,
            constraints: Vec::new(),
            grounded_facts: Vec::new(),
            touched_files: Vec::new(),
            open_questions: Vec::new(),
            verification_todo: Vec::new(),
            delegation_notes: Vec::new(),
            history_artifact_path: None,
            generated_at: "2026-03-14T00:00:00Z".to_string(),
        };
        let file_name = format!("{}_{suffix}.memory.json", &session_id[..32]);
        fs::write(
            history_dir.join(file_name),
            serde_json::to_string_pretty(&envelope).expect("serialize envelope"),
        )
        .expect("write envelope");
    }

    let mut history = vec![Message::user("resume".to_string())];
    assert!(inject_latest_memory_envelope(
        temp.path(),
        session_alpha,
        &mut history
    ));
    assert!(history[0].content.as_text().contains("Alpha summary"));
    assert!(!history[0].content.as_text().contains("Beta summary"));
}

#[tokio::test]
async fn compaction_strips_existing_memory_envelope_before_recompacting() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut history = test_history();
    history.insert(
        0,
        Message::system("[Session Memory Envelope]\nSummary:\nPersisted summary".to_string()),
    );
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    let outcome = compact_history_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &mut history,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("compaction succeeds")
    .expect("history should compact");

    assert_eq!(outcome.original_len, 12);
    assert_eq!(outcome.compacted_len, 5);
    assert_eq!(
        history
            .iter()
            .filter(|message| message
                .content
                .as_text()
                .contains("[Session Memory Envelope]"))
            .count(),
        1
    );
}

#[tokio::test]
async fn summarized_fork_history_reuses_compaction_pipeline_and_prior_envelope() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("history dir");
    let source_envelope = super::SessionMemoryEnvelope {
        session_id: "session-source".to_string(),
        schema_version: Some(super::SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
        summary: "Prior source summary".to_string(),
        objective: Some("Keep the source session moving".to_string()),
        task_summary: Some("Tracker: keep going".to_string()),
        spec_summary: None,
        evaluation_summary: None,
        constraints: Vec::new(),
        grounded_facts: vec![GroundedFactRecord {
            fact: "src/lib.rs was updated".to_string(),
            source: "tool:write_file".to_string(),
        }],
        touched_files: vec!["src/lib.rs".to_string()],
        open_questions: Vec::new(),
        verification_todo: Vec::new(),
        delegation_notes: Vec::new(),
        history_artifact_path: Some(".vtcode/history/session-source_0001.jsonl".to_string()),
        generated_at: "2026-03-14T00:00:00Z".to_string(),
    };
    fs::write(
        history_dir.join("session-source_0001.memory.json"),
        serde_json::to_string_pretty(&source_envelope).expect("serialize envelope"),
    )
    .expect("write envelope");

    let compacted = build_summarized_fork_history(
        &LocalCompactionProvider,
        "stub-model",
        "session-source",
        "session-target",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &test_history(),
        false,
    )
    .await
    .expect("summarized fork history");

    assert_eq!(compacted.len(), 6);
    assert!(
        compacted[0]
            .content
            .as_text()
            .contains("[Session Memory Envelope]")
    );
    assert!(compacted[0].content.as_text().contains("src/lib.rs"));
    assert!(
        compacted[1]
            .content
            .as_text()
            .contains("Previous conversation summary")
    );
    assert_eq!(
        compacted
            .iter()
            .filter(|message| message.role == MessageRole::User)
            .count(),
        4
    );
    assert!(compacted.iter().all(
        |message| message.role == MessageRole::System || message.role == MessageRole::User
    ));
}

#[tokio::test]
async fn budget_resume_summary_reuses_saved_envelope_without_provider_compaction() {
    let temp = tempdir().expect("tempdir");
    let history_dir = temp.path().join(".vtcode").join("history");
    fs::create_dir_all(&history_dir).expect("create history dir");

    let source_envelope = SessionMemoryEnvelope {
        session_id: "session-source".to_string(),
        schema_version: Some(SESSION_MEMORY_ENVELOPE_SCHEMA_VERSION),
        summary: "Budget-limited session summary".to_string(),
        objective: None,
        task_summary: None,
        spec_summary: None,
        evaluation_summary: None,
        constraints: Vec::new(),
        grounded_facts: Vec::new(),
        touched_files: vec!["src/lib.rs".to_string()],
        open_questions: Vec::new(),
        verification_todo: Vec::new(),
        delegation_notes: Vec::new(),
        history_artifact_path: None,
        generated_at: "2026-03-14T00:00:00Z".to_string(),
    };
    fs::write(
        history_dir.join("session-source_0001.memory.json"),
        serde_json::to_string_pretty(&source_envelope).expect("serialize envelope"),
    )
    .expect("write envelope");

    let compacted = build_summarized_fork_history(
        &FailingProviderCompactionProvider,
        "stub-model",
        "session-source",
        "session-target",
        temp.path(),
        Some(&VTCodeConfig::default()),
        &test_history(),
        true,
    )
    .await
    .expect("saved summary fork history");

    assert!(
        compacted[0]
            .content
            .as_text()
            .contains("[Session Memory Envelope]")
    );
    assert!(
        compacted[1]
            .content
            .as_text()
            .contains("Budget-limited session summary")
    );
}

#[tokio::test]
async fn local_and_fork_compaction_share_retained_user_budget() {
    let temp = tempdir().expect("tempdir");
    let provider = LocalCompactionProvider;
    let mut vt_cfg = VTCodeConfig::default();
    vt_cfg.context.dynamic.retained_user_messages = 2;

    let mut history = test_history();
    let mut session_stats = SessionStats::default();
    let mut context_manager = test_context_manager();

    compact_history_in_place(
        &provider,
        "stub-model",
        "session-alpha",
        temp.path(),
        Some(&vt_cfg),
        &mut history,
        &mut session_stats,
        &mut context_manager,
    )
    .await
    .expect("compaction succeeds")
    .expect("history should compact");

    assert_local_compaction_history_with_user_count(&history, 0, 2);

    let compacted = build_summarized_fork_history(
        &provider,
        "stub-model",
        "session-alpha",
        "session-beta",
        temp.path(),
        Some(&vt_cfg),
        &test_history(),
        false,
    )
    .await
    .expect("summarized fork history");

    assert_eq!(
        compacted
            .iter()
            .filter(|message| message.role == MessageRole::User)
            .count(),
        2
    );
}

#[test]
fn grounded_fact_extraction_dedupes_caps_and_skips_errors() {
    let history = vec![
        Message::tool_response_with_origin(
            "call_1".to_string(),
            "{\"result\":\"Cargo.toml declares vtcode-core\"}".to_string(),
            "read_file".to_string(),
        ),
        Message::tool_response_with_origin(
            "call_2".to_string(),
            "{\"result\":\"cargo.toml declares vtcode-core\"}".to_string(),
            "read_file".to_string(),
        ),
        Message::tool_response_with_origin(
            "call_3".to_string(),
            "{\"error\":\"denied\"}".to_string(),
            "read_file".to_string(),
        ),
        Message::user("I prefer concise answers.".to_string()),
    ];

    let facts = super::dedup_latest_facts(&history, 5);
    assert_eq!(facts.len(), 2);
    assert!(facts.iter().any(|fact| fact.source == "tool:read_file"));
    assert!(facts.iter().any(|fact| fact.source == "user_assertion"));
}

#[test]
fn resolve_compaction_threshold_prefers_configured_value() {
    assert_eq!(resolve_compaction_threshold(Some(42), 200_000), Some(42));
}

#[test]
fn resolve_compaction_threshold_uses_context_ratio_when_unset() {
    assert_eq!(resolve_compaction_threshold(None, 200_000), Some(180_000));
}

#[test]
fn resolve_compaction_threshold_clamps_to_context_size() {
    assert_eq!(
        resolve_compaction_threshold(Some(300_000), 200_000),
        Some(200_000)
    );
}

#[test]
fn resolve_compaction_threshold_requires_context_or_override() {
    assert_eq!(resolve_compaction_threshold(None, 0), None);
}

#[test]
fn build_server_compaction_context_management_creates_openai_payload() {
    assert_eq!(
        build_server_compaction_context_management(Some(512), 2_000),
        Some(json!([{
            "type": "compaction",
            "compact_threshold": 512,
        }]))
    );
}