swapdex 0.167.9

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

fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_swapdex")
}

// A fake `claude` that prints the CLAUDE_CONFIG_DIR it was launched with, then
// prints any args. `swapdex run` exec's it, so its stdout is what we capture.
fn fake_claude(root: &Path) -> std::path::PathBuf {
    let dir = root.join("fakebin");
    std::fs::create_dir_all(&dir).unwrap();
    let f = dir.join("claude");
    std::fs::write(
        &f,
        "#!/bin/sh\necho \"CFG=$CLAUDE_CONFIG_DIR\"\necho \"SECURE=${CLAUDE_SECURESTORAGE_CONFIG_DIR-unset}\"\necho \"ARGS=$*\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
    dir
}

#[test]
fn run_launches_claude_in_the_accounts_slot() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = Command::new(bin())
        .args(["run", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    // The slot dir was created under the store and passed as CLAUDE_CONFIG_DIR.
    let slots = root.path().join(".local/share/swapdex/slots");
    assert!(
        o.lines()
            .any(|l| l.starts_with("CFG=") && l.contains(slots.to_str().unwrap())),
        "claude launched with the slot as CLAUDE_CONFIG_DIR: {o}"
    );
}

#[test]
fn managed_claude_run_clears_a_conflicting_secure_storage_override() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let conflicting = root.path().join("different-claude-login");
    let out = Command::new(bin())
        .args(["run", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .env("CLAUDE_SECURESTORAGE_CONFIG_DIR", &conflicting)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "{stdout}");
    assert!(
        stdout.lines().any(|line| line == "SECURE=unset"),
        "managed Claude must use the selected slot's config: {stdout}"
    );
}

#[test]
fn run_forwards_extra_args_after_dash_dash() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = Command::new(bin())
        .args(["run", "work", "--", "--resume", "abc"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.lines()
            .any(|l| l.starts_with("ARGS=") && l.contains("--resume abc")),
        "extra args are forwarded to claude: {o}"
    );
}

#[test]
fn slots_lists_created_slots() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    // `run` creates the slot; then `slots` should list it.
    Command::new(bin())
        .args(["run", "work"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .output()
        .unwrap();
    let out = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(o.contains("work"), "the slot is listed: {o}");
}

#[test]
fn slots_empty_state_is_friendly() {
    let root = tempfile::tempdir().unwrap();
    let out = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    // "Slot" is the internal name for an account's own space; a person reading
    // the screen should only ever see "account".
    assert!(
        o.to_lowercase().contains("no accounts yet"),
        "empty-state hint: {o}"
    );
    assert!(!o.to_lowercase().contains("slot"), "no jargon: {o}");
}

fn run_in(root: &Path, args: &[&str], path_env: &str) -> String {
    // HOME must point inside the temp root. `swapdex shim` offers to put itself
    // on PATH by editing the shell profile of $HOME, and without this a test run
    // appended an export line - naming a temp dir that is deleted moments later -
    // to the developer's own ~/.bashrc.
    let home = root.join("home");
    std::fs::create_dir_all(&home).unwrap();
    let out = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("PATH", path_env)
        .env("HOME", &home)
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout).into_owned()
}

// End-to-end: `run` makes a slot, `use` repoints the default (no copy), the
// installed shim launches a plain `claude` in that default slot.
#[test]
fn shim_makes_plain_claude_follow_use() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    // Create the slot and set it as the default account.
    run_in(root.path(), &["run", "work"], &path);
    let used = run_in(root.path(), &["use", "work"], &path);
    assert!(
        // The tool is named now that Claude and Codex both switch by pointer.
        used.contains("default claude account -> work"),
        "use repoints: {used}"
    );
    // This fixture deliberately has no login, so direct passthrough is the only
    // authorized route. A failed managed proxy start must no longer launch the
    // native client implicitly.
    run_in(root.path(), &["serve", "--off"], &path);
    // Install the shim (finds the fake claude on PATH as the real one).
    let installed = run_in(root.path(), &["shim"], &path);
    assert!(
        installed.contains("installed the claude shim"),
        "{installed}"
    );
    // Run the shim directly; it should exec the fake claude with the slot dir.
    // With the test's own environment: the shim asks swapdex for a proxy, and
    // without SWAPDEX_ROOT that question is asked of the DEVELOPER's real store -
    // which answered by starting a daemon against their real accounts, on the
    // default port, outliving the test.
    let home = root.path().join("home");
    std::fs::create_dir_all(&home).unwrap();
    let shim = root.path().join(".local/share/swapdex/bin/claude");
    let out = Command::new(&shim)
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .env("HOME", &home)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    let slots = root.path().join(".local/share/swapdex/slots");
    assert!(
        o.lines()
            .any(|l| l.starts_with("CFG=") && l.contains(slots.to_str().unwrap())),
        "the shim launched claude in the default account's slot: {o}"
    );
    // Stop whatever proxy the shim started for this temp store.
    if let Ok(marker) = std::fs::read_to_string(root.path().join(".local/share/swapdex/proxy")) {
        if let Some(pid) = marker
            .split_whitespace()
            .next()
            .and_then(|p| p.parse::<i32>().ok())
        {
            unsafe { libc::kill(pid, libc::SIGTERM) };
        }
    }
}

#[test]
fn use_on_a_slot_does_not_touch_the_copy_model_credentials() {
    // A slot `use` must not read/write ~/.claude - it only sets the pointer.
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work"], &path);
    run_in(root.path(), &["use", "work"], &path);
    // No live Claude credential file was created by the switch.
    assert!(
        !root.path().join(".claude/.credentials.json").exists(),
        "slot use writes no credential"
    );
    // The pointer holds the slot dir.
    let ptr =
        std::fs::read_to_string(root.path().join(".local/share/swapdex/active-claude")).unwrap();
    assert!(ptr.contains("/slots/"), "pointer points at a slot: {ptr}");
}

#[test]
fn adopt_registers_an_existing_config_dir() {
    let root = tempfile::tempdir().unwrap();
    let existing = root.path().join("dot-claude-company");
    std::fs::create_dir_all(&existing).unwrap();
    let out = Command::new(bin())
        .args(["adopt", "company", existing.to_str().unwrap()])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(o.contains("registered 'company'"), "{o}");
    // It now shows up in the slot list.
    let listed = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert!(String::from_utf8_lossy(&listed.stdout).contains("company"));
}

// Seed a legacy copy-model Claude profile named `name` in the store.
fn seed_copy_profile(root: &Path, name: &str) {
    let d = root
        .join(".local/share/swapdex/accounts")
        .join(name)
        .join("claude-code");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("credentials"),
        br#"{"claudeAiOauth":{"accessToken":"A","refreshToken":"R"}}"#,
    )
    .unwrap();
    std::fs::write(
        d.join("oauth_account"),
        br#"{"accountUuid":"u","emailAddress":"a@x.com"}"#,
    )
    .unwrap();
}

#[test]
fn migrate_gives_each_legacy_profile_a_slot() {
    let root = tempfile::tempdir().unwrap();
    seed_copy_profile(root.path(), "work");
    seed_copy_profile(root.path(), "home");
    let out = Command::new(bin())
        .args(["migrate"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains("work") && o.contains("home"),
        "migrated both: {o}"
    );
    // Both are now slots.
    let listed = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let l = String::from_utf8_lossy(&listed.stdout);
    assert!(
        l.contains("work") && l.contains("home"),
        "listed as slots: {l}"
    );
    // Re-running is idempotent (nothing left to migrate).
    let again = Command::new(bin())
        .args(["migrate"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&again.stdout)
            .to_lowercase()
            .contains("nothing to migrate"),
        "idempotent"
    );
}

/// A legacy profile carrying a name no creator will accept must not take the
/// rest of the migration down with it.
///
/// `migrate` already renames a profile whose name a creator would refuse - a
/// tool-home name, or one a slot already holds - via `suggest_non_colliding`.
/// `-` is refused for the same kind of reason (`use -` toggles), and it is
/// neither of those two, so it reached `create_initialized` and the `?` there
/// aborted the whole command: every profile after it in the sweep was skipped.
#[test]
fn migrate_renames_a_legacy_profile_whose_name_no_creator_accepts() {
    let root = tempfile::tempdir().unwrap();
    // "-" sorts before "work", so an abort here loses "work" too.
    seed_copy_profile(root.path(), "-");
    seed_copy_profile(root.path(), "work");
    let out = Command::new(bin())
        .args(["migrate"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    let e = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "migrate failed: {o}{e}");

    // The profile after the bad name still got its slot.
    let listed = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let l = String::from_utf8_lossy(&listed.stdout);
    assert!(l.contains("work"), "later profile was skipped: {l}");

    // And the refused name was renamed, not registered.
    let rows: Vec<serde_json::Value> =
        std::fs::read(root.path().join(".local/share/swapdex/slots.json"))
            .ok()
            .and_then(|b| serde_json::from_slice(&b).ok())
            .unwrap_or_default();
    assert!(
        rows.iter().any(|r| r["name"] == "account"),
        "the refused name was not renamed: {rows:?}"
    );
}

/// The sign-in line migrate prints has to be a line that runs.
///
/// Every remedy this tool prints - about thirty of them - puts the slot name
/// where clap expects a positional, so a name beginning with `-` is read there
/// as an option and the command exits 2 before it reaches the account. Nothing
/// refused such a name where an account is born, so migrate registered it and
/// then handed out a command that cannot work.
#[test]
fn the_sign_in_line_migrate_prints_can_be_run() {
    let root = tempfile::tempdir().unwrap();
    seed_copy_profile(root.path(), "-x");
    let out = Command::new(bin())
        .args(["migrate"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    let e = String::from_utf8_lossy(&out.stderr);
    assert_eq!(out.status.code(), Some(0), "migrate failed: {o}{e}");

    let line = o
        .lines()
        .map(str::trim)
        .find(|l| l.starts_with("swapdex run "))
        .unwrap_or_else(|| panic!("migrate printed no sign-in line: {o}"));
    let args: Vec<&str> = line.split_whitespace().skip(1).collect();

    let ran = Command::new(bin())
        .args(&args)
        .arg("--no-launch")
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(
        ran.status.code(),
        Some(0),
        "the line migrate printed does not run: `{line}`\n{}{}",
        String::from_utf8_lossy(&ran.stdout),
        String::from_utf8_lossy(&ran.stderr)
    );
}

#[test]
fn doctor_reports_slots_default_and_shim() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work"], &path);
    run_in(root.path(), &["use", "work"], &path);
    let out = Command::new(bin())
        .args(["doctor"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains("slots") && o.contains("account(s)"),
        "slots line: {o}"
    );
    assert!(
        o.contains("default") && o.contains("work"),
        "default line: {o}"
    );
    assert!(o.contains("shim"), "shim line: {o}");
}

#[test]
fn new_slot_symlinks_shared_config_from_bare_claude() {
    let root = tempfile::tempdir().unwrap();
    // Bare ~/.claude with shared config the new slot should inherit.
    let bare = root.path().join(".claude");
    std::fs::create_dir_all(&bare).unwrap();
    std::fs::write(bare.join("settings.json"), b"{\"theme\":\"dark\"}").unwrap();
    std::fs::write(bare.join("CLAUDE.md"), b"# global rules").unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work"], &path);
    // The slot got symlinks to the shared files (same contents), but NOT a token.
    let slots = root.path().join(".local/share/swapdex/slots");
    let slot = std::fs::read_dir(&slots)
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path();
    assert_eq!(
        std::fs::read_to_string(slot.join("settings.json")).unwrap(),
        "{\"theme\":\"dark\"}",
        "settings shared into the slot"
    );
    assert!(slot.join("CLAUDE.md").exists(), "global memory shared");
    assert!(
        std::fs::symlink_metadata(slot.join("settings.json"))
            .unwrap()
            .file_type()
            .is_symlink(),
        "shared via symlink, not a copy"
    );
}

#[test]
fn onboard_registers_config_dirs_and_migrates_profiles() {
    let root = tempfile::tempdir().unwrap();
    // State 3: an existing ~/.claude-company dir. State 2: a legacy copy profile.
    std::fs::create_dir_all(root.path().join(".claude-company")).unwrap();
    seed_copy_profile(root.path(), "work");
    let out = Command::new(bin())
        .args(["onboard"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn_with_input("y\ny\nn\n");
    // Both an adopted slot and a migrated slot now exist.
    let listed = Command::new(bin())
        .args(["slots"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let l = String::from_utf8_lossy(&listed.stdout);
    assert!(
        l.contains("company"),
        "adopted the config dir: {l} / onboard out: {out}"
    );
    assert!(l.contains("work"), "migrated the legacy profile: {l}");
}

// Small helper: run with piped stdin, return stdout.
trait SpawnWithInput {
    fn spawn_with_input(&mut self, input: &str) -> String;
}
impl SpawnWithInput for Command {
    fn spawn_with_input(&mut self, input: &str) -> String {
        use std::io::Write;
        let mut child = self.spawn().unwrap();
        child
            .stdin
            .as_mut()
            .unwrap()
            .write_all(input.as_bytes())
            .unwrap();
        let out = child.wait_with_output().unwrap();
        String::from_utf8_lossy(&out.stdout).into_owned()
    }
}

#[test]
fn onboard_marks_itself_done_so_it_does_not_nag() {
    let root = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(root.path().join(".claude-company")).unwrap();
    // Before onboarding, the marker is absent (bare `swapdex` would offer it).
    let marker = root.path().join(".local/share/swapdex/onboarded");
    assert!(!marker.exists());
    // Run onboard (decline everything); it should still mark itself shown.
    Command::new(bin())
        .args(["onboard"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .spawn_with_input("n\nn\n");
    assert!(marker.exists(), "onboarding marks itself done");
}

#[test]
fn sync_mcp_shares_servers_into_slots_preserving_identity() {
    let root = tempfile::tempdir().unwrap();
    // Source: bare ~/.claude.json with mcpServers.
    std::fs::write(
        root.path().join(".claude.json"),
        br#"{"oauthAccount":{"emailAddress":"bare@x.com"},"mcpServers":{"ctx7":{"command":"c"}}}"#,
    )
    .unwrap();
    // A slot that has already "logged in" (its own .claude.json with a different account, no MCP).
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work"], &path);
    let slots = root.path().join(".local/share/swapdex/slots");
    let slot = std::fs::read_dir(&slots)
        .unwrap()
        .next()
        .unwrap()
        .unwrap()
        .path();
    std::fs::write(
        slot.join(".claude.json"),
        br#"{"oauthAccount":{"emailAddress":"work@x.com"},"mcpServers":{}}"#,
    )
    .unwrap();
    // Sync: the slot gets the shared MCP but keeps its own account.
    let out = Command::new(bin())
        .args(["sync-mcp"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&out.stdout).contains("1 MCP server"),
        "{}",
        String::from_utf8_lossy(&out.stdout)
    );
    let cfg: serde_json::Value =
        serde_json::from_slice(&std::fs::read(slot.join(".claude.json")).unwrap()).unwrap();
    assert!(
        cfg["mcpServers"]["ctx7"].is_object(),
        "shared MCP landed in the slot"
    );
    assert_eq!(
        cfg["oauthAccount"]["emailAddress"], "work@x.com",
        "slot's own account preserved"
    );
}

// doctor: per-slot login health. A slot that was never signed into and a slot
// whose login sat unrefreshed past the stale window are each named with the
// one next step; a slot whose access token expired ROUTINELY (hours ago -
// Claude refreshes that silently on the next run) is NOT flagged, or doctor
// would cry "expired" every day. Read-only: doctor never writes a slot.
#[test]
fn doctor_flags_slots_without_login_and_stale_logins() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    for name in ["empty", "old", "recent", "corrupt"] {
        run_in(root.path(), &["run", name], &path);
    }
    // Slot dirs from the `slots` listing lines: "  <name>  <dir>".
    let listing = run_in(root.path(), &["slots"], &path);
    let dir_of = |name: &str| -> std::path::PathBuf {
        listing
            .lines()
            .find_map(|l| {
                l.trim()
                    .strip_prefix(name)
                    .map(|rest| std::path::PathBuf::from(rest.trim()))
            })
            .unwrap_or_else(|| panic!("slot '{name}' in listing: {listing}"))
    };
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let creds = |expires_ms: i64| {
        format!(
            "{{\"claudeAiOauth\":{{\"accessToken\":\"AT\",\"refreshToken\":\"RT\",\
             \"expiresAt\":{expires_ms}}}}}"
        )
    };
    // 'old': expired 40 days ago - the refresh token itself may be revoked.
    std::fs::write(
        dir_of("old").join(".credentials.json"),
        creds(now_ms - 40 * 86_400_000),
    )
    .unwrap();
    // 'recent': expired 2 hours ago - routine, silently refreshed on next run.
    std::fs::write(
        dir_of("recent").join(".credentials.json"),
        creds(now_ms - 2 * 3_600_000),
    )
    .unwrap();
    // 'corrupt': a login artifact EXISTS but is unparseable - not "no login".
    std::fs::write(dir_of("corrupt").join(".credentials.json"), b"not json").unwrap();
    // 0600, the way swapdex and the tools themselves write a credential. A
    // fixture at the default mode trips doctor's permission check, which is
    // doctor being right rather than the check being wrong.
    {
        use std::os::unix::fs::PermissionsExt;
        for n in ["old", "recent", "corrupt"] {
            let f = dir_of(n).join(".credentials.json");
            if f.exists() {
                std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o600)).unwrap();
            }
        }
    }
    // PATH holds ONLY the fake tool dir. doctor now reports how many swapdex
    // copies are reachable, and inheriting the developer's PATH would make that
    // answer - and this test - depend on whose machine it runs on.
    let out = Command::new(bin())
        .args(["doctor"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", bin_dir.display().to_string())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(out.status.success(), "informational, stays exit 0: {o}");
    assert!(
        o.contains("slot:empty") && o.contains("swapdex run empty"),
        "never-signed-in slot named with the run remedy: {o}"
    );
    assert!(
        o.contains("slot:old") && o.contains("swapdex run old"),
        "long-idle slot named with the run remedy: {o}"
    );
    assert!(
        !o.contains("slot:recent"),
        "routinely-expired slot is not flagged: {o}"
    );
    assert!(
        !o.contains("slot:corrupt"),
        "a PRESENT but unparseable credential is not 'no login yet' - doctor \
         only flags what it can determine: {o}"
    );
}

// doctor: an installed shim that PATH never reaches is a trap - it LOOKS set
// up while a plain `claude` still runs bare, so `swapdex use` silently does
// nothing (the pointer flips but nothing reads it). doctor must say the shim
// is not taking effect (with the PATH fix), and call it active only when the
// shim really is what a plain `claude` resolves to.
#[test]
fn doctor_detects_shim_bypassed_and_active() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work"], &path);
    run_in(root.path(), &["shim"], &path);
    // Shim dir NOT on PATH, but `swapdex shim` just edited the shell profile:
    // the setup IS right, this shell simply predates the edit. Saying "add it to
    // PATH" here sends someone to do what was already done, so doctor names the
    // profile and says to open a new terminal - and does NOT count it a problem.
    let out = run_in(root.path(), &["doctor"], &path);
    assert!(
        out.contains("not on THIS shell's PATH") && out.contains("open a new terminal"),
        "a shell predating the profile edit is not a broken setup: {out}"
    );
    assert!(
        !out.contains("shim          problem"),
        "and it is not counted as a fault: {out}"
    );

    // Nothing configuring it anywhere IS a real finding, with the PATH fix.
    let profile = root.path().join(".bashrc");
    if profile.exists() {
        std::fs::write(&profile, "").unwrap();
    }
    let out = run_in(root.path(), &["doctor"], &path);
    assert!(
        out.contains("NOT taking effect") && out.contains("PATH"),
        "an unconfigured shim is still called out with the PATH fix: {out}"
    );
    // Shim dir FIRST on PATH: the shim genuinely intercepts a plain `claude`.
    let shim_first = format!(
        "{}:{}",
        root.path().join(".local/share/swapdex/bin").display(),
        path
    );
    let out = run_in(root.path(), &["doctor"], &shim_first);
    assert!(
        out.contains("shim active"),
        "engaged shim reported active: {out}"
    );
}

// `swapdex auto` is the setting proxy mode reads, so it must persist and be
// readable back - and reject anything that is not on/off rather than guessing.
#[test]
fn auto_setting_round_trips_and_rejects_nonsense() {
    let root = tempfile::tempdir().unwrap();
    let path = std::env::var("PATH").unwrap_or_default();
    assert!(
        run_in(root.path(), &["auto"], &path).contains("off"),
        "off until asked for"
    );
    assert!(run_in(root.path(), &["auto", "on"], &path).contains("on"));
    assert!(
        run_in(root.path(), &["auto"], &path).contains("on"),
        "the setting persisted"
    );
    assert!(run_in(root.path(), &["auto", "off"], &path).contains("off"));
    let out = Command::new(bin())
        .args(["auto", "sometimes"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(2), "a bad value is refused");
}

/// `--names` could not see a slot account, which `use` accepts.
///
/// The docs call it the form "for scripts and completion". It printed
/// `store.list()` and returned before the block that merges slot accounts into
/// the listing - so the human `ls` showed the account, `use <name>` switched to
/// it, and the one form written for tab-completion left it out. Every account
/// made by `swapdex run <name>` is exactly that shape.
#[test]
fn names_lists_the_accounts_use_accepts() {
    let root = tempfile::tempdir().unwrap();
    let dir = root.path().join("slotdir");
    std::fs::create_dir_all(&dir).unwrap();
    seed_copy_profile(root.path(), "saved");
    let path = std::env::var("PATH").unwrap_or_default();
    run_in(
        root.path(),
        &["adopt", "slotonly", dir.to_str().unwrap()],
        &path,
    );

    // Precondition: it is a real account - `use` takes it, an invented name is 5.
    let used = Command::new(bin())
        .args(["use", "slotonly"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(used.status.code(), Some(0), "the slot account is usable");

    let names = run_in(root.path(), &["ls", "--names"], &path);
    assert!(names.contains("saved"), "the profile: {names}");
    assert!(
        names.lines().any(|l| l.trim() == "slotonly"),
        "and the slot account completion would need: {names}"
    );
}

/// `status --json` called a healthy login expired, nearly always.
///
/// A Claude access token lives about an hour and the tool refreshes it silently.
/// Two paths learned that - `ls`'s marker ("this was the constant 'expired'
/// spam") and `status`'s own note - and both only speak past STALE_DAYS. The
/// JSON kept the literal `expires_at < now`, so for most of every hour it
/// reported `"expired": true` about an account that was working, while the
/// human line right beside it said nothing was wrong.
#[test]
fn the_json_status_does_not_call_an_hourly_refresh_expired() {
    let root = tempfile::tempdir().unwrap();
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    std::fs::create_dir_all(root.path().join(".claude")).unwrap();
    // The ordinary state: lapsed an hour ago, refreshes by itself.
    std::fs::write(
        root.path().join(".claude/.credentials.json"),
        format!(
            r#"{{"claudeAiOauth":{{"accessToken":"T","expiresAt":{},"subscriptionType":"max"}}}}"#,
            now_ms - 3_600_000
        ),
    )
    .unwrap();
    std::fs::write(
        root.path().join(".claude.json"),
        br#"{"oauthAccount":{"accountUuid":"u-1","emailAddress":"a@x.com"}}"#,
    )
    .unwrap();

    let out = Command::new(bin())
        .args(["status", "--json"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let v: serde_json::Value = serde_json::from_slice(&out.stdout).expect("status --json is JSON");
    let row = v
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["tool"] == "claude-code")
        .expect("the claude row");
    assert_eq!(row["logged_in"], serde_json::json!(true), "{row}");
    assert_eq!(
        row["expired"],
        serde_json::json!(false),
        "an hourly refresh is not an expired login: {row}"
    );
}

/// The JSON listing dropped the warning that it was incomplete.
///
/// A damaged `slots.json` means slot accounts are missing from the listing, and
/// `ls` says so. `ls --json` returned before that line ever ran: a truncated
/// array, exit 0, nothing on stderr - and every row carrying `"warning": null`,
/// so the one field a consumer would check for trouble reported none. The
/// status line and any script read this form.
#[test]
fn the_json_listing_says_when_it_is_incomplete() {
    let root = tempfile::tempdir().unwrap();
    seed_copy_profile(root.path(), "work");
    let store = root.path().join(".local/share/swapdex");
    std::fs::create_dir_all(&store).unwrap();
    std::fs::write(store.join("slots.json"), b"{ not json").unwrap();

    let out = Command::new(bin())
        .args(["ls", "--json"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    let stderr = String::from_utf8_lossy(&out.stderr).into_owned();

    // stdout stays parseable: a consumer mid-pipeline must not be handed prose.
    let parsed: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout is still JSON ({e}): {stdout}"));
    assert!(parsed.is_array(), "the shape does not change: {stdout}");

    assert!(
        stderr.contains("could not be read") || stderr.contains("damaged"),
        "and the incompleteness is said out loud: stderr={stderr:?}"
    );
}

/// `rm --tool claude` could not drop a Claude login.
///
/// Seven commands take `--tool` as the parsed `ToolSel`; `rm` alone took a raw
/// `Option<String>` and handed it straight to `drop_tool`, which looks under
/// `accounts/<name>/<tool>`. The directory is `claude-code`, and `ToolSel`'s own
/// definition makes `claude` the canonical spelling with `claude-code` the alias,
/// which `docs/COMMANDS.md` states too. So the documented spelling was the one
/// that failed, and it failed by saying the profile "has no claude login" about
/// a profile whose listing shows exactly that login. The unparsed string also
/// let any word through: `--tool banana` answered "has no banana login" where
/// every other command answers "invalid value".
#[test]
fn rm_drops_the_tool_the_documented_flag_names() {
    let root = tempfile::tempdir().unwrap();
    seed_copy_profile(root.path(), "work");
    let path = std::env::var("PATH").unwrap_or_default();
    assert!(
        run_in(root.path(), &["ls"], &path).contains("claude-code"),
        "precondition: the profile has that login"
    );

    let out = Command::new(bin())
        .args(["rm", "work", "--tool", "claude"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    let all = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert_eq!(out.status.code(), Some(0), "{all}");
    assert!(
        !run_in(root.path(), &["ls"], &path).contains("claude-code"),
        "the login is gone"
    );

    // And a word that is not a tool is a usage error, as everywhere else.
    let bad = Command::new(bin())
        .args(["rm", "work", "--tool", "banana"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(bad.status.code(), Some(2), "invalid value is exit 2");
}

/// A refused rename that already happened to half the account.
///
/// A name can be a registered slot AND a saved profile. `rename` renames the
/// slot first and persists it, THEN checks whether a profile already claims the
/// new name - and refuses with exit 6. So the slot is left renamed under a
/// message saying the rename did not happen: the mirror of `rm`, which did half
/// the job and called it success. Nothing may move unless all of it can.
#[test]
fn a_rename_that_is_refused_leaves_the_slot_alone() {
    let root = tempfile::tempdir().unwrap();
    let dir = root.path().join("dir-a");
    std::fs::create_dir_all(&dir).unwrap();
    let path = std::env::var("PATH").unwrap_or_default();
    run_in(
        root.path(),
        &["adopt", "bsgong", dir.to_str().unwrap()],
        &path,
    );
    seed_copy_profile(root.path(), "bsgong");
    seed_copy_profile(root.path(), "kong");

    let out = Command::new(bin())
        .args(["rename", "bsgong", "kong"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(6), "the target name is taken");

    // ...and the slot still answers to its old name.
    let slots = run_in(root.path(), &["slots"], &path);
    assert!(
        slots.contains("bsgong"),
        "a refused rename moved nothing: {slots}"
    );
    assert!(
        !slots.contains("kong"),
        "the slot must not carry the name the rename was refused: {slots}"
    );
}

/// One name, two halves - and `rm` says only what it did to the first.
///
/// A name can be a registered slot AND a saved profile at once. `rm` unregisters
/// the slot and deliberately leaves the profile ("a profile of the same name is a
/// separate thing"), then prints a plain success. On a real machine the account
/// was still listed afterwards, so the removal read as failed, and the next
/// `swapdex add <name>` refused with "already has a claude-code login" - which is
/// where the user ends up: told it exists after being told it was removed.
#[test]
fn rm_says_when_a_saved_profile_of_the_same_name_is_still_there() {
    let root = tempfile::tempdir().unwrap();
    let existing = root.path().join("dot-claude-kong");
    std::fs::create_dir_all(&existing).unwrap();
    std::fs::write(existing.join(".credentials.json"), b"{}").unwrap();
    let path = std::env::var("PATH").unwrap_or_default();
    run_in(
        root.path(),
        &["adopt", "kong", existing.to_str().unwrap()],
        &path,
    );
    seed_copy_profile(root.path(), "kong");

    let out = run_in(root.path(), &["rm", "kong", "--yes"], &path);
    assert!(out.contains("stopped managing"), "the slot went: {out}");
    assert!(
        out.contains("saved profile"),
        "and it says the other half is still here: {out}"
    );
    assert!(
        out.contains("rm kong"),
        "naming the command that removes it: {out}"
    );
    // The listing still shows the name, which is the whole reason this has to
    // be said out loud.
    assert!(
        run_in(root.path(), &["ls"], &path).contains("kong"),
        "the profile is still listed"
    );
}

/// Removing a slot account means "stop managing it", never "lose it": the mapping
/// goes, the directory and the login inside it stay, and `adopt` can bring it back.
#[test]
fn rm_unregisters_a_slot_and_leaves_its_login_alone() {
    let root = tempfile::tempdir().unwrap();
    let existing = root.path().join("dot-claude-company");
    std::fs::create_dir_all(&existing).unwrap();
    std::fs::write(existing.join(".credentials.json"), b"{\"keep\":\"me\"}").unwrap();
    let path = std::env::var("PATH").unwrap_or_default();
    run_in(
        root.path(),
        &["adopt", "company", existing.to_str().unwrap()],
        &path,
    );
    assert!(run_in(root.path(), &["slots"], &path).contains("company"));

    let out = run_in(root.path(), &["rm", "company", "--yes"], &path);
    assert!(out.contains("stopped managing"), "{out}");
    // ...and does not invent a leftover: nothing named 'company' was ever saved,
    // so pointing at a saved profile would send the user after a thing that is
    // not there.
    assert!(
        !out.contains("saved profile"),
        "no snapshot exists, so none is claimed: {out}"
    );
    assert!(
        !run_in(root.path(), &["slots"], &path).contains("company"),
        "the mapping is gone"
    );
    assert!(
        existing.join(".credentials.json").exists(),
        "the login was never touched"
    );
    // And it can be brought back.
    run_in(
        root.path(),
        &["adopt", "company", existing.to_str().unwrap()],
        &path,
    );
    assert!(run_in(root.path(), &["slots"], &path).contains("company"));
}

/// The shim is useless if PATH never reaches it, so installing it edits the shell
/// profile - once, idempotently, and never for a shell we would only be guessing
/// about.
#[test]
fn shim_puts_itself_on_path_via_the_shell_profile() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let home = root.path().join("home");
    std::fs::create_dir_all(&home).unwrap();
    std::fs::write(root.path().join(".zshrc"), "ROOT_SENTINEL\n").unwrap();
    std::fs::write(home.join(".zshrc"), "HOME_SENTINEL\n").unwrap();
    let run_shim = || {
        String::from_utf8_lossy(
            &Command::new(bin())
                .args(["shim"])
                .env("SWAPDEX_ROOT", root.path())
                .env("PATH", &path)
                .env("HOME", &home)
                .env("SHELL", "/bin/zsh")
                .output()
                .unwrap()
                .stdout,
        )
        .into_owned()
    };

    let out = run_shim();
    assert!(
        out.contains("added it to"),
        "it says what it changed: {out}"
    );
    let zshrc = std::fs::read_to_string(root.path().join(".zshrc")).expect("profile written");
    assert!(
        zshrc.contains("ROOT_SENTINEL")
            && zshrc.contains("swapdex")
            && zshrc.contains("export PATH="),
        "the line is there: {zshrc}"
    );
    assert_eq!(
        std::fs::read_to_string(home.join(".zshrc")).unwrap(),
        "HOME_SENTINEL\n",
        "the ambient HOME profile is outside the supplied Paths and stays untouched"
    );

    // Running it again must not stack a second copy.
    run_shim();
    let again = std::fs::read_to_string(root.path().join(".zshrc")).unwrap();
    assert_eq!(
        again.matches("export PATH=").count(),
        1,
        "idempotent: {again}"
    );

    // A shell we cannot reason about is told, not edited.
    let out = String::from_utf8_lossy(
        &Command::new(bin())
            .args(["shim"])
            .env("SWAPDEX_ROOT", root.path())
            .env("PATH", &path)
            .env("HOME", &home)
            .env("SHELL", "/usr/bin/fish")
            .output()
            .unwrap()
            .stdout,
    )
    .into_owned();
    assert!(
        out.contains("add this to your shell profile"),
        "fish gets instructions rather than a guessed edit: {out}"
    );
    assert!(
        !home.join(".config").exists(),
        "nothing was written for a shell we do not handle"
    );
}

/// PATH entries may be relative to the shell that installs the shim. The shim
/// runs later from arbitrary project directories, so the persisted client path
/// must be anchored at installation time while leaving a stable symlink intact.
#[test]
fn shim_anchors_relative_stable_client_paths_to_the_install_directory() {
    let root = tempfile::tempdir().unwrap();
    let install = root.path().join("install");
    let stable = install.join("bin");
    let versioned = install.join("versions/v1");
    let elsewhere = root.path().join("elsewhere");
    std::fs::create_dir_all(&stable).unwrap();
    std::fs::create_dir_all(&versioned).unwrap();
    std::fs::create_dir_all(&elsewhere).unwrap();
    for (name, marker) in [("claude", "RELATIVE_CLAUDE"), ("codex", "RELATIVE_CODEX")] {
        let native = versioned.join(name);
        std::fs::write(&native, format!("#!/bin/sh\nprintf '{marker}\\n'\n")).unwrap();
        std::fs::set_permissions(&native, std::fs::Permissions::from_mode(0o755)).unwrap();
        std::os::unix::fs::symlink(&native, stable.join(name)).unwrap();
    }

    let installed = Command::new(bin())
        .arg("shim")
        .current_dir(&install)
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", root.path())
        .env("SHELL", "/usr/bin/fish")
        .env("PATH", "bin:/usr/bin:/bin")
        .output()
        .unwrap();
    assert!(
        installed.status.success(),
        "shim install failed: {}{}",
        String::from_utf8_lossy(&installed.stdout),
        String::from_utf8_lossy(&installed.stderr)
    );

    let shim_dir = root.path().join(".local/share/swapdex/bin");
    for (name, marker) in [("claude", "RELATIVE_CLAUDE"), ("codex", "RELATIVE_CODEX")] {
        let body = std::fs::read_to_string(shim_dir.join(name)).unwrap();
        let exec_line = body
            .lines()
            .rev()
            .find(|line| line.starts_with("exec '") && line.ends_with("' \"$@\""))
            .unwrap_or_else(|| panic!("no native exec in generated {name} shim: {body}"));
        let embedded = std::path::PathBuf::from(
            exec_line
                .strip_prefix("exec '")
                .unwrap()
                .strip_suffix("' \"$@\"")
                .unwrap(),
        );
        assert!(
            embedded.is_absolute(),
            "the generated {name} shim persisted a relative client: {embedded:?}"
        );
        assert!(
            std::fs::symlink_metadata(&embedded)
                .unwrap()
                .file_type()
                .is_symlink(),
            "the generated {name} shim froze a versioned target: {embedded:?}"
        );
        assert_eq!(
            std::fs::canonicalize(&embedded).unwrap(),
            std::fs::canonicalize(versioned.join(name)).unwrap(),
            "the stable {name} symlink resolves to the native client"
        );
        let out = Command::new(shim_dir.join(name))
            .arg("--help")
            .current_dir(&elsewhere)
            .env("SWAPDEX_ROOT", root.path())
            .env("HOME", root.path())
            .env("PATH", "/usr/bin:/bin")
            .output()
            .unwrap();
        assert!(
            out.status.success() && String::from_utf8_lossy(&out.stdout).contains(marker),
            "the {name} shim did not reach its native client from another cwd: {}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
    }
}

#[test]
fn shim_skips_a_non_executable_path_shadow() {
    let root = tempfile::tempdir().unwrap();
    let shadow = root.path().join("shadow");
    let native = root.path().join("native");
    std::fs::create_dir_all(&shadow).unwrap();
    std::fs::create_dir_all(&native).unwrap();
    std::fs::write(shadow.join("claude"), "not executable\n").unwrap();
    std::fs::set_permissions(
        shadow.join("claude"),
        std::fs::Permissions::from_mode(0o644),
    )
    .unwrap();
    std::fs::write(
        native.join("claude"),
        "#!/bin/sh\nprintf 'EXECUTABLE_CLAUDE\\n'\n",
    )
    .unwrap();
    std::fs::set_permissions(
        native.join("claude"),
        std::fs::Permissions::from_mode(0o755),
    )
    .unwrap();
    let path = format!("{}:{}:/usr/bin:/bin", shadow.display(), native.display());

    let installed = Command::new(bin())
        .arg("shim")
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", root.path())
        .env("SHELL", "/usr/bin/fish")
        .env("PATH", &path)
        .output()
        .unwrap();
    assert!(installed.status.success());
    let out = Command::new(root.path().join(".local/share/swapdex/bin/claude"))
        .arg("--help")
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", root.path())
        .env("PATH", "/usr/bin:/bin")
        .output()
        .unwrap();
    assert!(
        out.status.success() && String::from_utf8_lossy(&out.stdout).contains("EXECUTABLE_CLAUDE"),
        "the non-executable shadow was persisted: {}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
}

#[test]
fn shim_service_detection_uses_the_supplied_home() {
    let root = tempfile::tempdir().unwrap();
    let ambient_home = root.path().join("ambient-home");
    let supplied_home = root.path().join("supplied-home");
    std::fs::create_dir_all(&ambient_home).unwrap();
    std::fs::create_dir_all(&supplied_home).unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!("{}:/usr/bin:/bin", bin_dir.display());
    let unit = |home: &Path| {
        if cfg!(target_os = "macos") {
            swapdex::service::launchd_path(home, "claude-code")
        } else {
            swapdex::service::systemd_path(home, "claude-code")
        }
    };

    let decoy = unit(&ambient_home);
    std::fs::create_dir_all(decoy.parent().unwrap()).unwrap();
    std::fs::write(&decoy, "decoy service\n").unwrap();
    let run = || {
        Command::new(bin())
            .arg("shim")
            .env("SWAPDEX_ROOT", &supplied_home)
            .env("HOME", &ambient_home)
            .env("SHELL", "/usr/bin/fish")
            .env("PATH", &path)
            .output()
            .unwrap()
    };
    assert!(run().status.success());
    assert!(
        !supplied_home.join(".claude/settings.json").exists(),
        "an unrelated ambient-home service must not authorize a proxy pin"
    );

    std::fs::remove_file(decoy).unwrap();
    let supplied_unit = unit(&supplied_home);
    std::fs::create_dir_all(supplied_unit.parent().unwrap()).unwrap();
    std::fs::write(supplied_unit, "synthetic service\n").unwrap();
    assert!(run().status.success());
    let settings = std::fs::read_to_string(supplied_home.join(".claude/settings.json"))
        .expect("the supplied service authorizes the synthetic root's proxy pin");
    assert!(settings.contains("127.0.0.1:8787"), "{settings}");
}

#[test]
fn doctor_reads_the_shell_profile_from_the_supplied_home() {
    let root = tempfile::tempdir().unwrap();
    let ambient_home = root.path().join("ambient-home");
    std::fs::create_dir_all(&ambient_home).unwrap();
    let bin_dir = fake_claude(root.path());
    let native_path = format!("{}:/usr/bin:/bin", bin_dir.display());
    run_in(root.path(), &["run", "work", "--no-launch"], &native_path);
    run_in(root.path(), &["use", "work"], &native_path);
    let shim_dir = root.path().join(".local/share/swapdex/bin");
    let profile_line = format!("export PATH=\"{}:$PATH\"\n", shim_dir.display());
    std::fs::write(root.path().join(".bashrc"), &profile_line).unwrap();
    std::fs::write(ambient_home.join(".bashrc"), "AMBIENT_SENTINEL\n").unwrap();
    let installed = Command::new(bin())
        .arg("shim")
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", &ambient_home)
        .env("SHELL", "/bin/bash")
        .env("PATH", &native_path)
        .output()
        .unwrap();
    assert!(installed.status.success());
    std::fs::write(ambient_home.join(".bashrc"), "AMBIENT_SENTINEL\n").unwrap();

    let out = Command::new(bin())
        .arg("doctor")
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", &ambient_home)
        .env("SHELL", "/bin/bash")
        .env("PATH", &native_path)
        .output()
        .unwrap();
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("shim set up in") && stdout.contains("not on THIS shell's PATH"),
        "doctor ignored the supplied home profile: {stdout}"
    );
}

/// Switching should not mean leaving the conversation for another terminal, so
/// swapdex installs a Claude Code slash command that does it in place.
#[test]
fn slash_installs_a_claude_code_command() {
    let root = tempfile::tempdir().unwrap();
    // Under `SWAPDEX_ROOT` the root IS the home - that is what `Paths::rooted`
    // means and what containment is. `slash` used to ask `dirs` for the home
    // instead, so it honoured $HOME here and the REAL one everywhere else.
    let home = root.path().to_path_buf();
    let out = String::from_utf8_lossy(
        &Command::new(bin())
            .args(["slash"])
            .env("SWAPDEX_ROOT", root.path())
            .env("HOME", &home)
            .output()
            .unwrap()
            .stdout,
    )
    .into_owned();
    assert!(out.contains("/swap"), "it names the command: {out}");

    // Each assistant only ever sees - and only ever moves - its OWN accounts.
    let claude_body = std::fs::read_to_string(home.join(".claude/commands/swap.md"))
        .expect("claude command written");
    assert!(claude_body.starts_with("---"), "frontmatter: {claude_body}");
    assert!(
        claude_body.contains("--tool claude-code") && !claude_body.contains("--tool codex"),
        "the Claude command switches Claude only: {claude_body}"
    );
    assert!(
        claude_body.contains("tagged `claude-code`"),
        "and lists Claude accounts only: {claude_body}"
    );

    let codex_body =
        std::fs::read_to_string(home.join(".codex/skills/swap/SKILL.md")).expect("codex skill");
    assert!(
        codex_body.contains("name: swap") && codex_body.contains("description:"),
        "codex frontmatter: {codex_body}"
    );
    assert!(
        codex_body.contains("--tool codex") && !codex_body.contains("--tool claude-code"),
        "the Codex skill switches Codex only: {codex_body}"
    );
    assert!(
        codex_body.contains("AskUserQuestion"),
        "a bare /swap still offers a pick-list: {codex_body}"
    );
    let f = home.join(".claude/commands/swap.md");
    let body = claude_body;

    // Re-running just rewrites it - no duplicate, no error.
    Command::new(bin())
        .args(["slash"])
        .env("SWAPDEX_ROOT", root.path())
        .env("HOME", &home)
        .output()
        .unwrap();
    assert_eq!(std::fs::read_to_string(&f).unwrap(), body);
}

/// `/swap <name>` is invoked mid-conversation, so its generated instruction
/// must move the payer pointer and leave the launch-home pointer where it was.
#[test]
fn slash_explicit_argument_executes_a_payer_only_switch() {
    for (tool, short, instruction) in [
        ("claude-code", "claude", ".claude/commands/swap.md"),
        ("codex", "codex", ".codex/skills/swap/SKILL.md"),
    ] {
        let root = tempfile::tempdir().unwrap();
        let path = "/usr/bin:/bin";
        for name in ["a", "b"] {
            run_in(
                root.path(),
                &["run", name, "--tool", tool, "--no-launch"],
                path,
            );
            let dir = slot_dir(root.path(), name, tool);
            if tool == "codex" {
                std::fs::write(
                    dir.join("auth.json"),
                    format!(
                        "{{\"tokens\":{{\"access_token\":\"{name}\",\"account_id\":\"{name}\"}}}}"
                    ),
                )
                .unwrap();
            } else {
                std::fs::write(
                    dir.join(".credentials.json"),
                    format!(
                        "{{\"claudeAiOauth\":{{\"accessToken\":\"{name}\",\"expiresAt\":32503680000000}}}}"
                    ),
                )
                .unwrap();
            }
        }
        run_in(root.path(), &["use", "a", "--tool", tool], path);
        let store = root.path().join(".local/share/swapdex");
        let active = store.join(format!("active-{short}"));
        let active_before = std::fs::read(&active).expect("launch-home pointer");

        run_in(root.path(), &["slash"], path);
        let body = std::fs::read_to_string(root.path().join(instruction)).unwrap();
        let generated = body
            .split('`')
            .nth(1)
            .unwrap_or_else(|| panic!("no executable command in {instruction}: {body}"));
        let command_dir = root.path().join("command-bin");
        std::fs::create_dir_all(&command_dir).unwrap();
        std::os::unix::fs::symlink(bin(), command_dir.join("swapdex")).unwrap();
        let generated_path = format!("{}:/usr/bin:/bin", command_dir.display());
        let out = Command::new("/bin/sh")
            .args(["-c", generated])
            .env("ARGUMENTS", "b")
            .env("SWAPDEX_ROOT", root.path())
            .env("HOME", root.path())
            .env("PATH", generated_path)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "generated {tool} instruction failed: {}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(
            std::fs::read(&active).unwrap(),
            active_before,
            "generated {tool} instruction moved the launch home"
        );
        assert_eq!(
            std::fs::read_to_string(store.join(format!("serving-{short}"))).unwrap(),
            slot_dir(root.path(), "b", tool).display().to_string(),
            "generated {tool} instruction did not select b as payer"
        );
    }
}

/// The threshold is a setting, not just a flag: the proxy the shim starts takes
/// no flags, and that is the one doing the work day to day.
#[test]
fn threshold_setting_accepts_both_notations_and_off() {
    let root = tempfile::tempdir().unwrap();
    let path = std::env::var("PATH").unwrap_or_default();
    assert!(
        run_in(root.path(), &["threshold"], &path).contains("no threshold"),
        "off until asked for"
    );
    // Fractions and percentages are both how people say this.
    assert!(run_in(root.path(), &["threshold", "0.9"], &path).contains("90%"));
    assert!(
        run_in(root.path(), &["threshold"], &path).contains("90%"),
        "it persists"
    );
    assert!(run_in(root.path(), &["threshold", "80%"], &path).contains("80%"));
    assert!(run_in(root.path(), &["threshold", "95"], &path).contains("95%"));
    // And it can be turned back off.
    assert!(run_in(root.path(), &["threshold", "off"], &path).contains("threshold off"));
    assert!(run_in(root.path(), &["threshold"], &path).contains("no threshold"));
    // Nonsense is refused rather than guessed at.
    let out = Command::new(bin())
        .args(["threshold", "soonish"])
        .env("SWAPDEX_ROOT", root.path())
        .output()
        .unwrap();
    assert_eq!(out.status.code(), Some(2));
}

#[test]
fn threshold_percentages_keep_their_literal_value_after_reloading() {
    let root = tempfile::tempdir().unwrap();
    let paths = swapdex::paths::Paths::rooted(root.path());
    for (input, expected, displayed) in [
        ("0.5%", 0.005, "0.5%"),
        ("1%", 0.01, "1%"),
        ("0.01%", 0.0001, "0.01%"),
        ("0.29%", 0.0029, "0.29%"),
        (" 0.25% ", 0.0025, "0.25%"),
        ("29%", 0.29, "29%"),
        ("99.9%", 0.999, "99.9%"),
        ("100%", 1.0, "100%"),
        ("0.5", 0.5, "50%"),
        ("1", 1.0, "100%"),
        ("95", 0.95, "95%"),
        ("1e-8%", 1e-10, "0.00000001%"),
        ("1e-13%", 1e-15, "1e-13%"),
    ] {
        let output = Command::new(bin())
            .args(["threshold", input])
            .env("SWAPDEX_ROOT", root.path())
            .output()
            .unwrap();
        assert!(output.status.success(), "{input}: {output:?}");
        let settings = swapdex::settings::load(&paths);
        let stored = settings.proxy_threshold.expect("stored threshold");
        assert!(
            (stored - expected).abs() < expected * 1e-12,
            "{input}: stored {stored}, expected {expected}"
        );
        assert_eq!(
            settings.threshold(),
            Some(stored),
            "{input}: silently clamped"
        );
        let stdout = String::from_utf8_lossy(&output.stdout);
        assert!(
            stdout.contains(&format!("at {displayed} used")),
            "{input}: {stdout}"
        );
        let reread = Command::new(bin())
            .arg("threshold")
            .env("SWAPDEX_ROOT", root.path())
            .output()
            .unwrap();
        assert!(reread.status.success());
        let stdout = String::from_utf8_lossy(&reread.stdout);
        assert!(
            stdout.contains(&format!("at {displayed} used")),
            "{input}: {stdout}"
        );
        let used_percent = stored * 100.0;
        assert!(swapdex::proxy::pick::over_threshold(
            Some(used_percent),
            None,
            stored
        ));
        assert!(!swapdex::proxy::pick::over_threshold(
            Some(used_percent / 2.0),
            None,
            stored
        ));
    }
}

#[test]
fn threshold_invalid_values_leave_the_previous_setting_untouched() {
    let root = tempfile::tempdir().unwrap();
    let paths = swapdex::paths::Paths::rooted(root.path());
    swapdex::settings::save(
        &paths,
        &swapdex::settings::Settings {
            proxy_threshold: Some(0.82),
            proxy_auto: Some(true),
            ..Default::default()
        },
    )
    .unwrap();
    let settings = paths.store_dir().join("settings.json");
    let before = std::fs::read(&settings).unwrap();
    for input in [
        "50%%", "1%%", "50%junk", "%", "NaN", "inf", "0", "-0.5", "100.1%", "101",
    ] {
        let output = Command::new(bin())
            .args(["threshold", "--", input])
            .env("SWAPDEX_ROOT", root.path())
            .output()
            .unwrap();
        assert_eq!(
            output.status.code(),
            Some(2),
            "accepted {input}: {output:?}"
        );
        assert_eq!(
            std::fs::read(&settings).unwrap(),
            before,
            "changed settings for {input}"
        );
    }
}

#[test]
fn threshold_runtime_preserves_small_values_and_ignores_invalid_stored_values() {
    for threshold in [0.005, 0.01, 0.049, 0.05, 0.9, 1.0] {
        let settings = swapdex::settings::Settings {
            proxy_threshold: Some(threshold),
            ..Default::default()
        };
        assert_eq!(settings.threshold(), Some(threshold));
    }
    for threshold in [0.0, -0.1, 1.01, f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
        let settings = swapdex::settings::Settings {
            proxy_threshold: Some(threshold),
            ..Default::default()
        };
        assert_eq!(
            settings.threshold(),
            None,
            "invalid stored threshold: {threshold}"
        );
    }
}

/// A stand-in `codex` that reports the home it was launched with.
fn fake_codex(root: &Path) -> std::path::PathBuf {
    let dir = root.join("fakebin");
    std::fs::create_dir_all(&dir).unwrap();
    let f = dir.join("codex");
    std::fs::write(
        &f,
        "#!/bin/sh\necho \"HOME_DIR=$CODEX_HOME\"\necho \"ARGS=$*\"\n",
    )
    .unwrap();
    std::fs::set_permissions(&f, std::fs::Permissions::from_mode(0o755)).unwrap();
    dir
}

fn slot_dir(root: &Path, name: &str, tool: &str) -> std::path::PathBuf {
    let store = root.join(".local/share/swapdex");
    let recs: Vec<serde_json::Value> =
        serde_json::from_slice(&std::fs::read(store.join("slots.json")).unwrap()).unwrap();
    recs.iter()
        .find(|record| record["name"] == name && record["tool"] == tool)
        .and_then(|record| record["config_dir"].as_str())
        .map(std::path::PathBuf::from)
        .expect("slot record")
}

// `swapdex run` is itself the direct, per-account launch path. Once the shims
// win PATH, looking the tool up by its bare name loops this launch back through
// managed proxy startup. A brand-new account has no credential for that proxy,
// so the native login client is never reached.
#[test]
fn run_steps_over_installed_shims_for_fresh_accounts() {
    for (tool_flag, tool, short, home_line) in [
        (None, "claude-code", "claude", "CFG="),
        (Some("codex"), "codex", "codex", "HOME_DIR="),
    ] {
        let root = tempfile::tempdir().unwrap();
        let bin_dir = fake_claude(root.path());
        fake_codex(root.path());
        let native_path = format!(
            "{}:{}",
            bin_dir.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        let mut existing_args = vec!["run", "existing", "--no-launch"];
        if let Some(tool_flag) = tool_flag {
            existing_args.extend(["--tool", tool_flag]);
        }
        run_in(root.path(), &existing_args, &native_path);
        let existing_dir = slot_dir(root.path(), "existing", tool);
        if tool == "codex" {
            std::fs::write(
                existing_dir.join("auth.json"),
                br#"{"tokens":{"access_token":"existing","account_id":"existing"}}"#,
            )
            .unwrap();
        } else {
            std::fs::write(
                existing_dir.join(".credentials.json"),
                br#"{"claudeAiOauth":{"accessToken":"existing","expiresAt":32503680000000}}"#,
            )
            .unwrap();
        }
        let mut use_args = vec!["use", "existing"];
        let mut serve_args = vec!["serve", "existing"];
        if let Some(tool_flag) = tool_flag {
            use_args.extend(["--tool", tool_flag]);
            serve_args.extend(["--tool", tool_flag]);
        }
        run_in(root.path(), &use_args, &native_path);
        run_in(root.path(), &serve_args, &native_path);
        let store = root.path().join(".local/share/swapdex");
        let active = store.join(format!("active-{short}"));
        let serving = store.join(format!("serving-{short}"));
        let active_before = std::fs::read(&active).expect("active pointer");
        let serving_before = std::fs::read(&serving).expect("serving pointer");

        let installed = run_in(root.path(), &["shim"], &native_path);
        assert!(
            installed.contains("installed the claude shim"),
            "{installed}"
        );

        let shim_dir = root.path().join(".local/share/swapdex/bin");
        let shim_first_path = format!("{}:{native_path}", shim_dir.display());
        let mut args = vec!["run", "fresh"];
        if let Some(tool_flag) = tool_flag {
            args.extend(["--tool", tool_flag]);
        }
        let home = root.path().join("home");
        let out = Command::new(bin())
            .args(args)
            .env("SWAPDEX_ROOT", root.path())
            .env("PATH", shim_first_path)
            .env("HOME", home)
            .output()
            .unwrap();
        let stdout = String::from_utf8_lossy(&out.stdout);
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(
            out.status.success() && stdout.lines().any(|line| line.starts_with(home_line)),
            "managed {tool} run did not reach the native tool: stdout={stdout:?} stderr={stderr:?}"
        );
        assert_eq!(std::fs::read(&active).unwrap(), active_before);
        assert_eq!(std::fs::read(&serving).unwrap(), serving_before);
    }
}

#[test]
fn run_reports_when_an_installed_shim_has_no_native_tool_behind_it() {
    for (tool_flag, binary) in [(None, "claude"), (Some("codex"), "codex")] {
        let root = tempfile::tempdir().unwrap();
        let bin_dir = fake_claude(root.path());
        fake_codex(root.path());
        let native_path = format!(
            "{}:{}",
            bin_dir.display(),
            std::env::var("PATH").unwrap_or_default()
        );
        run_in(root.path(), &["shim"], &native_path);
        std::fs::remove_file(bin_dir.join(binary)).unwrap();

        let shim_dir = root.path().join(".local/share/swapdex/bin");
        let mut args = vec!["run", "fresh"];
        if let Some(tool_flag) = tool_flag {
            args.extend(["--tool", tool_flag]);
        }
        let out = Command::new(bin())
            .args(args)
            .env("SWAPDEX_ROOT", root.path())
            .env("PATH", &shim_dir)
            .env("HOME", root.path().join("home"))
            .output()
            .unwrap();
        let stderr = String::from_utf8_lossy(&out.stderr);
        assert!(!out.status.success(), "shim-only PATH must fail");
        assert!(
            stderr.contains(&format!("real `{binary}` executable")) && stderr.contains("not found"),
            "missing-native diagnostic for {binary}: {stderr}"
        );
    }
}

// `run` is how an account gets its login in the first place: it makes the slot
// and launches the tool pointed at it, so the sign-in lands in that account's own
// home instead of the shared one every other account also reads.
#[test]
fn run_launches_codex_in_the_accounts_own_home() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_codex(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = run_in(root.path(), &["run", "work", "--tool", "codex"], &path);
    let store = root.path().join(".local/share/swapdex");
    let recs: Vec<serde_json::Value> =
        serde_json::from_slice(&std::fs::read(store.join("slots.json")).unwrap()).unwrap();
    let rec = recs
        .iter()
        .find(|r| r["name"] == "work")
        .expect("the slot was created");
    assert_eq!(rec["tool"], "codex", "registered as a Codex account");
    let dir = rec["config_dir"].as_str().unwrap();
    assert!(
        out.contains(&format!("HOME_DIR={dir}")),
        "codex was launched with that home: {out}"
    );
    // Claude's variable is not involved - one tool's launch must never point the
    // other tool anywhere.
    assert!(!out.contains("CLAUDE_CONFIG_DIR"), "{out}");
}

// Every account is a slot now, and the UI's rename only ever touched the store -
// so renaming from the dashboard failed with "no profile named X" on exactly the
// accounts the dashboard is made of.
#[test]
fn rename_works_on_a_slot_account() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "work", "--no-launch"], &path);
    let out = run_in(root.path(), &["rename", "work", "acme"], &path);
    assert!(out.contains("acme"), "the rename reported success: {out}");
    let listed = run_in(root.path(), &["slots"], &path);
    assert!(listed.contains("acme"), "the new name is listed: {listed}");
    assert!(!listed.contains("work"), "the old one is gone: {listed}");
}

// Every account in the dashboard is a slot, and both tools put them there. `rm`
// looked only in Claude's registry, so a Codex account could not be removed at
// all - and the dashboard's delete key reported "no profile named X" for the
// accounts it was showing.
#[test]
fn removing_an_account_works_for_either_tool() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(root.path(), &["run", "onclaude", "--no-launch"], &path);
    run_in(
        root.path(),
        &["run", "oncodex", "--tool", "codex", "--no-launch"],
        &path,
    );

    let out = run_in(root.path(), &["rm", "oncodex", "--yes"], &path);
    assert!(
        out.contains("oncodex"),
        "a Codex account can be removed: {out}"
    );
    let listed = run_in(root.path(), &["slots"], &path);
    assert!(!listed.contains("oncodex"), "it is gone: {listed}");
    assert!(
        listed.contains("onclaude"),
        "the other is untouched: {listed}"
    );

    // And Claude's still work.
    run_in(root.path(), &["rm", "onclaude", "--yes"], &path);
    let listed = run_in(root.path(), &["slots"], &path);
    assert!(!listed.contains("onclaude"), "{listed}");
}

// Which tool an account belongs to was worked out separately everywhere it was
// needed, and the versions disagreed: one fell back to Claude whenever the slot
// registry did not know the name, so pressing the sign-in key on a Codex account
// opened Claude's login.
#[test]
fn an_accounts_tool_is_read_the_same_way_everywhere() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(
        root.path(),
        &["run", "oncodex", "--tool", "codex", "--no-launch"],
        &path,
    );
    run_in(root.path(), &["run", "onclaude", "--no-launch"], &path);
    // Both slots are signed in: `serve` refuses an account that has no login,
    // because the proxy would forward the user's OWN credential and every screen
    // would still name this one. That guard is not what this test is about.
    let slot_of = |name: &str| -> std::path::PathBuf {
        let raw = std::fs::read_to_string(root.path().join(".local/share/swapdex/slots.json"))
            .expect("slots.json");
        let v: serde_json::Value = serde_json::from_str(&raw).unwrap();
        let dir = v
            .as_array()
            .unwrap()
            .iter()
            .find(|r| r["name"] == name)
            .unwrap()["config_dir"]
            .as_str()
            .unwrap()
            .to_string();
        std::path::PathBuf::from(dir)
    };
    std::fs::write(
        slot_of("oncodex").join("auth.json"),
        br#"{"tokens":{"access_token":"a","account_id":"acc"}}"#,
    )
    .unwrap();
    std::fs::write(
        slot_of("onclaude").join(".credentials.json"),
        br#"{"claudeAiOauth":{"accessToken":"a","expiresAt":32503680000000}}"#,
    )
    .unwrap();

    // `serve` is what the dashboard's Enter runs, and it is told the tool the
    // dashboard resolved - so a wrong answer here sends a Codex account down
    // Claude's path and silently does nothing.
    let out = run_in(root.path(), &["serve", "oncodex", "--tool", "codex"], &path);
    assert!(out.contains("oncodex"), "{out}");
    let store = root.path().join(".local/share/swapdex");
    assert!(
        store.join("serving-codex").exists(),
        "a Codex account is served through Codex's own pointer"
    );
    assert!(
        !store.join("serving-claude").exists(),
        "and never through Claude's"
    );

    let out = run_in(root.path(), &["serve", "onclaude"], &path);
    assert!(out.contains("onclaude"), "{out}");
    assert!(store.join("serving-claude").exists());
}

/// An install that silently did NOTHING looks exactly like one that worked. Two
/// copies on PATH, or shims still calling the copy you replaced, produce a tool
/// that keeps running the old binary while every update reports success. That
/// went unnoticed here for a full day, and once more when a scope typo made
/// every `npm i -g` a 404 nobody read. doctor answers the question directly.
#[test]
fn doctor_reports_which_swapdex_is_actually_in_use() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());

    // A second, decoy swapdex on PATH - a stale install from another installer.
    let decoy_dir = root.path().join("other-installer");
    std::fs::create_dir_all(&decoy_dir).unwrap();
    std::fs::write(decoy_dir.join("swapdex"), b"#!/bin/sh\nexit 0\n").unwrap();
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(
            decoy_dir.join("swapdex"),
            std::fs::Permissions::from_mode(0o755),
        )
        .unwrap();
    }
    let real_dir = std::path::Path::new(bin()).parent().unwrap().to_path_buf();
    let path = format!(
        "{}:{}:{}",
        bin_dir.display(),
        decoy_dir.display(),
        real_dir.display()
    );

    let out = Command::new(bin())
        .args(["doctor"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains("2 copies on PATH"),
        "the shadowed install is named: {o}"
    );
    assert!(
        o.contains("keep one installer"),
        "and the fix comes with it: {o}"
    );
    // The version check reaches a registry, which a test must never do.
    assert!(
        !o.contains("latest is"),
        "no network from a sandboxed run: {o}"
    );
}

/// A sign-in must ask the tool to SIGN IN, and must not be routed through the
/// proxy on the way. The dashboard's key used to run a bare `codex` off PATH -
/// which is our own shim, and the shim puts the proxy in front of any Codex run
/// it does not recognise as plain. A bare launch is not recognised, so the
/// sign-in talked to the proxy, which answered with the account it was already
/// serving: an account with no login of its own came up looking signed in.
///
/// Both entry points now share one runner, and this exercises it through the
/// command line - the dashboard's key reaches the same function, with the
/// account's home added.
#[test]
fn signing_in_asks_the_tool_to_sign_in_and_bypasses_the_proxy() {
    let root = tempfile::tempdir().unwrap();
    let bin_dir = fake_claude(root.path());

    // A recognisable real `codex`, plus our shim ahead of it on PATH.
    std::fs::write(
        bin_dir.join("codex"),
        b"#!/bin/sh\necho \"REAL-CODEX args=$*\" >> \"$SX_PROBE\"\nexit 0\n",
    )
    .unwrap();
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(
            bin_dir.join("codex"),
            std::fs::Permissions::from_mode(0o755),
        )
        .unwrap();
    }
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    run_in(
        root.path(),
        &["run", "work", "--tool", "codex", "--no-launch"],
        &path,
    );
    run_in(root.path(), &["shim"], &path);

    // The shim dir goes FIRST, which is what `swapdex shim` arranges on a real
    // machine. Without it a bare `codex` finds the real one anyway and the test
    // proves nothing - it passed against the very bug it was written for.
    let shim_dir = root.path().join(".local/share/swapdex/bin");
    assert!(
        shim_dir.join("codex").is_file(),
        "the codex shim was written"
    );
    let path = format!("{}:{}", shim_dir.display(), path);

    let probe = root.path().join("probe.log");
    let out = Command::new(bin())
        .args(["login", "work", "--tool", "codex"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .env("SX_PROBE", &probe)
        .output()
        .unwrap();
    let seen = std::fs::read_to_string(&probe).unwrap_or_default();
    let o = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        seen.contains("REAL-CODEX"),
        "codex was reached at all: probe={seen:?} out={o}"
    );
    // The one that matters. A bare launch is not a "plain" run to the shim, so it
    // gets the provider overrides - and then the sign-in talks to the proxy,
    // which answers with the account it is already serving.
    assert!(
        !seen.contains("model_provider=swapdex"),
        "the sign-in must not go through the proxy: probe={seen:?}"
    );
    assert!(
        seen.contains("args=login"),
        "and asks to sign in rather than opening a session: probe={seen:?}"
    );
}