swapdex 0.17.1

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
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
//! End-to-end switch behavior against an isolated SWAPDEX_ROOT. Never touches a
//! real login: every path resolves under the temp root.

use std::path::Path;
use std::process::Command;

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

fn run(root: &Path, args: &[&str]) -> (String, String, i32) {
    let out = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .output()
        .unwrap();
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

fn chmod600(p: &std::path::Path) {
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600)).unwrap();
}

fn seed_codex(root: &Path, account_id: &str) {
    let d = root.join(".codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode":"chatgpt","OPENAI_API_KEY":"sk-SENTINEL",
            "tokens":{"id_token":"h.eyJlbWFpbCI6ImFAeC5jb20ifQ.s","access_token":"AT",
                      "refresh_token":"RT","account_id":account_id},
            "last_refresh":"2026-07-03T00:00:00Z"}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&root.join(".codex/auth.json"));
}

#[test]
fn add_use_roundtrip_and_egress_sentinel() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, e, c) = run(root.path(), &["add", "work", "--tool", "codex"]);
    assert_eq!(c, 0, "add failed: {e}");

    seed_codex(root.path(), "acct-B"); // a different live login
    run(root.path(), &["add", "home", "--tool", "codex"]);

    let (_o, e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_eq!(c, 0, "use failed: {e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(
        live["tokens"]["account_id"], "acct-A",
        "live login is now work"
    );

    // EGRESS (A11): no command prints the sentinel token to stdout/stderr.
    for args in [vec!["ls"], vec!["status"], vec!["ls", "--json"]] {
        let (o, e, _c) = run(root.path(), &args);
        assert!(
            !o.contains("SENTINEL") && !e.contains("SENTINEL"),
            "token leak in {args:?}: {o}{e}"
        );
    }
}

#[test]
fn status_trusts_live_identity_not_stale_active_json() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    run(root.path(), &["use", "work", "--tool", "codex"]);
    // The user "logs in directly" to a different account behind swapdex's back.
    seed_codex(root.path(), "acct-Z");
    let (o, _e, _c) = run(root.path(), &["status"]);
    // active.json still says "work", but status must reflect the LIVE account,
    // which is now unsaved.
    assert!(
        o.contains("not saved"),
        "status must reconcile against the live login: {o}"
    );
}

#[test]
fn use_nonexistent_profile_exits_nonzero() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, _e, c) = run(root.path(), &["use", "ghost", "--tool", "codex"]);
    assert_ne!(c, 0);
}

#[test]
fn ls_empty_store_guides_onboarding() {
    let root = tempfile::tempdir().unwrap();
    let (o, _e, c) = run(root.path(), &["ls"]);
    assert_eq!(c, 0);
    assert!(o.contains("No accounts saved"));
    assert!(
        o.contains("swapdex setup"),
        "empty state should point to setup: {o}"
    );
}

// setup is interactive; piped (non-tty) it degrades instead of hanging.
#[test]
fn setup_non_tty_degrades_gracefully() {
    let root = tempfile::tempdir().unwrap();
    let out = std::process::Command::new(bin())
        .arg("setup")
        .env("SWAPDEX_ROOT", root.path())
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("interactive"),
        "setup should explain it needs a terminal"
    );
}

// Drive the interactive setup wizard over a pipe (SWAPDEX_ASSUME_TTY bypasses
// the tty check). Answers are one per line.
fn run_setup(root: &Path, input: &str) -> (String, i32) {
    use std::io::Write;
    use std::process::Stdio;
    let mut child = Command::new(bin())
        .arg("setup")
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .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(),
        out.status.code().unwrap_or(-1),
    )
}

// The wizard saves the current login from a typed name.
#[test]
fn setup_wizard_saves_account_from_prompts() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (o, c) = run_setup(root.path(), "mycodex\nn\n");
    assert_eq!(c, 0, "{o}");
    let (ls, _e, _c) = run(root.path(), &["ls"]);
    assert!(
        ls.contains("mycodex"),
        "setup should save the account: {ls}"
    );
}

// The wizard re-prompts on an invalid name instead of skipping it.
#[test]
fn setup_reprompts_on_an_invalid_name() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (o, c) = run_setup(root.path(), "bad/name\ngood\nn\n");
    assert_eq!(c, 0);
    assert!(
        o.contains("can't be a name"),
        "should reject the invalid name: {o}"
    );
    let (ls, _e, _c) = run(root.path(), &["ls"]);
    assert!(ls.contains("good"), "should save the valid retry: {ls}");
}

// login --tool claude: with Claude already logged in it guides the
// `swapdex add` step rather than spawning an interactive session. A fake
// `claude` on PATH makes this deterministic on machines (like CI) that do not
// have the real CLI installed.
#[test]
fn login_claude_guides_the_add_step() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    // Seed a live Claude login so the "already logged in" guidance path runs and
    // it never spawns `claude` interactively (which would hang the test).
    seed_claude(root.path(), "uuid-A", "a@x.com");
    let bin_dir = root.path().join("fakebin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("claude");
    std::fs::write(&fake, "#!/bin/sh\necho 1.0.0\n").unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    let out = Command::new(bin())
        .args(["login", "work", "--tool", "claude"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &bin_dir)
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    // Exit 3: guidance only, nothing saved - `login x && use x` in a
    // script must not proceed.
    assert_eq!(out.status.code().unwrap_or(-1), 3, "{o}");
    assert!(o.contains("swapdex add work --tool claude"), "{o}");
}

// C3: a profile name must not escape the store.
#[test]
fn profile_name_traversal_is_rejected() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, _e, c) = run(root.path(), &["add", "../escape", "--tool", "codex"]);
    assert_eq!(c, 2, "traversal name must be rejected");
    assert!(!root.path().join(".local/share/escape").exists());
    let (_o, _e, c2) = run(root.path(), &["rm", "../escape", "--yes"]);
    assert_eq!(c2, 2);
}

// H1/BUG3: switching to the already-active account writes nothing and appends no
// timeline event.
#[test]
fn use_already_active_is_a_noop() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_eq!(c, 0);
    assert!(o.contains("already active"), "{o}");
    let tl = std::fs::read_to_string(root.path().join(".local/share/swapdex/timeline.jsonl"))
        .unwrap_or_default();
    assert!(
        !tl.contains("\"account\":\"work\""),
        "no-op must not append a timeline event: {tl}"
    );
}

// rename moves the profile and ls reflects the new name.
#[test]
fn rename_moves_the_profile() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let (_o, e, c) = run(root.path(), &["rename", "work", "job"]);
    assert_eq!(c, 0, "rename failed: {e}");
    let (o, _e, _c) = run(root.path(), &["ls"]);
    assert!(o.contains("job"), "ls should show renamed profile: {o}");
}

// Mixed cross-tool live state: ls --json marks each profile active per-tool, not
// a flat bool that stars both.
#[test]
fn ls_json_reports_active_per_tool_in_mixed_state() {
    let root = tempfile::tempdir().unwrap();
    // claude live = uuid-A (profile work); codex live = acct-B (profile home)
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex_tok(root.path(), "acct-A", "AT", "2026-07-04T00:00:00Z");
    run(root.path(), &["add", "work"]);
    seed_codex_tok(root.path(), "acct-B", "AT2", "2026-07-04T00:00:00Z");
    run(root.path(), &["add", "home", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &["ls", "--json"]);
    assert_eq!(c, 0);
    let rows: serde_json::Value = serde_json::from_str(o.trim()).unwrap();
    let get = |name: &str| -> Vec<String> {
        rows.as_array()
            .unwrap()
            .iter()
            .find(|r| r["name"] == name)
            .unwrap()["active_tools"]
            .as_array()
            .unwrap()
            .iter()
            .map(|t| t.as_str().unwrap().to_string())
            .collect()
    };
    assert_eq!(
        get("work"),
        vec!["claude-code"],
        "work is active only for claude"
    );
    assert_eq!(get("home"), vec!["codex"], "home is active only for codex");
}

// A stray/legacy file in the store dir must not break a switch (swapdex derives
// the active account from the live login, not any stored hint).
#[test]
fn stray_file_in_store_is_ignored() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    std::fs::write(
        root.path().join(".local/share/swapdex/active.json"),
        b"[1,2,3]",
    )
    .unwrap();
    seed_codex(root.path(), "acct-B"); // force a real switch
    let (_o, _e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_ne!(c, 101, "must not panic on a stray file");
    assert_eq!(c, 0);
}

// The bare `swapdex` prints the ASCII wordmark; piped output carries no ANSI.
#[test]
fn no_args_prints_ascii_banner_plain_when_piped() {
    let root = tempfile::tempdir().unwrap();
    let (o, _e, c) = run(root.path(), &[]);
    assert_eq!(c, 0);
    assert!(o.contains('\u{2588}'), "should print block ASCII art");
    assert!(
        !o.contains('\u{1b}'),
        "no ANSI colour codes when stdout is piped"
    );
}

// completions generate a shell script; status --json is valid JSON.
#[test]
fn completions_and_status_json() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (o, _e, c) = run(root.path(), &["completions", "bash"]);
    assert_eq!(c, 0);
    assert!(
        o.contains("swapdex"),
        "completion script should mention swapdex"
    );
    let (o2, _e, c2) = run(root.path(), &["status", "--json"]);
    assert_eq!(c2, 0);
    let v: serde_json::Value =
        serde_json::from_str(o2.trim()).expect("status --json must be valid JSON");
    assert!(v.is_array(), "status --json is an array of tools");
}

fn seed_codex_tok(root: &Path, account_id: &str, access: &str, last_refresh: &str) {
    let d = root.join(".codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode":"chatgpt","OPENAI_API_KEY":"sk-X",
            "tokens":{"id_token":"h.eyJlbWFpbCI6ImFAeC5jb20ifQ.s","access_token":access,
                      "refresh_token":"RT","account_id":account_id},
            "last_refresh":last_refresh}))
        .unwrap(),
    )
    .unwrap();
}

fn seed_claude(root: &Path, uuid: &str, email: &str) {
    let d = root.join(".claude");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"AT","refreshToken":"RT","expiresAt":9999999999999i64,
            "subscriptionType":"max"}}))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        root.join(".claude.json"),
        serde_json::to_vec(&serde_json::json!({
            "oauthAccount":{"accountUuid":uuid,"emailAddress":email,"displayName":"X"}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&root.join(".claude/.credentials.json"));
    chmod600(&root.join(".claude.json"));
}

// --tool must reject a typo instead of silently falling through to both.
#[test]
fn tool_typo_is_rejected_not_fail_open() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, e, c) = run(root.path(), &["use", "x", "--tool", "cluade"]);
    assert_ne!(c, 0, "typo'd --tool must be rejected");
    assert!(e.contains("cluade") || e.contains("possible values"), "{e}");
}

// Two accounts with an EMPTY account_id must not compare 'already active' - the
// switch must actually write, never silently keep the wrong account.
#[test]
fn empty_account_id_still_switches() {
    let root = tempfile::tempdir().unwrap();
    seed_codex_tok(root.path(), "", "AAA", "2026-07-04T00:00:00Z");
    run(root.path(), &["add", "p1", "--tool", "codex"]);
    seed_codex_tok(root.path(), "", "BBB", "2026-07-04T00:00:00Z"); // different live login, same empty id
    let (o, _e, c) = run(root.path(), &["use", "p1", "--tool", "codex"]);
    assert_eq!(c, 0);
    assert!(
        !o.contains("already active"),
        "empty ids must not be 'already active': {o}"
    );
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(
        live["tokens"]["access_token"], "AAA",
        "must actually switch to p1"
    );
}

// A both-tool profile with a stale Codex snapshot must show (stale) in ls, even
// though claude-code sorts first.
#[test]
fn ls_shows_stale_codex_in_a_both_tool_profile() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex_tok(root.path(), "acct-A", "AT", "2020-01-01T00:00:00Z"); // stale codex
    run(root.path(), &["add", "work"]); // both tools
    let (o, _e, c) = run(root.path(), &["ls"]);
    assert_eq!(c, 0);
    assert!(
        o.contains("(stale)"),
        "codex staleness must surface in a both-tool profile: {o}"
    );
}

// add <name> default-both attaches a newly-available tool without --update.
#[test]
fn add_default_both_attaches_missing_tool() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com"); // only claude present
    run(root.path(), &["add", "work"]);
    seed_codex_tok(root.path(), "acct-A", "AT", "2026-07-04T00:00:00Z"); // now codex too
    let (o, _e, c) = run(root.path(), &["add", "work"]); // default both, no --update
    assert_eq!(c, 0, "should attach codex without --update: {o}");
    let (ls, _e, _c) = run(root.path(), &["ls"]);
    assert!(
        ls.contains("codex"),
        "codex should now be in the profile: {ls}"
    );
}

// ls marks a Codex profile whose login has not refreshed in a long time as
// stale (its refresh token may have rotated) - a cross-tool safety cue.
#[test]
fn ls_marks_a_stale_codex_profile() {
    let root = tempfile::tempdir().unwrap();
    let d = root.path().join(".codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode":"chatgpt","OPENAI_API_KEY":"sk-X",
            "tokens":{"id_token":"h.eyJlbWFpbCI6ImFAeC5jb20ifQ.s","access_token":"AT",
                      "refresh_token":"RT","account_id":"acct-A"},
            "last_refresh":"2020-01-01T00:00:00Z"}))
        .unwrap(),
    )
    .unwrap();
    run(root.path(), &["add", "old", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &["ls"]);
    assert_eq!(c, 0);
    assert!(
        o.contains("(stale)"),
        "old codex login should be flagged stale: {o}"
    );
}

// BUG1: right after a fresh Claude login there is no ~/.claude.json yet; add must
// still work.
#[test]
fn add_works_without_claude_json() {
    let root = tempfile::tempdir().unwrap();
    let d = root.path().join(".claude");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"AT","refreshToken":"RT","expiresAt":9999999999999i64,
            "subscriptionType":"max"}}))
        .unwrap(),
    )
    .unwrap();
    let (_o, e, c) = run(root.path(), &["add", "work", "--tool", "claude"]);
    assert_eq!(c, 0, "add must work without .claude.json: {e}");
}

// Recovery story: `use` backs up the outgoing login; `restore` must bring it
// back, and a second `restore` must toggle back again (restore is reversible
// because it backs up the current login before applying).
#[test]
fn restore_brings_back_the_pre_switch_login() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B"); // live login is now B (un-saved)

    let (_o, e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_eq!(c, 0, "use failed: {e}");

    // B was never saved as a profile; restore must still bring it back.
    let (o, e, c) = run(root.path(), &["restore", "--tool", "codex"]);
    assert_eq!(c, 0, "restore failed: {e}");
    assert!(o.contains("restored"), "should say what it did: {o}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-B", "B is live again");

    // Toggle back.
    let (_o, e, c) = run(root.path(), &["restore", "--tool", "codex"]);
    assert_eq!(c, 0, "second restore failed: {e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-A", "toggled back to A");
}

#[test]
fn restore_without_backups_is_a_clear_error() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, e, c) = run(root.path(), &["restore", "--tool", "codex"]);
    assert_eq!(c, 5, "no backup -> exit 5: {e}");
    assert!(e.contains("no backup"), "message should say why: {e}");
}

#[test]
fn restore_dry_run_changes_nothing() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["use", "work", "--tool", "codex"]);

    let (o, _e, c) = run(root.path(), &["restore", "--tool", "codex", "--dry-run"]);
    assert_eq!(c, 0);
    assert!(o.contains("would restore"), "dry-run narrates: {o}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-A", "nothing written");
}

// Partial profile: `use` on a profile that lacks a tool the user IS logged into
// must say that tool was left unchanged (silent partial switches confuse).
#[test]
fn use_notes_a_tool_left_unchanged() {
    let root = tempfile::tempdir().unwrap();
    // Logged into codex AND claude, but the profile only saves codex.
    seed_codex(root.path(), "acct-A");
    let d = root.path().join(".claude");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"AT","refreshToken":"RT","expiresAt":9999999999999i64,
            "subscriptionType":"max"}}))
        .unwrap(),
    )
    .unwrap();
    run(root.path(), &["add", "cx", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    let (o, e, c) = run(root.path(), &["use", "cx"]);
    assert_eq!(c, 0, "use failed: {e}");
    assert!(
        (o.clone() + &e).contains("unchanged"),
        "must note claude-code was left unchanged: {o}{e}"
    );
}

fn claude_live_uuid(root: &Path) -> String {
    let v: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.join(".claude.json")).unwrap()).unwrap();
    v["oauthAccount"]["accountUuid"]
        .as_str()
        .unwrap()
        .to_string()
}

// Bare `restore` must undo the LAST SWITCH only - not rewind every tool to its
// newest backup. A codex-only switch followed by a bare restore must leave
// claude-code untouched even though claude has an (older) backup.
#[test]
fn bare_restore_scopes_to_the_last_switch() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-C1", "c1@x.com");
    seed_codex(root.path(), "acct-X");
    run(root.path(), &["add", "p1"]); // saves both tools

    seed_claude(root.path(), "uuid-C2", "c2@x.com"); // live claude now C2
    seed_codex(root.path(), "acct-Y"); // live codex now Y
    let (_o, e, c) = run(root.path(), &["use", "p1"]); // both switch; backups: claude=C2, codex=Y
    assert_eq!(c, 0, "use p1 failed: {e}");
    std::thread::sleep(std::time::Duration::from_millis(1100)); // separate timeline seconds

    seed_codex(root.path(), "acct-Z"); // fresh codex login appears
    let (_o, e, c) = run(root.path(), &["use", "p1", "--tool", "codex"]); // codex-only switch; backup=Z
    assert_eq!(c, 0, "codex-only use failed: {e}");

    let (o, e, c) = run(root.path(), &["restore"]);
    assert_eq!(c, 0, "bare restore failed: {e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-Z", "codex undone: {o}");
    assert_eq!(
        claude_live_uuid(root.path()),
        "uuid-C1",
        "claude-code was NOT part of the last switch and must stay: {o}{e}"
    );
}

// `use` must warn when the OUTGOING live login is not saved as any profile -
// only the last 2 backups will remember it.
#[test]
fn use_warns_when_outgoing_login_is_unsaved() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-PRECIOUS"); // logged in, never saved
    let (o, e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_eq!(c, 0, "use failed: {e}");
    assert!(
        (o + &e).contains("not saved"),
        "must warn the outgoing login is unsaved"
    );
}

#[test]
fn rename_collision_exits_6() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    run(
        root.path(),
        &["add", "personal", "--tool", "codex", "--update"],
    );
    let (_o, e, c) = run(root.path(), &["rename", "work", "personal"]);
    assert_eq!(
        c, 6,
        "collision is 'already exists' (6), not a hard error: {e}"
    );
}

#[test]
fn login_claude_missing_cli_exits_3() {
    let root = tempfile::tempdir().unwrap();
    let out = Command::new(bin())
        .args(["login", "x", "--tool", "claude"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", "/nonexistent")
        .output()
        .unwrap();
    assert_eq!(
        out.status.code().unwrap_or(-1),
        3,
        "missing claude CLI must exit 3 like codex"
    );
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("PATH"),
        "guidance goes to stderr"
    );
}

// A corrupt live credential file must not block the one command that can fix
// it: `use <good-profile>` should warn, skip the backup, and apply.
#[test]
fn use_replaces_a_corrupt_live_login() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    std::fs::write(root.path().join(".codex/auth.json"), b"NOT JSON{{{").unwrap();

    let (_o, e, c) = run(root.path(), &["use", "work", "--tool", "codex"]);
    assert_eq!(c, 0, "use must recover from a corrupt live file: {e}");
    assert!(
        e.contains("could not be read"),
        "warns about the skipped backup: {e}"
    );
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(
        live["tokens"]["account_id"], "acct-A",
        "good snapshot applied"
    );
}

// status must report an unreadable login file per tool instead of dying
// mid-output, and status --json must mark it rather than claim logged_in:false.
#[test]
fn status_reports_unreadable_login_file() {
    let root = tempfile::tempdir().unwrap();
    let d = root.path().join(".codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(d.join("auth.json"), b"NOT JSON{{{").unwrap();

    let (o, e, c) = run(root.path(), &["status"]);
    assert_eq!(c, 0, "status must not abort: {e}");
    assert!(o.contains("unreadable"), "says the file is unreadable: {o}");

    let (o, _e, c) = run(root.path(), &["status", "--json"]);
    assert_eq!(c, 0);
    let v: serde_json::Value = serde_json::from_str(o.trim()).unwrap();
    let codex = v
        .as_array()
        .unwrap()
        .iter()
        .find(|r| r["tool"] == "codex")
        .unwrap();
    assert_eq!(codex["unreadable"], true, "json marks unreadable: {o}");
}

// doctor: a healthy setup reports ok per section and exits 0.
#[test]
fn doctor_healthy_exits_zero() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let (o, e, c) = run(root.path(), &["doctor"]);
    assert_eq!(c, 0, "healthy doctor must exit 0: {o}{e}");
    assert!(o.contains("ok"), "reports ok sections: {o}");
    assert!(
        !o.contains("problem"),
        "no problems on a healthy setup: {o}"
    );
}

// doctor: a corrupt saved snapshot is found, named, and given a remedy; the
// exit code (9) tells scripts that problems exist.
#[test]
fn doctor_flags_corrupt_snapshot_with_remedy() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    // Corrupt the stored snapshot blob.
    let blob = root
        .path()
        .join(".local/share/swapdex/accounts/work/codex/auth");
    std::fs::write(&blob, b"NOT JSON{{{").unwrap();
    let (o, _e, c) = run(root.path(), &["doctor"]);
    assert_eq!(c, 9, "problems -> exit 9: {o}");
    assert!(o.contains("work"), "names the profile: {o}");
    assert!(o.contains("--update"), "gives the remedy: {o}");
}

// doctor: a corrupt LIVE login file is flagged with the use-a-profile remedy.
#[test]
fn doctor_flags_corrupt_live_login() {
    let root = tempfile::tempdir().unwrap();
    let d = root.path().join(".codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(d.join("auth.json"), b"NOT JSON{{{").unwrap();
    let (o, _e, c) = run(root.path(), &["doctor"]);
    assert_eq!(c, 9);
    assert!(o.contains("unreadable"), "{o}");
}

// `manpage` prints a roff man page to stdout (consumed by the Homebrew formula
// at install time; also `swapdex manpage > /usr/local/share/man/man1/swapdex.1`).
#[test]
fn manpage_emits_roff() {
    let root = tempfile::tempdir().unwrap();
    let (o, _e, c) = run(root.path(), &["manpage"]);
    assert_eq!(c, 0);
    assert!(
        o.contains(".TH swapdex 1"),
        "roff man header present: {}",
        &o[..o.len().min(80)]
    );
    assert!(o.contains("restore"), "documents the subcommands");
}

// `use -` toggles to the other profile (the daily-driver shortcut: most users
// have exactly work + personal).
#[test]
fn use_dash_toggles_between_two_profiles() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    // live is B (= personal). `use -` must flip to work...
    let (o, e, c) = run(root.path(), &["use", "-"]);
    assert_eq!(c, 0, "use - failed: {o}{e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-A", "toggled to work");
    // ...and again back to personal.
    let (_o, _e, c) = run(root.path(), &["use", "-"]);
    assert_eq!(c, 0);
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-B", "toggled back");
}

#[test]
fn use_dash_with_ambiguity_refuses_with_candidates() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "one", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "two", "--tool", "codex"]);
    seed_codex(root.path(), "acct-C");
    run(root.path(), &["add", "three", "--tool", "codex"]);
    // 3 profiles, no prior switch on the timeline -> ambiguous target.
    let (_o, e, c) = run(root.path(), &["use", "-"]);
    assert_ne!(c, 0, "ambiguous toggle must refuse");
    assert!(
        e.contains("one") || e.contains("swapdex use"),
        "lists a way out: {e}"
    );
}

// Unique-prefix matching on `use`: `use w` finds "work"; an ambiguous prefix
// refuses and lists the candidates instead of guessing.
#[test]
fn use_unique_prefix_matches() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    let (o, e, c) = run(root.path(), &["use", "w"]);
    assert_eq!(c, 0, "unique prefix must resolve: {e}");
    assert!(
        (o + &e).contains("work"),
        "says which profile it resolved to"
    );
}

#[test]
fn use_ambiguous_prefix_refuses() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "prod-a", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "prod-b", "--tool", "codex"]);
    let (_o, e, c) = run(root.path(), &["use", "prod"]);
    assert_eq!(c, 5, "ambiguous prefix -> no such profile class: {e}");
    assert!(
        e.contains("prod-a") && e.contains("prod-b"),
        "lists candidates: {e}"
    );
}

// status --short: one line for shell prompts / statuslines.
#[test]
fn status_short_is_one_compact_line() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &["status", "--short"]);
    assert_eq!(c, 0);
    assert_eq!(o.trim().lines().count(), 1, "exactly one line: {o}");
    assert!(o.contains("codex:work"), "tool:profile pairs: {o}");
}

// On a terminal, `rm` asks y/N instead of demanding --yes (scripts still get
// exit 7 when stdin is not a tty - covered by rm_requires_yes elsewhere).
#[test]
fn rm_confirms_interactively_on_tty() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "victim", "--tool", "codex"]);
    let mut child = Command::new(bin())
        .args(["rm", "victim"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"y\n").unwrap();
    let out = child.wait_with_output().unwrap();
    assert_eq!(out.status.code().unwrap_or(-1), 0);
    let (ls, _e, _c) = run(root.path(), &["ls"]);
    assert!(!ls.contains("victim"), "profile removed after y: {ls}");
}

// `ls --names`: bare profile names, one per line - for scripts and the
// tab-completion snippet in the docs (no jq needed).
#[test]
fn ls_names_prints_bare_names() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &["ls", "--names"]);
    assert_eq!(c, 0);
    assert_eq!(o, "personal\nwork\n", "bare sorted names only: {o:?}");
}

// `add` with no name: on a terminal it suggests a name from the live account
// (like setup); non-interactively it errors with guidance instead of a bare
// clap usage error.
#[test]
fn add_without_name_asks_on_tty() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let mut child = Command::new(bin())
        .arg("add")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // Accept the suggested default by pressing enter.
    child.stdin.as_mut().unwrap().write_all(b"\n").unwrap();
    let out = child.wait_with_output().unwrap();
    assert_eq!(out.status.code().unwrap_or(-1), 0);
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert_eq!(names, "a\n", "saved under the suggested name: {names:?}");
}

#[test]
fn add_without_name_errors_helpfully_non_tty() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, e, c) = run(root.path(), &["add"]);
    assert_eq!(c, 2, "non-tty add without a name is an argument error");
    assert!(e.contains("swapdex add <name>"), "guides the fix: {e}");
}

// REVIEW-1 (must-fix): `use ""` (e.g. an unset shell variable) must NOT match
// the single profile as a "unique prefix" and switch - it is an invalid name.
#[test]
fn use_empty_string_never_switches() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-UNSAVED"); // live: an unsaved account
    let (_o, _e, c) = run(root.path(), &["use", ""]);
    assert_eq!(c, 2, "empty name is invalid, never a prefix match");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(
        live["tokens"]["account_id"], "acct-UNSAVED",
        "live login untouched"
    );
}

// REVIEW-6: `rm ghost` must say "no profile" without first asking y/N.
#[test]
fn rm_nonexistent_does_not_prompt() {
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    let out = Command::new(bin())
        .args(["rm", "ghost"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::null()) // would EOF the prompt if one appeared
        .output()
        .unwrap();
    assert_eq!(
        out.status.code().unwrap_or(-1),
        5,
        "straight to 'no profile'"
    );
    assert!(
        !String::from_utf8_lossy(&out.stdout).contains("delete saved profile"),
        "no confirmation prompt for a ghost"
    );
}

// REVIEW-5: with the live identity unreadable/empty, `use -` must not
// "toggle" right back to the profile of the newest switch (= where you are).
#[test]
fn use_dash_never_repicks_the_newest_switch_destination() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "a", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "b", "--tool", "codex"]);
    seed_codex(root.path(), "acct-C");
    run(root.path(), &["add", "c", "--tool", "codex"]);
    run(root.path(), &["use", "a", "--tool", "codex"]);
    // Live identity degrades (empty account_id): nothing matches a profile.
    seed_codex(root.path(), "");
    let (_o, e, _c) = run(root.path(), &["use", "-"]);
    assert!(
        !e.contains("'-' -> 'a'"),
        "must not re-pick the newest switch destination: {e}"
    );
}

// ls aligns by DISPLAY width: a CJK profile name (2 columns per char) must not
// shear the table for the profiles after it.
#[test]
fn ls_aligns_cjk_names_by_display_width() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "회사계정", "--tool", "codex"]); // 4 chars, 8 columns
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]); // 8 chars, 8 columns
    let (o, _e, c) = run(root.path(), &["ls"]);
    assert_eq!(c, 0);
    // Both rows must place the email at the same DISPLAY column (CJK ~ 2).
    fn disp_prefix(l: &str) -> usize {
        let idx = l.find("a@x.com").unwrap();
        l[..idx]
            .chars()
            .map(|c| if (c as u32) >= 0x1100 { 2 } else { 1 })
            .sum()
    }
    let widths: Vec<usize> = o
        .lines()
        .filter(|l| l.contains("a@x.com"))
        .map(disp_prefix)
        .collect();
    assert_eq!(widths.len(), 2, "both rows visible: {o}");
    assert_eq!(
        widths[0], widths[1],
        "email column must align in display columns: {o}"
    );
}

// `ui`: a numbered interactive picker. Piped "2" selects the second profile
// and performs the switch; plain Enter cancels without touching anything.
fn run_ui(root: &Path, input: &str) -> (String, String, i32) {
    use std::io::Write;
    use std::process::Stdio;
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .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(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

#[test]
fn ui_picker_switches_by_number() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    // live is B (= beta). The list is sorted: 1) alpha 2) beta. Pick 1.
    let (o, e, c) = run_ui(root.path(), "1\n");
    assert_eq!(c, 0, "picker switch failed: {o}{e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-A", "switched to alpha");
}

#[test]
fn ui_picker_enter_cancels() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    let (o, _e, c) = run_ui(root.path(), "\n");
    assert_eq!(c, 0);
    assert!(
        o.contains("cancel") || o.contains("nothing"),
        "says it did nothing: {o}"
    );
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(live["tokens"]["account_id"], "acct-B", "nothing switched");
}

#[test]
fn ui_picker_rejects_bad_number_then_accepts() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    let (o, e, c) = run_ui(root.path(), "9\n1\n");
    assert_eq!(c, 0, "{o}{e}");
    let live: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(
        live["tokens"]["account_id"], "acct-A",
        "re-prompt then switch"
    );
}

#[test]
fn ui_non_tty_degrades_gracefully() {
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    let out = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .stdin(Stdio::null())
        .output()
        .unwrap();
    assert_ne!(out.status.code().unwrap_or(-1), 0);
    assert!(
        String::from_utf8_lossy(&out.stderr).contains("terminal"),
        "explains it needs a terminal"
    );
}

// After a switch, picking a numbered session hands off to the official flow:
// swapdex execs `sessionwiki resume <id>` (one-shot handoff on explicit human
// action - the same precedent as `login` spawning `codex login`).
#[test]
fn ui_resume_pick_execs_sessionwiki() {
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);

    // Session fixture + a fake `sessionwiki` that proves the exec happened.
    let fixture = root.path().join("sessions.json");
    std::fs::write(
        &fixture,
        serde_json::to_vec(&serde_json::json!([
            {"id":"aaa111","tool":"codex","title":"fix the retry loop",
             "started":"2099-01-01T00:00:00Z"}
        ]))
        .unwrap(),
    )
    .unwrap();
    let bin_dir = root.path().join("fakebin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("sessionwiki");
    std::fs::write(&fake, "#!/bin/sh\necho \"RESUMED $4\"\n").unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();

    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("SWAPDEX_SESSIONWIKI_JSON", &fixture)
        .env("PATH", &path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // Pick profile 1 (alpha), then resume session 1.
    child.stdin.as_mut().unwrap().write_all(b"1\n1\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(
        o.contains("RESUMED aaa111"),
        "exec'd sessionwiki resume: {o}"
    );
}

// Enter at the resume prompt skips - no exec, clean exit.
#[test]
fn ui_resume_enter_skips() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    let fixture = root.path().join("sessions.json");
    std::fs::write(
        &fixture,
        serde_json::to_vec(&serde_json::json!([
            {"id":"aaa111","tool":"codex","title":"t","started":"2099-01-01T00:00:00Z"}
        ]))
        .unwrap(),
    )
    .unwrap();
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("SWAPDEX_SESSIONWIKI_JSON", &fixture)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"1\n\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(!o.contains("RESUMED"), "no exec on skip: {o}");
}

// REVIEW: a multibyte session id must not panic the ui hint (byte-6 slice).
#[test]
fn ui_hint_survives_multibyte_session_id() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    let fixture = root.path().join("sessions.json");
    std::fs::write(
        &fixture,
        serde_json::to_vec(&serde_json::json!([
            {"id":"a日本語id","tool":"codex","title":"t","started":"2099-01-01T00:00:00Z"}
        ]))
        .unwrap(),
    )
    .unwrap();
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("SWAPDEX_SESSIONWIKI_JSON", &fixture)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"1\n\n").unwrap();
    let out = child.wait_with_output().unwrap();
    assert_eq!(
        out.status.code().unwrap_or(-1),
        0,
        "no panic on multibyte id: {}",
        String::from_utf8_lossy(&out.stderr)
    );
}

// REVIEW: the any-account fallback must fire on the FIRST real switch (the
// timeline check has to happen before use_account writes the switch event).
#[test]
fn ui_hint_fallback_fires_on_first_real_switch() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    // A session that PREDATES every switch (nothing attributable).
    let fixture = root.path().join("sessions.json");
    std::fs::write(
        &fixture,
        serde_json::to_vec(&serde_json::json!([
            {"id":"aaa111","tool":"codex","title":"old work","started":"2000-01-01T00:00:00Z"}
        ]))
        .unwrap(),
    )
    .unwrap();
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("SWAPDEX_SESSIONWIKI_JSON", &fixture)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // Pick alpha = a REAL switch (live is beta).
    child.stdin.as_mut().unwrap().write_all(b"1\n\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains("recent sessions"),
        "fallback hint must appear on the first real switch: {o}"
    );
}

fn seed_gemini(root: &Path, sub: &str, email: &str) {
    use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
    let d = root.join(".gemini");
    std::fs::create_dir_all(&d).unwrap();
    let payload = URL_SAFE_NO_PAD
        .encode(serde_json::to_vec(&serde_json::json!({"sub": sub, "email": email})).unwrap());
    std::fs::write(
        d.join("oauth_creds.json"),
        serde_json::to_vec(&serde_json::json!({
            "access_token":"AT-SENTINEL","refresh_token":"RT-SENTINEL",
            "id_token": format!("h.{payload}.s"),
            "expiry_date": 9999999999999i64,
            "scope":"openid","token_type":"Bearer"}))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        d.join("google_accounts.json"),
        serde_json::to_vec(&serde_json::json!({"active": email, "old": []})).unwrap(),
    )
    .unwrap();
    chmod600(&root.join(".gemini/oauth_creds.json"));
    chmod600(&root.join(".gemini/google_accounts.json"));
}

// Gemini: add/use roundtrip switches BOTH files together, ls shows the email,
// and no command leaks the sentinel tokens.
#[test]
fn gemini_add_use_roundtrip() {
    let root = tempfile::tempdir().unwrap();
    seed_gemini(root.path(), "sub-A", "a@gmail.com");
    let (_o, e, c) = run(root.path(), &["add", "gwork", "--tool", "gemini"]);
    assert_eq!(c, 0, "add failed: {e}");
    seed_gemini(root.path(), "sub-B", "b@gmail.com");
    run(root.path(), &["add", "ghome", "--tool", "gemini"]);

    let (o, e, c) = run(root.path(), &["use", "gwork", "--tool", "gemini"]);
    assert_eq!(c, 0, "use failed: {o}{e}");
    let oauth: serde_json::Value = serde_json::from_slice(
        &std::fs::read(root.path().join(".gemini/oauth_creds.json")).unwrap(),
    )
    .unwrap();
    assert!(
        oauth["id_token"].as_str().unwrap().contains("."),
        "oauth swapped"
    );
    let accounts: serde_json::Value = serde_json::from_slice(
        &std::fs::read(root.path().join(".gemini/google_accounts.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(
        accounts["active"], "a@gmail.com",
        "accounts swapped together"
    );

    let (ls, _e, _c) = run(root.path(), &["ls"]);
    assert!(ls.contains("a@gmail.com"), "identity shown: {ls}");
    assert!(ls.contains("[gemini") || ls.contains("gemini"), "{ls}");
    for args in [vec!["ls"], vec!["status"], vec!["ls", "--json"]] {
        let (o, e, _c) = run(root.path(), &args);
        assert!(
            !o.contains("SENTINEL") && !e.contains("SENTINEL"),
            "token leak in {args:?}"
        );
    }
}

// A three-tool machine: one profile holds claude + codex + gemini and a single
// `use` switches all three.
#[test]
fn three_tool_profile_switches_together() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    seed_gemini(root.path(), "sub-A", "a@gmail.com");
    run(root.path(), &["add", "all-a"]);
    seed_claude(root.path(), "uuid-B", "b@x.com");
    seed_codex(root.path(), "acct-B");
    seed_gemini(root.path(), "sub-B", "b@gmail.com");
    run(root.path(), &["add", "all-b"]);

    let (o, e, c) = run(root.path(), &["use", "all-a"]);
    assert_eq!(c, 0, "{o}{e}");
    assert_eq!(claude_live_uuid(root.path()), "uuid-A");
    let codex: serde_json::Value =
        serde_json::from_slice(&std::fs::read(root.path().join(".codex/auth.json")).unwrap())
            .unwrap();
    assert_eq!(codex["tokens"]["account_id"], "acct-A");
    let g: serde_json::Value = serde_json::from_slice(
        &std::fs::read(root.path().join(".gemini/google_accounts.json")).unwrap(),
    )
    .unwrap();
    assert_eq!(g["active"], "a@gmail.com");
    assert_eq!(o.matches("switched").count(), 3, "all three switched: {o}");
}

fn seed_antigravity(root: &Path, refresh: &str) {
    let d = root.join(".gemini").join("antigravity-cli");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("antigravity-oauth-token"),
        serde_json::to_vec(&serde_json::json!({
            "token": {"access_token":"AT-SENTINEL","token_type":"Bearer",
                       "refresh_token": refresh,
                       "expiry":"2026-07-06T10:09:19.638+09:00"},
            "auth_method":"consumer"}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&root.join(".gemini/antigravity-cli/antigravity-oauth-token"));
}

// Antigravity: single-file swap roundtrip; identity has no email (none is
// stored on disk) but a stable token fingerprint matches profiles.
#[test]
fn antigravity_add_use_roundtrip() {
    let root = tempfile::tempdir().unwrap();
    seed_antigravity(root.path(), "RT-SENTINEL-A");
    let (_o, e, c) = run(root.path(), &["add", "aw", "--tool", "antigravity"]);
    assert_eq!(c, 0, "add failed: {e}");
    seed_antigravity(root.path(), "RT-SENTINEL-B");
    run(root.path(), &["add", "ah", "--tool", "antigravity"]);

    let (o, e, c) = run(root.path(), &["use", "aw", "--tool", "antigravity"]);
    assert_eq!(c, 0, "use failed: {o}{e}");
    let tok: serde_json::Value = serde_json::from_slice(
        &std::fs::read(
            root.path()
                .join(".gemini/antigravity-cli/antigravity-oauth-token"),
        )
        .unwrap(),
    )
    .unwrap();
    assert_eq!(tok["token"]["refresh_token"], "RT-SENTINEL-A", "swapped");

    // Already-active no-op works via the fingerprint (no email/id on disk).
    let (o, _e, c) = run(root.path(), &["use", "aw", "--tool", "antigravity"]);
    assert_eq!(c, 0);
    assert!(o.contains("already active"), "{o}");

    // Egress: the refresh token never appears in any output.
    for args in [
        vec!["ls"],
        vec!["status"],
        vec!["ls", "--json"],
        vec!["status", "--json"],
    ] {
        let (o, e, _c) = run(root.path(), &args);
        assert!(
            !o.contains("SENTINEL") && !e.contains("SENTINEL"),
            "token leak in {args:?}: {o}{e}"
        );
    }
}

// THE flow real use demanded: already logged into account A, want to ADD
// account B. `login <name> --tool claude` must save A, sign out locally, run
// claude for the fresh sign-in, and capture B - one command.
fn fake_claude(root: &Path, script: &str) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    let bin_dir = root.join("fakebin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("claude");
    std::fs::write(&fake, script).unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    bin_dir
}

fn run_login_tty(root: &Path, bin_dir: &Path, args: &[&str], input: &str) -> (String, String, i32) {
    use std::io::Write;
    use std::process::Stdio;
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut child = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("PATH", &path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .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(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

#[test]
fn login_claude_adds_a_second_account_in_one_flow() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "old", "--tool", "claude"]);
    // Fake claude: simulates the user signing into account B inside the app.
    // Must answer the `claude --version` probe without touching credentials.
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.claude"
cat > "$SWAPDEX_ROOT/.claude/.credentials.json" <<'CRED'
{"claudeAiOauth":{"accessToken":"AT-B","refreshToken":"RT-B","expiresAt":9999999999999,"subscriptionType":"pro"}}
CRED
cat > "$SWAPDEX_ROOT/.claude.json" <<'CFG'
{"oauthAccount":{"accountUuid":"uuid-B","emailAddress":"b@x.com","displayName":"B"},"projects":{"/keep/me":{"trust":true}}}
CFG
"#;
    let bin_dir = fake_claude(root.path(), script);
    // "y" confirms the sign-out-and-sign-in flow.
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "newacc", "--tool", "claude"],
        "y\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    assert_eq!(claude_live_uuid(root.path()), "uuid-B", "B is live: {o}");
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(names.contains("newacc"), "B saved as newacc: {names}");
    assert!(names.contains("old"), "A's profile still there: {names}");
    // And the old account is one command away.
    let (_o, e, c) = run(root.path(), &["use", "old"]);
    assert_eq!(c, 0, "{e}");
    assert_eq!(
        claude_live_uuid(root.path()),
        "uuid-A",
        "A restored via use"
    );
}

#[test]
fn login_claude_restores_original_when_no_new_signin() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "old", "--tool", "claude"]);
    // Fake claude that exits WITHOUT logging in (user quit / login failed).
    let bin_dir = fake_claude(root.path(), "#!/bin/sh\nexit 0\n");
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "newacc", "--tool", "claude"],
        "y\n",
    );
    assert_eq!(c, 8, "incomplete login flow: {o}{e}");
    assert_eq!(
        claude_live_uuid(root.path()),
        "uuid-A",
        "original login restored - NEVER lost: {o}{e}"
    );
}

// Switch -> conversation opens immediately: 'c' at the post-switch menu execs
// claude; `use --open --tool codex` execs codex right after the switch.
#[test]
fn ui_post_switch_c_opens_claude() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    let bin_dir = fake_claude(root.path(), "#!/bin/sh\necho CLAUDE-OPENED\n");
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("PATH", &path)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"1\nc\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(
        o.contains("CLAUDE-OPENED"),
        "claude exec'd after switch: {o}"
    );
}

#[test]
fn use_open_execs_the_tool() {
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    // fake codex binary
    use std::os::unix::fs::PermissionsExt;
    let bin_dir = root.path().join("fakebin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("codex");
    std::fs::write(&fake, "#!/bin/sh\necho CODEX-OPENED\n").unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = Command::new(bin())
        .args(["use", "alpha", "--tool", "codex", "--open"])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .stdin(Stdio::null())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(o.contains("switched codex"), "{o}");
    assert!(o.contains("CODEX-OPENED"), "codex exec'd after switch: {o}");
}

// Folder choice: the launched conversation opens IN the chosen directory
// (Claude/Codex sessions are per-directory).
#[test]
fn use_open_dir_launches_in_that_folder() {
    use std::os::unix::fs::PermissionsExt;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    let bin_dir = root.path().join("fakebin");
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join("codex");
    std::fs::write(&fake, "#!/bin/sh\necho \"OPENED-IN $(pwd)\"\n").unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    let proj = root.path().join("myproject");
    std::fs::create_dir_all(&proj).unwrap();
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let out = Command::new(bin())
        .args([
            "use",
            "alpha",
            "--tool",
            "codex",
            "--open",
            "--dir",
            proj.to_str().unwrap(),
        ])
        .env("SWAPDEX_ROOT", root.path())
        .env("PATH", &path)
        .stdin(Stdio::null())
        .output()
        .unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains(&format!("OPENED-IN {}", proj.display())),
        "launched in the chosen folder: {o}"
    );
}

// No sessionwiki anywhere: the post-switch menu still lists recent sessions
// (read natively from ~/.claude / ~/.codex) and resumes via the tool's own
// mechanism, in the session's own folder.
#[test]
fn post_switch_native_sessions_without_sessionwiki() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alpha", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "beta", "--tool", "codex"]);
    // A native claude session on disk, with a real cwd recorded.
    let proj_dir = root.path().join("myproj");
    std::fs::create_dir_all(&proj_dir).unwrap();
    let store = root.path().join(".claude/projects/-myproj");
    std::fs::create_dir_all(&store).unwrap();
    std::fs::write(
        store.join("0a000000-0000-4000-8000-0000000000aa.jsonl"),
        format!(
            "{}\n",
            serde_json::json!({"type":"user","cwd":proj_dir.to_str().unwrap(),
                "message":{"content":[{"type":"text","text":"fix the flaky retry test"}]}}),
        ),
    )
    .unwrap();
    // Fake claude proves the native resume exec: prints its args and pwd.
    let bin_dir = fake_claude(
        root.path(),
        "#!/bin/sh\necho \"RESUME-ARGS $@\"\necho \"RESUME-PWD $(pwd)\"\n",
    );
    let path = format!(
        "{}:{}",
        bin_dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("PATH", &path) // no sessionwiki in this PATH
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"1\n1\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(
        o.contains("fix the flaky retry"),
        "native session listed: {o}"
    );
    assert!(
        o.contains("RESUME-ARGS --resume 0a000000-0000-4000-8000-0000000000aa"),
        "claude --resume exec'd: {o}"
    );
    assert!(
        o.contains(&format!("RESUME-PWD {}", proj_dir.display())),
        "opened in the session's own folder: {o}"
    );
}

// Real-use angle-testing round: setup's "add another" must ask WHICH tool
// (the old block was Codex-only - the root of "it keeps asking about Codex"),
// and the login tool question must re-prompt on garbage instead of bailing.
#[test]
fn setup_add_another_asks_which_tool() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let mut child = Command::new(bin())
        .arg("setup")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // name the found login, say yes to "add another", then cancel at the
    // tool question, then no to the loop.
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(b"work\ny\n\nn\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(
        o.contains("which tool?") && o.contains("4) Antigravity"),
        "add-another asks the tool, all four listed: {o}"
    );
    assert!(
        !o.contains("add another Codex account"),
        "the Codex-only prompt is gone: {o}"
    );
}

#[test]
fn login_tool_question_reprompts_on_garbage() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    let mut child = Command::new(bin())
        .args(["login", "newone"])
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    child.stdin.as_mut().unwrap().write_all(b"7\n\n").unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert_eq!(out.status.code().unwrap_or(-1), 0, "{o}");
    assert!(
        o.contains("pick a number between 1 and 4"),
        "garbage re-prompts: {o}"
    );
    assert!(o.contains("cancelled"), "Enter cancels: {o}");
}

// THE deep account bug: refresh tokens ROTATE while you use an account. If
// switching away only writes the outgoing login to the backup ring, the
// matched profile keeps day-one tokens - and switching back later restores a
// refresh token the provider may have already revoked. Switching away must
// refresh the matched profile's snapshot with the live capture.
#[test]
fn switch_away_refreshes_matched_profile_snapshot() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    run(root.path(), &["use", "work"]);
    // Simulate the provider rotating acct-A's tokens during a long session.
    let auth = root.path().join(".codex/auth.json");
    let mut v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&auth).unwrap()).unwrap();
    v["tokens"]["access_token"] = "AT-ROTATED".into();
    v["tokens"]["refresh_token"] = "RT-ROTATED".into();
    std::fs::write(&auth, serde_json::to_string(&v).unwrap()).unwrap();
    // Switch away, then back.
    let (_o, e, c) = run(root.path(), &["use", "personal"]);
    assert_eq!(c, 0, "{e}");
    let (_o, e, c) = run(root.path(), &["use", "work"]);
    assert_eq!(c, 0, "{e}");
    let live = std::fs::read_to_string(&auth).unwrap();
    assert!(
        live.contains("RT-ROTATED"),
        "switching back restores the ROTATED tokens, not day-one ones: {live}"
    );
}

// Same invariant for the login flow's stash: if the current login matches a
// saved profile, the stash (its freshest tokens) must refresh that profile.
#[test]
fn login_flow_refreshes_matched_profile_from_stash() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "old", "--tool", "claude"]);
    // Rotate the live tokens after the profile was saved.
    let cred = root.path().join(".claude/.credentials.json");
    let mut v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&cred).unwrap()).unwrap();
    v["claudeAiOauth"]["refreshToken"] = "RT-ROTATED".into();
    std::fs::write(&cred, serde_json::to_string(&v).unwrap()).unwrap();
    // Add account B through the login flow. The fake must answer --version
    // WITHOUT touching credentials - swapdex probes `claude --version` first.
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.claude"
cat > "$SWAPDEX_ROOT/.claude/.credentials.json" <<'CRED'
{"claudeAiOauth":{"accessToken":"AT-B","refreshToken":"RT-B","expiresAt":9999999999999,"subscriptionType":"pro"}}
CRED
cat > "$SWAPDEX_ROOT/.claude.json" <<'CFG'
{"oauthAccount":{"accountUuid":"uuid-B","emailAddress":"b@x.com","displayName":"B"},"projects":{}}
CFG
"#;
    let bin_dir = fake_claude(root.path(), script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "newacc", "--tool", "claude"],
        "y\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    // Back to the old account: must carry the rotated token.
    let (_o, e, c) = run(root.path(), &["use", "old"]);
    assert_eq!(c, 0, "{e}");
    let live = std::fs::read_to_string(&cred).unwrap();
    assert!(
        live.contains("RT-ROTATED"),
        "profile 'old' was refreshed from the stash: {live}"
    );
}

// Deep account-security angle: snapshots ARE tokens. If anything loosens a
// mode inside the store (backup tools, cp -r, umask accidents), opening the
// store must tighten it back - 0700 dirs, 0600 files, all the way down.
#[test]
fn store_open_tightens_loose_permissions() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let dir = root.path().join(".local/share/swapdex/accounts/work/codex");
    let file = dir.join("auth");
    std::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o755)).unwrap();
    std::fs::set_permissions(&file, std::fs::Permissions::from_mode(0o644)).unwrap();
    // Any store-opening command repairs the modes.
    run(root.path(), &["ls"]);
    let dmode = std::fs::metadata(&dir).unwrap().permissions().mode() & 0o777;
    let fmode = std::fs::metadata(&file).unwrap().permissions().mode() & 0o777;
    assert_eq!(dmode, 0o700, "dir tightened");
    assert_eq!(fmode, 0o600, "token file tightened");
}

// Deep-dig round 2: the rotation invariant must hold on EVERY path that
// touches the live login, not just `use` switching away.
#[test]
fn restore_refreshes_outgoing_matched_profile() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    // Live is personal (B) after its add; switch to work so a backup of B
    // exists and A is live.
    run(root.path(), &["use", "work"]);
    // Rotation while on work.
    let auth = root.path().join(".codex/auth.json");
    let mut v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&auth).unwrap()).unwrap();
    v["tokens"]["refresh_token"] = "RT-ROTATED".into();
    std::fs::write(&auth, serde_json::to_string(&v).unwrap()).unwrap();
    // restore = undo the switch (back to personal); outgoing work must be
    // refreshed with the rotated tokens.
    let (_o, e, c) = run(root.path(), &["restore"]);
    assert_eq!(c, 0, "{e}");
    let (_o, e, c) = run(root.path(), &["use", "work"]);
    assert_eq!(c, 0, "{e}");
    let live = std::fs::read_to_string(&auth).unwrap();
    assert!(
        live.contains("RT-ROTATED"),
        "restore refreshed 'work': {live}"
    );
}

#[test]
fn use_noop_still_refreshes_profile() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let auth = root.path().join(".codex/auth.json");
    let mut v: serde_json::Value =
        serde_json::from_str(&std::fs::read_to_string(&auth).unwrap()).unwrap();
    v["tokens"]["refresh_token"] = "RT-ROTATED".into();
    std::fs::write(&auth, serde_json::to_string(&v).unwrap()).unwrap();
    let (o, _e, c) = run(root.path(), &["use", "work"]);
    assert_eq!(c, 0);
    assert!(o.contains("already active"), "{o}");
    // The no-op must still sync the profile snapshot with the live tokens.
    let stored = std::fs::read_to_string(
        root.path()
            .join(".local/share/swapdex/accounts/work/codex/auth"),
    )
    .unwrap();
    assert!(
        stored.contains("RT-ROTATED"),
        "no-op use refreshed the snapshot: {stored}"
    );
}

// `add --update` while logged into a DIFFERENT account must not silently
// repoint the profile - that changes what the name means.
#[test]
fn add_update_refuses_account_change_noninteractive() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    let (_o, e, c) = run(root.path(), &["add", "work", "--tool", "codex", "--update"]);
    assert_eq!(c, 7, "refused: {e}");
    assert!(
        e.contains("different account"),
        "says WHY and what it holds: {e}"
    );
    // Profile still holds acct-A.
    let stored = std::fs::read_to_string(
        root.path()
            .join(".local/share/swapdex/accounts/work/codex/auth"),
    )
    .unwrap();
    assert!(stored.contains("acct-A"), "unchanged: {stored}");
}

// THE core journey must work for ALL FOUR tools, not just claude: already
// logged into A, `login <name> --tool T` adds account B in one flow (save
// current, sign out locally, run the tool's own sign-in, capture B).
fn fake_tool(root: &Path, bin: &str, script: &str) -> std::path::PathBuf {
    use std::os::unix::fs::PermissionsExt;
    let bin_dir = root.join("fakebin").join(bin);
    std::fs::create_dir_all(&bin_dir).unwrap();
    let fake = bin_dir.join(bin);
    std::fs::write(&fake, script).unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    bin_dir
}

#[test]
fn login_gemini_adds_a_second_account_in_one_flow() {
    let root = tempfile::tempdir().unwrap();
    seed_gemini(root.path(), "a@x.com", "sub-A");
    run(root.path(), &["add", "old", "--tool", "gemini"]);
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.gemini"
printf '%s' '{"access_token":"AT-B","refresh_token":"RT-B","id_token":"h.eyJlbWFpbCI6ImJAeC5jb20iLCJzdWIiOiJzdWItQiJ9.s","expiry_date":9999999999999}' > "$SWAPDEX_ROOT/.gemini/oauth_creds.json"
printf '%s' '{"active":"b@x.com"}' > "$SWAPDEX_ROOT/.gemini/google_accounts.json"
"#;
    let bin_dir = fake_tool(root.path(), "gemini", script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "gemini"],
        "y\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(names.contains("second"), "B saved: {names}");
    // Old account one command away, with its original identity.
    let (_o, e, c) = run(root.path(), &["use", "old"]);
    assert_eq!(c, 0, "{e}");
    let creds = std::fs::read_to_string(root.path().join(".gemini/oauth_creds.json")).unwrap();
    assert!(creds.contains("RT-SENTINEL"), "A restored: {creds}");
}

#[test]
fn login_antigravity_adds_a_second_account_in_one_flow() {
    let root = tempfile::tempdir().unwrap();
    seed_antigravity(root.path(), "RT-A");
    run(root.path(), &["add", "old", "--tool", "antigravity"]);
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.gemini/antigravity-cli"
printf '%s' '{"token":{"access_token":"AT-B","refresh_token":"RT-B","expiry":"2027-01-01T00:00:00Z","token_type":"Bearer"},"auth_method":"consumer"}' > "$SWAPDEX_ROOT/.gemini/antigravity-cli/antigravity-oauth-token"
"#;
    let bin_dir = fake_tool(root.path(), "agy", script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "antigravity"],
        "y\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(names.contains("second") && names.contains("old"), "{names}");
    let (_o, e, c) = run(root.path(), &["use", "old"]);
    assert_eq!(c, 0, "{e}");
    let tok = std::fs::read_to_string(
        root.path()
            .join(".gemini/antigravity-cli/antigravity-oauth-token"),
    )
    .unwrap();
    assert!(tok.contains("RT-A"), "A restored: {tok}");
}

#[test]
fn login_gemini_restores_original_when_no_new_signin() {
    let root = tempfile::tempdir().unwrap();
    seed_gemini(root.path(), "a@x.com", "sub-A");
    run(root.path(), &["add", "old", "--tool", "gemini"]);
    let bin_dir = fake_tool(
        root.path(),
        "gemini",
        "#!/bin/sh\ncase \"$1\" in --version) echo 1.0.0; exit 0;; esac\nexit 0\n",
    );
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "gemini"],
        "y\n",
    );
    assert_eq!(c, 8, "incomplete: {o}{e}");
    let creds = std::fs::read_to_string(root.path().join(".gemini/oauth_creds.json")).unwrap();
    // The original seed's tokens, byte-identical (ids live inside JWT b64).
    assert!(creds.contains("RT-SENTINEL"), "A NEVER lost: {creds}");
}

// Ctrl+C during the interactive sign-in goes to the whole foreground process
// group. swapdex must SURVIVE it and run the restore-stash branch - dying
// would leave the user locally signed out of everything.
#[test]
fn login_survives_sigint_and_restores() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "old", "--tool", "claude"]);
    // Fake claude: SIGINTs its parent (swapdex) mid-login, then exits
    // without completing any sign-in.
    let script = "#!/bin/sh\ncase \"$1\" in --version) echo 1.0.0; exit 0;; esac\nkill -INT $PPID\nsleep 0.3\nexit 130\n";
    let bin_dir = fake_claude(root.path(), script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "claude"],
        "y\n",
    );
    assert_eq!(c, 8, "survived SIGINT, reported incomplete: {o}{e}");
    assert!(e.contains("was restored"), "restore branch ran: {e}");
    assert_eq!(
        claude_live_uuid(root.path()),
        "uuid-A",
        "previous login restored, NOT left signed out"
    );
}

// Walkthrough-audit HIGHs.

// Enter-through setup must attach every logged-in tool to the suggested
// profile, not scare the user with "replace it?" and silently skip 3 of 4.
#[test]
fn setup_enter_through_attaches_all_tools() {
    use std::io::Write;
    use std::process::Stdio;
    let root = tempfile::tempdir().unwrap();
    // Same email on both tools -> the SAME suggested name, which is where
    // the old "replace it?" prompt silently skipped the second tool.
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    let mut child = Command::new(bin())
        .arg("setup")
        .env("SWAPDEX_ROOT", root.path())
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    // Enter for each tool's default name, then 'n' to add-another.
    child
        .stdin
        .as_mut()
        .unwrap()
        .write_all(b"\n\n\nn\n")
        .unwrap();
    let out = child.wait_with_output().unwrap();
    let o = String::from_utf8_lossy(&out.stdout);
    assert!(!o.contains("replace it?"), "no replace scare: {o}");
    let (l, _e, _c) = run(root.path(), &["ls"]);
    assert!(
        l.contains("claude-code") && l.contains("codex"),
        "both tools attached to one profile: {l}"
    );
}

// A corrupt LIVE ~/.claude.json must be diagnosed as such - not blamed on
// the profile snapshot with a remedy that also fails - and doctor must flag it.
#[test]
fn corrupt_live_claude_config_diagnosed_not_blamed_on_snapshot() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "alice", "--tool", "claude"]);
    seed_claude(root.path(), "uuid-B", "b@x.com");
    run(root.path(), &["add", "bob", "--tool", "claude"]);
    std::fs::write(root.path().join(".claude.json"), b"not json{{").unwrap();
    // Correct perms, so doctor's permission check cannot mask the real test:
    // diagnosing the CORRUPTION itself.
    std::fs::set_permissions(
        root.path().join(".claude.json"),
        std::os::unix::fs::PermissionsExt::from_mode(0o600),
    )
    .unwrap();
    let (_o, e, c) = run(root.path(), &["use", "alice", "--tool", "claude"]);
    assert_ne!(c, 0);
    assert!(
        e.contains(".claude.json") && e.to_lowercase().contains("live"),
        "blames the LIVE file, not the snapshot: {e}"
    );
    let (o, _e, c) = run(root.path(), &["doctor"]);
    assert_eq!(c, 9, "doctor flags it: {o}");
    assert!(o.contains(".claude.json"), "doctor names the file: {o}");
}

// A per-tool failure must not abort the whole multi-tool switch: the other
// tools still switch, and a summary says what failed.
#[test]
fn use_continues_past_a_failing_tool() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alice"]);
    seed_claude(root.path(), "uuid-B", "b@x.com");
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "bob"]);
    // Corrupt alice's CODEX snapshot in the store.
    std::fs::write(
        root.path()
            .join(".local/share/swapdex/accounts/alice/codex/auth"),
        b"broken{{",
    )
    .unwrap();
    let (o, e, c) = run(root.path(), &["use", "alice"]);
    assert_eq!(c, 1, "partial switch exits 1: {o}{e}");
    assert_eq!(claude_live_uuid(root.path()), "uuid-A", "claude DID switch");
    assert!(
        e.contains("codex") && e.contains("failed"),
        "summary names the failed tool: {e}"
    );
    assert!(e.contains("restore"), "points at the undo: {e}");
}

// Same for add: a corrupt live login for one tool must not silently create a
// partial profile with exit 1 and no explanation.
#[test]
fn add_reports_a_failing_tool_and_keeps_going() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    std::fs::write(root.path().join(".codex/auth.json"), b"broken{{").unwrap();
    let (o, e, c) = run(root.path(), &["add", "prof"]);
    assert_eq!(c, 1, "{o}{e}");
    assert!(
        o.contains("saved profile 'prof'"),
        "claude still saved: {o}"
    );
    assert!(
        e.contains("codex") && (e.contains("skipped") || e.contains("could not")),
        "explains the skipped tool: {e}"
    );
}

// Walkthrough-audit MEDIUMs.
#[test]
fn login_reserved_name_dash_rejected() {
    let root = tempfile::tempdir().unwrap();
    let (_o, e, c) = run(root.path(), &["login", "-", "--tool", "codex"]);
    assert_ne!(c, 0, "'-' is the toggle, never a profile name: {e}");
}

#[test]
fn use_typo_is_one_line() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work"]);
    let (o, e, c) = run(root.path(), &["use", "zzz"]);
    assert_eq!(c, 5);
    assert!(
        !o.contains("left unchanged") && !e.contains("left unchanged"),
        "no per-tool noise for a typo: {o}{e}"
    );
}

#[test]
fn multi_tool_tier_prefers_claude_over_antigravity() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_antigravity(root.path(), "RT-A");
    run(root.path(), &["add", "all2"]);
    let (o, _e, _c) = run(root.path(), &["ls"]);
    assert!(
        o.contains("[max]"),
        "claude's real plan tier, not antigravity's auth_method: {o}"
    );
}

#[test]
fn rename_rewrites_timeline_attribution() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "alice", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "bob", "--tool", "codex"]);
    run(root.path(), &["use", "alice"]);
    run(root.path(), &["rename", "alice", "corp"]);
    let tl =
        std::fs::read_to_string(root.path().join(".local/share/swapdex/timeline.jsonl")).unwrap();
    assert!(
        !tl.contains("\"alice\"") && tl.contains("\"corp\""),
        "timeline follows the rename: {tl}"
    );
}

// Walkthrough-audit LOWs.
#[test]
fn ls_hides_ghost_dirs_and_unknown_tools() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "bee", "--tool", "codex"]);
    std::fs::create_dir_all(root.path().join(".local/share/swapdex/accounts/ghosty")).unwrap();
    std::fs::create_dir_all(
        root.path()
            .join(".local/share/swapdex/accounts/bee/fakedir"),
    )
    .unwrap();
    let (o, _e, _c) = run(root.path(), &["ls"]);
    assert!(!o.contains("ghosty"), "empty dir is not a profile: {o}");
    assert!(!o.contains("fakedir"), "unknown subdir is not a tool: {o}");
}

#[test]
fn whitespace_only_name_rejected() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    let (_o, e, c) = run(root.path(), &["add", "   ", "--tool", "codex"]);
    assert_eq!(c, 2, "{e}");
}

#[test]
fn doctor_flags_loose_live_cred_perms() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    std::fs::set_permissions(
        root.path().join(".codex/auth.json"),
        std::fs::Permissions::from_mode(0o644),
    )
    .unwrap();
    let (o, _e, c) = run(root.path(), &["doctor"]);
    assert_eq!(c, 9, "{o}");
    assert!(
        o.contains("auth.json") && o.contains("chmod 600"),
        "names the loose live file with the remedy: {o}"
    );
}

// Delta-hunt findings on the bug-sweep itself.

// F1: an UNREADABLE target snapshot must not bypass the repoint guard -
// corrupt-or-absent must not be conflated when the profile dir exists.
#[test]
fn login_repoint_guard_holds_for_unreadable_snapshot() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-C");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    std::fs::write(
        root.path()
            .join(".local/share/swapdex/accounts/work/codex/auth"),
        b"corrupt{{",
    )
    .unwrap();
    seed_codex(root.path(), "acct-A");
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.codex"
printf '%s' '{"auth_mode":"chatgpt","tokens":{"id_token":"h.eyJlbWFpbCI6ImJAeC5jb20ifQ.s","access_token":"AT-B","refresh_token":"RT-B","account_id":"acct-B"},"last_refresh":"2026-07-08T00:00:00Z"}' > "$SWAPDEX_ROOT/.codex/auth.json"
"#;
    let bin_dir = fake_tool(root.path(), "codex", script);
    // y = flow, Enter = skip keep-current, n = refuse repoint, Enter = skip rescue.
    let (o, e, _c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "work", "--tool", "codex"],
        "y\n\nn\n\n",
    );
    assert!(
        o.contains("Repoint"),
        "guard must fire even when the stored snapshot is unreadable: {o}{e}"
    );
    let stored = std::fs::read_to_string(
        root.path()
            .join(".local/share/swapdex/accounts/work/codex/auth"),
    )
    .unwrap();
    assert!(
        !stored.contains("acct-B"),
        "refusing must keep 'work' un-repointed: {stored}"
    );
}

// F2: refusing the repoint must OFFER to save the completed sign-in under a
// different name - a real browser login must not be silently discarded.
#[test]
fn login_repoint_refusal_offers_rescue_name() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-C");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-A");
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.codex"
printf '%s' '{"auth_mode":"chatgpt","tokens":{"id_token":"h.eyJlbWFpbCI6ImJAeC5jb20ifQ.s","access_token":"AT-B","refresh_token":"RT-B","account_id":"acct-B"},"last_refresh":"2026-07-08T00:00:00Z"}' > "$SWAPDEX_ROOT/.codex/auth.json"
"#;
    let bin_dir = fake_tool(root.path(), "codex", script);
    // y = flow, Enter = skip keeping the (unmatched) current account,
    // n = refuse repoint, "rescued" = save B under that name.
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "work", "--tool", "codex"],
        "y\n\nn\nrescued\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(
        names.contains("rescued"),
        "B saved under the rescue name: {names}"
    );
    assert!(names.contains("work"), "work untouched: {names}");
}

// F3/F4: ghost dirs (no known tools) are not profiles - rename must not act
// on them as source, and colliding with one as target is a clean exit 6.
#[test]
fn rename_treats_ghost_dirs_consistently() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    std::fs::create_dir_all(
        root.path()
            .join(".local/share/swapdex/accounts/legacy/some-old-tool"),
    )
    .unwrap();
    let (_o, e, c) = run(root.path(), &["rename", "legacy", "revived"]);
    assert_eq!(c, 5, "hidden source is not a profile: {e}");
    std::fs::create_dir_all(root.path().join(".local/share/swapdex/accounts/ghost/junk")).unwrap();
    let (_o, e, c) = run(root.path(), &["rename", "work", "ghost"]);
    assert_eq!(c, 6, "hidden target collision is a clean 'exists' (6): {e}");
}

// F5: SIGQUIT (Ctrl+backslash) must be ridden out like SIGINT.
#[test]
fn login_survives_sigquit_and_restores() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    run(root.path(), &["add", "old", "--tool", "claude"]);
    let script = "#!/bin/sh\ncase \"$1\" in --version) echo 1.0.0; exit 0;; esac\nkill -QUIT $PPID\nsleep 0.3\nexit 131\n";
    let bin_dir = fake_claude(root.path(), script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "claude"],
        "y\n",
    );
    assert_eq!(c, 8, "survived SIGQUIT: {o}{e}");
    assert_eq!(claude_live_uuid(root.path()), "uuid-A", "restored");
}

// Upgrade/environment audit findings.

// A future-stamped backup (clock skew during one switch) must not shadow the
// real newest backup forever - restore must undo the LAST switch.
#[test]
fn future_stamped_backup_does_not_hijack_restore() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal", "--tool", "codex"]);
    run(root.path(), &["use", "work"]); // backup: B
                                        // Ghost: a backup stamped in 2030 holding account C.
    let ghost = root
        .path()
        .join(".local/share/swapdex/backups/codex/1900000000000000000");
    std::fs::create_dir_all(&ghost).unwrap();
    std::fs::write(
        ghost.join("auth"),
        serde_json::to_vec(&serde_json::json!({"auth_mode":"chatgpt",
            "tokens":{"id_token":"h.eyJlbWFpbCI6ImNAei5jb20ifQ.s","access_token":"AT-C",
                      "refresh_token":"RT-C","account_id":"acct-C"},
            "last_refresh":"2026-07-01T00:00:00Z"}))
        .unwrap(),
    )
    .unwrap();
    let (o, e, c) = run(root.path(), &["restore", "--tool", "codex"]);
    assert_eq!(c, 0, "{e}");
    let live = std::fs::read_to_string(root.path().join(".codex/auth.json")).unwrap();
    assert!(
        live.contains("acct-B"),
        "restore undoes the LAST switch (B), never the future ghost (C): {o}{live}"
    );
}

// An unwritable store must say WHY, not claim another swapdex is mid-switch.
#[test]
fn unwritable_store_reports_the_real_problem() {
    use std::os::unix::fs::PermissionsExt;
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let lock = root.path().join(".local/share/swapdex/.lock");
    std::fs::write(&lock, b"").ok();
    std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o000)).unwrap();
    let (_o, e, c) = run(root.path(), &["use", "work"]);
    assert_ne!(c, 0);
    assert!(
        !e.contains("mid-switch"),
        "EACCES is not a lock contention: {e}"
    );
    assert!(
        e.to_lowercase().contains("perm") || e.to_lowercase().contains("writable"),
        "says the real cause: {e}"
    );
    std::fs::set_permissions(&lock, std::fs::Permissions::from_mode(0o600)).unwrap();
}

// A legacy all-whitespace profile (0.2.x allowed them) must stay MANAGEABLE:
// rm/rename/use may act on it even though creation now rejects it.
#[test]
fn legacy_whitespace_profile_is_manageable() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    // Simulate the 0.2.x-created profile by renaming the store dir directly.
    std::fs::rename(
        root.path().join(".local/share/swapdex/accounts/work"),
        root.path().join(".local/share/swapdex/accounts/ "),
    )
    .unwrap();
    let (_o, e, c) = run(root.path(), &["rename", " ", "fixed"]);
    assert_eq!(c, 0, "legacy name must be renamable: {e}");
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(names.contains("fixed"), "{names}");
}

// Two separate single-tool switches inside the same wall-clock second must
// NOT be treated as one invocation - a bare restore undoes only the LAST one.
#[test]
fn restore_scopes_to_last_invocation_not_same_second() {
    let root = tempfile::tempdir().unwrap();
    seed_claude(root.path(), "uuid-A", "a@x.com");
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work"]);
    seed_claude(root.path(), "uuid-B", "b@x.com");
    seed_codex(root.path(), "acct-B");
    run(root.path(), &["add", "personal"]);
    run(root.path(), &["use", "work"]);
    // Two back-to-back single-tool switches (same second, near-certainly).
    run(root.path(), &["use", "personal", "--tool", "codex"]);
    run(root.path(), &["use", "personal", "--tool", "claude"]);
    let (o, e, c) = run(root.path(), &["restore"]);
    assert_eq!(c, 0, "{e}");
    assert!(
        o.contains("claude") && !o.contains("restored codex"),
        "only the LAST invocation (claude) is undone: {o}"
    );
    // codex stays on personal (B).
    let auth = std::fs::read_to_string(root.path().join(".codex/auth.json")).unwrap();
    assert!(auth.contains("acct-B"), "codex untouched: {auth}");
}

// Bare `swapdex` over a pipe (no tty) prints the banner, never the TUI - and
// never creates the store on a fresh machine.
#[test]
fn bare_swapdex_pipe_is_banner_not_tui() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    let (o, _e, c) = run(root.path(), &[]);
    assert_eq!(c, 0);
    assert!(o.contains("swapdex"), "banner printed: {o}");
    assert!(o.contains("active:"), "shows where you stand: {o}");
}

#[test]
fn bare_swapdex_fresh_machine_is_banner_and_does_not_create_store() {
    let root = tempfile::tempdir().unwrap();
    let (o, _e, c) = run(root.path(), &[]);
    assert_eq!(c, 0);
    assert!(o.contains("swapdex setup"), "fresh-machine hint: {o}");
    assert!(
        !root.path().join(".local/share/swapdex").exists(),
        "a bare banner must not create the store"
    );
}

// Security F1: a symlinked accounts/<name> must not let a token write escape
// the 0700 store (the leaf-only symlink check missed intermediate dirs).
#[test]
fn add_refuses_symlinked_profile_dir() {
    let root = tempfile::tempdir().unwrap();
    let escape = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    // Pre-create the store, then plant accounts/beta -> attacker dir.
    run(root.path(), &["add", "seed", "--tool", "codex"]);
    let accounts = root.path().join(".local/share/swapdex/accounts");
    std::os::unix::fs::symlink(escape.path(), accounts.join("beta")).unwrap();
    let (_o, e, c) = run(root.path(), &["add", "beta", "--tool", "codex"]);
    assert_ne!(c, 0, "must refuse: {e}");
    // Nothing was written into the attacker's dir.
    assert!(
        !escape.path().join("codex/auth").exists(),
        "no token escaped the store into {}",
        escape.path().display()
    );
}

// Real-use bug: adding a NEW account but the tool signs you back into the
// SAME one (cached browser session). swapdex must NOT save a duplicate under
// the new name, must restore the login, and must explain how to switch.
#[test]
fn login_same_account_back_does_not_save_duplicate() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    // Fake codex whose "login" writes the SAME account back.
    let script = r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; logout) rm -f "$SWAPDEX_ROOT/.codex/auth.json"; exit 0;; esac
mkdir -p "$SWAPDEX_ROOT/.codex"
printf '%s' '{"auth_mode":"chatgpt","tokens":{"id_token":"h.eyJlbWFpbCI6ImFAeC5jb20ifQ.s","access_token":"AT2","refresh_token":"RT2","account_id":"acct-A"},"last_refresh":"2026-07-08T00:00:00Z"}' > "$SWAPDEX_ROOT/.codex/auth.json"
"#;
    let bin_dir = fake_tool(root.path(), "codex", script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "codex"],
        "y\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    assert!(
        e.contains("SAME account"),
        "explains the same-account outcome: {e}"
    );
    assert!(
        e.to_lowercase().contains("browser"),
        "tells how to actually switch: {e}"
    );
    // 'second' must NOT exist - no duplicate profile of acct-A.
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(
        !names.contains("second"),
        "no duplicate profile saved: {names}"
    );
    // The live login is intact (still acct-A).
    let auth = std::fs::read_to_string(root.path().join(".codex/auth.json")).unwrap();
    assert!(auth.contains("acct-A"), "login restored/intact: {auth}");
}

// The login flow must NOT hold the store lock across the interactive sign-in
// - otherwise a left-open login blocks rename/use/everything with "another
// swapdex is mid-switch" (the real macOS report). The fake tool, WHILE it is
// the spawned sign-in, runs a `rename` against the same store; it must
// succeed, proving the lock was released.
#[test]
fn login_does_not_hold_lock_during_signin() {
    let root = tempfile::tempdir().unwrap();
    seed_codex(root.path(), "acct-A");
    run(root.path(), &["add", "work", "--tool", "codex"]);
    // A second profile we will rename FROM INSIDE the spawned sign-in.
    seed_codex(root.path(), "acct-V");
    run(root.path(), &["add", "victim", "--tool", "codex"]);
    // Put the current account back so the login flow stashes acct-A.
    seed_codex(root.path(), "acct-A");
    // Fake codex: on `login`, rename victim -> moved (using the real swapdex
    // binary) BEFORE writing the new account. If login still held the lock,
    // this rename would fail with exit 4.
    let script = format!(
        r#"#!/bin/sh
case "$1" in --version) echo 1.0.0; exit 0;; logout) rm -f "$SWAPDEX_ROOT/.codex/auth.json"; exit 0;; esac
"{}" rename victim moved > "$SWAPDEX_ROOT/rename-rc.txt" 2>&1
echo "rc=$?" >> "$SWAPDEX_ROOT/rename-rc.txt"
mkdir -p "$SWAPDEX_ROOT/.codex"
printf '%s' '{{"auth_mode":"chatgpt","tokens":{{"id_token":"h.eyJlbWFpbCI6ImJAeC5jb20ifQ.s","access_token":"ATB","refresh_token":"RTB","account_id":"acct-B"}},"last_refresh":"2026-07-08T00:00:00Z"}}' > "$SWAPDEX_ROOT/.codex/auth.json"
"#,
        bin()
    );
    let bin_dir = fake_tool(root.path(), "codex", &script);
    let (o, e, c) = run_login_tty(
        root.path(),
        &bin_dir,
        &["login", "second", "--tool", "codex"],
        "\ny\n",
    );
    assert_eq!(c, 0, "{o}{e}");
    let rc = std::fs::read_to_string(root.path().join("rename-rc.txt")).unwrap_or_default();
    assert!(
        rc.contains("rc=0"),
        "rename during the sign-in succeeded (lock was free): {rc}"
    );
    let (names, _e, _c) = run(root.path(), &["ls", "--names"]);
    assert!(
        names.contains("moved") && !names.contains("victim"),
        "victim was renamed mid-sign-in: {names}"
    );
}