swapdex 0.167.13

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
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
//! Walk real command sequences and check that every screen agrees with the
//! state underneath it.
//!
//! Written after a day in which fifteen defects shipped past 599 unit tests.
//! None of them was a function computing the wrong answer; they were the joins
//! between functions - a helper built and never wired to the screen that needed
//! it, a refresh trapped inside an `if`, a record written inside the retry loop
//! it was meant to summarise, a listing that looked at snapshots and not slots.
//! A unit test cannot see those, because each unit passes.
//!
//! So these tests do what the owner does: run one command, then ask a DIFFERENT
//! command whether it agrees. Where they disagree is where this class of bug
//! lives.

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),
    )
}

/// `run` with no swapdex shim on PATH: the launch these tests describe is the
/// one that bypasses the shim, and the developer's own PATH usually has one.
fn run_unshimmed(root: &Path, args: &[&str]) -> (String, String, i32) {
    let out = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("PATH", "/usr/bin:/bin")
        .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: &Path) {
    use std::os::unix::fs::PermissionsExt;
    let _ = std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o600));
}

/// A logged-in Claude, the state `add` captures from.
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(&d.join(".credentials.json"));
    chmod600(&root.join(".claude.json"));
}

/// The email the LIVE Claude login carries, read from the tool's own file.
///
/// A test about what a switch WROTE has to read the file. The mark in `ls`
/// follows the slot pointer, which answers who pays - a different question, and
/// under the slot model the two are routinely different accounts.
fn live_claude_email(root: &Path) -> String {
    let bytes = std::fs::read(root.join(".claude.json")).expect("read the live .claude.json");
    let v: serde_json::Value = serde_json::from_slice(&bytes).expect("parse the live .claude.json");
    v["oauthAccount"]["emailAddress"]
        .as_str()
        .unwrap_or_default()
        .to_string()
}

/// A registered SLOT: an account that can actually pay for turns. `add` saves a
/// snapshot, which is a different thing - serving reads a slot's own credential
/// directory, so a snapshot cannot serve until it has been run once.
fn seed_slot(root: &Path, name: &str, email: &str) {
    let dir = root.join(".local/share/swapdex/slots").join(name);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"AT","refreshToken":"RT","expiresAt":9999999999999i64,
            "subscriptionType":"max"}}))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        dir.join(".claude.json"),
        serde_json::to_vec(&serde_json::json!({
            "oauthAccount":{"accountUuid":name,"emailAddress":email}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&dir.join(".credentials.json"));

    let reg = root.join(".local/share/swapdex/slots.json");
    let mut rows: Vec<serde_json::Value> = std::fs::read(&reg)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    rows.push(serde_json::json!({
        "name": name, "id": name, "config_dir": dir.to_string_lossy(),
        "adopted": false, "tool": "claude-code"}));
    std::fs::write(&reg, serde_json::to_vec_pretty(&rows).unwrap()).unwrap();
}

fn fixture() -> tempfile::TempDir {
    let t = tempfile::tempdir().unwrap();
    std::fs::create_dir_all(t.path().join(".local/share/swapdex")).unwrap();
    std::fs::write(t.path().join(".local/share/swapdex/onboarded"), b"1").unwrap();
    t
}

/// Run swapdex with a PATH holding a fake native `codex`, so `swapdex shim`
/// has something to wrap. Returns (stdout+stderr, exit code).
fn run_with_native_codex(root: &Path, args: &[&str]) -> (String, i32) {
    let native = root.join("native-bin");
    std::fs::create_dir_all(&native).unwrap();
    let codex = native.join("codex");
    if !codex.exists() {
        std::fs::write(&codex, "#!/bin/sh\nexit 0\n").unwrap();
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(&codex, std::fs::Permissions::from_mode(0o755)).unwrap();
    }
    let out = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("HOME", root)
        .env("PATH", format!("{}:/usr/bin:/bin", native.display()))
        .output()
        .unwrap();
    (
        format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        ),
        out.status.code().unwrap_or(-1),
    )
}

/// What an older swapdex wrote: today's shim with one of its lines gone - the
/// usage route that 0.167.0 added, the kind of fix a stale shim never carries.
fn age_the_codex_shim(shim: &Path) -> String {
    let current = std::fs::read_to_string(shim).unwrap();
    let aged: String = current
        .lines()
        .filter(|l| !l.contains("chatgpt_base_url=\"https"))
        .map(|l| format!("{l}\n"))
        .collect();
    assert_ne!(
        aged, current,
        "the fixture shim had no usage route to remove"
    );
    std::fs::write(shim, &aged).unwrap();
    current
}

/// Upgrading swapdex must not leave the launcher on the old behaviour.
///
/// Only `swapdex shim` wrote a shim, and nothing ran it on upgrade. So 0.166.1's
/// hotfix - which removed a flag that made every Codex launch exit - reached no
/// one whose shim 0.166.0 had written: they kept a launcher that could not
/// start Codex, on a binary that no longer produced it. Every launch already
/// asks this binary for its proxy (`proxy --ensure`), so that is where a shim
/// written by an older build gets rewritten.
#[test]
fn a_launch_rewrites_a_shim_an_older_swapdex_wrote() {
    let t = fixture();
    let root = t.path();
    let (out, code) = run_with_native_codex(root, &["shim"]);
    assert_eq!(code, 0, "shim failed: {out}");
    let shim = root.join(".local/share/swapdex/bin/codex");
    let fresh = age_the_codex_shim(&shim);

    let _ = run_with_native_codex(root, &["proxy", "--ensure", "--tool", "codex"]);
    assert_eq!(
        std::fs::read_to_string(&shim).unwrap(),
        fresh,
        "a launch left the shim an older swapdex wrote"
    );
}

/// The over-correction: a shim that calls a DIFFERENT swapdex belongs to that
/// install. Rewriting it would silently move the user onto this binary; doctor
/// already names the split, and that is the user's call.
#[test]
fn a_launch_leaves_a_shim_that_calls_another_swapdex() {
    let t = fixture();
    let root = t.path();
    let (out, code) = run_with_native_codex(root, &["shim"]);
    assert_eq!(code, 0, "shim failed: {out}");
    let shim = root.join(".local/share/swapdex/bin/codex");
    let fresh = std::fs::read_to_string(&shim).unwrap();
    let foreign = fresh.replace(bin(), "/opt/other/swapdex");
    assert_ne!(foreign, fresh, "the shim did not embed this binary's path");
    std::fs::write(&shim, &foreign).unwrap();

    let _ = run_with_native_codex(root, &["proxy", "--ensure", "--tool", "codex"]);
    assert_eq!(
        std::fs::read_to_string(&shim).unwrap(),
        foreign,
        "rewrote a shim that belongs to another swapdex"
    );
}

/// doctor said "the shims call this swapdex" about a shim whose CONTENT was an
/// older build's - the check looked at which binary it calls, never at what it
/// does with it.
#[test]
fn doctor_reports_a_shim_an_older_swapdex_wrote() {
    let t = fixture();
    let root = t.path();
    let (out, code) = run_with_native_codex(root, &["shim"]);
    assert_eq!(code, 0, "shim failed: {out}");
    let shim = root.join(".local/share/swapdex/bin/codex");
    let (fresh_doctor, _) = run_with_native_codex(root, &["doctor"]);
    assert!(
        !fresh_doctor.contains("older swapdex"),
        "a current shim was called stale:\n{fresh_doctor}"
    );
    age_the_codex_shim(&shim);
    let (said, _) = run_with_native_codex(root, &["doctor"]);
    assert!(
        said.contains("older swapdex"),
        "doctor passes a shim an older swapdex wrote:\n{said}"
    );
}

/// A live Codex proxy marker, owned by this test process so it reads as alive.
fn mark_codex_proxy(root: &Path, usage_port: Option<u16>) {
    let store = root.join(".local/share/swapdex");
    let tail = usage_port.map_or(String::new(), |p| format!(" {p}"));
    std::fs::write(
        store.join("proxy-codex"),
        format!("{} 8788 test-build{tail}\n", std::process::id()),
    )
    .unwrap();
}

fn doctor_usage_row(root: &Path, env: &[(&str, &str)]) -> String {
    let mut cmd = Command::new(bin());
    cmd.arg("doctor")
        .env("SWAPDEX_ROOT", root)
        .env_remove("CODEX_CA_CERTIFICATE")
        .env_remove("SSL_CERT_FILE");
    for (k, v) in env {
        cmd.env(k, v);
    }
    let out = cmd.output().unwrap();
    let text =
        String::from_utf8_lossy(&out.stdout).into_owned() + &String::from_utf8_lossy(&out.stderr);
    text.lines()
        .find(|l| l.starts_with("usage:codex"))
        .unwrap_or_else(|| panic!("doctor has no usage:codex row:\n{text}"))
        .to_string()
}

/// Codex's status line shows the paying account only while the usage route is
/// up, and every way it can be down is silent: the status line just goes back
/// to the window's own account. doctor names which state this machine is in.
#[test]
fn doctor_says_whether_codex_usage_reads_reach_the_payer() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");

    mark_codex_proxy(root, Some(18788));
    let on = doctor_usage_row(root, &[]);
    assert!(
        on.contains(" ok "),
        "a working route reported as a problem: {on}"
    );
    assert!(
        on.contains("18788"),
        "the row does not name the listener: {on}"
    );

    mark_codex_proxy(root, None);
    let off = doctor_usage_row(root, &[]);
    assert!(
        off.contains("problem"),
        "a proxy with no usage listener passed as fine: {off}"
    );

    mark_codex_proxy(root, Some(18788));
    for var in ["CODEX_CA_CERTIFICATE", "SSL_CERT_FILE"] {
        let row = doctor_usage_row(root, &[(var, "/etc/corp.pem")]);
        assert!(
            row.contains(var),
            "the route is left off for {var} and doctor does not say why: {row}"
        );
    }
}

/// Every account that a command will ACT on must be one a listing SHOWS.
///
/// `ls` built its rows from saved snapshots only. On a machine whose accounts
/// live as slots, `serve personal` moved the turns correctly and there was no
/// row for `personal` at all - so the mark naming the payer had nowhere to
/// appear and two of three switches looked like they did nothing. The listing
/// and the switch disagreed about which accounts existed.
#[test]
fn everything_serve_accepts_is_something_ls_shows() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");
    seed_claude(root, "uuid-b", "b@example.com");
    run(root, &["add", "beta"]);
    seed_slot(root, "beta", "b@example.com");

    let (listing, _, _) = run(root, &["ls"]);
    for name in ["alpha", "beta"] {
        // Serve accepts it...
        let (_, err, code) = run(root, &["serve", name]);
        assert_ne!(code, 5, "serve rejected '{name}' as unknown: {err}");
        // ...so the listing has to show it.
        assert!(
            listing.contains(name),
            "serve accepts '{name}' but `ls` never lists it:\n{listing}"
        );
    }
}

/// After a switch, the listing must name the account that was switched to.
///
/// `serve rnd` printed "turns -> rnd" and then `ls` starred a different
/// account, the one holding the login on disk, with the paying account named
/// nowhere.
/// Both facts were true and only one was shown, so switching read as not having
/// taken. Its owner concluded exactly that, repeatedly, over a day.
#[test]
fn a_switch_is_visible_in_the_listing_afterwards() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");
    seed_claude(root, "uuid-b", "b@example.com");
    run(root, &["add", "beta"]);
    seed_slot(root, "beta", "b@example.com");

    for name in ["alpha", "beta", "alpha"] {
        run(root, &["serve", name]);
        let (listing, _, _) = run(root, &["ls"]);
        let marked: Vec<&str> = listing.lines().filter(|l| l.contains("pays")).collect();
        assert_eq!(
            marked.len(),
            1,
            "after `serve {name}` exactly one row should be marked as paying:\n{listing}"
        );
        assert!(
            marked[0].contains(name),
            "after `serve {name}` the paying row names someone else:\n{}",
            marked[0]
        );
    }
}

/// `serve --quiet` is what a status bar calls; it must agree with `ls`.
///
/// The status line and the listing read different sources, so they could
/// disagree about who pays - and the bar is the surface people actually watch.
#[test]
fn the_status_bar_source_agrees_with_the_listing() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");
    seed_claude(root, "uuid-b", "b@example.com");
    run(root, &["add", "beta"]);
    seed_slot(root, "beta", "b@example.com");

    for name in ["beta", "alpha"] {
        run(root, &["serve", name]);
        let (quiet, _, _) = run(root, &["serve", "--quiet"]);
        assert!(
            quiet.starts_with(name),
            "the status bar reports '{}' after `serve {name}`",
            quiet.trim()
        );
        let (listing, _, _) = run(root, &["ls"]);
        let paying = listing
            .lines()
            .find(|l| l.contains("pays"))
            .unwrap_or_default();
        assert!(
            paying.contains(name),
            "bar says '{}' but listing marks:\n{paying}",
            quiet.trim()
        );
    }
}

/// A rename must move the account everywhere, for every tool it holds.
///
/// `Slots::open()` is hardcoded to claude, so renaming an account that also
/// held a Codex login moved half of it: the new name worked for one tool and
/// the old name lingered for the other.
#[test]
fn a_rename_moves_the_account_in_every_listing() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "before"]);
    seed_slot(root, "before", "a@example.com");

    let (_, err, code) = run(root, &["rename", "before", "after"]);
    assert_eq!(code, 0, "rename failed: {err}");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        listing.contains("after"),
        "the new name is missing after a rename:\n{listing}"
    );
    assert!(
        !listing.contains("before"),
        "the old name survived the rename:\n{listing}"
    );
    // And the renamed account is the one commands act on.
    let (_, err, code) = run(root, &["serve", "after"]);
    assert_ne!(code, 5, "serve does not know the new name: {err}");
    let (_, _, code) = run(root, &["serve", "before"]);
    assert_eq!(code, 5, "serve still answers to the old name");
}

/// Dropping one tool must not take the account with it.
///
/// The slot branch ran before the `--tool` flag was read, so on a name that is
/// both a slot and a profile, `rm kong --tool gemini --yes` unregistered kong
/// entirely instead of dropping one login. The opposite of what was asked.
#[test]
fn dropping_one_tool_leaves_the_account_listed() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");

    // Nothing to drop: reported, and the account is untouched either way.
    run(root, &["rm", "alpha", "--tool", "gemini", "--yes"]);
    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        listing.contains("alpha"),
        "dropping a tool removed the whole account:\n{listing}"
    );
    let (_, err, code) = run(root, &["serve", "alpha"]);
    assert_ne!(code, 5, "the account stopped existing: {err}");
}

/// A wrong name must answer with the names that exist.
///
/// A typo said "no account named 'alicee' - `swapdex ui` lists them", sending
/// the reader to open another screen to read four words.
#[test]
fn a_wrong_name_names_the_alternatives() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);

    let (_, err, code) = run(root, &["serve", "alphaa"]);
    assert_eq!(code, 5, "a typo should not be accepted");
    assert!(
        err.contains("alpha"),
        "the error does not name the account that exists: {err}"
    );
    assert!(
        !err.contains("swapdex ui"),
        "the error still sends the reader to another screen: {err}"
    );
}

/// Every switch is attributable afterwards.
///
/// The timeline held `serve kong` and nothing about the caller, so a paying
/// account that changed without anyone meaning to could not be traced to any of
/// twenty live sessions.
#[test]
fn a_switch_records_who_asked_for_it() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");
    run(root, &["serve", "alpha"]);

    let line = std::fs::read_to_string(root.join(".local/share/swapdex/timeline.jsonl"))
        .unwrap_or_default();
    let last = line.lines().last().unwrap_or_default();
    let v: serde_json::Value = serde_json::from_str(last).unwrap_or_default();
    assert!(
        v.get("by").and_then(|b| b.as_str()).is_some(),
        "the switch does not record who asked for it: {last}"
    );
}

/// The listing must say whose login each row is, however the account is stored.
///
/// Identity was read from the saved snapshot only, so a slot-only account
/// listed with an empty name column: the row was there and switching worked,
/// but nothing said which login it was.
#[test]
fn every_listed_account_says_whose_login_it_is() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "alpha@example.com");
    run(root, &["add", "alpha"]);

    let (listing, _, _) = run(root, &["ls"]);
    let row = listing
        .lines()
        .find(|l| l.contains("alpha "))
        .unwrap_or_default();
    assert!(
        row.contains("alpha@example.com"),
        "the row does not name the login it holds:\n{row}"
    );
}

/// A row must not claim a login it does not hold.
///
/// `ls` marked a freshly created Codex slot as the active account (`codex*`)
/// while `serve` refused it for having no codex login - the slot directory held
/// config and sessions but no `auth.json`. One screen asserted what the other
/// denied, and the assertion was the false one.
#[test]
fn a_slot_without_a_credential_is_not_reported_as_active() {
    let t = fixture();
    let root = t.path();

    // A registered codex slot with everything EXCEPT its credential.
    let dir = root.join(".local/share/swapdex/slots/codexish");
    std::fs::create_dir_all(dir.join("sessions")).unwrap();
    std::fs::write(dir.join("config.toml"), b"# nothing\n").unwrap();
    let reg = root.join(".local/share/swapdex/slots.json");
    std::fs::write(
        &reg,
        serde_json::to_vec_pretty(&serde_json::json!([{
            "name": "codexish", "id": "codexish",
            "config_dir": dir.to_string_lossy(), "adopted": false, "tool": "codex"}]))
        .unwrap(),
    )
    .unwrap();

    let (listing, _, _) = run(root, &["ls"]);
    let row = listing
        .lines()
        .find(|l| l.contains("codexish"))
        .unwrap_or_default();
    let (_, err, code) = run(root, &["serve", "codexish", "--tool", "codex"]);

    // Whatever they say, they must not contradict each other: a row cannot be
    // starred as the live account for a tool that refuses to serve it.
    if code == 5 || err.contains("no codex login") {
        assert!(
            !row.contains("codex*"),
            "listing stars a tool whose login serve says is missing:\n{row}\n{err}"
        );
    }
}

/// A minimal id_token whose payload carries the email, the way Codex stores it.
fn codex_id_token(email: &str) -> String {
    let payload = serde_json::json!({"email": email});
    let b64 = |b: &[u8]| {
        const T: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
        let mut o = String::new();
        for c in b.chunks(3) {
            let n = ((c[0] as u32) << 16)
                | ((*c.get(1).unwrap_or(&0) as u32) << 8)
                | (*c.get(2).unwrap_or(&0) as u32);
            for i in 0..(c.len() + 1) {
                o.push(T[((n >> (18 - i * 6)) & 63) as usize] as char);
            }
        }
        o
    };
    format!(
        "h.{}.s",
        b64(serde_json::to_string(&payload).unwrap().as_bytes())
    )
}

/// A live Codex login in the tool's own dir - what `add` captures from.
fn seed_live_codex(root: &Path, email: &str) {
    let dir = root.join(".codex");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode": "chatgpt",
            "tokens": {"id_token": codex_id_token(email), "access_token": "AT",
                       "refresh_token": "RT", "account_id": "acct-live"}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&dir.join("auth.json"));
}

/// A registered CODEX slot: the shape that can actually pay for Codex turns.
/// `YYYY-MM-DDTHH:MM:SSZ` from a unix timestamp, the way Codex writes it.
/// Civil-from-days, so no date crate is pulled in for two tests.
fn rfc3339_utc(secs: u64) -> String {
    let (days, rem) = ((secs / 86_400) as i64, secs % 86_400);
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097);
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = era * 400 + yoe + i64::from(m <= 2);
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        rem / 3600,
        (rem % 3600) / 60,
        rem % 60
    )
}

fn seed_codex_slot(root: &Path, name: &str, email: &str) {
    let dir = root.join(".local/share/swapdex/slots").join(name);
    std::fs::create_dir_all(dir.join("sessions")).unwrap();
    let tok = codex_id_token(email);
    std::fs::write(
        dir.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode": "chatgpt",
            "last_refresh": "2026-08-20T00:00:00Z",
            "tokens": {"id_token": tok, "access_token": "AT", "refresh_token": "RT",
                       "account_id": "acct-1"}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&dir.join("auth.json"));

    let reg = root.join(".local/share/swapdex/slots.json");
    let mut rows: Vec<serde_json::Value> = std::fs::read(&reg)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    rows.push(serde_json::json!({
        "name": name, "id": name, "config_dir": dir.to_string_lossy(),
        "adopted": false, "tool": "codex"}));
    std::fs::write(&reg, serde_json::to_vec_pretty(&rows).unwrap()).unwrap();
}

/// Codex accounts must switch the same way Claude ones do.
///
/// Every screen and command was built and fixed against Claude first; Codex
/// took its own branch in the proxy and its own registry entries, so a defect
/// fixed on one side could easily still be live on the other. This walks the
/// same sequence for Codex.
#[test]
fn a_codex_switch_is_visible_and_agrees_across_commands() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx-one", "one@example.com");
    seed_codex_slot(root, "cx-two", "two@example.com");

    for name in ["cx-one", "cx-two", "cx-one"] {
        let (_, err, code) = run(root, &["serve", name, "--tool", "codex"]);
        assert_eq!(code, 0, "serve {name} --tool codex failed: {err}");

        // The listing must mark exactly this one as paying.
        let (listing, _, _) = run(root, &["ls"]);
        let marked: Vec<&str> = listing.lines().filter(|l| l.contains("pays")).collect();
        assert_eq!(
            marked.len(),
            1,
            "after serving {name} exactly one row should pay:\n{listing}"
        );
        assert!(
            marked[0].contains(name),
            "the paying row names someone else after serving {name}:\n{}",
            marked[0]
        );

        // And the status-bar source must agree.
        let (quiet, _, _) = run(root, &["serve", "--quiet", "--tool", "codex"]);
        assert!(
            quiet.starts_with(name),
            "status bar says '{}' after serving {name}",
            quiet.trim()
        );
    }
}

/// A Codex account listed must say whose login it is.
#[test]
fn a_codex_row_names_its_login() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx-one", "one@example.com");

    let (listing, _, _) = run(root, &["ls"]);
    let row = listing
        .lines()
        .find(|l| l.contains("cx-one"))
        .unwrap_or_default();
    assert!(
        row.contains("one@example.com"),
        "the codex row does not name its login:\n{row}"
    );
}

/// Renaming a Codex account must move it everywhere too.
#[test]
fn renaming_a_codex_account_moves_it_everywhere() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx-before", "one@example.com");

    let (_, err, code) = run(root, &["rename", "cx-before", "cx-after"]);
    assert_eq!(code, 0, "rename failed: {err}");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(listing.contains("cx-after"), "new name missing:\n{listing}");
    assert!(
        !listing.contains("cx-before"),
        "old name survived:\n{listing}"
    );
    let (_, err, code) = run(root, &["serve", "cx-after", "--tool", "codex"]);
    assert_eq!(code, 0, "serve does not know the new codex name: {err}");
}

/// A rename must move EVERY tool's slot, not the first one it finds.
///
/// `find_any_tool` returns one tool, and rename renamed that tool's registry
/// entry only. An account holding both a Claude and a Codex slot came out split
/// in two: `cxtest [codex*, claude-code]` beside `codex-test [codex]`, one
/// login under two names. 0.88.0 fixed the slot-vs-snapshot half of this; the
/// slot-vs-slot half was still live.
#[test]
fn a_rename_moves_every_tool_slot() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "both", "b@example.com");
    seed_codex_slot(root, "both", "b@example.com");

    let (_, err, code) = run(root, &["rename", "both", "moved"]);
    assert_eq!(code, 0, "rename failed: {err}");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        !listing.contains("both"),
        "the old name survived on some tool:\n{listing}"
    );
    // One account, one row - not one row per tool that got left behind.
    let rows = listing.lines().filter(|l| l.contains("moved")).count();
    assert_eq!(rows, 1, "the account came out split in two:\n{listing}");

    // And both tools answer to the new name.
    for tool in ["claude-code", "codex"] {
        let (_, err, code) = run(root, &["serve", "moved", "--tool", tool]);
        assert_eq!(code, 0, "serve --tool {tool} does not know 'moved': {err}");
    }
}

/// `rm --tool` must be able to drop a SLOT, not just a snapshot.
///
/// It looked in the snapshot store only, so a tool that existed as a slot
/// answered "profile 'X' has no codex login" about a slot the listing was
/// showing - and the only way to remove it was editing slots.json by hand.
#[test]
fn dropping_a_tool_removes_its_slot_too() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "both", "b@example.com");
    seed_codex_slot(root, "both", "b@example.com");

    let (out, err, code) = run(root, &["rm", "both", "--tool", "codex", "--yes"]);
    assert_eq!(code, 0, "dropping the codex slot failed: {err}{out}");

    // The claude side survives...
    let (listing, _, _) = run(root, &["ls"]);
    assert!(listing.contains("both"), "the account vanished:\n{listing}");
    assert!(
        listing.contains("claude-code"),
        "the claude slot was taken too:\n{listing}"
    );
    // ...and the codex side is gone.
    let (_, err, code) = run(root, &["serve", "both", "--tool", "codex"]);
    assert_ne!(code, 0, "codex still serves after being dropped: {err}");
}

/// `ls` must say what the TUI says: an expired slot cannot serve.
///
/// The TUI marked bsgong "expired" and the proxy log agreed - "its login has
/// expired - passing your own login through" - while `ls` showed the row with
/// no note at all. A list that presents an unusable account as fine is the
/// worse of the two, because `ls` is what a script and a glance both read.
#[test]
fn ls_marks_a_slot_whose_token_has_expired() {
    let t = fixture();
    let root = t.path();
    // A slot whose access token lapsed weeks ago.
    let dir = root.join(".local/share/swapdex/slots/old");
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"AT","refreshToken":"RT",
            "expiresAt": 1_600_000_000_000i64, "subscriptionType":"max"}}))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        dir.join(".claude.json"),
        br#"{"oauthAccount":{"emailAddress":"old@example.com"}}"#,
    )
    .unwrap();
    chmod600(&dir.join(".credentials.json"));
    std::fs::write(
        root.join(".local/share/swapdex/slots.json"),
        serde_json::to_vec_pretty(&serde_json::json!([{
            "name": "old", "id": "old", "config_dir": dir.to_string_lossy(),
            "adopted": false, "tool": "claude-code"}]))
        .unwrap(),
    )
    .unwrap();

    let (listing, _, _) = run(root, &["ls"]);
    let row = listing
        .lines()
        .find(|l| l.contains("old"))
        .unwrap_or_default();
    assert!(
        row.contains("expired") || row.contains("stale") || row.contains("no login"),
        "an expired slot is listed as if it were fine:\n{row}"
    );
}

/// `ls` must show an account no matter which tool its slot belongs to.
///
/// The listing walked a hardcoded pair of tools while four adapters exist, so
/// an account living only as a Gemini or Antigravity slot had no row at all -
/// switching to it worked and the listing showed nothing, the same "the switch
/// did nothing" appearance already fixed once for Claude and once for Codex.
#[test]
fn ls_lists_an_account_that_lives_only_as_a_gemini_slot() {
    let td = fixture();
    let root = td.path();
    seed_gemini_slot(root, "kong", "kong@example.com");

    let (out, err, code) = run(root, &["ls"]);
    assert_eq!(code, 0, "ls failed: {err}");
    assert!(
        out.contains("kong"),
        "a Gemini-only account is missing from the listing:\n{out}"
    );
}

fn seed_gemini_slot(root: &Path, name: &str, email: &str) {
    let dir = root.join(".local/share/swapdex/slots").join(name);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(
        dir.join("oauth_creds.json"),
        serde_json::to_vec(&serde_json::json!({
            "access_token": "AT", "refresh_token": "RT",
            "expiry_date": 9999999999999i64}))
        .unwrap(),
    )
    .unwrap();
    std::fs::write(
        dir.join("google_accounts.json"),
        serde_json::to_vec(&serde_json::json!({"active": email, "old": []})).unwrap(),
    )
    .unwrap();
    chmod600(&dir.join("oauth_creds.json"));

    let reg = root.join(".local/share/swapdex/slots.json");
    let mut rows: Vec<serde_json::Value> = std::fs::read(&reg)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    rows.push(serde_json::json!({
        "name": name, "id": name, "config_dir": dir.to_string_lossy(),
        "adopted": false, "tool": "gemini"}));
    std::fs::write(&reg, serde_json::to_vec_pretty(&rows).unwrap()).unwrap();
}

/// The status bar must never go blank about usage without saying so.
///
/// With no reading in the cache the bar printed the account and stopped. The
/// numbers had been there the day before, so their absence read as a broken
/// status bar - and the two ordinary causes, nothing measured yet and a window
/// that passed its reset before a fresh read landed, both looked identical to
/// a failure.
#[test]
fn the_status_bar_says_when_it_has_no_usage_reading() {
    let td = fixture();
    let root = td.path();
    seed_slot(root, "rnd", "rnd@example.com");
    let (_, err, code) = run(root, &["serve", "rnd"]);
    assert_eq!(code, 0, "serve failed: {err}");

    let (out, err, code) = run(root, &["serve", "--quiet"]);
    assert_eq!(code, 0, "serve --quiet failed: {err}");
    assert!(
        out.contains("usage unread"),
        "the bar went silent about usage instead of saying it had no reading:\n{out:?}"
    );
}

/// A damaged registry must never be reported as "no accounts".
///
/// `slots.json` holds every account on the machine, and until 0.103.0 it was
/// written with a plain truncate-then-write - so an interrupted write could
/// leave it unparseable. `Slots::open_for` says "slots.json is corrupt", but
/// eight callers discard that, and `ls` then printed "No accounts saved yet"
/// with setup advice. That tells a user who still has every credential on disk
/// that they never had an account, and invites them to start over on top of it.
#[test]
fn a_damaged_registry_is_not_reported_as_having_no_accounts() {
    let td = fixture();
    let root = td.path();
    let reg = root.join(".local/share/swapdex/slots.json");
    std::fs::create_dir_all(reg.parent().unwrap()).unwrap();
    std::fs::write(&reg, b"[{\"name\":\"rnd\",").unwrap();

    let (out, err, _) = run(root, &["ls"]);
    let all = format!("{out}{err}").to_lowercase();
    assert!(
        !all.contains("no accounts saved yet"),
        "a damaged registry was reported as an empty one:\n{out}{err}"
    );
    assert!(
        all.contains("registry") || all.contains("corrupt") || all.contains("could not be read"),
        "nothing said the registry could not be read:\n{out}{err}"
    );
}

/// An account for a tool this swapdex does not know must not be invented.
///
/// The tool string went straight to `Slots::open_for`, which does not validate
/// it, so a manifest naming a tool this build has never heard of produced a slot
/// that can never serve - announced as "(claude)", because the display falls
/// back to Claude for an unknown name. swapdex ships four adapters and is built
/// to grow: exporting a Gemini account and importing it on a build that predates
/// Gemini turns it into a Claude account, and `FORMAT_VERSION` cannot catch that
/// because adding an adapter is not a format change.
#[test]
fn importing_an_account_for_an_unknown_tool_refuses_instead_of_guessing() {
    let td = fixture();
    let root = td.path();
    let manifest = root.join("in.json");
    std::fs::write(
        &manifest,
        br#"{"version":1,"accounts":[{"name":"zed","tool":"nosuchtool"},
             {"name":"ok","tool":"claude-code"}]}"#,
    )
    .unwrap();

    let (out, err, _) = run(root, &["import", manifest.to_str().unwrap()]);
    let all = format!("{out}{err}");
    assert!(
        all.contains("nosuchtool"),
        "the unknown tool was never named:\n{all}"
    );
    assert!(
        !all.contains("created zed"),
        "an account was created for a tool this build cannot serve:\n{all}"
    );
    // The rest of the file still imports.
    assert!(
        all.contains("created ok"),
        "a known account was skipped:\n{all}"
    );
}

/// Every command swapdex prints as a remedy must be a command swapdex accepts.
///
/// The remedy text is a second copy of the CLI, kept by hand, and it drifted:
/// `doctor` answered "the proxy service is installed but not running" - the
/// exact shape of an outage - with `swapdex service restart`, which has never
/// existed, and a credential warning pointed at `swapdex whoami`. Reading the
/// source for backtick-quoted commands and asking the binary about each one
/// keeps the two copies honest, and costs nothing to extend: a command that
/// takes subcommands has its second word checked too.
#[test]
fn every_command_we_tell_the_user_to_run_exists() {
    fn words(line: &str) -> Vec<(String, Option<String>)> {
        let mut out = Vec::new();
        let mut rest = line;
        while let Some(i) = rest.find("`swapdex ") {
            rest = &rest[i + "`swapdex ".len()..];
            let mut it = rest.split_whitespace();
            // The leading run of command characters: the token carries the
            // closing backtick, a `<placeholder>` or a `--flag` after it.
            let word = |w: &str| {
                if w.starts_with('-') {
                    return None;
                }
                let t: String = w
                    .chars()
                    .take_while(|c| c.is_ascii_lowercase() || *c == '-')
                    .collect();
                (!t.is_empty()).then_some(t)
            };
            let Some(first) = it.next().and_then(word) else {
                continue;
            };
            out.push((first, it.next().and_then(word)));
        }
        out
    }

    fn rs_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
        for e in std::fs::read_dir(dir).unwrap().flatten() {
            let p = e.path();
            if p.is_dir() {
                rs_files(&p, out);
            } else if p.extension().is_some_and(|x| x == "rs") {
                out.push(p);
            }
        }
    }

    let mut files = Vec::new();
    rs_files(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("src").as_path(),
        &mut files,
    );
    assert!(!files.is_empty(), "no source to read");

    let help = |args: &[&str]| {
        Command::new(bin())
            .args(args)
            .output()
            .unwrap()
            .status
            .success()
    };

    let mut missing: Vec<String> = Vec::new();
    for f in &files {
        let text = std::fs::read_to_string(f).unwrap();
        for (cmd, sub) in words(&text) {
            if !help(&["help", &cmd]) {
                missing.push(format!("{}: swapdex {cmd}", f.display()));
                continue;
            }
            // Only a command that HAS subcommands can have a wrong one.
            let listing = Command::new(bin()).args(["help", &cmd]).output().unwrap();
            let listing = String::from_utf8_lossy(&listing.stdout).into_owned();
            let Some(sub) = sub.filter(|_| listing.contains("Commands:")) else {
                continue;
            };
            if !help(&[&cmd, &sub, "--help"]) {
                missing.push(format!("{}: swapdex {cmd} {sub}", f.display()));
            }
        }
    }
    missing.sort();
    missing.dedup();
    assert!(
        missing.is_empty(),
        "swapdex tells the user to run commands it does not have:\n  {}",
        missing.join("\n  ")
    );
}

/// The status bar must not go on aging a number that has stopped arriving.
///
/// On a real machine the account paying for Codex had its token rejected by
/// the usage endpoint. `quota` said "token rejected"; the bar, which reads only
/// the cache, said "7d 95% . 1h old" and would have said "2h old", "3h old",
/// forever - the two surfaces disagreeing about the same account, with the one
/// people watch giving the reassuring answer.
#[test]
fn the_status_bar_says_a_reading_stopped_arriving_not_that_it_is_late() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");
    run(root, &["serve", "alpha"]);

    let cache = root.join(".local/share/swapdex/quota-cache.json");
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs() as i64;

    // A reading taken well over an hour ago, and nothing since.
    std::fs::write(
        &cache,
        serde_json::to_vec(&serde_json::json!({
            "alpha": {"seven_d": 5.0, "at": now - 6300}
        }))
        .unwrap(),
    )
    .unwrap();
    let (late, _, _) = run(root, &["serve", "--quiet"]);
    assert!(
        late.contains("7d 95%") && late.contains("old"),
        "a merely late reading still shows its number and its age: {late}"
    );

    // The same cache, plus the fact that the last read was refused outright.
    std::fs::write(
        &cache,
        serde_json::to_vec(&serde_json::json!({
            "alpha": {"seven_d": 5.0, "at": now - 6300, "token_rejected_at": now - 60}
        }))
        .unwrap(),
    )
    .unwrap();
    let (rejected, _, _) = run(root, &["serve", "--quiet"]);
    assert!(
        rejected.contains("token rejected"),
        "the bar must say why the number stopped: {rejected}"
    );
    assert!(
        !rejected.contains("95%"),
        "and must not keep offering a number nothing can refresh: {rejected}"
    );
}

/// Run `proxy --tool <tool>` and require it to EXIT. Returns (stderr, code).
/// Fails the test if it is still running after a few seconds, which is what
/// "it started a server instead of refusing" looks like from out here.
fn refuse_or_die(root: &Path, tool: &str) -> (String, i32) {
    use std::process::Stdio;
    let mut child = Command::new(bin())
        .args(["proxy", "--tool", tool, "--port", "39999"])
        .env("SWAPDEX_ROOT", root)
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .unwrap();
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
    loop {
        if let Some(status) = child.try_wait().unwrap() {
            let out = child.wait_with_output().unwrap();
            return (
                String::from_utf8_lossy(&out.stderr).into_owned(),
                status.code().unwrap_or(-1),
            );
        }
        if std::time::Instant::now() > deadline {
            let _ = child.kill();
            let _ = child.wait();
            panic!(
                "`proxy --tool {tool}` is still running - it started a proxy instead of refusing"
            );
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
}

/// A tool the proxy cannot carry must not be offered a proxy or a service.
///
/// `--tool` was accepted for gemini and antigravity and fell through to the
/// Anthropic branch: `swapdex proxy --tool gemini` announced itself as "swapdex
/// claude proxy" and told the reader to point CLAUDE at it, and `service
/// install --tool gemini` wrote a unit running exactly that on Gemini's port,
/// restarted forever by KeepAlive. The command surface said a Gemini proxy
/// existed; the relay only ever spoke to Anthropic and ChatGPT.
#[test]
fn the_proxy_refuses_a_tool_it_has_no_relay_for() {
    let t = fixture();
    let root = t.path();
    for tool in ["gemini", "antigravity"] {
        // Bounded on purpose. When this regressed, the proxy STARTED and served
        // forever, so a blocking `output()` hung instead of failing - a test
        // that hangs on the defect it exists to catch reports nothing at all.
        let (err, code) = refuse_or_die(root, tool);
        assert_ne!(code, 0, "`proxy --tool {tool}` must not start: {err}");
        assert!(
            err.contains(&format!("no {tool} relay")),
            "and must say why, naming the tool: {err}"
        );
        assert!(
            !err.contains("ANTHROPIC_BASE_URL"),
            "it must never hand out Claude's variable for another tool: {err}"
        );

        let (out, err, code) = run(root, &["service", "install", "--tool", tool]);
        assert_ne!(
            code, 0,
            "`service install --tool {tool}` must refuse: {out}{err}"
        );
        let unit = root.join(format!(".config/systemd/user/swapdex-{tool}.service"));
        let plist = root.join(format!(
            "Library/LaunchAgents/io.github.youdie006.swapdex.{tool}.plist"
        ));
        assert!(
            !unit.exists() && !plist.exists(),
            "and must leave no unit behind"
        );
    }

    // The two it DOES carry still get a unit written. (Whether the proxy then
    // comes UP is a different question, and in a fixture with no accounts it
    // does not - which is why this looks at the unit and not the exit code.)
    for (tool, unit) in [("claude", "swapdex-claude"), ("codex", "swapdex-codex")] {
        run(root, &["service", "install", "--tool", tool]);
        let systemd = root.join(format!(".config/systemd/user/{unit}.service"));
        let launchd = root.join(format!(
            "Library/LaunchAgents/io.github.youdie006.swapdex.{tool}.plist"
        ));
        assert!(
            systemd.exists() || launchd.exists(),
            "`service install --tool {tool}` must still write a unit"
        );
    }
}

/// No message swapdex prints carries a run of collapsed whitespace.
///
/// A string literal split across source lines needs a trailing `\`; without it
/// the indentation of the next line lands in the middle of the sentence. Three
/// apply's rollback must read the item it will write back to.
///
/// The journal records `kc_service: effective_computed_service()` and the
/// rollback calls `keychain_write`, which targets that same env-derived item -
/// but the PRIOR value was read through `keychain_service()`, whose fallback
/// returns a lone discovered item when the derived one does not exist. So on a
/// machine with one other profile's Keychain item and no item of its own - what
/// happens right after a sign-out - a failed apply could roll back by writing
/// ANOTHER ACCOUNT'S token into this environment's item. The `None` arm next to
/// it already names that hazard: "a token/identity mismatch a later `use` would
/// silently apply."
///
/// Only macOS has the Keychain, so the pairing is pinned where it is decided.
#[test]
fn the_rollback_reads_the_same_keychain_item_it_writes_back_to() {
    let src = std::fs::read_to_string(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("src/adapters/claude.rs"),
    )
    .unwrap();
    let at = src
        .find("fn keychain_prior()")
        .expect("the rollback's prior read");
    let end = src[at..].find("\n}\n").expect("the end of that function") + at;
    // Comments explain the hazard by name, so judge the CODE.
    let body: String = src[at..end]
        .lines()
        .filter(|l| !l.trim_start().starts_with("//"))
        .collect::<Vec<_>>()
        .join("\n");
    let body = body.as_str();
    assert!(
        body.contains("effective_computed_service()"),
        "prior must read the env-derived item, the one the rollback writes: {body}"
    );
    assert!(
        !body.contains("keychain_service()"),
        "not through the fallback that can return another profile's item: {body}"
    );
}

/// The check that a sign-out took must ask about the item the sign-out deleted.
///
/// `keychain_delete` targets the ENV-DERIVED Keychain item only - "never a
/// discovered one", because removing another `CLAUDE_CONFIG_DIR` profile's login
/// while adding an account would be a disaster. `present` reads through
/// `pick_service`, which falls back to a lone discovered item when the derived
/// one is gone - correct for an alias-only setup, and exactly wrong here: right
/// after the delete the derived item IS gone, the leftover answers instead, and
/// the sign-out reports failure. On a machine with one leftover - what `doctor`
/// calls "1 other Claude item(s)" - no second account could ever be added.
///
/// Only macOS has the Keychain, so no runnable test can reach this on Linux CI.
/// The wiring is what breaks, so the wiring is what is pinned.
#[test]
fn the_sign_out_check_asks_the_narrow_question() {
    let src =
        std::fs::read_to_string(Path::new(env!("CARGO_MANIFEST_DIR")).join("src/commands.rs"))
            .unwrap();
    let at = src
        .find("sign_out_locally(paths, tool);")
        .expect("the local sign-out");
    let after = &src[at..];
    let check = after
        .find("if still_same ||")
        .expect("the verification that it took");
    let line: String = after[check..].lines().next().unwrap().to_string();
    assert!(
        line.contains("managed_present"),
        "the check must ask about the item the delete targeted: {line}"
    );
    assert!(
        !line.contains(".present("),
        "not whether ANY credential can be read: {line}"
    );
}

/// had it, and two of those print on the proxy's request path - so an account
/// with a lapsed subscription was told about it in a sentence with an
/// eighteen-space hole in it, at the moment the tool most needs to be believed.
#[test]
fn no_printed_message_has_a_hole_in_the_middle_of_it() {
    fn rs_files(dir: &Path, out: &mut Vec<std::path::PathBuf>) {
        for e in std::fs::read_dir(dir).unwrap().flatten() {
            let p = e.path();
            if p.is_dir() {
                rs_files(&p, out);
            } else if p.extension().is_some_and(|x| x == "rs")
                // The wordmark is ASCII art; its spaces ARE the picture.
                && p.file_name().is_some_and(|n| n != "banner.rs")
            {
                out.push(p);
            }
        }
    }
    let mut files = Vec::new();
    rs_files(
        Path::new(env!("CARGO_MANIFEST_DIR")).join("src").as_path(),
        &mut files,
    );

    let mut bad: Vec<String> = Vec::new();
    for f in &files {
        for (i, line) in std::fs::read_to_string(f).unwrap().lines().enumerate() {
            let t = line.trim_start();
            // Comments and doc comments wrap freely; this is about literals.
            if t.starts_with("//") || !line.contains('"') {
                continue;
            }
            // A width/alignment spec marks a table row, where runs of spaces
            // are the columns. Plain `{}` interpolation is not one.
            if line.contains("{:") {
                continue;
            }
            // The shape that is always wrong: mid-SENTENCE. A letter or a
            // sentence mark, then a run long enough to be source indentation,
            // then more text on the same line. Column alignment does not look
            // like this - it follows a `:` or a `}` format spec - and a
            // deliberate output indent follows an escaped newline.
            let b = line.as_bytes();
            for w in 1..b.len().saturating_sub(7) {
                let prev = b[w];
                let sentence = prev.is_ascii_alphabetic() || matches!(prev, b'.' | b',' | b')');
                // `\n` inside a literal: the `n` is a letter but not a word.
                if !sentence || b[w - 1] == b'\\' {
                    continue;
                }
                let run = b[w + 1..].iter().take_while(|&&c| c == b' ').count();
                if run >= 6 && b.get(w + 1 + run).is_some_and(|&c| c != b'/') {
                    bad.push(format!("{}:{}: {}", f.display(), i + 1, line.trim()));
                    break;
                }
            }
        }
    }
    assert!(
        bad.is_empty(),
        "a printed string carries source indentation inside it:\n  {}",
        bad.join("\n  ")
    );
}

/// Every command that REGISTERS an account enforces the same name rule.
///
/// `add`, `use`, `rm`, `rename` and `login` all called it. `run` and `adopt` -
/// the two that actually create a slot - did not, so `adopt '../evil' <dir>`
/// registered that name and `run` with a carriage return in the name made a
/// permanent account that `ls` renders as something other than what it is.
#[test]
fn a_name_no_command_would_accept_cannot_be_registered_by_another() {
    let t = fixture();
    let root = t.path();
    let dir = root.join("adopted");
    std::fs::create_dir_all(&dir).unwrap();

    for bad in ["../evil", "a/b", ".hidden", "good\rEVIL"] {
        let (out, err, code) = run(root, &["adopt", bad, dir.to_str().unwrap()]);
        assert_ne!(code, 0, "adopt accepted {bad:?}: {out}{err}");
        let (out, err, code) = run(root, &["run", bad, "--no-launch"]);
        assert_ne!(code, 0, "run accepted {bad:?}: {out}{err}");
    }

    // Nothing was registered, and the refusal never echoes a control character.
    let listing = std::fs::read_to_string(root.join(".local/share/swapdex/slots.json"))
        .unwrap_or_else(|_| "[]".into());
    assert!(
        !listing.contains("evil"),
        "a refused name was registered: {listing}"
    );
    assert!(
        !listing.contains("EVIL"),
        "a refused name was registered: {listing}"
    );
    let (_, err, _) = run(root, &["adopt", "good\rEVIL", dir.to_str().unwrap()]);
    assert!(
        !err.contains('\r'),
        "the refusal echoed the control character: {err:?}"
    );
}

/// A name reserved where accounts are CREATED is reserved for every creator.
///
/// `add` refuses `-` because `swapdex use -` toggles to the previous account.
/// `adopt` and `run` register accounts too, and they check only the permanent
/// rule, which deliberately ALLOWS `-` so a legacy account carrying that name
/// stays rm-able. So `adopt - <dir>` registered it, and `use -` then selected
/// that account instead of toggling - the harm the reservation exists to stop.
#[test]
fn a_name_reserved_at_creation_is_refused_by_every_creator() {
    let t = fixture();
    let root = t.path();
    let dir = root.join("adopted");
    std::fs::create_dir_all(&dir).unwrap();

    let (out, err, code) = run(root, &["adopt", "-", dir.to_str().unwrap()]);
    assert_ne!(code, 0, "adopt accepted '-': {out}{err}");
    let (out, err, code) = run(root, &["run", "-", "--no-launch"]);
    assert_ne!(code, 0, "run accepted '-': {out}{err}");

    // The whole leading-dash range, not just the toggle. clap refuses these as
    // bare positionals, so they arrive the only way they can - after `--`, the
    // form migrate and a 0.2.x store can still hand over.
    let (out, err, code) = run(root, &["adopt", "--", "-x", dir.to_str().unwrap()]);
    assert_ne!(code, 0, "adopt accepted '-x': {out}{err}");
    let (out, err, code) = run(root, &["run", "--no-launch", "--", "-x"]);
    assert_ne!(code, 0, "run accepted '-x': {out}{err}");
    let (out, err, code) = run(root, &["add", "--", "-x"]);
    assert_ne!(code, 0, "add accepted '-x': {out}{err}");

    let rows: Vec<serde_json::Value> = std::fs::read(root.join(".local/share/swapdex/slots.json"))
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    for r in &rows {
        let n = r["name"].as_str().unwrap_or_default();
        assert!(
            !n.starts_with('-'),
            "a name reserved at creation was registered: {rows:?}"
        );
    }
}

/// The reservation is at creation only: an account already named `-` stays
/// manageable.
///
/// That is why the permanent rule allows the name, and why the refusal above
/// must not move into it - a 0.2.x account named `-` would otherwise be stuck,
/// unable to be renamed out of the name or removed.
#[test]
fn an_account_already_named_dash_can_still_be_renamed_and_removed() {
    let t = fixture();
    let root = t.path();

    seed_slot(root, "-", "dash@example.com");
    let (out, err, code) = run(root, &["rename", "-", "dash"]);
    assert_eq!(code, 0, "a legacy '-' could not be renamed: {out}{err}");

    seed_slot(root, "-", "dash2@example.com");
    let (out, err, code) = run(root, &["rm", "-", "--yes"]);
    assert_eq!(code, 0, "a legacy '-' could not be removed: {out}{err}");
}

/// An account's rotation preferences must answer to the same name the account does.
///
/// `settings.json` keys `disabled` and `priority` by account name, and the proxy
/// filters on exact string equality. `rename` moved the slot registries and the
/// stored profile but left the preferences pointing at a name that no longer
/// exists, so a paused account quietly rejoined rotation - the one thing pausing
/// it was meant to prevent. `rm` left the entry behind entirely, so a later
/// account that happened to reuse the name was born paused and pre-ranked, with
/// nothing on any screen to say why.
#[test]
fn rotation_preferences_follow_a_rename_and_leave_with_a_removal() {
    let t = fixture();
    let root = t.path();
    let settings = root.join(".local/share/swapdex/settings.json");

    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");

    std::fs::write(
        &settings,
        br#"{"disabled":["alpha"],"priority":["other","alpha"]}"#,
    )
    .unwrap();

    let (_, err, code) = run(root, &["rename", "alpha", "alpha2"]);
    assert_eq!(code, 0, "rename failed: {err}");
    let after = std::fs::read_to_string(&settings).unwrap();
    assert!(
        !after.contains("\"alpha\""),
        "the old name still holds the preferences after a rename: {after}"
    );
    assert!(
        after.contains("alpha2"),
        "the pause did not follow the account: {after}"
    );

    // This name is both a slot and a saved profile, so the first `rm` retires
    // only the slot - the profile still answers to the name, and so do its
    // preferences.
    let (out, err, code) = run(root, &["rm", "alpha2", "--yes"]);
    assert_eq!(code, 0, "rm failed: {err}");
    assert!(
        out.contains("still here"),
        "expected a partial removal: {out}"
    );
    let after = std::fs::read_to_string(&settings).unwrap();
    assert!(
        after.contains("alpha2"),
        "a partial removal dropped preferences the profile still owns: {after}"
    );

    // The second retires the profile, and now nothing answers to the name.
    let (_, err, code) = run(root, &["rm", "alpha2", "--yes"]);
    assert_eq!(code, 0, "rm failed: {err}");
    let after = std::fs::read_to_string(&settings).unwrap();
    assert!(
        !after.contains("alpha2"),
        "a removed account left its preferences for the next account of that name: {after}"
    );
}

/// A remembered usage reading must answer to the same name the account does.
///
/// `quota-cache.json` keys the last-known windows by account name and every
/// display looks them up by exact name. `rename` moved the account and left the
/// reading behind, so the old name went on drawing a row - a phantom account
/// with numbers - while the renamed one showed as never read. `rm` left it
/// behind entirely, so the next account registered under that name inherited a
/// stranger's percentages, its credit status and its sign-out.
///
/// The cache is sharded per tool, so this has to walk EVERY tool's file - the
/// same lesson `rename` already learned about the slot registries.
#[test]
fn remembered_usage_follows_a_rename_and_leaves_with_a_removal() {
    let t = fixture();
    let root = t.path();
    let store = root.join(".local/share/swapdex");
    let claude_cache = store.join("quota-cache.json");
    let codex_cache = store.join("codex-quota-cache.json");

    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "alpha", "a@example.com");

    let reading = |pct: f64| {
        serde_json::to_vec(&serde_json::json!({"alpha": {
            "five_h": pct, "five_h_reset": 9_000_000_000i64,
            "seven_d": pct, "seven_d_reset": 9_000_000_000i64, "at": 1_700_000_000i64}}))
        .unwrap()
    };
    std::fs::write(&claude_cache, reading(22.0)).unwrap();
    std::fs::write(&codex_cache, reading(44.0)).unwrap();

    let (_, err, code) = run(root, &["rename", "alpha", "alpha2"]);
    assert_eq!(code, 0, "rename failed: {err}");
    for f in [&claude_cache, &codex_cache] {
        let after = std::fs::read_to_string(f).unwrap();
        assert!(
            !after.contains("\"alpha\""),
            "{}: the old name still holds the reading: {after}",
            f.display()
        );
        assert!(
            after.contains("alpha2"),
            "{}: the reading did not follow the account: {after}",
            f.display()
        );
    }

    // `alpha2` is both a slot and a saved profile, so the first `rm` retires
    // only the slot - the profile still answers to the name, and so does its
    // remembered usage.
    let (out, err, code) = run(root, &["rm", "alpha2", "--yes"]);
    assert_eq!(code, 0, "rm failed: {err}");
    assert!(
        out.contains("still here"),
        "expected a partial removal: {out}"
    );
    assert!(
        std::fs::read_to_string(&claude_cache)
            .unwrap()
            .contains("alpha2"),
        "a partial removal dropped a reading the profile still owns"
    );

    // The second retires the profile, and now nothing answers to the name.
    let (_, err, code) = run(root, &["rm", "alpha2", "--yes"]);
    assert_eq!(code, 0, "rm failed: {err}");
    for f in [&claude_cache, &codex_cache] {
        let after = std::fs::read_to_string(f).unwrap();
        assert!(
            !after.contains("alpha2"),
            "{}: a removed account left its numbers for the next account of that name: {after}",
            f.display()
        );
    }
}

/// Dropping ONE tool from an account is a partial removal: the account is still
/// here, so everything keyed by its name stays with it.
///
/// `rm --tool` unregisters one slot and leaves the rest of the account alone,
/// and both name-keyed stores - its rotation preferences and its remembered
/// usage - still have an owner. Forgetting them here would silently un-pause an
/// account that is still listed and blank a reading it still answers to, from a
/// command that never claimed to remove the account at all.
#[test]
fn dropping_one_tool_keeps_the_side_state_the_account_still_owns() {
    let t = fixture();
    let root = t.path();
    let store = root.join(".local/share/swapdex");
    let settings = store.join("settings.json");
    let claude_cache = store.join("quota-cache.json");

    seed_slot(root, "both", "b@example.com");
    seed_codex_slot(root, "both", "b@example.com");
    std::fs::write(
        &settings,
        br#"{"disabled":["both"],"priority":["other","both"]}"#,
    )
    .unwrap();
    std::fs::write(
        &claude_cache,
        serde_json::to_vec(&serde_json::json!({"both": {
            "five_h": 22.0, "five_h_reset": 9_000_000_000i64,
            "seven_d": 22.0, "seven_d_reset": 9_000_000_000i64, "at": 1_700_000_000i64}}))
        .unwrap(),
    )
    .unwrap();

    let (out, err, code) = run(root, &["rm", "both", "--tool", "codex", "--yes"]);
    assert_eq!(code, 0, "dropping the codex slot failed: {err}{out}");
    let (listing, _, _) = run(root, &["ls"]);
    assert!(listing.contains("both"), "the account vanished:\n{listing}");

    let after = std::fs::read_to_string(&settings).unwrap();
    assert!(
        after.contains("both"),
        "dropping one tool un-paused an account that is still listed: {after}"
    );
    let after = std::fs::read_to_string(&claude_cache).unwrap();
    assert!(
        after.contains("both"),
        "dropping one tool blanked a reading the account still owns: {after}"
    );
}

/// A bare `rm <name>` must remove the account under EVERY tool, not the first
/// registry that happens to hold the name.
///
/// One name is one account across tools - `ls` draws a two-tool account as a
/// single row, and the prompt asks to "stop managing account '<name>'". The
/// removal opened one registry, so `rm both --yes` printed "stopped managing
/// 'both'." and left `both [codex]` listed, silently: the profile case prints
/// a "run it again" note, the second-tool case printed nothing. It also
/// dropped the account's preferences, readings and ledger row on the way out,
/// because the code below it assumed the account was now gone.
///
/// `mv` already loops every registry for this exact split - "an account holding
/// both a Claude and a Codex slot came out split in two - one login under two
/// names".
#[test]
fn removing_an_account_removes_it_under_every_tool() {
    let t = fixture();
    let root = t.path();
    let store = root.join(".local/share/swapdex");
    let settings = store.join("settings.json");

    seed_slot(root, "both", "b@example.com");
    seed_codex_slot(root, "both", "b@example.com");
    std::fs::write(
        &settings,
        br#"{"disabled":["both"],"priority":["other","both"]}"#,
    )
    .unwrap();

    let (out, err, code) = run(root, &["rm", "both", "--yes"]);
    assert_eq!(code, 0, "removing the account failed: {err}{out}");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        !listing.contains("both"),
        "one `rm` left half the account listed under the other tool:\n{listing}"
    );
    let (slots, _, _) = run(root, &["slots"]);
    assert!(
        !slots.contains("both"),
        "the slot survived under a tool `rm` never opened:\n{slots}"
    );

    // Nothing answers to the name now, so its side state goes with it.
    let after = std::fs::read_to_string(&settings).unwrap();
    assert!(
        !after.contains("both"),
        "a fully removed account kept its rotation preferences: {after}"
    );
}

/// The ledger that attributes usage must answer to the same name the account
/// does - whether or not the account ever saved a snapshot.
///
/// `timeline.jsonl` credits every session and every token to a name, and
/// `Store::rename` rewrites it for exactly that reason: leaving the old name
/// there makes `usage`/`sessions` report an account that no longer exists,
/// forever. But `rename` reaches that rewrite only when a profile moves. A
/// slot-only account takes the earlier branch, which carries its rotation
/// preferences and its remembered usage and nothing else, so the ledger goes
/// on naming an account the listing no longer knows.
#[test]
fn the_ledger_follows_a_slot_only_rename() {
    let t = fixture();
    let root = t.path();
    let timeline = root.join(".local/share/swapdex/timeline.jsonl");

    seed_claude(root, "uuid-live", "live@example.com");
    seed_slot(root, "before", "b@example.com");

    let (_, err, code) = run(root, &["use", "before"]);
    assert_eq!(code, 0, "switching to the slot failed: {err}");
    let ledger = std::fs::read_to_string(&timeline).unwrap();
    assert!(
        ledger.contains("\"before\""),
        "the switch left no record to carry: {ledger}"
    );

    let (_, err, code) = run(root, &["rename", "before", "after"]);
    assert_eq!(code, 0, "rename failed: {err}");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        !listing.contains("before") && listing.contains("after"),
        "the listing did not follow the rename:\n{listing}"
    );
    let ledger = std::fs::read_to_string(&timeline).unwrap();
    assert!(
        !ledger.contains("\"before\""),
        "the ledger still credits a name nothing answers to: {ledger}"
    );
    assert!(
        ledger.contains("\"after\""),
        "the ledger did not follow the account: {ledger}"
    );
}

/// A removed account must not hand its sessions and tokens to the next account
/// that takes its name.
///
/// Both of the other name-keyed stores drop their account on removal and both
/// say why in the source: what stays behind is inherited by whatever is
/// registered under that name next. `timeline.jsonl` is the third store keyed
/// by name, and `rm` leaves it untouched - so a stranger who registers the
/// freed name is credited with a removed account's history.
///
/// Deleting the events is not the fix. `usage` attributes each transcript to
/// the account active at its timestamp, so erasing the removed account's switch
/// hands its tokens to whichever account switched BEFORE it - a different,
/// innocent account. The name has to be retired in place.
#[test]
fn a_removed_account_does_not_hand_its_usage_to_the_next_account_of_that_name() {
    let t = fixture();
    let root = t.path();
    let timeline = root.join(".local/share/swapdex/timeline.jsonl");

    seed_claude(root, "uuid-live", "live@example.com");
    seed_slot(root, "keeper", "keeper@example.com");
    seed_slot(root, "ghost", "ghost@example.com");

    // `keeper` switches first, so erasing `ghost` would move ghost's tokens
    // onto keeper rather than off the books.
    for name in ["keeper", "ghost"] {
        let (_, err, code) = run(root, &["use", name]);
        assert_eq!(code, 0, "switching to {name} failed: {err}");
    }

    // Tokens spent a minute after the switch to `ghost`, so the ledger has
    // something to attribute.
    let ledger = std::fs::read_to_string(&timeline).unwrap();
    let last: serde_json::Value = serde_json::from_str(ledger.lines().last().unwrap()).unwrap();
    let spent_at = last["ts"].as_i64().unwrap() + 60;
    let proj = root.join(".claude/projects/p");
    std::fs::create_dir_all(&proj).unwrap();
    std::fs::write(
        proj.join("s.jsonl"),
        serde_json::to_vec(&serde_json::json!({
            "timestamp": swapdex::refresh::rfc3339_utc(spent_at),
            "message": {"usage": {"input_tokens": 12000, "output_tokens": 3000}}}))
        .unwrap(),
    )
    .unwrap();

    let (out, _, _) = run(root, &["usage"]);
    assert!(
        out.contains("@ghost"),
        "the switch did not attribute the tokens to ghost:\n{out}"
    );

    let (_, err, code) = run(root, &["rm", "ghost", "--yes"]);
    assert_eq!(code, 0, "rm failed: {err}");

    // A different person registers the freed name.
    seed_slot(root, "ghost", "stranger@example.com");

    let (out, _, _) = run(root, &["usage"]);
    assert!(
        !out.contains("@ghost"),
        "a removed account handed its tokens to the next account of that name:\n{out}"
    );
    assert!(
        !out.contains("@keeper"),
        "erasing the removed account moved its tokens onto the account before it:\n{out}"
    );
}

/// One directory is one account, or a pointer cannot name a payer.
///
/// `Slots::payer` resolves a pointer back to a name with `.find` - the pointer
/// files hold PATHS - and its doc says it lives in one place so that what a
/// screen claims and what the proxy does cannot drift apart. That holds only
/// while a directory belongs to one account. `adopt` rejected a duplicate NAME
/// and never a duplicate DIRECTORY, while onboarding - which calls that same
/// `adopt` - filters out the directories already registered before it does. Two
/// records on one directory made `use beta` write "beta" into the ledger while
/// `ls` and `serve --quiet` both credited alpha.
#[test]
fn one_directory_is_one_account() {
    let t = fixture();
    let root = t.path();
    let shared = root.join("home/.claude-shared");
    std::fs::create_dir_all(&shared).unwrap();
    let shared = shared.to_str().unwrap();

    let (out, err, code) = run(root, &["adopt", "alpha", shared]);
    assert_eq!(code, 0, "the first adopt was refused: {out}{err}");

    let (out, err, code) = run(root, &["adopt", "beta", shared]);
    assert_ne!(
        code, 0,
        "a second account was registered on alpha's directory: {out}{err}"
    );
    assert!(
        err.contains("alpha"),
        "the refusal has to name the account already holding it: {err}"
    );

    // Nothing half-written: the refused name reaches no screen, and the account
    // that does hold the directory is still the one every screen credits.
    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        !listing.contains("beta"),
        "a refused adopt still left a row:\n{listing}"
    );
    run(root, &["use", "alpha"]);
    let (quiet, _, _) = run(root, &["serve", "--quiet"]);
    assert!(
        quiet.starts_with("alpha"),
        "the status bar credits '{}' after `use alpha`",
        quiet.trim()
    );
}

/// The refusal is about ambiguity, not about seeing a directory twice.
///
/// A registry is opened FOR one tool and resolves pointers among that tool's
/// records only, and each tool keeps its own pointer files. A directory that is
/// a home for claude and a home for codex therefore names one account on each
/// side, and adopting it for the second tool has to keep working.
#[test]
fn each_tool_may_adopt_the_same_directory() {
    let t = fixture();
    let root = t.path();
    let shared = root.join("home/.shared");
    std::fs::create_dir_all(&shared).unwrap();
    let shared = shared.to_str().unwrap();

    let (out, err, code) = run(root, &["adopt", "alpha", shared]);
    assert_eq!(code, 0, "the claude adopt was refused: {out}{err}");
    let (out, err, code) = run(root, &["adopt", "alpha", shared, "--tool", "codex"]);
    assert_eq!(
        code, 0,
        "codex could not adopt the directory claude holds: {out}{err}"
    );
}

/// `use` has to reach every account the listing shows, whatever tool holds it.
///
/// `use` asked ONE registry - the helper that reads `--tool` collapses "no
/// --tool given" to claude-code - while `ls` asks every registry. A Codex-only
/// account was therefore listed and then rejected: `use cxonly` printed "no
/// profile named 'cxonly'" and exited 5, and only `--tool codex` moved it.
/// `use --help` promises the opposite: "default: every tool the profile has".
#[test]
fn a_codex_only_account_is_reachable_by_a_bare_use() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cxonly", "cx@example.com");

    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        listing.contains("cxonly"),
        "`ls` does not list it:\n{listing}"
    );

    let (_, err, code) = run(root, &["use", "cxonly"]);
    assert_eq!(
        code, 0,
        "`use cxonly` rejected an account `ls` shows: {err}"
    );

    // The default is who pays while nobody is serving, so the listing has to
    // name it - the same check every other switch here makes.
    let (after, _, _) = run(root, &["ls"]);
    let marked: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(
        marked.len(),
        1,
        "after `use cxonly` exactly one row should pay:\n{after}"
    );
    assert!(
        marked[0].contains("cxonly"),
        "the paying row names someone else:\n{}",
        marked[0]
    );
}

/// One row in `ls` is one account, so `use` moves all of it.
///
/// A name can be a saved Claude profile and a Codex slot at once, and `ls`
/// draws that as a single row. `use mix` reported success having moved only
/// the Claude half: the Codex default was left where it was, with nothing on
/// any screen saying so.
#[test]
fn use_moves_every_tool_of_an_account_that_spans_two() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-mix", "mix@example.com");
    run(root, &["add", "mix"]);
    seed_codex_slot(root, "mix", "mix@example.com");
    // Claude is signed in as someone else, so the Claude half is a real move.
    seed_claude(root, "uuid-oth", "oth@example.com");
    run(root, &["add", "other"]);

    let (_, err, code) = run(root, &["use", "mix"]);
    assert_eq!(code, 0, "`use mix` failed: {err}");

    let (after, _, _) = run(root, &["ls"]);
    let row = after
        .lines()
        .find(|l| l.trim_start_matches(['*', ' ']).starts_with("mix "))
        .unwrap_or_else(|| panic!("no row for mix:\n{after}"));
    assert!(
        row.contains("claude-code*"),
        "the claude half did not move:\n{after}"
    );
    assert!(
        row.contains("pays"),
        "the codex half did not move:\n{after}"
    );
}

/// A slot switch must not also copy a credential over the live login.
///
/// `migrate --tool claude` leaves an account holding both a Claude slot and a
/// Claude snapshot, so `use` had two ways to move the same tool and took both:
/// it repointed the default AND wrote the snapshot over whoever was signed in.
/// A credential copy is what the slot model buys its way out of - it is what
/// makes a rotating token log the other session out.
#[test]
fn a_slot_switch_does_not_copy_over_the_live_login() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-dual", "dual@example.com");
    seed_live_codex(root, "dual@example.com");
    run(root, &["add", "dual"]);
    // Claude gets a slot, Codex does not, so the profile still covers a tool no
    // slot took and the copy-model path still has something to do.
    run(root, &["migrate", "--tool", "claude"]);
    // Someone else is signed in to Claude, so a copy would be visible.
    seed_claude(root, "uuid-oth", "oth@example.com");
    run(root, &["add", "other"]);

    let (_, err, code) = run(root, &["use", "dual"]);
    assert_eq!(code, 0, "`use dual` failed: {err}");

    let (after, _, _) = run(root, &["ls"]);
    // The slot did move: the default pays while nobody is serving.
    let marked: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(marked.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        marked[0].contains("dual"),
        "the paying row names someone else:\n{}",
        marked[0]
    );
    // Nothing was written to the live Claude dir.
    assert_eq!(
        live_claude_email(root),
        "oth@example.com",
        "the live claude login was overwritten:\n{after}"
    );
}

/// `restore` undoes the LAST switch. A slot switch moves a pointer, not a
/// credential, so its undo is repointing the default back - the copy-model
/// backup belongs to some older switch. Reaching for that backup left the slot
/// switch standing and wrote a third account, saved nowhere, over the live
/// login instead.
#[test]
fn restore_undoes_a_slot_switch_not_an_older_backup() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "alpha@example.com");
    run(root, &["add", "alpha"]);
    seed_claude(root, "uuid-b", "beta@example.com");
    run(root, &["add", "beta"]);
    run(root, &["migrate", "--tool", "claude"]);
    // Added after the migration, so it is a profile and no slot: `use` still
    // has a copy-model path to take, and that path leaves a backup.
    seed_claude(root, "uuid-g", "gamma@example.com");
    run(root, &["add", "gamma"]);
    // Signed in by hand and saved nowhere - what the stale backup holds.
    seed_claude(root, "uuid-d", "delta@example.com");

    run(root, &["use", "gamma"]);
    run(root, &["use", "beta"]);
    run(root, &["use", "alpha"]);

    let (_, err, code) = run(root, &["restore"]);
    assert_eq!(code, 0, "`restore` failed: {err}");

    let (after, _, _) = run(root, &["ls"]);
    let marked: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(marked.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        marked[0].contains("beta"),
        "the slot switch was not undone:\n{after}"
    );
    assert_eq!(
        live_claude_email(root),
        "gamma@example.com",
        "the live login was overwritten from an older backup:\n{after}"
    );
}

/// The other side of the same seam: in a store that holds slots, a switch that
/// went the copy model still has to come back from the credential backup.
/// Repointing a default there would leave the live login where the bad switch
/// put it.
#[test]
fn restore_of_a_copy_model_switch_still_uses_the_backup() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "alpha@example.com");
    run(root, &["add", "alpha"]);
    seed_claude(root, "uuid-b", "beta@example.com");
    run(root, &["add", "beta"]);
    run(root, &["migrate", "--tool", "claude"]);
    seed_claude(root, "uuid-g", "gamma@example.com");
    run(root, &["add", "gamma"]);
    seed_claude(root, "uuid-d", "delta@example.com");

    let (before, _, _) = run(root, &["ls"]);
    let payer_before: Vec<&str> = before.lines().filter(|l| l.contains("pays")).collect();

    run(root, &["use", "gamma"]);
    let (out, err, code) = run(root, &["restore"]);
    assert_eq!(code, 0, "`restore` failed: {err}");
    assert!(
        out.contains("delta@example.com"),
        "the backed-up login did not come back:\n{out}"
    );

    let (after, _, _) = run(root, &["ls"]);
    let payer_after: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(
        payer_before, payer_after,
        "a copy-model restore moved the default pointer:\n{after}"
    );
}

/// Selecting the account that is already the default records a switch that
/// changed nothing. Undoing that one has to reach past it, or `restore` puts
/// back what is already there and the switch before it is stranded.
#[test]
fn restore_reaches_past_a_slot_switch_that_changed_nothing() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "alpha@example.com");
    run(root, &["add", "alpha"]);
    seed_claude(root, "uuid-b", "beta@example.com");
    run(root, &["add", "beta"]);
    run(root, &["migrate", "--tool", "claude"]);

    run(root, &["use", "beta"]);
    run(root, &["use", "alpha"]);
    run(root, &["use", "alpha"]);

    let (_, err, code) = run(root, &["restore"]);
    assert_eq!(code, 0, "`restore` failed: {err}");
    let (after, _, _) = run(root, &["ls"]);
    let marked: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(marked.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        marked[0].contains("beta"),
        "`restore` stopped at the switch that changed nothing:\n{after}"
    );
}

/// A slot account answers to the prefix its own row is listed under.
///
/// `ls` draws one row per account across every registry and `use <exact-name>`
/// repoints a slot fine, but the name resolver drew its candidates from the
/// snapshot store alone. A slot-only owner - the whole point of the slot model -
/// therefore had the short name they type every day rejected as a profile that
/// does not exist.
#[test]
fn a_slot_only_account_answers_to_its_prefix() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_slot(root, "workacct", "workacct@example.com");

    let (listed, _, _) = run(root, &["ls"]);
    assert!(
        listed.contains("personal"),
        "the slot is listed under this name:\n{listed}"
    );

    let (out, err, code) = run(root, &["use", "pers"]);
    assert_eq!(code, 0, "a unique prefix should switch: {err}{out}");
    let (after, _, _) = run(root, &["ls"]);
    let pays: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(pays.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        pays[0].contains("personal"),
        "the prefix should have switched the account it matched:\n{after}"
    );
}

/// `-` toggles between slot accounts too, and says which ones when it cannot.
///
/// The toggle reads the switch timeline, which a slot switch writes like any
/// other - but it then dropped every candidate the snapshot store did not know.
/// With no store profile at all the remedy it printed named an empty set,
/// `swapdex use <>`, a command nobody can type.
#[test]
fn the_toggle_reaches_a_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_slot(root, "workacct", "workacct@example.com");

    let (_, err, code) = run(root, &["use", "-"]);
    assert_ne!(
        code, 0,
        "nothing has been switched yet, so '-' means nothing"
    );
    assert!(
        err.contains("personal") && err.contains("workacct"),
        "the remedy has to name the accounts that exist:\n{err}"
    );

    run(root, &["use", "personal"]);
    run(root, &["use", "workacct"]);
    let (out, err, code) = run(root, &["use", "-"]);
    assert_eq!(
        code, 0,
        "'-' should go back to the previous slot: {err}{out}"
    );
    let (after, _, _) = run(root, &["ls"]);
    let pays: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(pays.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        pays[0].contains("personal"),
        "'-' should have gone back to the account before this one:\n{after}"
    );
}

/// A prefix on an account that owns a slot still moves the pointer.
///
/// `use` asked the slot registries about the raw argument, so a prefix - which
/// no registry has a row for - looked like a legacy copy-model profile and took
/// the copy path. That path writes a credential over the very slot the account
/// already has, which is what the slot model exists to prevent.
#[test]
fn a_prefix_on_a_migrated_account_repoints_its_slot() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "alpha@example.com");
    run(root, &["add", "alpha"]);
    seed_claude(root, "uuid-b", "beta@example.com");
    run(root, &["add", "beta"]);
    run(root, &["migrate", "--tool", "claude"]);

    let (exact, _, _) = run(root, &["use", "alpha"]);
    let (prefix, err, code) = run(root, &["use", "bet"]);
    assert_eq!(code, 0, "a unique prefix should switch: {err}{prefix}");
    assert_eq!(
        prefix.lines().next().map(|l| l.replace("beta", "alpha")),
        exact.lines().next().map(|l| l.to_string()),
        "the prefix took a different path than the name it expands to:\n\
         exact:  {exact}\nprefix: {prefix}"
    );
}

/// A prefix is resolved against the tool the switch is for.
///
/// Name resolution reaches into the slot registries, and has to stay inside the
/// selection `--tool` made. An account only Claude holds a slot for is not a
/// candidate for a Codex switch: counting it makes the Codex account's own
/// prefix read as two accounts, so the short name stops working the moment a
/// neighbour is registered for some other tool.
#[test]
fn a_prefix_resolves_only_against_the_selected_tool() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "shared-claude", "claude@example.com");
    seed_codex_slot(root, "shared-codex", "codex@example.com");

    let (out, err, code) = run(root, &["use", "shared", "--tool", "codex"]);
    assert_eq!(code, 0, "'shared' names one codex account: {err}{out}");
    let (after, _, _) = run(root, &["ls"]);
    assert!(
        after
            .lines()
            .any(|l| l.contains("shared-codex") && l.contains("pays")),
        "the codex account the prefix names should be paying:\n{after}"
    );
}

/// A stub tool binary on PATH, so `--open` has something to exec. Returns the
/// PATH to run with.
fn fake_tool(root: &Path, bin_name: &str, marker: &str) -> String {
    use std::os::unix::fs::PermissionsExt;
    let dir = root.join("fakebin");
    std::fs::create_dir_all(&dir).unwrap();
    let p = dir.join(bin_name);
    std::fs::write(&p, format!("#!/bin/sh\necho {marker}\n")).unwrap();
    std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
    format!(
        "{}:{}",
        dir.display(),
        std::env::var("PATH").unwrap_or_default()
    )
}

/// `run`, with the stub tools ahead of everything on PATH.
fn run_on_path(root: &Path, args: &[&str], path: &str) -> (String, String, i32) {
    let out = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("PATH", path)
        .stdin(std::process::Stdio::null())
        .output()
        .unwrap();
    (
        String::from_utf8_lossy(&out.stdout).into_owned(),
        String::from_utf8_lossy(&out.stderr).into_owned(),
        out.status.code().unwrap_or(-1),
    )
}

/// `--open` switches the same accounts a plain `use` switches.
///
/// A slot-only account is what the slot model produces: registered under a
/// tool, holding no snapshot. `use <name>` repoints its pointer, and `--open`
/// is that same switch plus a launch - but it went straight to the copy-model
/// path, which asks the snapshot store alone. So the account `ls` lists and
/// `use` had just switched to was rejected as a profile that does not exist.
#[test]
fn open_reaches_a_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_slot(root, "workacct", "workacct@example.com");
    let path = fake_tool(root, "claude", "CLAUDE-OPENED");

    let (out, err, code) = run_on_path(
        root,
        &["use", "workacct", "--tool", "claude", "--open"],
        &path,
    );
    assert_eq!(code, 0, "`use --open` on a listed account: {err}{out}");
    assert!(
        out.contains("CLAUDE-OPENED"),
        "claude should launch after the switch:\n{out}{err}"
    );
    let (after, _, _) = run(root, &["ls"]);
    assert!(
        after
            .lines()
            .any(|l| l.contains("workacct") && l.contains("pays")),
        "`--open` must make the switch `use` makes:\n{after}"
    );
}

/// `--open` must not copy a credential over the slot it just repointed.
///
/// An account that came through `migrate` holds both a slot and a snapshot, so
/// there are two ways to move the same tool. `use` asks the slot registry and
/// repoints the pointer; `--open` never asked it, so the snapshot was written
/// over whoever was signed in - the very copy the slot model exists to avoid -
/// and the pointer the switch was supposed to move stayed where it was.
#[test]
fn open_does_not_copy_over_the_slot_it_switched() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-dual", "dual@example.com");
    run(root, &["add", "dual"]);
    run(root, &["migrate", "--tool", "claude"]);
    // Someone else is signed in to Claude, so a copy would be visible.
    seed_claude(root, "uuid-oth", "oth@example.com");
    run(root, &["add", "other"]);
    let path = fake_tool(root, "claude", "CLAUDE-OPENED");

    let (out, err, code) = run_on_path(root, &["use", "dual", "--tool", "claude", "--open"], &path);
    assert_eq!(code, 0, "`use dual --open` failed: {err}{out}");

    let (after, _, _) = run(root, &["ls"]);
    let marked: Vec<&str> = after.lines().filter(|l| l.contains("pays")).collect();
    assert_eq!(marked.len(), 1, "exactly one row should pay:\n{after}");
    assert!(
        marked[0].contains("dual"),
        "the paying row names someone else:\n{}",
        marked[0]
    );
    assert_eq!(
        live_claude_email(root),
        "oth@example.com",
        "the live claude login was overwritten:\n{after}"
    );
}

/// A switch that did not work does not launch anything.
///
/// `--open` is a switch and then a launch, in that order. Landing in a live
/// session on the account the user was trying to leave is worse than not
/// launching: the next message is billed to the wrong account, and nothing on
/// screen says so.
#[test]
fn open_does_not_launch_a_failed_switch() {
    use std::os::unix::fs::PermissionsExt;
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_claude(root, "uuid-b", "b@example.com");
    run(root, &["add", "beta"]);
    let path = fake_tool(root, "claude", "CLAUDE-OPENED");
    // The live login cannot be written, so the switch cannot happen.
    let live = root.join(".claude");
    std::fs::set_permissions(&live, std::fs::Permissions::from_mode(0o500)).unwrap();

    let (out, err, code) =
        run_on_path(root, &["use", "alpha", "--tool", "claude", "--open"], &path);
    std::fs::set_permissions(&live, std::fs::Permissions::from_mode(0o700)).unwrap();

    assert_ne!(
        code, 0,
        "a switch that could not write should not report success:\n{out}{err}"
    );
    assert!(
        !out.contains("CLAUDE-OPENED"),
        "claude launched after a failed switch:\n{out}{err}"
    );
}

/// Drive the plain numbered menu over a pipe. `TERM=dumb` is what a terminal
/// that cannot render ANSI reports (Emacs shell, some CI), and it is what sends
/// `ui` down this path instead of the full-screen picker.
fn run_ui(root: &Path, keys: &str) -> (String, String, i32) {
    use std::io::Write;
    let mut child = Command::new(bin())
        .arg("ui")
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("TERM", "dumb")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(keys.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),
    )
}

/// Drive the real full-screen picker through a pseudo-terminal.
///
/// `SWAPDEX_ASSUME_TTY` deliberately selects the plain fallback; a PTY is
/// required to cover the dashboard row builder that runs on an actual terminal.
///
/// The child is put in its own session and given the slave as its CONTROLLING
/// terminal. Without that the macOS runner ran it to a thirty-second timeout
/// having written zero bytes - measured, by dumping what the pty received -
/// while Linux tolerated the same setup. A pty a process cannot claim is not a
/// terminal to it, so the screen this covers never drew.
#[cfg(unix)]
fn run_fullscreen_ui(root: &Path, keys: &[u8]) -> (String, i32) {
    use std::io::{Read, Write};
    use std::os::fd::FromRawFd;
    use std::os::unix::process::CommandExt;

    let mut master = -1;
    let mut slave = -1;
    let mut size = libc::winsize {
        ws_row: 40,
        ws_col: 120,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };
    // `*mut` for the termios and winsize arguments on BOTH platforms: macOS
    // declares them `*mut` and Linux `*const`, and a `*mut` coerces to a
    // `*const` while the reverse does not. Written the other way round this
    // compiled here and broke the macOS job only. Raw pointers rather than
    // `&mut`, because on Linux clippy rejects a mutable reference the callee
    // does not need.
    let rc = unsafe {
        libc::openpty(
            &mut master,
            &mut slave,
            std::ptr::null_mut(),
            std::ptr::null_mut(),
            std::ptr::addr_of_mut!(size),
        )
    };
    assert_eq!(rc, 0, "openpty failed");
    let mut master = unsafe { std::fs::File::from_raw_fd(master) };
    let slave = unsafe { std::fs::File::from_raw_fd(slave) };

    let mut cmd = Command::new(bin());
    cmd.arg("ui")
        .env("SWAPDEX_ROOT", root)
        .env("TERM", "xterm")
        .stdin(std::process::Stdio::from(slave.try_clone().unwrap()))
        .stdout(std::process::Stdio::from(slave.try_clone().unwrap()))
        .stderr(std::process::Stdio::from(slave));
    // Runs in the child after the stdio dup2s and before exec, so fd 0 is
    // already the pty slave. `setsid` first - TIOCSCTTY is refused unless the
    // caller is a session leader with no controlling terminal yet. Both calls
    // are async-signal-safe, which is the rule for anything in here.
    unsafe {
        cmd.pre_exec(|| {
            if libc::setsid() == -1 {
                return Err(std::io::Error::last_os_error());
            }
            if libc::ioctl(0, libc::TIOCSCTTY as _, 0) == -1 {
                return Err(std::io::Error::last_os_error());
            }
            Ok(())
        });
    }
    let mut child = cmd.spawn().unwrap();
    // The parent's copies of the slave close with `cmd`. Held open - as they
    // are while a `Command` binding lives - the master never reaches EOF and
    // the read below blocks forever. The old temporary `Command::new(..)
    // .spawn()` dropped them at the end of its own statement.
    drop(cmd);
    // Non-blocking for the rest of this function, and drained as the child
    // runs rather than once at the end. Two reasons, both measured on macOS:
    // a pty master whose slave has closed reports EIO on Linux and can simply
    // block on BSD, and a full screen is bigger than the pty buffer, so a
    // child nobody is reading from stops mid-draw and never reaches its exit.
    unsafe {
        let fd = std::os::fd::AsRawFd::as_raw_fd(&master);
        let fl = libc::fcntl(fd, libc::F_GETFL);
        assert_ne!(fl, -1, "F_GETFL on the pty master");
        assert_ne!(
            libc::fcntl(fd, libc::F_SETFL, fl | libc::O_NONBLOCK),
            -1,
            "F_SETFL O_NONBLOCK on the pty master"
        );
    }
    let mut seen: Vec<u8> = Vec::new();
    let drain = |m: &mut std::fs::File, out: &mut Vec<u8>| {
        let mut buf = [0u8; 4096];
        loop {
            match m.read(&mut buf) {
                Ok(0) => break,
                Ok(n) => out.extend_from_slice(&buf[..n]),
                // WouldBlock is "nothing right now"; anything else is the
                // slave being gone, which is not an error here either.
                Err(_) => break,
            }
        }
    };
    let mut input = master.try_clone().unwrap();
    let keys = keys.to_vec();
    let writer = std::thread::spawn(move || {
        std::thread::sleep(std::time::Duration::from_millis(300));
        input.write_all(&keys).unwrap();
    });

    // Generous, because the macOS runner is far slower than this box and a
    // deadline that merely expires tells you nothing about why.
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
    let status = loop {
        drain(&mut master, &mut seen);
        if let Some(status) = child.try_wait().unwrap() {
            break status;
        }
        if std::time::Instant::now() >= deadline {
            let _ = child.kill();
            let _ = child.wait();
            drain(&mut master, &mut seen);
            // Say what the terminal actually received. "Did not exit" alone
            // cannot distinguish a screen that never drew from one that drew
            // and ignored the keys, and a CI-only failure gives no other way
            // to look.
            let text = String::from_utf8_lossy(&seen);
            panic!(
                "full-screen ui did not exit after the supplied keys; \
                 the pty received {} bytes:\n{}",
                text.len(),
                text.chars().take(2000).collect::<String>()
            );
        }
        std::thread::sleep(std::time::Duration::from_millis(20));
    };
    writer.join().unwrap();
    drain(&mut master, &mut seen);
    (
        String::from_utf8_lossy(&seen).into_owned(),
        status.code().unwrap_or(-1),
    )
}

/// The full-screen dashboard must list slots for every supported tool.
///
/// Its hand-written join covered Claude and Codex only. A Gemini slot appeared
/// in `ls` and the plain picker but the terminal dashboard showed the empty
/// welcome screen, so the command disagreed with itself based on terminal type.
#[cfg(unix)]
#[test]
fn the_fullscreen_menu_lists_a_gemini_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "kong", "kong@example.com");

    let (out, code) = run_fullscreen_ui(root, b"q");
    assert_eq!(code, 0, "full-screen menu failed:\n{out}");
    assert!(
        out.contains("kong"),
        "the Gemini account listed by ls is missing from the full-screen menu:\n{out}"
    );
}

/// The number the menu printed beside `name`, so a test can pick that row
/// without assuming what order the menu sorts in.
fn menu_number(out: &str, name: &str) -> String {
    out.lines()
        .find(|l| l.contains(name))
        .and_then(|l| l.trim().split(')').next().map(str::to_string))
        .unwrap_or_else(|| panic!("no menu row for {name}:\n{out}"))
}

/// The menu offers the accounts that exist, not the saved snapshots.
///
/// A slot-only install is what the slot model produces, and `ls` lists it and
/// `use` switches it. The menu asked the snapshot store alone, so it told an
/// owner with a working account to start over - and `setup`, the command it
/// sends them to, is not where you go when you already have one.
#[test]
fn the_menu_lists_a_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");

    let (ls_out, _, _) = run(root, &["ls"]);
    assert!(
        ls_out.contains("personal"),
        "fixture check - `ls` should list the slot:\n{ls_out}"
    );

    let (out, err, code) = run_ui(root, "\n");
    assert_eq!(code, 0, "menu should open:\n{out}{err}");
    assert!(
        !out.contains("No accounts saved yet"),
        "an install with a registered slot was told it has nothing:\n{out}{err}"
    );
    assert!(
        out.contains("personal"),
        "the account `ls` lists is missing from the menu:\n{out}{err}"
    );
    // A row you cannot check is a row you cannot trust: the slot's own config
    // is the only thing that names it, and `ls` already reads it for this.
    assert!(
        out.contains("personal@example.com"),
        "the slot row named nobody, so a switch to it is unverifiable:\n{out}{err}"
    );
}

/// A snapshot account must not crowd a slot account off the menu.
///
/// With one of each, the menu numbered only the snapshot - so the slot account
/// had no number, and a menu row is the only way to pick one here. `ls` shows
/// both, and the pick itself already goes through the same switch `use` does.
#[test]
fn the_menu_numbers_every_account_ls_shows() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    run(root, &["add", "alpha"]);
    seed_slot(root, "beta", "b@example.com");

    let (out, err, code) = run_ui(root, "\n");
    assert_eq!(code, 0, "menu should open:\n{out}{err}");
    assert!(
        out.contains("alpha"),
        "the snapshot account is missing from the menu:\n{out}{err}"
    );
    assert!(
        out.contains("beta"),
        "the slot account is missing from the menu:\n{out}{err}"
    );

    // Listed is not enough: the number beside the row has to switch to it.
    let n = menu_number(&out, "beta");
    let (out2, err2, code2) = run_ui(root, &format!("{n}\n"));
    assert_eq!(code2, 0, "picking the slot row failed:\n{out2}{err2}");
    let (ls_out, _, _) = run(root, &["ls"]);
    assert!(
        ls_out
            .lines()
            .any(|l| l.contains("beta") && l.contains("<- pays")),
        "the menu pick did not switch to the slot account:\n{ls_out}\n{out2}{err2}"
    );
}

/// A slot-only row must keep its tool after the switch.
///
/// The picker found the row through the merged account list, then the
/// post-switch prompt looked the same name up in the snapshot store alone.
/// That made a working slot lose its "new Claude" action immediately after
/// the picker had switched to it.
#[test]
fn the_menu_offers_the_tool_held_by_a_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");

    let (out, err, code) = run_ui(root, "1\n\n");
    assert_eq!(code, 0, "menu switch failed:\n{out}{err}");
    assert!(
        out.contains("c new claude"),
        "the slot's tool disappeared from the post-switch menu:\n{out}{err}"
    );
}

/// `add` must not mint a name that means two different accounts.
///
/// `ls` warns on every listing when one name holds a profile and a slot of a
/// DIFFERENT account, because the row shows one and `use` selects the other.
/// `add` is what creates that state, and its own guards against a name meaning
/// two accounts - exit 6 for an occupied profile, exit 7 for a repoint - only
/// ever asked the store.
#[test]
fn add_refuses_a_name_a_different_account_already_holds() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_claude(root, "work-uuid", "work@example.com");

    let (out, err, code) = run(root, &["add", "personal", "--tool", "claude-code"]);
    assert_ne!(
        code, 0,
        "add saved over a name a different account's slot already holds:\n{out}{err}"
    );

    // Ask a different command whether the state it left is sound.
    let (ls_out, ls_err, _) = run(root, &["ls"]);
    assert!(
        !ls_err.contains("DIFFERENT"),
        "add created the very state `ls` warns about:\n{ls_out}{ls_err}"
    );
}

/// One name on ONE account is the ordinary case, not a collision.
///
/// `swapdex run <name>` registers a slot, and snapshotting that same login
/// under that same name is what `add` is for. A guard that refused every name a
/// slot holds would break it.
#[test]
fn add_still_snapshots_a_slot_holding_the_same_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_claude(root, "personal", "personal@example.com");

    let (out, err, code) = run(root, &["add", "personal", "--tool", "claude-code"]);
    assert_eq!(
        code, 0,
        "add refused to snapshot the account its own slot holds:\n{out}{err}"
    );
}

/// A slot swapdex cannot read holds no account to collide with.
///
/// `swapdex run <name>` registers the slot before anyone logs into it, so the
/// directory is there and empty. Refusing on the bare registry entry would
/// block the first save on every freshly-made slot.
#[test]
fn add_accepts_a_name_whose_slot_holds_nothing_readable() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    let dir = root.join(".local/share/swapdex/slots/personal");
    std::fs::remove_file(dir.join(".credentials.json")).unwrap();
    std::fs::remove_file(dir.join(".claude.json")).unwrap();
    seed_claude(root, "work-uuid", "work@example.com");

    let (out, err, code) = run(root, &["add", "personal", "--tool", "claude-code"]);
    assert_eq!(
        code, 0,
        "add refused over a slot holding no readable account:\n{out}{err}"
    );
}

/// `login` must not save a different account over a name held by a slot.
///
/// `add` and `setup` already protect this seam. The interactive login flow
/// repeated the repoint guard against snapshots only, so completing a real
/// sign-in could leave `ls` showing one account while `use` selected another.
#[test]
fn login_rescues_a_new_account_from_a_slot_name_collision() {
    use std::io::Write;
    use std::os::unix::fs::PermissionsExt;

    let t = fixture();
    let root = t.path();
    seed_slot(root, "personal", "personal@example.com");
    seed_claude(root, "old-uuid", "old@example.com");
    let (_, err, code) = run(root, &["add", "old", "--tool", "claude-code"]);
    assert_eq!(code, 0, "could not save the outgoing account: {err}");

    let dir = root.join("fakebin-login-collision");
    std::fs::create_dir_all(&dir).unwrap();
    let fake = dir.join("claude");
    std::fs::write(
        &fake,
        r#"#!/bin/sh
mkdir -p "$SWAPDEX_ROOT/.claude"
printf '%s' '{"claudeAiOauth":{"accessToken":"AT-NEW","refreshToken":"RT-NEW","expiresAt":9999999999999,"subscriptionType":"max"}}' > "$SWAPDEX_ROOT/.claude/.credentials.json"
printf '%s' '{"oauthAccount":{"accountUuid":"new-uuid","emailAddress":"new@example.com"}}' > "$SWAPDEX_ROOT/.claude.json"
"#,
    )
    .unwrap();
    std::fs::set_permissions(&fake, std::fs::Permissions::from_mode(0o755)).unwrap();
    let path = format!(
        "{}:{}",
        dir.display(),
        std::env::var("PATH").unwrap_or_default()
    );

    let mut child = Command::new(bin())
        .args(["login", "personal", "--tool", "claude-code"])
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .env("PATH", path)
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .unwrap()
        .write_all(b"y\nrescued\n")
        .unwrap();
    let output = child.wait_with_output().unwrap();
    let out = String::from_utf8_lossy(&output.stdout);
    let err = String::from_utf8_lossy(&output.stderr);
    assert_eq!(
        output.status.code().unwrap_or(-1),
        0,
        "login failed:\n{out}{err}"
    );
    assert!(
        out.contains("saved profile 'rescued'"),
        "the new login was not rescued under a free name:\n{out}{err}"
    );

    let (listing, listing_err, _) = run(root, &["ls"]);
    assert!(
        !listing_err.contains("DIFFERENT"),
        "login minted the crossed name that ls warns about:\n{listing}{listing_err}"
    );
    assert!(
        listing.contains("personal") && listing.contains("rescued"),
        "both accounts should remain reachable under distinct names:\n{listing}{listing_err}"
    );
}

/// Drive the interactive wizard over a pipe. `SWAPDEX_ASSUME_TTY` is the escape
/// hatch `setup` already carries for exactly this.
fn run_stdin(root: &Path, args: &[&str], input: &str) -> (String, String, i32) {
    use std::io::Write;
    let mut child = Command::new(bin())
        .args(args)
        .env("SWAPDEX_ROOT", root)
        .env("SWAPDEX_ASSUME_TTY", "1")
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::piped())
        .stderr(std::process::Stdio::piped())
        .spawn()
        .unwrap();
    child
        .stdin
        .take()
        .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),
    )
}

/// Attaching a tool to a profile must still respect a same-named slot.
///
/// Setup normally sends names through the slot collision guard, but its
/// automatic multi-tool attach branch returned early. A Codex profile and a
/// different Claude slot named `work` therefore made setup file the current
/// Claude login under the slot's name without asking for a safe alternative.
#[test]
fn setup_does_not_auto_attach_over_a_different_slots_name() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "personal@example.com");
    seed_live_codex(root, "codex@example.com");
    let (_, err, code) = run(root, &["add", "work", "--tool", "codex"]);
    assert_eq!(code, 0, "could not seed the Codex profile: {err}");
    seed_claude(root, "work-uuid", "work@example.com");

    let (out, err, code) = run_stdin(root, &["setup"], "safe\n\n");
    assert_eq!(code, 0, "setup failed:\n{out}{err}");
    assert!(
        out.contains("saved as 'safe'"),
        "setup did not ask for a name clear of the existing slot:\n{out}{err}"
    );

    let (listing, listing_err, _) = run(root, &["ls"]);
    assert!(
        !listing_err.contains("DIFFERENT"),
        "setup auto-attached over a different slot account:\n{listing}{listing_err}"
    );
}

/// Setup's summary must acknowledge accounts already held in slots.
///
/// A slot-only account is ready for `use`, `ls`, and `rm`. Summarising the
/// snapshot store alone called that same machine empty at the end of setup.
#[test]
fn setup_recognises_an_existing_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");

    let (out, err, code) = run_stdin(root, &["setup"], "n\n");
    assert_eq!(code, 0, "setup failed:\n{out}{err}");
    assert!(
        !out.contains("No accounts saved yet"),
        "setup called the slot account nonexistent:\n{out}{err}"
    );
    assert!(
        out.contains("You're set - saved: work."),
        "setup did not acknowledge the account every other command sees:\n{out}{err}"
    );
}

/// Onboarding must not call a saved snapshot "no accounts".
///
/// Declining migration leaves the old account usable through `use`, `ls`, and
/// `rm`. The final summary counted permanent slots alone and contradicted all
/// three commands about whether that account still existed.
#[test]
fn onboard_recognises_a_snapshot_account_that_was_not_migrated() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "work-uuid", "work@example.com");
    let (_, err, code) = run(root, &["add", "work", "--tool", "claude-code"]);
    assert_eq!(code, 0, "could not seed the saved account: {err}");

    let (out, err, code) = run(root, &["onboard"]);
    assert_eq!(code, 0, "onboard failed:\n{out}{err}");
    assert!(
        !out.contains("No accounts yet"),
        "onboard called the snapshot account nonexistent:\n{out}{err}"
    );
    assert!(
        out.contains("swapdex ui` shows your accounts"),
        "onboard did not acknowledge the account every other command sees:\n{out}{err}"
    );
}

/// `setup` must not mint the name `ls` warns about either.
///
/// `add` learned to refuse a name a slot holds for a different account, but the
/// wizard names accounts through `ask_name`, which asks the snapshot store
/// alone. It is the worse door: the name it collides on is the one it SUGGESTS
/// as the default, so pressing Enter is enough.
#[test]
fn setup_refuses_a_name_a_different_account_already_holds() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "personal@example.com");
    seed_claude(root, "work-uuid", "work@example.com");

    // Enter accepts the suggested [work]; 'skip' leaves the tool unsaved.
    let (out, err, code) = run_stdin(root, &["setup"], "\nskip\n");
    assert_eq!(code, 0, "setup failed:\n{out}{err}");

    let (ls_out, ls_err, _) = run(root, &["ls"]);
    assert!(
        !ls_err.contains("DIFFERENT"),
        "setup minted the crossed name ls warns about:\n{out}\n--- ls ---\n{ls_out}{ls_err}"
    );
}

/// One name on ONE account is still the ordinary case.
///
/// A slot registered by `swapdex run <name>` and the login you are sitting on
/// are usually the same account. Saving a snapshot of it under that name is
/// what the wizard is for; a guard that refused every name a slot holds would
/// break the common path.
#[test]
fn setup_still_saves_under_a_slot_holding_the_same_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    seed_claude(root, "work", "work@example.com");

    let (out, err, code) = run_stdin(root, &["setup"], "\n");
    assert_eq!(code, 0, "setup failed:\n{out}{err}");
    assert!(
        out.contains("saved as 'work'"),
        "setup refused a slot holding the SAME account:\n{out}{err}"
    );
}

/// A slot swapdex cannot read holds no account to collide with.
///
/// `swapdex run <name>` registers the slot before anyone logs into it. Treating
/// an unreadable slot as a different account would refuse the wizard's own
/// suggestion on every freshly-made slot, with no name it would accept.
#[test]
fn setup_accepts_a_name_whose_slot_holds_nothing_readable() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let dir = root.join(".local/share/swapdex/slots/work");
    std::fs::remove_file(dir.join(".credentials.json")).unwrap();
    std::fs::remove_file(dir.join(".claude.json")).unwrap();
    seed_claude(root, "work-uuid", "work@example.com");

    let (out, err, code) = run_stdin(root, &["setup"], "\n");
    assert_eq!(code, 0, "setup failed:\n{out}{err}");
    assert!(
        out.contains("saved as 'work'"),
        "setup refused over a slot holding no readable account:\n{out}{err}"
    );
}

/// Ask the MCP server for its account list the way an agent would.
fn mcp_list_accounts(root: &Path) -> Vec<serde_json::Value> {
    let input = concat!(
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#,
        "\n",
        r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"list_accounts"}}"#,
        "\n",
    );
    let (out, err, code) = run_stdin(root, &["mcp"], input);
    assert_eq!(code, 0, "mcp exited {code}:\n{out}{err}");
    let reply = out
        .lines()
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .find(|v| v["id"] == 2)
        .unwrap_or_else(|| panic!("no reply to list_accounts:\n{out}{err}"));
    let text = reply["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_else(|| panic!("list_accounts returned no text: {reply}"));
    serde_json::from_str(text).unwrap_or_else(|e| panic!("not a JSON array: {text}: {e}"))
}

/// The MCP list must name the accounts a switch can name.
///
/// An account can live as a registered slot alone - `swapdex run <name>` makes
/// exactly that - and `ls`, `use` and `rm` all merge both registries. The tool
/// read the snapshot store alone, so an agent asking swapdex what accounts
/// exist was told none on a machine whose accounts are slots.
#[test]
fn mcp_lists_a_slot_only_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");

    let rows = mcp_list_accounts(root);
    assert!(
        rows.iter().any(|r| r["name"] == "work"),
        "list_accounts hid a slot-only account: {rows:?}"
    );
}

/// An account held as both a snapshot and a slot is still one account.
///
/// The two registries overlap, so a listing that merges them by concatenation
/// names the same account twice and an agent counts two logins where there is
/// one.
#[test]
fn mcp_lists_an_account_held_both_ways_once() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "work-uuid", "work@example.com");
    let (o, e, c) = run(root, &["add", "work"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    seed_slot(root, "work", "work@example.com");

    let rows = mcp_list_accounts(root);
    let held: Vec<_> = rows.iter().filter(|r| r["name"] == "work").collect();
    assert_eq!(held.len(), 1, "'work' listed twice: {rows:?}");
}

/// Widening the source must not cost the field that says which one is live.
#[test]
fn mcp_still_reports_active_tools_for_a_live_account() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "home-uuid", "me@example.com");
    let (o, e, c) = run(root, &["add", "home"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");

    let rows = mcp_list_accounts(root);
    let row = rows
        .iter()
        .find(|r| r["name"] == "home")
        .unwrap_or_else(|| panic!("'home' missing: {rows:?}"));
    assert_eq!(
        row["active_tools"],
        serde_json::json!(["claude-code"]),
        "active_tools lost: {row}"
    );
}

/// A codex slot with its account and refresh token spelled out.
///
/// `seed_codex_slot` fixes both, which is what most tests want. A rotation is
/// only visible when two holders of ONE account differ in the refresh token, so
/// these tests have to set the pair themselves.
fn seed_codex_slot_as(root: &Path, name: &str, email: &str, account_id: &str, refresh: &str) {
    let dir = root.join(".local/share/swapdex/slots").join(name);
    std::fs::create_dir_all(dir.join("sessions")).unwrap();
    std::fs::write(
        dir.join("auth.json"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode": "chatgpt",
            "last_refresh": "2026-09-03T02:56:06Z",
            "tokens": {"id_token": codex_id_token(email), "access_token": "AT",
                       "refresh_token": refresh, "account_id": account_id}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&dir.join("auth.json"));

    let reg = root.join(".local/share/swapdex/slots.json");
    let mut rows: Vec<serde_json::Value> = std::fs::read(&reg)
        .ok()
        .and_then(|b| serde_json::from_slice(&b).ok())
        .unwrap_or_default();
    rows.push(serde_json::json!({
        "name": name, "id": name, "config_dir": dir.to_string_lossy(),
        "adopted": false, "tool": "codex"}));
    std::fs::write(&reg, serde_json::to_vec_pretty(&rows).unwrap()).unwrap();
}

fn ls_with_path(root: &Path, path: &str) -> String {
    let out = Command::new(bin())
        .arg("ls")
        .env("SWAPDEX_ROOT", root)
        .env("HOME", root)
        .env("PATH", path)
        .env_remove("CODEX_HOME")
        .output()
        .unwrap();
    format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    )
}

/// The login left in `~/.codex` is what a launch that bypasses the shim uses.
/// With the shim first on PATH, a plain `codex` follows the pointer instead -
/// yet `ls` still said it "would launch on" the leftover account and told the
/// user to run `swapdex shim`, which was already in place.
#[test]
fn a_shimmed_codex_is_not_said_to_launch_on_the_leftover_login() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot_as(root, "one", "one@example.com", "acct-one", "rt-one");
    seed_codex_snapshot(root, "two", "two@example.com", "acct-two", "rt-two");
    std::fs::create_dir_all(root.join(".codex")).unwrap();
    std::fs::copy(
        root.join(".local/share/swapdex/accounts/two/codex/auth"),
        root.join(".codex/auth.json"),
    )
    .unwrap();
    std::fs::write(
        root.join(".local/share/swapdex/active-codex"),
        root.join(".local/share/swapdex/slots/one")
            .to_string_lossy()
            .as_bytes(),
    )
    .unwrap();
    let (said, code) = run_with_native_codex(root, &["shim"]);
    assert_eq!(code, 0, "{said}");
    let native = root.join("native-bin");
    let shims = root.join(".local/share/swapdex/bin");

    let bare = ls_with_path(root, &format!("{}:/usr/bin:/bin", native.display()));
    assert!(
        bare.contains("would launch on 'two'"),
        "without the shim on PATH the leftover login is what launches:\n{bare}"
    );
    let shimmed = ls_with_path(
        root,
        &format!("{}:{}:/usr/bin:/bin", shims.display(), native.display()),
    );
    assert!(
        !shimmed.contains("would launch on"),
        "the shim is first on PATH, so a plain launch follows the pointer:\n{shimmed}"
    );
}

fn doctor_with_path(root: &Path, path: &str) -> String {
    let out = Command::new(bin())
        .arg("doctor")
        .env("SWAPDEX_ROOT", root)
        .env("HOME", root)
        .env("PATH", path)
        .output()
        .unwrap();
    format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    )
}

/// doctor checked that the Claude shim is what PATH reaches and never asked
/// the same of Codex, so a `codex` earlier on PATH than the shim - an nvm bin
/// dir, say - left every switch unread with no row to say so, and no row
/// reads as a passing one.
#[test]
fn doctor_says_whether_the_codex_shim_is_what_path_reaches() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    let (said, code) = run_with_native_codex(root, &["shim"]);
    assert_eq!(code, 0, "{said}");
    let native = root.join("native-bin");
    let shims = root.join(".local/share/swapdex/bin");

    let row = |path: String| -> String {
        let text = doctor_with_path(root, &path);
        text.lines()
            .find(|l| l.starts_with("shim:codex"))
            .unwrap_or_else(|| panic!("doctor has no shim:codex row:\n{text}"))
            .to_string()
    };
    let shadowed = row(format!(
        "{}:{}:/usr/bin:/bin",
        native.display(),
        shims.display()
    ));
    assert!(shadowed.contains("problem"), "{shadowed}");
    assert!(
        shadowed.contains(&native.join("codex").display().to_string()),
        "the row does not say what runs instead: {shadowed}"
    );
    let first = row(format!(
        "{}:{}:/usr/bin:/bin",
        shims.display(),
        native.display()
    ));
    assert!(first.contains(" ok "), "{first}");
}

/// The stale note told the user to run `add --update`. Without a name that
/// fails off a terminal, and without `--tool` it re-saves EVERY tool from
/// whatever is live - so following it to refresh one old codex copy could
/// overwrite the account's Claude copy with another account's login. The note
/// has to be a command that does only the thing it describes.
#[test]
fn the_stale_note_names_a_command_that_resaves_that_tool() {
    let t = fixture();
    let root = t.path();
    seed_codex_snapshot(root, "old", "old@example.com", "acct-old", "rt-old");
    let auth = root.join(".local/share/swapdex/accounts/old/codex/auth");
    let text = std::fs::read_to_string(&auth).unwrap();
    std::fs::write(
        &auth,
        text.replace("2026-09-03T02:56:06Z", "2026-01-01T00:00:00Z"),
    )
    .unwrap();
    let (out, err, _) = run(root, &["ls"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("stale"),
        "the fixture copy is not stale:\n{said}"
    );
    assert!(
        said.contains("swapdex add old --tool codex --update"),
        "the note does not say how to re-save this codex copy:\n{said}"
    );
}

/// `--tool all` is documented as "every tool", and commands that act on one
/// tool quietly took it to mean Claude: `serve x --tool all` switched only
/// Claude and said nothing, so the user believed every tool had moved. A
/// command that acts on one tool has to refuse it and say which to name.
#[test]
fn a_one_tool_command_refuses_tool_all_instead_of_meaning_claude() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    for args in [
        &["serve", "cx", "--tool", "all"][..],
        &["share-history", "--tool", "all", "--dry-run"],
        &["share-history", "--tool", "gemini", "--dry-run"],
    ] {
        let (out, err, code) = run(root, args);
        let said = format!("{out}{err}");
        assert_ne!(code, 0, "{args:?} was accepted:\n{said}");
        assert!(
            said.contains("--tool claude") && said.contains("--tool codex"),
            "{args:?} does not say which tool to name:\n{said}"
        );
    }
    // Leaving `--tool` out still means Claude, as it always has.
    let (out, err, code) = run(root, &["share-history", "--dry-run"]);
    assert_eq!(code, 0, "{out}{err}");
}

fn default_store_row(root: &Path) -> Option<String> {
    let out = Command::new(bin())
        .arg("doctor")
        .env("SWAPDEX_ROOT", root)
        .env("HOME", root)
        .env("PATH", "/usr/bin:/bin")
        .output()
        .unwrap();
    String::from_utf8_lossy(&out.stdout)
        .lines()
        .find(|l| l.starts_with("default store"))
        .map(str::to_string)
}

/// doctor warned that conversations in `~/.claude` are out of reach of a plain
/// `claude -r` while another account is active - also on a machine where every
/// account's `projects` is a link into `~/.claude/projects` (what
/// `share-history` sets up), where those conversations are exactly what
/// `-r` lists. It then told the user to adopt `~/.claude`, which they did not
/// need.
#[test]
fn doctor_does_not_call_shared_history_unreachable() {
    let t = fixture();
    let root = t.path();
    std::fs::create_dir_all(root.join(".claude/projects/-work-repo")).unwrap();
    seed_slot(root, "work", "work@example.com");
    // No default yet: a plain `claude` runs in ~/.claude itself.
    let unset = default_store_row(root);
    assert!(unset.is_none(), "nothing redirects `claude` yet: {unset:?}");
    let (_, err, code) = run(root, &["use", "work"]);
    assert_eq!(code, 0, "{err}");

    let apart = default_store_row(root);
    assert!(
        apart.as_deref().is_some_and(|r| r.contains("problem")),
        "a store that shares nothing really is out of reach: {apart:?}"
    );

    let projects = root.join(".local/share/swapdex/slots/work/projects");
    let _ = std::fs::remove_dir_all(&projects);
    std::os::unix::fs::symlink(root.join(".claude/projects"), &projects).unwrap();
    let shared = default_store_row(root);
    assert!(
        shared.is_none(),
        "the account reads ~/.claude/projects itself, so nothing is out of reach: {shared:?}"
    );
}

/// "not saved - run `swapdex add <name>`" sat on one tool's row, but `add`
/// with no `--tool` saves EVERY tool's live login under that name - so saving
/// the codex login this way also filed whatever Claude account was signed in
/// under the same name. Both screens that print it must name the tool.
#[test]
fn the_not_saved_note_names_the_tool_to_save() {
    let t = fixture();
    let root = t.path();
    seed_live_codex(root, "loose@example.com");
    for cmd in ["status", "doctor"] {
        let (out, err, _) = run(root, &[cmd]);
        let said = format!("{out}{err}");
        let row = said
            .lines()
            .find(|l| l.starts_with("codex") && l.contains("not saved"))
            .unwrap_or_else(|| panic!("{cmd} has no unsaved codex row:\n{said}"));
        assert!(
            row.contains("swapdex add <name> --tool codex"),
            "{cmd} would save every tool: {row}"
        );
    }
}

/// Switching away from a login nobody saved says how to keep it. It said
/// "`swapdex restore` undoes this switch; `swapdex add <name>` would keep it" -
/// but after the switch `add` saves the login just switched TO, and with no
/// `--tool` both commands act on every tool. The note has to be the sequence
/// that keeps the outgoing login, for this tool only.
#[test]
fn the_outgoing_login_note_keeps_the_login_it_names() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-a", "a@example.com");
    let (o, e, c) = run(root, &["add", "a", "--tool", "claude"]);
    assert_eq!(c, 0, "{o}{e}");
    // A different account signs in and is never saved.
    seed_claude(root, "uuid-b", "b@example.com");
    let (out, err, code) = run(root, &["use", "a", "--tool", "claude"]);
    let said = format!("{out}{err}");
    assert_eq!(code, 0, "{said}");
    let note = said
        .lines()
        .find(|l| l.contains("is not saved as a profile"))
        .unwrap_or_else(|| panic!("no note about the unsaved login:\n{said}"));
    let restore = note.find("swapdex restore --tool claude");
    let keep = note.find("swapdex add <name> --tool claude");
    assert!(
        restore.is_some() && keep.is_some() && restore < keep,
        "the note must bring the login back, then save it, for Claude only: {note}"
    );
    // And following it does keep the outgoing login, under the new name.
    let (o, e, c) = run(root, &["restore", "--tool", "claude"]);
    assert_eq!(c, 0, "{o}{e}");
    let (o, e, c) = run(root, &["add", "kept", "--tool", "claude"]);
    assert_eq!(c, 0, "{o}{e}");
    let (listing, _, _) = run(root, &["ls"]);
    assert!(
        listing
            .lines()
            .any(|l| l.contains("kept") && l.contains("b@example.com")),
        "following the note did not keep the outgoing login:\n{listing}"
    );
}

/// With a Claude payer and a Codex payer at once, `ls` marked only the Claude
/// one: "one mark can only carry one name". But every row carries its own
/// mark, so the Codex payer went unmarked on exactly the machines that use
/// both - `serve x --tool codex` then looked like it had not taken.
#[test]
fn ls_marks_the_payer_of_each_tool() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "cl", "cl@example.com");
    seed_slot(root, "idle", "idle@example.com");
    seed_codex_slot(root, "cx", "cx@example.com");
    for args in [&["serve", "cl"][..], &["serve", "cx", "--tool", "codex"]] {
        let (o, e, c) = run(root, args);
        assert_eq!(c, 0, "{args:?}: {o}{e}");
    }
    let (listing, _, _) = run(root, &["ls"]);
    let row = |name: &str| -> String {
        listing
            .lines()
            .find(|l| l.trim_start_matches(['*', ' ']).starts_with(name))
            .unwrap_or_else(|| panic!("no row for {name}:\n{listing}"))
            .to_string()
    };
    let cl = row("cl");
    // A Claude-only payer keeps the words it always had.
    assert!(cl.trim_end().ends_with("<- pays"), "{cl}");
    let idle = row("idle");
    assert!(
        !idle.contains("pays"),
        "an account paying for nothing was marked: {idle}"
    );
    let cx = row("cx");
    assert!(
        cx.contains("<- pays (codex)"),
        "the codex payer is not marked:\n{listing}"
    );
}

/// `service status` ended with "logs: ~/.local/share/swapdex/logs". A launchd
/// agent writes there, but a systemd unit sets no output file, so on Linux a
/// supervised proxy logs to the journal and that folder only ever held what
/// launch-started proxies wrote - days stale on a machine running services.
#[cfg(target_os = "linux")]
#[test]
fn service_status_points_a_systemd_machine_at_the_journal() {
    let t = fixture();
    let root = t.path();
    let logs_line = |root: &Path| -> String {
        let (out, err, code) = run(root, &["service", "status"]);
        assert_eq!(code, 0, "{out}{err}");
        out.lines()
            .find(|l| l.trim_start().starts_with("logs:"))
            .unwrap_or_else(|| panic!("no logs line:\n{out}"))
            .to_string()
    };
    let none = logs_line(root);
    assert!(
        !none.contains("journalctl"),
        "no service is installed: {none}"
    );

    let units = root.join(".config/systemd/user");
    std::fs::create_dir_all(&units).unwrap();
    std::fs::write(
        units.join("swapdex-codex.service"),
        "[Service]\nExecStart=/bin/true proxy --tool codex\n",
    )
    .unwrap();
    let installed = logs_line(root);
    assert!(
        installed.contains("journalctl --user -u 'swapdex-*'"),
        "a systemd service logs to the journal: {installed}"
    );
}

/// `swapdex serve` with no name answers "who pays?", and answered for Claude
/// only - the default tool of a command that switches one - so the codex payer,
/// whose turns had just moved, went unnamed. Asked with no `--tool`, it now
/// names each tool's payer. And the "nobody is directing turns" answer carried
/// a line break followed by the source's own indentation.
#[test]
fn serve_with_no_name_names_every_tools_payer() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "cl", "cl@example.com");
    seed_codex_slot(root, "cx", "cx@example.com");
    let (o, e, c) = run(root, &["serve", "cl"]);
    assert_eq!(c, 0, "{o}{e}");

    let (before, _, _) = run(root, &["serve"]);
    assert!(before.contains("'cl' (claude)"), "{before}");
    assert!(
        before.contains("no account is directing turns (codex)"),
        "the codex side is not answered:\n{before}"
    );
    assert!(
        !before.lines().any(|l| l.starts_with("          ")),
        "a line carries the source's indentation:\n{before}"
    );

    let (o, e, c) = run(root, &["serve", "cx", "--tool", "codex"]);
    assert_eq!(c, 0, "{o}{e}");
    let (after, _, _) = run(root, &["serve"]);
    assert!(
        after.contains("'cl' (claude)") && after.contains("'cx' (codex)"),
        "both payers must be named:\n{after}"
    );
    // Asked about one tool, it still answers for that tool alone.
    let (one, _, _) = run(root, &["serve", "--tool", "codex"]);
    assert!(
        one.contains("'cx' (codex)") && !one.contains("'cl'"),
        "{one}"
    );
}

/// A window started before the usage route pays through the proxy while its
/// status line reads its OWN account, which does not move - so its numbers sat
/// still until the window was restarted and then dropped at once. doctor said
/// only "windows started before it keep their own account", which named no
/// window. It now names each one by pid.
#[cfg(target_os = "linux")]
#[test]
fn doctor_names_a_codex_window_started_without_the_usage_route() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    mark_codex_proxy(root, Some(18788));
    // A stand-in window: /bin/sh under the name `codex`, kept alive by its
    // script while its arguments carry what a real launch would.
    let bin = root.join("fake-bin");
    std::fs::create_dir_all(&bin).unwrap();
    let fake = bin.join("codex");
    // A link, not a copy: exec takes the link's basename as the process name,
    // and nothing ever holds a writable descriptor to it - a just-copied file
    // can fail with ETXTBSY while sibling tests fork.
    std::os::unix::fs::symlink("/bin/sh", &fake).unwrap();
    let spawn = |extra: &[&str]| {
        let mut args = vec![
            "-c",
            "sleep 30",
            "codex",
            "-c",
            "openai_base_url=http://127.0.0.1:8788/v1",
        ];
        args.extend_from_slice(extra);
        Command::new(&fake)
            .args(&args)
            .env("SWAPDEX_ROOT", root)
            .spawn()
            .unwrap()
    };
    let mut stale = spawn(&[]);
    let mut current = spawn(&[
        "-c",
        "chatgpt_base_url=https://127.0.0.1:18788/backend-api/",
    ]);
    std::thread::sleep(std::time::Duration::from_millis(300));

    let row = doctor_usage_row(root, &[]);
    let _ = stale.kill();
    let _ = current.kill();
    let _ = stale.wait();
    let _ = current.wait();
    assert!(row.contains("problem"), "{row}");
    assert!(
        row.contains(&stale.id().to_string()),
        "the window reading its own account is not named: {row}"
    );
    assert!(
        !row.contains(&current.id().to_string()),
        "a window that reads the payer was named: {row}"
    );
}

/// With shared history every account's `projects` is ONE directory, and
/// `whereis` listed each conversation once per account that links to it - four
/// times on a machine with three accounts and the default store - under a
/// header saying the account column is "whose store holds it". One file is one
/// conversation: list it once and name everyone who shares it.
#[test]
fn whereis_lists_a_shared_conversation_once() {
    let t = fixture();
    let root = t.path();
    let shared = root.join(".claude/projects/-work-repo");
    std::fs::create_dir_all(&shared).unwrap();
    std::fs::write(
        shared.join("11111111-2222-3333-4444-555555555555.jsonl"),
        "{}\n",
    )
    .unwrap();
    for name in ["one", "two"] {
        seed_slot(root, name, &format!("{name}@example.com"));
        let projects = root
            .join(".local/share/swapdex/slots")
            .join(name)
            .join("projects");
        let _ = std::fs::remove_dir_all(&projects);
        std::os::unix::fs::symlink(root.join(".claude/projects"), &projects).unwrap();
    }
    let (out, err, code) = run(root, &["whereis"]);
    assert_eq!(code, 0, "{out}{err}");
    let resumes = out
        .lines()
        .filter(|l| l.contains("11111111-2222-3333-4444-555555555555"))
        .count();
    assert_eq!(resumes, 1, "one file, listed once:\n{out}");
    let row = out
        .lines()
        .find(|l| l.contains("-work-repo"))
        .unwrap_or_else(|| panic!("no row:\n{out}"));
    assert!(
        row.contains("one") && row.contains("two"),
        "the row does not name the accounts sharing it: {row}"
    );

    // The same for Codex, whose accounts share one `sessions` directory.
    let day = root.join(".codex/sessions/2026/09/30");
    std::fs::create_dir_all(&day).unwrap();
    std::fs::write(
        day.join("rollout-2026-09-30T00-00-00-aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee.jsonl"),
        "{\"type\":\"session_meta\",\"payload\":{\"cwd\":\"/work/cx-repo\"}}\n",
    )
    .unwrap();
    for name in ["cx1", "cx2"] {
        seed_codex_slot(root, name, &format!("{name}@example.com"));
        let sessions = root
            .join(".local/share/swapdex/slots")
            .join(name)
            .join("sessions");
        let _ = std::fs::remove_dir_all(&sessions);
        std::os::unix::fs::symlink(root.join(".codex/sessions"), &sessions).unwrap();
    }
    let (out, err, code) = run(root, &["whereis"]);
    assert_eq!(code, 0, "{out}{err}");
    let resumes = out
        .lines()
        .filter(|l| l.contains("aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))
        .count();
    assert_eq!(resumes, 1, "one rollout, listed once:\n{out}");
}

/// An idle Claude account's access token now lapses between keep-alive
/// renewals, which happen by the refresh token's end. That is not an expired
/// account - the next use renews it - so `ls` must not call it one. A refresh
/// token the login server refused is, and must say so.
#[test]
fn an_idle_claude_account_is_not_called_expired_until_its_refresh_is_refused() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "idle", "idle@example.com");
    let slot = root.join(".local/share/swapdex/slots/idle");
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    let blob = serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
        "accessToken":"AT","refreshToken":"RT-IDLE","expiresAt": now_ms - 3_600_000,
        "refreshTokenExpiresAt": now_ms + 20 * 86_400_000i64, "subscriptionType":"max"}}))
    .unwrap();
    std::fs::write(slot.join(".credentials.json"), &blob).unwrap();
    chmod600(&slot.join(".credentials.json"));

    let row = |listing: &str| -> String {
        listing
            .lines()
            .find(|l| l.trim_start_matches(['*', ' ']).starts_with("idle"))
            .unwrap_or_else(|| panic!("no idle row:\n{listing}"))
            .to_string()
    };
    let (listing, _, _) = run(root, &["ls"]);
    let idle = row(&listing);
    assert!(
        !idle.contains("expired"),
        "an idle account with a live refresh token was called expired: {idle}"
    );

    let fingerprint = swapdex::refresh_health::claude_refresh_fingerprint(&blob).unwrap();
    swapdex::refresh_health::record_claude_rejection(&slot, &fingerprint, now_ms).unwrap();
    let (listing, _, _) = run(root, &["ls"]);
    let refused = row(&listing);
    assert!(
        refused.contains("refresh rejected - re-login required"),
        "a refused refresh token is not reported: {refused}"
    );
    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.lines()
            .any(|l| l.starts_with("slot:idle") && l.contains("refused")),
        "doctor passes a refused Claude login:\n{said}"
    );
}

/// Claude Code empties both tokens when its own renewal is refused, but leaves
/// the refresh token's stated end in place. That end is no evidence the login
/// lives: `ls` listed such an account with no note at all.
#[test]
fn a_claude_login_with_its_tokens_emptied_is_not_listed_as_fine() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "blank", "blank@example.com");
    let slot = root.join(".local/share/swapdex/slots/blank");
    let now_ms = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_millis() as i64;
    std::fs::write(
        slot.join(".credentials.json"),
        serde_json::to_vec(&serde_json::json!({"claudeAiOauth":{
            "accessToken":"","refreshToken":"","expiresAt": 0,
            "refreshTokenExpiresAt": now_ms + 17 * 86_400_000i64, "subscriptionType":"team"}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&slot.join(".credentials.json"));

    let (listing, _, _) = run(root, &["ls"]);
    let row = listing
        .lines()
        .find(|l| l.trim_start_matches(['*', ' ']).starts_with("blank"))
        .unwrap_or_else(|| panic!("no blank row:\n{listing}"));
    assert!(
        row.contains("expired"),
        "a login with no tokens is listed as if it were fine: {row}"
    );
}

/// A saved copy-model codex snapshot in the store.
fn seed_codex_snapshot(root: &Path, name: &str, email: &str, account_id: &str, refresh: &str) {
    let d = root
        .join(".local/share/swapdex/accounts")
        .join(name)
        .join("codex");
    std::fs::create_dir_all(&d).unwrap();
    std::fs::write(
        d.join("auth"),
        serde_json::to_vec(&serde_json::json!({
            "auth_mode": "chatgpt",
            "last_refresh": "2026-09-03T02:56:06Z",
            "tokens": {"id_token": codex_id_token(email), "access_token": "AT",
                       "refresh_token": refresh, "account_id": account_id}}))
        .unwrap(),
    )
    .unwrap();
    chmod600(&d.join("auth"));
}

/// A snapshot whose refresh token was rotated away is dead, not merely old.
///
/// These refresh tokens are single-use: redeeming one retires the copy every
/// other holder is carrying. So when a live slot and a saved snapshot name the
/// SAME account but differ in the refresh token, the snapshot's token is one
/// the server has already retired, and restoring it hands the tool a login that
/// cannot renew itself. The wall-clock staleness check cannot see this - it
/// measures how long ago the snapshot was written, and a rotation can retire a
/// token minutes after it is saved.
///
/// A real machine sat in exactly this state for six days with nothing said: the
/// slot held a live pair, the snapshot and the tool's own dir held the retired
/// one, and the failure surfaced only when the access token lapsed and the
/// renewal it then attempted was refused.
#[test]
fn use_refuses_a_codex_snapshot_whose_refresh_token_was_rotated_away() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot_as(root, "live", "shared@example.com", "acct-shared", "RT-NEW");
    seed_codex_snapshot(root, "stale", "shared@example.com", "acct-shared", "RT-OLD");

    let (out, err, code) = run(root, &["use", "stale", "--tool", "codex"]);
    let said = format!("{out}{err}");
    assert_ne!(
        code, 0,
        "a retired snapshot was restored as a success:\n{said}"
    );
    assert!(
        said.contains("rotated") || said.contains("retired") || said.contains("revoked"),
        "nothing said the refresh token was retired by another holder:\n{said}"
    );
}

/// The rotation check must not fire on the copy that IS current.
///
/// Two holders of one account are normal - a slot and the snapshot it was
/// captured from agree until something rotates. A check that refused those too
/// would refuse every healthy switch and get taken back out.
#[test]
fn a_codex_snapshot_holding_the_live_refresh_token_still_switches() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot_as(root, "live", "shared@example.com", "acct-shared", "RT-SAME");
    seed_codex_snapshot(root, "twin", "shared@example.com", "acct-shared", "RT-SAME");

    let (out, err, code) = run(root, &["use", "twin", "--tool", "codex"]);
    assert_eq!(
        code, 0,
        "a snapshot holding the live token was refused:\n{out}{err}"
    );
}

/// `ls` must mark the account swapdex is actually pointing the tool at.
///
/// The per-tool mark was read from the tool's OWN config dir, which the slot
/// model does not write: switching repoints a pointer and leaves the tool's dir
/// alone. On a machine whose dir was left behind by an earlier copy-model
/// switch, `ls` therefore marked the abandoned account active while every
/// switch, the proxy and the serving pointer all named a different one.
#[test]
fn the_codex_active_marker_follows_the_slot_pointer() {
    let t = fixture();
    let root = t.path();
    // An orphan login in the tool's own dir, saved as a profile so the mark has
    // a name to land on.
    seed_live_codex(root, "orphan@example.com");
    let (o, e, c) = run(root, &["add", "orphan"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    seed_codex_slot(root, "cx-one", "one@example.com");
    let (_, err, code) = run(root, &["use", "cx-one", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, _, _) = run(root, &["ls"]);
    let row = |n: &str| {
        out.lines()
            .find(|l| l.contains(n))
            .unwrap_or("")
            .to_string()
    };
    assert!(
        row("cx-one").contains("codex*"),
        "the pointer names cx-one but ls does not mark it:\n{out}"
    );
    assert!(
        !row("orphan").contains("codex*"),
        "ls marks an orphaned tool dir as the active codex account:\n{out}"
    );
}

/// A tool dir that disagrees with the pointer is news, not something to hide.
///
/// Reading the mark off the pointer alone would make the orphan invisible - and
/// an unshimmed launch still lands on whatever the tool's own dir holds. The
/// disagreement is the thing a reader needs, since it is the state in which the
/// account swapdex reports and the account that actually pays are different.
#[test]
fn a_tool_dir_that_disagrees_with_the_pointer_is_reported() {
    let t = fixture();
    let root = t.path();
    seed_live_codex(root, "orphan@example.com");
    let (o, e, c) = run(root, &["add", "orphan"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    seed_codex_slot(root, "cx-one", "one@example.com");
    let (_, err, code) = run(root, &["use", "cx-one", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err, _) = run_unshimmed(root, &["ls"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("orphan"),
        "the abandoned login in the tool's own dir is never mentioned:\n{said}"
    );
    assert!(
        said.contains("not the account") || said.contains("would launch") || said.contains("stale"),
        "nothing explains that an unshimmed launch lands somewhere else:\n{said}"
    );
}

/// The disagreement note must stay silent when the two agree.
///
/// It fires on a comparison, and a note that also fired when the pointer and
/// the tool's own dir named the SAME account would tell every healthy machine
/// that a plain launch goes somewhere else. That reads as a warning about
/// nothing, and a warning about nothing is what gets a real one ignored.
#[test]
fn a_tool_dir_that_agrees_with_the_pointer_is_not_reported() {
    let t = fixture();
    let root = t.path();
    seed_live_codex(root, "same@example.com");
    let (o, e, c) = run(root, &["add", "same"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    // The slot carries the profile's own name, so the pointer and the tool's
    // dir resolve to one account.
    seed_codex_slot(root, "same", "same@example.com");
    let (_, err, code) = run(root, &["use", "same", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err, _) = run_unshimmed(root, &["ls"]);
    let said = format!("{out}{err}");
    assert!(
        !said.contains("would launch"),
        "the note fired although the pointer and the tool's dir agree:\n{said}"
    );
}

/// Every reader of the listing must name the same active account.
///
/// On a machine whose accounts live only as slots, the human listing starred a
/// row and marked it `<- pays` while `ls --json` reported every row with an
/// empty `active_tools`, and the MCP account list said the same nothing. The
/// per-tool mark was read from the tool's own config dir, which such a machine
/// does not have - so the two listings disagreed about whether any account was
/// active at all, and anything reading the JSON could not name the one paying.
#[test]
fn every_listing_names_the_same_active_tool() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (human, _, _) = run(root, &["ls"]);
    assert!(
        human.contains("claude-code*"),
        "the human listing marks no active tool:\n{human}"
    );

    let (json, _, _) = run(root, &["ls", "--json"]);
    let rows: serde_json::Value = serde_json::from_str(&json)
        .unwrap_or_else(|e| panic!("ls --json is not json ({e}): {json}"));
    let row = rows
        .as_array()
        .and_then(|a| a.iter().find(|r| r["name"] == "work"))
        .unwrap_or_else(|| panic!("no row for work: {json}"));
    assert_eq!(
        row["active_tools"],
        serde_json::json!(["claude-code"]),
        "`ls --json` does not name the tool the human listing marks: {row}"
    );

    let mcp = mcp_list_accounts(root);
    let mrow = mcp
        .iter()
        .find(|r| r["name"] == "work")
        .unwrap_or_else(|| panic!("no mcp row for work: {mcp:?}"));
    assert_eq!(
        mrow["active_tools"],
        serde_json::json!(["claude-code"]),
        "the MCP account list does not name it either: {mrow}"
    );
}

/// `status` and `ls` must name the same active account.
///
/// `status` is documented as "the active account per tool" - the question `ls`
/// answers with its star. It read the tool's own config dir, which the slot
/// model never writes, so on a machine whose accounts live only as slots it
/// said "not logged in" while `ls` starred an account and `serve` was serving
/// it. Both ship as statusline commands, so the contradiction went straight
/// into people's prompts.
#[test]
fn status_names_the_account_ls_marks_active() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (human, _, _) = run(root, &["ls"]);
    assert!(
        human.contains("claude-code*"),
        "ls marks no active account:\n{human}"
    );

    let (st, _, _) = run(root, &["status"]);
    assert!(
        !st.contains("claude-code: not logged in"),
        "status says not logged in while ls marks an account active:\n{st}"
    );
    assert!(
        st.contains("work"),
        "status does not name the active account:\n{st}"
    );
}

/// The compact line is the one that lands in a shell prompt.
#[test]
fn status_short_names_the_slot_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (short, _, _) = run(root, &["status", "--short"]);
    assert!(
        short.contains("claude:work"),
        "the compact line does not name the active account: {short:?}"
    );
}

/// Anything parsing `status --json` needs the same answer the screen gives.
#[test]
fn status_json_reports_the_slot_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (json, _, _) = run(root, &["status", "--json"]);
    let rows: serde_json::Value = serde_json::from_str(&json)
        .unwrap_or_else(|e| panic!("status --json is not json ({e}): {json}"));
    let row = rows
        .as_array()
        .and_then(|a| a.iter().find(|r| r["tool"] == "claude-code"))
        .unwrap_or_else(|| panic!("no claude-code row: {json}"));
    assert_eq!(
        row["logged_in"],
        serde_json::json!(true),
        "status --json calls an active slot account logged out: {row}"
    );
    assert_eq!(
        row["profile"],
        serde_json::json!("work"),
        "status --json does not name the active profile: {row}"
    );
}

/// A machine with no slots must still report what its tool dir holds.
///
/// The pointer is the better answer only where there is one. Reading it in
/// preference must not cost the copy-model machine its own answer, nor the
/// honest "not logged in" on a machine that really has no login.
#[test]
fn status_still_reports_a_live_login_when_no_slot_points_anywhere() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-live", "live@example.com");
    let (o, e, c) = run(root, &["add", "live"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");

    let (st, _, _) = run(root, &["status"]);
    assert!(
        st.contains("live@example.com"),
        "status lost the live login on a machine with no slots:\n{st}"
    );
    let (short, _, _) = run(root, &["status", "--short"]);
    assert!(
        short.contains("claude:live"),
        "the compact line lost it too: {short:?}"
    );
}

/// Following the pointer must not hide what the tool's own dir holds.
///
/// The two answer different questions and both are true: the pointer says who
/// swapdex serves, the tool's dir says who an unshimmed launch would use. A
/// `status` that printed only the first would be exactly as misleading as the
/// one that printed only the second - it would just be wrong in the other
/// direction, and the abandoned login that cost a scheduled job 42 hours would
/// stay off the screen that claims to say who is active.
#[test]
fn status_names_the_abandoned_login_too() {
    let t = fixture();
    let root = t.path();
    seed_live_codex(root, "orphan@example.com");
    let (o, e, c) = run(root, &["add", "orphan"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    seed_codex_slot(root, "cx-one", "one@example.com");
    let (_, err, code) = run(root, &["use", "cx-one", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (st, _, _) = run_unshimmed(root, &["status"]);
    assert!(
        st.contains("cx-one"),
        "status does not name the account the pointer serves:\n{st}"
    );
    assert!(
        st.contains("orphan"),
        "status hides the login the tool's own dir still holds:\n{st}"
    );
}

/// One `tools/call` against the MCP server, with its text payload parsed.
fn mcp_call(root: &Path, tool: &str) -> serde_json::Value {
    let input = format!(
        "{}\n{{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/call\",\"params\":{{\"name\":\"{tool}\"}}}}\n",
        r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18"}}"#
    );
    let (out, err, code) = run_stdin(root, &["mcp"], &input);
    assert_eq!(code, 0, "mcp exited {code}:\n{out}{err}");
    let reply = out
        .lines()
        .filter_map(|l| serde_json::from_str::<serde_json::Value>(l).ok())
        .find(|v| v["id"] == 2)
        .unwrap_or_else(|| panic!("no reply to {tool}:\n{out}{err}"));
    let text = reply["result"]["content"][0]["text"]
        .as_str()
        .unwrap_or_else(|| panic!("{tool} returned no text: {reply}"));
    serde_json::from_str(text).unwrap_or_else(|e| panic!("{tool} text is not JSON: {text}: {e}"))
}

fn mcp_whoami(root: &Path) -> Vec<serde_json::Value> {
    mcp_call(root, "whoami")
        .as_array()
        .cloned()
        .unwrap_or_else(|| panic!("whoami did not return an array"))
}

/// One MCP server must not give two answers to "is anyone signed in".
///
/// `list_accounts` reports `active_tools` from the pointer, while `whoami` read
/// the tool's own config dir - which a slot switch never writes. So an agent
/// that asked swapdex what accounts it had, and then asked who was signed in,
/// got a list of accounts and a flat denial that any of them was: the two calls
/// are answered by the same process, from the same store, one line apart.
#[test]
fn mcp_whoami_agrees_with_mcp_list_accounts() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let rows = mcp_list_accounts(root);
    let listed = rows
        .iter()
        .find(|r| r["name"] == "work")
        .unwrap_or_else(|| panic!("no row for work: {rows:?}"));
    assert_eq!(
        listed["active_tools"],
        serde_json::json!(["claude-code"]),
        "list_accounts does not call it active: {listed}"
    );

    let who = mcp_whoami(root);
    let claude = who
        .iter()
        .find(|r| r["tool"] == "claude-code")
        .unwrap_or_else(|| panic!("whoami has no claude-code row: {who:?}"));
    assert_ne!(
        claude["display"],
        serde_json::json!("not logged in"),
        "whoami denies the account list_accounts calls active: {claude}"
    );
    assert!(
        claude.to_string().contains("work"),
        "whoami does not name the active account: {claude}"
    );
}

/// Preferring the pointer must not cost a copy-model machine its answer.
///
/// `whoami` is the call an agent makes to find out whose login it is talking
/// to. Reading the pointer first is right where there is one; a machine with no
/// slots still has a live login, and answering "not logged in" there would be
/// the same defect pointing the other way.
#[test]
fn mcp_whoami_still_reports_a_live_login_when_no_slot_points_anywhere() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-live", "live@example.com");
    let (o, e, c) = run(root, &["add", "live"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");

    let who = mcp_whoami(root);
    let claude = who
        .iter()
        .find(|r| r["tool"] == "claude-code")
        .unwrap_or_else(|| panic!("whoami has no claude-code row: {who:?}"));
    assert_ne!(
        claude["display"],
        serde_json::json!("not logged in"),
        "whoami lost the live login on a machine with no slots: {claude}"
    );
    assert_eq!(
        claude["email"],
        serde_json::json!("live@example.com"),
        "whoami does not name the live login: {claude}"
    );
}

/// `doctor` must not deny the account its own next line names.
///
/// A Codex login refreshed days ago is current, and doctor must say nothing.
///
/// This is the units guard. Claude records a deadline in MILLISECONDS and Codex
/// records `last_refresh` as RFC 3339 seconds, so the reader scales one and not
/// the other. Get that wrong and every healthy Codex slot reports roughly fifty
/// years idle - which an ancient-timestamp test cannot catch, because seconds
/// and milliseconds both clear the threshold there. Only a fresh login
/// separates them.
#[test]
fn doctor_does_not_call_a_freshly_refreshed_codex_login_idle() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    let cred = root.join(".local/share/swapdex/slots/cx/auth.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&cred).unwrap()).unwrap();
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs();
    v["last_refresh"] = serde_json::json!(rfc3339_utc(now));
    std::fs::write(&cred, serde_json::to_vec(&v).unwrap()).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        !said.contains("idle"),
        "doctor calls a login refreshed just now idle:\n{said}"
    );
}

/// The other direction: a Codex login that has sat unrefreshed past the
/// threshold must be flagged, because by then the refresh token itself may have
/// been rotated away and the account is dead without saying so.
#[test]
fn doctor_flags_a_codex_login_that_has_sat_unrefreshed() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    let cred = root.join(".local/share/swapdex/slots/cx/auth.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&cred).unwrap()).unwrap();
    let long_ago = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        - 200 * 86_400;
    v["last_refresh"] = serde_json::json!(rfc3339_utc(long_ago));
    std::fs::write(&cred, serde_json::to_vec(&v).unwrap()).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("slot:cx") && said.contains("idle"),
        "doctor says nothing about a Codex login unrefreshed for 200 days:\n{said}"
    );
}

/// The over-correction of the test below: a credential that is THERE but will
/// not parse is not a missing login.
///
/// Claude's reader documents this - unreadable is "treated as healthy rather
/// than guessed at" - because the remedy differs. "No login yet, run once to
/// sign in" sent at an account that is signed in tells the user to redo work
/// they already did, and buries the real problem (a damaged file) under it.
#[test]
fn doctor_does_not_call_an_unparseable_codex_credential_a_missing_login() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    let cred = root.join(".local/share/swapdex/slots/cx/auth.json");
    assert!(cred.exists(), "the fixture wrote no credential");
    std::fs::write(&cred, b"{ this is not json").unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        !said.contains("no login yet"),
        "doctor calls a present-but-damaged credential a missing login:\n{said}"
    );
}

/// Register a slot for `tool` whose directory holds no credential at all.
fn seed_empty_codex_slot(root: &Path, name: &str) {
    seed_codex_slot(root, name, "unused@example.com");
    let dir = root.join(".local/share/swapdex/slots").join(name);
    std::fs::remove_file(dir.join("auth.json")).unwrap();
}

/// `status` must read the identity in a Gemini slot, not call it unreadable.
///
/// `any_slot_email` promises to read whichever tool wrote the slot, but stopped
/// after adding Codex. Gemini records the active address in
/// `google_accounts.json`, so hiding it makes a healthy active login look
/// damaged on the screen whose job is to say who is active.
#[test]
fn status_reads_a_gemini_slots_recorded_email() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "gwork", "g@example.com");
    let (_, err, code) = run(root, &["use", "gwork", "--tool", "gemini"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err, code) = run(root, &["status"]);
    assert_eq!(code, 0, "status failed: {err}");
    assert!(
        out.contains("gemini: g@example.com (profile 'gwork')"),
        "status calls a named Gemini login unreadable:\n{out}{err}"
    );
}

/// An address in Gemini's `old` list is not the slot's current identity.
///
/// Extending the cross-tool reader one field too far would put a previous login
/// beside the active slot and turn missing information into wrong information.
#[test]
fn mcp_whoami_does_not_call_an_old_gemini_account_active() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "gwork", "current@example.com");
    let accounts = root.join(".local/share/swapdex/slots/gwork/google_accounts.json");
    std::fs::write(accounts, br#"{"old":["old@example.com"]}"#).unwrap();
    let (_, err, code) = run(root, &["use", "gwork", "--tool", "gemini"]);
    assert_eq!(code, 0, "use failed: {err}");

    let who = mcp_whoami(root);
    let gemini = who
        .iter()
        .find(|r| r["tool"] == "gemini")
        .unwrap_or_else(|| panic!("whoami has no Gemini row: {who:?}"));
    assert_eq!(
        gemini["email"],
        serde_json::Value::Null,
        "whoami called an old Gemini login active: {gemini}"
    );
}

/// An old, present login is refreshed by running its own tool, not signed in
/// from scratch; the remedy must preserve both that verb and Codex's flag.
#[test]
fn doctor_names_codex_in_the_remedy_for_an_idle_codex_login() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cx", "cx@example.com");
    let cred = root.join(".local/share/swapdex/slots/cx/auth.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&cred).unwrap()).unwrap();
    let old = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap()
        .as_secs()
        - 200 * 86_400;
    v["last_refresh"] = serde_json::json!(rfc3339_utc(old));
    std::fs::write(&cred, serde_json::to_vec(&v).unwrap()).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("`swapdex run cx --tool codex` once refreshes it"),
        "doctor gives the wrong action for an idle Codex login:\n{said}"
    );
}

/// Claude remains `run`'s default even on the idle-login branch.
#[test]
fn doctor_leaves_claudes_default_out_of_an_idle_login_remedy() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "cl", "cl@example.com");
    let cred = root.join(".local/share/swapdex/slots/cl/.credentials.json");
    let mut v: serde_json::Value = serde_json::from_slice(&std::fs::read(&cred).unwrap()).unwrap();
    v["claudeAiOauth"]["expiresAt"] = serde_json::json!(1_600_000_000_000i64);
    std::fs::write(&cred, serde_json::to_vec(&v).unwrap()).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("`swapdex run cl` once refreshes it"),
        "doctor no longer names the default Claude refresh:\n{said}"
    );
    assert!(
        !said.contains("`swapdex run cl --tool"),
        "doctor redundantly spells Claude's default on the idle branch:\n{said}"
    );
}

/// `ls` marks who pays. An account with no login cannot.
///
/// `serve` refuses to put one there and says why: "it cannot pay for turns -
/// your own account would, while every screen named '<name>'". `payer_line`
/// exists so the reason travels with the name, and Codex's /status line uses
/// it. `ls` marked the row `<- pays` with no login check at all, so a glance
/// (and a script) read an account as footing the bill while the proxy was
/// quietly forwarding the reader's own credential.
#[test]
fn ls_does_not_say_an_account_with_no_login_pays() {
    let t = fixture();
    let root = t.path();
    seed_empty_codex_slot(root, "cxwork");
    let (_, err, code) = run(root, &["use", "cxwork", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["ls"]);
    let said = format!("{out}{err2}");
    assert!(
        said.contains("cxwork"),
        "ls no longer lists the account, so this measures nothing:\n{said}"
    );
    assert!(
        said.contains("pays"),
        "ls no longer marks a payer, so this measures nothing:\n{said}"
    );
    assert!(
        said.contains("no login"),
        "ls says an account with no login pays, without saying it cannot:\n{said}"
    );
}

/// The over-correction: a payer that IS signed in must not be slandered.
#[test]
fn ls_does_not_claim_a_signed_in_payer_has_no_login() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cxwork", "cx@example.com");
    let (_, err, code) = run(root, &["use", "cxwork", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["ls"]);
    let said = format!("{out}{err2}");
    assert!(said.contains("pays"), "ls no longer marks a payer:\n{said}");
    assert!(
        !said.contains("no login"),
        "ls calls a signed-in payer loginless:\n{said}"
    );
}

/// `short_line` goes in a shell prompt, and its own contract says "None when
/// nothing is logged in".
///
/// It took the pointer without asking whether that slot holds a credential, so
/// a prompt read `codex:cxwork` on a machine where nothing is signed in at all
/// and `serve` refuses that account for having no login. The comment right
/// above the branch states the rule it broke: a prompt naming the account
/// swapdex is not serving is worse than no line at all.
#[test]
fn the_short_line_does_not_name_an_account_with_no_login() {
    let t = fixture();
    let root = t.path();
    seed_empty_codex_slot(root, "cxwork");
    let (_, err, code) = run(root, &["use", "cxwork", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["status", "--short"]);
    let said = format!("{out}{err2}");
    assert!(
        !said.contains("cxwork"),
        "the prompt line names an account with no login:\n{said}"
    );
    assert!(
        said.contains("not signed in"),
        "nothing is signed in on this machine; the line should say so:\n{said}"
    );
}

/// The over-correction: a slot that IS signed in still belongs in the prompt.
#[test]
fn the_short_line_names_a_slot_that_is_signed_in() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["status", "--short"]);
    let said = format!("{out}{err2}");
    assert!(
        said.contains("claude:work"),
        "the prompt line dropped a slot that is signed in:\n{said}"
    );
}

/// The other direction: a slot that IS signed in shows its identity.
///
/// Without this, wording the not-signed-in case could swallow the signed-in one
/// and every existing check would stay green - `doctor_agrees_with_the_default_
/// it_reports` only asks that the row contain the account name, which the
/// remedy text "`swapdex run work` signs it in" also does.
#[test]
fn status_shows_the_identity_of_a_slot_that_is_signed_in() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["status"]);
    let said = format!("{out}{err2}");
    assert!(
        said.contains("work@example.com"),
        "status hides the email of a slot that is signed in:\n{said}"
    );
    assert!(
        !said.contains("not signed in"),
        "status calls a signed-in slot unsigned:\n{said}"
    );
}

/// The pointer naming an account is not the account being signed in.
///
/// `slot_active_identity` answers "who does the pointer name, and what identity
/// does that slot carry". Three screens read it as "who is logged in", and none
/// of them asked whether the slot holds a credential - so a registered Codex
/// slot with an EMPTY directory was reported as logged in. `serve` gets this
/// right about the same account ("has no codex login"), and `proxy::has_login`
/// is the helper that knows.
#[test]
fn status_does_not_call_an_empty_slot_signed_in() {
    let t = fixture();
    let root = t.path();
    seed_empty_codex_slot(root, "cxwork");
    let (_, err, code) = run(root, &["use", "cxwork", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    // The surface that already answers correctly. Without it this measures
    // nothing: it is the disagreement that makes the others wrong.
    let (so, se, _) = run(root, &["serve", "cxwork", "--tool", "codex"]);
    assert!(
        format!("{so}{se}").contains("no codex login"),
        "serve no longer reports the missing login, so there is nothing to disagree with"
    );

    let (out, err2, _) = run(root, &["status"]);
    let said = format!("{out}{err2}");
    assert!(
        !said.contains("login unreadable in the slot"),
        "status calls an empty slot's login unreadable rather than absent:\n{said}"
    );

    let (jout, jerr, _) = run(root, &["status", "--json"]);
    let rows: serde_json::Value =
        serde_json::from_str(&jout).unwrap_or_else(|e| panic!("status --json: {e}\n{jout}{jerr}"));
    let codex = rows
        .as_array()
        .and_then(|a| a.iter().find(|r| r["tool"] == "codex"))
        .unwrap_or_else(|| panic!("no codex row:\n{jout}"));
    assert_eq!(
        codex["logged_in"], false,
        "status --json reports an empty slot as logged in:\n{codex}"
    );
}

/// doctor said both things at once about the same account:
///
///   codex         ok - login unreadable in the slot (profile 'cxwork')
///   slot:cxwork   ok - no login yet - ...
///
/// which is the contradiction the comment above doctor's own pointer branch was
/// written about, in the other direction.
#[test]
fn doctor_does_not_contradict_itself_about_an_empty_slot() {
    let t = fixture();
    let root = t.path();
    seed_empty_codex_slot(root, "cxwork");
    let (_, err, code) = run(root, &["use", "cxwork", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, err2, _) = run(root, &["doctor"]);
    let said = format!("{out}{err2}");
    assert!(
        said.contains("slot:cxwork"),
        "the per-slot row is gone, so this measures nothing:\n{said}"
    );
    // The agreement itself, not one wording of the disagreement: the tool row
    // must say the same thing the slot row does. Asserting only the absence of
    // the old phrase let a mutant through that swapped it for "signed in,
    // email unreadable" - still the contradiction this test is named for.
    let codex_row = said
        .lines()
        .find(|l| l.starts_with("codex"))
        .unwrap_or_else(|| panic!("doctor has no codex row:\n{said}"));
    assert!(
        codex_row.contains("not signed in"),
        "doctor's codex row claims a login one row above reporting none:\n{said}"
    );
}

/// The per-slot row names `run`, and `run` defaults to Claude.
///
/// That walk was Claude-only until it was generalised across tools; the message
/// came along unchanged, so a Codex slot was told `swapdex run <name>`.
#[test]
fn the_slot_login_row_names_the_tool() {
    let t = fixture();
    let root = t.path();
    seed_empty_codex_slot(root, "cxwork");

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("swapdex run cxwork"),
        "the row no longer names `run`, so this measures nothing:\n{said}"
    );
    assert!(
        !said.contains("swapdex run cxwork`"),
        "the Codex slot's remedy names a command that runs Claude:\n{said}"
    );
}

/// `import` tells the reader each imported account still needs a sign-in, and
/// named `swapdex run <name>` as a placeholder - with no tool in it.
///
/// The manifest carries a tool per account and `import` creates slots for all
/// of them, so for a Codex account the substituted command launches Claude and
/// leaves a second account of that name behind. The plan already knows the
/// tool; printing the real commands says it without the reader guessing.
#[test]
fn the_import_sign_in_line_names_each_accounts_tool() {
    let t = fixture();
    let root = t.path();
    let manifest = root.join("setup.json");
    std::fs::write(
        &manifest,
        br#"{"version":1,"accounts":[{"name":"cxwork","tool":"codex"},{"name":"clwork","tool":"claude-code"}]}"#,
    )
    .unwrap();

    let (out, err, code) = run(root, &["import", manifest.to_str().unwrap()]);
    assert_eq!(code, 0, "import failed:\n{out}{err}");
    let said = format!("{out}{err}");
    assert!(
        said.contains("still needs its own sign-in"),
        "import no longer mentions signing in, so this measures nothing:\n{said}"
    );
    assert!(
        said.contains("swapdex run cxwork --tool codex"),
        "the sign-in named for an imported Codex account runs Claude:\n{said}"
    );
    assert!(
        said.contains("swapdex run clwork"),
        "the Claude account was not named at all:\n{said}"
    );
    // Not `contains("swapdex run clwork ")`: a trailing space matches
    // "... clwork --tool claude-code" too, so that form passes while the flag
    // is being printed. Assert the flag's absence directly.
    assert!(
        !said.contains("swapdex run clwork --tool"),
        "Claude is run's default; spelling it out is noise:\n{said}"
    );
}

/// `pause` names two commands as still working. One of them did not.
///
/// `use` resolves the tool from the name by itself - `swapdex use cxwork`
/// answers "default codex account -> cxwork". `serve` does not: it defaults to
/// Claude and looks the name up in Claude's registry alone, so for a Codex-only
/// account the command `pause` had just recommended answers "no account named
/// 'cxwork'". Measured, both of them.
#[test]
fn the_pause_note_names_a_serve_that_works_for_this_account() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "cxwork", "cx@example.com");

    let (out, err, code) = run(root, &["pause", "cxwork"]);
    assert_eq!(code, 0, "pause failed: {err}");
    let said = format!("{out}{err}");
    assert!(
        said.contains("swapdex serve cxwork"),
        "the note no longer names `serve`, so this measures nothing:\n{said}"
    );
    assert!(
        said.contains("swapdex serve cxwork --tool codex"),
        "pause recommends a `serve` that cannot find this account:\n{said}"
    );
}

/// The over-correction: Claude is the default for both commands, so flagging it
/// would add noise to the common case and teach the flag where it is not
/// needed. `use` never needs one at all - it resolves the tool itself.
#[test]
fn the_pause_note_leaves_claudes_default_unspelled() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");

    let (out, err, code) = run(root, &["pause", "work"]);
    assert_eq!(code, 0, "pause failed: {err}");
    let said = format!("{out}{err}");
    assert!(
        said.contains("swapdex serve work"),
        "the note no longer names `serve`:\n{said}"
    );
    assert!(
        !said.contains("--tool"),
        "Claude is the default for both commands; spelling it out is noise:\n{said}"
    );
}

/// `run` defaults to Claude, so advice naming it must carry the tool.
///
/// `sign_in_remedy` exists because of exactly this: "a Codex account that could
/// not serve was told to run `swapdex run codex-test`, and `run` defaults to
/// Claude - so following the instruction launched Claude for a Codex profile."
/// The tip printed after a switch never got that fix, and it is on the common
/// path - every first switch of a tool whose shim is not installed yet.
/// Following it creates a second account of the same name under Claude.
#[test]
fn the_switch_tip_names_the_tool_it_just_switched() {
    let t = fixture();
    let root = t.path();
    seed_codex_slot(root, "work", "work@example.com");

    let (out, err, code) = run(root, &["use", "work", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");
    let said = format!("{out}{err}");
    assert!(
        said.contains("swapdex run work"),
        "the tip no longer names `run`, so this test measures nothing:\n{said}"
    );
    assert!(
        said.contains("swapdex run work --tool codex"),
        "the tip after a Codex switch names a command that runs Claude:\n{said}"
    );
}

/// Gemini and Antigravity have no shim and no `run`: `shim` installs only the
/// Claude and Codex ones, and `run` refuses them outright ("no per-account home
/// to launch into"). Offering both after a Gemini switch promised a shim that
/// is never installed and a command that cannot succeed - and the form it
/// printed, without a `--tool`, quietly built a Claude account of the same
/// name.
#[test]
fn switching_a_tool_with_no_shim_does_not_offer_one() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "gwork", "g@example.com");

    let (out, err, code) = run(root, &["use", "gwork", "--tool", "gemini"]);
    assert_eq!(code, 0, "use failed: {err}");
    let said = format!("{out}{err}");
    assert!(
        said.contains("gwork"),
        "the switch printed nothing, so this measures nothing:\n{said}"
    );
    assert!(
        !said.contains("swapdex shim"),
        "promises a gemini shim that `swapdex shim` never installs:\n{said}"
    );
    assert!(
        !said.contains("swapdex run gwork"),
        "names `run`, which refuses gemini and builds a Claude account instead:\n{said}"
    );
}

/// `serve` decides who PAYS for turns, and turns are paid through the proxy.
///
/// There is no Gemini or Antigravity relay: `proxy` and `service install` both
/// refuse those tools by name, with a sentence written for it. `serve` did not
/// ask, so it wrote a serving pointer for a relay that does not exist, reported
/// "now <name>", and told the reader to run `swapdex proxy` - which then
/// refuses to start. Three commands, two answers.
#[test]
fn serve_refuses_a_tool_the_proxy_cannot_carry() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "gwork", "g@example.com");

    // The sibling command refuses; without that this test measures nothing.
    let (pout, perr, _) = run(root, &["proxy", "--tool", "gemini"]);
    assert!(
        format!("{pout}{perr}").contains("no gemini relay"),
        "`proxy` no longer refuses gemini, so serve has nothing to disagree with"
    );

    let (out, err2, code2) = run(root, &["serve", "gwork", "--tool", "gemini"]);
    let said = format!("{out}{err2}");
    assert_ne!(
        code2, 0,
        "serve accepted a tool the proxy cannot carry:\n{said}"
    );
    assert!(
        !root.join(".local/share/swapdex/serving-gemini").exists(),
        "serve wrote a serving pointer for a relay that does not exist"
    );
}

/// The line printed after a switch must not send the reader at a command that
/// refuses to run. It offered `swapdex proxy` for every tool, so switching a
/// Gemini account pointed at a relay that does not exist - and without a
/// `--tool`, the command it named starts Claude's.
#[test]
fn switching_a_tool_without_a_relay_does_not_offer_the_proxy() {
    let t = fixture();
    let root = t.path();
    seed_gemini_slot(root, "gwork", "g@example.com");

    let (out, err2, code2) = run(root, &["use", "gwork", "--tool", "gemini"]);
    assert_eq!(code2, 0, "use failed: {err2}");
    let said = format!("{out}{err2}");
    assert!(
        said.contains("gwork"),
        "the switch printed nothing about the account, so this measures nothing:\n{said}"
    );
    assert!(
        !said.contains("swapdex proxy"),
        "switching a gemini account points at a proxy that refuses to start:\n{said}"
    );
}

/// Per-slot login health is checked for one tool out of four.
///
/// `snapshot_refreshed_at` exists because each reader used to work out a
/// tool's freshness for itself and they disagreed; snapshots got one helper
/// covering all four tools. The per-slot walk never did - it calls
/// `claude::slot_login`, so a Codex slot that has never been signed in gets no
/// `slot:` row at all. Slots are the shape `run` and `migrate` steer people
/// into, so this is the common machine, and an absent check reads as a passed
/// one.
#[test]
fn doctor_checks_a_codex_slot_login_the_way_it_checks_a_claude_one() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "cl", "cl@example.com");
    seed_codex_slot(root, "cx", "cx@example.com");
    // Neither account has signed in yet.
    std::fs::remove_file(root.join(".local/share/swapdex/slots/cl/.credentials.json")).unwrap();
    std::fs::remove_file(root.join(".local/share/swapdex/slots/cx/auth.json")).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("slot:cl"),
        "the Claude half of the comparison is gone, so this test measures nothing:\n{said}"
    );
    assert!(
        said.contains("slot:cx"),
        "doctor reports a Claude slot with no login and says nothing about a Codex one:\n{said}"
    );
}

/// The default pointer is the one pointer nothing validates.
///
/// `serving_dir()` refuses to answer with a directory the registry does not
/// hold - slots.rs tests that. `default_dir()` hands back whatever the file
/// says, so a pointer left naming a slot the registry no longer lists makes
/// `doctor` print `default ok - plain `claude` -> '(unknown)'`: the code has
/// already failed to resolve the name and still records the row as healthy,
/// while the shim exports that directory to CLAUDE_CONFIG_DIR unchecked. The
/// remedy doctor itself gives for a damaged registry - restore slots.json from
/// a backup - is one way to arrive here.
#[test]
fn doctor_reports_a_default_pointer_naming_no_account() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let ptr = root.join(".local/share/swapdex/active-claude");
    assert!(ptr.exists(), "use wrote no default pointer at {ptr:?}");
    let orphan = root.join(".local/share/swapdex/slots/not-in-the-registry");
    std::fs::write(&ptr, orphan.to_string_lossy().as_bytes()).unwrap();

    let (out, err2, code2) = run(root, &["doctor"]);
    let said = format!("{out}{err2}");
    assert!(
        !said.contains("(unknown)"),
        "doctor prints an unresolvable default as if it were an account name:\n{said}"
    );
    assert_ne!(
        code2, 0,
        "doctor exited 0 with a default naming no account:\n{said}"
    );
}

/// The per-tool row was read from the tool's own config dir, so on a machine
/// whose accounts live only as slots `doctor` printed `claude-code ok - not
/// logged in` and, four rows down, `default ok - plain claude -> 'work'`. Both
/// lines are in one screen whose whole job is to tell somebody whether their
/// setup is sound, and they said opposite things about the same machine.
#[test]
fn doctor_agrees_with_the_default_it_reports() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (_, err, code) = run(root, &["use", "work", "--tool", "claude"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, _, _) = run(root, &["doctor"]);
    assert!(
        out.contains("-> 'work'"),
        "doctor does not report the default it is being checked against:\n{out}"
    );
    let row = out
        .lines()
        .find(|l| l.starts_with("claude-code"))
        .unwrap_or_else(|| panic!("doctor has no claude-code row:\n{out}"));
    assert!(
        !row.contains("not logged in"),
        "doctor calls the tool logged out while naming its default account:\n{out}"
    );
    assert!(
        row.contains("work"),
        "doctor's claude-code row does not name the active account: {row:?}"
    );
}

/// Both branches of doctor's default row must name the tool they are about.
///
/// The positive branch says ``plain `claude` -> 'work'`` and the negative one
/// said "no default account set" with no tool in it, so on a machine with a
/// Codex default and no Claude one `doctor` denied having a default two rows
/// below reporting one. One `match`, one scoped arm and one unscoped: the
/// unscoped arm reads as a statement about the machine.
#[test]
fn doctor_scopes_the_missing_default_to_its_tool() {
    let t = fixture();
    let root = t.path();
    // A Claude slot with no default pointer, so the row is reached and takes
    // its negative arm.
    seed_slot(root, "work", "work@example.com");
    // ... while Codex demonstrably has one.
    seed_codex_slot(root, "cx-one", "one@example.com");
    let (_, err, code) = run(root, &["use", "cx-one", "--tool", "codex"]);
    assert_eq!(code, 0, "use failed: {err}");

    let (out, _, _) = run(root, &["doctor"]);
    let row = out
        .lines()
        .find(|l| l.starts_with("default "))
        .unwrap_or_else(|| panic!("doctor has no default row:\n{out}"));
    assert!(
        row.contains("no default"),
        "this machine should have no CLAUDE default: {row:?}"
    );
    assert!(
        row.contains("claude"),
        "the missing-default row does not say which tool it is about: {row:?}"
    );
}

/// The help must name the slash command the installer actually creates.
///
/// It promised `/sx` while `swapdex slash` wrote `~/.claude/commands/swap.md`,
/// which Claude Code exposes as `/swap` - the filename IS the command name. So
/// the one line telling somebody what to type named something that has never
/// existed, and the installer's own output, the closing hint and the Codex
/// skill all said `/swap`. Four places agreed and the help did not.
#[test]
fn the_help_names_the_slash_command_that_gets_installed() {
    let t = fixture();
    let root = t.path();
    let (out, err, code) = run(root, &["slash", "--help"]);
    assert_eq!(code, 0, "slash --help failed:\n{out}{err}");
    assert!(
        out.contains("/swap"),
        "the help does not name the command the installer writes:\n{out}"
    );
    assert!(
        !out.contains("/sx"),
        "the help still names a command nothing installs:\n{out}"
    );
}

/// Every command the binary has must appear in the reference that claims to
/// list them all.
///
/// The README sends people to `docs/COMMANDS.md` for the "full command,
/// exit-code, and environment reference". It listed twenty-five of forty -
/// missing `serve`, which the README itself features; `refresh` and `service`,
/// which are how an account is kept from expiring; `export`/`import`; and the
/// four commands that configure auto-continue. A reference is only a reference
/// while it is complete, and nothing was checking.
#[test]
fn the_command_reference_lists_every_command() {
    let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR"));
    let doc = std::fs::read_to_string(root.join("docs/COMMANDS.md")).expect("read COMMANDS.md");

    let t = fixture();
    let (help, err, code) = run(t.path(), &["--help"]);
    assert_eq!(code, 0, "--help failed:\n{help}{err}");

    let mut missing: Vec<String> = Vec::new();
    let mut in_commands = false;
    for line in help.lines() {
        if line.starts_with("Commands:") {
            in_commands = true;
            continue;
        }
        if !in_commands {
            continue;
        }
        if line.starts_with("Options:") {
            break;
        }
        let Some(name) = line
            .strip_prefix("  ")
            .and_then(|l| l.split_whitespace().next())
        else {
            continue;
        };
        // `help` is clap's own; it is not a swapdex command to document.
        if name == "help" || !name.chars().all(|c| c.is_ascii_lowercase() || c == '-') {
            continue;
        }
        if !doc.contains(&format!("`swapdex {name}")) {
            missing.push(name.to_string());
        }
    }
    assert!(
        missing.is_empty(),
        "docs/COMMANDS.md is the reference and does not list: {}",
        missing.join(", ")
    );
}

/// What `ls` lists, `export` must carry.
///
/// `export` walked the slot registries only. On a machine whose accounts are
/// saved profiles, which `ls`, `use` and `rm` all still serve, it wrote an
/// empty manifest and reported success, so the setup restored on the next
/// machine was nothing at all. Its own comment says the one thing an export
/// must never do is hand back a manifest that looks complete and is not; it
/// guarded the registry it could not READ and not the one it never ASKED.
#[test]
fn export_carries_the_accounts_the_listing_shows() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-w", "w@example.com");
    let (o, e, c) = run(root, &["add", "work"]);
    assert_eq!(c, 0, "add failed:\n{o}{e}");
    seed_slot(root, "slotted", "s@example.com");

    let (listed, _, _) = run(root, &["ls"]);
    for name in ["work", "slotted"] {
        assert!(listed.contains(name), "ls does not show {name}:\n{listed}");
    }

    let out = root.join("setup.json");
    let (o, e, c) = run(root, &["export", out.to_str().unwrap()]);
    assert_eq!(c, 0, "export failed:\n{o}{e}");
    let text = std::fs::read_to_string(&out).expect("read the export");
    let v: serde_json::Value = serde_json::from_str(&text).expect("export is json");
    let names: Vec<&str> = v["accounts"]
        .as_array()
        .map(|a| a.iter().filter_map(|x| x["name"].as_str()).collect())
        .unwrap_or_default();
    for name in ["work", "slotted"] {
        assert!(
            names.contains(&name),
            "the export drops an account the listing shows: {name} not in {names:?}"
        );
    }
}

/// Import must leave an account already present as a snapshot alone.
///
/// Export writes both registries, but import compared the manifest with slots
/// alone. Re-importing a snapshot account therefore created a second, empty
/// slot under the same name instead of preserving the local login it found.
#[test]
fn import_recognises_a_snapshot_account_already_here() {
    let t = fixture();
    let root = t.path();
    seed_claude(root, "uuid-w", "w@example.com");
    let (out, err, code) = run(root, &["add", "work", "--tool", "claude-code"]);
    assert_eq!(code, 0, "add failed:\n{out}{err}");

    let manifest = root.join("setup.json");
    std::fs::write(
        &manifest,
        br#"{"version":1,"accounts":[{"name":"work","tool":"claude-code"}]}"#,
    )
    .unwrap();
    let (out, err, code) = run(root, &["import", manifest.to_str().unwrap()]);
    assert_eq!(code, 0, "import failed:\n{out}{err}");
    assert!(
        out.contains("every account in that file is already here"),
        "import did not recognise the snapshot account:\n{out}{err}"
    );
    assert!(
        !out.contains("created work"),
        "import created an empty slot over an account already here:\n{out}{err}"
    );
}

/// The rotation check covers Claude, not only Codex.
///
/// It was written for Codex because Codex keeps the account and the refresh
/// token in one readable blob, and Claude splits them across two parts of the
/// same snapshot - a reason to write more code, not a reason to leave the tool
/// unguarded. Claude's refresh tokens rotate too; the module note that opens
/// refresh.rs is about exactly that.
#[test]
fn use_refuses_a_claude_snapshot_whose_refresh_token_was_rotated_away() {
    let t = fixture();
    let root = t.path();
    // A live slot holding the account with the token the last rotation minted.
    let slot = root.join(".local/share/swapdex/slots/live");
    std::fs::create_dir_all(&slot).unwrap();
    std::fs::write(
        slot.join(".credentials.json"),
        br#"{"claudeAiOauth":{"accessToken":"AT","refreshToken":"RT-NEW","expiresAt":9999999999999,"subscriptionType":"max"}}"#,
    )
    .unwrap();
    std::fs::write(
        slot.join(".claude.json"),
        br#"{"oauthAccount":{"accountUuid":"u-shared","emailAddress":"shared@example.com"}}"#,
    )
    .unwrap();
    std::fs::write(
        root.join(".local/share/swapdex/slots.json"),
        serde_json::to_vec(&serde_json::json!([{
            "name": "live", "id": "live", "config_dir": slot,
            "adopted": false, "tool": "claude-code"}]))
        .unwrap(),
    )
    .unwrap();
    // A saved profile for the SAME account carrying the retired token.
    let snap = root.join(".local/share/swapdex/accounts/stale/claude-code");
    std::fs::create_dir_all(&snap).unwrap();
    std::fs::write(
        snap.join("credentials"),
        br#"{"claudeAiOauth":{"accessToken":"AT-OLD","refreshToken":"RT-OLD"}}"#,
    )
    .unwrap();
    std::fs::write(
        snap.join("oauth_account"),
        br#"{"accountUuid":"u-shared","emailAddress":"shared@example.com"}"#,
    )
    .unwrap();

    let (out, err, code) = run(root, &["use", "stale", "--tool", "claude"]);
    let said = format!("{out}{err}");
    assert_ne!(code, 0, "a retired Claude snapshot was applied:\n{said}");
    assert!(
        said.contains("retired") || said.contains("rotated"),
        "nothing said the token was retired elsewhere:\n{said}"
    );
}

/// A settings file that will not parse must be reported, not absorbed.
///
/// `settings::load` falls back to defaults on a parse error, because every
/// caller wants a value rather than an error. The consequence is that a corrupt
/// file reads as NO settings: every account the user paused is silently back in
/// the proxy's rotation, the strategy is back to default, and the listing shows
/// nothing unusual. The proxy reads the same file, so an account somebody took
/// out of rotation starts paying for turns again with no signal anywhere.
/// `doctor` is the one screen whose job is to find exactly this.
#[test]
fn doctor_reports_a_settings_file_that_will_not_parse() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let (o, e, c) = run(root, &["pause", "work"]);
    assert_eq!(c, 0, "pause failed:\n{o}{e}");

    let settings = root.join(".local/share/swapdex/settings.json");
    assert!(settings.exists(), "pause wrote no settings file");
    std::fs::write(&settings, b"NOT JSON {{{").unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.to_lowercase().contains("settings"),
        "doctor says nothing about a settings file it cannot read:\n{said}"
    );
}

/// The permission check must look where the credentials actually live.
///
/// It walked the four bare paths - `~/.claude/.credentials.json` and its
/// siblings - and never a slot. Under the slot model, which is what `run`,
/// `migrate` and `onboard` all steer people into, every credential lives in a
/// slot instead, so on such a machine the check ran over nothing at all while
/// reporting a clean bill. The README's promise that every credential swapdex
/// writes is 0600 was being verified for the one file it no longer writes.
#[test]
fn doctor_checks_the_permissions_of_credentials_in_slots() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let cred = root
        .join(".local/share/swapdex/slots/work")
        .join(".credentials.json");
    assert!(cred.exists(), "the fixture wrote no slot credential");
    use std::os::unix::fs::PermissionsExt;
    std::fs::set_permissions(&cred, std::fs::Permissions::from_mode(0o644)).unwrap();

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("group/world-readable"),
        "doctor passed a world-readable slot credential:\n{said}"
    );
}

/// The over-correction of the test above: a registry that parses must not be
/// announced as damaged. A health check that cries wolf on a healthy machine
/// teaches the user to skim past the row that will one day be real.
#[test]
fn doctor_stays_quiet_about_a_registry_that_parses() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let reg = root.join(".local/share/swapdex/slots.json");
    assert!(reg.exists(), "the fixture wrote no registry");

    let (out, err, _) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        !said.contains("will not parse"),
        "doctor called a readable registry damaged:\n{said}"
    );
}

/// A registry that will not parse is a finding, not an absence.
///
/// `doctor` opened the slot registry with `if let Ok(..)` and skipped every
/// check inside when it would not parse - the account count, the default
/// pointer, the per-slot login rows, all of it. The rows did not say "cannot
/// check"; they simply were not printed, and a shorter clean report reads as a
/// healthier one. So with a damaged registry `doctor` said "everything looks
/// healthy" and exited 0, while `ls` printed a paragraph about the same file
/// being damaged and told the reader how to restore it.
#[test]
fn doctor_reports_a_slot_registry_that_will_not_parse() {
    let t = fixture();
    let root = t.path();
    seed_slot(root, "work", "work@example.com");
    let reg = root.join(".local/share/swapdex/slots.json");
    assert!(reg.exists(), "the fixture wrote no registry");
    std::fs::write(&reg, b"").unwrap();

    // `ls` knows. That is the bar doctor has to meet.
    let (listed, lerr, _) = run(root, &["ls"]);
    assert!(
        format!("{listed}{lerr}").contains("could not be read"),
        "ls no longer reports a damaged registry, so this test is measuring the wrong thing"
    );

    let (out, err, code) = run(root, &["doctor"]);
    let said = format!("{out}{err}");
    assert!(
        said.contains("registry") || said.contains("slots.json"),
        "doctor called a damaged account registry healthy:\n{said}"
    );
    assert_ne!(code, 0, "doctor exited 0 with a damaged registry:\n{said}");
}