tokensave 7.9.0

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

use tempfile::TempDir;
use tokensave::agents::*;

mod common;
use common::{make_install_ctx, make_install_ctx_with_real_bin};

// ---------------------------------------------------------------------------
// 1. Registry tests
// ---------------------------------------------------------------------------

#[test]
fn test_get_all_integrations() {
    let all = all_integrations();
    assert_eq!(all.len(), 20);
}

#[test]
fn test_available_integrations() {
    let ids = available_integrations();
    assert!(ids.contains(&"claude"));
    assert!(ids.contains(&"copilot"));
    assert!(ids.contains(&"codex"));
    assert!(ids.contains(&"gemini"));
    assert!(ids.contains(&"qwen"));
    assert!(ids.contains(&"opencode"));
    assert!(ids.contains(&"cursor"));
    assert!(ids.contains(&"droid"));
    assert!(ids.contains(&"zed"));
    assert!(ids.contains(&"cline"));
    assert!(ids.contains(&"roo-code"));
    assert!(ids.contains(&"antigravity"));
    assert!(ids.contains(&"kilo"));
    assert!(ids.contains(&"kiro"));
    assert!(ids.contains(&"kimi"));
    assert!(ids.contains(&"vibe"));
    assert!(ids.contains(&"grok"));
    assert!(ids.contains(&"pi"));
    assert!(ids.contains(&"plank"));
    assert!(ids.contains(&"qwen"));
    assert!(ids.contains(&"auggie"));
    assert_eq!(ids.len(), 20);
}

#[test]
fn test_get_integration_valid() {
    for id in &[
        "claude",
        "opencode",
        "codex",
        "gemini",
        "qwen",
        "copilot",
        "cursor",
        "droid",
        "zed",
        "cline",
        "roo-code",
        "antigravity",
        "kilo",
        "kiro",
        "kimi",
        "vibe",
        "grok",
        "pi",
        "plank",
        "auggie",
    ] {
        let agent = get_integration(id).unwrap();
        assert_eq!(agent.id(), *id);
    }
}

#[test]
fn test_get_integration_invalid() {
    assert!(get_integration("nonexistent").is_err());
    assert!(get_integration("").is_err());
    assert!(get_integration("CLAUDE").is_err()); // case-sensitive
}

// ---------------------------------------------------------------------------
// 2. Agent trait tests (name/id)
// ---------------------------------------------------------------------------

#[test]
fn test_agent_names_and_ids() {
    for agent in all_integrations() {
        assert!(!agent.name().is_empty(), "agent name should not be empty");
        assert!(!agent.id().is_empty(), "agent id should not be empty");
    }
}

#[test]
fn test_agent_names_are_human_readable() {
    // Names should have at least one space or capital letter (human-readable, not slug)
    let expected_names: Vec<(&str, &str)> = vec![
        ("claude", "Claude Code"),
        ("copilot", "GitHub Copilot"),
        ("codex", "Codex CLI"),
        ("gemini", "Gemini CLI"),
        ("qwen", "Qwen Code"),
        ("opencode", "OpenCode"),
        ("cursor", "Cursor"),
        ("droid", "Factory Droid"),
        ("zed", "Zed"),
        ("cline", "Cline"),
        ("roo-code", "Roo Code"),
        ("antigravity", "Antigravity"),
        ("kilo", "Kilo CLI"),
        ("kiro", "Kiro"),
        ("kimi", "Kimi CLI"),
        ("vibe", "Mistral Vibe"),
        ("grok", "Grok Build"),
        ("pi", "Pi"),
        ("plank", "Plank"),
        ("auggie", "AugmentCode"),
    ];
    for (id, expected_name) in expected_names {
        let agent = get_integration(id).unwrap();
        assert_eq!(agent.name(), expected_name, "name mismatch for agent {id}");
    }
}

// ---------------------------------------------------------------------------
// 3. Install / config creation tests (with tempdir)
// ---------------------------------------------------------------------------

#[test]
fn test_claude_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    ClaudeIntegration.install(&ctx).unwrap();

    // Check ~/.claude.json exists and has mcpServers.tokensave
    let claude_json = home.join(".claude.json");
    assert!(
        claude_json.exists(),
        "~/.claude.json should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&claude_json).unwrap()).unwrap();
    assert!(
        content.get("mcpServers").is_some(),
        "mcpServers key should exist"
    );
    assert!(
        content["mcpServers"]["tokensave"].is_object(),
        "mcpServers.tokensave should be an object"
    );
    // Verify args contain "serve"
    let args = content["mcpServers"]["tokensave"]["args"]
        .as_array()
        .unwrap();
    assert!(args.iter().any(|v| v.as_str() == Some("serve")));

    // Check ~/.claude/settings.json exists with hook and permissions
    let settings_path = home.join(".claude/settings.json");
    assert!(
        settings_path.exists(),
        "settings.json should exist after install"
    );
    let settings: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    // Check hook
    assert!(
        settings["hooks"]["PreToolUse"].is_array(),
        "PreToolUse hook should be an array"
    );
    // Check permissions
    assert!(
        settings["permissions"]["allow"].is_array(),
        "permissions.allow should be an array"
    );

    // Issue #256: rules live in a tokensave-owned managed file, not
    // appended to the user's CLAUDE.md.
    assert!(
        !home.join(".claude/CLAUDE.md").exists(),
        "install should not create/touch CLAUDE.md"
    );
    let rules_path = home.join(".claude/rules/tokensave.md");
    assert!(
        rules_path.exists(),
        "managed rules file should exist after install"
    );
    let rules_content = std::fs::read_to_string(&rules_path).unwrap();
    assert!(
        rules_content.contains("tokensave"),
        "managed rules file should mention tokensave"
    );
}

#[test]
fn test_gemini_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    GeminiIntegration.install(&ctx).unwrap();

    // Check ~/.gemini/settings.json
    let settings_path = home.join(".gemini/settings.json");
    assert!(
        settings_path.exists(),
        "settings.json should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(
        content["mcpServers"]["tokensave"].is_object(),
        "mcpServers.tokensave should exist"
    );
    // Verify trust flag
    assert_eq!(
        content["mcpServers"]["tokensave"]["trust"],
        serde_json::json!(true),
        "gemini should have trust: true"
    );

    // Check GEMINI.md
    let gemini_md = home.join(".gemini/GEMINI.md");
    assert!(gemini_md.exists(), "GEMINI.md should exist after install");
    let md_content = std::fs::read_to_string(&gemini_md).unwrap();
    assert!(md_content.contains("tokensave"));
}

#[test]
fn test_qwen_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    QwenIntegration.install(&ctx).unwrap();

    // Check ~/.qwen/settings.json
    let settings_path = home.join(".qwen/settings.json");
    assert!(
        settings_path.exists(),
        "settings.json should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(
        content["mcpServers"]["tokensave"].is_object(),
        "mcpServers.tokensave should exist"
    );
    // Verify trust flag
    assert_eq!(
        content["mcpServers"]["tokensave"]["trust"],
        serde_json::json!(true),
        "qwen should have trust: true"
    );

    // Check QWEN.md
    let qwen_md = home.join(".qwen/QWEN.md");
    assert!(qwen_md.exists(), "QWEN.md should exist after install");
    let md_content = std::fs::read_to_string(&qwen_md).unwrap();
    assert!(md_content.contains("tokensave"));
}

#[test]
fn test_codex_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CodexIntegration.install(&ctx).unwrap();

    // Check ~/.codex/config.toml
    let config_path = home.join(".codex/config.toml");
    assert!(
        config_path.exists(),
        "config.toml should exist after install"
    );
    // Verify the file contains the expected content as text (the TOML output from
    // toml::to_string_pretty uses dotted headers which may not round-trip through
    // toml::Value::parse in all crate versions)
    let content = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        content.contains("[mcp_servers.tokensave]"),
        "config.toml should contain [mcp_servers.tokensave]"
    );
    assert!(
        content.contains("\"serve\""),
        "config.toml should contain \"serve\" in args"
    );

    // Check AGENTS.md
    let agents_md = home.join(".codex/AGENTS.md");
    assert!(agents_md.exists(), "AGENTS.md should exist after install");
    let md_content = std::fs::read_to_string(&agents_md).unwrap();
    assert!(md_content.contains("tokensave"));
}

#[test]
fn test_kimi_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    KimiIntegration.install(&ctx).unwrap();

    let mcp_path = home.join(".kimi/mcp.json");
    assert!(mcp_path.exists(), "mcp.json should exist after install");
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&mcp_path).unwrap()).unwrap();
    assert!(
        content["mcpServers"]["tokensave"].is_object(),
        "mcpServers.tokensave should be an object"
    );
    let args = content["mcpServers"]["tokensave"]["args"]
        .as_array()
        .unwrap();
    assert!(args.iter().any(|v| v.as_str() == Some("serve")));

    let agents_md = home.join(".kimi/AGENTS.md");
    assert!(agents_md.exists(), "AGENTS.md should exist after install");
    let md_content = std::fs::read_to_string(&agents_md).unwrap();
    assert!(md_content.contains("tokensave"));
}

#[test]
fn test_kimi_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    KimiIntegration.install(&ctx).unwrap();
    let mcp_path = home.join(".kimi/mcp.json");
    assert!(mcp_path.exists());

    KimiIntegration.uninstall(&ctx).unwrap();

    assert!(
        !mcp_path.exists(),
        "mcp.json with only tokensave should be removed on uninstall"
    );

    let agents_md = home.join(".kimi/AGENTS.md");
    if agents_md.exists() {
        let content = std::fs::read_to_string(&agents_md).unwrap();
        assert!(
            !content.contains("## Prefer tokensave MCP tools"),
            "AGENTS.md should not have tokensave rules after uninstall"
        );
    }
}

#[test]
fn test_kimi_is_detected_and_has_tokensave() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    assert!(!KimiIntegration.is_detected(home));
    assert!(!KimiIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    KimiIntegration.install(&ctx).unwrap();

    assert!(KimiIntegration.is_detected(home));
    assert!(KimiIntegration.has_tokensave(home));
}

#[test]
fn test_cursor_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CursorIntegration.install(&ctx).unwrap();

    let mcp_path = home.join(".cursor/mcp.json");
    assert!(mcp_path.exists(), "mcp.json should exist after install");
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&mcp_path).unwrap()).unwrap();
    assert!(content["mcpServers"]["tokensave"].is_object());

    let hooks_path = home.join(".cursor/hooks.json");
    assert!(hooks_path.exists(), "hooks.json should exist after install");
    let hooks: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&hooks_path).unwrap()).unwrap();
    let pre = hooks["hooks"]["preToolUse"].as_array().unwrap();
    assert!(pre.iter().any(|e| {
        e["matcher"].as_str() == Some("Grep|Shell")
            && e["command"]
                .as_str()
                .is_some_and(|c| c.contains("hook-pre-tool-use"))
    }));
}

#[test]
fn test_cursor_install_preserves_foreign_hooks() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let hooks_path = home.join(".cursor/hooks.json");
    std::fs::create_dir_all(hooks_path.parent().unwrap()).unwrap();
    std::fs::write(
        &hooks_path,
        r#"{
            "version": 1,
            "hooks": {
                "preToolUse": [
                    {"command": "rtk hook cursor", "matcher": "Shell"},
                    {"command": "/opt/custom/limit.py", "matcher": "Task"}
                ]
            }
        }"#,
    )
    .unwrap();

    let ctx = make_install_ctx(home);
    CursorIntegration.install(&ctx).unwrap();

    let hooks: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&hooks_path).unwrap()).unwrap();
    let pre = hooks["hooks"]["preToolUse"].as_array().unwrap();
    assert_eq!(pre.len(), 3, "should append tokensave, keep rtk + custom");
    assert!(pre
        .iter()
        .any(|e| e["command"].as_str() == Some("rtk hook cursor")));
    assert!(pre.iter().any(|e| {
        e["command"]
            .as_str()
            .is_some_and(|c| c.contains("hook-pre-tool-use"))
    }));
}

#[test]
fn test_cursor_uninstall_removes_only_tokensave_hooks() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CursorIntegration.install(&ctx).unwrap();
    CursorIntegration.uninstall(&ctx).unwrap();

    let hooks_path = home.join(".cursor/hooks.json");
    assert!(
        !hooks_path.exists() || {
            let hooks: serde_json::Value =
                serde_json::from_str(&std::fs::read_to_string(&hooks_path).unwrap()).unwrap();
            hooks["hooks"]["preToolUse"]
                .as_array()
                .map(|a| {
                    !a.iter().any(|e| {
                        e["command"]
                            .as_str()
                            .is_some_and(|c| c.contains("tokensave"))
                    })
                })
                .unwrap_or(true)
        }
    );
}

#[test]
fn test_opencode_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    // OpenCode uses ~/.config/opencode/opencode.json
    // Create the parent dir so install can discover it
    let ctx = make_install_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let config_path = home.join(".config/opencode/opencode.json");
    assert!(
        config_path.exists(),
        "opencode.json should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&config_path).unwrap()).unwrap();
    assert!(content["mcp"]["tokensave"].is_object());
}

#[test]
fn test_zed_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    ZedIntegration.install(&ctx).unwrap();

    // On macOS: ~/Library/Application Support/Zed/settings.json
    // On linux: ~/.config/zed/settings.json
    #[cfg(target_os = "macos")]
    let settings_path = home.join("Library/Application Support/Zed/settings.json");
    #[cfg(not(target_os = "macos"))]
    let settings_path = home.join(".config/zed/settings.json");

    assert!(
        settings_path.exists(),
        "Zed settings.json should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(content["context_servers"]["tokensave"].is_object());
}

#[test]
fn test_cline_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    ClineIntegration.install(&ctx).unwrap();

    // Cline uses VS Code extension global storage
    #[cfg(target_os = "macos")]
    let settings_path = home.join("Library/Application Support/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
    #[cfg(target_os = "linux")]
    let settings_path = home.join(
        ".config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json",
    );
    #[cfg(target_os = "windows")]
    let settings_path = home.join("AppData/Roaming/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json");
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let settings_path = home.join(
        ".config/Code/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json",
    );

    assert!(
        settings_path.exists(),
        "Cline settings should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(content["mcpServers"]["tokensave"].is_object());
}

#[test]
fn test_roo_code_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    RooCodeIntegration.install(&ctx).unwrap();

    #[cfg(target_os = "macos")]
    let settings_path = home.join("Library/Application Support/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
    #[cfg(target_os = "linux")]
    let settings_path = home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
    #[cfg(target_os = "windows")]
    let settings_path = home.join("AppData/Roaming/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let settings_path = home.join(".config/Code/User/globalStorage/rooveterinaryinc.roo-cline/settings/cline_mcp_settings.json");

    assert!(
        settings_path.exists(),
        "Roo Code settings should exist after install"
    );
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(content["mcpServers"]["tokensave"].is_object());
}

#[test]
fn test_copilot_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CopilotIntegration.install(&ctx).unwrap();

    // Check VS Code's dedicated mcp.json (1.102+, GA MCP — issue #266)
    #[cfg(target_os = "macos")]
    let vscode_mcp_json = home.join("Library/Application Support/Code/User/mcp.json");
    #[cfg(target_os = "linux")]
    let vscode_mcp_json = home.join(".config/Code/User/mcp.json");
    #[cfg(target_os = "windows")]
    let vscode_mcp_json = home.join("AppData/Roaming/Code/User/mcp.json");
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    let vscode_mcp_json = home.join(".config/Code/User/mcp.json");

    assert!(vscode_mcp_json.exists(), "VS Code mcp.json should exist");
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&vscode_mcp_json).unwrap()).unwrap();
    assert!(content["servers"]["tokensave"].is_object());

    // Check CLI config
    let cli_config = home.join(".copilot/mcp-config.json");
    assert!(cli_config.exists(), "Copilot CLI config should exist");
    let cli_content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&cli_config).unwrap()).unwrap();
    assert!(cli_content["mcpServers"]["tokensave"].is_object());
}

#[test]
fn test_vibe_install_creates_config() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    VibeIntegration.install(&ctx).unwrap();

    let config_path = home.join(".vibe/config.toml");
    assert!(
        config_path.exists(),
        "config.toml should exist after install"
    );
    let content = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        content.contains("name = \"tokensave\""),
        "config should contain tokensave MCP server"
    );
    assert!(
        content.contains("transport = \"stdio\""),
        "config should use stdio transport"
    );
    assert!(
        content.contains("args = [\"serve\"]"),
        "config should have serve arg"
    );

    // Check prompt rules
    let prompt_path = home.join(".vibe/prompts/cli.md");
    assert!(
        prompt_path.exists(),
        "Vibe prompt should exist after install"
    );
    let prompt = std::fs::read_to_string(&prompt_path).unwrap();
    assert!(prompt.contains("tokensave"));
}

// ---------------------------------------------------------------------------
// 4. Install followed by Uninstall
// ---------------------------------------------------------------------------

#[test]
fn test_claude_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    // Install
    ClaudeIntegration.install(&ctx).unwrap();
    assert!(home.join(".claude.json").exists());

    // Uninstall
    ClaudeIntegration.uninstall(&ctx).unwrap();

    // ~/.claude.json should be removed (was only tokensave)
    // It may be removed entirely or have mcpServers removed
    if home.join(".claude.json").exists() {
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
                .unwrap();
        // Should not have tokensave anymore
        let has_tokensave = content
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(
            !has_tokensave,
            "tokensave should be removed from .claude.json after uninstall"
        );
    }
}

#[test]
fn test_gemini_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    GeminiIntegration.install(&ctx).unwrap();
    let settings_path = home.join(".gemini/settings.json");
    assert!(settings_path.exists());

    GeminiIntegration.uninstall(&ctx).unwrap();

    // After uninstall, settings.json should be removed or not contain tokensave
    if settings_path.exists() {
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
        let has_tokensave = content
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(
            !has_tokensave,
            "tokensave should be removed from settings.json"
        );
    }

    // GEMINI.md should be removed (was only tokensave rules)
    let gemini_md = home.join(".gemini/GEMINI.md");
    if gemini_md.exists() {
        let content = std::fs::read_to_string(&gemini_md).unwrap();
        assert!(
            !content.contains("## Prefer tokensave MCP tools"),
            "GEMINI.md should not contain tokensave rules after uninstall"
        );
    }
}

#[test]
fn test_qwen_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    QwenIntegration.install(&ctx).unwrap();
    let settings_path = home.join(".qwen/settings.json");
    assert!(settings_path.exists());

    QwenIntegration.uninstall(&ctx).unwrap();

    // After uninstall, settings.json should be removed or not contain tokensave
    if settings_path.exists() {
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
        let has_tokensave = content
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(
            !has_tokensave,
            "tokensave should be removed from settings.json"
        );
    }

    // QWEN.md should be removed (was only tokensave rules)
    let qwen_md = home.join(".qwen/QWEN.md");
    if qwen_md.exists() {
        let content = std::fs::read_to_string(&qwen_md).unwrap();
        assert!(
            !content.contains("## Prefer tokensave MCP tools"),
            "QWEN.md should not contain tokensave rules after uninstall"
        );
    }
}

#[test]
fn test_codex_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    CodexIntegration.install(&ctx).unwrap();
    let config_path = home.join(".codex/config.toml");
    assert!(config_path.exists());

    CodexIntegration.uninstall(&ctx).unwrap();

    // After uninstall, the config (which only contained tokensave) becomes
    // empty and is removed; or, if other content existed, the tokensave
    // server is dropped but the rest is preserved.
    assert!(
        !config_path.exists(),
        "config.toml with only tokensave should be removed on uninstall"
    );

    let agents_md = home.join(".codex/AGENTS.md");
    if agents_md.exists() {
        let content = std::fs::read_to_string(&agents_md).unwrap();
        assert!(
            !content.contains("## Prefer tokensave MCP tools"),
            "AGENTS.md should not have tokensave rules after uninstall"
        );
    }
}

#[test]
fn test_codex_install_preserves_existing_config() {
    // Regression test for issue #63: installing tokensave used to wipe out the
    // entire ~/.codex/config.toml because load_toml_file silently returned an
    // empty table.
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    std::fs::create_dir_all(home.join(".codex")).unwrap();
    let config_path = home.join(".codex/config.toml");
    let original = "\
model = \"o4-mini\"
approval_policy = \"on-failure\"

[mcp_servers.other]
command = \"other-bin\"
args = [\"--flag\"]
";
    std::fs::write(&config_path, original).unwrap();

    let ctx = make_install_ctx(home);
    CodexIntegration.install(&ctx).unwrap();

    // A backup of the original must exist.
    let backup = home.join(".codex/config.toml.bak");
    assert!(backup.exists(), "install must back up the existing config");
    assert_eq!(std::fs::read_to_string(&backup).unwrap(), original);

    // The new config must keep the user's settings.
    let new_contents = std::fs::read_to_string(&config_path).unwrap();
    let parsed: toml::Table = toml::from_str(&new_contents).unwrap();
    assert_eq!(
        parsed.get("model").and_then(|v| v.as_str()),
        Some("o4-mini"),
        "top-level user keys must be preserved"
    );
    assert_eq!(
        parsed.get("approval_policy").and_then(|v| v.as_str()),
        Some("on-failure"),
    );
    let servers = parsed
        .get("mcp_servers")
        .and_then(|v| v.as_table())
        .expect("mcp_servers should still be a table");
    assert!(
        servers.contains_key("other"),
        "pre-existing mcp_servers entries must be preserved"
    );
    assert!(
        servers.contains_key("tokensave"),
        "tokensave should be registered alongside existing servers"
    );
}

#[test]
fn test_codex_install_refuses_unparseable_config() {
    // Issue #63 guard: if the existing config can't be parsed, refuse to
    // overwrite rather than silently replacing the user's content.
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    std::fs::create_dir_all(home.join(".codex")).unwrap();
    let config_path = home.join(".codex/config.toml");
    let original = "this is not valid TOML {{{{";
    std::fs::write(&config_path, original).unwrap();

    let ctx = make_install_ctx(home);
    let result = CodexIntegration.install(&ctx);
    assert!(
        result.is_err(),
        "install must fail when existing config.toml is unparseable"
    );
    assert_eq!(
        std::fs::read_to_string(&config_path).unwrap(),
        original,
        "the broken config must be left untouched so the user can fix it"
    );
}

// ---------------------------------------------------------------------------
// Issue #63 regression: every agent must back up an existing config before
// overwriting it, and the user's pre-existing content must survive install.
// ---------------------------------------------------------------------------

/// Seed the agent's primary config with `original`, run install, then assert
/// that a `.bak` was created with the original bytes and that the new content
/// still contains the user's `marker` substring.
///
/// The path is taken from `agent.primary_config_path(home)` so a future change
/// to platform-conditional path logic (e.g. zed v4.3.15 Windows incident)
/// can't drift between tests and production.
fn assert_install_backs_up_and_preserves(
    agent: &dyn AgentIntegration,
    home: &Path,
    original: &str,
    marker: &str,
) {
    let config_path = agent
        .primary_config_path(home)
        .unwrap_or_else(|| panic!("{} must implement primary_config_path", agent.name()));
    std::fs::create_dir_all(config_path.parent().unwrap()).unwrap();
    std::fs::write(&config_path, original).unwrap();

    let ctx = make_install_ctx(home);
    agent.install(&ctx).expect("install should succeed");

    let mut backup = config_path.as_os_str().to_owned();
    backup.push(".bak");
    let backup = std::path::PathBuf::from(backup);
    assert!(
        backup.exists(),
        "{}: install must back up the existing config to {}",
        agent.name(),
        backup.display()
    );
    assert_eq!(
        std::fs::read_to_string(&backup).unwrap(),
        original,
        "{}: backup must contain the exact original bytes",
        agent.name()
    );

    let new = std::fs::read_to_string(&config_path).unwrap();
    assert!(
        new.contains(marker),
        "{}: user's pre-existing content (marker {marker:?}) must be preserved, got:\n{new}",
        agent.name(),
    );
}

#[test]
fn test_claude_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "theme": "solarized",
  "mcpServers": {
    "other": { "command": "other-bin", "args": ["--flag"] }
  }
}
"#;
    assert_install_backs_up_and_preserves(&ClaudeIntegration, dir.path(), original, "solarized");
}

#[test]
fn test_gemini_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "theme": "dark",
  "mcpServers": { "other": { "command": "other-bin" } }
}
"#;
    assert_install_backs_up_and_preserves(&GeminiIntegration, dir.path(), original, "\"theme\"");
}

#[test]
fn test_cursor_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "mcpServers": { "other": { "command": "other-bin" } }
}
"#;
    assert_install_backs_up_and_preserves(&CursorIntegration, dir.path(), original, "other-bin");
}

#[test]
fn test_opencode_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "$schema": "https://opencode.ai/config.json",
  "mcp": { "other": { "type": "local", "command": ["other-bin"] } }
}
"#;
    assert_install_backs_up_and_preserves(&OpenCodeIntegration, dir.path(), original, "other-bin");
}

#[test]
fn test_zed_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "theme": "One Dark",
  "context_servers": { "other": { "command": { "path": "other-bin", "args": [] } } }
}
"#;
    assert_install_backs_up_and_preserves(&ZedIntegration, dir.path(), original, "One Dark");
}

#[test]
fn test_cline_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "mcpServers": { "other": { "command": "other-bin" } }
}
"#;
    assert_install_backs_up_and_preserves(&ClineIntegration, dir.path(), original, "other-bin");
}

#[test]
fn test_roo_code_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "mcpServers": { "other": { "command": "other-bin" } }
}
"#;
    assert_install_backs_up_and_preserves(&RooCodeIntegration, dir.path(), original, "other-bin");
}

#[test]
fn test_cursor_uninstall_backs_up_config_with_other_content() {
    // Regression for issue #63: uninstall paths must also back up the file
    // before rewriting, so a botched rewrite is recoverable.
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    let path = home.join(".cursor/mcp.json");
    std::fs::create_dir_all(path.parent().unwrap()).unwrap();
    let original = r#"{
  "mcpServers": {
    "tokensave": { "command": "/usr/local/bin/tokensave", "args": ["serve"] },
    "other": { "command": "other-bin" }
  }
}
"#;
    std::fs::write(&path, original).unwrap();

    CursorIntegration.uninstall(&ctx).unwrap();

    let backup = home.join(".cursor/mcp.json.bak");
    assert!(
        backup.exists(),
        "uninstall must back up the existing config before rewriting it"
    );
    assert_eq!(
        std::fs::read_to_string(&backup).unwrap(),
        original,
        "backup must contain the exact pre-uninstall bytes"
    );
    let new = std::fs::read_to_string(&path).unwrap();
    assert!(
        new.contains("other-bin") && !new.contains("tokensave"),
        "uninstall must drop tokensave but keep other servers; got:\n{new}"
    );
}

#[test]
fn test_kilo_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  // user comment about their workflow
  "mcp": { "other": { "type": "local", "command": ["other-bin"], "enabled": true } }
}
"#;
    assert_install_backs_up_and_preserves(&KiloIntegration, dir.path(), original, "other-bin");
}

#[test]
fn test_antigravity_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "mcpServers": { "other": { "command": "other-bin" } }
}
"#;
    assert_install_backs_up_and_preserves(
        &AntigravityIntegration,
        dir.path(),
        original,
        "other-bin",
    );
}

/// Regression for #85: `tokensave install --agent antigravity` must populate
/// both the IDE config and the CLI plugin file so the `agy` CLI can see the
/// server. Before the fix only the IDE path was written, which left the CLI
/// invisible in `/mcp`.
#[test]
fn test_antigravity_install_writes_cli_plugin() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let bin = "/usr/local/bin/tokensave";
    let ctx = InstallContext {
        home: home.to_path_buf(),
        tokensave_bin: bin.to_string(),
        tool_permissions: expected_tool_perms(),
        scope: tokensave::agents::InstallScope::Global,
        force_permission_style: false,
    };

    AntigravityIntegration.install(&ctx).expect("install ok");

    let ide_path = home.join(".gemini/antigravity/mcp_config.json");
    let cli_path = home.join(".gemini/antigravity-cli/plugins/tokensave.json");
    assert!(
        ide_path.exists(),
        "IDE config must be written: {ide_path:?}"
    );
    assert!(
        cli_path.exists(),
        "CLI plugin must be written: {cli_path:?}"
    );

    for path in [&ide_path, &cli_path] {
        let body: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
        let server = body
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .expect("tokensave entry");
        assert_eq!(
            server.get("command").and_then(|v| v.as_str()),
            Some(bin),
            "{path:?} must point at the install bin"
        );
        assert!(
            server
                .get("args")
                .and_then(|v| v.as_array())
                .is_some_and(|a| a.iter().any(|v| v.as_str() == Some("serve"))),
            "{path:?} must invoke `serve`"
        );
    }
}

/// Uninstall must remove the CLI plugin file outright (it belongs only to
/// tokensave) and remove the `tokensave` entry from the shared IDE config
/// without touching the user's other entries.
#[test]
fn test_antigravity_uninstall_removes_both_locations() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let bin = "/usr/local/bin/tokensave";
    let ctx = InstallContext {
        home: home.to_path_buf(),
        tokensave_bin: bin.to_string(),
        tool_permissions: expected_tool_perms(),
        scope: tokensave::agents::InstallScope::Global,
        force_permission_style: false,
    };

    AntigravityIntegration.install(&ctx).unwrap();
    AntigravityIntegration.uninstall(&ctx).unwrap();

    let cli_path = home.join(".gemini/antigravity-cli/plugins/tokensave.json");
    assert!(
        !cli_path.exists(),
        "CLI plugin file must be deleted, still exists at {cli_path:?}"
    );

    let ide_path = home.join(".gemini/antigravity/mcp_config.json");
    // IDE config either deleted (empty) or rewritten without our entry —
    // both are acceptable; what's not acceptable is the entry persisting.
    if ide_path.exists() {
        let body: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&ide_path).unwrap()).unwrap();
        assert!(
            body.get("mcpServers")
                .and_then(|v| v.get("tokensave"))
                .is_none(),
            "tokensave entry must be removed from {ide_path:?}"
        );
    }
}

#[test]
fn test_copilot_install_preserves_existing_config() {
    let dir = TempDir::new().unwrap();
    let original = r#"{
  "editor.fontSize": 14,
  "workbench.colorTheme": "Default Dark+"
}
"#;
    assert_install_backs_up_and_preserves(
        &CopilotIntegration,
        dir.path(),
        original,
        "Default Dark+",
    );
}

/// Meta-test: every agent that goes through `assert_install_backs_up_and_preserves`
/// above must also actually return a path from `primary_config_path`. Catches
/// the case where a new integration is added without wiring up the method,
/// which would otherwise only surface as a confusing panic in CI.
#[test]
fn test_every_tested_agent_advertises_primary_config_path() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let agents: Vec<(&dyn AgentIntegration, &str)> = vec![
        (&ClaudeIntegration, "claude"),
        (&GeminiIntegration, "gemini"),
        (&CursorIntegration, "cursor"),
        (&OpenCodeIntegration, "opencode"),
        (&ZedIntegration, "zed"),
        (&ClineIntegration, "cline"),
        (&RooCodeIntegration, "roo-code"),
        (&CopilotIntegration, "copilot"),
        (&KiloIntegration, "kilo"),
        (&AntigravityIntegration, "antigravity"),
        (&CodexIntegration, "codex"),
        (&KiroIntegration, "kiro"),
        (&KimiIntegration, "kimi"),
    ];
    for (agent, id) in agents {
        let path = agent
            .primary_config_path(home)
            .unwrap_or_else(|| panic!("{id} must implement primary_config_path"));
        assert!(
            path.starts_with(home),
            "{id}: primary_config_path must be under the home arg, got {}",
            path.display()
        );
    }
}

#[test]
fn test_cursor_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    CursorIntegration.install(&ctx).unwrap();
    let mcp_path = home.join(".cursor/mcp.json");
    assert!(mcp_path.exists());

    CursorIntegration.uninstall(&ctx).unwrap();

    // mcp.json should be removed (was only tokensave)
    if mcp_path.exists() {
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&mcp_path).unwrap()).unwrap();
        let has_tokensave = content
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(!has_tokensave, "tokensave should be removed from mcp.json");
    }
}

#[test]
fn test_copilot_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    CopilotIntegration.install(&ctx).unwrap();
    CopilotIntegration.uninstall(&ctx).unwrap();

    // CLI config should be cleaned up
    let cli_config = home.join(".copilot/mcp-config.json");
    if cli_config.exists() {
        let content: serde_json::Value =
            serde_json::from_str(&std::fs::read_to_string(&cli_config).unwrap()).unwrap();
        let has_tokensave = content
            .get("mcpServers")
            .and_then(|v| v.get("tokensave"))
            .is_some();
        assert!(!has_tokensave);
    }
}

#[test]
fn test_vibe_install_then_uninstall() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    VibeIntegration.install(&ctx).unwrap();
    VibeIntegration.uninstall(&ctx).unwrap();

    let config_path = home.join(".vibe/config.toml");
    if config_path.exists() {
        let content = std::fs::read_to_string(&config_path).unwrap();
        assert!(
            !content.contains("name = \"tokensave\""),
            "tokensave should be removed from config.toml"
        );
    }

    let prompt_path = home.join(".vibe/prompts/cli.md");
    if prompt_path.exists() {
        let content = std::fs::read_to_string(&prompt_path).unwrap();
        assert!(
            !content.contains("tokensave"),
            "tokensave rules should be removed from prompt"
        );
    }
}

// ---------------------------------------------------------------------------
// 5. Healthcheck with tempdir
// ---------------------------------------------------------------------------

#[test]
fn test_healthcheck_claude_clean_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx_with_real_bin(home);
    ClaudeIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    ClaudeIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(dc.issues, 0, "clean Claude install should have no issues");
}

#[test]
fn test_healthcheck_gemini_clean_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    GeminiIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    GeminiIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(dc.issues, 0, "clean Gemini install should have no issues");
}

#[test]
fn test_healthcheck_codex_after_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CodexIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    CodexIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(
        dc.issues, 0,
        "Codex healthcheck should pass after a clean install"
    );
}

#[test]
fn test_healthcheck_cursor_clean_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    CursorIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    CursorIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(dc.issues, 0, "clean Cursor install should have no issues");
}

#[test]
fn test_healthcheck_opencode_clean_install() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();

    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    OpenCodeIntegration.healthcheck(&mut dc, &hctx);
    assert_eq!(dc.issues, 0, "clean OpenCode install should have no issues");
}

#[test]
fn test_healthcheck_no_install_warns() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Healthcheck without installing should produce warnings (not crashes)
    let mut dc = DoctorCounters::new();
    let hctx = HealthcheckContext {
        home: home.to_path_buf(),
        project_path: home.to_path_buf(),
    };
    ClaudeIntegration.healthcheck(&mut dc, &hctx);
    // Should have issues (missing config files)
    assert!(
        dc.issues > 0 || dc.warnings > 0,
        "healthcheck on empty dir should report issues or warnings"
    );
}

#[test]
fn test_doctor_counters() {
    let mut dc = DoctorCounters::new();
    assert_eq!(dc.issues, 0);
    assert_eq!(dc.warnings, 0);

    dc.pass("this is fine");
    assert_eq!(dc.issues, 0);
    assert_eq!(dc.warnings, 0);

    dc.fail("something broke");
    assert_eq!(dc.issues, 1);
    assert_eq!(dc.warnings, 0);

    dc.warn("be careful");
    assert_eq!(dc.issues, 1);
    assert_eq!(dc.warnings, 1);

    dc.info("just info");
    assert_eq!(dc.issues, 1);
    assert_eq!(dc.warnings, 1);

    dc.fail("another failure");
    assert_eq!(dc.issues, 2);
    assert_eq!(dc.warnings, 1);
}

// ---------------------------------------------------------------------------
// 6. Helper function tests
// ---------------------------------------------------------------------------

#[test]
fn test_load_json_file_missing() {
    let val = load_json_file(Path::new("/nonexistent/file.json"));
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_load_json_file_valid() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.json");
    std::fs::write(&path, r#"{"key": "value"}"#).unwrap();
    let val = load_json_file(&path);
    assert_eq!(val["key"], "value");
}

#[test]
fn test_load_json_file_invalid_returns_empty() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("bad.json");
    std::fs::write(&path, "not valid json").unwrap();
    let val = load_json_file(&path);
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_load_json_file_strict_missing() {
    let result = load_json_file_strict(Path::new("/nonexistent/file.json"));
    assert!(result.is_ok());
    let val = result.unwrap();
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_load_json_file_strict_empty_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("empty.json");
    std::fs::write(&path, "").unwrap();
    let result = load_json_file_strict(&path);
    assert!(result.is_ok());
    let val = result.unwrap();
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_load_json_file_strict_whitespace_only() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("ws.json");
    std::fs::write(&path, "   \n  \t  ").unwrap();
    let result = load_json_file_strict(&path);
    assert!(result.is_ok());
}

#[test]
fn test_load_json_file_strict_invalid() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("bad.json");
    std::fs::write(&path, "not valid json").unwrap();
    assert!(load_json_file_strict(&path).is_err());
}

#[test]
fn test_load_json_file_strict_valid() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("good.json");
    std::fs::write(&path, r#"{"hello": "world"}"#).unwrap();
    let val = load_json_file_strict(&path).unwrap();
    assert_eq!(val["hello"], "world");
}

#[test]
fn test_backup_config_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("config.json");
    std::fs::write(&path, r#"{"original": true}"#).unwrap();
    let backup = backup_config_file(&path).unwrap();
    assert!(backup.is_some());
    let backup_path = backup.unwrap();
    assert!(backup_path.exists());
    // Verify backup content matches original
    let backup_content = std::fs::read_to_string(&backup_path).unwrap();
    assert_eq!(backup_content, r#"{"original": true}"#);
}

#[test]
fn test_backup_config_file_missing() {
    let result = backup_config_file(Path::new("/nonexistent/file.json")).unwrap();
    assert!(result.is_none());
}

#[test]
fn test_safe_write_json_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("output.json");
    let value = serde_json::json!({"hello": "world"});
    safe_write_json_file(&path, &value, None).unwrap();
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(content["hello"], "world");
}

#[test]
fn test_safe_write_json_file_creates_parent_dirs() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("deep/nested/dir/output.json");
    let value = serde_json::json!({"nested": true});
    safe_write_json_file(&path, &value, None).unwrap();
    assert!(path.exists());
}

#[test]
fn test_safe_write_json_file_overwrites_existing() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("existing.json");
    std::fs::write(&path, r#"{"old": true}"#).unwrap();
    let value = serde_json::json!({"new": true});
    safe_write_json_file(&path, &value, None).unwrap();
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(content["new"], true);
    assert!(content.get("old").is_none());
}

#[test]
fn test_write_json_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("write_test.json");
    let value = serde_json::json!({"test": 42});
    write_json_file(&path, &value).unwrap();
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(content["test"], 42);
}

#[test]
fn test_load_toml_file_missing() {
    let val = load_toml_file(Path::new("/nonexistent/file.toml")).unwrap();
    assert!(val.is_table());
    assert!(val.as_table().unwrap().is_empty());
}

#[test]
fn test_load_toml_file_valid() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.toml");
    std::fs::write(&path, "key = \"value\"\nnumber = 42\n").unwrap();
    let val = load_toml_file(&path).expect("valid TOML should parse as document");
    let table = val.as_table().expect("top-level should be a table");
    assert_eq!(table.get("key").and_then(|v| v.as_str()), Some("value"));
    assert_eq!(table.get("number").and_then(|v| v.as_integer()), Some(42));
}

#[test]
fn test_load_toml_file_invalid_returns_err() {
    // Bug #63: invalid TOML used to silently return an empty table, which let
    // install_mcp_server wipe out the user's config. Now it must surface an
    // error so the caller refuses to overwrite.
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("bad.toml");
    std::fs::write(&path, "{{{{not valid toml").unwrap();
    assert!(
        load_toml_file(&path).is_err(),
        "unparseable TOML must surface as error, not silently empty"
    );
}

#[test]
fn test_load_toml_file_empty_file_returns_empty_table() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("empty.toml");
    std::fs::write(&path, "").unwrap();
    let val = load_toml_file(&path).expect("empty file should be treated as empty table");
    assert!(val.as_table().unwrap().is_empty());
}

#[test]
fn test_write_toml_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("output.toml");
    let mut table = toml::map::Map::new();
    table.insert("key".to_string(), toml::Value::String("value".to_string()));
    let val = toml::Value::Table(table);
    write_toml_file(&path, &val).unwrap();
    assert!(path.exists());
    let content = std::fs::read_to_string(&path).unwrap();
    assert!(content.contains("key"));
    assert!(content.contains("value"));
}

#[test]
fn test_write_toml_file_backs_up_existing() {
    // Issue #63: overwriting an existing config must always leave a .bak copy
    // so the user can recover if anything goes wrong.
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("config.toml");
    let original = "preserved = \"keep me\"\n";
    std::fs::write(&path, original).unwrap();

    let mut table = toml::map::Map::new();
    table.insert(
        "new".to_string(),
        toml::Value::String("content".to_string()),
    );
    write_toml_file(&path, &toml::Value::Table(table)).unwrap();

    let backup = dir.path().join("config.toml.bak");
    assert!(
        backup.exists(),
        "write must create a .bak of the prior file"
    );
    assert_eq!(
        std::fs::read_to_string(&backup).unwrap(),
        original,
        "the backup must contain the exact previous bytes"
    );
}

#[test]
fn test_write_toml_file_no_backup_when_no_prior_file() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("fresh.toml");
    let mut table = toml::map::Map::new();
    table.insert("k".to_string(), toml::Value::String("v".to_string()));
    write_toml_file(&path, &toml::Value::Table(table)).unwrap();

    let backup = dir.path().join("fresh.toml.bak");
    assert!(
        !backup.exists(),
        "no backup should be created on first write"
    );
}

// ---------------------------------------------------------------------------
// JSONC helpers
// ---------------------------------------------------------------------------

#[test]
fn test_load_jsonc_file_missing() {
    let val = load_jsonc_file(Path::new("/nonexistent/file.jsonc"));
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_load_jsonc_file_with_comments() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.jsonc");
    std::fs::write(
        &path,
        r#"{
        // This is a comment
        "key": "value", // trailing comment
        /* block comment */
        "number": 42,
    }"#,
    )
    .unwrap();
    let val = load_jsonc_file(&path);
    assert_eq!(val["key"], "value");
    assert_eq!(val["number"], 42);
}

#[test]
fn test_load_jsonc_file_strict_missing() {
    let result = load_jsonc_file_strict(Path::new("/nonexistent/file.jsonc"));
    assert!(result.is_ok());
}

#[test]
fn test_load_jsonc_file_strict_with_comments() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("test.jsonc");
    std::fs::write(
        &path,
        r#"{
        // comment
        "key": "value"
    }"#,
    )
    .unwrap();
    let val = load_jsonc_file_strict(&path).unwrap();
    assert_eq!(val["key"], "value");
}

#[test]
fn test_parse_jsonc() {
    let input = r#"{
        // line comment
        "a": 1,
        /* block */ "b": 2,
    }"#;
    let val = parse_jsonc(input);
    assert_eq!(val["a"], 1);
    assert_eq!(val["b"], 2);
}

// ---------------------------------------------------------------------------
// 7. is_detected / has_tokensave tests
// ---------------------------------------------------------------------------

#[test]
fn test_is_detected_claude() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!ClaudeIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".claude")).unwrap();
    assert!(ClaudeIntegration.is_detected(home));
}

#[test]
fn test_is_detected_codex() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!CodexIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".codex")).unwrap();
    assert!(CodexIntegration.is_detected(home));
}

#[test]
fn test_is_detected_gemini() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!GeminiIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".gemini")).unwrap();
    assert!(GeminiIntegration.is_detected(home));
}

#[test]
fn test_is_detected_cursor() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!CursorIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".cursor")).unwrap();
    assert!(CursorIntegration.is_detected(home));
}

#[test]
fn test_is_detected_opencode() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!OpenCodeIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".config/opencode")).unwrap();
    assert!(OpenCodeIntegration.is_detected(home));
}

#[test]
fn test_is_detected_zed() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!ZedIntegration.is_detected(home));
    #[cfg(target_os = "macos")]
    std::fs::create_dir_all(home.join("Library/Application Support/Zed")).unwrap();
    #[cfg(not(target_os = "macos"))]
    std::fs::create_dir_all(home.join(".config/zed")).unwrap();
    assert!(ZedIntegration.is_detected(home));
}

#[test]
fn test_is_detected_copilot() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    // Copilot is detected when either VS Code User dir or .copilot dir exists
    assert!(!CopilotIntegration.is_detected(home));
    std::fs::create_dir_all(home.join(".copilot")).unwrap();
    assert!(CopilotIntegration.is_detected(home));
}

#[test]
fn test_has_tokensave_claude() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    // No config => false
    assert!(!ClaudeIntegration.has_tokensave(home));

    // After install => true
    let ctx = make_install_ctx(home);
    ClaudeIntegration.install(&ctx).unwrap();
    assert!(ClaudeIntegration.has_tokensave(home));

    // After uninstall => false
    ClaudeIntegration.uninstall(&ctx).unwrap();
    assert!(!ClaudeIntegration.has_tokensave(home));
}

#[test]
fn test_has_tokensave_gemini() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!GeminiIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    GeminiIntegration.install(&ctx).unwrap();
    assert!(GeminiIntegration.has_tokensave(home));
}

#[test]
fn test_has_tokensave_codex() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!CodexIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    CodexIntegration.install(&ctx).unwrap();
    assert!(home.join(".codex/config.toml").exists());
    assert!(
        CodexIntegration.has_tokensave(home),
        "has_tokensave should detect tokensave after a clean install"
    );
}

#[test]
fn test_has_tokensave_cursor() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!CursorIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    CursorIntegration.install(&ctx).unwrap();
    assert!(CursorIntegration.has_tokensave(home));
}

#[test]
fn test_has_tokensave_opencode() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!OpenCodeIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    OpenCodeIntegration.install(&ctx).unwrap();
    assert!(OpenCodeIntegration.has_tokensave(home));
}

#[test]
fn test_has_tokensave_copilot() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    assert!(!CopilotIntegration.has_tokensave(home));

    let ctx = make_install_ctx(home);
    CopilotIntegration.install(&ctx).unwrap();
    assert!(CopilotIntegration.has_tokensave(home));
}

// ---------------------------------------------------------------------------
// 8. Idempotency tests
// ---------------------------------------------------------------------------

#[test]
fn test_claude_install_idempotent() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    // Install twice should not fail
    ClaudeIntegration.install(&ctx).unwrap();
    ClaudeIntegration.install(&ctx).unwrap();

    // Config should still be valid
    let claude_json: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap()).unwrap();
    assert!(claude_json["mcpServers"]["tokensave"].is_object());
}

#[test]
fn test_gemini_install_idempotent() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    GeminiIntegration.install(&ctx).unwrap();
    GeminiIntegration.install(&ctx).unwrap();

    let settings: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(home.join(".gemini/settings.json")).unwrap())
            .unwrap();
    assert!(settings["mcpServers"]["tokensave"].is_object());
}

#[test]
fn test_uninstall_without_install_does_not_crash() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let ctx = make_install_ctx(home);

    // Uninstalling when nothing is installed should not panic or error
    ClaudeIntegration.uninstall(&ctx).unwrap();
    GeminiIntegration.uninstall(&ctx).unwrap();
    CodexIntegration.uninstall(&ctx).unwrap();
    CursorIntegration.uninstall(&ctx).unwrap();
    CopilotIntegration.uninstall(&ctx).unwrap();
    OpenCodeIntegration.uninstall(&ctx).unwrap();
    ZedIntegration.uninstall(&ctx).unwrap();
    ClineIntegration.uninstall(&ctx).unwrap();
    RooCodeIntegration.uninstall(&ctx).unwrap();
    KiroIntegration.uninstall(&ctx).unwrap();
    VibeIntegration.uninstall(&ctx).unwrap();
}

// ---------------------------------------------------------------------------
// 9. Install preserves existing config
// ---------------------------------------------------------------------------

#[test]
fn test_claude_install_preserves_existing_claude_json() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Pre-populate .claude.json with other data
    let claude_json_path = home.join(".claude.json");
    std::fs::write(
        &claude_json_path,
        r#"{"mcpServers": {"other-server": {"command": "foo"}}, "customKey": 42}"#,
    )
    .unwrap();

    let ctx = make_install_ctx(home);
    ClaudeIntegration.install(&ctx).unwrap();

    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&claude_json_path).unwrap()).unwrap();
    // tokensave added
    assert!(content["mcpServers"]["tokensave"].is_object());
    // existing server preserved
    assert!(content["mcpServers"]["other-server"].is_object());
    // custom key preserved
    assert_eq!(content["customKey"], 42);
}

#[test]
fn test_gemini_install_preserves_existing_settings() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    let settings_path = home.join(".gemini/settings.json");
    std::fs::create_dir_all(home.join(".gemini")).unwrap();
    std::fs::write(
        &settings_path,
        r#"{"mcpServers": {"other": {"command": "bar"}}, "theme": "dark"}"#,
    )
    .unwrap();

    let ctx = make_install_ctx(home);
    GeminiIntegration.install(&ctx).unwrap();

    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&settings_path).unwrap()).unwrap();
    assert!(content["mcpServers"]["tokensave"].is_object());
    assert!(content["mcpServers"]["other"].is_object());
    assert_eq!(content["theme"], "dark");
}

// ---------------------------------------------------------------------------
// 10. Constants sanity
// ---------------------------------------------------------------------------

#[test]
fn test_tool_names_not_empty() {
    let names = tool_names();
    assert!(!names.is_empty());
    for name in &names {
        assert!(
            name.starts_with("tokensave_"),
            "tool name should start with tokensave_: {name}"
        );
    }
}

#[test]
fn test_read_only_tool_names_excludes_mutating_tools() {
    let read_only = read_only_tool_names();
    let read_only_set: std::collections::HashSet<&str> =
        read_only.iter().map(String::as_str).collect();
    let known_tools: std::collections::HashSet<String> = tool_names().into_iter().collect();
    assert!(!read_only.is_empty());

    for name in &read_only {
        assert!(
            known_tools.contains(name),
            "read-only tool should be a known MCP tool: {name}"
        );
    }

    for mutating in [
        "tokensave_str_replace",
        "tokensave_multi_str_replace",
        "tokensave_insert_at",
        "tokensave_ast_grep_rewrite",
        "tokensave_session_start",
        "tokensave_session_end",
        "tokensave_record_decision",
        "tokensave_record_code_area",
    ] {
        assert!(
            !read_only_set.contains(mutating),
            "mutating tool should not be read-only: {mutating}"
        );
    }
}

#[test]
fn test_expected_tool_perms_not_empty() {
    let perms = expected_tool_perms();
    assert!(!perms.is_empty());
    for perm in &perms {
        assert!(
            perm.starts_with("mcp__tokensave__"),
            "tool perm should start with mcp__tokensave__: {perm}"
        );
    }
}

#[test]
fn test_tool_perms_match_tool_names() {
    let names = tool_names();
    let perms = expected_tool_perms();
    assert_eq!(
        names.len(),
        perms.len(),
        "tool_names and expected_tool_perms should have same length"
    );
    for name in &names {
        let expected_perm = format!("mcp__tokensave__{name}");
        assert!(
            perms.contains(&expected_perm),
            "missing permission for tool {name}: expected {expected_perm}"
        );
    }
}

// ---------------------------------------------------------------------------
// 11. restore_config_backup
// ---------------------------------------------------------------------------

#[test]
fn test_restore_config_backup_restores_content() {
    let dir = TempDir::new().unwrap();
    let original_path = dir.path().join("config.json");
    let backup_path = dir.path().join("config.json.bak");

    // Create original and backup
    std::fs::write(&original_path, r#"{"version": 1}"#).unwrap();
    std::fs::write(&backup_path, r#"{"version": 1}"#).unwrap();

    // Corrupt the original
    std::fs::write(&original_path, "CORRUPTED").unwrap();

    // Restore from backup
    restore_config_backup(&original_path, &backup_path);

    let restored = std::fs::read_to_string(&original_path).unwrap();
    assert_eq!(
        restored, r#"{"version": 1}"#,
        "restored content should match the backup"
    );
}

#[test]
fn test_restore_config_backup_to_missing_original() {
    let dir = TempDir::new().unwrap();
    let original_path = dir.path().join("config.json");
    let backup_path = dir.path().join("config.json.bak");

    // Only create backup, not original
    std::fs::write(&backup_path, r#"{"saved": true}"#).unwrap();

    restore_config_backup(&original_path, &backup_path);

    assert!(
        original_path.exists(),
        "original should be created from backup"
    );
    let content = std::fs::read_to_string(&original_path).unwrap();
    assert_eq!(content, r#"{"saved": true}"#);
}

#[test]
fn test_restore_config_backup_missing_backup_does_not_panic() {
    let dir = TempDir::new().unwrap();
    let original_path = dir.path().join("config.json");
    let backup_path = dir.path().join("config.json.bak");

    std::fs::write(&original_path, "original").unwrap();

    // Restore with a nonexistent backup — should not panic
    restore_config_backup(&original_path, &backup_path);

    // Original should remain untouched since backup failed
    let content = std::fs::read_to_string(&original_path).unwrap();
    assert_eq!(content, "original");
}

// ---------------------------------------------------------------------------
// 12. which_tokensave
// ---------------------------------------------------------------------------

#[test]
fn test_which_tokensave_returns_some_or_none() {
    // which_tokensave checks current_exe and PATH — we just verify it
    // doesn't panic and returns a sensible result.
    let result = which_tokensave();
    // In a test environment, the current exe is the test runner, not tokensave,
    // so it may return None (unless tokensave is on PATH). Either way, no panic.
    if let Some(ref path) = result {
        assert!(!path.is_empty(), "path should not be empty if Some");
    }
    // Test passes regardless of Some or None — just ensures no panic.
}

// ---------------------------------------------------------------------------
// 13. home_dir
// ---------------------------------------------------------------------------

#[test]
fn test_home_dir_returns_some() {
    let result = home_dir();
    assert!(
        result.is_some(),
        "home_dir should return Some on most systems"
    );
    let home = result.unwrap();
    assert!(home.is_absolute(), "home dir should be an absolute path");
}

// ---------------------------------------------------------------------------
// 14. migrate_installed_agents
// ---------------------------------------------------------------------------

#[test]
fn test_migrate_installed_agents_skips_when_already_populated() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let mut config = tokensave::user_config::UserConfig::default();
    config.installed_agents = vec!["claude".to_string()];

    // Should return immediately since installed_agents is non-empty
    migrate_installed_agents(home, &mut config);

    // The existing list should be unchanged
    assert_eq!(config.installed_agents, vec!["claude".to_string()]);
}

#[test]
fn test_migrate_installed_agents_detects_installed_agents() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Install copilot so it can be detected
    let ctx = make_install_ctx(home);
    CopilotIntegration.install(&ctx).unwrap();

    let mut config = tokensave::user_config::UserConfig::default();
    assert!(config.installed_agents.is_empty());

    // migrate will scan and detect copilot is installed
    // Note: save() will try to write to ~/.tokensave/config.toml which may fail
    // in CI, but the function still populates installed_agents in memory.
    migrate_installed_agents(home, &mut config);

    assert!(
        config.installed_agents.contains(&"copilot".to_string()),
        "copilot should be detected, got: {:?}",
        config.installed_agents
    );
}

#[test]
fn test_migrate_installed_agents_empty_home_no_change() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();
    let mut config = tokensave::user_config::UserConfig::default();

    migrate_installed_agents(home, &mut config);

    // No agents installed in empty home, list should remain empty
    assert!(
        config.installed_agents.is_empty(),
        "installed_agents should remain empty when no agents detected"
    );
}

// ---------------------------------------------------------------------------
// 15. pick_integrations_interactive (no-agent-detected error path)
// ---------------------------------------------------------------------------

#[test]
fn test_pick_integrations_interactive_no_agents_detected() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Empty home — no agents detected
    let result = pick_integrations_interactive(home, &[]);
    assert!(
        result.is_err(),
        "pick_integrations_interactive should error when no agents detected"
    );

    let err_msg = format!("{}", result.unwrap_err());
    assert!(
        err_msg.contains("No supported agents detected"),
        "error should mention no agents detected, got: {err_msg}"
    );
}

#[test]
fn test_pick_integrations_interactive_single_uninstalled_agent() {
    let dir = TempDir::new().unwrap();
    let home = dir.path();

    // Create only the .copilot dir so exactly one agent is detected
    std::fs::create_dir_all(home.join(".copilot")).unwrap();

    // Single detected agent that is NOT installed => fast path returns it directly
    let result = pick_integrations_interactive(home, &[]);
    assert!(
        result.is_ok(),
        "should succeed with single uninstalled agent"
    );
    let (to_install, to_uninstall) = result.unwrap();
    assert_eq!(to_install, vec!["copilot".to_string()]);
    assert!(to_uninstall.is_empty());
}

// ---------------------------------------------------------------------------
// 16. vscode_data_dir / copilot_cli_dir
// ---------------------------------------------------------------------------

#[test]
fn test_vscode_data_dir_is_under_home() {
    let home = Path::new("/fake/home");
    let dir = tokensave::agents::vscode_data_dir(home);
    assert!(
        dir.starts_with("/fake/home"),
        "vscode_data_dir should be under home: {}",
        dir.display()
    );
}

#[test]
fn test_copilot_cli_dir_is_under_home() {
    let home = Path::new("/fake/home");
    let dir = tokensave::agents::copilot_cli_dir(home);
    assert_eq!(
        dir,
        Path::new("/fake/home/.copilot"),
        "copilot_cli_dir should be home/.copilot"
    );
}

// ---------------------------------------------------------------------------
// 17. parse_jsonc edge cases
// ---------------------------------------------------------------------------

#[test]
fn test_parse_jsonc_empty_string() {
    let val = parse_jsonc("");
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_parse_jsonc_only_comments() {
    let input = "// just a comment\n/* block */\n";
    let val = parse_jsonc(input);
    assert!(val.is_object());
    assert!(val.as_object().unwrap().is_empty());
}

#[test]
fn test_parse_jsonc_nested_comments() {
    let input = r#"{
        "a": "hello // not a comment",
        /* this is a real comment */
        "b": true
    }"#;
    let val = parse_jsonc(input);
    assert_eq!(val["a"].as_str().unwrap(), "hello // not a comment");
    assert_eq!(val["b"], true);
}

#[test]
fn test_parse_jsonc_trailing_comma_in_object() {
    let input = r#"{"a": 1, "b": 2,}"#;
    let val = parse_jsonc(input);
    assert_eq!(val["a"], 1);
    assert_eq!(val["b"], 2);
}

#[test]
fn test_parse_jsonc_trailing_comma_in_array() {
    let input = r#"{"arr": [1, 2, 3,]}"#;
    let val = parse_jsonc(input);
    let arr = val["arr"].as_array().unwrap();
    assert_eq!(arr.len(), 3);
}

// ---------------------------------------------------------------------------
// 18. backup + safe_write round-trip
// ---------------------------------------------------------------------------

#[test]
fn test_backup_and_safe_write_round_trip() {
    let dir = TempDir::new().unwrap();
    let path = dir.path().join("roundtrip.json");

    // Create initial file
    let initial = serde_json::json!({"name": "tokensave", "version": 1});
    safe_write_json_file(&path, &initial, None).unwrap();

    // Create backup
    let backup = backup_config_file(&path).unwrap();
    assert!(backup.is_some());
    let backup_path = backup.unwrap();

    // Overwrite with new content
    let updated = serde_json::json!({"name": "tokensave", "version": 2});
    safe_write_json_file(&path, &updated, Some(&backup_path)).unwrap();

    // Verify new content
    let content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(content["version"], 2);

    // Verify backup still has old content
    let backup_content: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&backup_path).unwrap()).unwrap();
    assert_eq!(backup_content["version"], 1);

    // Restore from backup
    restore_config_backup(&path, &backup_path);
    let restored: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
    assert_eq!(restored["version"], 1);
}