swapdex 0.166.1

Switch between multiple Claude Code, Codex, Gemini, and Antigravity login accounts, locally and safely.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
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
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
6281
6282
6283
6284
6285
6286
6287
6288
6289
6290
6291
6292
6293
6294
6295
6296
6297
6298
6299
6300
6301
6302
6303
6304
6305
6306
6307
6308
6309
6310
6311
6312
6313
6314
6315
6316
6317
6318
6319
6320
6321
6322
6323
6324
6325
6326
6327
6328
6329
6330
6331
6332
6333
6334
6335
6336
6337
6338
6339
6340
6341
6342
6343
6344
6345
6346
6347
6348
6349
6350
6351
6352
6353
6354
6355
6356
6357
6358
6359
6360
6361
6362
6363
6364
6365
6366
6367
6368
6369
6370
6371
6372
6373
6374
6375
6376
6377
6378
6379
6380
6381
6382
6383
6384
6385
6386
6387
6388
6389
6390
6391
6392
6393
6394
6395
6396
6397
6398
6399
6400
6401
6402
6403
6404
6405
6406
6407
6408
6409
6410
6411
6412
6413
6414
6415
6416
6417
6418
6419
6420
6421
6422
6423
6424
6425
6426
6427
6428
6429
6430
6431
6432
6433
6434
6435
6436
6437
6438
6439
6440
6441
6442
6443
6444
6445
6446
6447
6448
6449
6450
6451
6452
6453
6454
6455
6456
6457
6458
6459
6460
6461
6462
6463
6464
6465
6466
6467
6468
6469
6470
6471
6472
6473
6474
6475
6476
6477
6478
6479
6480
6481
6482
6483
6484
6485
6486
6487
6488
6489
6490
6491
6492
6493
6494
6495
6496
6497
6498
6499
6500
6501
6502
6503
6504
6505
6506
6507
6508
6509
6510
6511
6512
6513
6514
6515
6516
6517
6518
6519
6520
6521
6522
6523
6524
6525
6526
6527
6528
6529
6530
6531
6532
6533
6534
6535
6536
6537
6538
6539
6540
6541
6542
6543
6544
6545
6546
6547
6548
6549
6550
6551
6552
6553
6554
6555
6556
6557
6558
6559
6560
6561
6562
6563
6564
6565
6566
6567
6568
6569
6570
6571
6572
6573
6574
6575
6576
6577
6578
6579
6580
6581
6582
6583
6584
6585
6586
6587
6588
6589
6590
6591
6592
6593
6594
6595
6596
6597
6598
6599
6600
6601
6602
6603
6604
6605
6606
6607
6608
6609
6610
6611
6612
6613
6614
6615
6616
6617
6618
6619
6620
6621
6622
6623
6624
6625
6626
6627
6628
6629
6630
6631
6632
6633
6634
6635
6636
6637
6638
6639
6640
6641
6642
6643
6644
6645
6646
6647
6648
6649
6650
6651
6652
6653
6654
6655
6656
6657
6658
6659
6660
6661
6662
6663
6664
6665
6666
6667
6668
6669
6670
6671
6672
6673
6674
6675
6676
6677
6678
6679
6680
6681
6682
6683
6684
6685
6686
6687
6688
6689
6690
6691
6692
6693
6694
6695
6696
6697
6698
6699
6700
6701
6702
6703
6704
6705
6706
6707
6708
6709
6710
6711
6712
6713
6714
6715
6716
6717
6718
6719
6720
6721
6722
6723
6724
6725
6726
6727
6728
6729
6730
6731
6732
6733
6734
6735
6736
6737
6738
6739
6740
6741
6742
6743
6744
6745
6746
6747
6748
6749
6750
6751
6752
6753
6754
6755
6756
6757
6758
6759
6760
6761
6762
6763
6764
6765
6766
6767
6768
6769
6770
6771
6772
6773
6774
6775
6776
6777
6778
6779
6780
6781
6782
6783
6784
6785
6786
6787
6788
6789
6790
6791
6792
6793
6794
6795
6796
6797
6798
6799
6800
6801
6802
6803
6804
6805
6806
6807
6808
6809
6810
6811
6812
6813
6814
6815
6816
6817
6818
6819
6820
6821
6822
6823
6824
6825
6826
6827
6828
6829
6830
6831
6832
6833
6834
6835
6836
6837
6838
6839
6840
6841
6842
6843
6844
6845
6846
6847
6848
6849
6850
6851
6852
6853
6854
6855
6856
6857
6858
6859
6860
6861
6862
6863
6864
6865
6866
6867
6868
6869
6870
6871
6872
6873
6874
6875
6876
6877
6878
6879
6880
6881
6882
6883
6884
6885
6886
6887
6888
6889
6890
6891
6892
6893
6894
6895
6896
6897
6898
6899
6900
6901
6902
6903
6904
6905
6906
6907
6908
6909
6910
6911
6912
6913
6914
6915
6916
6917
6918
6919
6920
6921
6922
6923
6924
6925
6926
6927
6928
6929
6930
6931
6932
6933
6934
6935
6936
6937
6938
6939
6940
6941
6942
6943
6944
6945
6946
6947
6948
6949
6950
6951
6952
6953
6954
6955
6956
6957
6958
6959
6960
6961
6962
6963
6964
6965
6966
6967
6968
6969
6970
6971
6972
6973
6974
6975
6976
6977
6978
6979
6980
6981
6982
6983
6984
6985
6986
6987
6988
6989
6990
6991
6992
6993
6994
6995
6996
6997
6998
6999
7000
7001
7002
7003
7004
7005
7006
7007
7008
7009
7010
7011
7012
7013
7014
7015
7016
7017
7018
7019
7020
7021
7022
7023
7024
7025
7026
7027
7028
7029
7030
7031
7032
7033
7034
7035
7036
7037
7038
7039
7040
7041
7042
7043
7044
7045
7046
7047
7048
7049
7050
7051
7052
7053
7054
7055
7056
7057
7058
7059
7060
7061
7062
7063
7064
7065
7066
7067
7068
7069
7070
7071
7072
7073
7074
7075
7076
7077
7078
7079
7080
7081
7082
7083
7084
7085
7086
7087
7088
7089
7090
7091
7092
7093
7094
7095
7096
7097
7098
7099
7100
7101
7102
7103
7104
7105
7106
7107
7108
7109
7110
7111
7112
7113
7114
7115
7116
7117
7118
7119
7120
7121
7122
7123
7124
7125
7126
7127
7128
7129
7130
7131
7132
7133
7134
7135
7136
7137
7138
7139
7140
7141
7142
7143
7144
7145
7146
7147
7148
7149
7150
7151
7152
7153
7154
7155
7156
7157
7158
7159
7160
7161
7162
7163
7164
7165
7166
7167
7168
7169
7170
7171
7172
7173
7174
7175
7176
7177
7178
7179
7180
7181
7182
7183
7184
7185
7186
7187
7188
7189
7190
7191
7192
7193
7194
7195
7196
7197
7198
7199
7200
7201
7202
7203
7204
7205
7206
7207
7208
7209
7210
7211
7212
7213
7214
7215
7216
7217
7218
7219
7220
7221
7222
7223
7224
7225
7226
7227
7228
7229
7230
7231
7232
7233
7234
7235
7236
7237
7238
7239
7240
7241
7242
7243
7244
7245
7246
7247
7248
7249
7250
7251
7252
7253
7254
7255
7256
7257
7258
7259
7260
7261
7262
7263
7264
7265
7266
7267
7268
7269
7270
7271
7272
7273
7274
7275
7276
7277
7278
7279
7280
7281
7282
7283
7284
7285
7286
7287
7288
7289
7290
7291
7292
7293
7294
7295
7296
7297
7298
7299
7300
7301
7302
7303
7304
7305
7306
7307
7308
7309
7310
7311
7312
7313
7314
7315
7316
7317
7318
7319
7320
7321
7322
7323
7324
7325
7326
7327
7328
7329
7330
7331
7332
7333
7334
7335
7336
7337
7338
7339
7340
7341
7342
7343
7344
7345
7346
7347
7348
7349
7350
7351
7352
7353
7354
7355
7356
7357
7358
7359
7360
7361
7362
7363
7364
7365
7366
7367
7368
7369
7370
7371
7372
7373
7374
7375
7376
7377
7378
7379
7380
7381
7382
7383
7384
7385
7386
7387
7388
7389
7390
7391
7392
7393
7394
7395
7396
7397
7398
7399
7400
7401
7402
7403
7404
7405
7406
7407
7408
7409
7410
7411
7412
7413
7414
7415
7416
7417
7418
7419
7420
7421
7422
7423
7424
7425
7426
7427
7428
7429
7430
7431
7432
7433
7434
7435
7436
7437
7438
7439
7440
7441
7442
7443
7444
7445
7446
7447
7448
7449
7450
7451
7452
7453
7454
7455
7456
7457
7458
7459
7460
7461
7462
7463
7464
7465
7466
7467
7468
7469
7470
7471
7472
7473
7474
7475
7476
7477
7478
7479
7480
7481
7482
7483
7484
7485
7486
7487
7488
7489
7490
7491
7492
7493
7494
7495
7496
7497
7498
7499
7500
7501
7502
7503
7504
7505
7506
7507
7508
7509
7510
7511
7512
7513
7514
7515
7516
7517
7518
7519
7520
7521
7522
7523
7524
7525
7526
7527
7528
7529
7530
7531
7532
7533
7534
7535
7536
7537
7538
7539
7540
7541
7542
7543
7544
7545
7546
7547
7548
7549
7550
7551
7552
7553
7554
7555
7556
7557
7558
7559
7560
7561
7562
7563
7564
7565
7566
7567
7568
7569
7570
7571
7572
7573
7574
7575
7576
7577
7578
7579
7580
7581
7582
7583
7584
7585
7586
7587
7588
7589
7590
7591
7592
7593
7594
7595
7596
7597
7598
7599
7600
7601
7602
7603
7604
7605
7606
7607
7608
7609
7610
7611
7612
7613
7614
7615
7616
7617
7618
7619
7620
7621
7622
7623
7624
7625
7626
7627
7628
7629
7630
7631
7632
7633
7634
7635
7636
7637
7638
7639
7640
7641
7642
7643
7644
7645
7646
7647
7648
7649
7650
7651
7652
7653
7654
7655
7656
7657
7658
7659
7660
7661
7662
7663
7664
7665
7666
7667
7668
7669
7670
7671
7672
7673
7674
7675
7676
7677
7678
7679
7680
7681
7682
7683
7684
7685
7686
7687
7688
7689
7690
7691
7692
7693
7694
7695
7696
7697
7698
7699
7700
7701
7702
7703
7704
7705
7706
7707
7708
7709
7710
7711
7712
7713
7714
7715
7716
7717
7718
7719
7720
7721
7722
7723
7724
7725
7726
7727
7728
7729
7730
7731
7732
7733
7734
7735
7736
7737
7738
7739
7740
7741
7742
7743
7744
7745
7746
7747
7748
7749
7750
7751
7752
7753
7754
7755
7756
7757
7758
7759
7760
7761
7762
7763
7764
7765
7766
7767
7768
7769
7770
7771
7772
7773
7774
7775
7776
7777
7778
7779
7780
7781
7782
7783
7784
7785
7786
7787
7788
7789
7790
7791
7792
7793
7794
7795
7796
7797
7798
7799
7800
7801
7802
7803
7804
7805
7806
7807
7808
7809
7810
7811
7812
7813
7814
7815
7816
7817
7818
7819
7820
7821
7822
7823
7824
7825
7826
7827
7828
7829
7830
7831
7832
7833
7834
7835
7836
7837
7838
7839
7840
7841
7842
7843
7844
7845
7846
7847
7848
7849
7850
7851
7852
7853
7854
7855
7856
7857
7858
7859
7860
7861
7862
7863
7864
7865
7866
7867
7868
7869
7870
7871
7872
7873
7874
7875
7876
7877
7878
7879
7880
7881
7882
7883
7884
7885
7886
7887
7888
7889
7890
7891
7892
7893
7894
7895
7896
7897
7898
7899
7900
7901
7902
7903
7904
7905
7906
7907
7908
7909
7910
7911
7912
7913
7914
7915
7916
7917
7918
7919
7920
7921
7922
7923
7924
7925
7926
7927
7928
7929
7930
7931
7932
7933
7934
7935
7936
7937
7938
7939
7940
7941
7942
7943
7944
7945
7946
7947
7948
7949
7950
7951
7952
7953
7954
7955
7956
7957
7958
7959
7960
7961
7962
7963
7964
7965
7966
7967
7968
7969
7970
7971
7972
7973
7974
7975
7976
7977
7978
7979
7980
7981
7982
7983
7984
7985
7986
7987
7988
7989
7990
7991
7992
7993
7994
7995
7996
7997
7998
7999
8000
8001
8002
8003
8004
8005
8006
8007
8008
8009
8010
8011
8012
8013
8014
8015
8016
8017
8018
8019
8020
8021
8022
8023
8024
8025
8026
8027
8028
8029
8030
8031
8032
8033
8034
8035
8036
8037
8038
8039
8040
8041
8042
8043
8044
8045
8046
8047
8048
8049
8050
8051
8052
8053
8054
8055
8056
8057
8058
8059
8060
8061
8062
8063
8064
8065
8066
8067
8068
8069
8070
8071
8072
8073
8074
8075
8076
8077
8078
8079
8080
8081
8082
8083
8084
8085
8086
8087
8088
8089
8090
8091
8092
8093
8094
8095
8096
8097
8098
8099
8100
8101
8102
8103
8104
8105
8106
8107
8108
8109
8110
8111
8112
8113
8114
8115
8116
8117
8118
8119
8120
8121
8122
8123
8124
8125
8126
8127
8128
8129
8130
8131
8132
8133
8134
8135
8136
8137
8138
8139
8140
8141
8142
8143
8144
8145
8146
8147
8148
8149
8150
8151
8152
8153
8154
8155
8156
8157
8158
8159
8160
8161
8162
8163
8164
8165
8166
8167
8168
8169
8170
8171
8172
8173
8174
8175
8176
8177
8178
8179
8180
8181
8182
8183
8184
8185
8186
8187
8188
8189
8190
8191
8192
8193
8194
8195
8196
8197
8198
8199
8200
8201
8202
8203
8204
8205
8206
8207
8208
8209
8210
8211
8212
8213
8214
8215
8216
8217
8218
8219
8220
8221
8222
8223
8224
8225
8226
8227
8228
8229
8230
8231
8232
8233
8234
8235
8236
8237
8238
8239
8240
8241
8242
8243
8244
8245
8246
8247
8248
8249
8250
8251
8252
8253
8254
8255
8256
8257
8258
8259
8260
8261
8262
8263
8264
8265
8266
8267
8268
8269
8270
8271
8272
8273
8274
8275
8276
8277
8278
8279
8280
8281
8282
8283
8284
8285
8286
8287
8288
8289
8290
8291
8292
8293
8294
8295
8296
8297
8298
8299
8300
8301
8302
8303
8304
8305
8306
8307
8308
8309
8310
8311
8312
8313
8314
8315
8316
8317
8318
8319
8320
8321
8322
8323
8324
8325
8326
8327
8328
8329
8330
8331
8332
8333
8334
8335
8336
8337
8338
8339
8340
8341
8342
8343
8344
8345
8346
8347
8348
8349
8350
8351
8352
8353
8354
8355
8356
8357
8358
8359
8360
8361
8362
8363
8364
8365
8366
8367
8368
8369
8370
8371
8372
8373
8374
8375
8376
8377
8378
8379
8380
8381
8382
8383
8384
8385
8386
8387
8388
8389
8390
8391
8392
8393
8394
8395
8396
8397
8398
8399
8400
8401
8402
8403
8404
8405
8406
8407
8408
8409
8410
8411
8412
8413
8414
8415
8416
8417
8418
8419
8420
8421
8422
8423
8424
8425
8426
8427
8428
8429
8430
8431
8432
8433
8434
8435
8436
8437
8438
8439
8440
8441
8442
8443
8444
8445
8446
8447
8448
8449
8450
8451
8452
8453
8454
8455
8456
8457
8458
8459
8460
8461
8462
8463
8464
8465
8466
8467
8468
8469
8470
8471
8472
8473
8474
8475
8476
8477
8478
8479
8480
8481
8482
8483
8484
8485
8486
8487
8488
8489
8490
8491
8492
8493
8494
8495
8496
8497
8498
8499
8500
8501
8502
8503
8504
8505
8506
8507
8508
8509
8510
8511
8512
8513
8514
8515
8516
8517
8518
8519
8520
8521
8522
8523
8524
8525
8526
8527
8528
8529
8530
8531
8532
8533
8534
8535
8536
8537
8538
8539
8540
8541
8542
8543
8544
8545
8546
8547
8548
8549
8550
8551
8552
8553
8554
8555
8556
8557
8558
8559
8560
8561
8562
8563
8564
8565
8566
8567
8568
8569
8570
8571
8572
8573
8574
8575
8576
8577
8578
8579
8580
8581
8582
8583
8584
8585
8586
8587
8588
8589
8590
8591
8592
8593
8594
8595
8596
8597
8598
8599
8600
8601
8602
8603
8604
8605
8606
8607
8608
8609
8610
8611
8612
8613
8614
8615
8616
8617
8618
8619
8620
8621
8622
8623
8624
8625
8626
8627
8628
8629
8630
8631
8632
8633
8634
8635
8636
8637
8638
8639
8640
8641
8642
8643
8644
8645
8646
8647
8648
8649
8650
8651
8652
8653
8654
8655
8656
8657
8658
8659
8660
8661
8662
8663
8664
8665
8666
8667
8668
8669
8670
8671
8672
8673
8674
8675
8676
8677
8678
8679
8680
8681
8682
8683
8684
8685
8686
8687
8688
8689
8690
8691
8692
8693
8694
8695
8696
8697
8698
8699
8700
8701
8702
8703
8704
8705
8706
8707
8708
8709
8710
8711
8712
8713
8714
8715
8716
8717
8718
8719
8720
8721
8722
8723
8724
8725
8726
8727
8728
8729
8730
8731
8732
8733
8734
8735
8736
8737
8738
8739
8740
8741
8742
8743
8744
8745
8746
8747
8748
8749
8750
8751
8752
8753
8754
8755
8756
8757
8758
8759
8760
8761
8762
8763
8764
8765
8766
8767
8768
8769
8770
8771
8772
8773
8774
8775
8776
8777
8778
8779
8780
8781
8782
8783
8784
8785
8786
8787
8788
8789
8790
8791
8792
8793
8794
8795
8796
8797
8798
8799
8800
8801
8802
8803
8804
8805
8806
8807
8808
8809
8810
8811
8812
8813
8814
8815
8816
8817
8818
8819
8820
8821
8822
8823
8824
8825
8826
8827
8828
8829
8830
8831
8832
8833
8834
8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
8845
8846
8847
8848
8849
8850
8851
8852
8853
8854
8855
8856
8857
8858
8859
8860
8861
8862
8863
8864
8865
8866
8867
8868
8869
8870
8871
8872
8873
8874
8875
8876
8877
8878
8879
8880
8881
8882
8883
8884
8885
8886
8887
8888
8889
8890
8891
8892
8893
8894
8895
8896
8897
8898
8899
8900
8901
8902
8903
8904
8905
8906
8907
8908
8909
8910
8911
8912
8913
8914
8915
8916
8917
8918
8919
8920
8921
8922
8923
8924
8925
8926
8927
8928
8929
8930
8931
8932
8933
8934
8935
8936
8937
8938
8939
8940
8941
8942
8943
8944
8945
8946
8947
8948
8949
8950
8951
8952
8953
8954
8955
8956
8957
8958
8959
8960
8961
8962
8963
8964
8965
8966
8967
8968
8969
8970
8971
8972
8973
8974
8975
8976
8977
8978
8979
8980
8981
8982
8983
8984
8985
8986
8987
8988
8989
8990
8991
8992
8993
8994
8995
8996
8997
8998
8999
9000
9001
9002
9003
9004
9005
9006
9007
9008
9009
9010
9011
9012
9013
9014
9015
9016
9017
9018
9019
9020
9021
9022
9023
9024
9025
9026
9027
9028
9029
9030
9031
9032
9033
9034
9035
9036
9037
9038
9039
9040
9041
9042
9043
9044
9045
9046
9047
9048
9049
9050
9051
9052
9053
9054
9055
9056
9057
9058
9059
9060
9061
9062
9063
9064
9065
9066
9067
9068
9069
9070
9071
9072
9073
9074
9075
9076
9077
9078
9079
9080
9081
9082
9083
9084
9085
9086
9087
9088
9089
9090
9091
9092
9093
9094
9095
9096
9097
9098
9099
9100
9101
9102
9103
9104
9105
9106
9107
9108
9109
9110
9111
9112
9113
9114
9115
9116
9117
9118
9119
9120
9121
9122
9123
9124
9125
9126
9127
9128
9129
9130
9131
9132
9133
9134
9135
9136
9137
9138
9139
9140
9141
9142
9143
9144
9145
9146
9147
9148
9149
9150
9151
9152
9153
9154
9155
9156
9157
9158
9159
9160
9161
9162
9163
9164
9165
9166
9167
9168
9169
9170
9171
9172
9173
9174
9175
9176
9177
9178
9179
9180
9181
9182
9183
9184
9185
9186
9187
9188
9189
9190
9191
9192
9193
9194
9195
9196
9197
9198
9199
9200
9201
9202
9203
9204
9205
9206
9207
9208
9209
9210
9211
9212
9213
9214
9215
9216
9217
9218
9219
9220
9221
9222
9223
9224
9225
9226
9227
9228
9229
9230
9231
9232
9233
9234
9235
9236
9237
9238
9239
9240
9241
9242
9243
9244
9245
9246
9247
9248
9249
9250
9251
9252
9253
9254
9255
9256
9257
9258
9259
9260
9261
9262
9263
9264
9265
9266
9267
9268
9269
9270
9271
9272
9273
9274
9275
9276
9277
9278
9279
9280
9281
9282
9283
9284
9285
9286
9287
9288
9289
9290
9291
9292
9293
9294
9295
9296
9297
9298
9299
9300
9301
9302
9303
9304
9305
9306
9307
9308
9309
9310
9311
9312
9313
9314
9315
9316
9317
9318
9319
9320
9321
9322
9323
9324
9325
9326
9327
9328
9329
9330
9331
9332
9333
9334
9335
9336
9337
9338
9339
9340
9341
9342
9343
9344
9345
9346
9347
9348
9349
9350
9351
9352
9353
9354
9355
9356
9357
9358
9359
9360
9361
9362
9363
9364
9365
9366
9367
9368
9369
9370
9371
9372
9373
9374
9375
9376
9377
9378
9379
9380
9381
9382
9383
9384
9385
9386
9387
9388
9389
9390
9391
9392
9393
9394
9395
9396
9397
9398
9399
9400
9401
9402
9403
9404
9405
9406
9407
9408
9409
9410
9411
9412
9413
9414
9415
9416
9417
9418
9419
9420
9421
9422
9423
9424
9425
9426
9427
9428
9429
9430
9431
9432
9433
9434
9435
9436
9437
9438
9439
9440
9441
9442
9443
9444
9445
9446
9447
9448
9449
9450
9451
9452
9453
9454
9455
9456
9457
9458
9459
9460
9461
9462
9463
9464
9465
9466
9467
9468
9469
9470
9471
9472
9473
9474
9475
9476
9477
9478
9479
9480
9481
9482
9483
9484
9485
9486
9487
9488
9489
9490
9491
9492
9493
9494
9495
9496
9497
9498
9499
9500
9501
9502
9503
9504
9505
9506
9507
9508
9509
9510
9511
9512
9513
9514
9515
9516
9517
9518
9519
9520
9521
9522
9523
9524
9525
9526
9527
9528
9529
9530
9531
9532
9533
9534
9535
9536
9537
9538
9539
9540
9541
9542
9543
9544
9545
9546
9547
9548
9549
9550
9551
9552
9553
9554
9555
9556
9557
9558
9559
9560
9561
9562
9563
9564
9565
9566
9567
9568
9569
9570
9571
9572
9573
9574
9575
9576
9577
9578
9579
9580
9581
9582
9583
9584
9585
9586
9587
9588
9589
9590
9591
9592
9593
9594
9595
9596
9597
9598
9599
9600
9601
9602
9603
9604
9605
9606
9607
9608
9609
9610
9611
9612
9613
9614
9615
9616
9617
9618
9619
9620
9621
9622
9623
9624
9625
9626
9627
9628
9629
9630
9631
9632
9633
9634
9635
9636
9637
9638
9639
9640
9641
9642
9643
9644
9645
9646
9647
9648
9649
9650
9651
9652
9653
9654
9655
9656
9657
9658
9659
9660
9661
9662
9663
9664
9665
9666
9667
9668
9669
9670
9671
9672
9673
9674
9675
9676
9677
9678
9679
9680
9681
9682
9683
9684
9685
9686
9687
9688
9689
9690
9691
9692
9693
9694
9695
9696
9697
9698
9699
9700
9701
9702
9703
9704
9705
9706
9707
9708
9709
9710
9711
9712
9713
9714
9715
9716
9717
9718
9719
9720
9721
9722
9723
9724
9725
9726
9727
9728
9729
9730
9731
9732
9733
9734
9735
9736
9737
9738
9739
9740
9741
9742
9743
9744
9745
9746
9747
9748
9749
9750
9751
9752
9753
9754
9755
9756
9757
9758
9759
9760
9761
9762
9763
9764
9765
9766
9767
9768
9769
9770
9771
9772
9773
9774
9775
9776
9777
9778
9779
9780
9781
9782
9783
9784
9785
9786
9787
9788
9789
9790
9791
9792
9793
9794
9795
9796
9797
9798
9799
9800
9801
9802
9803
9804
9805
9806
9807
9808
9809
9810
9811
9812
9813
9814
9815
9816
9817
9818
9819
9820
9821
9822
9823
9824
9825
9826
9827
9828
9829
9830
9831
9832
9833
9834
9835
9836
9837
9838
9839
9840
9841
9842
9843
9844
9845
9846
9847
9848
9849
9850
9851
9852
9853
9854
9855
9856
9857
9858
9859
9860
9861
9862
9863
9864
9865
9866
9867
9868
9869
9870
9871
9872
9873
9874
9875
9876
9877
9878
9879
9880
9881
9882
9883
9884
9885
9886
9887
9888
9889
9890
9891
9892
9893
9894
9895
9896
9897
9898
9899
9900
9901
9902
9903
9904
9905
9906
9907
9908
9909
9910
9911
9912
9913
9914
9915
9916
9917
9918
9919
9920
9921
9922
9923
9924
9925
9926
9927
9928
9929
9930
9931
9932
9933
9934
9935
9936
9937
9938
9939
9940
9941
9942
9943
9944
9945
9946
9947
9948
9949
9950
9951
9952
9953
9954
9955
9956
9957
9958
9959
9960
9961
9962
9963
9964
9965
9966
9967
9968
9969
9970
9971
9972
9973
9974
9975
9976
9977
9978
9979
9980
9981
9982
9983
9984
9985
9986
9987
9988
9989
9990
9991
9992
9993
9994
9995
9996
9997
9998
9999
10000
10001
10002
10003
10004
10005
10006
10007
10008
10009
10010
10011
10012
10013
10014
10015
10016
10017
10018
10019
10020
10021
10022
10023
10024
10025
10026
10027
10028
10029
10030
10031
10032
10033
10034
10035
10036
10037
10038
10039
10040
10041
10042
10043
10044
10045
10046
10047
10048
10049
10050
10051
10052
10053
10054
10055
10056
10057
10058
10059
10060
10061
10062
10063
10064
10065
10066
10067
10068
10069
10070
10071
10072
10073
10074
10075
10076
10077
10078
10079
10080
10081
10082
10083
10084
10085
10086
10087
10088
10089
10090
10091
10092
10093
10094
10095
10096
10097
10098
10099
10100
10101
10102
10103
10104
10105
10106
10107
10108
10109
10110
10111
10112
10113
10114
10115
10116
10117
10118
10119
10120
10121
10122
10123
10124
10125
10126
10127
10128
10129
10130
10131
10132
10133
10134
10135
10136
10137
10138
10139
10140
10141
10142
10143
10144
10145
10146
10147
10148
10149
10150
10151
10152
10153
10154
10155
10156
10157
10158
10159
10160
10161
10162
10163
10164
10165
10166
10167
10168
10169
10170
10171
10172
10173
10174
10175
10176
10177
10178
10179
10180
10181
10182
10183
10184
10185
10186
10187
10188
10189
10190
10191
10192
10193
10194
10195
10196
10197
10198
10199
10200
10201
10202
10203
10204
10205
10206
10207
10208
10209
10210
10211
10212
10213
10214
10215
10216
10217
10218
10219
10220
10221
10222
10223
10224
10225
10226
10227
10228
10229
10230
10231
10232
10233
10234
10235
10236
10237
10238
10239
10240
10241
10242
10243
10244
10245
10246
10247
10248
10249
10250
10251
10252
10253
10254
10255
10256
10257
10258
10259
10260
10261
10262
10263
10264
10265
10266
10267
10268
10269
10270
10271
10272
10273
10274
10275
10276
10277
10278
10279
10280
10281
10282
10283
10284
10285
10286
10287
10288
10289
10290
10291
10292
10293
10294
10295
10296
10297
10298
10299
10300
10301
10302
10303
10304
10305
10306
10307
10308
10309
10310
10311
10312
10313
10314
10315
10316
10317
10318
10319
10320
10321
10322
10323
10324
10325
10326
10327
10328
10329
10330
10331
10332
10333
10334
10335
10336
10337
10338
10339
10340
10341
10342
10343
10344
10345
10346
10347
10348
10349
10350
10351
10352
10353
10354
10355
10356
10357
10358
10359
10360
10361
10362
10363
10364
10365
10366
10367
10368
10369
10370
10371
10372
10373
10374
10375
10376
10377
10378
10379
10380
10381
10382
10383
10384
10385
10386
10387
10388
10389
10390
10391
10392
10393
10394
10395
10396
10397
10398
10399
10400
10401
10402
10403
10404
10405
10406
10407
10408
10409
10410
10411
10412
10413
10414
10415
10416
10417
10418
10419
10420
10421
10422
10423
10424
10425
10426
10427
10428
10429
10430
10431
10432
10433
10434
10435
10436
10437
10438
10439
10440
10441
10442
10443
10444
10445
10446
10447
10448
10449
10450
10451
10452
10453
10454
10455
10456
10457
10458
10459
10460
10461
10462
10463
10464
10465
10466
10467
10468
10469
10470
10471
10472
10473
10474
10475
10476
10477
10478
10479
10480
10481
10482
10483
10484
10485
10486
10487
10488
10489
10490
10491
10492
10493
10494
10495
10496
10497
10498
10499
10500
10501
10502
10503
10504
10505
10506
10507
10508
10509
10510
10511
10512
10513
10514
10515
10516
10517
10518
10519
10520
10521
10522
10523
10524
10525
10526
10527
10528
10529
10530
10531
10532
10533
10534
10535
10536
10537
10538
10539
10540
10541
10542
10543
10544
10545
10546
10547
10548
10549
10550
10551
10552
10553
10554
10555
10556
10557
10558
10559
10560
10561
10562
10563
10564
10565
10566
10567
10568
10569
10570
10571
10572
10573
10574
10575
10576
10577
10578
10579
10580
10581
10582
10583
10584
10585
10586
10587
10588
10589
10590
10591
10592
10593
10594
10595
10596
10597
10598
10599
10600
10601
10602
10603
10604
10605
10606
10607
10608
10609
10610
10611
10612
10613
10614
10615
10616
10617
10618
10619
10620
10621
10622
10623
10624
10625
10626
10627
10628
10629
10630
10631
10632
10633
10634
10635
10636
10637
10638
10639
10640
10641
10642
10643
10644
10645
10646
10647
10648
10649
10650
10651
10652
10653
10654
10655
10656
10657
10658
10659
10660
10661
10662
10663
10664
10665
10666
10667
10668
10669
10670
10671
10672
10673
10674
10675
10676
10677
10678
10679
10680
10681
10682
10683
10684
10685
10686
10687
10688
10689
10690
10691
10692
10693
10694
10695
10696
10697
10698
10699
10700
10701
10702
10703
10704
10705
10706
10707
10708
10709
10710
10711
10712
10713
10714
10715
10716
10717
10718
10719
10720
10721
10722
10723
10724
10725
10726
10727
10728
10729
10730
10731
10732
10733
10734
10735
10736
10737
10738
10739
10740
10741
10742
10743
10744
10745
10746
10747
10748
10749
10750
10751
10752
10753
10754
10755
10756
10757
10758
10759
10760
10761
10762
10763
10764
10765
10766
10767
10768
10769
10770
10771
10772
10773
10774
10775
10776
10777
10778
10779
10780
10781
10782
10783
10784
10785
10786
10787
10788
10789
10790
10791
10792
10793
10794
10795
10796
10797
10798
10799
10800
10801
10802
10803
10804
10805
10806
10807
10808
10809
10810
10811
10812
10813
10814
10815
10816
10817
10818
10819
10820
10821
10822
10823
10824
10825
10826
10827
10828
10829
10830
10831
10832
10833
10834
10835
10836
10837
10838
10839
10840
10841
10842
10843
10844
10845
10846
10847
10848
10849
10850
10851
10852
10853
10854
10855
10856
10857
10858
10859
10860
10861
10862
10863
10864
10865
10866
10867
10868
10869
10870
10871
10872
10873
10874
10875
10876
10877
10878
10879
10880
10881
10882
10883
10884
10885
10886
10887
10888
10889
10890
10891
10892
10893
10894
10895
10896
10897
10898
10899
10900
10901
10902
10903
10904
10905
10906
10907
10908
10909
10910
10911
10912
10913
10914
10915
10916
10917
10918
10919
10920
10921
10922
10923
10924
10925
10926
10927
10928
10929
10930
10931
10932
10933
10934
10935
10936
10937
10938
10939
10940
10941
10942
10943
10944
10945
10946
10947
10948
10949
10950
10951
10952
10953
10954
10955
10956
10957
10958
10959
10960
10961
10962
10963
10964
10965
10966
10967
10968
10969
10970
10971
10972
10973
10974
10975
10976
10977
10978
10979
10980
10981
10982
10983
10984
10985
10986
10987
10988
10989
10990
10991
10992
10993
10994
10995
10996
10997
10998
10999
11000
11001
11002
11003
11004
11005
11006
11007
11008
11009
11010
11011
11012
11013
11014
11015
11016
11017
11018
11019
11020
11021
11022
11023
11024
11025
11026
11027
11028
11029
11030
11031
11032
11033
11034
11035
11036
11037
11038
11039
11040
11041
11042
11043
11044
11045
11046
11047
11048
11049
11050
11051
11052
11053
11054
11055
11056
11057
11058
11059
11060
11061
11062
11063
11064
11065
11066
11067
11068
11069
11070
11071
11072
11073
11074
11075
11076
11077
11078
11079
11080
11081
11082
11083
11084
11085
11086
11087
11088
11089
11090
11091
11092
11093
11094
11095
11096
11097
11098
11099
11100
11101
11102
11103
11104
11105
11106
11107
11108
11109
11110
11111
11112
11113
11114
11115
11116
11117
11118
11119
11120
11121
11122
11123
11124
11125
11126
11127
11128
11129
11130
11131
11132
11133
11134
11135
11136
11137
11138
11139
11140
11141
11142
11143
11144
11145
11146
11147
11148
11149
11150
11151
11152
11153
11154
11155
11156
11157
11158
11159
11160
11161
11162
11163
11164
11165
11166
11167
11168
11169
11170
11171
11172
11173
11174
11175
11176
11177
11178
11179
11180
11181
11182
11183
11184
11185
11186
11187
11188
11189
11190
11191
11192
11193
11194
11195
11196
11197
11198
11199
11200
11201
11202
11203
11204
11205
11206
11207
11208
11209
11210
11211
11212
11213
11214
11215
11216
11217
11218
11219
11220
11221
11222
11223
11224
11225
11226
11227
11228
11229
11230
11231
11232
11233
11234
11235
11236
11237
11238
11239
11240
11241
11242
11243
11244
11245
11246
11247
11248
11249
11250
11251
11252
11253
11254
11255
11256
11257
11258
11259
11260
11261
11262
11263
11264
11265
11266
11267
11268
11269
11270
11271
11272
11273
11274
11275
11276
11277
11278
11279
11280
11281
11282
11283
11284
11285
11286
11287
11288
11289
11290
11291
11292
11293
11294
11295
11296
11297
11298
11299
11300
11301
11302
11303
11304
11305
11306
11307
11308
11309
11310
11311
11312
11313
11314
11315
11316
11317
11318
11319
11320
11321
11322
11323
11324
11325
11326
11327
11328
11329
11330
11331
11332
11333
11334
11335
11336
11337
11338
11339
11340
11341
11342
11343
11344
11345
11346
11347
11348
11349
11350
11351
11352
11353
11354
11355
11356
11357
11358
11359
11360
11361
11362
11363
11364
11365
11366
11367
11368
11369
11370
11371
11372
11373
11374
11375
11376
11377
11378
11379
11380
11381
11382
11383
11384
11385
11386
11387
11388
11389
11390
11391
11392
11393
11394
11395
11396
11397
11398
11399
11400
11401
11402
11403
11404
11405
11406
11407
11408
11409
11410
11411
11412
11413
11414
11415
11416
11417
11418
11419
11420
11421
11422
11423
11424
11425
11426
11427
11428
11429
11430
11431
11432
11433
11434
11435
11436
11437
11438
11439
11440
11441
11442
11443
11444
11445
11446
11447
11448
11449
11450
11451
11452
11453
11454
11455
11456
11457
11458
11459
11460
11461
11462
11463
11464
11465
11466
11467
11468
11469
11470
11471
11472
11473
11474
11475
11476
11477
11478
11479
11480
11481
11482
11483
11484
11485
11486
11487
11488
11489
11490
11491
11492
11493
11494
11495
11496
11497
11498
11499
11500
11501
11502
11503
11504
11505
11506
11507
11508
11509
11510
11511
11512
11513
11514
11515
11516
11517
11518
11519
11520
11521
11522
11523
11524
11525
11526
11527
11528
11529
11530
11531
11532
11533
11534
11535
11536
11537
11538
11539
11540
11541
11542
11543
11544
11545
11546
11547
11548
11549
11550
11551
11552
11553
11554
11555
11556
11557
11558
11559
11560
11561
11562
11563
11564
11565
11566
11567
11568
11569
11570
11571
11572
11573
11574
11575
11576
11577
11578
11579
11580
11581
11582
11583
11584
11585
11586
11587
11588
11589
11590
11591
11592
11593
11594
11595
11596
11597
11598
11599
11600
11601
11602
11603
11604
11605
11606
11607
11608
11609
11610
11611
11612
11613
11614
11615
11616
11617
11618
11619
11620
11621
11622
11623
11624
11625
11626
11627
11628
11629
11630
11631
11632
11633
11634
11635
11636
11637
11638
11639
11640
11641
11642
11643
11644
11645
11646
11647
11648
11649
11650
11651
11652
11653
11654
11655
11656
11657
11658
11659
11660
11661
11662
11663
11664
11665
11666
11667
11668
11669
11670
11671
11672
11673
11674
11675
11676
11677
11678
11679
11680
11681
11682
11683
11684
11685
11686
11687
11688
11689
11690
11691
11692
11693
11694
11695
11696
11697
11698
11699
11700
11701
11702
11703
11704
11705
11706
11707
11708
11709
11710
11711
11712
11713
11714
11715
11716
11717
11718
11719
11720
11721
11722
11723
11724
11725
11726
11727
11728
11729
11730
11731
11732
11733
11734
11735
11736
11737
11738
11739
11740
11741
11742
11743
11744
11745
11746
11747
11748
11749
11750
11751
11752
11753
11754
11755
11756
11757
11758
11759
11760
11761
11762
11763
11764
11765
11766
11767
11768
11769
11770
11771
11772
11773
11774
11775
11776
11777
11778
11779
11780
11781
11782
11783
11784
11785
11786
11787
11788
11789
11790
11791
11792
11793
11794
11795
11796
11797
11798
11799
11800
11801
11802
11803
11804
11805
11806
11807
11808
11809
11810
11811
11812
11813
11814
11815
11816
11817
11818
11819
11820
11821
11822
11823
11824
11825
11826
11827
11828
11829
11830
11831
11832
11833
11834
11835
11836
11837
11838
11839
11840
11841
11842
11843
11844
11845
11846
11847
11848
11849
11850
11851
11852
11853
11854
11855
11856
11857
11858
11859
11860
11861
11862
11863
11864
11865
11866
11867
11868
11869
11870
11871
11872
11873
11874
11875
11876
11877
11878
11879
11880
11881
11882
11883
11884
11885
11886
11887
11888
11889
11890
11891
11892
11893
11894
11895
11896
11897
11898
11899
11900
11901
11902
11903
11904
11905
11906
11907
11908
11909
11910
11911
11912
11913
11914
11915
11916
11917
11918
11919
11920
11921
11922
11923
11924
11925
11926
11927
11928
11929
11930
11931
11932
11933
11934
11935
11936
11937
11938
11939
11940
11941
11942
11943
11944
11945
11946
11947
11948
11949
11950
11951
11952
11953
11954
11955
11956
11957
11958
11959
11960
11961
11962
11963
11964
11965
11966
11967
11968
11969
11970
11971
11972
11973
11974
11975
11976
11977
11978
11979
11980
11981
11982
11983
11984
11985
11986
11987
11988
11989
11990
11991
11992
11993
11994
11995
11996
11997
11998
11999
12000
12001
12002
12003
12004
12005
12006
12007
12008
12009
12010
12011
12012
12013
12014
12015
12016
12017
12018
12019
12020
12021
12022
12023
12024
12025
12026
12027
12028
12029
12030
12031
12032
12033
12034
12035
12036
12037
12038
12039
12040
12041
12042
12043
12044
12045
12046
12047
12048
12049
12050
12051
12052
12053
12054
12055
12056
12057
12058
12059
12060
12061
12062
12063
12064
12065
12066
12067
12068
12069
12070
12071
12072
12073
12074
12075
12076
12077
12078
12079
12080
12081
12082
12083
12084
12085
12086
12087
12088
12089
12090
12091
12092
12093
12094
12095
12096
12097
12098
12099
12100
12101
12102
12103
12104
12105
12106
12107
12108
12109
12110
12111
12112
12113
12114
12115
12116
12117
12118
12119
12120
12121
12122
12123
12124
12125
12126
12127
12128
12129
12130
12131
12132
12133
12134
12135
12136
12137
12138
12139
12140
12141
12142
12143
12144
12145
12146
12147
12148
12149
12150
12151
12152
12153
12154
12155
12156
12157
12158
12159
12160
12161
12162
12163
12164
12165
12166
12167
12168
12169
12170
12171
12172
12173
12174
12175
12176
12177
12178
12179
12180
12181
12182
12183
12184
12185
12186
12187
12188
12189
12190
12191
12192
12193
12194
12195
12196
12197
12198
12199
12200
12201
12202
12203
12204
12205
12206
12207
12208
12209
12210
12211
12212
12213
12214
12215
12216
12217
12218
12219
12220
12221
12222
12223
12224
12225
12226
12227
12228
12229
12230
12231
12232
12233
12234
12235
12236
12237
12238
12239
12240
12241
12242
12243
12244
12245
12246
12247
12248
12249
12250
12251
12252
12253
12254
12255
12256
12257
12258
12259
12260
12261
12262
12263
12264
12265
12266
12267
12268
12269
12270
12271
12272
12273
12274
12275
12276
12277
12278
12279
12280
12281
12282
12283
12284
12285
12286
12287
12288
12289
12290
12291
12292
12293
12294
12295
12296
12297
12298
12299
12300
12301
12302
12303
12304
12305
12306
12307
12308
12309
12310
12311
12312
12313
12314
12315
12316
12317
12318
12319
12320
12321
12322
12323
12324
12325
12326
12327
12328
12329
12330
12331
12332
12333
12334
12335
12336
12337
12338
12339
12340
12341
12342
12343
12344
12345
12346
12347
12348
12349
12350
12351
12352
12353
12354
12355
12356
12357
12358
12359
12360
12361
12362
12363
12364
12365
12366
12367
12368
12369
12370
12371
12372
12373
12374
12375
12376
12377
12378
12379
12380
12381
12382
12383
12384
12385
12386
12387
12388
12389
12390
12391
12392
12393
12394
12395
12396
12397
12398
12399
12400
12401
12402
12403
12404
12405
12406
12407
12408
12409
12410
12411
12412
12413
12414
12415
12416
12417
12418
12419
12420
12421
12422
12423
12424
12425
12426
12427
12428
12429
12430
12431
12432
12433
12434
12435
12436
12437
12438
12439
12440
12441
12442
12443
12444
12445
12446
12447
12448
12449
12450
12451
12452
12453
12454
12455
12456
12457
12458
12459
12460
12461
12462
12463
12464
12465
12466
12467
12468
//! The subcommand handlers. Each returns an exit code; a hard error propagates
//! and `main` prints a redacted message + exits 1. Output is identity-based and
//! never prints a credential byte (the A11 egress guarantee) - the only reader
//! of a `Secret` is inside the adapters/store.

use crate::adapters::{self, Account, AuthTool};
use crate::paths::Paths;
use crate::store::Store;
use anyhow::{bail, Context, Result};
use serde_json::Value;
use std::process::Command;

/// Is a CLI on PATH and runnable?
/// The `--tool` flag value for a tool name (claude-code -> claude).
fn pretty_tool_flag(tool: &str) -> &str {
    if tool == "claude-code" {
        "claude"
    } else {
        tool
    }
}

fn now_nanos() -> u128 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0)
}

/// Is `cmd` on PATH? Answered by LOOKING, never by running it.
///
/// This used to shell out to `cmd --version`, which meant `swapdex doctor` -
/// whose whole job is to observe - executed whatever `claude` resolved to. With
/// the shim installed that is the shim, and the shim starts a proxy: a
/// diagnostic that silently launched a daemon every time it ran.
fn command_exists(cmd: &str) -> bool {
    let Some(path) = std::env::var_os("PATH") else {
        return false;
    };
    std::env::split_paths(&path).any(|dir| is_executable(&dir.join(cmd)))
}

#[cfg(unix)]
fn is_executable(p: &std::path::Path) -> bool {
    use std::os::unix::fs::PermissionsExt;
    std::fs::metadata(p).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
}

#[cfg(not(unix))]
fn is_executable(p: &std::path::Path) -> bool {
    p.is_file()
}

/// Which tool a `--tool` value targets. A clap `ValueEnum`, so an unknown or
/// miscased value (`--tool cluade`) is rejected with a did-you-mean instead of
/// silently falling through to "both" and switching a tool you meant to leave
/// alone. `None` (no `--tool`) means the default: act on whichever tools apply.
#[derive(Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum ToolSel {
    #[value(alias = "claude-code")]
    Claude,
    Codex,
    Gemini,
    Antigravity,
    /// Every tool (the default when --tool is omitted)
    #[value(alias = "both")]
    All,
}

impl ToolSel {
    /// Asked through `one_tool`, so the selection maps to a tool name in exactly
    /// one place: a tool added to this enum cannot be wired into one of them and
    /// forgotten in the other.
    fn wants(self, tool: &str) -> bool {
        one_tool(self).is_none_or(|t| t == tool)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
pub enum MigrationToolSel {
    #[value(alias = "claude-code")]
    Claude,
    Codex,
}

impl MigrationToolSel {
    fn wants(self, tool: &str) -> bool {
        match self {
            MigrationToolSel::Claude => tool == "claude-code",
            MigrationToolSel::Codex => tool == "codex",
        }
    }
}

/// The adapters a command targets. `None` and `Some(Both)` mean all; an explicit
/// single tool narrows it.
fn selected_adapters(sel: Option<ToolSel>) -> Vec<Box<dyn AuthTool>> {
    adapters::all()
        .into_iter()
        .filter(|a| sel.map(|s| s.wants(a.name())).unwrap_or(true))
        .collect()
}

/// Whether the user explicitly asked for one tool (so a missing one is an error,
/// not a silent skip). `--tool both` is treated as the lenient default.
fn is_explicit(sel: Option<ToolSel>) -> bool {
    matches!(
        sel,
        Some(ToolSel::Claude)
            | Some(ToolSel::Codex)
            | Some(ToolSel::Gemini)
            | Some(ToolSel::Antigravity)
    )
}

fn migration_tools(sel: Option<MigrationToolSel>) -> Vec<&'static str> {
    crate::adapters::names()
        .into_iter()
        .filter(|tool| crate::slots::home_var(tool).is_some())
        .filter(|tool| sel.map(|selected| selected.wants(tool)).unwrap_or(true))
        .collect()
}

/// On macOS, Claude Code keeps its OAuth login in the Keychain rather than in
/// `~/.claude/.credentials.json`, so swapdex sees "not logged in" even when a
/// login exists. When the config file proves a login is present, explain that
/// instead of gaslighting the user. (`cfg!` keeps this type-checked on Linux.)
fn macos_keychain_note(_paths: &Paths, _tool: &str) -> Option<&'static str> {
    // Claude Code on macOS is now supported: the adapter reads and writes the
    // login Keychain via `security`. So there is no longer anything to skip or
    // warn about - this returns None everywhere and the old skip branches are
    // inert. (Kept as a single seam in case a future tool needs a similar
    // platform note.)
    None
}

/// The account_id inside a snapshot's blobs (works for stored profiles and
/// backups alike).
fn snapshot_account_id(snap: &crate::adapters::Snapshot, tool: &str) -> Option<String> {
    match tool {
        "codex" => {
            let v: Value = serde_json::from_slice(snap.part("auth")?.expose()).ok()?;
            v["tokens"]["account_id"].as_str().map(|s| s.to_string())
        }
        "claude-code" => {
            let v: Value = serde_json::from_slice(snap.part("oauth_account")?.expose()).ok()?;
            v["accountUuid"].as_str().map(|s| s.to_string())
        }
        "gemini" => {
            let v: Value = serde_json::from_slice(snap.part("oauth")?.expose()).ok()?;
            crate::adapters::gemini_jwt_claim(v["id_token"].as_str(), "sub")
        }
        "antigravity" => {
            let v: Value = serde_json::from_slice(snap.part("token")?.expose()).ok()?;
            let fp = crate::adapters::antigravity_fingerprint(&v);
            (!fp.is_empty()).then_some(fp)
        }
        _ => None,
    }
}

/// The account_id a stored profile's snapshot resolves to, for matching a live
/// identity back to a profile name (A2). Reads the snapshot, not `active.json`.
fn profile_account_id(store: &Store, name: &str, tool: &str) -> Option<String> {
    let snap = store.load(name, tool).ok()??;
    snapshot_account_id(&snap, tool)
}

const MIGRATED_ACCOUNT_MARKER: &str = ".swapdex-migrated-account";

/// The account a registered slot of `name` holds, if one is readable.
fn slot_account_under(paths: &Paths, tool: &str, name: &str) -> Option<String> {
    crate::slots::Slots::open_for(paths, tool)
        .ok()
        .and_then(|sl| {
            sl.list()
                .into_iter()
                .find(|r| r.name == name)
                .and_then(|r| slot_account_id_for(tool, &r.config_dir))
        })
}

/// The account that will come to hold the name being asked for.
struct NameHolder<'a> {
    paths: &'a Paths,
    tool: &'a str,
    account_id: &'a str,
}

fn slot_account_id_for(tool: &str, dir: &std::path::Path) -> Option<String> {
    let connected = match tool {
        "claude-code" => crate::proxy::creds::slot_account_uuid(dir),
        "codex" => crate::proxy::codex::slot_account_id(dir),
        _ => None,
    };
    connected.or_else(|| {
        std::fs::read_to_string(dir.join(MIGRATED_ACCOUNT_MARKER))
            .ok()
            .map(|id| id.trim().to_string())
            .filter(|id| !id.is_empty())
    })
}

#[derive(Clone, Debug, PartialEq, Eq)]
enum MigrationClass {
    AlreadySlotted,
    CopyOfSlot(String),
    NeedsSlot,
    Unreadable,
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct MigrationProfile {
    name: String,
    account_id: Option<String>,
    class: MigrationClass,
}

fn classify_migration_profile(
    profile_name: &str,
    profile_account: Option<&str>,
    slots: &[(String, Option<String>)],
) -> MigrationClass {
    let Some(account) = profile_account.filter(|id| !id.is_empty()) else {
        return MigrationClass::Unreadable;
    };
    if slots
        .iter()
        .any(|(name, id)| name == profile_name && id.as_deref() == Some(account))
    {
        return MigrationClass::AlreadySlotted;
    }
    if let Some((name, _)) = slots.iter().find(|(_, id)| id.as_deref() == Some(account)) {
        return MigrationClass::CopyOfSlot(name.clone());
    }
    MigrationClass::NeedsSlot
}

fn classify_migrations(
    store: &Store,
    slots: &crate::slots::Slots,
    tool: &str,
) -> Vec<MigrationProfile> {
    let slot_accounts: Vec<(String, Option<String>)> = slots
        .list()
        .into_iter()
        .map(|slot| {
            let account = slot_account_id_for(tool, &slot.config_dir).filter(|id| !id.is_empty());
            (slot.name, account)
        })
        .collect();
    store
        .list()
        .into_iter()
        .filter(|profile| profile.tools.iter().any(|saved| saved == tool))
        .map(|profile| {
            let account =
                profile_account_id(store, &profile.name, tool).filter(|id| !id.is_empty());
            let class =
                classify_migration_profile(&profile.name, account.as_deref(), &slot_accounts);
            MigrationProfile {
                name: profile.name,
                account_id: account,
                class,
            }
        })
        .collect()
}

/// Find the stored profile name whose snapshot matches this live account_id.
pub(crate) fn matched_profile_name(store: &Store, tool: &str, live_id: &str) -> Option<String> {
    if live_id.is_empty() {
        return None;
    }
    store
        .list()
        .into_iter()
        .find(|p| {
            p.tools.iter().any(|t| t == tool)
                && profile_account_id(store, &p.name, tool).as_deref() == Some(live_id)
        })
        .map(|p| p.name)
}

/// Every profile holding this tool+account - refresh targets when the live
/// login (with its freshest, possibly rotated tokens) is switched away.
fn matching_profile_names(store: &Store, tool: &str, live_id: &str) -> Vec<String> {
    if live_id.is_empty() {
        return Vec::new();
    }
    store
        .list()
        .into_iter()
        .filter(|p| {
            p.tools.iter().any(|t| t == tool)
                && profile_account_id(store, &p.name, tool).as_deref() == Some(live_id)
        })
        .map(|p| p.name)
        .collect()
}

/// Reject a profile name that could escape the store (path traversal). Returns
/// the exit code to use if invalid.
fn reject_bad_name(name: &str) -> Option<i32> {
    if crate::store::valid_profile_name(name) {
        None
    } else {
        eprintln!(
            "swapdex: invalid profile name '{name}' (1-64 bytes, not all spaces; \
             no '/', '\\', leading '.', or control chars)"
        );
        Some(2)
    }
}

/// Additionally reject a leading "-" where a profile is CREATED - the same rule
/// `Slots::name_is_reserved` enforces one layer down, and for the same reasons:
/// `use -` toggles, and every remedy this tool prints reads a leading "-" as an
/// option. A legacy profile carrying one stays manageable.
fn reject_reserved_name(name: &str) -> Option<i32> {
    if name.trim().starts_with('-') {
        eprintln!(
            "swapdex: '{name}' cannot start with '-': every command that names a \
             profile reads it there as an option, and `swapdex use -` toggles to \
             the previous profile"
        );
        Some(2)
    } else if name.trim().is_empty() {
        // CREATION-time only (like '-'): a legacy all-whitespace profile from
        // 0.2.x must stay rm-able/renamable after an upgrade.
        eprintln!("swapdex: a profile name cannot be only whitespace");
        Some(2)
    } else {
        None
    }
}

pub fn add(paths: &Paths, name: Option<&str>, sel: Option<ToolSel>, update: bool) -> Result<i32> {
    crate::atomic::ensure_not_root()?;
    let store = Store::open(paths)?;
    // No name: on a terminal, suggest one from the live account (setup's flow);
    // non-interactively, error with the fix instead of a bare usage error.
    let asked;
    let name: &str = match name {
        Some(n) => n,
        None => {
            use std::io::IsTerminal;
            let tty =
                std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
            if !tty {
                eprintln!(
                    "swapdex: a profile name is required: swapdex add <name> \
                     (or run `swapdex setup` for the guided flow)"
                );
                return Ok(2);
            }
            let suggestion = suggested_profile_name(paths);
            match ask_name(
                &store,
                &format!("name for this account [{suggestion}]: "),
                &suggestion,
                None,
            ) {
                Some(n) => {
                    asked = n;
                    &asked
                }
                None => {
                    println!("nothing saved.");
                    return Ok(0);
                }
            }
        }
    };
    if let Some(c) = reject_bad_name(name).or_else(|| reject_reserved_name(name)) {
        return Ok(c);
    }
    // Take the switch lock so `add --update` can't race a `use` into a torn
    // (mismatched credentials + identity) two-file Claude snapshot.
    let _lock = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    let mut saved = Vec::new();
    let mut skipped = Vec::new();
    let mut capture_failed: Vec<&str> = Vec::new();
    let mut declined: Vec<&str> = Vec::new(); // repoint prompt answered No
    for adapter in selected_adapters(sel) {
        let tool = adapter.name();
        if !adapter.present(paths) {
            if is_explicit(sel) {
                eprintln!("swapdex: not logged in to {tool}");
                if let Some(note) = macos_keychain_note(paths, tool) {
                    eprintln!("swapdex: note - {note}");
                }
                return Ok(3);
            }
            continue;
        }
        if update {
            // Updating must not silently REPOINT the profile to a different
            // account - that changes what the name means. Same-account
            // updates (the documented stale-token refresh) pass through.
            let stored_id = profile_account_id(&store, name, tool).filter(|s| !s.is_empty());
            let live_id = adapter
                .identity(paths)
                .ok()
                .flatten()
                .map(|i| i.account_id)
                .filter(|s| !s.is_empty());
            if let (Some(stored), Some(live)) = (&stored_id, &live_id) {
                if stored != live {
                    use std::io::IsTerminal;
                    let tty = std::io::stdin().is_terminal()
                        || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
                    let msg = format!(
                        "profile '{name}' holds a different account for {tool} \
                         than the one you're logged into"
                    );
                    if !tty {
                        eprintln!("swapdex: {msg}.");
                        eprintln!(
                            "  keep both: swapdex add <new-name> --tool {}  |  really \
                             repoint: swapdex rm {name} && swapdex add {name}",
                            pretty_tool_flag(tool)
                        );
                        return Ok(7);
                    }
                    if !yes_no(
                        &format!("{msg}. Repoint '{name}' to the current login? [y/N]: "),
                        false,
                    ) {
                        println!("skipped {tool}.");
                        declined.push(tool);
                        continue;
                    }
                }
            }
        }
        if store.load(name, tool)?.is_some() && !update {
            // Explicit --tool on an already-saved tool is an error; in the
            // default case, just skip it and still attach the missing tool(s).
            if is_explicit(sel) {
                eprintln!(
                    "swapdex: profile '{name}' already has a {tool} login; pass --update to replace"
                );
                return Ok(6);
            }
            skipped.push(tool);
            continue;
        }
        // A slot holds the name as surely as a profile does: `use <name>` selects
        // it, and `ls` fills that row from the profile. Saving another account
        // under it mints the state `ls` warns about on every listing.
        let slot_id = slot_account_under(paths, tool, name);
        let live_id = adapter
            .identity(paths)
            .ok()
            .flatten()
            .map(|i| i.account_id)
            .filter(|s| !s.is_empty());
        if name_means_two_accounts(live_id.as_deref(), slot_id.as_deref()) {
            eprintln!(
                "swapdex: '{name}' is already a {tool} slot holding a different account \
                 than the one you're logged into."
            );
            eprintln!(
                "  keep both: swapdex add <new-name> --tool {}  |  free the name: \
                 swapdex rename {name} <other-name>",
                pretty_tool_flag(tool)
            );
            return Ok(7);
        }
        let snap = match adapter.capture(paths) {
            Ok(s) => s,
            Err(e) => {
                eprintln!("swapdex: {tool}: could not read the live login ({e:#}) - skipped");
                capture_failed.push(tool);
                continue;
            }
        };
        store.save(name, &snap)?;
        // The mirror of the --update guard above: that one refuses to repoint a
        // NAME at another account, while a second name on the SAME account went
        // unremarked and listed as two logins to switch between.
        if let Some(id) = snapshot_account_id(&snap, tool) {
            let twin =
                store.list().into_iter().map(|p| p.name).find(|n| {
                    n != name && profile_account_id(&store, n, tool).as_deref() == Some(&id)
                });
            if let Some(twin) = twin {
                println!("  note: that account is already saved as '{twin}'");
            }
        }
        // Surface the captured identity so a stale oauthAccount (saving 'rnd'
        // while bsgong is the live account) is caught at save, not discovered
        // later when `use` connects the wrong account.
        let email = adapter
            .identity(paths)
            .ok()
            .flatten()
            .and_then(|id| id.email);
        saved.push((tool, email));
    }
    if saved.is_empty() {
        if !declined.is_empty() {
            // The user was logged in but declined to repoint - nothing wrong,
            // nothing saved. NOT "not logged in" (exit 3 would be a lie).
            println!(
                "nothing saved for {} (you declined the repoint).",
                declined.join(", ")
            );
            return Ok(0);
        }
        if !skipped.is_empty() {
            eprintln!(
                "swapdex: profile '{name}' already has {}; pass --update to replace",
                skipped.join(", ")
            );
            return Ok(6);
        }
        if !capture_failed.is_empty() {
            // present() said the login IS there but capture failed - a corrupt
            // or unreadable live login (a hand-edited ~/.claude.json with a
            // JSON syntax error is the common one), NOT "not logged in". The
            // per-tool error above carries the fix; this is a hard error (1),
            // never exit 3 (which would send the user to re-log-in in vain).
            eprintln!(
                "swapdex: nothing saved - the live login for {} is present but could not be \
                 read (see the error above)",
                capture_failed.join(", ")
            );
            return Ok(1);
        }
        eprintln!("swapdex: not logged in to any selected tool");
        return Ok(3);
    }
    let note = if skipped.is_empty() {
        String::new()
    } else {
        format!(
            " ({} already saved; --update to replace)",
            skipped.join(", ")
        )
    };
    let saved_disp = saved
        .iter()
        .map(|(tool, email)| match email {
            Some(e) => format!("{tool} = {e}"),
            None => tool.to_string(),
        })
        .collect::<Vec<_>>()
        .join(", ");
    println!("saved profile '{name}' ({saved_disp}){note}");
    if !capture_failed.is_empty() {
        eprintln!(
            "swapdex: {} tool(s) could not be read and were NOT saved: {}",
            capture_failed.len(),
            capture_failed.join(", ")
        );
    }
    if name.contains(char::is_whitespace) {
        println!(
            "note: the name has spaces - quote it in later commands (`swapdex use \"{name}\"`)"
        );
    }
    Ok(if capture_failed.is_empty() { 0 } else { 1 })
}

/// Whether a name-detectable, non-slotted tool (codex/gemini/antigravity) has a
/// live process - the rotation-logout guard input. A dry-run and SWAPDEX_ROOT
/// never scan real processes (an isolated root's credentials are not the ones a
/// real session uses); under SWAPDEX_ROOT a test hook names the tools to treat
/// as running, e.g. `SWAPDEX_TEST_RUNNING=codex,gemini`.
fn tool_session_running(tool: &str, running: &[String], dry_run: bool) -> bool {
    if dry_run {
        return false;
    }
    if std::env::var_os("SWAPDEX_ROOT").is_some() {
        return std::env::var("SWAPDEX_TEST_RUNNING")
            .map(|v| v.split(',').any(|t| t.trim() == tool))
            .unwrap_or(false);
    }
    crate::proc::tool_running(tool, running)
}

pub fn use_account(
    paths: &Paths,
    name: &str,
    sel: Option<ToolSel>,
    dry_run: bool,
    force: bool,
) -> Result<i32> {
    use_account_switch(paths, name, sel, dry_run, force, false, None)
}

/// The switch itself, with or without a launch after it. `--open` had its own
/// copy of this, which asked the snapshot store alone: it rejected the
/// slot-only accounts `use` switches fine, and for an account holding both a
/// slot and a snapshot it copied a credential over the slot it should have
/// repointed.
#[allow(clippy::too_many_arguments)]
fn use_account_switch(
    paths: &Paths,
    name: &str,
    sel: Option<ToolSel>,
    dry_run: bool,
    force: bool,
    open: bool,
    open_dir: Option<&std::path::Path>,
) -> Result<i32> {
    // Permanent-slot account: `use` just repoints that tool's default pointer
    // (the shim follows it) - no credential copy, so no rotation logout. EVERY
    // selected registry is asked, not Claude's alone: `ls` draws one row per
    // account across all of them, so asking one left a Codex-only account
    // listed and then rejected as "no profile named".
    // Resolve the NAME first: a prefix or `-` names an account, and asking the
    // registries about the raw argument answered for a name nobody has - which
    // sent an account that owns a slot down the copy-model path instead.
    let store = Store::open(paths)?;
    let name = match resolve_use_name(&store, paths, name, sel)? {
        Some(n) => n,
        None => return Ok(5),
    };
    let name = name.as_str();
    let wanted = |t: &str| sel.map(|s| s.wants(t)).unwrap_or(true);
    let held: Vec<&'static str> = crate::adapters::names()
        .into_iter()
        .filter(|t| wanted(t))
        .filter(|t| {
            crate::slots::Slots::open_for(paths, t)
                .map(|s| s.get(name).is_some())
                .unwrap_or(false)
        })
        .collect();
    let mut code = 0;
    if held.is_empty() {
        // A legacy copy-model profile (in no slot registry) falls through to
        // the old guarded switch.
        code = use_account_inner(paths, name, sel, dry_run, force, &[])?;
    }
    for tool in &held {
        let c = use_slot_default(paths, name, tool, dry_run)?;
        if c != 0 {
            code = c;
        }
    }
    if !held.is_empty() {
        // A name can be a slot under one tool and a saved profile under
        // another, and `ls` draws that as one row. Fall through only when the
        // profile covers a tool no slot took: otherwise the copy-model switch
        // matches nothing and reports the account it just moved as unknown.
        // `held` is passed as skips - a credential copy onto a slot is what the
        // slot model exists to prevent.
        let rest: Vec<&str> = crate::adapters::names()
            .into_iter()
            .filter(|t| wanted(t) && !held.contains(t))
            .collect();
        let spans_more = store
            .list()
            .iter()
            .any(|p| p.name == name && p.tools.iter().any(|t| rest.contains(&t.as_str())));
        if spans_more {
            let c = use_account_inner(paths, name, sel, dry_run, force, &held)?;
            if c != 0 {
                code = c;
            }
        }
    }
    // The launch belongs after the whole switch, and only to a switch that
    // worked: a tool that failed to switch would otherwise open on the account
    // the user was leaving.
    if open && code == 0 {
        if let Some(adapter) = selected_adapters(sel).into_iter().next() {
            let tool = adapter.name();
            println!("opening {}...", pretty_tool(tool));
            return Err(exec_tool(tool, open_dir));
        }
    }
    Ok(code)
}

/// `open`: after a successful switch, exec the tool (the --open flag; needs an
/// explicit --tool so there is never a guess about WHICH conversation opens).
pub fn use_account_open(
    paths: &Paths,
    name: &str,
    sel: Option<ToolSel>,
    dir: Option<&std::path::Path>,
    force: bool,
) -> Result<i32> {
    if !is_explicit(sel) {
        eprintln!("swapdex: --open needs --tool <claude|codex|gemini|antigravity> so it knows what to launch");
        return Ok(2);
    }
    if let Some(d) = dir {
        if !d.is_dir() {
            eprintln!("swapdex: --dir is not a directory: {}", d.display());
            return Ok(2);
        }
    }
    use_account_switch(paths, name, sel, false, force, true, dir)
}

/// `skip`: tools this switch has already handled as slots, so the copy-model
/// path leaves them alone.
fn use_account_inner(
    paths: &Paths,
    name: &str,
    sel: Option<ToolSel>,
    dry_run: bool,
    force: bool,
    skip: &[&str],
) -> Result<i32> {
    crate::atomic::ensure_not_root()?;
    let store = Store::open(paths)?;
    // Resolve the NAME first: `-` toggles to the previous/other profile and a
    // unique prefix expands, so the daily switch is two keystrokes.
    let name = match resolve_use_name(&store, paths, name, sel)? {
        Some(n) => n,
        None => return Ok(5),
    };
    let name = name.as_str();
    if let Some(c) = reject_bad_name(name) {
        return Ok(c);
    }
    let _lock = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    // A typo must be ONE line, not four "left unchanged" notes implying the
    // profile exists but lacks those tools.
    if !store.list().iter().any(|p| p.name == name) {
        eprintln!("swapdex: no profile named '{name}'");
        return Ok(5);
    }
    let mut matched = 0; // profile had a snapshot for this tool
    let mut changed = 0; // an actual switch was written
    let mut failed: Vec<&str> = Vec::new(); // tools whose switch errored

    // Snapshot running processes once (best-effort) so we can warn if a switch
    // pulls the login out from under a live session. Skipped on a dry-run.
    // Skip the scan on a dry-run, and under SWAPDEX_ROOT: an isolated root's
    // credentials are not the ones any running session uses, so the warning
    // would be a false positive there.
    let running = if dry_run || std::env::var_os("SWAPDEX_ROOT").is_some() {
        Vec::new()
    } else {
        crate::proc::running_process_names()
    };
    // Pre-switch guard for Claude: swapping the login slot while a `claude`
    // session is using THAT slot both clobbers the incoming login AND revokes
    // the outgoing account's just-saved snapshot on the session's next token
    // refresh (Claude's refresh tokens rotate - the saved copy dies). Compute
    // the verdict once (a process scan); enforced per-tool below unless --force.
    // Skipped on a dry-run and under SWAPDEX_ROOT (no real sessions in play).
    let claude_guard = if dry_run {
        crate::proc::GuardVerdict::Clear
    } else if std::env::var_os("SWAPDEX_ROOT").is_some() {
        // Sandbox: never scan real processes (they are not the ones an isolated
        // root's credentials belong to). A test hook - honored ONLY here - can
        // inject a verdict to exercise the enforcement path.
        match std::env::var("SWAPDEX_TEST_CLAUDE_GUARD").ok().as_deref() {
            Some("same-slot") => crate::proc::GuardVerdict::SameSlot,
            Some("unknown") => crate::proc::GuardVerdict::Unknown,
            _ => crate::proc::GuardVerdict::Clear,
        }
    } else {
        crate::proc::claude_switch_guard(
            std::env::var("CLAUDE_SECURESTORAGE_CONFIG_DIR")
                .ok()
                .as_deref(),
            std::env::var("CLAUDE_CONFIG_DIR").ok().as_deref(),
            std::env::var("HOME").ok().as_deref(),
            &crate::proc::running_claude_procs(),
        )
    };
    // One shared timestamp for every tool this invocation switches, so a later
    // bare `restore` can identify exactly this switch's tool set.
    let switch_ts = now_secs();
    let switch_inv = now_nanos();
    for adapter in selected_adapters(sel) {
        let tool = adapter.name();
        // Already repointed as a slot: copying a credential over it would undo
        // the very thing the slot model buys.
        if skip.contains(&tool) {
            continue;
        }
        // A Keychain-mode Claude install (macOS) cannot be switched yet. In
        // the default both-tools case SKIP it with a note so Codex still
        // switches; the adapter's own refusal stays for an explicit --tool.
        if !is_explicit(sel) && macos_keychain_note(paths, tool).is_some() {
            println!(
                "{tool}: skipped - the login lives in the macOS Keychain \
                 (github.com/youdie006/swapdex/issues/1); other tools continue"
            );
            continue;
        }
        let target = match store.load(name, tool)? {
            Some(s) => s,
            None => {
                if is_explicit(sel) {
                    eprintln!("swapdex: profile '{name}' has no {tool} login");
                    return Ok(5);
                }
                // Not an error in the default case, but if the user IS logged
                // into this tool, say so - a silent partial switch reads as a
                // full one and leaves the old account active unnoticed.
                if adapter.present(paths) {
                    println!("{tool}: profile '{name}' has no {tool} login - left unchanged");
                }
                continue;
            }
        };
        matched += 1;
        // Already-active is a no-op success. Ignore EMPTY ids: two accounts with
        // no account_id must never compare equal, or the switch would be skipped
        // and the WRONG account silently kept active. An UNREADABLE live file is
        // treated as unknown (not an abort): `use <good-profile>` is exactly the
        // command that can replace a corrupt login.
        let live = adapter.identity(paths).ok().flatten();
        let live_id = live
            .as_ref()
            .map(|i| i.account_id.clone())
            .filter(|s| !s.is_empty());
        let target_id = profile_account_id(&store, name, tool).filter(|s| !s.is_empty());
        if live_id.is_some() && live_id == target_id {
            println!("{tool}: '{name}' is already active");
            // Still a sync point: the live login IS this profile's account
            // and its tokens may have rotated since the last save. No backup
            // is needed. A timeline event is written only when this selection
            // ends a serving override and therefore changes who pays.
            if !dry_run {
                if let (Ok(snap), Some(id)) = (adapter.capture(paths), &live_id) {
                    for pname in matching_profile_names(&store, tool, id) {
                        store.save(&pname, &snap)?;
                    }
                }
                if clear_serving_choice(paths, tool)? {
                    store.append_timeline_inv(tool, name, "use", switch_ts, switch_inv)?;
                    changed += 1;
                }
            }
            continue;
        }
        warn_if_expired(&target, tool);
        // A retired token is not a stale one: restoring it does not give a
        // worse login, it gives a dead one, and the tool discovers that only
        // when its next renewal is refused.
        if snapshot_rotated_away(paths, &target, tool) {
            eprintln!(
                "swapdex: {tool}: this saved login's refresh token was retired when another \
                 holder of the same account renewed it - these tokens are single-use, so the \
                 copy that missed a renewal is dead. Restoring it would leave {tool} unable to \
                 renew. Switch to the slot that holds the current token, or sign in again and \
                 re-save with `swapdex add {name} --tool {} --update`.",
                pretty_tool_flag(tool)
            );
            failed.push(tool);
            continue;
        }
        if dry_run {
            match profile_detail(&store, name, tool).and_then(|(email, _, _)| email) {
                Some(email) => println!("would switch {tool} -> {name} ({email})"),
                None => println!("would switch {tool} -> {name}"),
            }
            continue;
        }
        // Pre-switch guard (Claude only): refuse to swap the slot while a claude
        // session is using it, or when a running session's slot is unknown
        // (fail closed). Doing so would clobber the incoming login and, on the
        // session's next refresh, revoke the outgoing account's snapshot ->
        // a later switch-back logs it out. `--force` overrides.
        if tool == "claude-code" && !force {
            match claude_guard {
                crate::proc::GuardVerdict::SameSlot => {
                    eprintln!(
                        "swapdex: {tool}: a Claude session is running on THIS login slot. \
                         Switching now would log that account out on its next token refresh \
                         (the refresh token rotates and the saved copy is revoked). Quit that \
                         `claude` and retry, or `swapdex use {name} --tool claude --force` to \
                         switch anyway."
                    );
                    failed.push(tool);
                    continue;
                }
                crate::proc::GuardVerdict::Unknown => {
                    eprintln!(
                        "swapdex: {tool}: a Claude session is running but swapdex could not read \
                         which login slot it uses, so it can't rule out that switching would log \
                         it out. Quit `claude` and retry, or `--force` to switch anyway."
                    );
                    failed.push(tool);
                    continue;
                }
                crate::proc::GuardVerdict::Clear => {}
            }
        }
        // Pre-switch rotation-logout guard for the NON-slotted tools (codex,
        // gemini, antigravity), the running-session analog of Claude's guard.
        // They all rotate their OAuth token on refresh, and swapdex swaps their
        // shared credential files - so switching while the tool runs lets that
        // session's next refresh revoke the account being switched, logging it
        // out (e.g. a `codex` MCP server used from Claude). Claude is slot-
        // isolated and guarded above. Detection is by process name (no slot);
        // --force overrides.
        if matches!(tool, "codex" | "gemini" | "antigravity")
            && !force
            && tool_session_running(tool, &running, dry_run)
        {
            eprintln!(
                "swapdex: {tool}: a running {tool} session was detected. {tool} rotates its \
                 OAuth token on refresh, so switching now can log that account out on the \
                 session's next refresh. Quit it and retry, or `swapdex use {name} --tool \
                 {} --force` to switch anyway.",
                pretty_tool_flag(tool)
            );
            failed.push(tool);
            continue;
        }
        // Exclude a concurrent `login` mid-sign-in on THIS tool: it holds the
        // per-tool credential lock across its interactive wait (while the store
        // lock is free), so switching now would race its sign-out/capture. Skip
        // this tool, keep switching the others. Held for the rest of this tool's
        // credential work.
        let _cred_lock = match store.lock_tool(tool) {
            Ok(g) => g,
            Err(_) => {
                eprintln!(
                    "swapdex: {tool}: a `swapdex login` is signing this tool in right now; \
                     skipped. Retry after it finishes."
                );
                failed.push(tool);
                continue;
            }
        };
        // Safe order (A6): back up the CURRENT live login first (atomic + fsync
        // inside write_secret); if the backup fails, `?` aborts BEFORE we touch
        // the live login. An unreadable live file only skips its own backup -
        // there is nothing usable to save.
        if adapter.present(paths) {
            match adapter.capture(paths) {
                Ok(live_snap) => {
                    store.backup(&live_snap)?;
                    // Refresh tokens ROTATE while an account is in use, so a
                    // profile snapshot goes stale the moment you work on that
                    // account. Write the live capture (the freshest known
                    // tokens) back into every profile holding this account -
                    // otherwise switching back later restores a refresh token
                    // the provider may have already revoked.
                    if let Some(id) = &live_id {
                        for pname in matching_profile_names(&store, tool, id) {
                            store.save(&pname, &live_snap)?;
                        }
                        if matched_profile_name(&store, tool, id).is_none() {
                            let who = live
                                .as_ref()
                                .map(identity_line)
                                .unwrap_or_else(|| "current".into());
                            eprintln!(
                                "swapdex: note - the outgoing {tool} login ({who}) is not \
                                 saved as a profile; only the last 2 backups keep it. \
                                 `swapdex restore` undoes this switch; `swapdex add <name>` \
                                 would keep it for good."
                            );
                        }
                    }
                }
                Err(e) if live.is_some() => {
                    // identity() SUCCEEDED but capture() failed: the login is
                    // valid and recoverable, only a sibling file is corrupt (a
                    // hand-edited ~/.claude.json, or a Gemini
                    // google_accounts.json). Applying now would OVERWRITE a
                    // recoverable login with NO backup - a lost login. Refuse
                    // for this tool (the others still switch) and point at the
                    // repair.
                    eprintln!(
                        "swapdex: {tool}: the current login is present but could not be backed \
                         up ({e:#}) - refusing to overwrite it without a backup. Repair the file \
                         named above (or re-login), then retry."
                    );
                    failed.push(tool);
                    continue;
                }
                Err(e) => eprintln!(
                    // identity() ALSO failed: the live login is genuinely
                    // broken (its primary credential is unparseable), so there
                    // is nothing recoverable to preserve - switching in a good
                    // profile IS the fix. Proceed, warning about the skipped
                    // backup.
                    "swapdex: note - the current {tool} login could not be read ({e:#}); \
                     switching without a backup of it"
                ),
            }
        }
        if let Err(e) = adapter.apply(paths, &target) {
            // Do NOT abort the whole multi-tool switch: the other tools can
            // still switch; a summary at the end says what failed.
            eprintln!(
                "swapdex: {tool}: switch failed - {:#}\n  (if the error is about the \
                 SNAPSHOT: log in to that account and re-save with `swapdex add {name} \
                 --tool {} --update`)",
                e,
                pretty_tool_flag(tool)
            );
            failed.push(tool);
            continue;
        }
        clear_serving_choice(paths, tool)?;
        store.append_timeline_inv(tool, name, "use", switch_ts, switch_inv)?;
        if let Some(id) = adapter.identity(paths).ok().flatten() {
            println!("switched {tool} -> {}", identity_line(&id));
        }
        if crate::proc::tool_running(tool, &running) {
            eprintln!(
                "swapdex: note - a {tool} session looks like it's running. Restart it \
                 to use '{name}'; a live session can overwrite the switched login on \
                 its next token refresh."
            );
        }
        changed += 1;
    }
    if matched == 0 {
        eprintln!("swapdex: no profile named '{name}'");
        return Ok(5);
    }
    // Only when a login was actually written - not for a no-op or a dry-run.
    if changed > 0 {
        println!("(takes effect on your next message)");
    }
    if !failed.is_empty() {
        eprintln!(
            "swapdex: {} tool(s) failed to switch ({}); the tools above did switch - \
             `swapdex restore` undoes this switch entirely",
            failed.len(),
            failed.join(", ")
        );
        return Ok(1);
    }
    Ok(0)
}

/// `restore` - put back the login that was live before the last switch. `use`
/// backs up the outgoing login before every switch; this is the command that
/// brings a backup back, so a bad switch is a one-command recovery even when
/// the outgoing account was never saved as a profile. It backs up the current
/// login first, so running `restore` twice toggles between the two. A slot
/// switch moves no credential, so its undo is repointing the default back.
pub fn restore(paths: &Paths, sel: Option<ToolSel>, dry_run: bool) -> Result<i32> {
    crate::atomic::ensure_not_root()?;
    let store = Store::open(paths)?;
    let _lock = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    // Skip the scan on a dry-run, and under SWAPDEX_ROOT: an isolated root's
    // credentials are not the ones any running session uses, so the warning
    // would be a false positive there.
    let running = if dry_run || std::env::var_os("SWAPDEX_ROOT").is_some() {
        Vec::new()
    } else {
        crate::proc::running_process_names()
    };
    // Bare `restore` means "undo the LAST SWITCH" - scope it to the tool(s)
    // that switch touched, or a codex-only undo would also rewind claude-code
    // to some older, unrelated backup.
    let last_switch = last_switch_tools(paths);
    let restore_ts = now_secs();
    let restore_inv = now_nanos();
    let mut found = 0; // a backup existed for this tool
    let mut changed = 0; // an actual restore was written
    let mut repointed = 0; // a slot switch was put back (no credential moved)
    for adapter in selected_adapters(sel) {
        let tool = adapter.name();
        if !is_explicit(sel) {
            if let Some(tools) = &last_switch {
                if !tools.iter().any(|t| t == tool) {
                    continue;
                }
            }
            // Keychain-mode Claude (macOS): skip with a note, keep restoring
            // the other tool (mirror of the `use` skip).
            if macos_keychain_note(paths, tool).is_some() {
                println!(
                    "{tool}: skipped - the login lives in the macOS Keychain \
                     (github.com/youdie006/swapdex/issues/1); other tools continue"
                );
                continue;
            }
        }
        // A slot switch moved a pointer, not a credential, so its undo is
        // repointing the default back. The newest credential backup belongs to
        // some OLDER copy-model switch: reaching for it here would leave the
        // slot switch standing and write a third account over the live login.
        let names = switch_names_for(paths, tool);
        let last_dest = names.last().cloned().unwrap_or_default();
        let slot_undo = crate::slots::Slots::open_for(paths, tool)
            .ok()
            .filter(|s| !last_dest.is_empty() && s.get(&last_dest).is_some());
        if let Some(slots) = slot_undo {
            let bin = tool_binary(tool);
            let prev = names
                .iter()
                .rev()
                .skip(1)
                .find(|n| **n != last_dest && slots.get(n).is_some());
            let Some(prev) = prev else {
                eprintln!(
                    "swapdex: {tool}: the last switch repointed the default to {last_dest}, \
                     and no earlier slot is on record to put back"
                );
                if is_explicit(sel) {
                    return Ok(5);
                }
                repointed += 1;
                continue;
            };
            if dry_run {
                println!("would put the default {bin} account back to {prev}");
                repointed += 1;
                continue;
            }
            slots.set_default(prev)?;
            store.append_timeline_inv(tool, prev, "restore", restore_ts, restore_inv)?;
            println!(
                "{}",
                switch_outcome_line(
                    tool,
                    prev,
                    crate::proxy::running_proxy_for(paths, tool).is_some(),
                    crate::slots::history_is_shared(paths, tool)
                )
            );
            repointed += 1;
            continue;
        }
        let Some((stamp, target)) = store.load_backup(tool)? else {
            if is_explicit(sel) {
                eprintln!("swapdex: no backup for {tool} (a backup is taken on every `use`)");
                return Ok(5);
            }
            continue;
        };
        found += 1;
        // Restoring the already-live account is a no-op success. An unreadable
        // live file is treated as unknown, not an abort - restore is the
        // disaster-recovery command.
        let live_id = adapter
            .identity(paths)
            .ok()
            .flatten()
            .map(|i| i.account_id)
            .filter(|s| !s.is_empty());
        let backup_id = snapshot_account_id(&target, tool).filter(|s| !s.is_empty());
        if live_id.is_some() && live_id == backup_id {
            println!("{tool}: the newest backup is already the active login");
            if !dry_run && clear_serving_choice(paths, tool)? {
                let event_name = backup_id
                    .as_deref()
                    .and_then(|id| matched_profile_name(&store, tool, id))
                    .unwrap_or_else(|| "(backup)".into());
                store.append_timeline_inv(tool, &event_name, "restore", restore_ts, restore_inv)?;
                changed += 1;
            }
            continue;
        }
        let age = age_line(stamp);
        if dry_run {
            println!("would restore {tool} from the backup taken {age}");
            continue;
        }
        // Same per-tool credential lock as `use`: a `login` mid-sign-in on this
        // tool holds it across its interactive wait, so restoring now would race
        // its sign-out/capture. Skip this tool, keep restoring the others.
        let _cred_lock = match store.lock_tool(tool) {
            Ok(g) => g,
            Err(_) => {
                eprintln!(
                    "swapdex: {tool}: a `swapdex login` is signing this tool in right now; \
                     skipped. Retry after it finishes."
                );
                continue;
            }
        };
        // Capture the CURRENT login first, but do NOT back it up yet: if
        // apply(target) fails, backing it up now would make it the NEWEST backup,
        // and a retry would see it as "already active" - stranding the very
        // backup we were asked to restore. Promote it only after apply succeeds.
        let live_snap = if adapter.present(paths) {
            match adapter.capture(paths) {
                Ok(s) => Some(s),
                Err(e) => {
                    eprintln!(
                        "swapdex: note - the current {tool} login could not be read ({e:#}); \
                         restoring without a backup of it"
                    );
                    None
                }
            }
        } else {
            None
        };
        // The same two questions `use` asks of a snapshot before applying it.
        // `use` refuses a retired token; this one restores anyway and says so,
        // because `restore` is the escape hatch and refusing to undo leaves
        // somebody with nowhere to go. Putting a dead credential back silently
        // is the part that is not acceptable: it replaces a working login with
        // one that cannot renew, and reports success.
        warn_if_expired(&target, tool);
        if snapshot_rotated_away(paths, &target, tool) {
            eprintln!(
                "swapdex: {tool}: this backup's refresh token was retired when another holder \
                 of the same account renewed it - these tokens are single-use. The account is \
                 going back, but it will need a fresh sign-in before it can renew \
                 (`swapdex run <name>` signs a slot in)."
            );
        }
        adapter.apply(paths, &target)?;
        clear_serving_choice(paths, tool)?;
        // apply(target) succeeded: NOW it is safe to record the outgoing login as
        // a backup (so `restore` toggles back) and refresh its profile(s) with
        // its freshest tokens - the same rotation invariant as `use`.
        if let Some(live_snap) = &live_snap {
            store.backup(live_snap)?;
            if let Some(id) = &live_id {
                for pname in matching_profile_names(&store, tool, id) {
                    store.save(&pname, live_snap)?;
                }
            }
        }
        // Attribute the timeline event to the restored account's profile name
        // when one matches, or `sessions` would blame "(backup)" forever after.
        let restored = adapter.identity(paths).ok().flatten();
        let event_name = restored
            .as_ref()
            .and_then(|id| matched_profile_name(&store, tool, &id.account_id))
            .unwrap_or_else(|| "(backup)".into());
        store.append_timeline_inv(tool, &event_name, "restore", restore_ts, restore_inv)?;
        match restored {
            Some(id) => println!("restored {tool} -> {} (backup {age})", identity_line(&id)),
            None => println!("restored {tool} from the backup taken {age}"),
        }
        if crate::proc::tool_running(tool, &running) {
            eprintln!(
                "swapdex: note - a {tool} session looks like it's running. Restart it \
                 to pick up the restored login."
            );
        }
        changed += 1;
    }
    if found == 0 && repointed == 0 {
        eprintln!("swapdex: no backup to restore (a backup is taken on every `use`)");
        return Ok(5);
    }
    if changed > 0 {
        println!("(takes effect on your next message)");
    }
    Ok(0)
}

/// Every account `use` can name: the saved profiles plus each selected tool's
/// registered slots. `ls` draws one row per account across both registries, so
/// resolution has to see both - drawing candidates from the store alone left a
/// slot-only owner's prefix and `-` rejected as a profile that does not exist.
fn use_candidates(store: &Store, paths: &Paths, sel: Option<ToolSel>) -> Vec<String> {
    let mut names: Vec<String> = store.list().into_iter().map(|p| p.name).collect();
    for tool in crate::adapters::names() {
        if !sel.map(|s| s.wants(tool)).unwrap_or(true) {
            continue;
        }
        if let Ok(slots) = crate::slots::Slots::open_for(paths, tool) {
            names.extend(slots.list().into_iter().map(|r| r.name));
        }
    }
    names.sort();
    names.dedup();
    names
}

/// Resolve `use`'s NAME argument. `-` means "the profile I was on before":
/// with exactly two profiles it is simply the other one; otherwise the most
/// recent timeline switch to a profile that is not currently active. A unique
/// prefix expands (`use w` -> work); an ambiguous one refuses and lists the
/// candidates rather than guessing (switching is a write). `Ok(None)` means
/// "already reported, exit 5".
fn resolve_use_name(
    store: &Store,
    paths: &Paths,
    raw: &str,
    sel: Option<ToolSel>,
) -> Result<Option<String>> {
    // An empty name (an unset shell variable) must fall through to the
    // invalid-name rejection: every string starts with "", so prefix matching
    // would otherwise "uniquely" match a single-profile store and switch.
    if raw.is_empty() {
        return Ok(Some(raw.to_string()));
    }
    let profiles = use_candidates(store, paths, sel);
    if raw == "-" {
        // Scope "previous" to the selected tool(s): `use - --tool codex` asks
        // about codex history, not claude's.
        let mut act: Vec<String> = active_by_tool(store, paths)
            .into_iter()
            .filter(|(t, _)| sel.map(|s| s.wants(t)).unwrap_or(true))
            .map(|(_, n)| n)
            .collect();
        act.sort();
        act.dedup();
        // The overwhelmingly common case: two profiles, one active.
        if profiles.len() == 2 && act.len() == 1 {
            if let Some(other) = profiles.iter().find(|p| **p != act[0]) {
                eprintln!("swapdex: '-' -> '{other}'");
                return Ok(Some(other.clone()));
            }
        }
        // Otherwise: the most recent switch to a profile that is neither
        // active now nor the destination of the newest switch (when the live
        // identity is unreadable, that newest destination IS the current
        // profile - excluding it keeps '-' from re-picking where you already
        // are).
        if let Some(prev) = last_switch_name_excluding(paths, &act, &profiles, sel) {
            eprintln!("swapdex: '-' -> '{prev}'");
            return Ok(Some(prev));
        }
        if act.len() > 1 {
            eprintln!(
                "swapdex: both profiles are active ({}) - '-' is ambiguous here; \
                 say which: swapdex use <{}>",
                act.join(", "),
                profiles.join("|")
            );
        } else {
            eprintln!(
                "swapdex: can't tell which profile '-' means yet. \
                 Pick one: swapdex use <{}>",
                profiles.join("|")
            );
        }
        return Ok(None);
    }
    if profiles.iter().any(|p| p == raw) {
        return Ok(Some(raw.to_string()));
    }
    let cands: Vec<&String> = profiles.iter().filter(|p| p.starts_with(raw)).collect();
    match cands.len() {
        1 => {
            let n = cands[0].clone();
            eprintln!("swapdex: '{raw}' matched profile '{n}'");
            Ok(Some(n))
        }
        // No prefix match: fall through so the normal "no profile" error runs.
        0 => Ok(Some(raw.to_string())),
        _ => {
            eprintln!(
                "swapdex: '{raw}' is ambiguous: {}",
                cands
                    .iter()
                    .map(|s| s.as_str())
                    .collect::<Vec<_>>()
                    .join(", ")
            );
            Ok(None)
        }
    }
}

/// The most recent `use`/`restore` timeline entry naming a profile that still
/// exists and is not in `exclude` - i.e. "the profile you were on before".
/// The destination of the NEWEST switch is also excluded (it is where you are
/// now, even when the live identity cannot be read), and `sel` scopes which
/// tools' events count.
fn last_switch_name_excluding(
    paths: &Paths,
    exclude: &[String],
    profiles: &[String],
    sel: Option<ToolSel>,
) -> Option<String> {
    let text = std::fs::read_to_string(paths.store_dir().join("timeline.jsonl")).ok()?;
    let mut events: Vec<(i64, String)> = Vec::new();
    for line in text.lines() {
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        if !matches!(v["action"].as_str(), Some("use") | Some("restore")) {
            continue;
        }
        if let Some(tool) = v["tool"].as_str() {
            if !sel.map(|s| s.wants(tool)).unwrap_or(true) {
                continue;
            }
        }
        let (Some(ts), Some(name)) = (v["ts"].as_i64(), v["account"].as_str()) else {
            continue;
        };
        events.push((ts, name.to_string()));
    }
    // Where the newest switch went = where you are now; never "toggle" there.
    let newest = events
        .iter()
        .max_by_key(|(ts, _)| *ts)
        .map(|(_, n)| n.clone());
    let mut best: Option<(i64, String)> = None;
    for (ts, name) in events {
        if exclude.contains(&name)
            || newest.as_deref() == Some(name.as_str())
            || !profiles.contains(&name)
        {
            continue;
        }
        if best.as_ref().map(|(t, _)| ts >= *t).unwrap_or(true) {
            best = Some((ts, name.to_string()));
        }
    }
    best.map(|(_, n)| n)
}

/// The `use`/`restore` destinations recorded for one tool, oldest first.
fn switch_names_for(paths: &Paths, tool: &str) -> Vec<String> {
    let path = paths.store_dir().join("timeline.jsonl");
    let Ok(text) = std::fs::read_to_string(path) else {
        return Vec::new();
    };
    text.lines()
        .filter_map(|line| serde_json::from_str::<Value>(line).ok())
        .filter(|v| matches!(v["action"].as_str(), Some("use") | Some("restore")))
        .filter(|v| v["tool"].as_str() == Some(tool))
        .filter_map(|v| v["account"].as_str().map(str::to_string))
        .collect()
}

/// The tool(s) the most recent switch (`use` or `restore`) touched, from the
/// timeline. Every tool of one invocation is written with the SAME ts
/// (append_timeline_at), so strict ts equality identifies the invocation.
/// None when no switch is on record - the caller falls back to every tool.
fn last_switch_tools(paths: &Paths) -> Option<Vec<String>> {
    let path = paths.store_dir().join("timeline.jsonl");
    let text = std::fs::read_to_string(path).ok()?;
    let mut events: Vec<(i64, String, String)> = Vec::new();
    for line in text.lines() {
        let Ok(v) = serde_json::from_str::<Value>(line) else {
            continue;
        };
        if !matches!(v["action"].as_str(), Some("use") | Some("restore")) {
            continue;
        }
        if let (Some(ts), Some(tool)) = (v["ts"].as_i64(), v["tool"].as_str()) {
            let inv = v["inv"].as_str().unwrap_or("").to_string();
            events.push((ts, inv, tool.to_string()));
        }
    }
    // Group by the last event's INVOCATION id when it has one - whole-second
    // ts equality collides when two separate invocations run inside one
    // second. Legacy events (no inv) fall back to ts grouping.
    let (last_ts, last_inv) = events
        .iter()
        .map(|(ts, inv, _)| (*ts, inv.clone()))
        .next_back()?;
    let mut tools: Vec<String> = events
        .into_iter()
        .filter(|(ts, inv, _)| {
            if last_inv.is_empty() {
                *ts == last_ts && inv.is_empty()
            } else {
                *inv == last_inv
            }
        })
        .map(|(_, _, tool)| tool)
        .collect();
    tools.sort();
    tools.dedup();
    Some(tools)
}

/// "3m ago" / "2h ago" from a unix-nanos backup stamp.
fn age_line(stamp_nanos: u128) -> String {
    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let secs = (now.saturating_sub(stamp_nanos) / 1_000_000_000) as u64;
    if secs < 60 {
        format!("{secs}s ago")
    } else if secs < 3600 {
        format!("{}m ago", secs / 60)
    } else if secs < 86400 {
        format!("{}h ago", secs / 3600)
    } else {
        format!("{}d ago", secs / 86400)
    }
}

/// A saved snapshot ages out even before its access token expires, because the
/// refresh token can rotate; flag one that has not been refreshed in a while.
const STALE_DAYS: i64 = 30;

/// One name, two different accounts: the saved profile holds one and the slot
/// registered under that same name holds another.
///
/// It matters because the two are not interchangeable. `use <name>` moves the
/// slot pointer, so the account it selects is the SLOT's, while the listing
/// fills that row from the profile's snapshot - the row names one account and
/// switching produces the other. Unknown on either side is not a conflict:
/// swapdex does not condemn a pairing it could not read.
fn name_means_two_accounts(profile: Option<&str>, slot: Option<&str>) -> bool {
    matches!((profile, slot), (Some(a), Some(b)) if a != b)
}

/// Is a login's access token old enough for its lapse to mean anything?
///
/// A Claude access token lives about an hour and the tool refreshes it silently,
/// so "expired the moment it lapsed" is true for most of every hour and says
/// nothing about whether the account works - `ls`'s marker calls that "the
/// constant expired spam" and `status`'s note says the same. Past STALE_DAYS the
/// refresh token itself may be gone, which is worth reporting. `None` stays
/// None: a login with no deadline on it is not condemned.
fn login_is_ancient(expires_at_ms: Option<i64>, now_ms: i64) -> Option<bool> {
    expires_at_ms.map(|ms| now_ms - ms > STALE_DAYS * 86400 * 1000)
}

/// When a stored snapshot was last refreshed, in unix seconds.
///
/// Every tool records it somewhere different, and each reader used to work that
/// out for itself: `ls` marked all four "stale" past STALE_DAYS while the switch
/// warned about Claude alone, so `use` installed a login whose refresh token may
/// be long revoked and said only "switched".
fn snapshot_refreshed_at(snap: &crate::adapters::Snapshot, tool: &str) -> Option<i64> {
    let part = |n: &str| {
        snap.part(n)
            .and_then(|b| serde_json::from_slice::<Value>(b.expose()).ok())
    };
    match tool {
        "claude-code" => part("credentials")?["claudeAiOauth"]["expiresAt"]
            .as_i64()
            .map(|ms| ms / 1000),
        "codex" => part("auth")?["last_refresh"]
            .as_str()
            .and_then(crate::session_link::rfc3339_to_secs),
        "gemini" => part("oauth")?["expiry_date"].as_i64().map(|ms| ms / 1000),
        "antigravity" => part("token")?["token"]["expiry"]
            .as_str()
            .and_then(crate::session_link::rfc3339_to_secs),
        _ => None,
    }
}

/// The question [`snapshot_refreshed_at`] answers, asked of a LIVE slot.
///
/// Snapshots got one helper across every tool because readers working it out
/// for themselves disagreed. The per-slot walk still called Claude's, so a
/// Codex slot went unchecked entirely.
fn slot_login_of(
    paths: &Paths,
    tool: &str,
    dir: &std::path::Path,
) -> crate::adapters::claude::SlotLogin {
    use crate::adapters::claude::SlotLogin;
    // Claude's own reader also consults the Keychain, which no other tool uses.
    if tool == "claude-code" {
        return crate::adapters::claude::slot_login(dir);
    }
    let Some(p) = paths.try_with_tool_dir(tool, dir) else {
        return SlotLogin::Present(None);
    };
    let file = match tool {
        "codex" => p.codex_auth(),
        "gemini" => p.gemini_oauth(),
        "antigravity" => p.antigravity_token(),
        _ => return SlotLogin::Present(None),
    };
    let Ok(bytes) = std::fs::read(&file) else {
        return SlotLogin::Absent;
    };
    let secs = serde_json::from_slice::<Value>(&bytes)
        .ok()
        .and_then(|v| match tool {
            "codex" => v["last_refresh"]
                .as_str()
                .and_then(crate::session_link::rfc3339_to_secs),
            "gemini" => v["expiry_date"].as_i64().map(|ms| ms / 1000),
            _ => v["token"]["expiry"]
                .as_str()
                .and_then(crate::session_link::rfc3339_to_secs),
        });
    SlotLogin::Present(secs.map(|s| s * 1000))
}

/// Is renewal standing down for this slot because a live session owns the login?
///
/// `ls` asks this for Codex and `quota` asks it for Claude; the health screen
/// asked neither, so the one place whose job is to say whether a setup is sound
/// stayed silent while an account went days without a renewal.
fn renewal_deferred_for(paths: &Paths, tool: &str, dir: &std::path::Path) -> bool {
    match tool {
        "codex" => crate::refresh::codex_renewal_deferred(paths, dir, now_ms() / 1000),
        "claude-code" => crate::refresh::claude_renewal_deferred(paths, dir, now_ms()),
        _ => false,
    }
}

/// Whether a snapshot is old enough that its REFRESH token may itself be dead.
///
/// An access token that merely lapsed is not news for any of these tools - they
/// all refresh silently - which is why the threshold is days, not seconds.
fn snapshot_is_stale(snap: &crate::adapters::Snapshot, tool: &str) -> bool {
    snapshot_refreshed_at(snap, tool)
        .is_some_and(|secs| now_ms() / 1000 - secs > STALE_DAYS * 86400)
}

/// Identity extracted from a STORED snapshot (no live read, no secrets):
/// (email, tier, marker). marker is "stale" (a login snapshot older than
/// STALE_DAYS whose refresh token may
/// have rotated, so re-run `add --update`), else None.
fn profile_detail(
    store: &Store,
    name: &str,
    tool: &str,
) -> Option<(Option<String>, Option<String>, Option<&'static str>)> {
    let snap = store.load(name, tool).ok()??;
    // From here the snapshot EXISTS: a missing part or unparseable blob is an
    // UNREADABLE snapshot (surfaced as a marker), not silently "no data" - a
    // corrupt profile must be visible in `ls` before `use` trips over it.
    let unreadable = (None, None, Some("unreadable"));
    match tool {
        "claude-code" => {
            let (Some(cred_part), Some(oauth_part)) =
                (snap.part("credentials"), snap.part("oauth_account"))
            else {
                return Some(unreadable);
            };
            let (Ok(creds), Ok(oauth)) = (
                serde_json::from_slice::<Value>(cred_part.expose()),
                serde_json::from_slice::<Value>(oauth_part.expose()),
            ) else {
                return Some(unreadable);
            };
            // Claude access tokens live ~1h and Claude Code refreshes them
            // silently with the refresh token, so "expired" the moment the
            // access token lapses is pure noise (this was the constant
            // "expired" spam). Only flag a snapshot whose access token is
            // ANCIENT (>30 days) - by then the refresh token itself may be
            // revoked. Same rule as Codex / Gemini / Antigravity.
            let marker = snapshot_is_stale(&snap, tool).then_some("stale");
            Some((
                oauth["emailAddress"].as_str().map(String::from),
                creds["claudeAiOauth"]["subscriptionType"]
                    .as_str()
                    .map(String::from),
                marker,
            ))
        }
        "codex" => {
            let Some(auth_part) = snap.part("auth") else {
                return Some(unreadable);
            };
            let Ok(auth) = serde_json::from_slice::<Value>(auth_part.expose()) else {
                return Some(unreadable);
            };
            let email = crate::adapters::codex::decode_email_from_id_token(
                auth["tokens"]["id_token"].as_str(),
            );
            let marker = snapshot_is_stale(&snap, tool).then_some("stale");
            Some((email, auth["auth_mode"].as_str().map(String::from), marker))
        }
        "gemini" => {
            let oauth: Value = serde_json::from_slice(snap.part("oauth")?.expose()).ok()?;
            let email = snap
                .part("accounts")
                .and_then(|a| serde_json::from_slice::<Value>(a.expose()).ok())
                .and_then(|v| v["active"].as_str().map(String::from))
                .or_else(|| crate::adapters::gemini_jwt_claim(oauth["id_token"].as_str(), "email"));
            // Gemini access tokens live ~1h and the CLI refreshes them
            // silently, so "expired right now" is noise. Meaningful signal:
            // a snapshot whose expiry is ANCIENT was refreshed long ago and
            // its refresh token may be revoked - same idea as codex's stale.
            let marker = snapshot_is_stale(&snap, tool).then_some("stale");
            Some((email, None, marker))
        }
        "antigravity" => {
            let v: Value = serde_json::from_slice(snap.part("token")?.expose()).ok()?;
            // A snapshot whose token expiry is ancient was refreshed long ago;
            // its refresh token may be revoked - same idea as codex's stale.
            let marker = snapshot_is_stale(&snap, tool).then_some("stale");
            Some((None, v["auth_method"].as_str().map(String::from), marker))
        }
        _ => None,
    }
}

/// What to DO about the stale tools, and what still works despite them.
///
/// Naming the stale tool was half the job. The old hint said to re-run
/// `add --update`, which re-saves a snapshot FROM a live login - no help when
/// the login itself is what lapsed. The tool has to be signed into first, and
/// that is per-tool.
///
/// It also says which tools still serve. A lone marker beside an account reads
/// as "this account is broken" when Claude and Codex are working perfectly
/// well - which was the actual confusion it caused.
///
/// Empty when nothing is stale. When EVERYTHING is stale it promises nothing,
/// because there is nothing to reassure anyone about.
pub fn stale_hint(stale: &[&str], healthy: &[&str]) -> String {
    if stale.is_empty() {
        return String::new();
    }
    let mut out = format!(
        "  ({}: this saved copy is old, so its token may no longer work - run that \
         tool once, then `add --update` saves whatever it signed in as)",
        stale.join(", ")
    );
    if !healthy.is_empty() {
        out.push_str(&format!(
            "\n  (the account still serves {} - a stale tool does not hold the others back)",
            healthy.join(", ")
        ));
    }
    out
}

/// The payer's remaining quota, short enough for a status bar.
///
/// Going through the proxy costs the tool its own `rate_limits` block, so a
/// status line that reads them prints "weekly N/A | 5h N/A" while swapdex holds
/// a reading from a minute ago. This renders that reading from cache: a bar
/// redraws constantly and cannot wait on a request.
///
/// Takes USED percentages and reports what is LEFT. Empty when nothing has been
/// measured, so the bar can omit the segment rather than print a placeholder
/// that looks like a reading.
/// How stale the status bar's number is, in the fewest characters that say it.
///
/// The bar reads the cache, which records when each number was taken, and threw
/// that away - so a reading taken before an account's window filled sat there
/// saying "5h 100%" while the account was refusing every turn. The bar is
/// refreshed about once a minute, so past ten minutes the readings have stopped
/// arriving, and that is worth a few characters.
fn bar_age(age_secs: i64, refresh_secs: i64) -> Option<String> {
    // Late means late for THIS account's own schedule. An account with plenty
    // left is re-read every fifteen minutes by design, so a flat ten-minute
    // threshold flagged it while everything was working - and a warning that
    // shows when nothing is wrong is one the reader learns to skip. Twice its
    // own interval means a refresh was due and did not come; the ten-minute
    // floor keeps a once-a-minute account from being nagged about at two.
    let overdue = refresh_secs.saturating_mul(2).max(600);
    if age_secs < overdue {
        return None;
    }
    let m = age_secs / 60;
    Some(if m < 60 {
        format!(" · {m}m old")
    } else {
        format!(" · {}h old", m / 60)
    })
}

/// What a display reading only the cache should say about one account.
///
/// It used to say the number and how old it was. "Old" and "not coming" are
/// different news: on a machine where the paying account's token was being
/// rejected, the bar read "7d 95% . 1h old" and would have gone on aging that
/// number forever, because no live read could ever replace it. A rejection is
/// about the account, so it replaces the number rather than annotating it -
/// and it matches what `swapdex quota` says about the same account, which is
/// where the reader goes next.
fn cached_brief(e: &crate::quota_cache::Entry, now: i64) -> String {
    // Only when the rejection is the LAST thing that happened. A reading
    // clears the stamp, but a cache written by an older swapdex can carry both.
    if e.token_rejected_at.is_some_and(|at| at >= e.at) {
        return "token rejected".to_string();
    }
    // Carry the number's age. Without it the bar showed a reading taken hours
    // earlier exactly like one taken now.
    let refresh =
        crate::proxy::pick::measure_after(crate::proxy::pick::headroom(e.five_h, e.seven_d))
            .as_secs() as i64;
    let age = bar_age(now.saturating_sub(e.at), refresh).unwrap_or_default();
    format!("{}{age}", quota_brief(e.five_h, e.seven_d))
}

pub fn quota_brief(five_h_used: Option<f64>, seven_d_used: Option<f64>) -> String {
    let left = |u: f64| (100.0 - u).clamp(0.0, 100.0);
    match (five_h_used, seven_d_used) {
        (Some(a), Some(b)) => format!("5h {:.0}% | 7d {:.0}%", left(a), left(b)),
        (Some(a), None) => format!("5h {:.0}%", left(a)),
        (None, Some(b)) => format!("7d {:.0}%", left(b)),
        // Saying nothing is indistinguishable from a broken status bar. The
        // numbers vanish for two ordinary reasons - nothing measured yet, and a
        // window that passed its reset before a fresh read landed - and in both
        // the honest answer is that there is no reading, not blank space.
        (None, None) => "usage unread".to_string(),
    }
}

/// How to sign an account in, naming the tool it is about.
///
/// 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. Advice that names the wrong tool is
/// worse than none.
pub fn sign_in_remedy(name: &str, tool: &str) -> String {
    // Claude is `run`'s default; naming it would be noise.
    let flag = match tool {
        "claude-code" | "claude" => String::new(),
        other => format!(" --tool {other}"),
    };
    format!("`swapdex run {name}{flag}` signs it in once")
}

/// What to say when a name matches no account.
///
/// A typo answered "no account named 'alicee' - `swapdex ui` lists them",
/// sending the user to open another screen to read four words. The list is
/// right here; and when one candidate is an obvious near-miss, naming it is the
/// whole answer.
pub fn unknown_account_or_unservable(
    asked: &str,
    servable: &[&str],
    saved: &[&str],
    tool: &str,
) -> String {
    // A name that IS saved but cannot serve is a different problem, and saying
    // "no account named X - you have: X" is worse than useless. Serving reads a
    // slot's own credential directory; a snapshot has none until it is run once.
    if saved.contains(&asked) && !servable.contains(&asked) {
        return format!(
            "'{asked}' is saved but has never been signed in on this machine, so it \
             cannot pay for turns - {}",
            sign_in_remedy(asked, tool)
        );
    }
    // Nothing can serve, but something IS saved: "no accounts saved yet" would
    // be a plain untruth about accounts `ls` is showing. Name them and say what
    // they still need.
    if servable.is_empty() && !saved.is_empty() {
        let flag = if tool == "claude-code" {
            String::new()
        } else {
            format!(" --tool {tool}")
        };
        return format!(
            "no account named '{asked}'. Saved, but not yet signed in on this machine: \
             {} - `swapdex run <name>{flag}` signs one in",
            saved.join(", ")
        );
    }
    unknown_account(asked, servable)
}

/// `pause` / `resume` - keep an account out of the proxy's rotation, or put it
/// back.
///
/// The setting existed and the proxy has honoured it all along; the only way to
/// SET it was a keystroke inside the full-screen picker. A headless machine, a
/// scripted setup, and anyone who does not open that screen could not say "never
/// rotate into this one" - and could not see that it had been said.
///
/// Pausing does not stop `use` or `serve`: this is about what the proxy reaches
/// for on its own, not about what the person can ask for by name.
pub fn pause_rotation(paths: &Paths, name: &str, pause: bool) -> Result<i32> {
    let store = Store::open(paths)?;
    let (profiles, _, _) = merged_accounts(paths, &store);
    if !profiles.iter().any(|p| p.name == name) {
        let known: Vec<&str> = profiles.iter().map(|p| p.name.as_str()).collect();
        eprintln!("swapdex: {}", unknown_account(name, &known));
        return Ok(5);
    }
    // Through `update`, so a concurrent edit cannot be lost - the same reason
    // the picker stopped reading and writing the settings itself.
    crate::settings::update(paths, |cfg| {
        if cfg.is_disabled(name) != pause {
            cfg.toggle_disabled(name);
        }
    })?;
    // `use` resolves the tool from the name; `serve` does not, and defaults to
    // Claude, so naming it bare pointed a Codex-only account at a command that
    // answers "no account named '<name>'". Claude needs no flag: it is what
    // both default to.
    let serve_flag = profiles
        .iter()
        .find(|p| p.name == name)
        .filter(|p| !p.tools.iter().any(|t| t == "claude-code"))
        .and_then(|p| p.tools.first())
        .map(|t| format!(" --tool {t}"))
        .unwrap_or_default();
    if pause {
        println!(
            "{name} paused - the proxy will not pick it (`swapdex use {name}` and \
             `swapdex serve {name}{serve_flag}` still work)"
        );
    } else {
        println!("{name} back in rotation");
    }
    Ok(0)
}

pub fn unknown_account(asked: &str, known: &[&str]) -> String {
    if known.is_empty() {
        return "no accounts saved yet - `swapdex add <name>` saves the login you are on"
            .to_string();
    }
    // A near-miss is a typo: one edit away, or one is a prefix of the other.
    let near = known.iter().find(|k| {
        let (a, b) = (asked.to_lowercase(), k.to_lowercase());
        a != b && (a.starts_with(&b) || b.starts_with(&a)) && a.len().abs_diff(b.len()) <= 2
    });
    match near {
        Some(hit) => {
            let others: Vec<&str> = known.iter().copied().filter(|k| k != hit).collect();
            if others.is_empty() {
                format!("no account named '{asked}' - did you mean '{hit}'?")
            } else {
                format!(
                    "no account named '{asked}' - did you mean '{hit}'? (also: {})",
                    others.join(", ")
                )
            }
        }
        None => format!(
            "no account named '{asked}' - you have: {}",
            known.join(", ")
        ),
    }
}

/// One line confirming a switch: who is paying now, and what they have left.
///
/// `serve` printed the destination and two lines of explanation, and said
/// nothing about the account itself - so every switch was followed by `ls` to
/// see whether it took, and by `usage` to see whether that account had any
/// room. Both answers belong in the switch that prompted them.
///
/// What is unknown is left unsaid: an account whose window has never been read
/// gets its name and nothing more, rather than a percentage nobody measured.
pub fn switch_line(name: &str, email: Option<&str>, week_left_pct: Option<f64>) -> String {
    let who = match email {
        Some(e) => format!("now {name} ({e})"),
        None => format!("now {name}"),
    };
    match week_left_pct {
        // Spent reads worse as "0% left" than as plain words.
        Some(p) if p < 0.5 => format!("{who} - no week left"),
        Some(p) => format!("{who} - {:.0}% of the week left", p),
        None => who,
    }
}

/// Whose account this row is, preferring what the snapshot recorded.
///
/// Identity was read from the saved snapshot only, so an account that exists as
/// a slot and was never snapshotted had an empty name column - the row was
/// there and switching worked, but nothing said which login it was. The slot's
/// own `.claude.json` answers when the snapshot cannot.
///
/// The snapshot wins when both speak: it is what this profile was SAVED as,
/// and a slot's config can be overwritten by whatever last ran in it.
pub fn best_identity(from_snapshot: Option<String>, from_slot: Option<String>) -> Option<String> {
    from_snapshot.or(from_slot)
}

/// Every account that can be switched to, snapshots and slots together.
///
/// `ls` listed saved snapshots only. On a machine whose accounts live as SLOTS,
/// `serve personal` moved the turns correctly and the list had no row for
/// `personal` at all - so the mark saying who pays had nowhere to appear, and
/// two of three switches looked like they did nothing.
///
/// Sorted and de-duplicated: an account with both a slot and a snapshot is one
/// account, and a stable order keeps the table from reshuffling between runs.
pub fn listable(snapshots: &[&str], slots: &[&str]) -> Vec<String> {
    let mut all: Vec<String> = snapshots
        .iter()
        .chain(slots.iter())
        .map(|s| s.to_string())
        .collect();
    all.sort();
    all.dedup();
    all
}

/// Who is paying, across tools.
///
/// `ls` asked Claude's registry alone, so serving a Codex account moved the
/// turns correctly and the listing marked nobody - the same "the switch did
/// nothing" appearance fixed for Claude in 0.80.0, still live on the Codex
/// side. Claude wins when both have a payer: one mark can only carry one name,
/// and Claude is the tool the rest of the row is about.
pub fn payer_of_any(per_tool: &[(&str, Option<&str>)]) -> Option<String> {
    let pick = |want: &str| {
        per_tool
            .iter()
            .find(|(t, _)| *t == want)
            .and_then(|(_, p)| p.map(str::to_string))
    };
    pick("claude-code").or_else(|| per_tool.iter().find_map(|(_, p)| p.map(str::to_string)))
}

/// The mark a single row gets for paying, if any.
///
/// `serve rnd` says "turns -> rnd", and then `ls` starred a different account -
/// the one holding the login on disk - with the paying account named nowhere.
/// Switching looked like it had not taken, which is what its owner concluded,
/// repeatedly, over a day.
///
/// `None` when there is nothing to disambiguate: same account, or nothing
/// paying. An extra mark on the common case is noise.
pub fn row_suffix(
    row: &str,
    _signed_in: Option<&str>,
    paying: Option<&str>,
) -> Option<&'static str> {
    // Marked even when the payer also holds the login. Suppressing it there
    // meant that of three accounts, switching to one produced no visible
    // change at all, which reads as that one switch having failed.
    (row == paying?).then_some("pays")
}

/// Who pays, when that is not who the tool is signed in as.
///
/// `ls` marks the account Claude holds a login for. When a proxy is paying with
/// a different one, that mark is true and misleading at once: the owner
/// switched to bsgong, the proxy served every turn from bsgong, and the list
/// went on starring kong because that is whose login sits on disk. Both facts
/// are real; showing only one reads as the switch having failed.
///
/// `None` when there is nothing to disambiguate - same account, or nothing
/// paying - because an extra note on the common case is just noise.
pub fn payer_note(signed_in: Option<&str>, paying: Option<&str>) -> Option<String> {
    let paying = paying?;
    if signed_in == Some(paying) {
        return None;
    }
    Some(format!("{paying} pays"))
}

/// The staleness note for a profile, naming the tools it is about.
///
/// One tool going stale is not the account going stale. A profile holding four
/// logins was marked `(stale)` whole because gemini had not been refreshed in
/// 37 days, while the Codex login added minutes earlier answered the server
/// perfectly well - so the row said "unusable" about an account that worked,
/// and the owner reasonably read it as the add having failed.
///
/// `None` when nothing is wrong, which is the common case and needs no words.
pub fn stale_marker(per_tool: &[(&str, Option<&str>)]) -> Option<String> {
    let named: Vec<String> = per_tool
        .iter()
        .filter_map(|(tool, m)| m.map(|m| format!("{tool} {m}")))
        .collect();
    (!named.is_empty()).then(|| named.join(", "))
}

/// Summarize a profile across ALL its tools (not just the first): a marker if
/// ANY tool is stale/expired, and the first non-empty email/tier. `p.tools` is
/// alphabetical, so inspecting only the first would always be "claude-code" and
/// hide Codex entirely.
fn profile_summary(
    store: &Store,
    name: &str,
    tools: &[String],
) -> (Option<String>, Option<String>, Option<String>) {
    let mut email = None;
    let mut tier = None;
    let mut per_tool: Vec<(&str, Option<&str>)> = Vec::new();
    // Adapter order (Claude first), NOT the store's alphabetical order:
    // antigravity sorts first alphabetically and its auth_method ("consumer")
    // would mask claude's real plan tier ("max") on multi-tool profiles.
    for a in adapters::all() {
        let t = a.name();
        if !tools.iter().any(|x| x == t) {
            continue;
        }
        if let Some((e, ti, m)) = profile_detail(store, name, t) {
            email = email.or(e);
            tier = tier.or(ti);
            // Recorded per tool, so the note can say WHICH login is stale
            // rather than condemning the account.
            per_tool.push((t, m));
        }
    }
    (email, tier, stale_marker(&per_tool))
}

/// Provider-qualified health for the live slots represented by one account row.
///
/// A profile name is only unique within a tool: Claude and Codex can both have
/// a slot called `work`. Health therefore resolves `(tool, name)` directly from
/// that tool's registry instead of consulting the listing's legacy name-only
/// directory map. Snapshot warnings are carried through unchanged.
#[derive(Default)]
struct AccountHealth {
    warning: Option<String>,
    access_expired: bool,
    refresh_rejected_at_ms: std::collections::BTreeMap<String, i64>,
    renewal_owner: std::collections::BTreeMap<String, String>,
}

fn account_health(
    paths: &Paths,
    name: &str,
    tools: &[String],
    snapshot_warning: Option<String>,
    now_ms: i64,
) -> AccountHealth {
    let mut warnings: Vec<String> = snapshot_warning
        .into_iter()
        .flat_map(|warning| warning.split(", ").map(str::to_owned).collect::<Vec<_>>())
        .collect();
    let mut access_expired = false;
    let mut refresh_rejected_at_ms = std::collections::BTreeMap::new();
    let mut renewal_owner = std::collections::BTreeMap::new();

    for tool in tools {
        let Some(slot) = crate::slots::Slots::open_for(paths, tool)
            .ok()
            .and_then(|slots| slots.get(name))
        else {
            continue;
        };
        // A registered live slot supersedes its historical snapshot's status.
        // In particular an unreadable Mac Keychain is not an expired snapshot.
        warnings.retain(|warning| !warning.starts_with(&format!("{tool} ")));
        if let Some(login) = crate::live_login::resolve(paths, &slot.config_dir, tool, now_ms) {
            renewal_owner.insert(tool.clone(), "native".to_owned());
            if let Some(rejected_at) = login.refresh_rejected_at_ms {
                warnings.push(format!("{tool} refresh rejected - re-login required"));
                refresh_rejected_at_ms.insert(tool.clone(), rejected_at);
            }
            continue;
        }
        match tool.as_str() {
            "codex" => {
                if let Some(rejected_at) = crate::refresh_health::codex_rejection(&slot.config_dir)
                {
                    warnings.push("codex refresh rejected - re-login required".to_string());
                    refresh_rejected_at_ms.insert("codex".to_string(), rejected_at);
                } else if crate::proxy::codex::slot_token_expired(&slot.config_dir, now_ms / 1000) {
                    warnings.push("codex expired - needs refresh".to_string());
                    access_expired = true;
                } else if crate::refresh::codex_renewal_deferred(
                    paths,
                    &slot.config_dir,
                    now_ms / 1000,
                ) {
                    warnings.push("codex renewal deferred - refresh unverified".to_string());
                }
            }
            "claude-code"
                if crate::proxy::creds::slot_token_expired_for(paths, &slot.config_dir, now_ms) =>
            {
                warnings.push("claude-code expired - needs refresh".to_string());
                access_expired = true;
            }
            "claude-code" => {
                if matches!(
                    crate::proxy::creds::slot_token_detail_for(paths, &slot.config_dir),
                    Err(crate::proxy::creds::TokenUnavailable::KeychainLocked)
                ) {
                    warnings.push(
                        "claude-code keychain unavailable - verify in a local terminal".to_string(),
                    );
                }
            }
            _ => {}
        }
    }

    AccountHealth {
        warning: (!warnings.is_empty()).then(|| warnings.join(", ")),
        // A definitive rejection is the stronger diagnosis. The TUI renders
        // `stale` before `warn`, so leaving this true would hide the re-login
        // verdict behind the weaker word "expired".
        access_expired: access_expired && refresh_rejected_at_ms.is_empty(),
        refresh_rejected_at_ms,
        renewal_owner,
    }
}

fn tui_row_names_tool(row: &crate::tui::Row, name: &str, tool: &str) -> bool {
    row.name == name
        && row
            .tools
            .split(',')
            .map(|listed| listed.trim().trim_end_matches('*'))
            .any(|listed| listed == tool)
}

#[cfg(test)]
mod account_health_tests {
    use super::*;

    #[test]
    fn a_codex_row_does_not_hide_a_claude_slot_with_the_same_name() {
        let codex = crate::tui::Row {
            name: "shared".into(),
            ident: String::new(),
            tools: "codex".into(),
            active: false,
            warn: None,
            disabled: false,
            needs_login: false,
            stale: false,
            is_slot: true,
            also: Vec::new(),
        };

        assert!(!tui_row_names_tool(&codex, "shared", "claude-code"));
        assert!(tui_row_names_tool(&codex, "shared", "codex"));
    }
}

/// Which profile is the LIVE account for each tool (from live identity, A2).
/// A mixed state (claude on profile X, codex on profile Y) is representable.
pub(crate) fn active_by_tool(store: &Store, paths: &Paths) -> Vec<(&'static str, String)> {
    adapters::all()
        .iter()
        .filter_map(|a| {
            let tool = a.name();
            // Under the slot model the pointer IS the answer: a switch repoints
            // it and deliberately never writes the tool's own config dir. So
            // reading that dir reports whatever an earlier copy-model switch
            // left behind - on a real machine an account abandoned six days
            // earlier, marked active while `serve`, the proxy and the serving
            // pointer all named a different one.
            if let Some(name) = slot_default_name(paths, tool) {
                return Some((tool, name));
            }
            a.identity(paths)
                .ok()
                .flatten()
                .and_then(|id| matched_profile_name(store, tool, &id.account_id))
                .map(|name| (tool, name))
        })
        .collect()
}

/// The name of the slot a tool's default pointer names, when it has one.
pub(crate) fn slot_default_name(paths: &Paths, tool: &str) -> Option<String> {
    let slots = crate::slots::Slots::open_for(paths, tool).ok()?;
    let dir = slots.default_dir()?;
    slots
        .list()
        .into_iter()
        .find(|r| r.config_dir == dir)
        .map(|r| r.name)
}

/// The account a tool's pointer names, with whatever identity the slot carries.
///
/// `status` is documented as the active account per tool, and under the slot
/// model that is the pointer: a switch repoints it and never writes the tool's
/// own config dir. Reading that dir answers a different question - what an
/// unshimmed launch would use, which on a slots-only machine is nothing at all
/// and on an older one is whatever a copy-model switch abandoned there.
pub(crate) fn slot_active_identity(paths: &Paths, tool: &str) -> Option<(String, Option<String>)> {
    slot_active_login(paths, tool).map(|(name, email, _)| (name, email))
}

/// The same, plus whether that slot holds a login at all.
///
/// The pointer naming an account and the account being signed in are different
/// facts, and reading the first as the second reported an EMPTY slot directory
/// as logged in - while `serve`, asking `proxy::has_login` about the very same
/// account, refused it for having no login. A missing credential is not an
/// unreadable one: the remedies differ.
pub(crate) fn slot_active_login(
    paths: &Paths,
    tool: &str,
) -> Option<(String, Option<String>, bool)> {
    let slots = crate::slots::Slots::open_for(paths, tool).ok()?;
    let dir = slots.default_dir()?;
    let rec = slots.list().into_iter().find(|r| r.config_dir == dir)?;
    let email = crate::proxy::creds::any_slot_email(&rec.config_dir);
    let signed_in = crate::proxy::has_login(paths, tool, &rec.config_dir);
    Some((rec.name, email, signed_in))
}

/// How a screen should describe the account a pointer names.
///
/// Three states, not two: signed in with a readable email, signed in but the
/// email cannot be read, and not signed in at all. Collapsing the last two into
/// "login unreadable in the slot" told somebody with an empty slot directory to
/// go looking for a damaged file.
fn slot_who(name: &str, email: Option<String>, signed_in: bool, tool: &str) -> String {
    match (signed_in, email) {
        (true, Some(e)) => e,
        (true, None) => "signed in, email unreadable in the slot".into(),
        (false, _) => format!(
            "selected but not signed in - `swapdex run {name}{}` signs it in",
            tool_flag(tool)
        ),
    }
}

/// The profile whose login sits in the tool's OWN config dir, when that is not
/// the one the pointer names.
///
/// Both are true at once and they answer different questions: the pointer says
/// who swapdex serves, the tool's dir says who an unshimmed launch would use.
/// Reporting only the first hides exactly the state this returns.
pub(crate) fn tool_dir_disagrees(
    store: &Store,
    paths: &Paths,
    tool: &str,
    pointed_at: &str,
) -> Option<String> {
    let adapter = adapters::all().into_iter().find(|a| a.name() == tool)?;
    let id = adapter.identity(paths).ok().flatten()?;
    let live = matched_profile_name(store, tool, &id.account_id)?;
    (live != pointed_at).then_some(live)
}

/// Pad-or-truncate to `w` DISPLAY columns (CJK chars occupy two; counting
/// chars would shear the table); a longer value ends in one '…'.
fn fit(s: &str, w: usize) -> String {
    use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
    let n = UnicodeWidthStr::width(s);
    if n <= w {
        let mut out = String::from(s);
        out.extend(std::iter::repeat_n(' ', w - n));
        return out;
    }
    let mut out = String::new();
    let mut used = 0usize;
    for c in s.chars() {
        let cw = UnicodeWidthChar::width(c).unwrap_or(0);
        if used + cw > w.saturating_sub(1) {
            break;
        }
        out.push(c);
        used += cw;
    }
    out.push('…');
    // Pad if the truncation landed a column short (a wide char didn't fit).
    out.extend(std::iter::repeat_n(' ', w.saturating_sub(used + 1)));
    out
}

/// The account column: email if known, else just the tier (never a stray
/// leading-space " [tier]").
fn identity_column(email: Option<String>, tier: Option<String>) -> String {
    match (email.filter(|e| !e.is_empty()), tier) {
        (Some(e), Some(t)) => format!("{e} [{t}]"),
        (Some(e), None) => e,
        (None, Some(t)) => format!("[{t}]"),
        (None, None) => String::new(),
    }
}

/// Every account a switch can name: saved snapshots and registered slots in one
/// sorted list, plus the directory each slot lives in and the registries that
/// would not parse.
///
/// Slots are switchable too, and on a machine whose accounts live as slots they
/// are the only accounts there are. `ls` and the dashboard each learned that
/// separately and the numbered menu was left behind; one merge so they cannot
/// drift again. An unparseable registry is reported, not counted as empty.
pub(crate) fn merged_accounts(
    paths: &Paths,
    store: &Store,
) -> (
    Vec<crate::store::ProfileInfo>,
    std::collections::HashMap<String, std::path::PathBuf>,
    Vec<&'static str>,
) {
    let mut profiles = store.list();
    let mut slot_dirs: std::collections::HashMap<String, std::path::PathBuf> =
        std::collections::HashMap::new();
    let mut unreadable: Vec<&'static str> = Vec::new();
    for tool in crate::adapters::names() {
        let Ok(sl) = crate::slots::Slots::open_for(paths, tool) else {
            unreadable.push(tool);
            continue;
        };
        for r in sl.list() {
            match profiles.iter_mut().find(|p| p.name == r.name) {
                Some(p) => {
                    if !p.tools.iter().any(|t| t == tool) {
                        p.tools.push(tool.to_string());
                    }
                }
                None => profiles.push(crate::store::ProfileInfo {
                    name: r.name.clone(),
                    tools: vec![tool.to_string()],
                }),
            }
            // Remember where this slot lives, so a row with no snapshot can
            // still say whose login it is - the slot's own .claude.json knows,
            // and an empty name column left switching unverifiable.
            slot_dirs
                .entry(r.name.clone())
                .or_insert_with(|| r.config_dir.clone());
        }
    }
    profiles.sort_by(|a, b| a.name.cmp(&b.name));
    (profiles, slot_dirs, unreadable)
}

pub fn ls(paths: &Paths, json: bool, names: bool) -> Result<i32> {
    let store = Store::open(paths)?;
    let active = active_by_tool(&store, paths);
    let active_tools_for = |name: &str| -> Vec<&'static str> {
        active
            .iter()
            .filter(|(_, n)| n == name)
            .map(|(t, _)| *t)
            .collect()
    };

    let (profiles, _, unreadable_registry) = merged_accounts(paths, &store);
    if names {
        // The SAME accounts the listing shows, slot accounts included: this is
        // the form written for scripts and tab-completion, and it printed only
        // `store.list()` - so a name `use` accepts, and `ls` displays, could not
        // be completed. Every account `swapdex run <name>` makes is that shape.
        let mut out: Vec<&str> = profiles.iter().map(|p| p.name.as_str()).collect();
        out.sort_unstable();
        for n in out {
            println!("{n}");
        }
        return Ok(0);
    }
    // Before the `--json` branch, not after it: that branch returns, so the
    // machine-readable listing was the one form that never said it was
    // incomplete - and every row carries `"warning": null`, which reads as
    // "nothing wrong". stderr, so stdout stays a parseable array.
    // A name that means two accounts: the row is built from the profile while
    // `use` selects the slot. swapdex already reports the harmless direction
    // (same account, two names) and said nothing about this one.
    let mut crossed: Vec<String> = Vec::new();
    let mut crossed_names = std::collections::HashSet::new();
    let mut crossed_tools = std::collections::HashSet::new();
    if let Ok(st) = Store::open(paths) {
        for tool in crate::adapters::names() {
            if let Ok(sl) = crate::slots::Slots::open_for(paths, tool) {
                for r in sl.list() {
                    let p_id = profile_account_id(&st, &r.name, tool);
                    let s_id = slot_account_id_for(tool, &r.config_dir);
                    if name_means_two_accounts(p_id.as_deref(), s_id.as_deref()) {
                        crossed.push(format!("{} ({tool})", r.name));
                        crossed_names.insert(r.name.clone());
                        crossed_tools.insert((r.name.clone(), tool));
                    }
                }
            }
        }
    }
    if !crossed.is_empty() {
        eprintln!(
            "swapdex: {} names a saved profile AND a slot holding a DIFFERENT \
             account. For that tool, listing and selection use the slot's identity. \
             `swapdex slots` shows which directory each one is.",
            crossed.join(", ")
        );
    }
    if !unreadable_registry.is_empty() {
        eprintln!(
            "swapdex: the account registry could not be read ({}) - \
             ~/.local/share/swapdex/slots.json is damaged, so accounts are missing \
             from this listing. The slot directories still hold their logins; \
             restore the file from a backup or re-register with `swapdex adopt`.",
            unreadable_registry.join(", ")
        );
    }
    let summary_for = |p: &crate::store::ProfileInfo| {
        let (_, _, marker) = profile_summary(&store, &p.name, &p.tools);
        let mut health = account_health(paths, &p.name, &p.tools, marker, now_ms());
        // Legacy ls rows aggregate providers. Keep their displayed email and
        // tier together under one primary provider (adapter order), never an
        // arbitrary same-name directory from another tool.
        let primary = adapters::names()
            .into_iter()
            .find(|tool| p.tools.iter().any(|held| held == tool));
        let (mut email, mut tier) = primary
            .and_then(|tool| profile_detail(&store, &p.name, tool))
            .map(|(email, tier, _)| (email, tier))
            .unwrap_or_default();
        if let Some(tool) = primary {
            if let Some(slot) = crate::slots::Slots::open_for(paths, tool)
                .ok()
                .and_then(|slots| slots.get(&p.name))
            {
                email = match tool {
                    "claude-code" => crate::proxy::creds::slot_email(&slot.config_dir),
                    "codex" => codex_slot_email(&slot.config_dir),
                    _ => paths
                        .try_with_tool_dir(tool, &slot.config_dir)
                        .and_then(|at| adapters::by_name(tool)?.identity(&at).ok().flatten())
                        .and_then(|identity| identity.email),
                };
            }
            if crossed_tools.contains(&(p.name.clone(), tool)) {
                // The saved profile's plan describes a different account.
                tier = None;
            }
        };
        if crossed_names.contains(&p.name) {
            let conflict =
                "saved profile and slot hold different accounts; selection uses that tool's slot";
            health.warning = Some(match health.warning {
                Some(warning) => format!("{warning}, {conflict}"),
                None => conflict.to_string(),
            });
        }
        (email, tier, health)
    };
    if json {
        let rows: Vec<Value> = profiles
            .iter()
            .map(|p| {
                let (email, tier, health) = summary_for(p);
                serde_json::json!({
                    "name": p.name,
                    "tools": p.tools,
                    "active_tools": active_tools_for(&p.name),
                    // Settable from the CLI, so readable from it: a script that
                    // can pause an account and not see that it is paused has
                    // half an interface.
                    "paused": crate::settings::load(paths).is_disabled(&p.name),
                    "email": email,
                    "tier": tier,
                    "warning": health.warning,
                    "refresh_rejected_at_ms": health.refresh_rejected_at_ms,
                    "renewal_owner": health.renewal_owner,
                })
            })
            .collect();
        println!("{}", serde_json::to_string(&rows)?);
        return Ok(0);
    }
    if profiles.is_empty() {
        if unreadable_registry.is_empty() {
            println!("No accounts saved yet.");
            println!("  guided setup:  swapdex setup");
            println!("  or add one:    swapdex login <name>");
        }
        return Ok(0);
    }
    // Two-pass so columns fit the actual content (with a sane cap).
    struct Row {
        name: String,
        ident: String,
        tools: String,
        warn: Option<String>,
        active: bool,
        /// Set when this row is the account PAYING and a different one holds
        /// the login. `serve` said "turns -> rnd" and the list starred another
        /// name, so the switch read as not having taken.
        pays: bool,
    }
    // Same resolution the proxy performs, so what this screen claims and what
    // the proxy does cannot drift apart.
    // Ask EVERY tool who pays. Asking Claude's registry alone meant serving a
    // Codex account moved the turns and the listing marked nobody - the same
    // "the switch did nothing" appearance fixed for Claude in 0.80.0.
    let payers: Vec<(&str, Option<String>)> = crate::adapters::names()
        .into_iter()
        .map(|t| {
            (
                t,
                crate::slots::Slots::open_for(paths, t)
                    .ok()
                    .and_then(|s| s.payer()),
            )
        })
        .collect();
    let refs: Vec<(&str, Option<&str>)> = payers.iter().map(|(t, p)| (*t, p.as_deref())).collect();
    let paying = payer_of_any(&refs);
    // A selected account with no login cannot pay. Managed requests now fail
    // explicitly; selection alone must not imply it served a request.
    let payer_has_login = paying.as_deref().is_some_and(|who| {
        payers.iter().any(|(t, p)| {
            p.as_deref() == Some(who)
                && crate::slots::Slots::open_for(paths, t).is_ok_and(|s| {
                    s.get(who)
                        .is_some_and(|r| crate::proxy::has_login(paths, t, &r.config_dir))
                })
        })
    });
    let signed_in = active_by_tool(&store, paths)
        .into_iter()
        .find(|(t, _)| *t == "claude-code")
        .map(|(_, n)| n);
    let rows: Vec<Row> = profiles
        .iter()
        .map(|p| {
            let (email, tier, health) = summary_for(p);
            let at = active_tools_for(&p.name);
            let tools = p
                .tools
                .iter()
                .map(|t| {
                    if at.contains(&t.as_str()) {
                        format!("{t}*")
                    } else {
                        t.clone()
                    }
                })
                .collect::<Vec<_>>()
                .join(", ");
            Row {
                pays: row_suffix(&p.name, signed_in.as_deref(), paying.as_deref()).is_some(),
                name: p.name.clone(),
                ident: identity_column(email, tier),
                tools,
                warn: health.warning,
                active: !at.is_empty(),
            }
        })
        .collect();
    // Widths in CHARS (not bytes - non-ASCII names must not shear the table),
    // and content longer than the cap is truncated with '…' so one long row
    // cannot un-align every other. Full values stay available in `ls --json`.
    let name_w = rows
        .iter()
        .map(|r| unicode_width::UnicodeWidthStr::width(r.name.as_str()))
        .max()
        .unwrap_or(4)
        .clamp(4, 24);
    let ident_w = rows
        .iter()
        .map(|r| unicode_width::UnicodeWidthStr::width(r.ident.as_str()))
        .max()
        .unwrap_or(0)
        .clamp(0, 40);
    let mut saw_refreshable = false;
    let mut saw_unreadable = false;
    // Which tools are stale, and which of that account's tools still serve.
    // A lone marker reads as "this account is broken" when the others work.
    let mut stale_tools: Vec<String> = Vec::new();
    let mut healthy_tools: Vec<String> = Vec::new();
    // Who the user has taken out of rotation; the proxy reads the same file.
    let cfg = crate::settings::load(paths);
    for r in &rows {
        let mark = if r.active { "* " } else { "  " };
        let warn = r
            .warn
            .as_deref()
            .map(|m| format!("  ({m})"))
            .unwrap_or_default();
        saw_unreadable |= r.warn.as_deref() == Some("unreadable");
        // The note now names the tool ("gemini stale"), so match on the
        // word rather than the whole string.
        saw_refreshable |= r
            .warn
            .as_deref()
            .is_some_and(|w| w.contains("expired") || w.contains("stale"));
        if let Some(w) = r.warn.as_deref() {
            for t in r.tools.split(',').map(|t| t.trim().trim_end_matches('*')) {
                if t.is_empty() {
                    continue;
                }
                // The note already names the tools ("gemini stale"), so it is
                // the authority on which side each one falls.
                let bucket = if w.contains(t) {
                    &mut stale_tools
                } else {
                    &mut healthy_tools
                };
                if !bucket.iter().any(|x| x == t) {
                    bucket.push(t.to_string());
                }
            }
        }
        // The paying account is named on its own row: `serve` moved the turns
        // there, and without this the list starred a different name and the
        // switch read as not having taken.
        let pays = match (r.pays, payer_has_login) {
            (true, true) => "  <- pays",
            // Same words `payer_line` uses, so the two screens cannot drift.
            (true, false) => "  <- pays (no login)",
            (false, _) => "",
        };
        // Being out of rotation is a thing somebody chose, and the screen that
        // lists accounts is where they would look to check. It was settable and
        // visible only inside the picker, so a paused account read here as an
        // ordinary one the proxy simply never reached.
        // Named, because this row can also say `<- pays` and carry the active
        // mark: what is paused is the proxy's own picking, not the account.
        let paused = if cfg.is_disabled(&r.name) {
            "  (rotation paused)"
        } else {
            ""
        };
        println!(
            "{mark}{} {} [{}]{warn}{pays}{paused}",
            fit(&r.name, name_w),
            fit(&r.ident, ident_w),
            r.tools
        );
    }
    if saw_refreshable {
        let stale: Vec<&str> = stale_tools.iter().map(String::as_str).collect();
        let healthy: Vec<&str> = healthy_tools.iter().map(String::as_str).collect();
        let hint = stale_hint(&stale, &healthy);
        if hint.is_empty() {
            println!(
                "  (expired/stale: run that tool once and sign in - re-saving the profile \
                 cannot refresh a login that has already lapsed)"
            );
        } else {
            println!("{hint}");
        }
    }
    if saw_unreadable {
        println!(
            "  (unreadable: the saved snapshot is corrupt - log in to that account and \
             re-save it with `swapdex add <name> --update`)"
        );
    }
    if active
        .iter()
        .map(|(_, n)| n)
        .collect::<std::collections::HashSet<_>>()
        .len()
        > 1
    {
        println!("  (* marks the active account per tool)");
    }
    // The mark follows the pointer, so a login left behind in the tool's own
    // config dir would otherwise be invisible - and it is the one an unshimmed
    // launch still lands on. Saying both is the only honest answer here.
    for (tool, pointed_at) in &active {
        // Only the pointer can disagree with the tool's dir. Without one the
        // mark was READ from that dir, so comparing the two compares a value
        // with itself - and, since each side reads the file separately, a tool
        // rewriting it mid-listing made that self-comparison briefly fail.
        if slot_default_name(paths, tool).is_none() {
            continue;
        }
        if let Some(live) = tool_dir_disagrees(&store, paths, tool, pointed_at) {
            println!(
                "  (a plain `{}` would launch on '{live}', not the account marked here - \
                 run `swapdex shim` so it follows your switches)",
                tool_binary(tool)
            );
        }
    }
    Ok(0)
}

/// One compact line for shell prompts / statuslines: `claude:work codex:personal`.
/// The value per tool is the matched profile name, falling back to the email.
/// None when nothing is logged in (or nothing is readable).
/// What to say when `short_line` had nothing to report.
///
/// "Nothing is signed in" and "the logins cannot be read from here" are
/// different news, and a blank line says neither. A locked macOS Keychain over
/// SSH produces the second, and reporting it as the first is how a working
/// account gets called signed out.
fn absence_reason(any_unreadable: bool) -> &'static str {
    if any_unreadable {
        "logins unreadable from this shell"
    } else {
        "not signed in to any tool"
    }
}

pub fn short_line(paths: &Paths) -> Option<String> {
    let store = Store::open(paths).ok()?;
    let parts: Vec<String> = adapters::all()
        .iter()
        .filter_map(|a| {
            if crate::slots::Slots::open_for(paths, a.name())
                .is_ok_and(|slots| slots.serving_is_off())
            {
                return None;
            }
            let tool = match a.name() {
                "claude-code" => "claude",
                t => t,
            };
            // The pointer wherever there is one: this line goes in a prompt,
            // and a prompt naming the account swapdex is not serving is worse
            // than no line at all.
            // Only when that slot holds a login. The pointer governs a shimmed
            // launch, so an empty slot means swapdex has nothing to serve for
            // this tool - and naming it anyway is the case the line above warns
            // about, with the contract ("None when nothing is logged in")
            // broken on top.
            match slot_active_login(paths, a.name()) {
                Some((name, _, true)) => return Some(format!("{tool}:{name}")),
                Some((_, _, false)) => return None,
                None => {}
            }
            let id = a.identity(paths).ok().flatten()?;
            let who = matched_profile_name(&store, a.name(), &id.account_id)
                .or(id.email)
                .unwrap_or_else(|| "?".into());
            Some(format!("{tool}:{who}"))
        })
        .collect();
    if parts.is_empty() {
        None
    } else {
        Some(parts.join(" "))
    }
}

pub fn status(paths: &Paths, json: bool, short: bool) -> Result<i32> {
    if short {
        println!(
            "{}",
            short_line(paths).unwrap_or_else(|| {
                let unreadable = adapters::all().iter().any(|a| a.identity(paths).is_err());
                absence_reason(unreadable).to_string()
            })
        );
        return Ok(0);
    }
    let store = Store::open(paths)?;
    if json {
        let rows: Vec<Value> = adapters::all()
            .iter()
            .map(|adapter| {
                let tool = adapter.name();
                // Stable shape: every key present on every row, null when
                // unknown, so `jq .[].email` never needs guards.
                if let Some((name, email, signed_in)) = slot_active_login(paths, tool) {
                    // The slot carries the login; its tier is not recorded
                    // anywhere the pointer can reach, and null already means
                    // unknown here. `logged_in` follows the credential, not the
                    // pointer - an empty slot is selected, not signed in.
                    return serde_json::json!({
                        "tool": tool, "logged_in": signed_in, "unreadable": false,
                        "email": email, "tier": null, "profile": name, "expired": null,
                    });
                }
                match adapter.identity(paths) {
                    Err(_) => serde_json::json!({
                        "tool": tool, "logged_in": false, "unreadable": true,
                        "email": null, "tier": null, "profile": null, "expired": null,
                    }),
                    Ok(None) => serde_json::json!({
                        "tool": tool, "logged_in": false, "unreadable": false,
                        "email": null, "tier": null, "profile": null, "expired": null,
                    }),
                    Ok(Some(id)) => serde_json::json!({
                        "tool": tool,
                        "logged_in": true,
                        "unreadable": false,
                        "email": id.email,
                        "tier": id.tier,
                        "profile": matched_profile_name(&store, tool, &id.account_id),
                        "expired": login_is_ancient(id.expires_at, now_ms()),
                    }),
                }
            })
            .collect();
        println!("{}", serde_json::to_string(&rows)?);
        return Ok(0);
    }
    for adapter in adapters::all() {
        let tool = adapter.name();
        if let Some((name, email, signed_in)) = slot_active_login(paths, tool) {
            let who = slot_who(&name, email, signed_in, tool);
            println!("{tool}: {who} (profile '{name}')");
            // The abandoned login is the one an unshimmed launch still uses, so
            // it belongs on the screen that claims to say who is active.
            if let Some(live) = tool_dir_disagrees(&store, paths, tool, &name) {
                println!(
                    "  (a plain `{}` would launch on '{live}' instead - `swapdex shim` \
                     makes it follow your switches)",
                    tool_binary(tool)
                );
            }
            continue;
        }
        match adapter.identity(paths) {
            Err(_) => println!(
                "{tool}: login file unreadable - `swapdex use <profile>` can replace it \
                 (or log in again in the tool)"
            ),
            Ok(None) => match macos_keychain_note(paths, tool) {
                Some(note) => println!("{tool}: not manageable - {note}"),
                None => println!("{tool}: not logged in"),
            },
            Ok(Some(id)) => {
                let name = matched_profile_name(&store, tool, &id.account_id);
                let saved = match &name {
                    Some(n) => format!("profile '{n}'"),
                    None => "not saved - run `swapdex add <name>`".to_string(),
                };
                let exp = expiry_note(id.expires_at, tool);
                println!("{tool}: {} ({saved}){exp}", identity_line(&id));
            }
        }
    }
    // A1: warn about the world-readable .claude.json (holds account PII).
    if let Ok(meta) = std::fs::metadata(paths.claude_config_json()) {
        use std::os::unix::fs::PermissionsExt;
        if meta.permissions().mode() & 0o077 != 0 {
            println!(
                "note: {} is group/world-readable (holds your account email/org); `chmod 600` it",
                crate::util::redact_path(&paths.claude_config_json().display().to_string())
            );
        }
    }
    // Ecosystem: best-effort session count grouped by account (session_link).
    if let Some(line) = crate::session_link::status_line(paths) {
        println!("{line}");
    }
    Ok(0)
}

/// `proxy` - run proxy mode in the foreground. Claude Code pointed at it
/// (`ANTHROPIC_BASE_URL`) gets its account chosen per request, so a RUNNING
/// conversation can change accounts without a restart or a resume.
#[allow(clippy::too_many_arguments)]
pub fn proxy(
    paths: &Paths,
    port: u16,
    account: Option<String>,
    sel: Option<ToolSel>,
    auto: bool,
    no_auto: bool,
    ensure: bool,
    threshold: Option<f64>,
) -> Result<i32> {
    // Refuse where the relay does not exist, rather than starting a Claude proxy
    // under another tool's name and port.
    let tool = slot_tool(sel);
    if !crate::proxy::carries(tool) {
        eprintln!("{}", crate::proxy::cannot_carry(tool));
        return Ok(2);
    }
    if threshold.is_some_and(|value| !crate::settings::valid_threshold(value)) {
        eprintln!("swapdex: --threshold expects a finite fraction greater than 0 and at most 1");
        return Ok(2);
    }
    if ensure {
        return proxy_ensure(paths, port, tool);
    }
    // A flag decides THIS run; no flag means "whatever the setting says", and the
    // proxy re-reads that on every request - so `swapdex auto on` reaches one that
    // is already running rather than waiting for a restart nobody performs.
    let auto = match (auto, no_auto) {
        (true, _) => Some(true),
        (_, true) => Some(false),
        _ => None,
    };
    // A threshold means "step off before the wall", which needs one usage read per
    // account; opt-in, so the proxy originates no traffic unless asked.
    let threshold_pinned = threshold.is_some();
    let opts = crate::proxy::Opts {
        port,
        account,
        tool: slot_tool(sel).to_string(),
        auto,
        threshold,
        threshold_pinned,
    };
    crate::proxy::serve(paths, &opts)?;
    // The serve loop has no exit of its own, so reaching here means something
    // ended it. A supervised proxy that exits 0 is restarted in silence -
    // systemd logs nothing for a clean exit - and this one did that twice in
    // six seconds with no record anywhere of why. Leave one.
    println!("  the proxy stopped serving and is exiting; nothing asked it to");
    std::io::Write::flush(&mut std::io::stdout()).ok();
    Ok(0)
}

/// The port `swapdex proxy` listens on unless told otherwise. Codex's proxy
/// takes the next one, so both tools' shims can start their own.
pub const DEFAULT_PROXY_PORT: u16 = 8787;

/// The port a tool's proxy binds when nobody names one. Codex takes the next
/// port so both can run at once - the rule `proxy --ensure` has always applied,
/// now stated once so anything else writing a proxy invocation agrees with it.
/// One port per tool. Two proxies cannot share one, and the port is written
/// into the service unit - gemini and antigravity both used to take Claude's.
pub fn default_port_for(tool: &str) -> u16 {
    match tool {
        "codex" => DEFAULT_PROXY_PORT + 1,
        "gemini" => DEFAULT_PROXY_PORT + 2,
        "antigravity" => DEFAULT_PROXY_PORT + 3,
        _ => DEFAULT_PROXY_PORT,
    }
}

/// `proxy --ensure` - print the port of a live proxy, starting one in the
/// background if there is none. This is what lets a plain `claude` (through the
/// shim) get proxy mode without the user running or remembering anything. The
/// private passthrough exit is reserved for a checked direct route; all other
/// failures stop the shim before the native client can use another login.
fn proxy_ensure(paths: &Paths, port: u16, tool: &str) -> Result<i32> {
    // A hermetic root is a sandbox, and the proxy is deliberately DETACHED so it
    // outlives the shell that asked for it. Under a temporary store that is wrong
    // twice: the daemon outlives the store it was pointed at, and it keeps the
    // port - so a run leaves a listener on 127.0.0.1 answering for a directory
    // that no longer exists. One was found still bound hours after its store had
    // been deleted.
    // Two proxies cannot share a port. Codex takes the next one, so the shim for
    // either tool can start its own without asking the user to pick.
    let startup = crate::slots::proxy_startup_route(paths, tool)?;
    if startup == crate::slots::ProxyStartupRoute::Unmanaged {
        return Ok(crate::shim::PROXY_PASSTHROUGH_EXIT_STATUS);
    }

    let mut port = if tool == "codex" && port == DEFAULT_PROXY_PORT {
        port + 1
    } else {
        port
    };
    if let Some((pid, running, build)) = crate::proxy::running_proxy_for(paths, tool) {
        if build == crate::proxy::build_id() {
            println!("{running}");
            return Ok(0);
        }
        // A proxy from an older build is still answering: updating swapdex does
        // not update what is already running, so a fix can be installed, verified,
        // and still not be what serves the next request. Replace it on the SAME
        // port, because sessions already point at that port and would otherwise
        // be left talking to nothing.
        //
        // Through the supervisor when one owns it. Signalling a supervised proxy
        // makes the supervisor count a crash and wait out its restart delay -
        // five seconds on systemd - so every routine upgrade both dropped the
        // request in flight and added one to the restart count that `service
        // status` now reports as "it is not staying up". The supervisor's own
        // restart is orderly and immediate; the signal stays as the fallback,
        // because leaving a stale proxy serving is worse than either.
        // paths.home(), never dirs::home_dir(): under a test root the latter
        // still points at the real home, and asking the supervisor there
        // restarts the developer's own proxy from inside a sandboxed run.
        if let Err(why) = crate::service::restart_via_supervisor(Some(paths.home()), tool) {
            // Say it. The fallback is worse for the user - a five second gap
            // and a crash on the supervisor's record - so a machine that takes
            // it every time must not look like one that never does.
            eprintln!("swapdex: replacing the proxy by signal instead ({why})");
            unsafe { libc::kill(pid, libc::SIGTERM) };
        }
        // Two endings, and starting a proxy on the wrong one is how a pair of
        // them would displace each other for as long as the machine is on: the
        // supervisor puts the current build back (use it, start nothing), or
        // the old proxy simply goes (start one below).
        for _ in 0..60 {
            match crate::proxy::running_proxy_for(paths, tool) {
                None => break,
                Some((_, p, b)) if b == crate::proxy::build_id() => {
                    println!("{p}");
                    return Ok(0);
                }
                _ => std::thread::sleep(std::time::Duration::from_millis(50)),
            }
        }
        port = running;
    }
    // A live proxy keeps explicit passthrough switchable: `serve <account>` can
    // move the next turn of the same session back onto a managed payer. Without
    // one, `off` intentionally authorizes the native client's own route and must
    // not start a new background service merely to pass traffic through.
    if startup == crate::slots::ProxyStartupRoute::ExplicitPassthrough {
        return Ok(crate::shim::PROXY_PASSTHROUGH_EXIT_STATUS);
    }
    let Ok(exe) = std::env::current_exe() else {
        return Ok(1);
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.arg("proxy")
        .arg("--port")
        .arg(port.to_string())
        .arg("--tool")
        .arg(tool)
        .stdin(std::process::Stdio::null());
    // Send its voice to a file rather than /dev/null. Discarding it meant that
    // on a machine where the shim starts the proxy, nothing recorded which
    // account served which turn - and that silence made a real switching bug
    // undiagnosable: three wrong conclusions before the log was added by hand.
    let log = paths.proxy_log(tool);
    let piped = std::fs::create_dir_all(log.parent().unwrap_or(&log))
        .ok()
        .and_then(|()| {
            std::fs::OpenOptions::new()
                .create(true)
                .append(true)
                .open(&log)
                .ok()
        });
    // A log we cannot open must not stop the proxy from starting: being unable
    // to record is bad, being unable to serve is worse.
    match piped.and_then(|f| f.try_clone().ok().map(|e| (f, e))) {
        Some((out, err)) => {
            cmd.stdout(std::process::Stdio::from(out))
                .stderr(std::process::Stdio::from(err));
        }
        None => {
            cmd.stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null());
        }
    }
    // Detach: the proxy must outlive this short-lived helper and the shell that
    // started it, and must never take the terminal (it would fight `claude` for
    // stdin) or die with the session.
    #[cfg(unix)]
    {
        use std::os::unix::process::CommandExt;
        unsafe {
            cmd.pre_exec(|| {
                libc::setsid();
                Ok(())
            });
        }
    }
    if cmd.spawn().is_err() {
        return Ok(1);
    }
    // Wait briefly for it to announce itself; a proxy that cannot bind must not
    // hang the launch of Claude.
    for _ in 0..40 {
        if let Some((_, p, _)) = crate::proxy::running_proxy_for(paths, tool) {
            println!("{p}");
            return Ok(0);
        }
        std::thread::sleep(std::time::Duration::from_millis(50));
    }
    Ok(1)
}

/// The instructions both assistants get. Kept deliberately small: run one swapdex
/// command and report what happened, so switching accounts does not mean leaving
/// the conversation for another terminal.
/// The switcher's instructions, written for ONE tool. A switcher offered inside
/// Claude that lists Codex accounts (or switches one) is answering a question
/// nobody asked - each assistant should only ever see, and only ever move, its
/// own accounts.
fn slash_body(tool: &str, host: &str) -> String {
    format!(
        "**If arguments were given**, run `swapdex serve $ARGUMENTS --tool {tool}`, then \
         report the result in one line.\n\
         \n\
         **If not**, do not make the user recall account names:\n\
         \n\
         1. Run `swapdex ls` and keep ONLY the accounts tagged `{tool}` - this is {host}, \
         so accounts for other tools are not offered and never switched.\n\
         2. Ask the user to choose one with the AskUserQuestion tool, so they can pick with \
         the arrow keys. One option per account, labelled with the account name, with its \
         email and current state as the description. Put the active one first and say it is \
         active. If there are more accounts than the tool allows, offer the ones not \
         currently active and let the rest come from free text.\n\
         3. Run `swapdex serve <the account they chose> --tool {tool}` and report the \
         result in one line. `serve` is the right verb here: it changes which account \
         pays for the turns and leaves this conversation exactly where it is. `use` \
         would move the store the conversation lives in, which is never what someone \
         asking mid-conversation means.\n\
         \n\
         Report what swapdex printed and nothing beyond it. Its last line says whether \
         anything running actually moved: with a proxy the next turn of THIS session is \
         served by the new account, and without one the change reaches only the next \
         launch while this conversation keeps the account it began with. Do not promise \
         the stronger of the two - a switch announced as live when it was not is worse \
         than no switch, because the work continues on the account the user thinks they \
         left. If the output says the shim is not taking effect, say so and stop.\n"
    )
}

/// `slash` - install the Claude Code slash command, so an account switch can be
/// typed into the conversation instead of another terminal.
/// The Claude Code form: a command file with the frontmatter its picker reads.
fn claude_command_body() -> String {
    format!(
        "---\ndescription: Switch the Claude account serving this session (swapdex)\n---\n\n{}",
        slash_body("claude-code", "Claude Code")
    )
}

/// The Codex form: a skill, with the frontmatter Codex reads.
fn codex_skill_body() -> String {
    format!(
        "---\nname: swap\ndescription: >-\n  Switch the Codex account serving this session \
         (swapdex). Use when the user asks to change accounts, says an account is out of \
         quota, or types /swap.\n---\n\n{}",
        slash_body("codex", "Codex")
    )
}

/// `threshold [<fraction>|off]` - read or set the point at which the proxy steps
/// off an account. A setting rather than a flag because the proxy the shim starts
/// takes no flags, and that is the one doing the work day to day.
pub fn threshold(paths: &Paths, value: Option<&str>) -> Result<i32> {
    let cfg = crate::settings::load(paths);
    let Some(value) = value else {
        match cfg.threshold() {
            Some(t) => println!(
                "stepping off an account at {} used",
                crate::settings::threshold_label(t)
            ),
            None => println!(
                "no threshold - the proxy waits for an account to refuse a turn \
                 (`swapdex threshold 0.9` steps off earlier)"
            ),
        }
        return Ok(0);
    };
    let v = value.trim();
    if v.eq_ignore_ascii_case("off") || v.eq_ignore_ascii_case("none") {
        crate::settings::update(paths, |c| c.proxy_threshold = None)?;
        println!("threshold off - the proxy waits for a refusal before moving");
        return Ok(0);
    }
    // Accept "0.9" and "90%"/"90" alike: both are how people say this.
    let percentage = v.strip_suffix('%');
    let parsed = percentage.unwrap_or(v).parse::<f64>().ok().map(|n| {
        if percentage.is_some() || n > 1.0 {
            n / 100.0
        } else {
            n
        }
    });
    let Some(t) = parsed.filter(|t| crate::settings::valid_threshold(*t)) else {
        eprintln!(
            "swapdex: expected a fraction like 0.9, a percentage like 90%, or `off` - got '{v}'"
        );
        return Ok(2);
    };

    crate::settings::update(paths, |c| c.proxy_threshold = Some(t))?;
    // Report what was just stored, not the value read before the write: `cfg`
    // is the pre-edit snapshot and would print the OLD threshold back.
    println!(
        "stepping off an account at {} used - it hands the session on before \
         being refused",
        crate::settings::threshold_label(t)
    );
    Ok(0)
}

/// `slash` - install the in-conversation switcher for both assistants, so an
/// account change can be typed where you already are rather than in another
/// terminal. Claude Code reads `~/.claude/commands`, Codex reads `~/.codex/skills`.
/// Hand the conversation you were just in to an account that still has room.
///
/// The proxy already moves a RUNNING session between accounts. This is the
/// other case: the turn is over, you are out, and the conversation lives in one
/// account's store. Under swapdex's slot model each account has its own
/// `CLAUDE_CONFIG_DIR` with its own `projects/`, so continuing elsewhere means
/// carrying the transcript across that boundary - which is sessionwiki's job,
/// and why this command orchestrates rather than implements.
///
/// Nothing here is silent. Each step says what it did, and a step that could
/// not run says so rather than letting the next one look like it worked.
/// Make every conversation reachable from every account.
///
/// Slots created before transcripts were shared keep their own `projects/`, so
/// a conversation started on one account is invisible from the others. This
/// carries those conversations into the shared store and points the slot at it.
///
/// Nothing is deleted. The slot's old directory is renamed aside, not removed,
/// because it holds real conversations and a rename is undoable while a delete
/// is not.
/// The files Codex keeps its conversation LIST in, beside the rollout files.
///
/// Sharing `sessions/` shares the transcripts. It does not share the store the
/// picker reads: Codex moved its conversation list into a paginated thread
/// history, so `share-history` reported success while a switched account still
/// opened an empty picker, and a slot that had never run Codex had no store at
/// all. Same defect the Claude side fixed for `projects/` - not lost, but
/// invisible, which for a resume list is the same thing.
const CODEX_THREAD_STORE: &[&str] = &["thread_history_1.sqlite", "session_index.jsonl"];

/// Link one slot's thread store to the shared one, and never over it.
///
/// A slot that already has its own store holds conversations the shared one may
/// not, and replacing it with a link would put them out of reach - the exact
/// harm this command exists to undo. Those are reported and left alone; merging
/// two sqlite stores is not something to do behind someone's back.
fn share_codex_thread_store(
    tool: &str,
    bare: &std::path::Path,
    slot: &std::path::Path,
    name: &str,
    dry_run: bool,
) -> usize {
    if tool != "codex" {
        return 0;
    }
    let mut touched = 0;
    for file in CODEX_THREAD_STORE {
        let src = bare.join(file);
        let own = slot.join(file);
        if !src.exists() {
            continue;
        }
        if std::fs::symlink_metadata(&own).is_ok_and(|m| m.file_type().is_symlink()) {
            continue;
        }
        if own.exists() {
            println!(
                "  {name} - keeps its own {file}; linking would hide the conversations \
                 only it has, so it was left alone"
            );
            continue;
        }
        if !dry_run {
            #[cfg(unix)]
            std::os::unix::fs::symlink(&src, &own).ok();
        }
        println!("  {name} - {file} linked to the shared history");
        touched += 1;
    }
    touched
}

pub fn share_history(paths: &Paths, tool: &str, dry_run: bool) -> Result<i32> {
    let bare = match tool {
        "codex" => paths.codex_dir().to_path_buf(),
        _ => paths.claude_dir().to_path_buf(),
    };
    let dir_name = if tool == "codex" {
        "sessions"
    } else {
        "projects"
    };
    let shared = bare.join(dir_name);

    let slots = crate::slots::Slots::open_for(paths, tool)
        .map(|s| s.list())
        .unwrap_or_default();
    let mut touched = 0;
    for r in slots {
        // Before the transcript directory, because a slot whose `sessions` is
        // already a link exits below - and that is exactly the slot whose
        // thread store was never linked, on every machine already repaired.
        touched += share_codex_thread_store(tool, &bare, &r.config_dir, &r.name, dry_run);
        let own = r.config_dir.join(dir_name);
        if own == shared {
            continue;
        }
        if std::fs::symlink_metadata(&own).is_ok_and(|m| m.file_type().is_symlink()) {
            continue; // already shared
        }
        if !own.is_dir() {
            // Never linked and nothing of its own: just point it at the shared
            // store so the next session lands somewhere everyone can see.
            if !dry_run {
                std::fs::create_dir_all(&shared)?;
                #[cfg(unix)]
                std::os::unix::fs::symlink(&shared, &own).ok();
            }
            println!("  {} - linked to the shared history", r.name);
            touched += 1;
            continue;
        }
        let carried = crate::slots::carry_history_into_shared(&own, &shared, dry_run)?;
        println!(
            "  {} - {carried} conversation(s) only it had, carried over",
            r.name
        );
        if !dry_run {
            let aside = r.config_dir.join(format!("{dir_name}.before-sharing"));
            if aside.exists() {
                anyhow::bail!(
                    "{} already has {} - move it away first; nothing was changed for this account",
                    r.name,
                    aside.display()
                );
            }
            std::fs::rename(&own, &aside)?;
            #[cfg(unix)]
            std::os::unix::fs::symlink(&shared, &own).ok();
            println!("    its old copy kept at {}", aside.display());
        }
        touched += 1;
    }
    if touched == 0 {
        println!("every account already shares its history - nothing to do");
    } else if dry_run {
        println!("(dry run - nothing changed)");
    } else {
        println!("done - every conversation is now reachable from every account");
    }
    Ok(0)
}

pub fn install_slash(paths: &Paths) -> Result<i32> {
    // The dirs belong to the assistants rather than to swapdex's store, but the
    // HOME they hang off is still the one `paths` names: asking `dirs` for it
    // meant a run under `SWAPDEX_ROOT` wrote into the real `~/.claude`, which is
    // the one thing that variable exists to prevent.
    let home = paths.home().to_path_buf();
    let mut installed = 0;

    let claude_dir = home.join(".claude").join("commands");
    match crate::atomic::write_managed(
        &claude_dir.join("swap.md"),
        claude_command_body().as_bytes(),
    ) {
        Ok(()) => {
            println!(
                "Claude Code: /swap  ({})",
                crate::util::redact_path(&claude_dir.join("swap.md").display().to_string())
            );
            installed += 1;
        }
        Err(e) => eprintln!("swapdex: could not install the Claude command: {e}"),
    }

    let codex_dir = home.join(".codex").join("skills").join("swap");
    match crate::atomic::write_managed(&codex_dir.join("SKILL.md"), codex_skill_body().as_bytes()) {
        Ok(()) => {
            println!(
                "Codex:       /swap  ({})",
                crate::util::redact_path(&codex_dir.join("SKILL.md").display().to_string())
            );
            installed += 1;
        }
        Err(e) => eprintln!("swapdex: could not install the Codex skill: {e}"),
    }

    if installed == 0 {
        return Ok(1);
    }
    println!("  type `/swap` to pick an account, or `/swap <name>` to go straight there");
    println!("  shell: `swapdex serve <name> --tool claude` or `--tool codex`");
    Ok(0)
}

/// `auto [on|off]` - read or set auto-continue: whether proxy mode may hand a
/// spent session to another account by itself. Kept as its own setting rather
/// than a flag you must remember, since the whole point is not having to think
/// about accounts.
pub fn auto(paths: &Paths, state: Option<&str>) -> Result<i32> {
    let s = crate::settings::load(paths);
    let Some(state) = state else {
        println!("auto-continue is {}", if s.auto() { "on" } else { "off" });
        return Ok(0);
    };
    let on = match state.trim().to_ascii_lowercase().as_str() {
        "on" | "true" | "yes" | "1" => true,
        "off" | "false" | "no" | "0" => false,
        other => {
            eprintln!("swapdex: expected `on` or `off`, got '{other}'");
            return Ok(2);
        }
    };

    crate::settings::update(paths, |c| c.proxy_auto = Some(on))?;
    println!(
        "auto-continue {}{}",
        if on { "on" } else { "off" },
        if on {
            " - a spent account hands the running session to another one"
        } else {
            " - the proxy stays on the account you chose"
        }
    );
    Ok(0)
}

/// `ui` - a numbered interactive picker: see every profile (active marked from
/// the live login), type a number, switch. Plain Enter cancels. Deliberately
/// stdin-only (no raw-mode/TUI crate pulls a socket library into the graph),
/// and the switch itself goes through the exact same `use` path - a human
/// picking a number IS the explicit `swapdex use <name>`.
pub fn ui(paths: &Paths) -> Result<i32> {
    use std::io::IsTerminal;
    let real_tty = std::io::stdin().is_terminal() && std::io::stdout().is_terminal();
    let tty = real_tty || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
    if !tty {
        eprintln!("swapdex: `ui` is interactive and needs a terminal (try `swapdex use <name>`)");
        return Ok(2);
    }
    // A real terminal gets the full-screen picker; the pipe-driven path (tests,
    // SWAPDEX_ASSUME_TTY) keeps the plain numbered prompt below. TERM=dumb /
    // empty (Emacs shell, some CI) cannot render ANSI - crossterm never checks
    // TERM, so we do.
    let dumb = std::env::var("TERM")
        .map(|t| t.is_empty() || t == "dumb")
        .unwrap_or(true);
    if real_tty && !dumb {
        return ui_tui(paths);
    }
    let store = Store::open(paths)?;
    let (profiles, slot_dirs, _) = merged_accounts(paths, &store);
    if profiles.is_empty() {
        println!("No accounts saved yet.");
        println!("  guided setup:  swapdex setup");
        return Ok(0);
    }
    let active = active_by_tool(&store, paths);
    let color = crate::util::color_enabled();
    println!();
    for (i, p) in profiles.iter().enumerate() {
        let (email, tier, marker) = profile_summary(&store, &p.name, &p.tools);
        // A slot-only row has no snapshot to name it; its own config does.
        let email = best_identity(
            email,
            slot_dirs
                .get(&p.name)
                .and_then(|d| crate::proxy::creds::any_slot_email(d)),
        );
        let at: Vec<&str> = active
            .iter()
            .filter(|(_, n)| n == &p.name)
            .map(|(t, _)| *t)
            .collect();
        let star = if at.is_empty() { "  " } else { "* " };
        let ident = identity_column(email, tier);
        let warn = marker.map(|m| format!("  ({m})")).unwrap_or_default();
        let line = format!(
            "  {}) {star}{} {} [{}]{warn}",
            i + 1,
            fit(&p.name, 16),
            fit(&ident, 32),
            p.tools.join(", ")
        );
        if color && !at.is_empty() {
            println!("\x1b[1m{line}\x1b[0m");
        } else {
            println!("{line}");
        }
    }
    if let Some(line) = crate::session_link::status_line(paths) {
        println!("\n  {line}");
    }
    println!();
    loop {
        let Some(ans) = prompt(
            &format!("switch to [1-{}] (Enter cancels): ", profiles.len()),
            "",
        ) else {
            println!("cancelled - nothing switched.");
            return Ok(0);
        };
        if ans.is_empty() || ans.eq_ignore_ascii_case("q") {
            println!("cancelled - nothing switched.");
            return Ok(0);
        }
        match ans.parse::<usize>() {
            Ok(n) if (1..=profiles.len()).contains(&n) => {
                let name = profiles[n - 1].name.clone();
                println!();
                // Timeline state BEFORE the switch below appends its own
                // event - otherwise the first-ever switch would skip the
                // fallback written exactly for it.
                let first_time = crate::session_link::read_timeline(paths).is_empty();
                let rc = use_account(paths, &name, None, false, false)?;
                if rc == 0 {
                    ui_session_hints(paths, &name, first_time)?;
                }
                return Ok(rc);
            }
            _ => {
                println!(
                    "  pick a number between 1 and {} (Enter cancels)",
                    profiles.len()
                );
            }
        }
    }
}

/// One session row for the post-switch menu, whatever the source.
pub(crate) enum MenuSession {
    Wiki(crate::session_link::RecentSession),
    Native(crate::native_sessions::NativeSession),
}

impl MenuSession {
    pub(crate) fn describe(&self) -> (String, i64, String, String) {
        match self {
            MenuSession::Wiki(s) => (
                s.id.chars().take(6).collect(),
                s.started,
                s.tool.clone(),
                s.title.clone(),
            ),
            MenuSession::Native(s) => (
                s.id.chars().take(6).collect(),
                s.started,
                s.tool.to_string(),
                s.title.clone(),
            ),
        }
    }
}

/// Recent sessions for the just-switched profile - sessionwiki when present
/// (cross-tool, richer), the tools' own on-disk stores otherwise. Never
/// requires sessionwiki (real-use feedback).
pub(crate) fn recent_menu_sessions(
    paths: &Paths,
    name: &str,
    first_time: bool,
    n: usize,
) -> (Vec<MenuSession>, String) {
    recent_menu_sessions_for_tool(paths, name, first_time, n, None)
}

/// The picker has already selected a provider. Apply that filter before any
/// recent-session limit, including the any-account and native fallbacks.
pub(crate) fn recent_menu_sessions_for_tool(
    paths: &Paths,
    name: &str,
    first_time: bool,
    n: usize,
    tool: Option<&str>,
) -> (Vec<MenuSession>, String) {
    // sessionwiki path (attributed, then honest any-account fallback).
    if let Some(r) = crate::session_link::recent_sessions_for_tool(paths, name, n, tool) {
        if !r.is_empty() {
            return (
                r.into_iter().map(MenuSession::Wiki).collect(),
                format!("recent sessions on '{name}' (sessionwiki):"),
            );
        }
        // No sessions attributed to this account: still show recent ones so
        // the menu is useful (you can resume any). Attribution is best-effort;
        // an empty menu is worse than a broad one.
        if let Some(any) = crate::session_link::recent_sessions_any_for_tool(n, tool) {
            if !any.is_empty() {
                let label = if first_time {
                    "recent sessions (any account - attribution starts with your first switch):"
                } else {
                    "recent sessions (any account):"
                };
                return (
                    any.into_iter().map(MenuSession::Wiki).collect(),
                    label.to_string(),
                );
            }
        }
        // sessionwiki is present but returned NOTHING (installed yet never
        // `sessionwiki sync`ed, or a genuinely empty index). Do NOT stop here -
        // fall through to the native reader so the real on-disk sessions still
        // show, instead of a blank menu that hides sessions the user can see.
    }
    // Native path: straight from ~/.claude and ~/.codex.
    let events = crate::session_link::read_timeline(paths);
    let mine = crate::native_sessions::recent_for_tool_matching(paths, n, tool, |tool, started| {
        crate::session_link::active_at(&events, tool, started).as_deref() == Some(name)
    });
    if !mine.is_empty() {
        return (
            mine.into_iter().map(MenuSession::Native).collect(),
            format!("recent sessions on '{name}':"),
        );
    }
    let any: Vec<MenuSession> = crate::native_sessions::recent_for_tool(paths, n, tool)
        .into_iter()
        .map(MenuSession::Native)
        .collect();
    if !any.is_empty() {
        let label = if first_time {
            "recent sessions (any account - attribution starts with your first switch):"
        } else {
            "recent sessions (any account):"
        };
        return (any, label.to_string());
    }
    (Vec::new(), String::new())
}

/// Exec the resume for a picked menu session (never returns on success).
fn exec_menu_resume(s: &MenuSession) -> anyhow::Error {
    match s {
        MenuSession::Wiki(w) => {
            println!("opening session {} via sessionwiki...", w.id);
            exec_sessionwiki_resume(&w.id)
        }
        MenuSession::Native(nat) => {
            println!("resuming {} session {}...", pretty_tool(nat.tool), nat.id);
            crate::native_sessions::exec_resume(nat)
        }
    }
}

/// Post-switch continuity: recent sessions of the picked account + the
/// numbered resume handoff. Shared by the numbered picker and the TUI.
fn ui_session_hints(paths: &Paths, name: &str, first_time: bool) -> Result<()> {
    // `first_time` is captured by the CALLER before the switch writes its own
    // timeline event.
    let (recent, label) = recent_menu_sessions(paths, name, first_time, 3);
    // Offer "open a NEW X" only for tools THIS profile actually holds: launching
    // a tool that was NOT switched would open the user's unrelated live account
    // (the plain-picker twin of the TUI's new_conv_for filtering).
    let ptools = profile_tools(paths, name);
    let choices: Vec<(&str, &str, &str)> = [
        ("c", "claude-code", "claude"),
        ("x", "codex", "codex"),
        ("g", "gemini", "gemini"),
        ("a", "antigravity", "agy"),
    ]
    .into_iter()
    .filter(|(_, tool, _)| ptools.iter().any(|t| t == tool))
    .collect();
    let new_hint = if choices.is_empty() {
        String::new()
    } else {
        let keys = choices
            .iter()
            .map(|(k, _, p)| format!("{k} new {p}"))
            .collect::<Vec<_>>()
            .join(", ");
        format!(", {keys}")
    };
    let pick = |ans: &str| -> Option<&'static str> {
        launch_letter(ans).filter(|t| choices.iter().any(|(_, ct, _)| ct == t))
    };
    if !recent.is_empty() {
        println!("\n{label}");
        for (i, s) in recent.iter().enumerate() {
            let (id6, started, tool, title) = s.describe();
            let age = age_line((started.max(0) as u128) * 1_000_000_000);
            let line = format!(
                "  {}) {id6}  {:>7}  {}  {}",
                i + 1,
                age,
                fit(&format!("[{tool}]"), 13),
                fit(&title, 44)
            );
            println!("{}", line.trim_end());
        }
        if let Some(ans) = prompt(
            &format!(
                "open: [1-{}] resume that session{new_hint}, Enter skips: ",
                recent.len()
            ),
            "",
        ) {
            if let Ok(k) = ans.parse::<usize>() {
                if (1..=recent.len()).contains(&k) {
                    return Err(exec_menu_resume(&recent[k - 1]));
                }
            }
            if let Some(tool) = pick(&ans) {
                return Err(launch_in_folder(tool));
            }
        }
    } else if !choices.is_empty() {
        if let Some(ans) = prompt(&format!("open now?{new_hint} (Enter skips): "), "") {
            if let Some(tool) = pick(&ans) {
                return Err(launch_in_folder(tool));
            }
        }
    }
    Ok(())
}

/// The tools an account holds, however that account is registered.
fn profile_tools(paths: &Paths, name: &str) -> Vec<String> {
    Store::open(paths)
        .ok()
        .and_then(|s| {
            // The post-switch menu receives names from the merged picker. A
            // second snapshot-only lookup made every slot-only account lose
            // its "new conversation" action immediately after selection.
            merged_accounts(paths, &s)
                .0
                .into_iter()
                .find(|p| p.name == name)
                .map(|p| p.tools)
        })
        .unwrap_or_default()
}

/// Ask for the project folder (conversations are per-directory), then exec.
/// Enter keeps the current directory.
fn launch_in_folder(tool: &str) -> anyhow::Error {
    let dir = prompt("folder to open in [current dir]: ", "")
        .filter(|d| !d.is_empty())
        .map(|d| {
            if d == "~" {
                if let Some(home) = dirs::home_dir() {
                    return home;
                }
            }
            if let Some(rest) = d.strip_prefix("~/") {
                if let Some(home) = dirs::home_dir() {
                    return home.join(rest);
                }
            }
            std::path::PathBuf::from(d)
        });
    if let Some(d) = &dir {
        if !d.is_dir() {
            return anyhow::anyhow!("not a directory: {}", d.display());
        }
    }
    println!("opening {}...", pretty_tool(tool));
    exec_tool(tool, dir.as_deref())
}

/// c/x/g/a -> the tool a post-switch launch letter means.
fn launch_letter(ans: &str) -> Option<&'static str> {
    match ans.to_ascii_lowercase().as_str() {
        "c" => Some("claude-code"),
        "x" => Some("codex"),
        "g" => Some("gemini"),
        "a" => Some("antigravity"),
        _ => None,
    }
}

/// Retain the last successful Claude figures when the latest provider read
/// could only report a failure. The failure reason still belongs to this row.
fn merge_cached_claude_usage(
    claude: &mut Vec<(String, crate::tui::Usage)>,
    cached: crate::quota_cache::Cache,
) {
    for (name, e) in cached {
        if let Some((_, u)) = claude
            .iter_mut()
            .find(|(n, u)| *n == name && u.five_h.is_none() && u.seven_d.is_none())
        {
            u.five_h = e.five_h;
            u.five_h_reset = e.five_h_reset;
            u.seven_d = e.seven_d;
            u.seven_d_reset = e.seven_d_reset;
            u.observed_at = Some(e.at);
            // The newer read failed. Keep its cause beside the old figures,
            // and preserve the extra-usage state recorded with those figures.
            u.on_credits = e.on_credits;
            continue;
        }
        if claude.iter().any(|(n, _)| *n == name) {
            continue;
        }
        claude.push((
            name,
            crate::tui::Usage {
                five_h: e.five_h,
                five_h_reset: e.five_h_reset,
                seven_d: e.seven_d,
                seven_d_reset: e.seven_d_reset,
                observed_at: Some(e.at),
                note: None,
                on_credits: e.on_credits,
                ident: None,
            },
        ));
    }
}

/// The persistent full-screen ui: one alternate-screen session, everything
/// inside it. Switch/restore run this same binary as a subprocess (output
/// condensed into the status line - no second switching implementation);
/// opening a conversation is the one action that leaves.
fn ui_tui(paths: &Paths) -> Result<i32> {
    struct Ctx<'a> {
        paths: &'a Paths,
        last_sessions: Vec<MenuSession>,
        /// Timeline emptiness CAPTURED BEFORE the last switch wrote its own
        /// events - the only correct "first time" signal (audit).
        pre_switch_first: bool,
    }
    fn run_self(args: &[&str]) -> (bool, String) {
        match crate::self_exe::output(args) {
            Ok(out) => {
                let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
                text.push_str(&String::from_utf8_lossy(&out.stderr));
                let mut msg = text
                    .lines()
                    .filter(|l| !l.trim().is_empty())
                    .collect::<Vec<_>>()
                    .join("  |  ");
                if msg.chars().count() > 160 {
                    msg = msg.chars().take(159).collect::<String>() + "…";
                }
                (out.status.success(), msg)
            }
            Err(e) => (false, format!("failed: {e}")),
        }
    }
    /// Read every account's usage. A free function so the dashboard can run it
    /// on a thread: doing it on the loop froze the screen for seconds.
    fn read_quota_usage(paths: &Paths) -> Vec<(crate::tui::AccountKey, crate::tui::Usage)> {
        let Ok(out) = crate::self_exe::output(&["quota", "--json"]) else {
            return Vec::new();
        };
        let Ok(v) = serde_json::from_slice::<serde_json::Value>(&out.stdout) else {
            return Vec::new();
        };
        // Accept an array of account objects or {"accounts": [...]}.
        let arr = v
            .as_array()
            .cloned()
            .or_else(|| v.get("accounts").and_then(|a| a.as_array()).cloned())
            .unwrap_or_default();
        let mut claude: Vec<(String, crate::tui::Usage)> = arr
            .iter()
            .filter_map(|acc| {
                // `name` may carry an " (active)" marker; strip it to match Row.name.
                let name = acc
                    .get("name")?
                    .as_str()?
                    .trim_end_matches(" (active)")
                    .to_string();
                let win = |key: &str| -> (Option<f64>, Option<i64>) {
                    let w = acc.get(key);
                    (
                        w.and_then(|w| w.get("used_pct")).and_then(|v| v.as_f64()),
                        w.and_then(|w| w.get("resets_at")).and_then(|v| v.as_i64()),
                    )
                };
                let (five_h, five_h_reset) = win("five_hour");
                let (seven_d, seven_d_reset) = win("seven_day");
                // No numbers is still worth a row: empty tracks alone cannot
                // say whether the account was never asked, could not answer,
                // or has nothing left, and that ambiguity is exactly what
                // makes a healthy account look broken. Carry the reason.
                let note = match acc.get("status").and_then(|s| s.as_str()) {
                    Some("ok") | None => None,
                    Some("throttled") => Some("usage lookup limited - retrying".to_string()),
                    Some("unavailable") => acc
                        .get("detail")
                        .and_then(|detail| detail.as_str())
                        .map(|detail| format!("usage lookup coordination unavailable: {detail}")),
                    Some("expired") => Some("login expired".to_string()),
                    Some("offline") => acc
                        .get("detail")
                        .and_then(|d| d.as_str())
                        // The long-form fix belongs in `swapdex quota`; the
                        // row has one column, so keep the first clause.
                        .map(|d| d.split(" - ").next().unwrap_or(d).to_string()),
                    Some(other) => Some(other.to_string()),
                };
                if five_h.is_none() && seven_d.is_none() && note.is_none() {
                    return None;
                }
                Some((
                    name,
                    crate::tui::Usage {
                        five_h,
                        five_h_reset,
                        seven_d,
                        seven_d_reset,
                        // A live read has no age to disclose.
                        observed_at: None,
                        note,
                        on_credits: acc
                            .get("on_credits")
                            .and_then(|v| v.as_bool())
                            .unwrap_or(false),
                        ident: None,
                    },
                ))
            })
            .collect();
        // Fill the gaps from what was read before. The usage endpoint
        // rate-limits when several accounts are asked in a row, and an account
        // that could not be read this minute is not an account with no quota -
        // blanking it looks exactly like a broken one. The reading is recorded
        // by `quota` itself, where it is taken; a run that got nothing has
        // nothing to record and must not overwrite what it failed to refresh.
        merge_cached_claude_usage(&mut claude, crate::quota_cache::load(paths));
        // Codex usage comes from two places, and a row takes whichever answers.
        //
        // The account itself answers per CREDENTIAL and names itself. That is
        // the only source that can report a home holding no transcripts, which
        // is not a rare case - a saved account that has not been driven through
        // this machine has none, and its row was a permanent blank.
        //
        // Its transcripts answer for free and keep answering when the endpoint
        // is throttled or the machine is offline. A reading found there belongs
        // to the home it was read from; captioning it with whoever the switch
        // timeline said was PAYING moved real numbers onto the wrong row.
        //
        // This runs on a thread, off the render loop, which is what makes it
        // safe to put a network call here at all.
        let mut codex: Vec<(String, crate::tui::Usage)> = Vec::new();
        let codex_homes: Vec<(String, std::path::PathBuf)> =
            crate::slots::Slots::open_for(paths, "codex")
                .map(|s| {
                    s.list()
                        .into_iter()
                        .map(|r| (r.name, r.config_dir))
                        .collect()
                })
                .unwrap_or_default();
        // What the proxy recorded while serving. Windows past their reset are
        // dropped on load, so a turned-over window never lingers here.
        let codex_seen = crate::quota_cache::load_for(paths, "codex");
        // Read them concurrently, staggered: sequential reads made the numbers
        // arrive after the sum of every round trip.
        let fetched = fetch_codex_live(codex_homes.clone());
        let live_by_name: std::collections::HashMap<String, crate::codex_usage::Account> = fetched
            .iter()
            .filter_map(|(n, a, _)| a.clone().map(|a| (n.clone(), a)))
            .collect();
        // The accounts whose own token was rejected. Not the same as an account
        // the endpoint would not answer about, and the remembered reading must
        // not stand in for it: it would show a dead account as an unused one.
        let refused_names: std::collections::HashSet<String> = fetched
            .iter()
            .filter(|(_, _, refused)| *refused)
            .map(|(n, _, _)| n.clone())
            .collect();
        // Write the refusal down where a display that never fetches can see it.
        // The dashboard blanks the row itself; the status line reads only the
        // cache, and without this it went on aging a number that had stopped
        // arriving.
        for name in &refused_names {
            crate::quota_cache::note_token_rejected(paths, "codex", name, now_secs() as i64);
        }
        for (name, dir) in &codex_homes {
            let live = live_by_name.get(name).cloned();
            // Only when those transcripts are this account's alone. Codex slots
            // share `sessions/` by design, so on a normal machine every slot
            // reads the same file and the row would show one account's usage
            // under every name - which is exactly what was reported, on both
            // machines here.
            let all_dirs: Vec<std::path::PathBuf> =
                codex_homes.iter().map(|(_, d)| d.clone()).collect();
            let transcript = crate::codex_limits::transcript_is_private(dir, &all_dirs)
                .then(|| crate::codex_limits::for_slot(dir, now_secs(), 7 * 86_400))
                .flatten();
            let seen_by_proxy = if refused_names.contains(name) {
                None
            } else {
                codex_seen.get(name).cloned()
            };
            if let Some(row) = codex_row(
                name,
                live.as_ref(),
                codex_slot_email(dir).as_deref(),
                seen_by_proxy,
                transcript,
                now_secs() as i64,
            ) {
                // Remember it. Claude's numbers come from the cache and appear
                // the instant the dashboard opens; Codex's were read live every
                // time and never written down, so every open showed "checking…"
                // for as long as the network took. A remembered reading fills
                // the row immediately and the live one replaces it when it
                // lands.
                if !refused_names.contains(name) {
                    remember_codex_reading(paths, &row.0, &row.1);
                }
                codex.push(row);
            }
        }
        // Codex accounts that live only as a saved snapshot. The loop above
        // walks the slot registry, so these were never asked about and their
        // windows sat empty - while `swapdex quota`, which reads exactly this
        // case, printed real numbers for them. Two commands, one account, two
        // answers, and the silent one is the dashboard.
        {
            let slot_names: Vec<String> = codex_homes.iter().map(|(n, _)| n.clone()).collect();
            let stored: Vec<String> = Store::open(paths)
                .map(|st| {
                    st.list()
                        .into_iter()
                        .filter(|p| p.tools.iter().any(|t| t == "codex"))
                        .map(|p| p.name)
                        .collect()
                })
                .unwrap_or_default();
            let extra: Vec<String> = codex_names_without_a_slot(&stored, &slot_names)
                .into_iter()
                .filter(|n| !codex.iter().any(|(have, _)| have == n))
                .collect();
            // Same treatment as the slot reads: concurrent, staggered.
            let extra_live: std::collections::HashMap<String, crate::codex_usage::Account> = extra
                .iter()
                .map(|n| (n.clone(), snapshot_codex_auth(paths, n)))
                .filter_map(|(n, a)| a.map(|a| (n, a)))
                .collect::<Vec<_>>()
                .into_iter()
                .enumerate()
                .filter_map(|(i, (n, auth))| {
                    if i > 0 {
                        std::thread::sleep(std::time::Duration::from_millis(
                            crate::quota::pace_ms(),
                        ));
                    }
                    let f = crate::codex_usage::fetch(&auth);
                    crate::codex_usage::note_token_outcome(paths, &n, &f, now_secs() as i64);
                    match f {
                        crate::codex_usage::Fetch::Ok(a) => Some((n, *a)),
                        _ => None,
                    }
                })
                .collect();
            for name in extra {
                if codex.iter().any(|(n, _)| *n == name) {
                    continue;
                }
                let live = extra_live.get(&name).cloned();
                let seen_by_proxy = codex_seen.get(&name).cloned();
                if let Some(row) = codex_row(
                    &name,
                    live.as_ref(),
                    None,
                    seen_by_proxy,
                    None,
                    now_secs() as i64,
                ) {
                    remember_codex_reading(paths, &row.0, &row.1);
                    codex.push(row);
                }
            }
        }
        // The user asked for an account and the proxy is serving another. Say
        // so on the row they picked: resolving it silently leaves them looking
        // at an account they did not choose with no idea why.
        if let Some(why) = unhonoured_ask(
            crate::slots::Slots::open_for(paths, "claude-code")
                .ok()
                .and_then(|sl| {
                    sl.serving_dir()
                        .and_then(|d| sl.list().into_iter().find(|r| r.config_dir == d))
                        .map(|r| r.name)
                })
                .as_deref(),
            crate::proxy::serving_account_for(paths, "claude-code").as_deref(),
            proxy_acted_since_ask(paths, "claude-code"),
        ) {
            if let Some((_, u)) = claude.iter_mut().find(|(n, _)| why.contains(n.as_str())) {
                u.note = Some(why);
            }
        }
        // Disk caches and CLI schemas stay unchanged. Provider qualification is
        // attached only at the dashboard boundary, where same-named Claude and
        // Codex rows must never share a number or status.
        claude
            .into_iter()
            .map(|(name, usage)| (("claude-code".to_string(), name), usage))
            .chain(
                codex
                    .into_iter()
                    .map(|(name, usage)| (("codex".to_string(), name), usage)),
            )
            .collect()
    }
    impl crate::tui::TuiCtx for Ctx<'_> {
        fn rows(&mut self) -> Vec<crate::tui::Row> {
            let Ok(store) = Store::open(self.paths) else {
                return Vec::new();
            };
            let active = active_by_tool(&store, self.paths);
            let cfg = crate::settings::load(self.paths);
            // Keep every registry provider-qualified. A name is reusable across
            // tools, so a flat name -> directory map lets a Claude slot lend its
            // health, active state, and switching semantics to a Codex snapshot.
            let slots_by_tool: Vec<(&'static str, Vec<crate::slots::SlotRecord>)> =
                crate::adapters::names()
                    .into_iter()
                    .map(|tool| {
                        let rows = crate::slots::Slots::open_for(self.paths, tool)
                            .map(|slots| slots.list())
                            .unwrap_or_default();
                        (tool, rows)
                    })
                    .collect();
            let active_by_provider: Vec<(&'static str, Option<String>)> = crate::adapters::names()
                .into_iter()
                .map(|tool| (tool, active_slot_name(self.paths, tool)))
                .collect();
            let slot_dir_of = |tool: &str, name: &str| {
                slots_by_tool
                    .iter()
                    .find(|(held, _)| *held == tool)
                    .and_then(|(_, rows)| rows.iter().find(|row| row.name == name))
                    .map(|row| row.config_dir.clone())
            };
            let pointer_active = |tool: &str, name: &str| {
                active_by_provider
                    .iter()
                    .find(|(held, _)| *held == tool)
                    .and_then(|(_, active)| active.as_ref())
                    .map(|active| active == name)
            };
            let slot_email = |tool: &str, dir: &std::path::Path| match tool {
                "claude-code" => crate::proxy::creds::slot_email(dir),
                "codex" => codex_slot_email(dir),
                _ => self
                    .paths
                    .try_with_tool_dir(tool, dir)
                    .and_then(|at| {
                        crate::adapters::by_name(tool)
                            .and_then(|adapter| adapter.identity(&at).ok().flatten())
                    })
                    .and_then(|identity| identity.email),
            };

            // A profile that holds several providers is several independent TUI
            // rows. The legacy `ls --json` aggregation remains unchanged; the
            // picker needs the provider as part of its selection and action key.
            let mut list: Vec<crate::tui::Row> = store
                .list()
                .iter()
                .flat_map(|profile| {
                    profile.tools.iter().filter_map(|tool| {
                        if !crate::adapters::names().contains(&tool.as_str()) {
                            return None;
                        }
                        let tools = vec![tool.clone()];
                        let (snapshot_email, snapshot_tier, marker) =
                            profile_summary(&store, &profile.name, &tools);
                        let slot_dir = slot_dir_of(tool, &profile.name);
                        // The snapshot is only a saved copy once a slot exists.
                        // Its stale/unreadable marker says nothing about the live
                        // slot that serves this row; slot health is still checked
                        // below by `account_health` through (tool, name).
                        let snapshot_warning = if slot_dir.is_some() { None } else { marker };
                        let health = account_health(
                            self.paths,
                            &profile.name,
                            &tools,
                            snapshot_warning,
                            now_ms(),
                        );
                        // A slot is the live account the row can serve. Once one
                        // exists, its identity wins even when it is empty and
                        // waiting for sign-in; showing a saved copy's old email
                        // would label the live home as a different account.
                        let ident = match slot_dir.as_deref() {
                            Some(dir) => identity_column(slot_email(tool, dir), None),
                            None => identity_column(snapshot_email, snapshot_tier),
                        };
                        let live = active
                            .iter()
                            .any(|(held, name)| *held == tool && name == &profile.name);
                        let can_serve = matches!(tool.as_str(), "claude-code" | "codex");
                        Some(crate::tui::Row {
                            is_slot: can_serve && slot_dir.is_some(),
                            disabled: cfg.is_disabled(&profile.name),
                            needs_login: row_needs_login(self.paths, tool, slot_dir.as_deref()),
                            name: profile.name.clone(),
                            ident,
                            tools: if live {
                                format!("{tool}*")
                            } else {
                                tool.clone()
                            },
                            active: pointer_active(tool, &profile.name).unwrap_or(live),
                            warn: health.warning,
                            also: Vec::new(),
                            stale: health.access_expired,
                        })
                    })
                })
                .collect();

            // Slot-only accounts use the same provider-qualified resolution. A
            // slot already represented by that provider's snapshot stays one row.
            for (tool, records) in &slots_by_tool {
                let can_serve = matches!(*tool, "claude-code" | "codex");
                for record in records {
                    if list
                        .iter()
                        .any(|row| tui_row_names_tool(row, &record.name, tool))
                    {
                        continue;
                    }
                    let tools = vec![(*tool).to_string()];
                    let health = account_health(self.paths, &record.name, &tools, None, now_ms());
                    let email = slot_email(tool, &record.config_dir);
                    list.push(crate::tui::Row {
                        is_slot: can_serve,
                        disabled: cfg.is_disabled(&record.name),
                        needs_login: row_needs_login(self.paths, tool, Some(&record.config_dir)),
                        name: record.name.clone(),
                        ident: identity_column(email, None),
                        tools: (*tool).to_string(),
                        active: pointer_active(tool, &record.name).unwrap_or(false),
                        warn: health.warning,
                        also: Vec::new(),
                        stale: health.access_expired,
                    });
                }
            }
            // One row per account (a snapshot and a slot for the same login are
            // one account), then grouped by tool so the four registries read as
            // separate sections rather than one mixed list.
            crate::tui::group_sorted(crate::tui::dedupe_by_identity(list))
        }
        fn switch(&mut self, name: &str, tool: &str, is_slot: bool) -> (bool, String) {
            self.pre_switch_first = crate::session_link::read_timeline(self.paths).is_empty();
            // Enter means "let this account serve me" - not "move where my
            // conversations live". Moving the store is what `use` does, and having
            // the most natural key do it split a history in two every time
            // somebody changed accounts, which is the opposite of the point.
            // A snapshot cannot pay for turns - serving reads a slot's own
            // credential directory - so `serve` on one only ever answered that
            // it had never been signed in here. Switching a snapshot means
            // copying its credentials into place, which is what `use` does.
            run_self(&[crate::tui::switch_verb(is_slot), name, "--tool", tool])
        }
        fn toggle_rotation(&mut self, name: &str) -> String {
            // Through `update`, not load-then-save: this was the last caller
            // reading and writing the settings unlocked, which is exactly the
            // lost update `update` exists to prevent.
            let mut paused = false;
            match crate::settings::update(self.paths, |cfg| paused = cfg.toggle_disabled(name)) {
                Ok(()) if paused => {
                    format!("{name} paused - the proxy will not pick it (Enter still switches)")
                }
                Ok(()) => format!("{name} back in rotation"),
                Err(e) => format!("could not save that: {e}"),
            }
        }
        fn delete(&mut self, name: &str, tool: &str) -> String {
            // Delegate to the command every other caller uses. Deleting here only
            // ever touched the STORE, and every account in this list is a slot -
            // so it answered "no profile named X" for exactly the accounts the
            // dashboard is made of. Renaming had the same fault and was fixed
            // without me looking at its neighbour.
            run_self(&["rm", name, "--yes", "--tool", pretty_tool_flag(tool)]).1
        }
        fn rename(&mut self, old: &str, new: &str) -> (bool, String) {
            // Delegate to the command every other caller uses. Renaming here only
            // ever touched the STORE, and every account in this list is a slot -
            // so renaming from the dashboard failed with "no profile named X" on
            // exactly the accounts the dashboard is made of.
            run_self(&["rename", old, new])
        }
        fn sign_in(&mut self, name: &str, tool: &str) -> (bool, String) {
            sign_in_child(self.paths, name, tool)
        }
        fn save_current(&mut self, name: &str) -> (bool, String) {
            // `add <name>` captures the CURRENT live logins (all tools) - no
            // sign-out, no interactive spawn - so it is safe to run in-loop.
            run_self(&["add", name])
        }
        fn doctor(&mut self) -> Vec<String> {
            match crate::self_exe::output(&["doctor"]) {
                Ok(out) => {
                    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
                    text.push_str(&String::from_utf8_lossy(&out.stderr));
                    text.lines().map(|l| l.to_string()).collect()
                }
                Err(e) => vec![format!("doctor failed: {e}")],
            }
        }
        fn usage(&mut self) -> Vec<String> {
            match crate::self_exe::output(&["usage"]) {
                Ok(out) => {
                    let text = String::from_utf8_lossy(&out.stdout);
                    let mut lines: Vec<String> = text.lines().map(|l| l.to_string()).collect();
                    lines.push(String::new());
                    lines.push(
                        "swapdex is local: this is tokens USED here, not remaining quota."
                            .to_string(),
                    );
                    lines
                }
                Err(e) => vec![format!("usage failed: {e}")],
            }
        }
        fn quota(&mut self) -> Vec<String> {
            match crate::self_exe::output(&["quota"]) {
                Ok(out) => {
                    // stderr too (like doctor): a failed quota must show its
                    // error in the panel, not render blank.
                    let mut text = String::from_utf8_lossy(&out.stdout).into_owned();
                    text.push_str(&String::from_utf8_lossy(&out.stderr));
                    text.lines().map(|l| l.to_string()).collect()
                }
                Err(e) => vec![format!("quota failed: {e}")],
            }
        }
        fn usage_async(&mut self) -> crate::tui::PanelReceiver {
            crate::tui::PanelReceiver::command("usage")
        }
        fn quota_async(&mut self) -> crate::tui::PanelReceiver {
            crate::tui::PanelReceiver::command("quota")
        }
        fn cached_quota(&mut self) -> Vec<(crate::tui::AccountKey, crate::tui::Usage)> {
            // Every tool's cache, not just Claude's: a remembered reading that
            // nobody reads back leaves the row empty until the network answers.
            cached_quota_tools()
                .into_iter()
                .flat_map(|tool| {
                    crate::quota_cache::load_for(self.paths, tool)
                        .into_iter()
                        .map(move |(name, entry)| (tool, name, entry))
                })
                .collect::<Vec<_>>()
                .into_iter()
                .map(|(tool, name, e)| {
                    (
                        crate::tui::account_key(tool, &name),
                        crate::tui::Usage {
                            five_h: e.five_h,
                            five_h_reset: e.five_h_reset,
                            seven_d: e.seven_d,
                            seven_d_reset: e.seven_d_reset,
                            // Shown with its age: a remembered number that looked
                            // live would be worse than no number at all.
                            observed_at: Some(e.at),
                            note: None,
                            on_credits: e.on_credits,
                            ident: None,
                        },
                    )
                })
                .collect()
        }
        fn quota_pct(&mut self) -> Vec<(crate::tui::AccountKey, crate::tui::Usage)> {
            read_quota_usage(self.paths)
        }
        /// Start a reading and hand back the channel it arrives on. The read is
        /// several network round trips with backoff; on the loop it froze the
        /// dashboard with no keys and no cursor, which reads as a broken tool.
        fn quota_pct_async(
            &mut self,
        ) -> std::sync::mpsc::Receiver<Vec<(crate::tui::AccountKey, crate::tui::Usage)>> {
            let (tx, rx) = std::sync::mpsc::channel();
            let paths = self.paths.clone();
            std::thread::spawn(move || {
                let _ = tx.send(read_quota_usage(&paths));
            });
            rx
        }
        fn proxy_running(&mut self, tool: &str) -> bool {
            crate::proxy::running_proxy_for(self.paths, tool).is_some()
        }
        fn paying_account(&mut self) -> Option<String> {
            crate::adapters::names()
                .into_iter()
                .find_map(|t| crate::proxy::serving_account_for(self.paths, t))
        }
        fn sessionwiki_present(&mut self) -> bool {
            command_exists("sessionwiki")
        }
        fn live_tools(&mut self) -> Vec<String> {
            adapters::all()
                .iter()
                .filter(|a| a.present(self.paths))
                .map(|a| pretty_tool(a.name()).to_string())
                .collect()
        }
        fn suggested_name(&mut self) -> String {
            suggested_profile_name(self.paths)
        }
        fn sessions(
            &mut self,
            name: &str,
            tool: &str,
        ) -> (String, Vec<crate::tui::SessionEntry>, Vec<&'static str>) {
            let first_time = self.pre_switch_first;
            let (sessions, label) =
                recent_menu_sessions_for_tool(self.paths, name, first_time, 5, Some(tool));
            let tools: Vec<&'static str> = ["claude-code", "codex", "gemini", "antigravity"]
                .into_iter()
                .filter(|held| *held == tool)
                .collect();
            let entries = sessions
                .iter()
                .map(|s| {
                    let (id6, started, tool, title) = s.describe();
                    let age = age_line((started.max(0) as u128) * 1_000_000_000);
                    crate::tui::SessionEntry {
                        line: format!(
                            "{id6}  {:>7}  {}  {}",
                            age,
                            fit(&format!("[{tool}]"), 13),
                            fit(&title, 44)
                        )
                        .trim_end()
                        .to_string(),
                    }
                })
                .collect();
            self.last_sessions = sessions;
            let label = if label.is_empty() {
                format!("open a conversation on '{name}'")
            } else {
                label.trim_end_matches(':').to_string()
            };
            (label, entries, tools)
        }
    }

    let mut ctx = Ctx {
        paths,
        last_sessions: Vec::new(),
        pre_switch_first: crate::session_link::read_timeline(paths).is_empty(),
    };
    loop {
        // An empty store is fine now: the TUI draws an onboarding welcome
        // (offers to save the accounts you're already logged into). Only fall
        // back to text if there is truly nothing to do AND nothing to save.
        // Slots count as accounts. Checking only the store and the live logins
        // meant a slot-only install - which is every install now - could not open
        // its own dashboard until something happened to be signed in, and the
        // dashboard is where you go to sign in.
        let has_slots = crate::adapters::names().iter().any(|t| {
            crate::slots::Slots::open_for(paths, t)
                .map(|s| !s.list().is_empty())
                .unwrap_or(false)
        });
        if Store::open(paths)?.list().is_empty()
            && !has_slots
            && adapters::all().iter().all(|a| !a.present(paths))
        {
            println!("No accounts saved yet, and you're not logged into any tool.");
            println!(
                "  sign in to Claude Code / Codex / Gemini / Antigravity, then run `swapdex`."
            );
            return Ok(0);
        }
        match crate::tui::run(&mut ctx)? {
            crate::tui::Outcome::Quit => return Ok(0),
            crate::tui::Outcome::OpenSession(i) => {
                let Some(sess) = ctx.last_sessions.get(i) else {
                    return Ok(0);
                };
                return Err(exec_menu_resume(sess));
            }
            crate::tui::Outcome::NewConv { tool, dir } => {
                println!("opening {}...", pretty_tool(tool));
                return Err(exec_tool(tool, dir.as_deref()));
            }

            crate::tui::Outcome::AddAccount(tool) => {
                let sel = match tool {
                    "claude-code" => Some(ToolSel::Claude),
                    "codex" => Some(ToolSel::Codex),
                    "gemini" => Some(ToolSel::Gemini),
                    _ => Some(ToolSel::Antigravity),
                };
                let store = Store::open(paths)?;
                let Some(name) = ask_name(&store, new_account_prompt(), "", None) else {
                    println!("nothing added.");
                    continue;
                };
                drop(store);
                let rc = login(paths, &name, sel)?;
                if rc != 0 {
                    return Ok(rc);
                }
                println!("(press Enter to go back to the picker)");
                let _ = prompt("", "");
            }
        }
    }
}

/// Replace this process with the official tool - the "switch and land in a
/// conversation" handoff. Only returns on exec failure.
fn exec_tool(tool: &str, dir: Option<&std::path::Path>) -> anyhow::Error {
    use std::os::unix::process::CommandExt;
    // One table, in tool_binary. An unknown name is refused here rather than
    // silently launching Claude.
    if !matches!(tool, "claude-code" | "codex" | "gemini" | "antigravity") {
        return anyhow::anyhow!("unknown tool '{tool}'");
    }
    let bin = tool_binary(tool);
    let mut cmd = Command::new(bin);
    if let Some(d) = dir {
        cmd.current_dir(d);
    }
    let err = cmd.exec();
    anyhow::anyhow!("could not launch `{bin}`: {err}")
}

/// Replace this process with `sessionwiki resume <id>` - a one-shot handoff to
/// the official reopen flow (sessionwiki launches the session's own tool).
/// exec(2) only returns on failure, so this returns the error to propagate.
fn exec_sessionwiki_resume(id: &str) -> anyhow::Error {
    use std::os::unix::process::CommandExt;
    let err = Command::new("sessionwiki")
        .args(["resume", "--no-sync", "--", id])
        .exec();
    anyhow::anyhow!("could not launch `sessionwiki resume {id}`: {err}")
}

/// Turn the macOS Keychain reality into a doctor verdict. `None` = nothing to
/// report (no Claude item found: not logged in, or a locked/headless keychain).
/// `computed` is the item swapdex's own env derives (bare when no env) - the
/// one a `claude` launched from this same shell would read.
///
/// The contract: swapdex manages the profile of the environment it runs in.
/// Other Claude items are OTHER profiles (CLAUDE_CONFIG_DIR aliases) or
/// leftovers - swapdex never touches them, and this verdict says so.
fn keychain_verdict(
    found: &[String],
    target: Option<&str>,
    computed: &str,
) -> Option<(bool, String)> {
    if found.is_empty() {
        return None;
    }
    let list = found
        .iter()
        .map(|s| format!("'{s}'"))
        .collect::<Vec<_>>()
        .join(", ");
    let Some(t) = target else {
        // The derived item does not exist and several items are present:
        // refusing to guess is the safe behavior, and this is the remedy.
        return Some((
            false,
            format!(
                "this environment's profile item ('{computed}') does not exist; the items \
                 present ({list}) belong to other CLAUDE_CONFIG_DIR profiles, and swapdex \
                 refuses to guess between them. Run swapdex with the profile's \
                 CLAUDE_CONFIG_DIR, or log in once with plain `claude` to create '{computed}'."
            ),
        ));
    };
    if !found.iter().any(|s| s == t) {
        // Defensive: the two keychain reads disagreed (item vanished between).
        return Some((
            false,
            format!(
                "swapdex resolves '{t}' but the Keychain currently shows {list} - re-run \
                 `swapdex doctor`; if this persists, launch swapdex with the same \
                 CLAUDE_CONFIG_DIR you launch `claude` with."
            ),
        ));
    }
    if t != computed {
        // Single-item fallback: swapdex's env derives a missing item, so it
        // manages the only login that exists. Working alias-only setup.
        return Some((
            true,
            format!(
                "this environment derives '{computed}' (not present); managing the only \
                 Claude login, '{t}' - if your `claude` runs with a CLAUDE_CONFIG_DIR, \
                 launch swapdex with the same one"
            ),
        ));
    }
    let msg = if found.len() > 1 {
        format!(
            "managing this environment's profile ('{t}'); {} other Claude item(s) belong to \
             other CLAUDE_CONFIG_DIR profiles (or are leftovers) - swapdex never touches them",
            found.len() - 1
        )
    } else {
        format!("managing this environment's profile ('{t}')")
    };
    Some((true, msg))
}

/// `doctor` - local-only health check with a remedy per finding. Exit 0 when
/// healthy, 9 when any problem was found (scripts can gate on it). Checks the
/// store, every saved snapshot, both live logins, backups, and the CLIs on
/// PATH - and never touches the network.
/// What a switch can actually reach for this tool, given whether a proxy carries
/// its traffic.
///
/// swapdex reported the Codex login, listed three Codex accounts, and never said
/// that nothing was carrying Codex traffic. A session opened believing swapdex
/// was "on" for it went straight to the vendor, and switching accounts changed
/// nothing it could see. Running without a proxy is a legitimate way to use
/// swapdex - so this is a fact, not a fault - but it is a fact only swapdex
/// knows, and it was keeping it.
fn serving_reach(has_proxy: bool, accounts: usize) -> Option<String> {
    if accounts == 0 {
        return None;
    }
    Some(if has_proxy {
        format!("{accounts} account(s), proxy carrying traffic - a switch moves a running session")
    } else {
        format!(
            "{accounts} account(s), no proxy - a switch takes effect in the NEXT session, \
             not one already running (`swapdex service install --tool <tool>` to change that)"
        )
    })
}

pub fn doctor(paths: &Paths) -> Result<i32> {
    use std::os::unix::fs::PermissionsExt;
    // Stat BEFORE Store::open, which self-heals the mode to 0700 - otherwise
    // the permission check below could never observe a problem.
    let pre_mode = std::fs::metadata(paths.store_dir())
        .ok()
        .map(|m| m.permissions().mode() & 0o777);
    let store = Store::open(paths)?;
    let mut problems = 0u32;
    let color = crate::util::color_enabled();
    let mut report = |label: &str, ok: bool, msg: String| {
        let verdict = match (ok, color) {
            (true, true) => "\x1b[32mok\x1b[0m".to_string(),
            (false, true) => "\x1b[31mproblem\x1b[0m".to_string(),
            (true, false) => "ok".to_string(),
            (false, false) => "problem".to_string(),
        };
        println!("{label:<13} {verdict} - {msg}");
        if !ok {
            problems += 1;
        }
    };

    // Store directory. Store::open already tightened it to 0700; report what
    // it FOUND (pre_mode), or "ok" would paper over a store that sat
    // group-readable until this very run.
    let sd = paths.store_dir();
    let profiles = store.list();
    let count = format!(
        "{} profile{}",
        profiles.len(),
        if profiles.len() == 1 { "" } else { "s" }
    );
    match (pre_mode, std::fs::metadata(&sd)) {
        (Some(m), Ok(now)) if m & 0o077 != 0 && now.permissions().mode() & 0o077 == 0 => report(
            "store",
            true,
            format!("was mode {m:03o} - tightened to 0700 just now; {count}"),
        ),
        (_, Ok(now)) if now.permissions().mode() & 0o077 != 0 => report(
            "store",
            false,
            format!(
                "directory is group/world-accessible; run `chmod 700 {}`",
                crate::util::redact_path(&sd.display().to_string())
            ),
        ),
        (_, Ok(_)) => report("store", true, format!("0700, {count}")),
        (_, Err(e)) => report("store", false, format!("cannot stat store dir: {e}")),
    }

    // `settings::load` falls back to defaults when the file will not parse,
    // because every caller of it wants a value rather than an error. That makes
    // a corrupt file read as NO settings: every paused account is quietly back
    // in the proxy's rotation - the proxy reads this same file - the strategy
    // is back to default, and no listing looks any different. Nothing else can
    // say so, which leaves this screen.
    {
        let f = crate::settings::file(paths);
        match std::fs::read(&f) {
            Ok(bytes) if serde_json::from_slice::<serde_json::Value>(&bytes).is_err() => report(
                "settings",
                false,
                format!(
                    "{} will not parse, so it is being read as no settings at all - any \
                     account you paused is back in rotation. Fix the file, or delete it to \
                     start from defaults.",
                    crate::util::redact_path(&f.display().to_string())
                ),
            ),
            _ => {}
        }
    }

    // Live logins per tool.
    for adapter in adapters::all() {
        let tool = adapter.name();
        // The pointer first: this screen exists to tell somebody whether their
        // setup is sound, and reading the tool's own config dir made it print
        // "not logged in" four rows above its own "default -> 'work'".
        if let Some((name, email, signed_in)) = slot_active_login(paths, tool) {
            let who = slot_who(&name, email, signed_in, tool);
            report(tool, true, format!("{who} (profile '{name}')"));
            if let Some(live) = tool_dir_disagrees(&store, paths, tool, &name) {
                report(
                    tool,
                    true,
                    format!("a plain `{}` would launch on '{live}'", tool_binary(tool)),
                );
            }
            continue;
        }
        match adapter.identity(paths) {
            Ok(Some(id)) => {
                let saved = matched_profile_name(&store, tool, &id.account_id)
                    .map(|n| format!("profile '{n}'"))
                    .unwrap_or_else(|| "not saved - `swapdex add <name>` keeps it".into());
                report(
                    tool,
                    true,
                    format!("live login {} ({saved})", identity_line(&id)),
                );
            }
            Ok(None) => match macos_keychain_note(paths, tool) {
                Some(note) => report(tool, true, format!("not manageable - {note}")),
                None => report(tool, true, "not logged in".into()),
            },
            Err(_) => report(
                tool,
                false,
                "live login file unreadable; `swapdex use <profile>` can replace it, \
                 or log in again in the tool"
                    .into(),
            ),
        }
    }

    // macOS: swapdex swaps Claude's login INSIDE the Keychain, so a mismatch
    // between the item Claude reads and the one swapdex writes is the classic
    // "I switched but the old account is still active". Read-only; no-op off
    // macOS (Claude is file-based there).
    if let Some(diag) = crate::adapters::claude::keychain_diagnostic() {
        if let Some((ok, msg)) =
            keychain_verdict(&diag.found, diag.target.as_deref(), &diag.computed)
        {
            report("keychain", ok, msg);
        }
        if let Some(dir) = &diag.config_dir {
            report(
                "config-dir",
                true,
                format!(
                    "CLAUDE_CONFIG_DIR={} (swapdex must see the same value)",
                    crate::util::redact_path(dir)
                ),
            );
        }
    }

    // Permanent slots (the no-copy model): the slots, the default account the
    // claude shim follows, and whether the shim is installed.
    // Every check below lives inside this open. Skipping them when the registry
    // will not parse printed a SHORTER clean report, and a shorter clean report
    // reads as a healthier one - `doctor` said "everything looks healthy" about
    // a machine whose account registry `ls` was describing as damaged in a
    // paragraph. An absent check is not a passed one.
    let unreadable: Vec<&str> = crate::adapters::names()
        .into_iter()
        .filter(|t| crate::slots::Slots::open_for(paths, t).is_err())
        .collect();
    if !unreadable.is_empty() {
        // One file backs every tool, so name the tools once rather than
        // repeating the same path per tool - `ls` already words it this way.
        report(
            "registry",
            false,
            format!(
                "the account registry will not parse ({}), so the slot checks below were \
                 skipped - the slot directories still hold their logins. Restore {} from a \
                 backup, or re-register each with `swapdex adopt <name> <dir>`.",
                unreadable.join(", "),
                crate::util::redact_path(
                    &paths.store_dir().join("slots.json").display().to_string()
                )
            ),
        );
    }
    if let Ok(slots) = crate::slots::Slots::open(paths) {
        let list = slots.list();
        // Which swapdex the shims actually call. A shim embeds an ABSOLUTE
        // path to whichever swapdex wrote it, so with two copies installed -
        // npm and brew, say - updating one leaves the shims calling the
        // other. Nothing on screen says so: a fix ships, the user updates,
        // and the tool goes on running the old binary. That went unnoticed
        // for a full day here, and the check exists because of it.
        if let Ok(me) = std::env::current_exe() {
            let me = std::fs::canonicalize(&me).unwrap_or(me);
            let mut stale: Vec<(String, std::path::PathBuf)> = Vec::new();
            for tool in crate::adapters::names() {
                let f = crate::shim::shim_path_for(paths, tool);
                let Ok(text) = std::fs::read_to_string(&f) else {
                    continue;
                };
                let Some(called) = crate::shim::swapdex_path_in(&text) else {
                    continue;
                };
                let called = std::fs::canonicalize(&called).unwrap_or(called);
                if called != me {
                    stale.push((tool_binary(tool).to_string(), called));
                }
            }
            report(
                "shim target",
                stale.is_empty(),
                if stale.is_empty() {
                    format!("the shims call this swapdex ({})", me.display())
                } else {
                    format!(
                        "the {} shim calls a DIFFERENT swapdex ({}) - updating this one changes nothing it does; re-run `swapdex shim`",
                        stale[0].0,
                        stale[0].1.display()
                    )
                },
            );
        }

        // More than one real copy on PATH: one shadows the other, and
        // updating the shadowed one changes nothing anybody can see.
        let copies = crate::shim::swapdex_copies_on(&std::env::var("PATH").unwrap_or_default());
        report(
            "install",
            copies.len() < 2,
            match copies.len() {
                0 => "swapdex is not on PATH (running it by full path)".to_string(),
                1 => format!("one copy on PATH ({})", copies[0].display()),
                _ => format!(
                    "{} copies on PATH - `{}` wins and the rest are shadowed; keep one installer and remove the others",
                    copies.len(),
                    copies[0].display()
                ),
            },
        );
        // Whether this copy is the current one. The version check is the
        // only thing here that touches the network, and it is confined to
        // `doctor`: a check that ran on every command would be a request
        // nobody asked for. It exists because an install that silently did
        // NOTHING - a scope typo, a 404, no error the user kept - looks
        // exactly like an install that worked.
        let running = env!("CARGO_PKG_VERSION");
        match if paths.sandboxed() {
            None
        } else {
            crate::quota::latest_published()
        } {
            Some(latest) if crate::quota::is_behind(running, &latest) => report(
                "version",
                false,
                format!(
                    "running {running}, but {latest} is published - update, then check \
                     `swapdex --version` actually changed"
                ),
            ),
            Some(latest) => report("version", true, format!("{running} (latest is {latest})")),
            // Offline is not a fault: say what is known and move on.
            None => report(
                "version",
                true,
                format!("{running} - could not reach the registry to compare"),
            ),
        }

        if !list.is_empty() {
            report("slots", true, format!("{} account(s)", list.len()));
            match slots.default_dir() {
                Some(dir) => match list.iter().find(|r| r.config_dir == dir) {
                    Some(r) => report("default", true, format!("plain `claude` -> '{}'", r.name)),
                    // The shim exports this directory to CLAUDE_CONFIG_DIR without
                    // checking it, so an unresolvable pointer is not a cosmetic
                    // gap: a plain `claude` starts in a directory no account holds
                    // and asks for a fresh login. This arm used to print the name
                    // as "(unknown)" and still record the row as healthy.
                    None => report(
                        "default",
                        false,
                        format!(
                            "the default pointer names {}, which no account holds - a plain \
                             `claude` would start there and ask to log in again. Repoint it \
                             with `swapdex use <name>`.",
                            crate::util::redact_path(&dir.display().to_string())
                        ),
                    ),
                },
                // Name the tool the way the arm above does. Unqualified, this
                // read as "this machine has no default" on a machine whose
                // Codex default was reported two rows higher.
                None => report(
                    "default",
                    true,
                    "no default for a plain `claude` - `swapdex use <name>` sets it".into(),
                ),
            }
            // Conversations live inside the store they were started in, so
            // pointing `claude` at an account also decides which conversations
            // `-c` and `-r` can offer. When the default store holds work and is
            // not a registered account, that work becomes unreachable from a
            // plain `claude` with nothing to explain it - and swapdex is what
            // redirected it, so swapdex is what has to say so.
            {
                let bare = paths.claude_dir().to_path_buf();
                let registered = crate::slots::Slots::open_for(paths, "claude-code")
                    .map(|s| s.list().iter().any(|r| r.config_dir == bare))
                    .unwrap_or(false);
                let held = std::fs::read_dir(bare.join("projects"))
                    .map(|rd| rd.flatten().count())
                    .unwrap_or(0);
                if !registered && held > 0 {
                    report(
                        "default store",
                        false,
                        format!(
                            "~/.claude holds {held} project(s) of conversations but is not a \
                             swapdex account, so a plain `claude -r` cannot reach them while \
                             another account is active - register it to switch back: \
                             `swapdex adopt personal {}`",
                            crate::util::redact_path(&bare.display().to_string())
                        ),
                    );
                }
            }
            // A name above another account's numbers is worse than no name: it
            // is not "missing information", it is wrong information, and every
            // figure on that row belongs to somebody else.
            {
                let mixed: Vec<String> = crate::slots::Slots::open_for(paths, "claude-code")
                    .map(|s| s.list())
                    .unwrap_or_default()
                    .into_iter()
                    .filter_map(|r| {
                        crate::proxy::creds::identity_contradicts_login(&r.config_dir)
                            .map(|why| format!("'{}' is {why}", r.name))
                    })
                    .collect();
                // Stated, not counted as a problem: the evidence available here
                // cannot separate "two accounts got mixed" from "this person has
                // a personal plan and an organisation", and a problem count that
                // includes maybes is one people stop reading.
                for line in &mixed {
                    report("account identity", true, line.clone());
                }
            }
            // Two directories can hold ONE login. Nothing said so, and the
            // fleet then reads as more accounts than exist - while a rate limit
            // on one applies to its twin. Not a fault (keeping two directories
            // for one account is a fair thing to do), so it is stated rather
            // than counted as a problem.
            {
                let named: Vec<(String, Option<String>)> = crate::adapters::names()
                    .into_iter()
                    .flat_map(|t| {
                        crate::slots::Slots::open_for(paths, t)
                            .map(|s| s.list())
                            .unwrap_or_default()
                    })
                    .map(|r| {
                        (
                            r.name.clone(),
                            crate::proxy::creds::slot_account_uuid(&r.config_dir),
                        )
                    })
                    .collect();
                for group in crate::slots::slots_sharing_an_account(&named) {
                    report(
                        "shared account",
                        true,
                        format!(
                            "{} hold the same login in different directories - rotation \
                             counts them once, because a rate limit belongs to the account",
                            group.join(" and ")
                        ),
                    );
                }
            }
            // A slot named after a tool cannot be refused after the fact, but it
            // can be named: it reads as that tool's home and points elsewhere.
            {
                let colliding: Vec<String> = crate::slots::Slots::open_for(paths, "claude-code")
                    .map(|s| s.list())
                    .unwrap_or_default()
                    .into_iter()
                    .chain(
                        crate::slots::Slots::open_for(paths, "codex")
                            .map(|s| s.list())
                            .unwrap_or_default(),
                    )
                    .filter(|r| crate::slots::name_reads_as_a_tool_home(&r.name))
                    .map(|r| r.name)
                    .collect();
                if !colliding.is_empty() {
                    report(
                        "account names",
                        false,
                        format!(
                            "account '{}' reads as the tool's own home directory but points \
                             somewhere else - rename it so the two are not confused: \
                             `swapdex rename {} <name>` (the folder and login are untouched)",
                            colliding.join("', '"),
                            colliding[0]
                        ),
                    );
                }
            }
            // Shim ENGAGEMENT, not mere existence: an installed shim that PATH
            // never reaches looks set up while a plain `claude` still runs
            // bare - `swapdex use` flips the pointer and nothing reads it.
            let shim_file = crate::shim::shim_path(paths);
            let (shim_ok, shim_msg) = if !shim_file.exists() {
                (
                    true,
                    "claude shim not installed - run `swapdex shim` so a plain \
                     `claude` follows `swapdex use`"
                        .to_string(),
                )
            } else {
                let shim_dir_path = shim_file.parent().unwrap_or(&shim_file).to_path_buf();
                let shim_dir = shim_dir_path.display();
                let resolved = crate::shim::resolved_claude();
                let active = matches!(resolved, Some((_, true)));
                let profile = crate::shim::shell_profile_text_for(paths);
                match crate::shim::shim_reach_for(
                    paths,
                    active,
                    profile.as_ref().map(|(_, t)| t.as_str()),
                    &shim_dir_path,
                ) {
                    crate::shim::ShimReach::Active => (
                        true,
                        "claude shim active - plain `claude` follows `swapdex use`".to_string(),
                    ),
                    // Set up correctly; THIS shell has not picked it up. Two
                    // ordinary causes - a shell that never reads the profile
                    // (a script, a cron job, `ssh host cmd`), or one that
                    // started before the profile was edited. Neither is a
                    // fault, and calling it one sends someone to fix a
                    // configuration that is already right.
                    crate::shim::ShimReach::ConfiguredElsewhere => {
                        let p = profile
                            .as_ref()
                            .map(|(p, _)| crate::util::redact_path(&p.display().to_string()))
                            .unwrap_or_else(|| "your shell profile".to_string());
                        (
                            true,
                            format!(
                                "claude shim set up in {p} but not on THIS shell's PATH - \
                                 open a new terminal (or `source {p}`); a shell that does \
                                 not read that file, like a script or `ssh host cmd`, \
                                 never will"
                            ),
                        )
                    }
                    crate::shim::ShimReach::Missing => (
                        false,
                        match resolved {
                            Some((found, _)) => format!(
                                "claude shim installed but NOT taking effect - plain `claude` \
                                 runs {} instead; add the shim first on PATH: \
                                 export PATH=\"{shim_dir}:$PATH\"",
                                found.display()
                            ),
                            None => format!(
                                "claude shim installed but PATH has no `claude` at all - \
                                 add it: export PATH=\"{shim_dir}:$PATH\""
                            ),
                        },
                    ),
                }
            };
            report("shim", shim_ok, shim_msg);
        }
    }

    // Per-slot login health (read-only), for EVERY tool. Flag only a slot with
    // NO login yet, or one whose token sat unrefreshed past STALE_DAYS (by then
    // the refresh token itself may be revoked). Routine access-token expiry
    // (hours) is NOT flagged - every tool refreshes silently on the next run.
    // This walked Claude's registry alone, so a Codex slot that had never been
    // signed in produced no row, and no row reads as a passing one.
    use crate::adapters::claude::SlotLogin;
    for tool in crate::adapters::names() {
        let Ok(slots) = crate::slots::Slots::open_for(paths, tool) else {
            continue;
        };
        for r in slots.list() {
            let key = format!("slot:{}", r.name);
            match slot_login_of(paths, tool, &r.config_dir) {
                SlotLogin::Absent => report(
                    &key,
                    true,
                    format!(
                        "no login yet - `swapdex run {}{}` once signs it in",
                        r.name,
                        tool_flag(tool)
                    ),
                ),
                SlotLogin::Present(Some(ts)) if now_ms() - ts > STALE_DAYS * 86_400_000 => {
                    let days = (now_ms() - ts) / 86_400_000;
                    report(
                        &key,
                        true,
                        format!(
                            "login idle ~{days}d - `swapdex run {}{}` once refreshes \
                             it (re-login if it asks)",
                            r.name,
                            tool_flag(tool)
                        ),
                    );
                }
                // Fresh, or present-but-undeterminable: stay quiet - doctor
                // flags only what it can determine.
                SlotLogin::Present(_) => {}
            }
            // Not a fault: the guard is doing its job, and renewing under a
            // live session would retire the token that session is holding.
            // But it is why an account can sit days past its renewal, so the
            // screen that answers "is this sound" has to be able to say it.
            if renewal_deferred_for(paths, tool, &r.config_dir) {
                // The two tools defer for opposite reasons and one sentence
                // cannot serve both. A native Claude session refreshes its own
                // token hourly, so the login stays fresh and nothing waits on
                // exit - telling a Claude user it "renews once that session
                // exits" sends them to kill a healthy session. Codex renews only
                // when it runs, so there the session really is what stands in
                // the way, with a ceiling past which it no longer does.
                let why = match tool {
                    "claude-code" => "renewal deferred to native session - the running claude \
                                      session refreshes this login itself"
                        .to_string(),
                    _ => format!(
                        "renewal deferred - a running {} session holds this login; \
                         it renews once that session exits",
                        tool_binary(tool)
                    ),
                };
                report(&key, true, why);
            }
        }
    }

    // Live credential files hold refresh tokens - flag loose modes on ALL of
    // them, not just .claude.json (the store already self-tightens; the live
    // files are each tool's own, so we can only warn).
    // The bare paths, plus every slot: under the slot model each account keeps
    // its credential in its own directory, and this list checked only the file
    // a copy-model machine writes. On a machine set up with `run` or `migrate`
    // - the shape this tool steers people into - it therefore walked nothing
    // and reported a clean bill.
    let mut to_check = vec![
        paths.claude_credentials(),
        paths.codex_auth(),
        paths.gemini_oauth(),
        paths.antigravity_token(),
    ];
    for tool in crate::adapters::names() {
        if let Ok(slots) = crate::slots::Slots::open_for(paths, tool) {
            for r in slots.list() {
                if let Some(p) = paths.try_with_tool_dir(tool, &r.config_dir) {
                    to_check.extend([
                        p.claude_credentials(),
                        p.codex_auth(),
                        p.gemini_oauth(),
                        p.antigravity_token(),
                    ]);
                }
            }
        }
    }
    to_check.sort();
    to_check.dedup();
    for f in to_check {
        if let Ok(meta) = std::fs::metadata(&f) {
            use std::os::unix::fs::PermissionsExt;
            if meta.permissions().mode() & 0o077 != 0 {
                report(
                    "perms",
                    false,
                    format!(
                        "{} is group/world-readable (holds tokens); run `chmod 600` on it",
                        crate::util::redact_path(&f.display().to_string())
                    ),
                );
            }
        }
    }
    // A corrupt live .claude.json breaks every claude switch with an error
    // users misread as a snapshot problem - diagnose it here by name.
    if paths.claude_config_json().exists() {
        if let Ok(bytes) = std::fs::read(paths.claude_config_json()) {
            if serde_json::from_slice::<Value>(&bytes).is_err() {
                report(
                    "claude-config",
                    false,
                    format!(
                        "{} is not valid JSON - claude switches will fail until it is \
                         repaired or removed (removing loses local settings like \
                         project trust)",
                        crate::util::redact_path(&paths.claude_config_json().display().to_string())
                    ),
                );
            }
        }
    }
    // .claude.json permissions (holds account PII).
    if let Ok(meta) = std::fs::metadata(paths.claude_config_json()) {
        if meta.permissions().mode() & 0o077 != 0 {
            report(
                "claude-config",
                false,
                format!(
                    "{} is group/world-readable; run `chmod 600` on it",
                    crate::util::redact_path(&paths.claude_config_json().display().to_string())
                ),
            );
        }
    }

    // Every saved snapshot must parse.
    for p in &profiles {
        for tool in &p.tools {
            match profile_detail(&store, &p.name, tool) {
                Some((_, _, Some("unreadable"))) => report(
                    &format!("profile:{}", p.name),
                    false,
                    format!(
                        "{tool} snapshot unreadable; log in to that account and run \
                         `swapdex add {} --tool {tool} --update`",
                        p.name
                    ),
                ),
                // The precondition matters: `add --update` snapshots whatever
                // is LIVE, so without "log in to that account first" the
                // remedy would overwrite this profile with the wrong account.
                Some((_, _, Some(m))) => report(
                    &format!("profile:{}", p.name),
                    true,
                    format!(
                        "{tool} snapshot {m} - log in to that account and run \
                         `swapdex add {} --tool {tool} --update`",
                        p.name
                    ),
                ),
                _ => {}
            }
        }
    }

    // Backups: newest intact per tool (load_backup already skips torn ones).
    let mut kept = Vec::new();
    for tool in ["claude-code", "codex", "gemini", "antigravity"] {
        if let Ok(Some((stamp, _))) = store.load_backup(tool) {
            kept.push(format!("{tool} (newest {})", age_line(stamp)));
        }
    }
    if kept.is_empty() {
        report(
            "backups",
            true,
            "none yet (one is taken on every `use`; `swapdex restore` brings it back)".into(),
        );
    } else {
        report("backups", true, format!("intact - {}", kept.join(", ")));
    }

    // The proxy service. Its failure takes every session down at once, and this
    // check did not exist - so the outage that reads as "API error everywhere"
    // had nothing here to name it. The unit records an absolute path resolved at
    // install time; for an npm install that path carries the Node version, so
    // upgrading Node deletes it while the service still reads as installed.
    // A sandboxed run has no real service, and reading the machine's own unit
    // from a temporary store would report the developer's box, not the sandbox.
    let home = (!paths.sandboxed()).then(|| paths.home());
    // Every tool `service install --tool` accepts. It checked two of the four,
    // so a gemini or antigravity proxy could be down with doctor saying nothing.
    for tool in crate::store::KNOWN_TOOLS {
        let Some(path) = home.as_ref().map(|h| {
            if cfg!(target_os = "macos") {
                crate::service::launchd_path(h, tool)
            } else {
                crate::service::systemd_path(h, tool)
            }
        }) else {
            continue;
        };
        let Ok(body) = std::fs::read_to_string(&path) else {
            continue; // not installed for this tool: not a problem
        };
        let label = format!("service:{}", crate::commands::tool_binary(tool));
        match crate::service::unit_program(&body) {
            Some(prog) if std::path::Path::new(&prog).exists() => {
                let running = crate::proxy::running_proxy_for(paths, tool);
                if let Some((_, _, build)) = &running {
                    match stale_proxy_note(build, &crate::proxy::build_id(), tool) {
                        Some(note) => report(&label, false, note),
                        None => report(&label, true, "installed and running".into()),
                    }
                } else {
                    report(
                        &label,
                        false,
                        format!(
                            "installed but not running - `swapdex service install --tool {}` \
                             writes the unit and hands it back to the supervisor \
                             (sessions fall back to your own login until it is up)",
                            pretty_tool_flag(tool)
                        ),
                    );
                }
            }
            Some(prog) => report(
                &label,
                false,
                format!(
                    "points at {} which no longer exists - reinstall with \
                     `swapdex service install --tool {}` (an npm path carries the Node \
                     version, so upgrading Node breaks it)",
                    crate::util::redact_path(&prog),
                    pretty_tool_flag(tool)
                ),
            ),
            None => report(
                &label,
                false,
                format!("{} names no program - reinstall it", path.display()),
            ),
        }
    }

    // The pinned proxy address. `swapdex shim` refuses to write it unless a
    // proxy is alive, so pinning is safe - and then nothing watched it. When the
    // proxy went away, every session got "Connection refused" while the settings
    // still named an address nobody answered, and this health check said the
    // service was fine because it looked at the unit and the process, never at
    // the address. A pin nothing answers is a brick.
    {
        let settings_file = paths.claude_dir().join("settings.json");
        let pinned = std::fs::read_to_string(&settings_file)
            .ok()
            .and_then(|t| serde_json::from_str::<serde_json::Value>(&t).ok())
            .and_then(|v| crate::shim::pinned_port(&v));
        if let Some(port) = pinned {
            let addr = std::net::SocketAddr::from(([127, 0, 0, 1], port));
            let answers =
                std::net::TcpStream::connect_timeout(&addr, std::time::Duration::from_millis(700))
                    .is_ok();
            if answers {
                report(
                    "proxy pin",
                    true,
                    format!("Claude Code -> 127.0.0.1:{port}, answering"),
                );
            } else {
                report(
                    "proxy pin",
                    false,
                    format!(
                        "settings.json sends Claude Code to 127.0.0.1:{port} and nothing is \
                         answering there - every session gets 'Connection refused'. Start the \
                         proxy (`swapdex service install --tool claude`, from a terminal \
                         on this machine so it can read the Keychain), or remove the pin from \
                         {} to go direct.",
                        crate::util::redact_path(&settings_file.display().to_string())
                    ),
                );
            }
        }
    }

    // What a switch can actually reach, per tool. swapdex knew that nothing was
    // carrying a tool's traffic and never said so, so a session opened believing
    // swapdex was "on" for it was talking straight to the vendor.
    for tool in crate::adapters::names() {
        let accounts = crate::slots::Slots::open_for(paths, tool)
            .map(|s| s.list().len())
            .unwrap_or(0);
        let has_proxy = crate::proxy::running_proxy_for(paths, tool).is_some();
        if let Some(msg) = serving_reach(has_proxy, accounts) {
            report(&format!("reach:{}", tool_binary(tool)), true, msg);
        }
    }

    // CLIs on PATH - informational (a codex-only user is not "broken").
    let mut found = Vec::new();
    for cli in ["claude", "codex", "gemini", "agy"] {
        if command_exists(cli) {
            found.push(cli);
        }
    }
    report(
        "tools",
        true,
        if found.is_empty() {
            "none of `claude`, `codex`, `gemini`, `agy` found on PATH".into()
        } else {
            format!("on PATH: {}", found.join(", "))
        },
    );

    if problems > 0 {
        println!(
            "\n{problems} problem{} found - each line above ends with its fix.",
            if problems == 1 { "" } else { "s" }
        );
        return Ok(9);
    }
    println!("\neverything looks healthy.");
    Ok(0)
}

pub fn rm(paths: &Paths, name: &str, yes: bool, sel: Option<ToolSel>) -> Result<i32> {
    // The parsed selection, like every other command's `--tool`. Taking a raw
    // string here meant `--tool claude` looked for `accounts/<name>/claude`
    // while the directory is `claude-code`, so the documented spelling could not
    // drop a Claude login - and any word at all was accepted.
    let tool = sel.and_then(one_tool);
    if let Some(c) = reject_bad_name(name) {
        return Ok(c);
    }
    let store = Store::open(paths)?;
    // A slot account is not a saved snapshot: removing it means "stop managing
    // this account", and the directory holding its login is left untouched, so
    // the account itself is never lost.
    // Both tools keep accounts here. Looking only in Claude's registry meant a
    // Codex account could not be removed at all, and the dashboard - which lists
    // both - reported "no account named X" for something it was showing.
    let is_slot = crate::adapters::names().into_iter().any(|t| {
        crate::slots::Slots::open_for(paths, t)
            .map(|s| s.get(name).is_some())
            .unwrap_or(false)
    });
    let is_profile = store.list().iter().any(|p| p.name == name);
    if !is_slot && !is_profile {
        eprintln!("swapdex: no account named '{name}'");
        return Ok(5);
    }
    // Naming a tool means "drop that tool", whatever else the name refers to.
    // The slot branch below used to run first, so on a name that was BOTH a
    // slot and a profile the flag was ignored and the whole account was
    // unregistered - the opposite of what was asked, and destructive.
    if let Some(t) = tool {
        // Both kinds: a tool can exist as a saved snapshot, as a registered
        // slot, or both. Looking only at snapshots answered "has no {t} login"
        // about a slot the listing was showing, and left no way to remove it
        // short of editing slots.json by hand.
        let dropped_snapshot = store.drop_tool(name, t)?;
        let dropped_slot = crate::slots::Slots::open_for_update(paths, t)
            .and_then(|mut sl| sl.remove(name))
            .unwrap_or(false);
        if !dropped_snapshot && !dropped_slot {
            eprintln!("swapdex: profile '{name}' has no {t} login");
            return Ok(5);
        }
        println!("dropped {t} from '{name}' (its live login keeps running, now unsaved)");
        if !name_still_known(paths, name) {
            drop_side_state(paths, name);
        }
        return Ok(0);
    }
    if is_slot {
        if !yes {
            use std::io::IsTerminal;
            let tty =
                std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
            if !tty {
                eprintln!(
                    "swapdex: `rm {name}` unregisters that account (its login and folder \
                     stay). Re-run with --yes to confirm."
                );
                return Ok(7);
            }
            if !yes_no(
                &format!(
                    "stop managing account '{name}'? Its login and folder stay, so \
                     `swapdex adopt` can bring it back. [y/N]: "
                ),
                false,
            ) {
                println!("kept '{name}'.");
                return Ok(0);
            }
        }
        // Every tool's registry, not the first one holding the name: one name
        // is one account across tools, and `mv` loops for the same reason.
        let mut dirs: Vec<std::path::PathBuf> = Vec::new();
        let mut warnings: Vec<String> = Vec::new();
        for tool in crate::adapters::names() {
            let Ok(mut slots) = crate::slots::Slots::open_for_update(paths, tool) else {
                continue;
            };
            let Some(dir) = slots.get(name).map(|r| r.config_dir) else {
                continue;
            };
            slots.remove(name)?;
            if !dirs.contains(&dir) {
                dirs.push(dir);
            }
            if let Some(w) = last_slot_warning(
                crate::slots::Slots::open_for(paths, tool)
                    .map(|s| s.list().len())
                    .unwrap_or(0),
                crate::proxy::running_proxy_for(paths, tool).is_some(),
                tool,
            ) {
                warnings.push(w);
            }
        }
        println!("stopped managing '{name}'.");
        for d in &dirs {
            println!(
                "  its login is untouched at {}",
                crate::util::redact_path(&d.display().to_string())
            );
        }
        for w in &warnings {
            println!("{w}");
        }
        // A profile of the same name is a separate thing; leave it alone - but
        // say so, or the name stays listed and the removal reads as failed.
        if is_profile {
            println!(
                "  a saved profile named '{name}' is still here - `swapdex rm {name} --yes` \
                 again removes it"
            );
        }
        // The preferences belong to whatever still answers to the name.
        if !name_still_known(paths, name) {
            drop_side_state(paths, name);
        }
        return Ok(0);
    }
    if !yes {
        // On a terminal, just ask; --yes stays for scripts (and remains the
        // only path when stdin is not a tty, exit 7 as documented).
        use std::io::IsTerminal;
        let tty =
            std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
        if !tty {
            eprintln!(
                "swapdex: `rm {name}` deletes the saved profile. Re-run with --yes to confirm."
            );
            return Ok(7);
        }
        if !yes_no(
            &format!("delete saved profile '{name}'? The live login stays. [y/N]: "),
            false,
        ) {
            println!("kept '{name}'.");
            return Ok(0);
        }
    }
    let _lock = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    if !store.remove(name)? {
        eprintln!("swapdex: no profile named '{name}'");
        return Ok(5);
    }
    println!("removed profile '{name}' (any live login it matched keeps running, now unsaved)");
    // `settings::update` takes this same store lock, and a second open of it in
    // one process conflicts, so hand it back before forgetting the name.
    drop(_lock);
    if !name_still_known(paths, name) {
        drop_side_state(paths, name);
    }
    Ok(0)
}

/// Move everything an account is known by NAME to its new name.
///
/// Three stores key an account by name and match it exactly: its rotation
/// preferences (`disabled`, `priority`), its remembered usage readings, and the
/// timeline that credits sessions and tokens. A rename that leaves the first
/// behind silently un-pauses the account; one that leaves either of the others
/// behind draws a row for a name nothing answers to. They move together here
/// because the timeline used to move inside `Store::rename`, which the
/// slot-only rename never reaches. None of it is worth failing a rename that
/// already happened on disk.
fn carry_side_state(paths: &Paths, old: &str, new: &str) {
    if crate::settings::update(paths, |s| s.rename_account(old, new)).is_err() {
        eprintln!("swapdex: account renamed, but its rotation preferences could not be moved; check pause and order settings");
    }
    crate::quota_cache::rename_account(paths, old, new);
    if let Ok(st) = Store::open(paths) {
        let _ = st.rename_timeline_account(old, new);
    }
}

/// Drop the same three stores. They outlive the account otherwise, and the next
/// account registered under that name inherits its pause, its rank and a
/// stranger's usage numbers.
///
/// The ledger is retired rather than dropped - see `retire_timeline_account`.
fn drop_side_state(paths: &Paths, name: &str) {
    if crate::settings::update(paths, |s| s.forget_account(name)).is_err() {
        eprintln!("swapdex: account removed, but its rotation preferences could not be cleared; check pause and order settings before reusing the name");
    }
    crate::quota_cache::forget_account(paths, name);
    if let Ok(st) = Store::open(paths) {
        let _ = st.retire_timeline_account(name);
    }
}

/// Whether anything still answers to this name - a slot under any tool, or a
/// saved profile. A removal that leaves either behind is a partial one, and the
/// account's preferences still have an owner.
fn name_still_known(paths: &Paths, name: &str) -> bool {
    Store::open(paths).is_ok_and(|st| st.list().iter().any(|p| p.name == name))
        || crate::adapters::names()
            .into_iter()
            .any(|t| crate::slots::Slots::open_for(paths, t).is_ok_and(|s| s.get(name).is_some()))
}

pub fn rename(paths: &Paths, old: &str, new: &str) -> Result<i32> {
    if let Some(c) = reject_bad_name(old) {
        return Ok(c);
    }
    if let Some(c) = reject_bad_name(new).or_else(|| reject_reserved_name(new)) {
        return Ok(c);
    }
    // A slot account renames by mapping only: its directory (and so its Keychain
    // item, and so its login) must not move.
    //
    // Across every tool, not Claude's registry alone. Looking only there left a
    // Codex slot unfound: the snapshot was renamed and the slot kept its old
    // name, so one account answered to two - `ls` said one thing and the
    // registry another. `rm` already had this fix; rename did not.
    // An account can be BOTH a slot and a snapshot. Renaming the slot and
    // returning left the snapshot under the old name, so one account showed as
    // two rows - `after` and `before` side by side, each half of the same
    // login. Rename every kind that answers to this name.
    // EVERY tool's registry, not the first one `find_any_tool` happens to
    // name. Renaming one left the others behind, so an account holding both a
    // Claude and a Codex slot came out split in two - one login under two
    // names. 0.88.0 fixed the slot-vs-snapshot half of this; this is the
    // slot-vs-slot half.
    // Refuse BEFORE moving anything. The slot rename persists immediately, so
    // checking the profile collision afterwards left the slot renamed under a
    // message saying the rename had not happened. Only once the source is known
    // to exist: "there is nothing by that name" outranks "the new name is taken".
    let old_exists = Store::open(paths).is_ok_and(|st| st.list().iter().any(|p| p.name == old))
        || crate::adapters::names()
            .into_iter()
            .any(|t| crate::slots::Slots::open_for(paths, t).is_ok_and(|s| s.get(old).is_some()));
    if old_exists && Store::open(paths).is_ok_and(|st| st.profile_dir_exists(new)) {
        eprintln!("swapdex: a profile named '{new}' already exists");
        return Ok(6);
    }
    let mut slot_renamed = false;
    for tool in adapters::all().iter().map(|a| a.name()) {
        if let Ok(mut slots) = crate::slots::Slots::open_for_update(paths, tool) {
            match slots.rename(old, new) {
                Ok(true) => slot_renamed = true,
                Ok(false) => {}
                Err(e) => {
                    eprintln!("swapdex: {e}");
                    return Ok(6);
                }
            }
        }
    }
    // No snapshot to move as well: the slot rename was the whole job.
    if slot_renamed
        && Store::open(paths)
            .map(|st| !st.list().iter().any(|p| p.name == old))
            .unwrap_or(true)
    {
        carry_side_state(paths, old, new);
        println!("renamed account '{old}' to '{new}'");
        return Ok(0);
    }
    let store = Store::open(paths)?;
    // Take the switch lock like every other store mutation, and make the
    // collision a first-class "already exists" (6) rather than a hard error -
    // a script must be able to tell "pick another name" from "disk broke".
    let _lock = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    // Source must be a REAL profile (ghost dirs with no known tools are
    // hidden from ls - acting on them here would contradict it)...
    if !store.list().iter().any(|p| p.name == old) {
        eprintln!("swapdex: no profile named '{old}'");
        return Ok(5);
    }
    // ...while the TARGET collision checks the directory itself: colliding
    // with a hidden ghost dir must still be a clean "exists" (6), not a
    // hard error from the rename syscall.
    if store.profile_dir_exists(new) {
        eprintln!("swapdex: a profile named '{new}' already exists");
        return Ok(6);
    }
    if store.rename(old, new)? {
        // `settings::update` takes this same store lock, and a second open of it
        // in one process conflicts, so hand it back before carrying the names.
        drop(_lock);
        carry_side_state(paths, old, new);
        println!("renamed profile '{old}' -> '{new}'");
        Ok(0)
    } else {
        eprintln!("swapdex: no profile named '{old}'");
        Ok(5)
    }
}

/// Onboarding in one step: run a tool's login flow, then save the result as a
/// named profile. Codex has a driveable CLI login; Claude Code signs in inside
/// the app, so for it swapdex guides the two-step manual path.
/// Repoint the default account at slot `name` (the `claude` shim follows this).
/// No credential is moved. Called by `use_account` when the name is a slot.
/// What a slot switch actually did, said plainly.
///
/// Moving the pointer is not the same as moving a conversation. Without a proxy
/// the change reaches the NEXT launch and nothing that is already running, and
/// reporting it as "this account now serves you" was simply false - the session
/// carried on with the old account while the line said otherwise.
pub fn switch_outcome_line(
    tool: &str,
    name: &str,
    proxy_running: bool,
    history_shared: bool,
) -> String {
    let bin = tool_binary(tool);
    if proxy_running {
        format!("{name} serves this session from the next turn ({bin} proxy is running)")
    } else {
        let mut out = format!("default {bin} account -> {name}\n");
        out.push_str(&format!(
            "  this applies to the NEXT {bin} you start; a session already open keeps the account it began with\n"
        ));
        // Only where a relay exists. Naming `swapdex proxy` for Gemini or
        // Antigravity pointed at a command that refuses to start, and without a
        // `--tool` the one it named starts Claude's.
        if crate::proxy::carries(tool) {
            out.push_str(&format!(
                "  to move one that is already running: swapdex proxy{}\n",
                tool_flag(tool)
            ));
        }
        // This used to warn that a switch changed which conversations `-c` and
        // `-r` could see, which was true and cost people time. Slots share their
        // history now, so it is no longer true - and a warning that has stopped
        // being true is worse than none, because it teaches a rule the tool no
        // longer follows. `share-history` repairs accounts made before that.
        if !history_shared {
            out.push_str(
                "  note: this account keeps its own conversation history - \
                 `swapdex share-history` makes them all reachable from every account",
            );
        }
        out
    }
}

/// Take the whole-store lock, or say which way it could not be taken.
///
/// `Err` carries the exit code the other store writers already use for both
/// causes, so a caller only has to hand it back.
fn store_lock_or_exit(store: &Store) -> std::result::Result<crate::store::LockGuard, i32> {
    match store.lock() {
        Ok(g) => Ok(g),
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            Err(4)
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            Err(4)
        }
    }
}

/// A direct `use` or `restore` intentionally selects the account again, so it
/// ends any prior serving override, including durable passthrough. The return
/// value says whether clearing it changed who pays and therefore needs its own
/// timeline event on an otherwise no-op credential selection.
fn clear_serving_choice(paths: &Paths, tool: &str) -> Result<bool> {
    let slots = crate::slots::Slots::open_for(paths, tool)?;
    let existed = slots.serving_pointer_file().exists();
    slots.clear_serving()?;
    Ok(existed)
}

fn use_slot_default(paths: &Paths, name: &str, tool: &str, dry_run: bool) -> Result<i32> {
    let bin = tool_binary(tool);
    if dry_run {
        println!("would set the default {bin} account -> {name}");
        return Ok(0);
    }
    let slots = crate::slots::Slots::open_for(paths, tool)?;
    // Slots share one conversation store, so nothing in a transcript says which
    // account produced it - the switch timeline is the only record, and `usage`
    // credits every token by it. Repointing the default IS a switch, so write
    // the same event `use <profile>` writes, under the same store lock.
    let store = Store::open(paths)?;
    let lock = match store_lock_or_exit(&store) {
        Ok(g) => g,
        Err(code) => return Ok(code),
    };
    slots.set_default(name)?;
    store.append_timeline(tool, name, "use")?;
    drop(lock);
    let proxy = crate::proxy::running_proxy_for(paths, tool).is_some();
    println!(
        "{}",
        switch_outcome_line(
            tool,
            name,
            proxy,
            crate::slots::history_is_shared(paths, tool)
        )
    );
    // First-time nudge: without the shim, a plain launch won't follow this.
    // Only where both halves are true. `swapdex shim` installs the Claude and
    // Codex shims alone, and `run` refuses a tool with no per-account home, so
    // for Gemini and Antigravity this promised a shim that never arrives and a
    // command that cannot succeed. And `run` defaults to Claude: naming it
    // without the tool is the mistake `sign_in_remedy` was written to fix, so
    // following the tip after a Codex switch built a second account of the same
    // name under Claude.
    if crate::slots::home_var(tool).is_some() && !crate::shim::shim_path_for(paths, tool).exists() {
        println!(
            "  tip: run `swapdex shim` once so a plain `{bin}` follows your switches\n\
             \x20      (or launch directly with `swapdex run {name}{}`)",
            tool_flag(tool)
        );
    }
    Ok(0)
}

/// Install shims for the supported clients that are present on this machine.
/// Each client is optional; finding one must not depend on finding the other.
pub fn install_shim(paths: &Paths) -> Result<i32> {
    install_requested_shims(paths, &["claude-code", "codex"])
}

fn install_requested_shims(paths: &Paths, requested: &[&str]) -> Result<i32> {
    let shim_dir = crate::shim::shim_bin_dir(paths);
    let mut installed = Vec::new();

    if requested.contains(&"claude-code") {
        match crate::shim::install_claude(paths)? {
            Some((shim, _)) => {
                println!("installed the claude shim at {}", shim.display());
                installed.push("claude");
            }
            None => println!("  (no `claude` on PATH - skipped its shim)"),
        }
    }
    if requested.contains(&"codex") {
        match crate::shim::install_codex(paths)? {
            Some(shim) => {
                println!("installed the codex shim at {}", shim.display());
                installed.push("codex");
            }
            None => println!("  (no `codex` on PATH - skipped its shim)"),
        }
    }
    if installed.is_empty() {
        eprintln!(
            "swapdex: no `claude` or `codex` executable found on PATH - install Claude Code or \
             Codex, then rerun `swapdex shim`"
        );
        return Ok(1);
    }

    // Reaching the proxy must not depend on winning the PATH. The shim only
    // fires when it does, and on a real machine another `claude` sat ahead of
    // it - so the proxy went unused and `serve` silently changed nothing for a
    // day, on two machines. Pinning the address in the tool's own settings is
    // what every competing proxy switcher does, and no PATH ordering undoes it.
    if installed.contains(&"claude") {
        let svc = {
            let h = paths.home();
            if cfg!(target_os = "macos") {
                crate::service::launchd_path(h, "claude-code").exists()
            } else {
                crate::service::systemd_path(h, "claude-code").exists()
            }
        };
        match crate::shim::pin_base_url(paths, 8787, svc)? {
            Some(f) => println!(
                "  pinned the proxy address in {} - a plain `claude` reaches it \
                 however it is started",
                crate::util::redact_path(&f.display().to_string())
            ),
            None => println!(
                "  not pinning the proxy address: no service keeps the proxy alive, and a \
                 pinned address with nothing behind it would stop `claude` from starting.\n\
                 \x20     run `swapdex service install --tool claude` first"
            ),
        }
    }

    // Put it on PATH ourselves. Leaving that to the user is how the shim ends up
    // installed but never reached: `swapdex use` then flips a pointer nothing
    // reads, and the switch appears to work while changing nothing.
    match crate::shim::ensure_on_path_for(paths, &shim_dir)? {
        crate::shim::PathSetup::AlreadyThere => {
            // On the PATH is not the same as WINNING it. Reporting membership as
            // success is how the shim ends up installed and never reached: the
            // proxy is never used and `serve` silently does nothing, while the
            // install says everything is fine. Say which entry holds the name.
            let entries: Vec<String> = std::env::var("PATH")
                .unwrap_or_default()
                .split(':')
                .map(str::to_string)
                .collect();
            let refs: Vec<&str> = entries.iter().map(String::as_str).collect();
            for binary in &installed {
                match crate::shim::path_verdict_for(&shim_dir, &refs, binary) {
                    crate::shim::PathVerdict::Wins => println!(
                        "  it is already on your PATH - a plain `{binary}` goes through its shim"
                    ),
                    crate::shim::PathVerdict::Shadowed(winner) => println!(
                        "  it is on your PATH but {} comes first and holds `{binary}`, so the \
                         {binary} shim never runs - `swapdex serve` would change nothing.\n\
                         \x20     put the shim ahead of it:  export PATH=\"{}:$PATH\"",
                        crate::util::redact_path(&winner),
                        shim_dir.display()
                    ),
                    crate::shim::PathVerdict::Absent => println!(
                        "  add this to your shell profile so it wins over the real {binary}:\n\
                         \x20     export PATH=\"{}:$PATH\"",
                        shim_dir.display()
                    ),
                }
            }
        }
        crate::shim::PathSetup::Added(profile) => {
            println!(
                "  added it to {} - open a new terminal (or `source` that file) and a plain \
                 {} goes through the installed shim",
                crate::util::redact_path(&profile.display().to_string()),
                installed
                    .iter()
                    .map(|binary| format!("`{binary}`"))
                    .collect::<Vec<_>>()
                    .join(" or ")
            );
        }
        crate::shim::PathSetup::Manual => {
            println!(
                "  add this to your shell profile so the installed shims win:\n\
                 \x20     export PATH=\"{}:$PATH\"",
                shim_dir.display()
            );
        }
    }
    Ok(0)
}

/// A [Y/n] prompt defaulting to yes. Non-interactive (no TTY) returns false so
/// onboarding never blocks a script - it prints guidance instead.
fn ask_yes(question: &str) -> bool {
    use std::io::IsTerminal;
    let tty = std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
    if !tty {
        return false;
    }
    matches!(
        prompt(&format!("{question} [Y/n]"), "y").as_deref(),
        Some("y") | Some("Y") | Some("")
    )
}

/// The marker written once onboarding has been shown, so a bare `swapdex` does
/// not re-run the guided flow on every launch.
fn onboarded_marker(paths: &Paths) -> std::path::PathBuf {
    paths.store_dir().join("onboarded")
}

/// Installed native clients whose plain launch still bypasses Swapdex.
fn available_missing_shims(paths: &Paths) -> Vec<&'static str> {
    ["claude-code", "codex"]
        .into_iter()
        .filter(|tool| {
            !crate::shim::shim_path_for(paths, tool).exists()
                && crate::shim::real_tool(paths, tool).is_some()
        })
        .collect()
}

/// True when a bare `swapdex` has an available client to wrap, an unregistered
/// Claude dir, or an unslotted profile account.
pub fn needs_onboarding(paths: &Paths) -> bool {
    if onboarded_marker(paths).exists() {
        return false;
    }
    if !available_missing_shims(paths).is_empty() {
        return true;
    }
    let Ok(slots) = crate::slots::Slots::open(paths) else {
        return false;
    };
    let has_unregistered = paths
        .discover_claude_config_dirs()
        .iter()
        .any(|d| !slots.list().iter().any(|r| &r.config_dir == d));
    if has_unregistered {
        return true;
    }
    if let Ok(store) = Store::open(paths) {
        return migration_tools(None).into_iter().any(|tool| {
            crate::slots::Slots::open_for(paths, tool)
                .map(|tool_slots| {
                    classify_migrations(&store, &tool_slots, tool)
                        .iter()
                        .any(|profile| profile.class == MigrationClass::NeedsSlot)
                })
                .unwrap_or(false)
        });
    }
    false
}

/// Guided first-run: detect what the user already has and walk them to a safe
/// slot setup, one [Y/n] at a time. Explains the win, hides the machinery.
pub fn onboard(paths: &Paths) -> Result<i32> {
    println!("swapdex gives each account its own space, so switching never logs you out.\n");

    // State 3: existing ~/.claude-* dirs the user runs by hand, not yet registered.
    let slots_now = crate::slots::Slots::open(paths)?;
    let unregistered: Vec<std::path::PathBuf> = paths
        .discover_claude_config_dirs()
        .into_iter()
        .filter(|d| !slots_now.list().iter().any(|r| &r.config_dir == d))
        .collect();
    if !unregistered.is_empty() {
        println!("Found Claude config dirs you already use:");
        for d in &unregistered {
            println!("  {}", d.display());
        }
        if ask_yes("Register them as swapdex accounts?") {
            let mut s = crate::slots::Slots::open_for_update(paths, "claude-code")?;
            for d in &unregistered {
                let name = d
                    .file_name()
                    .and_then(|n| n.to_str())
                    .map(|n| n.trim_start_matches(".claude-").to_string())
                    .filter(|n| !n.is_empty())
                    .unwrap_or_else(|| "account".into());
                match s.adopt(&name, d) {
                    Ok(r) => println!("  registered '{}'", r.name),
                    Err(e) => eprintln!("  skipped {}: {e}", d.display()),
                }
            }
        }
        println!();
    }

    // State 2: copy-model profiles classified against slot account identities.
    if let Ok(store) = Store::open(paths) {
        let mut legacy = 0;
        let mut copies = 0;
        for tool in migration_tools(None) {
            let slots = crate::slots::Slots::open_for(paths, tool)?;
            for profile in classify_migrations(&store, &slots, tool) {
                match profile.class {
                    MigrationClass::NeedsSlot => legacy += 1,
                    MigrationClass::CopyOfSlot(_) => copies += 1,
                    MigrationClass::AlreadySlotted | MigrationClass::Unreadable => {}
                }
            }
        }
        let mut reported_copies = false;
        if legacy > 0 {
            let profile_label = if legacy == 1 {
                "profile login"
            } else {
                "profile logins"
            };
            println!(
                "You have {legacy} saved Claude/Codex {profile_label} on the old copy-switch model \
                 (the one that could log you out)."
            );
            if ask_yes("Give each its own space now?") {
                migrate(paths, None)?;
                reported_copies = true;
                println!();
            }
        }
        if copies > 0 && !reported_copies {
            let copy_label = if copies == 1 {
                "profile copy"
            } else {
                "profile copies"
            };
            println!(
                "You also have {copies} saved {copy_label} whose account already lives in a \
                 differently named slot; nothing needs to be migrated for those."
            );
        }
    }

    // Casual convenience: offer only shims that can wrap a client this machine
    // actually has. Each tool can arrive later, so explicit `onboard` checks
    // again even when an older shim is already present.
    let missing_shims = available_missing_shims(paths);
    let question = match missing_shims.as_slice() {
        ["claude-code"] => Some(
            "Make a plain `claude` follow `swapdex use`? (installs a small shim)",
        ),
        ["codex"] => Some(
            "Make a plain `codex` follow `swapdex use --tool codex`? (installs a small shim)",
        ),
        ["claude-code", "codex"] => Some(
            "Make plain `claude` and `codex` follow their `swapdex use` selections? (installs small shims)",
        ),
        _ => None,
    };
    if let Some(question) = question {
        if ask_yes(question) {
            install_requested_shims(paths, &missing_shims)?;
            println!();
        }
    }

    // Mark it shown so a bare `swapdex` does not re-run this every launch.
    let _ = crate::atomic::write_managed(&onboarded_marker(paths), b"1");

    // Wrap up from the same union every account-facing command uses. A person
    // may decline migration and keep a usable snapshot, and slots now exist
    // for four tools; counting two slot registries called both states empty.
    if !has_any_account(paths) {
        println!(
            "No accounts yet. Install your native client if needed, then sign in inside a new slot:\n\
             \x20 Codex:  swapdex run work --tool codex -- login --device-auth\n\
             \x20 Claude: swapdex run work --tool claude -- auth login\n\
             Use the command for your client; `work` is an example account name.\n\
             Continue with shim activation and launch selection:\n\
             \x20 https://github.com/youdie006/swapdex#quick-start"
        );
    } else {
        println!("You're set. `swapdex ui` shows your accounts and switches between them.");
    }
    Ok(0)
}

/// Create permanent slots for copy-model Claude and Codex profiles matched by
/// account, so they can be used via `run`/`use` with no credential copying.
///
/// Still does NOT import a token: a slot's login is created by a fresh sign-in,
/// and swapdex never writes a credential. What it writes for a slot it just made
/// is the account id that slot is FOR, which is an identifier, not a secret -
/// see the marker below.
pub fn migrate(paths: &Paths, sel: Option<MigrationToolSel>) -> Result<i32> {
    let store = Store::open(paths)?;
    let tools = migration_tools(sel);
    if tools.is_empty() {
        eprintln!("swapdex: migrate supports only claude and codex");
        return Ok(2);
    }
    for (index, tool) in tools.into_iter().enumerate() {
        if index > 0 {
            println!();
        }
        println!("{}:", pretty_tool(tool));
        let mut slots = crate::slots::Slots::open_for_update(paths, tool)?;
        let classified = classify_migrations(&store, &slots, tool);
        let mut created = Vec::new();
        let mut renamed = Vec::new();
        let mut copies = Vec::new();
        let mut unreadable = Vec::new();
        let mut assigned_accounts: Vec<(String, String)> = Vec::new();
        let taken: Vec<String> = slots.list().into_iter().map(|r| r.name).collect();
        let mut taken = taken;
        for profile in classified {
            match profile.class {
                MigrationClass::AlreadySlotted => {}
                MigrationClass::CopyOfSlot(slot_name) => {
                    copies.push((profile.name, slot_name));
                }
                MigrationClass::Unreadable => unreadable.push(profile.name),
                MigrationClass::NeedsSlot => {
                    if let Some((_, slot_name)) = assigned_accounts.iter().find(|(account, _)| {
                        profile.account_id.as_deref() == Some(account.as_str())
                    }) {
                        copies.push((profile.name, slot_name.clone()));
                        continue;
                    }
                    let collides = taken.iter().any(|name| name == &profile.name);
                    let name = if crate::slots::name_reads_as_a_tool_home(&profile.name)
                        || crate::slots::name_is_reserved(&profile.name)
                        || collides
                    {
                        crate::slots::suggest_non_colliding(&profile.name, &taken)
                    } else {
                        profile.name.clone()
                    };
                    if name != profile.name {
                        renamed.push((profile.name, name.clone()));
                    }
                    let account = profile.account_id.as_deref().ok_or_else(|| {
                        anyhow::anyhow!("migration account disappeared after classification")
                    })?;
                    // Which account this slot is FOR, before anyone has signed
                    // into it - otherwise the next run reads no account id here
                    // and offers to create the same slot again. Written with the
                    // secret writer for its atomicity, not its secrecy: a torn
                    // write would name the wrong account, and it is the only
                    // atomic writer there is. The id itself is an identifier,
                    // and a real login always outranks it when one arrives.
                    let rec = slots.create_initialized(&name, |dir| {
                        crate::atomic::write_secret(
                            &dir.join(MIGRATED_ACCOUNT_MARKER),
                            account.as_bytes(),
                        )
                    })?;
                    if let Some(account) = &profile.account_id {
                        assigned_accounts.push((account.clone(), name.clone()));
                    }
                    crate::slots::link_shared_config(
                        &rec.config_dir,
                        &shared_source(paths, tool),
                        tool,
                    );
                    taken.push(name.clone());
                    created.push(name);
                }
            }
        }
        if !created.is_empty() {
            for (profile, slot_name) in renamed {
                println!(
                    "  '{profile}' cannot be used as this slot name, so the account is named '{slot_name}'"
                );
            }
            println!("  Created slots for: {}", created.join(", "));
            println!("  Sign in to each once:");
            for name in &created {
                println!("    swapdex run {name} --tool {}", pretty_tool_flag(tool));
            }
        }
        for (profile, slot_name) in &copies {
            println!(
                "  Saved profile '{profile}' is a saved copy of slot '{slot_name}' - nothing to \
                 do; leave it alone or remove it with `swapdex rm {profile} --tool {}`.",
                pretty_tool_flag(tool)
            );
        }
        for profile in &unreadable {
            println!(
                "  Could not read the account ID from saved profile '{profile}'; no slot was created."
            );
        }
        if created.is_empty() && copies.is_empty() && unreadable.is_empty() {
            println!("  Nothing to migrate.");
        }
    }
    Ok(0)
}

/// Share MCP servers across slots. Each Claude slot keeps its own `.claude.json`
/// (which mixes the per-account `oauthAccount` with the shareable `mcpServers`),
/// so MCP config cannot simply be symlinked like `settings.json`. This copies the
/// `mcpServers` block from the bare `~/.claude.json` into every slot's own
/// `.claude.json`, preserving each slot's account identity and other keys. Run it
/// after logging into your slots (a slot has no `.claude.json` until first login).
pub fn sync_mcp(paths: &Paths) -> Result<i32> {
    let src_path = paths.claude_config_json();
    let src: Value = if src_path.exists() {
        serde_json::from_slice(&crate::atomic::read_regular(&src_path)?).unwrap_or(Value::Null)
    } else {
        Value::Null
    };
    let mcp = src
        .get("mcpServers")
        .cloned()
        .unwrap_or_else(|| serde_json::json!({}));
    let n = mcp.as_object().map(|o| o.len()).unwrap_or(0);
    if n == 0 {
        println!("No MCP servers in ~/.claude.json to share.");
        return Ok(0);
    }
    let slots = crate::slots::Slots::open(paths)?;
    let mut synced = 0;
    let mut pending = 0;
    for r in slots.list() {
        let target = r.config_dir.join(".claude.json");
        if !target.exists() {
            pending += 1;
            continue;
        }
        let mut cfg: Value =
            serde_json::from_slice(&crate::atomic::read_regular(&target)?).unwrap_or(Value::Null);
        let Some(obj) = cfg.as_object_mut() else {
            continue;
        };
        obj.insert("mcpServers".into(), mcp.clone());
        crate::atomic::write_secret(&target, &serde_json::to_vec(&cfg)?)?;
        synced += 1;
    }
    println!("shared {n} MCP server(s) into {synced} account(s).");
    if pending > 0 {
        println!(
            "  {pending} account(s) have no login yet - sign them in from `swapdex ui` (the `l` key)."
        );
    }
    Ok(0)
}

/// Register an existing `CLAUDE_CONFIG_DIR` directory as a slot, in place.
pub fn adopt_slot(
    paths: &Paths,
    name: &str,
    dir: &std::path::Path,
    sel: Option<ToolSel>,
) -> Result<i32> {
    let tool = slot_tool(sel);
    let mut slots = crate::slots::Slots::open_for_update(paths, tool)?;
    let rec = slots.adopt(name, dir)?;
    println!(
        "registered '{}' ({tool}) -> {}",
        rec.name,
        rec.config_dir.display()
    );
    Ok(0)
}

/// An absent credential is the only unbound slot that may skip association.
/// On macOS the Keychain is authoritative; an old credential file cannot prove
/// the item exists. Query only the exact service's attributes, never its secret.
fn claude_slot_credential_absent(paths: &Paths, dir: &std::path::Path) -> Result<bool> {
    if cfg!(target_os = "macos") && !paths.sandboxed() && std::env::var_os("SWAPDEX_ROOT").is_none()
    {
        use std::process::Stdio;
        use std::time::{Duration, Instant};

        let service = crate::adapters::claude::slot_service(dir);
        let mut check = std::process::Command::new("/usr/bin/security")
            .args(["find-generic-password", "-s", &service])
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .context("check selected Claude Keychain service")?;
        let deadline = Instant::now() + Duration::from_secs(3);
        loop {
            if let Some(status) = check.try_wait()? {
                return match status.code() {
                    Some(44) => Ok(true),
                    Some(0) => Ok(false),
                    _ => bail!("cannot verify whether the selected Claude Keychain item exists"),
                };
            }
            if Instant::now() >= deadline {
                check.kill().ok();
                check.wait().ok();
                bail!("timed out checking the selected Claude Keychain item");
            }
            std::thread::sleep(Duration::from_millis(20));
        }
    }
    match std::fs::symlink_metadata(dir.join(".credentials.json")) {
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(true),
        Err(error) => Err(error).context("inspect selected Claude credential"),
        Ok(_) => Ok(false),
    }
}

/// Guard a managed Claude launch before exec. A bound descriptor always wins;
/// otherwise a present slot login must be associated with a matching live
/// native store before either inference or a new explicit authentication.
fn prepare_claude_launch(
    paths: &Paths,
    dir: &std::path::Path,
    authentication: bool,
    known_slot: bool,
) -> Result<Option<crate::claude_authority::Authority>> {
    let marker = dir.join(crate::claude_authority::RECORD);
    let bound = match std::fs::symlink_metadata(&marker) {
        Ok(_) => true,
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => false,
        Err(error) => return Err(error).context("inspect Claude authority marker"),
    };
    let registered = if known_slot || bound {
        true
    } else {
        let slots = crate::slots::Slots::open_for(paths, "claude-code")?;
        let mut directories: Vec<_> = slots
            .list()
            .into_iter()
            .map(|slot| slot.config_dir)
            .collect();
        directories.extend(slots.default_dir());
        if directories.iter().any(|registered| registered == dir) {
            true
        } else {
            if let Ok(actual) = std::fs::canonicalize(dir) {
                if directories.iter().any(|registered| {
                    std::fs::canonicalize(registered).is_ok_and(|registered| registered == actual)
                }) {
                    // Claude hashes the raw config path for its Keychain key.
                    // Neither treating this alias as independent nor silently
                    // rewriting it can safely select that authentication store.
                    bail!("Claude config aliases a managed account; use its registered config directory or `swapdex run <account>`");
                }
            }
            false
        }
    };
    if !bound && !registered {
        return Ok(None); // caller-chosen, unregistered CLAUDE_CONFIG_DIR
    }
    if !bound && !claude_slot_credential_absent(paths, dir)? {
        crate::claude_authority::reconcile_live(paths, dir)?;
    }
    let authority = if authentication {
        crate::claude_authority::resolve_for_authentication(paths, dir)?
    } else {
        crate::claude_authority::resolve(paths, dir)?
    };
    Ok(Some(authority))
}

/// Launch Claude in `<name>`'s permanent slot (create the slot on first use).
/// swapdex never writes the credential here - the tool's own login does, into
/// the slot's own `CLAUDE_CONFIG_DIR`. `exec` replaces this process, so this
/// only returns on failure.
pub fn run_account(
    paths: &Paths,
    name: &str,
    sel: Option<ToolSel>,
    no_launch: bool,
    args: &[String],
) -> Result<i32> {
    use std::os::unix::process::CommandExt;
    let tool = slot_tool(sel);
    let Some(home_var) = crate::slots::home_var(tool) else {
        eprintln!(
            "swapdex: {tool} has no per-account home to launch into - only claude and codex do"
        );
        return Ok(2);
    };
    let mut slots = crate::slots::Slots::open_for_update(paths, tool)?;
    let rec = match slots.get(name) {
        Some(r) => r,
        None => {
            let r = slots.create(name)?;
            crate::slots::link_shared_config(&r.config_dir, &shared_source(paths, tool), tool);
            r
        }
    };
    // The registry write is done. What follows launches the tool and never
    // returns, so the lock must be given back here rather than at a scope end
    // that `exec` will not reach.
    drop(slots);
    if no_launch {
        println!("account '{name}' is ready ({tool})");
        println!(
            "  its home: {}",
            crate::util::redact_path(&rec.config_dir.display().to_string())
        );
        return Ok(0);
    }
    let bin = tool_binary(tool);
    if !command_exists(bin) {
        eprintln!("swapdex: `{bin}` isn't on your PATH. Install it, then retry.");
        return Ok(3);
    }
    // A named run is the direct path used to create or refresh this slot's own
    // login. If our shim wins PATH, invoking the bare name loops through managed
    // proxy startup before the new slot has a credential and the login client
    // never opens. Step over that shim exactly as the dashboard sign-in does.
    let Some(exe) = crate::shim::real_tool(paths, tool) else {
        eprintln!(
            "swapdex: real `{bin}` executable not found behind the installed shim. \
             Reinstall `{bin}`, then retry."
        );
        return Ok(3);
    };
    let mut cmd = std::process::Command::new(exe);
    cmd.args(args);
    configure_managed_tool_home(&mut cmd, tool, home_var, &rec.config_dir);
    if tool == "claude-code" {
        let authentication = crate::shim::claude_authentication_command(args);
        let authority = prepare_claude_launch(paths, &rec.config_dir, authentication, true)?
            .context("selected Claude account has no launch authority")?;
        authority.configure_launch(paths, &mut cmd, authentication)?;
    }
    // This is the path a sign-in takes, and signing in must reach the vendor
    // directly. An inherited proxy address both breaks the OAuth code exchange
    // and answers with whichever account the proxy already holds - so a fresh
    // slot appears to be signed in as somebody else, or its prompt takes no
    // input at all. A slot launched here serves itself, so the proxy has nothing
    // to add either way.
    for var in ["ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY"] {
        cmd.env_remove(var);
    }
    let err = cmd.exec();
    Err(anyhow::anyhow!("failed to launch {bin}: {err}"))
}

/// Called by the generated shim for every nonempty Claude config directory.
/// All text passed to the native executable remains individual argv elements.
pub fn launch_claude_authority(
    paths: &Paths,
    native: &std::path::Path,
    args: &[String],
) -> Result<i32> {
    use std::os::unix::process::CommandExt;
    let dir = std::env::var_os("CLAUDE_CONFIG_DIR")
        .map(std::path::PathBuf::from)
        .ok_or_else(|| {
            anyhow::anyhow!("a linked Claude launch requires its session config directory")
        })?;
    let authentication = crate::shim::claude_authentication_command(args);
    let mut cmd = Command::new(native);
    cmd.args(args);
    if let Some(authority) = prepare_claude_launch(paths, &dir, authentication, false)? {
        authority.configure_launch(paths, &mut cmd, authentication)?;
    }
    Err(anyhow::anyhow!("could not launch Claude: {}", cmd.exec()))
}

/// Why a token could not be used, without guessing which kind of failure it was.
///
/// `token_usable` rejects an empty token and a malformed one alike, so a
/// credential that came back EMPTY - on macOS, a Keychain that would not open
/// for this shell - was reported as a corrupt snapshot with `add --update`
/// offered as the fix. That would overwrite a perfectly good saved copy with
/// whatever this shell can see, which is nothing. Other accounts in the same
/// listing said plainly that the keychain could not be read; only this branch
/// guessed, and guessed destructively.
pub fn unusable_token_reason(token: &str, unreadable: Option<&str>) -> String {
    if !token.is_empty() {
        return "saved token unusable (corrupt snapshot?) - `swapdex add <name> --update` \
                re-saves it"
            .to_string();
    }
    match unreadable {
        Some(why) => why.to_string(),
        None => "its credential read back empty here - nothing was saved wrong; \
                 run this where the login can be read"
            .to_string(),
    }
}

/// Where a capture reads the credential from.
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum CaptureSource {
    /// The live login - what every capture has always read.
    LiveHome,
    /// The account's own slot directory.
    Slot,
}

/// Which one `--from-slot` selects.
///
/// A stale saved copy did not mean a bad login: the slot holds a good one, which
/// is why the account serves turns fine. Only the snapshot was old, and the sole
/// path that could refresh it ran inside the interactive sign-in key - so the
/// only way to clear the marker was to sign in again for no reason.
pub fn capture_source(from_slot: bool) -> CaptureSource {
    if from_slot {
        CaptureSource::Slot
    } else {
        CaptureSource::LiveHome
    }
}

pub(crate) fn sign_in_child(paths: &Paths, name: &str, tool: &str) -> (bool, String) {
    let Some(home_var) = crate::slots::home_var(tool) else {
        return (
            false,
            format!("{tool} has no per-account home to sign into"),
        );
    };
    let mut slots = match crate::slots::Slots::open_for_update(paths, tool) {
        Ok(s) => s,
        Err(e) => return (false, format!("cannot open the account list: {e}")),
    };
    let rec = match slots.get(name) {
        Some(r) => r,
        None => match slots.create(name) {
            Ok(r) => {
                crate::slots::link_shared_config(&r.config_dir, &shared_source(paths, tool), tool);
                r
            }
            Err(e) => return (false, format!("could not make a space for '{name}': {e}")),
        },
    };
    // The registry write is done, and the sign-in below waits on a human at a
    // browser. Holding the registry lock across that would stall every other
    // account registration for as long as the person takes.
    drop(slots);
    let bin = tool_binary(tool);
    if !command_exists(bin) {
        return (false, format!("`{bin}` isn't on your PATH"));
    }
    // Signing in must reach the vendor directly, and there are two ways it did
    // not. An inherited proxy ADDRESS answers with whichever account the proxy
    // already holds - that one is cleared below. And the shim itself puts the
    // proxy in front of any Codex run it does not recognise as plain: a bare
    // launch is not recognised, so pressing the sign-in key opened a session
    // served by the account that was already paying. An account with no login
    // came up looking signed in, and nothing about it was true. So: the REAL
    // binary, never the shim, and the subcommand that actually signs in.
    let Some(exe) = crate::shim::real_tool(paths, tool) else {
        return (
            false,
            format!(
                "real `{bin}` executable not found behind the installed shim; \
                 reinstall `{bin}`, then retry"
            ),
        );
    };
    match spawn_tool_login_in(
        paths,
        &exe,
        tool,
        Some((home_var, rec.config_dir.as_path())),
    ) {
        Ok(_) => {
            // Whether the sign-in succeeded is the credential's story, not the
            // exit code's: the tool exits 0 when the user simply quits it.
            //
            // Asked through has_login, which is the one place that knows what a
            // login looks like per tool. This was a third copy of that question
            // and it was wrong twice over: gemini and antigravity got Claude's
            // check, so a sign-in that worked was reported as failed, and it
            // used `slot_token` - the wrapper that throws away WHY - so a
            // Keychain that would not open also read as never signed in.
            let signed_in = crate::proxy::has_login(paths, tool, &rec.config_dir);
            if signed_in {
                // Re-capture from the slot this sign-in just landed in. The
                // marker the user is trying to clear is about the SAVED COPY,
                // and until now nothing could refresh it from the login they had
                // just made. Reading the default dir instead would file whoever
                // happens to be live under this account's name, so the paths are
                // pointed at the slot explicitly rather than through an
                // environment variable a sandbox would ignore.
                // A redirect that quietly did nothing is worse than none: the
                // capture below would then read the LIVE default dir and file
                // whoever is signed in there under this account's name.
                match paths
                    .try_with_tool_dir(tool, &rec.config_dir)
                    .ok_or_else(|| {
                        anyhow::anyhow!(
                            "cannot point '{tool}' at its slot, so a capture would \
                             read the live default instead"
                        )
                    })
                    .and_then(|at_slot| {
                        crate::adapters::by_name(tool)
                            .ok_or_else(|| anyhow::anyhow!("unknown tool"))
                            .and_then(|a| a.capture(&at_slot))
                    })
                    .and_then(|snap| {
                        crate::store::Store::open(paths)?.save(name, &snap)?;
                        Ok(())
                    }) {
                    Ok(()) => (
                        true,
                        format!("'{name}' is signed in, and its saved copy is fresh"),
                    ),
                    Err(e) => (
                        true,
                        format!(
                            "'{name}' is signed in, but its saved copy could not be \
                             refreshed ({e})"
                        ),
                    ),
                }
            } else {
                (
                    false,
                    format!("'{name}' still has no login - run it again and complete the sign-in"),
                )
            }
        }
        Err(e) => (false, format!("could not start {bin}: {e}")),
    }
}

/// The tool a slot command means. Slots exist for the two tools that can be
/// pointed at a per-account home; anything else is the caller's error to report.
/// The one tool a `--tool` selection names, or None for "every tool" - which is
/// what omitting the flag already means.
///
/// `slot_tool` answers a different question (which tool a SLOT defaults to, and
/// that default is Claude), so it cannot stand in here: it would turn `--tool
/// all` into `--tool claude`.
pub(crate) fn one_tool(sel: ToolSel) -> Option<&'static str> {
    match sel {
        ToolSel::Claude => Some("claude-code"),
        ToolSel::Codex => Some("codex"),
        ToolSel::Gemini => Some("gemini"),
        ToolSel::Antigravity => Some("antigravity"),
        ToolSel::All => None,
    }
}

pub(crate) fn slot_tool(sel: Option<ToolSel>) -> &'static str {
    match sel {
        Some(ToolSel::Codex) => "codex",
        Some(ToolSel::Gemini) => "gemini",
        Some(ToolSel::Antigravity) => "antigravity",
        // Claude is the default: it is what slots were built for, and every
        // existing `swapdex run <name>` must keep meaning the same thing.
        _ => "claude-code",
    }
}

/// The executable each tool actually installs.
///
/// The one table. `exec_tool` had this right while this had everything that
/// was not codex answering "claude", and fourteen call sites read this one -
/// including the shim's search for the real binary, so for gemini and
/// antigravity swapdex went looking for Claude.
pub(crate) fn tool_binary(tool: &str) -> &'static str {
    match tool {
        "codex" => "codex",
        "gemini" => "gemini",
        "antigravity" => "agy",
        _ => "claude",
    }
}

/// The bare config dir a new slot borrows its shared, account-agnostic files
/// from.
fn shared_source(paths: &Paths, tool: &str) -> std::path::PathBuf {
    match tool {
        "codex" => paths.codex_dir().to_path_buf(),
        // Their own tree, not Claude's. Nothing is linked from here for these
        // two today, but pointing the source at the wrong tool is how an empty
        // list becomes a wrong one the moment somebody fills it in.
        "gemini" | "antigravity" => paths.gemini_dir().to_path_buf(),
        _ => paths.claude_dir().to_path_buf(),
    }
}

/// `swapdex whereis [project]` - which account's store holds a conversation.
///
/// Switching accounts also switches which conversations `claude -c` and
/// `claude -r` can see, because Claude keeps them inside the config dir it was
/// launched with. Nothing is lost, but "no conversation found" reads exactly
/// like it was, so this says where the conversation actually is and how to
/// reopen it from any account.
pub fn whereis(paths: &Paths, project: Option<&str>) -> Result<i32> {
    // Both tools: a conversation is lost the same way in either, and someone
    // looking for theirs does not know which store to ask about.
    let mut found = crate::whereis::find(paths, project, 15);
    found.extend(crate::whereis::find_codex(paths, project, 15));
    found.sort_by_key(|f| std::cmp::Reverse(f.modified));
    found.truncate(15);
    if found.is_empty() {
        match project {
            Some(p) => println!("No conversation under a path matching '{p}', in any account."),
            None => println!("No conversations found in any account's store yet."),
        }
        return Ok(0);
    }
    println!("conversations, newest first - the account column is whose store holds it\n");
    let width = found
        .iter()
        .map(|f| f.account.chars().count())
        .max()
        .unwrap_or(8);
    for f in &found {
        println!(
            "  {:<width$} {:>8}  {}",
            f.account,
            // age_line takes the moment itself, not how long ago it was.
            age_line(f.modified as u128 * 1_000_000_000),
            f.project,
        );
        println!("    {}", f.resume_command());
    }
    println!(
        "\nnaming the config dir is what makes these work from any account - the shim\n\
         only fills that variable in when it is unset, so an explicit one always wins."
    );
    Ok(0)
}

/// `swapdex serve [name]` - hand turns to an account without moving where new
/// sessions start.
///
/// This is the operation the whole tool exists for: one place where all your
/// conversations live, and accounts swapped underneath it as they run out. It is
/// what a credential-copying switcher gets for free by only ever having one
/// store - and what swapdex had to separate deliberately, because isolating
/// accounts is also what isolates their conversations.
/// Is there anything for the dashboard to show?
///
/// A bare `swapdex` opens the picker when the answer is yes. It used to ask only
/// about saved profiles and live logins, never about slots - which is what
/// `run`, `adopt`, and `onboard` create. So the model swapdex steers people into
/// did not count as having accounts, and a user whose accounts were all slots
/// got a banner where the picker should have been.
pub fn has_any_account(paths: &Paths) -> bool {
    if Store::open(paths)
        .map(|st| !st.list().is_empty())
        .unwrap_or(false)
    {
        return true;
    }
    crate::adapters::names().into_iter().any(|t| {
        crate::slots::Slots::open_for(paths, t)
            .map(|s| !s.list().is_empty())
            .unwrap_or(false)
    })
}

/// Which account a dashboard row should be marked active for.
///
/// A running proxy's own record wins, because after a rotation it may be
/// serving someone other than the one chosen; otherwise the pointers decide.
/// Claude's rows already asked this way and Codex's asked only its pointer, so
/// handing turns to a Codex account left the mark where it was and the change
/// read as nothing having happened. One resolution for both tools.
pub fn active_slot_name(paths: &Paths, tool: &str) -> Option<String> {
    let slots = crate::slots::Slots::open_for(paths, tool).ok()?;
    if slots.serving_is_off() {
        return None;
    }
    let name_of = |dir: std::path::PathBuf| {
        slots
            .list()
            .into_iter()
            .find(|r| r.config_dir == dir)
            .map(|r| r.name)
    };
    pick_active(
        slots.serving_dir().and_then(&name_of),
        crate::proxy::serving_account_for(paths, tool),
        slots.default_dir().and_then(&name_of),
        proxy_acted_since_ask(paths, tool),
    )
}

/// Has the proxy served a turn SINCE the account was chosen?
///
/// Both records are files, and their timestamps answer it: the ask is written
/// when the user picks, the proxy's record when it forwards. If the proxy's is
/// the newer of the two, it has had its say about the choice.
///
/// False when either is missing - no ask cannot be thwarted, and a proxy that
/// has never served has not contradicted anything.
fn proxy_acted_since_ask(paths: &Paths, tool: &str) -> bool {
    let asked = crate::slots::Slots::open_for(paths, tool)
        .ok()
        .map(|s| s.serving_pointer_file());
    let did = crate::proxy::serving_record_file(paths, tool);
    let stamp = |p: Option<std::path::PathBuf>| {
        p.and_then(|p| std::fs::metadata(p).ok())
            .and_then(|m| m.modified().ok())
    };
    match (stamp(asked), stamp(Some(did))) {
        (Some(a), Some(d)) => d > a,
        _ => false,
    }
}

/// The order of authority behind that mark: what was ASKED FOR, then what
/// HAPPENED, then where sessions start.
///
/// It used to read the other way round, and the past outranked the instruction:
/// `proxy-serving` is what the proxy LAST did, which until the next turn goes
/// out is still the previous account. So pressing Enter changed who pays and the
/// row went on naming the old one, with nothing to say the key had worked.
///
/// A rotation still shows, because it happens when nobody asked for anything -
/// exactly when the proxy's own record is the only answer there is.
pub fn pick_active(
    asked_for: Option<String>,
    proxy_did: Option<String>,
    default: Option<String>,
    proxy_acted_since_ask: bool,
) -> Option<String> {
    // The ask wins until the proxy has served someone ELSE since it was made.
    // At that point the ask demonstrably did not take, and going on naming it
    // tells the user their key worked when it did not - seen on a real machine,
    // where an account asked for at 13:45 was still marked active half an hour
    // later while every turn went elsewhere because it refuses on overage.
    if proxy_acted_since_ask {
        if let (Some(a), Some(d)) = (asked_for.as_deref(), proxy_did.as_deref()) {
            if a != d {
                return proxy_did;
            }
        }
    }
    asked_for.or(proxy_did).or(default)
}

/// An ask the proxy is not honouring, in words - or `None` when there is none.
///
/// Resolving the disagreement silently would leave the user staring at an
/// account they did not choose with no idea why. They asked for something; the
/// screen owes them the reason it is not happening.
pub fn unhonoured_ask(
    asked_for: Option<&str>,
    proxy_did: Option<&str>,
    proxy_acted_since_ask: bool,
) -> Option<String> {
    if !proxy_acted_since_ask {
        return None;
    }
    match (asked_for, proxy_did) {
        (Some(a), Some(d)) if a != d => Some(format!(
            "asked for {a} - it cannot serve, so turns are going to {d}"
        )),
        _ => None,
    }
}

/// What a screen should call the account paying the next turn.
///
/// Used by Swapdex's status surfaces and `serve --quiet`. Include login health
/// so an account without usable credentials is not represented as ready to pay.
pub fn payer_label(paths: &Paths, tool: &str) -> Option<String> {
    let slots = crate::slots::Slots::open_for(paths, tool).ok()?;
    let who = slots.payer()?;
    let rec = slots.get(&who)?;
    let email = match tool {
        "codex" => codex_slot_email(&rec.config_dir),
        _ => crate::proxy::creds::slot_email(&rec.config_dir),
    };
    // The DEFAULT pointer, not `active_slot_name` - that one consults the
    // serving pointer first, so it always agreed with the payer and the note
    // could never appear. `use` is what decides where a plain launch lands.
    let home = slots.default_dir().and_then(|d| {
        slots
            .list()
            .into_iter()
            .find(|r| r.config_dir == d)
            .map(|r| r.name)
    });
    Some(format!(
        "{}{}",
        payer_line(
            &who,
            email.as_deref(),
            crate::proxy::has_login(paths, tool, &rec.config_dir),
        ),
        home_note(&who, home.as_deref())
    ))
}

/// Where the session's files live, when that is NOT the account paying for it.
///
/// `serve` decides who pays; `use` decides where new sessions live. Include
/// the home in Swapdex's payer label when those choices differ.
pub fn home_note(payer: &str, home: Option<&str>) -> String {
    match home {
        Some(h) if h != payer => format!(" - home: {h}"),
        _ => String::new(),
    }
}

/// A compact payer label for Swapdex status. The email identifies the login
/// behind a user-chosen slot name such as `work`.
pub fn payer_line(name: &str, email: Option<&str>, has_login: bool) -> String {
    match (email.filter(|e| *e != name), has_login) {
        (Some(e), true) => format!("{name} ({e})"),
        (Some(e), false) => format!("{name} ({e}, no login)"),
        (None, true) => name.to_string(),
        // The shape callers already depended on, kept: a name with nothing
        // known about it still says plainly that it cannot pay.
        (None, false) => format!("{name} (no login)"),
    }
}

/// The `--tool` flag where it is needed, nothing where it is not.
///
/// Claude is every command's default, so naming it is noise. Knowing only
/// Codex was a trap: any caller reached with a third tool got an empty flag
/// and printed a command aimed at Claude. Same wording as `sign_in_remedy`.
fn tool_flag(tool: &str) -> String {
    match tool {
        "claude-code" | "claude" => String::new(),
        other => format!(" --tool {other}"),
    }
}

pub fn serve(
    paths: &Paths,
    name: Option<&str>,
    off: bool,
    sel: Option<ToolSel>,
    quiet: bool,
) -> Result<i32> {
    let tool = slot_tool(sel);
    // Turns are paid through the relay, so where there is none there is no
    // payer to choose. `proxy` and `service install` already refuse these tools
    // by name; this one wrote a serving pointer, said "now <name>", and sent the
    // reader to a `swapdex proxy` that then refuses to start.
    if !crate::proxy::carries(tool) {
        eprintln!("{}", crate::proxy::cannot_carry(tool));
        return Ok(2);
    }
    let bin = tool_binary(tool);
    let slots = crate::slots::Slots::open_for(paths, tool)?;
    // A pointer naming an account that is gone is inert but not harmless: adopt
    // its directory back and it would start paying again. This is the command
    // that owns the pointer, so it is the one that clears it.
    slots.prune_serving();
    if off {
        let store = Store::open(paths)?;
        let _lock = match store_lock_or_exit(&store) {
            Ok(g) => g,
            Err(code) => return Ok(code),
        };
        slots.set_serving_off()?;
        store.append_timeline(tool, "", crate::session_link::SERVE_OFF)?;
        // A prior proxy result is no longer authoritative. The durable marker
        // also suppresses it on reads, while removing it keeps old readers
        // from claiming that managed account still pays.
        match std::fs::remove_file(crate::proxy::serving_record_file(paths, tool)) {
            Ok(()) => {}
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
            Err(error) => return Err(error.into()),
        }
        println!("passthrough is on - each session pays with its own login ({bin})");
        return Ok(0);
    }
    // The bare answer, for a caller that puts it somewhere else - the codex shim
    // labels its provider with it. The question there is "who pays", so it takes
    // the default when nobody is directing turns; naming only the explicit case
    // would leave the common one anonymous. Silence means there is no account at
    // all, which is a real answer and not a failure, so it still exits 0.
    if quiet {
        if let Some(label) = payer_label(paths, tool) {
            // Append what that account has left, from cache. Going through the
            // proxy costs the tool its own rate_limits block, so a status line
            // reading those prints "N/A" while swapdex holds a reading from a
            // minute ago. No request is made: a bar redraws constantly.
            let who = label
                .split_whitespace()
                .next()
                .unwrap_or(&label)
                .to_string();
            let cache = crate::quota_cache::load_for(paths, tool);
            let brief = cache
                .get(&who)
                .map(|e| cached_brief(e, now_secs() as i64))
                // No entry at all is the same news as an entry with no numbers.
                .unwrap_or_else(|| quota_brief(None, None));
            if brief.is_empty() {
                print!("{label}");
            } else {
                print!("{label} - {brief}");
            }
        }
        return Ok(0);
    }
    let Some(name) = name else {
        if slots.serving_is_off() {
            println!("passthrough is on ({bin}) - each session pays with its own login");
            return Ok(0);
        }
        match slots.serving_dir() {
            Some(dir) => {
                let who = slots
                    .list()
                    .into_iter()
                    .find(|r| r.config_dir == dir)
                    .map(|r| r.name)
                    .unwrap_or_else(|| "(unknown)".into());
                println!("turns are served by '{who}' ({bin})");
            }
            None => println!(
                "no account is directing turns ({bin}) - each session pays for itself\n                   `swapdex serve <name>{}` hands them to one without moving your conversations",
                tool_flag(tool)
            ),
        }
        return Ok(0);
    };
    let Some(rec) = slots.get(name) else {
        // Name the accounts here rather than sending the reader to another
        // screen to read four words - and name BOTH kinds. Listing only slots
        // answered "no accounts saved yet" about a profile `add` had just
        // saved and `ls` was already showing.
        let mut servable: Vec<String> = crate::slots::Slots::open_for(paths, tool)
            .map(|sl| sl.list().into_iter().map(|r| r.name).collect())
            .unwrap_or_default();
        servable.sort();
        let mut saved: Vec<String> = Store::open(paths)
            .map(|st| st.list().into_iter().map(|p| p.name).collect())
            .unwrap_or_default();
        saved.sort();
        let sv: Vec<&str> = servable.iter().map(String::as_str).collect();
        let sa: Vec<&str> = saved.iter().map(String::as_str).collect();
        eprintln!(
            "swapdex: {}",
            unknown_account_or_unservable(name, &sv, &sa, tool)
        );
        return Ok(5);
    };
    // Handing turns to an account with no login does not fail loudly: the proxy
    // steps aside and forwards the client's OWN credential, so the turn works
    // and somebody else pays for it while every screen names this account. Refuse
    // the state rather than report it after the fact.
    if !crate::proxy::has_login(paths, tool, &rec.config_dir) {
        eprintln!(
            "swapdex: '{name}' has no {bin} login, so it cannot pay for turns - your own account would, while every screen named '{name}'"
        );
        eprintln!(
            "  sign it in first: `swapdex run {name}{}`",
            tool_flag(tool)
        );
        return Ok(6);
    }
    // Changing the payer is a store-global write, so take the store lock the way
    // every other writer of that record does. The timeline is read-modify-written
    // whole: a writer that skips the lock drops the event of one that took it.
    // `use` and `restore` take it, and `login` retries for it rather than write
    // the timeline unlocked.
    let store = Store::open(paths)?;
    let _lock = match store_lock_or_exit(&store) {
        Ok(g) => g,
        Err(code) => return Ok(code),
    };
    slots.set_serving(name)?;
    // Record WHO PAYS from here on. Only `use` and `restore` were written, so the
    // action that changes the payer left no trace - and Codex usage, which comes
    // out of a transcript written in whichever home was running, has no other way
    // to know whose token produced those numbers. Raise a failure here the way the
    // pointer write above does: a payer that changed with no record is the state
    // this event exists to prevent.
    store.append_timeline(tool, name, crate::session_link::SERVE)?;
    // Start the proxy this needs. Directing turns with nothing to carry them is
    // a setting that quietly does nothing, and telling someone to run a second
    // command to make the first one take effect is the same as not doing it.
    // Starting one is a convenience, and the proxy is DETACHED so it outlives
    // the shell that asked. Under a sandboxed root that daemon outlives the
    // temporary store itself and keeps the port, answering for a directory that
    // is deleted moments later - one was found still bound hours after. An
    // explicit `swapdex proxy` there is still honoured; this implicit one is not.
    if !paths.sandboxed() && crate::proxy::running_proxy_for(paths, tool).is_none() {
        let _ = proxy_ensure(paths, DEFAULT_PROXY_PORT, tool);
    }
    let live = crate::proxy::running_proxy_for(paths, tool).is_some();
    // Confirm the switch here rather than making the user run `ls` to see
    // whether it took and `usage` to see whether that account has room. What is
    // unknown stays unsaid - a window nobody has read gets no percentage.
    {
        let email = crate::slots::Slots::open_for(paths, tool)
            .ok()
            .and_then(|sl| sl.get(name).map(|r| r.config_dir.clone()))
            .and_then(|d| crate::proxy::creds::slot_email(&d));
        let left = crate::quota_cache::load_for(paths, tool)
            .get(name)
            .and_then(|e| e.seven_d)
            .map(|used| (100.0 - used).clamp(0.0, 100.0));
        println!("{}", switch_line(name, email.as_deref(), left));
    }
    if live {
        println!("  the session you have open moves from its next turn");
        if tool == "codex" {
            println!("  check the paying account with `swapdex serve --tool codex --quiet`");
        }
    } else {
        println!(
            "  but nothing is carrying them yet - `swapdex proxy{}` in another terminal",
            if tool == "codex" { " --tool codex" } else { "" }
        );
    }
    println!(
        "  your conversations stay where they are - this changed who pays, not where you work"
    );
    Ok(0)
}

/// A Codex row's identity label, and a warning when the two answers disagree.
///
/// Two things claim to name the account. The usage endpoint says whose token
/// the server just accepted; the home's saved `id_token` says whose the home
/// believes it is. They are normally the same, and when they are not, the live
/// answer is the true one and the disagreement is worth saying out loud: that
/// gap is the shape of the identity mix-up where signing in as one account
/// leaves another connected.
///
/// With no live answer the saved label stands unqualified. It is all there is,
/// and marking it suspect would be inventing a doubt rather than reporting one.
pub fn codex_identity(
    live_email: Option<&str>,
    live_plan: Option<&str>,
    saved_email: Option<&str>,
) -> String {
    fn clean(s: Option<&str>) -> Option<&str> {
        s.map(str::trim).filter(|s| !s.is_empty())
    }
    let (live, saved) = (clean(live_email), clean(saved_email));
    let mut out = identity_column(
        live.or(saved).map(str::to_string),
        clean(live_plan).map(str::to_string),
    );
    // Said in the identity column rather than the status word: a home that
    // disagrees with the server about whose it is still serves turns perfectly
    // well, so this is not a reason to call the account unusable. It is a
    // reason to doubt the NAME, and it belongs where the name is.
    if let (Some(l), Some(s)) = (live, saved) {
        if !l.eq_ignore_ascii_case(s) {
            out.push_str(&format!(" (saved as {s})"));
        }
    }
    out
}

/// One Codex account's row, from whichever source could answer.
///
/// Three can, and they fail in different places, which is why all three exist:
///
/// - The account itself, asked directly. Answers per CREDENTIAL, names itself,
///   and is the only one that answers for a home holding no transcripts - the
///   case where there is nothing local to read and the row was a permanent
///   blank. Needs the network and can be throttled.
/// - What the proxy read off a response it was already carrying. Free, and
///   bound to the account that served the turn. Only exists once that account
///   has served something.
/// - The home's transcripts. Free and always there, but bound to the home
///   rather than to a credential, and often hours old.
///
/// The live answer wins, being taken just now. Between the two local ones the
/// NEWER answers rather than a fixed rank: both are honest, and the stale one
/// is simply older. No source at all means no row - shown at zero, an account
/// nobody has measured reads as a full one.
pub fn codex_row(
    home: &str,
    live: Option<&crate::codex_usage::Account>,
    saved_email: Option<&str>,
    seen_by_proxy: Option<crate::quota_cache::Entry>,
    transcript: Option<crate::codex_limits::Limits>,
    now: i64,
) -> Option<(String, crate::tui::Usage)> {
    if let Some(a) = live {
        let mut l = a.limits;
        l.observed_at = Some(now);
        let (name, mut u) = codex_usage_row(home, &l);
        // Why it is refusing, in the account's own words. Beside a window with
        // room left, "out of quota" and "the workspace spend limit is reached"
        // send you to entirely different places.
        u.note = a.refused.as_deref().map(crate::codex_usage::refusal_words);
        // Credits carry an account past a full window, so a window at 100% is
        // not the end of it - unless the cap on those credits is reached too,
        // which is a way through that is closed.
        u.on_credits = a
            .credits
            .as_ref()
            .is_some_and(|c| (c.has_credits || c.unlimited) && !c.overage_limit_reached);
        u.ident = Some(codex_identity(
            a.email.as_deref(),
            a.plan.as_deref(),
            saved_email,
        ));
        return Some((name, u));
    }
    let from_transcript = transcript.map(|l| codex_usage_row(home, &l));
    let from_proxy = seen_by_proxy.map(|e| {
        (
            home.to_string(),
            crate::tui::Usage {
                five_h: e.five_h,
                five_h_reset: e.five_h_reset,
                seven_d: e.seven_d,
                seven_d_reset: e.seven_d_reset,
                observed_at: Some(e.at),
                on_credits: e.on_credits,
                // What the account said would clear it, when it said. A row
                // that can report a refusal and not its remedy sends the
                // reader looking in the wrong place.
                note: e.refused,
                ..Default::default()
            },
        )
    });
    match (from_proxy, from_transcript) {
        (Some(p), Some(t)) => Some(if p.1.observed_at >= t.1.observed_at {
            p
        } else {
            t
        }),
        (p, t) => p.or(t),
    }
}

/// One Codex account's row: the reading, under the name of the home it came from.
///
/// The name is the ONLY thing this can be keyed by, and taking it as the sole
/// argument is the point - a caller cannot substitute a different account for it.
/// An earlier version looked up whoever the switch timeline said was paying when
/// the reading was written, which moved real numbers onto an account that had no
/// transcripts at all.
/// Stored Codex accounts the slot registry does not cover.
///
/// The dashboard built its Codex rows by walking slots, so an account living
/// only as a saved snapshot was never asked about and its windows stayed empty.
/// `swapdex quota` reads that case through `snapshot_codex_auth` and prints real
/// numbers, so the two commands disagreed about the same account - and the one
/// people look at was the one saying nothing.
/// Write a Codex reading where the next dashboard open can find it instantly.
///
/// Claude's numbers come from the quota cache and fill the row the moment the
/// dashboard draws. Codex's were read live on every open and never written down,
/// so every open sat on "checking…" for as long as the network took - and if the
/// read failed, the row had nothing at all to show. Only the proxy wrote this
/// cache, and there is no Codex proxy on most machines.
fn remember_codex_reading(paths: &Paths, name: &str, u: &crate::tui::Usage) {
    if u.five_h.is_none() && u.seven_d.is_none() {
        return; // nothing read is not a reading
    }
    let entry = crate::quota_cache::Entry {
        five_h: u.five_h,
        five_h_reset: u.five_h_reset,
        seven_d: u.seven_d,
        seven_d_reset: u.seven_d_reset,
        at: u.observed_at.unwrap_or(now_secs() as i64),
        on_credits: u.on_credits,
        refused: None,
        // A reading arrived, so the token works.
        token_rejected_at: None,
    };
    crate::quota_cache::update_for(paths, "codex", &[(name.to_string(), entry)]);
}

/// The tool name Claude Code is registered under.
pub const CLAUDE_TOOL: &str = "claude-code";
/// The tool name Codex is registered under.
pub const CODEX_TOOL: &str = "codex";

/// Which tools' caches the dashboard's first frame reads.
///
/// It called `quota_cache::load`, which is hardcoded to Claude, so a remembered
/// reading for any other tool was written and never read back - those rows sat
/// empty until a live network read returned, and that wait is the delay. Making
/// the "checking" note go away made it quieter, not shorter.
pub fn cached_quota_tools() -> [&'static str; 2] {
    [CLAUDE_TOOL, CODEX_TOOL]
}

/// Read several Codex accounts concurrently, started one pace apart.
///
/// The reads were sequential, so the dashboard's numbers arrived after the SUM
/// of every account's round trip - which is the "usage shows up late" report.
/// Starting them all at once would be a burst, the thing `pace_between_accounts`
/// exists to prevent and the cause of the throttled, blank gauges this file
/// keeps having to fix. So they are staggered by that same gap and run
/// concurrently from there: wall clock becomes the slowest single read plus the
/// stagger, instead of the total.
fn fetch_codex_live(
    items: Vec<(String, std::path::PathBuf)>,
) -> Vec<(String, Option<crate::codex_usage::Account>, bool)> {
    let handles: Vec<_> = items
        .into_iter()
        .enumerate()
        .map(|(i, (name, dir))| {
            std::thread::spawn(move || {
                if i > 0 {
                    std::thread::sleep(std::time::Duration::from_millis(
                        crate::quota::pace_ms() * i as u64,
                    ));
                }
                // Three outcomes, not two. A throttled or unreadable reply says
                // nothing about the account, so the remembered reading still
                // stands; a REJECTED token is a fact about the account, and
                // letting the remembered reading stand there shows a dead
                // account as a fresh one.
                let mut live = None;
                let mut refused = false;
                if let Some(auth) = crate::proxy::codex::slot_auth(&dir) {
                    let f = crate::codex_usage::fetch(&auth);
                    match crate::codex_usage::outcome_of(&f) {
                        crate::codex_usage::LiveOutcome::Reading => {
                            if let crate::codex_usage::Fetch::Ok(a) = f {
                                live = Some(*a);
                            }
                        }
                        crate::codex_usage::LiveOutcome::Refused => refused = true,
                        crate::codex_usage::LiveOutcome::KeepRemembered => {}
                    }
                }
                (name, live, refused)
            })
        })
        .collect();
    handles.into_iter().filter_map(|h| h.join().ok()).collect()
}

pub fn codex_names_without_a_slot(store: &[String], slots: &[String]) -> Vec<String> {
    store
        .iter()
        .filter(|n| !slots.contains(n))
        .cloned()
        .collect()
}

pub fn codex_usage_row(home: &str, l: &crate::codex_limits::Limits) -> (String, crate::tui::Usage) {
    let p = crate::codex_limits::place(l);
    let u = crate::tui::Usage {
        observed_at: l.observed_at,
        five_h: p.five_h.map(|w| w.used_pct),
        five_h_reset: p.five_h.and_then(|w| w.resets_at),
        seven_d: p.seven_d.map(|w| w.used_pct),
        seven_d_reset: p.seven_d.and_then(|w| w.resets_at),
        ..Default::default()
    };
    (home.to_string(), u)
}

/// Does this row have to say "no login"?
///
/// One place, because there were two and they disagreed. The slot rows asked
/// `has_login`, which knows a Keychain that will not open is not an account
/// nobody signed into; the profile rows asked `slot_token`, the wrapper that
/// throws that distinction away. A profile and a slot sharing a name leaves only
/// the profile row, so on a real machine `rnd` said "no login" beside its own
/// live usage figures.
///
/// A row with no slot behind it has nothing to sign into and never asks.
pub fn row_needs_login(paths: &Paths, tool: &str, dir: Option<&std::path::Path>) -> bool {
    dir.is_some_and(|d| !crate::proxy::has_login(paths, tool, d))
}

/// `swapdex export [file]` - this machine's account setup, without a single
/// secret in it.
pub fn export(paths: &Paths, out: Option<&std::path::Path>) -> Result<i32> {
    use anyhow::Context;
    let portable = crate::portable::export(paths);
    if !portable.unreadable.is_empty() {
        eprintln!(
            "swapdex: the account registry could not be read ({}) - this export is \
             INCOMPLETE and does not list every account.",
            portable.unreadable.join(", ")
        );
    }
    let text = serde_json::to_string_pretty(&portable)?;
    match out {
        Some(p) => {
            std::fs::write(p, format!("{text}\n"))
                .with_context(|| format!("write {}", p.display()))?;
            println!(
                "wrote {} - names and settings only; every account still signs in on its own machine",
                crate::util::redact_path(&p.display().to_string())
            );
        }
        None => println!("{text}"),
    }
    Ok(0)
}

/// `swapdex import <file>` - re-create that setup here.
pub fn import(paths: &Paths, file: &std::path::Path, dry_run: bool) -> Result<i32> {
    use anyhow::Context;
    let bytes = std::fs::read(file).with_context(|| format!("read {}", file.display()))?;
    let incoming: crate::portable::Portable =
        serde_json::from_slice(&bytes).context("that file is not a swapdex export")?;
    if incoming.version > crate::portable::FORMAT_VERSION {
        eprintln!(
            "swapdex: that export was written by a newer swapdex (format {}) - upgrade first",
            incoming.version
        );
        return Ok(2);
    }
    // Imported metadata cannot improve an account that is already local: it
    // carries no login. Include snapshots here too, or re-importing an export
    // builds an empty slot over the account whose local copy should win.
    let store = Store::open(paths)?;
    let here: Vec<(String, String)> = merged_accounts(paths, &store)
        .0
        .into_iter()
        .flat_map(|p| p.tools.into_iter().map(move |tool| (p.name.clone(), tool)))
        .collect();
    let settings = incoming.settings.clone();
    let todo = crate::portable::plan(&here, &incoming);
    if todo.is_empty() {
        println!("every account in that file is already here");
    }
    let mut unknown_tools: Vec<&str> = Vec::new();
    for a in &todo {
        // The tool name goes straight to the slot store, which does not check
        // it, and the display falls back to Claude for anything it does not
        // recognise - so a manifest naming a tool this build has never heard of
        // produced a slot that can never serve, announced as a Claude account.
        // swapdex ships four adapters and is built to grow; a file from a newer
        // build is the ordinary case, and FORMAT_VERSION cannot catch it because
        // adding an adapter is not a format change.
        if crate::adapters::by_name(&a.tool).is_none() {
            eprintln!(
                "swapdex: skipped '{}': this build does not know the tool '{}' - \
                 upgrade swapdex and import again",
                a.name, a.tool
            );
            unknown_tools.push(&a.tool);
            continue;
        }
        if dry_run {
            println!("would create {} ({})", a.name, tool_binary(&a.tool));
            continue;
        }
        match crate::slots::Slots::open_for_update(paths, &a.tool)
            .and_then(|mut s| s.create(&a.name))
        {
            Ok(rec) => {
                crate::slots::link_shared_config(
                    &rec.config_dir,
                    &shared_source(paths, &a.tool),
                    &a.tool,
                );
                println!("created {} ({})", a.name, tool_binary(&a.tool));
            }
            Err(e) => eprintln!("swapdex: could not create '{}': {e}", a.name),
        }
    }
    if let Some(s) = settings {
        if !dry_run {
            crate::settings::save(paths, &s)?;
            println!("settings applied");
        }
    }
    if !todo.is_empty() && !dry_run {
        // The plan knows each account's tool, and `run` defaults to Claude, so
        // a bare `<name>` placeholder pointed every imported Codex account at
        // the wrong one. Print what to actually type.
        println!("  each one still needs its own sign-in:");
        for a in &todo {
            println!("    swapdex run {}{}", a.name, tool_flag(&a.tool));
        }
    }
    if !unknown_tools.is_empty() {
        // Non-zero so a script does not read a partial import as a clean one.
        return Ok(2);
    }
    Ok(0)
}

/// `swapdex fallback-model [<model>|off]` - what to ask for when every account
/// is past the threshold and there is nowhere left to rotate.
pub fn fallback_model(paths: &Paths, value: Option<&str>) -> Result<i32> {
    let cfg = crate::settings::load(paths);
    let Some(value) = value else {
        match cfg.fallback_model.as_deref() {
            Some(m) => {
                println!("{m}");
                println!("  asked for only when every account is past the threshold");
            }
            None => println!(
                "off - a turn with nowhere left to go gets the refusal, not a different model"
            ),
        }
        return Ok(0);
    };
    if value.eq_ignore_ascii_case("off") || value.is_empty() {
        crate::settings::update(paths, |c| c.fallback_model = None)?;
        println!("fallback model off");
        return Ok(0);
    }

    crate::settings::update(paths, |c| c.fallback_model = Some(value.to_string()))?;
    println!("fallback model: {value}");
    println!("  used ONLY when every account is past the threshold - rotating to an account");
    println!("  with room comes first, because that gives you the model you asked for");
    Ok(0)
}

/// `swapdex strategy [roomiest|consume-first]` - which account auto-continue
/// reaches for when the current one is full.
pub fn strategy(paths: &Paths, value: Option<&str>) -> Result<i32> {
    let cfg = crate::settings::load(paths);
    let Some(value) = value else {
        let s = cfg.strategy();
        println!("{}", s.as_str());
        println!(
            "{}",
            match s {
                crate::proxy::pick::Strategy::Roomiest =>
                    "  reaches for the account with the most left - the largest buffer for a burst",
                crate::proxy::pick::Strategy::ConsumeFirst =>
                    "  reaches for the window about to reset, so quota does not lapse unused",
            }
        );
        return Ok(0);
    };
    let Some(parsed) = crate::proxy::pick::Strategy::parse(value) else {
        eprintln!("swapdex: unknown strategy '{value}' - use `roomiest` or `consume-first`");
        return Ok(2);
    };

    crate::settings::update(paths, |c| {
        c.proxy_strategy = Some(parsed.as_str().to_string())
    })?;
    println!("strategy: {}", parsed.as_str());
    // Read per request, so a proxy already running follows without a restart.
    println!("  a running proxy follows this from its next turn");
    Ok(0)
}

/// `swapdex service install` - hand the proxy to launchd or systemd.
///
/// Two things this fixes, both learned the hard way. A proxy started by the shim
/// dies with the shell that started it, so killing a terminal quietly removes it;
/// and one started over ssh on macOS cannot open the Keychain, so it answers
/// every turn with the client's own login and never says so. An agent runs in the
/// user's own login session, has that access, and is restarted when it stops.
/// What to say after installing the service, once it is known whether it came up.
///
/// The install used to announce "it starts at login, comes back if it stops"
/// without checking that it had. On a Mac whose launchd context cannot open the
/// Keychain the proxy refuses to run - deliberately, because it would forward
/// the user's own login and never say so - so the unit failed every start while
/// swapdex called it installed. The only working proxy on that machine was one
/// started by hand, which is also why it never picked up an upgrade.
fn install_verdict(came_up: bool, tool: &str) -> (bool, String) {
    if came_up {
        return (true, "installed and running".to_string());
    }
    (
        false,
        format!(
            "the unit is written but the proxy did not start. On macOS this is \
             usually the Keychain: a service started by launchd cannot open it, \
             and swapdex refuses to run a proxy that would forward your own login \
             without saying so. Start it from a terminal on this machine instead: \
             `swapdex proxy --ensure --tool {tool}`, then `swapdex shim`"
        ),
    )
}

pub fn service_install(paths: &Paths, sel: Option<ToolSel>) -> Result<i32> {
    let tool = slot_tool(sel);
    // The unit runs `proxy --tool <tool>`. Installing one for a tool the proxy
    // cannot carry put a Claude proxy on that tool's port, under the supervisor,
    // restarted forever by KeepAlive.
    if !crate::proxy::carries(tool) {
        eprintln!("{}", crate::proxy::cannot_carry(tool));
        return Ok(2);
    }
    let path = crate::service::install(paths, tool)?;
    println!(
        "the {} proxy is now a service: {}",
        tool_binary(tool),
        crate::util::redact_path(&path.display().to_string())
    );
    println!(
        "  it writes what it says to {}",
        crate::util::redact_path(&crate::service::log_dir(paths).display().to_string())
    );
    // Wait for it to actually come up. Announcing that it "starts at login and
    // comes back if it stops" without looking is how a machine ends up with a
    // unit that has failed every start since the day it was installed.
    let mut came_up = false;
    for _ in 0..10 {
        if crate::proxy::running_proxy_for(paths, tool).is_some() {
            came_up = true;
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(400));
    }
    let (ok, msg) = install_verdict(came_up, tool);
    if ok {
        println!("  {msg}");
        Ok(0)
    } else {
        eprintln!("swapdex: {msg}");
        Ok(2)
    }
}

/// `swapdex service uninstall` - stop it and take the unit away.
pub fn service_uninstall(paths: &Paths, sel: Option<ToolSel>) -> Result<i32> {
    let tool = slot_tool(sel);
    match crate::service::uninstall(paths, tool)? {
        Some(p) => println!(
            "removed {}",
            crate::util::redact_path(&p.display().to_string())
        ),
        None => println!("no {} service was installed", tool_binary(tool)),
    }
    Ok(0)
}

/// `swapdex service status` - what is installed, and whether it is up.
pub fn service_status(paths: &Paths) -> Result<i32> {
    // All four, not the two that were listed here. `install` now refuses a tool
    // the proxy cannot carry, but a machine that installed one BEFORE that
    // refusal still has the unit, and a supervised proxy nothing reports on is
    // exactly the one nobody removes. The unit's location comes from `paths` so
    // a sandboxed run reports on the sandbox rather than on the machine.
    for tool in ["claude-code", "codex", "gemini", "antigravity"] {
        let path = crate::service::unit_path(paths, tool);
        let installed = path.exists();
        let running = crate::proxy::running_proxy_for(paths, tool).is_some();
        // A proxy that keeps dying and being restarted reads as "running" on
        // the instant this runs, which is how a crash every hour stayed
        // invisible. Ask the supervisor what it has been watching.
        let note = if installed {
            let (restarts, last_exit, uptime) = crate::service::supervisor_report(tool);
            crate::service::supervision_note(restarts, last_exit, uptime)
        } else {
            None
        };
        println!(
            "{:<12} service: {:<13} proxy: {}{}",
            tool_binary(tool),
            if installed {
                "installed"
            } else {
                "not installed"
            },
            if running { "running" } else { "not running" },
            note.map(|n| format!("  - {n}")).unwrap_or_default()
        );
    }
    println!(
        "  logs: {}",
        crate::util::redact_path(&crate::service::log_dir(paths).display().to_string())
    );
    Ok(0)
}

/// `swapdex refresh --keep-alive` - renew every idle account heading for expiry.
///
/// The same sweep the proxy runs on a timer, exposed so it can be run by hand or
/// from cron on a machine where the proxy is not always up. An account nobody
/// touches is the one that dies: its refresh token goes stale unused, and then
/// only a browser sign-in brings it back.
pub fn keep_alive(paths: &Paths) -> Result<i32> {
    let listed = |tool: &str| -> Vec<(String, std::path::PathBuf)> {
        crate::slots::Slots::open_for(paths, tool)
            .map(|s| {
                s.list()
                    .into_iter()
                    .map(|r| (r.name, r.config_dir))
                    .collect()
            })
            .unwrap_or_default()
    };
    let slots = listed("claude-code");
    // Codex was the tool this sweep was most needed for and the one it skipped:
    // its token lives ten days and only a Codex RUN renews it, so an account
    // nobody opens dies on a schedule with nothing watching.
    let codex = listed("codex");
    if slots.is_empty() && codex.is_empty() {
        println!("no accounts to keep alive");
        return Ok(0);
    }
    let now = now_ms();
    let mut claude = crate::refresh::keep_alive_sweep_report(paths, &slots, now);
    let codex = crate::refresh::keep_alive_sweep_codex_report(paths, &codex, now);
    claude.renewed.extend(codex.renewed);
    let native_managed: Vec<(String, &str)> = claude
        .native_managed
        .into_iter()
        .map(|name| (name, "Claude"))
        .chain(codex.native_managed.into_iter().map(|name| (name, "Codex")))
        .collect();
    // Which sweep produced a failure is the last place the tool is known;
    // merging the two lists first threw it away, and the remedy names `run`.
    let deferred: Vec<(String, &str)> = claude
        .deferred
        .into_iter()
        .map(|name| (name, "claude-code"))
        .chain(codex.deferred.into_iter().map(|name| (name, "codex")))
        .collect();
    let failed: Vec<(String, &str, crate::refresh::RefreshError)> = claude
        .failed
        .into_iter()
        .map(|(n, e)| (n, "claude-code", e))
        .chain(codex.failed.into_iter().map(|(n, e)| (n, "codex", e)))
        .collect();
    for name in &claude.renewed {
        println!("renewed {name}");
    }
    for (name, tool) in &native_managed {
        println!("{name} uses a live {tool} login; renewal is managed by {tool}");
    }
    for (name, tool) in &deferred {
        println!("{}", crate::refresh::RefreshError::InUse.remedy(name, tool));
    }
    for (name, tool, why) in &failed {
        eprintln!("{}", why.remedy(name, tool));
    }
    if claude.renewed.is_empty()
        && native_managed.is_empty()
        && deferred.is_empty()
        && failed.is_empty()
    {
        println!("no scheduled renewals were needed");
    }
    // A sweep that could not renew something is worth an exit code, so cron can
    // notice; nothing to do is success.
    Ok(i32::from(!failed.is_empty()) * 4)
}

/// `swapdex refresh [name]` - renew a lapsed access token so the account stays
/// usable without signing in again.
///
/// An access token lives about an hour; an account idle longer than that is not
/// broken, it just needs renewing, and only its own refresh token can do it.
pub fn refresh(paths: &Paths, name: Option<&str>) -> Result<i32> {
    let slots = crate::slots::Slots::open_for(paths, "claude-code")?;
    let list: Vec<_> = match name {
        Some(n) => slots.get(n).into_iter().collect(),
        None => slots.list(),
    };
    let codex = crate::slots::Slots::open_for(paths, "codex").ok();
    let codex_list: Vec<_> = match (&codex, name) {
        (Some(c), Some(n)) => c.get(n).into_iter().collect(),
        (Some(c), None) => c.list(),
        (None, _) => Vec::new(),
    };
    // A named account is unknown only when NEITHER tool has it. Asking Claude
    // alone meant `refresh <a codex account>` reported the name as unknown and
    // returned before the Codex half ever ran.
    if name.is_some() && list.is_empty() && codex_list.is_empty() {
        let mut known: Vec<String> = slots.list().into_iter().map(|r| r.name).collect();
        known.extend(codex.iter().flat_map(|c| c.list()).map(|r| r.name));
        let refs: Vec<&str> = known.iter().map(String::as_str).collect();
        eprintln!("swapdex: {}", unknown_account(name.unwrap_or(""), &refs));
        return Ok(5);
    }
    let now = now_ms();
    let mut renewed = 0;
    let mut failed = 0;
    if list.is_empty() && codex_list.is_empty() {
        println!("No accounts to renew.");
    }
    // One renewal per ACCOUNT, not per directory - see `already_renewed`.
    let mut done: Vec<String> = Vec::new();
    for r in &list {
        if !crate::proxy::has_login(paths, "claude-code", &r.config_dir) {
            println!(
                "  {}",
                crate::refresh::RefreshError::NoCredential.remedy(&r.name, "claude-code")
            );
            failed += 1;
            continue;
        }
        if !crate::proxy::creds::slot_token_expired_for(paths, &r.config_dir, now) {
            println!("  {} is already current", r.name);
            continue;
        }
        let account = slot_account_of(&r.config_dir, "claude-code");
        if let Some(note) = already_renewed(&account, &done, &r.name) {
            println!("  {note}");
            continue;
        }
        match crate::refresh::refresh_slot(paths, &r.config_dir, now) {
            Ok(crate::refresh::RefreshOutcome::Renewed) => {
                println!("  {} renewed", r.name);
                if let Some(a) = account {
                    done.push(a);
                }
                renewed += 1;
            }
            Ok(crate::refresh::RefreshOutcome::NativeManaged) => {
                println!(
                    "  {} uses its live Claude login; renewal is managed by Claude",
                    r.name
                );
            }
            Err(why) => {
                println!("  {}", why.remedy(&r.name, "claude-code"));
                failed += 1;
            }
        }
    }
    let (codex_renewed, codex_failed) = refresh_codex(paths, &codex_list, now, &mut done);
    renewed += codex_renewed;
    failed += codex_failed;
    if renewed > 0 {
        println!("\n{renewed} account(s) renewed - no sign-in needed.");
    }
    // Explicit renewal must expose incomplete work to callers even when another
    // account succeeded. A safety deferral also leaves the requested renewal
    // incomplete; the scheduled keep-alive command has its own deferral policy.
    Ok(if failed == 0 { 0 } else { 4 })
}

/// The Codex half of `swapdex refresh`.
///
/// This command opened the claude-code slot list only, so a Codex login could
/// not be renewed by any means swapdex offered. Codex renews its own token when
/// Codex RUNS, which is fine for a slot in daily use and useless for one that
/// is not: measured across two machines, a slot dies exactly ten days after its
/// last run, and four of eight were already dead when this was written.
fn refresh_codex(
    paths: &Paths,
    list: &[crate::slots::SlotRecord],
    now: i64,
    done: &mut Vec<String>,
) -> (usize, usize) {
    let mut renewed = 0;
    let mut failed = 0;
    for r in list {
        if !crate::proxy::has_login(paths, "codex", &r.config_dir) {
            println!(
                "  {}",
                crate::refresh::RefreshError::NoCredential.remedy(&r.name, "codex")
            );
            failed += 1;
            continue;
        }
        if !crate::proxy::codex::slot_token_expired(&r.config_dir, now / 1000) {
            println!("  {} is already current", r.name);
            continue;
        }
        let auth = std::fs::read(r.config_dir.join("auth.json")).ok();
        let account = auth
            .as_deref()
            .and_then(|bytes| crate::refresh::credential_identity(bytes, "codex"));
        let token_identity = auth
            .as_deref()
            .and_then(|bytes| crate::refresh::refresh_token_identity(bytes, "codex"));
        if let Some(note) = already_renewed(&account, done, &r.name)
            .or_else(|| already_renewed(&token_identity, done, &r.name))
        {
            println!("  {note}");
            continue;
        }
        match crate::refresh::refresh_codex_slot(paths, &r.config_dir, now) {
            Ok(crate::refresh::RefreshOutcome::Renewed) => {
                println!("  {} renewed", r.name);
                if let Some(a) = account {
                    done.push(a);
                }
                if let Some(identity) = token_identity {
                    done.push(identity);
                }
                renewed += 1;
            }
            Ok(crate::refresh::RefreshOutcome::NativeManaged) => {
                println!(
                    "  {} uses its live Codex login; renewal is managed by Codex",
                    r.name
                );
            }
            Err(why) => {
                println!("  {}", why.remedy(&r.name, "codex"));
                failed += 1;
            }
        }
    }
    (renewed, failed)
}

/// The selected tool's account identity, namespaced by provider. A directory
/// may contain another tool's metadata, and provider IDs are not globally unique.
fn slot_account_of(dir: &std::path::Path, tool: &str) -> Option<String> {
    let file = match tool {
        "claude-code" => ".claude.json",
        "codex" => "auth.json",
        _ => return None,
    };
    crate::refresh::credential_identity(&std::fs::read(dir.join(file)).ok()?, tool)
}

/// Why this slot must be left alone, when its account was already renewed.
///
/// These refresh tokens are single-use: renewing one holder retires the copy
/// every other holder carries. Two directories for one login are a thing people
/// keep, and `doctor` reports them, so a renewal loop walks straight into
/// spending the retired copy - the double-spend this command's own remedy for
/// a concurrent renewal calls "what logs an account out". Same rule, and it was
/// enforced per directory instead of per account.
///
/// An unreadable identity is never grouped: two unknowns are not one account.
fn already_renewed(account: &Option<String>, done: &[String], name: &str) -> Option<String> {
    let a = account.as_ref()?;
    done.contains(a).then(|| {
        format!(
            "{name} holds the login just renewed - left alone rather than spending \
             the token that renewal retired; `swapdex run {name}` signs this \
             directory in again if you want its own copy current"
        )
    })
}

/// List the permanent slots (name + the config dir each launches into).
pub fn list_slots(paths: &Paths) -> Result<i32> {
    // Both tools, each under its own heading. Listing only Claude's hid half the
    // accounts from the command whose whole job is to show them.
    let mut any = false;
    for tool in crate::adapters::names() {
        let slots = crate::slots::Slots::open_for(paths, tool)?;
        let list = slots.list();
        if list.is_empty() {
            continue;
        }
        let pointer = slots.default_dir();
        println!("{tool}:");
        for r in list {
            // The default is what a plain launch of that tool will use, which is
            // the one thing a list of directories cannot otherwise show.
            let mark = if pointer.as_deref() == Some(r.config_dir.as_path()) {
                "*"
            } else {
                " "
            };
            println!("{mark} {}  {}", r.name, r.config_dir.display());
        }
        if crate::slots::home_var(tool).is_some() {
            if let Ok(store) = Store::open(paths) {
                for profile in classify_migrations(&store, &slots, tool) {
                    if let MigrationClass::CopyOfSlot(slot_name) = profile.class {
                        println!(
                            "  saved profile '{}' is a copy of slot '{}'",
                            profile.name, slot_name
                        );
                    }
                }
            }
        }
        any = true;
    }
    if !any {
        println!("No accounts yet. Run `swapdex onboard` to set them up,");
        println!("  or launch one directly: swapdex run <name>");
        return Ok(0);
    }
    println!("  (* is the account a plain launch uses)");
    Ok(0)
}

pub fn login(paths: &Paths, name: &str, sel: Option<ToolSel>) -> Result<i32> {
    crate::atomic::ensure_not_root()?;
    if let Some(c) = reject_bad_name(name).or_else(|| reject_reserved_name(name)) {
        return Ok(c);
    }
    let tool = match sel {
        Some(ToolSel::Claude) => "claude-code",
        Some(ToolSel::Codex) => "codex",
        Some(ToolSel::Gemini) => "gemini",
        Some(ToolSel::Antigravity) => "antigravity",
        _ => {
            // Never guess which tool the user means (real-use feedback: the
            // old codex-if-installed default kept asking about the wrong
            // tool). On a terminal, ask; otherwise require --tool.
            use std::io::IsTerminal;
            let tty =
                std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
            if !tty {
                eprintln!("swapdex: say which tool: swapdex login {name} --tool <claude|codex|gemini|antigravity>");
                return Ok(2);
            }
            println!("Which tool do you want to log '{name}' into?");
            println!("  1) Claude Code   2) Codex   3) Gemini CLI   4) Antigravity");
            loop {
                match prompt("pick [1-4] (Enter cancels): ", "").as_deref() {
                    Some("1") => break "claude-code",
                    Some("2") => break "codex",
                    Some("3") => break "gemini",
                    Some("4") => break "antigravity",
                    Some("") | None => {
                        println!("cancelled.");
                        return Ok(0);
                    }
                    _ => println!("pick a number between 1 and 4 (Enter cancels)"),
                }
            }
        }
    };

    // One flow for all four tools from here on.
    let bin = match tool {
        "claude-code" => "claude",
        "codex" => "codex",
        "gemini" => "gemini",
        _ => "agy",
    };
    if !command_exists(bin) {
        // stderr + exit 3: `login x && ...` in a script must not proceed as
        // if a login was saved.
        eprintln!("swapdex: `{bin}` isn't on your PATH. Install it, then retry.");
        return Ok(3);
    }
    let adapter = adapters::by_name(tool).expect("known tool");
    let flag = pretty_tool_flag(tool);

    let Some(cur) = adapter.identity(paths).ok().flatten() else {
        // Not logged in at all: run the tool's own sign-in, then capture.
        // (codex has a real `login` subcommand; the others sign in on first
        // run of the app itself.)
        println!(
            "Opening {} to sign in. Complete the login{}",
            pretty_tool(tool),
            if tool == "codex" {
                " in your browser.".to_string()
            } else {
                ", then exit it.".to_string()
            }
        );
        spawn_tool_login(paths, bin, tool)?;
        if adapter.identity(paths).ok().flatten().is_none() {
            eprintln!(
                "swapdex: no {} login was completed - nothing saved.",
                pretty_tool(tool)
            );
            return Ok(8);
        }
        println!();
        // update=true so re-running `login <name>` refreshes an existing profile.
        return add(paths, Some(name), sel_for_tool(tool), true);
    };

    // Already logged in - the user wants to ADD a different account. Do the
    // whole thing: save the current login, sign out locally, run the tool's
    // sign-in, capture the new account. The original login is stashed in the
    // store and restored on any failure, so this can never lose an account.
    use std::io::IsTerminal;
    let tty = std::io::stdin().is_terminal() || std::env::var_os("SWAPDEX_ASSUME_TTY").is_some();
    if !tty {
        // Scripts get guidance - this flow is interactive.
        println!(
            "You're already logged into {} ({}).",
            pretty_tool(tool),
            identity_line(&cur)
        );
        println!("  save the current account:  swapdex add {name} --tool {flag}");
        println!(
            "  add a DIFFERENT account:   swapdex login {name} --tool {flag}  (on a terminal)"
        );
        // Exit 3, not 0: `login x && use x` in a script must not proceed as
        // if a login was saved (nothing was).
        return Ok(3);
    }
    println!("Currently logged in as {}.", identity_line(&cur));
    if !yes_no(
        &format!(
            "Sign in to a DIFFERENT account as '{name}'? swapdex will save the \
             current login, sign you out locally, and open {} for the \
             new sign-in. [Y/n]: ",
            pretty_tool(tool)
        ),
        true,
    ) {
        println!("cancelled - nothing changed.");
        return Ok(0);
    }
    let store = Store::open(paths)?;
    let lock1 = match store.lock() {
        Ok(g) => g,
        Err(crate::store::LockError::Busy) => {
            eprintln!(
                "swapdex: another swapdex is busy (a switch, or a `swapdex login` waiting \
                 for a sign-in). Finish or close it, then retry."
            );
            return Ok(4);
        }
        Err(crate::store::LockError::Unwritable(e)) => {
            eprintln!(
                "swapdex: the store is not writable ({e}) - check permissions/mount of \
                 the store directory"
            );
            return Ok(4);
        }
    };
    // Take the per-tool credential lock and HOLD it across the whole flow -
    // including the interactive sign-in, during which the store lock (lock1) is
    // released so unrelated ops proceed. This is what stops a concurrent
    // `swapdex use` on THIS tool from interleaving with our sign-out/sign-in and
    // pairing the wrong token with the new account. Held to end of function.
    let _tool_lock = match store.lock_tool(tool) {
        Ok(g) => g,
        Err(_) => {
            eprintln!(
                "swapdex: another swapdex is signing {tool} in/out right now. \
                 Finish or close it, then retry."
            );
            return Ok(4);
        }
    };
    // 1) The current login, saved twice over: a store backup (restore can
    //    always bring it back) plus a refresh of every profile holding it -
    //    and, if unmatched, an offer to keep it under a name.
    let stash = adapter.capture(paths)?;
    store.backup(&stash)?;
    for pname in matching_profile_names(&store, tool, &cur.account_id) {
        store.save(&pname, &stash)?;
    }
    if matched_profile_name(&store, tool, &cur.account_id).is_none() {
        // No email on disk (antigravity): suggest a plain name instead of a
        // sanitized display string like "GoogleaccountAntigravity".
        let suggestion = match &cur.email {
            Some(e) => suggest_name(e),
            None => "main".to_string(),
        };
        while let Some(keep) = ask_name(
            &store,
            &format!("name to keep the CURRENT account under [{suggestion}]: "),
            &suggestion,
            Some(NameHolder {
                paths,
                tool,
                account_id: &cur.account_id,
            }),
        ) {
            if keep == name {
                // '{name}' is reserved for the NEW account - accepting it here
                // would let the new sign-in silently overwrite the current one.
                println!("'{name}' is the name for the NEW account - pick another.");
                continue;
            }
            store.save(&keep, &stash)?;
            println!("saved current login as '{keep}'.");
            break;
        }
    }
    // 2) Local sign-out, so the tool's own flow prompts a FRESH sign-in.
    sign_out_locally(paths, tool);
    // Verify the sign-out actually took. Two independent checks:
    // - identity: same account still resolvable (e.g. an aliased
    //   CLAUDE_CONFIG_DIR kept .claude.json's oauthAccount alive);
    // - present: a CREDENTIAL still lingers even with the identity gone
    //   (e.g. a second suffixed macOS Keychain item that keychain_delete's
    //   discovery did not target). Proceeding then is worse than the trust
    //   prompt: the eventual capture could pair the OLD token with the NEW
    //   account's identity - a profile that switches to the wrong login.
    // Either way: abort clearly and restore.
    let still_same = adapter
        .identity(paths)
        .ok()
        .flatten()
        .is_some_and(|still| still.account_id == cur.account_id);
    if still_same || adapter.managed_present(paths) {
        adapter.apply(paths, &stash)?;
        drop(lock1);
        eprintln!(
            "swapdex: couldn't sign {} out of the current account ({}), so a new \
             account can't be added this way - your login is unchanged.",
            pretty_tool(tool),
            identity_line(&cur)
        );
        eprintln!("  {}", sign_out_blocked_remedy(still_same, tool));
        // Exit 8 is the documented code for "login was started but the flow did
        // not complete" - nothing was added, and 0 told a script otherwise.
        return Ok(8);
    }
    // RELEASE the store lock before the interactive sign-in: it can take
    // minutes (or be left open), and holding it would block every other
    // swapdex - rename, use, everything - with "another swapdex is
    // mid-switch". The stash is already safe in the store's backups.
    drop(lock1);
    // 3) Fresh sign-in inside the official app.
    println!(
        "Opening {} - sign in with the OTHER account{}",
        pretty_tool(tool),
        if tool == "codex" {
            " in your browser.".to_string()
        } else {
            ", then exit it.".to_string()
        }
    );
    // Proactive warning: the tool may re-use a cached browser session and log
    // you straight back into the SAME account without asking. Tell them how to
    // avoid it BEFORE it happens.
    println!("  tip: {}", same_account_hint(tool));
    let spawn = spawn_tool_login(paths, bin, tool);
    // Re-take the STORE lock for the final store-global writes (timeline,
    // profile save). The per-tool credential lock above already excludes a
    // concurrent switch on THIS tool, so this only serializes with other-tool
    // ops - a bounded retry instead of the old single-shot best-effort that
    // could write the timeline unlocked. No other op holds the store lock for
    // long (only login has an interactive wait, and same-tool login is excluded
    // by the per-tool lock), so this settles in well under the bound; the None
    // fallback only avoids discarding the user's completed sign-in in the rare
    // case it truly can't be taken.
    let mut relock = store.lock().ok();
    for _ in 0..25 {
        if relock.is_some() {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(120));
        relock = store.lock().ok();
    }
    let _lock = relock;
    // 4) Capture, or restore the stash on any failure.
    let new_id = adapter.identity(paths).ok().flatten();
    match (spawn, new_id) {
        (Ok(status), Some(new)) if !new.account_id.is_empty() => {
            if new.account_id == cur.account_id {
                // The tool re-used its browser session and signed BACK INTO
                // the same account - swapdex removed the local login, but it
                // cannot force the tool's OAuth to offer an account picker.
                // Do NOT save a duplicate profile under a new name; explain
                // how to actually reach the other account, and restore the
                // stash so the login is exactly as it was.
                adapter.apply(paths, &stash)?;
                eprintln!(
                    "swapdex: you were signed back into the SAME account ({}), so \
                     nothing was saved as '{name}'.",
                    identity_line(&new)
                );
                eprintln!("  {}", same_account_hint(tool));
                eprintln!(
                    "  (to just save THIS account under a name, use `swapdex add {name} \
                     --tool {}`.)",
                    pretty_tool_flag(tool)
                );
                // 0, not 8: the login flow DID complete, it just landed on the
                // account already saved - the documented no-op case.
                return Ok(0);
            }
            // A slot owns its name as surely as a snapshot does, but saving a
            // snapshot cannot repoint that slot. Letting the fresh sign-in use
            // a name held by another slot would make `ls` describe one account
            // while `use` selects the other, so preserve both under distinct
            // names instead.
            let slot_id = slot_account_under(paths, tool, name);
            if name_means_two_accounts(Some(&new.account_id), slot_id.as_deref()) {
                println!("'{name}' is already a {tool} slot holding a different account.");
                if let Some(rescue) = ask_name(
                    &store,
                    "save the NEW account under a different name instead (Enter discards it): ",
                    "",
                    Some(NameHolder {
                        paths,
                        tool,
                        account_id: &new.account_id,
                    }),
                ) {
                    let snap = adapter.capture(paths)?;
                    store.save(&rescue, &snap)?;
                    println!(
                        "saved profile '{rescue}' ({}). '{name}' is untouched.",
                        identity_line(&new)
                    );
                    println!("switch back any time:  swapdex use <name>  (or `swapdex ui`)");
                    return Ok(0);
                }
                adapter.apply(paths, &stash)?;
                println!(
                    "the new sign-in was DISCARDED and your previous login restored - \
                     '{name}' is untouched. Re-run `swapdex login <other-name>` to \
                     redo it under another name."
                );
                return Ok(0);
            }
            // Same repoint rule as `add --update`: if '{name}' already has a
            // snapshot for this tool, changing what the name means must be
            // explicit. An UNREADABLE snapshot counts as "different" - corrupt
            // and absent must not be conflated, or the guard is bypassable.
            let has_tool_snapshot = store
                .list()
                .iter()
                .any(|p| p.name == name && p.tools.iter().any(|t| t == tool));
            let same_account = profile_account_id(&store, name, tool)
                .filter(|s| !s.is_empty())
                .as_deref()
                == Some(new.account_id.as_str());
            if has_tool_snapshot
                && !same_account
                && !yes_no(
                    &format!(
                        "profile '{name}' already holds a different (or unreadable) \
                         {tool} account. Repoint it to this new login? [y/N]: "
                    ),
                    false,
                )
            {
                // The user completed a REAL sign-in - never discard it
                // silently. Offer a different name; skipping restores the
                // stash and honestly says the new sign-in is gone.
                if let Some(rescue) = ask_name(
                    &store,
                    "save the NEW account under a different name instead (Enter discards it): ",
                    "",
                    Some(NameHolder {
                        paths,
                        tool,
                        account_id: &new.account_id,
                    }),
                ) {
                    if rescue != name {
                        let snap = adapter.capture(paths)?;
                        store.save(&rescue, &snap)?;
                        println!(
                            "saved profile '{rescue}' ({}). '{name}' is untouched.",
                            identity_line(&new)
                        );
                        println!("switch back any time:  swapdex use <name>  (or `swapdex ui`)");
                        return Ok(0);
                    }
                }
                adapter.apply(paths, &stash)?;
                println!(
                    "the new sign-in was DISCARDED and your previous login restored - \
                     '{name}' is untouched. Re-run `swapdex login <other-name>` to \
                     redo it under another name."
                );
                return Ok(0);
            }
            let snap = adapter.capture(paths)?;
            store.save(name, &snap)?;
            println!("saved profile '{name}' ({}).", identity_line(&new));
            if tool == "antigravity" {
                // Honesty over silence: the token file stores no email or
                // account id, so the same-account check above can never fire
                // here and ls cannot show WHO this is.
                println!(
                    "note: Antigravity stores no account identity on disk - swapdex \
                     cannot confirm WHICH Google account this is; verify inside agy."
                );
            }
            if !status.success() {
                println!(
                    "note: {} exited with an error after signing in - if anything \
                     looks off, `swapdex restore --tool {flag}` undoes this.",
                    pretty_tool(tool)
                );
            }
            println!("switch back any time:  swapdex use <name>  (or `swapdex ui`)");
            Ok(0)
        }
        _ => {
            adapter.apply(paths, &stash)?;
            eprintln!(
                "swapdex: no new {} login was completed - your previous \
                 login ({}) was restored.",
                pretty_tool(tool),
                identity_line(&cur)
            );
            Ok(8)
        }
    }
}

/// The ToolSel a canonical tool name maps back to.
fn sel_for_tool(tool: &str) -> Option<ToolSel> {
    match tool {
        "claude-code" => Some(ToolSel::Claude),
        "codex" => Some(ToolSel::Codex),
        "gemini" => Some(ToolSel::Gemini),
        "antigravity" => Some(ToolSel::Antigravity),
        _ => None,
    }
}

/// Run the tool's own sign-in command, terminal inherited. codex has a real
/// `login` subcommand; the other three sign in on first run of the app.
/// Whether `codex login` should get `--device-auth` (the device-code flow):
/// on by DEFAULT, opt out with `SWAPDEX_CODEX_LOGIN=browser`. Codex's default
/// login is a localhost-redirect browser flow, which needs a browser that can
/// reach localhost on the SAME machine - it fails over SSH / on a headless box
/// (swapdex's common remote use). Pure so the policy is unit-tested.
fn codex_device_auth(opt_out_browser: bool) -> bool {
    !opt_out_browser
}

/// Read the opt-out from the environment: `SWAPDEX_CODEX_LOGIN=browser`.
fn codex_login_opts_out_of_device() -> bool {
    std::env::var("SWAPDEX_CODEX_LOGIN").is_ok_and(|v| v.eq_ignore_ascii_case("browser"))
}

fn spawn_tool_login(paths: &Paths, bin: &str, tool: &str) -> Result<std::process::ExitStatus> {
    spawn_tool_login_in(paths, std::path::Path::new(bin), tool, None)
}

/// The same sign-in, optionally in one account's own home.
///
/// The dashboard used to build its own invocation here: a BARE launch of
/// whatever `codex` PATH resolved to. That is our shim, and the shim puts the
/// proxy in front of any Codex run it does not recognise as plain - a bare
/// launch is not recognised. So the sign-in talked to the proxy, which answered
/// with the account it was already serving, and an account with no login of its
/// own came up looking signed in. Two ways to build one command is how that
/// happened, so now there is one.
fn spawn_tool_login_in(
    paths: &Paths,
    bin: &std::path::Path,
    tool: &str,
    home: Option<(&str, &std::path::Path)>,
) -> Result<std::process::ExitStatus> {
    let mut cmd = Command::new(bin);
    if let Some((var, dir)) = home {
        configure_managed_tool_home(&mut cmd, tool, var, dir);
        if tool == "claude-code" {
            crate::claude_authority::resolve_for_authentication(paths, dir)?
                .configure_launch(paths, &mut cmd, true)?;
        }
    }
    // A shell Ctrl+C during the interactive sign-in hits the whole foreground
    // process group. With the default disposition it would kill swapdex before
    // the restore-stash branch runs - leaving the user locally signed out of
    // everything. A no-op HANDLER (not SIG_IGN: handlers reset to default
    // across exec, SIG_IGN would be inherited by the child) makes swapdex
    // ride it out; the child keeps normal Ctrl+C behavior.
    unsafe extern "C" fn ride_out(_: libc::c_int) {}
    #[allow(function_casts_as_integer)]
    let prev_int = unsafe { libc::signal(libc::SIGINT, ride_out as libc::sighandler_t) };
    #[allow(function_casts_as_integer)]
    let prev_quit = unsafe { libc::signal(libc::SIGQUIT, ride_out as libc::sighandler_t) };
    // A sign-in must reach the vendor directly: an inherited proxy address
    // answers with whichever account the proxy already holds.
    for var in ["ANTHROPIC_BASE_URL", "ANTHROPIC_API_KEY"] {
        cmd.env_remove(var);
    }
    match tool {
        // Codex has a `login` subcommand; Claude Code a proper `auth login`
        // that does JUST the OAuth sign-in (no workspace-trust / session
        // detour); Gemini / Antigravity sign in on first run of the app.
        "codex" => {
            cmd.arg("login");
            // Device-code flow by default so login works over SSH / headless
            // (opt out with SWAPDEX_CODEX_LOGIN=browser). A codex old enough to
            // lack the flag can opt out; current codex ships it.
            if codex_device_auth(codex_login_opts_out_of_device()) {
                cmd.arg("--device-auth");
            }
        }
        "claude-code" => {
            cmd.args(["auth", "login"]);
        }
        _ => {}
    }
    let status = cmd.status();
    unsafe {
        libc::signal(libc::SIGINT, prev_int);
        libc::signal(libc::SIGQUIT, prev_quit);
    }
    status.map_err(|e| anyhow::anyhow!("could not run {}: {e}", bin.display()))
}

/// Point a managed child at one account's home. Claude's secure-storage
/// override has higher precedence than CLAUDE_CONFIG_DIR, so inheriting it
/// would send login and renewal writes to another account's Keychain item.
fn configure_managed_tool_home(
    command: &mut Command,
    tool: &str,
    home_var: &str,
    dir: &std::path::Path,
) {
    command.env(home_var, dir);
    if tool == "claude-code" {
        command.env_remove("CLAUDE_SECURESTORAGE_CONFIG_DIR");
    }
}

#[cfg(test)]
mod managed_tool_home_tests {
    use super::configure_managed_tool_home;
    use std::ffi::{OsStr, OsString};
    use std::process::Command;

    fn command_env(command: &Command, key: &str) -> Option<Option<OsString>> {
        command
            .get_envs()
            .find(|(name, _)| *name == OsStr::new(key))
            .map(|(_, value)| value.map(OsStr::to_os_string))
    }

    #[test]
    fn a_managed_claude_login_targets_one_coherent_child_environment() {
        let slot = std::path::Path::new("/tmp/swapdex-managed-claude");
        let mut command = Command::new("claude");
        command.env(
            "CLAUDE_SECURESTORAGE_CONFIG_DIR",
            "/tmp/a-different-claude-login",
        );

        configure_managed_tool_home(&mut command, "claude-code", "CLAUDE_CONFIG_DIR", slot);

        assert_eq!(
            command_env(&command, "CLAUDE_CONFIG_DIR"),
            Some(Some(slot.as_os_str().to_os_string()))
        );
        assert_eq!(
            command_env(&command, "CLAUDE_SECURESTORAGE_CONFIG_DIR"),
            Some(None),
            "the conflicting higher-precedence source must be removed"
        );
    }

    #[test]
    fn another_tools_managed_home_does_not_rewrite_claude_storage() {
        let mut command = Command::new("codex");
        command.env("CLAUDE_SECURESTORAGE_CONFIG_DIR", "/tmp/intentional-live");

        configure_managed_tool_home(
            &mut command,
            "codex",
            "CODEX_HOME",
            std::path::Path::new("/tmp/swapdex-managed-codex"),
        );

        assert_eq!(
            command_env(&command, "CLAUDE_SECURESTORAGE_CONFIG_DIR"),
            Some(Some(OsString::from("/tmp/intentional-live")))
        );
    }
}

/// Remove the live credential files so the tool's next run prompts a fresh
/// sign-in. Claude keeps the rest of .claude.json (projects, settings) - only
/// the oauthAccount block goes.
fn sign_out_locally(paths: &Paths, tool: &str) {
    match tool {
        "claude-code" => {
            // Sign out LOCALLY only - deliberately NOT `claude auth logout`.
            // That command REVOKES the OAuth token server-side, which kills the
            // snapshot we captured one step earlier AND every saved profile
            // that shares this account - the "all my logins got signed out"
            // disaster. A safe switcher must never destroy a login it exists to
            // preserve. Clearing the local Keychain item + credential file is
            // enough for Claude to prompt a fresh sign-in for the NEW account,
            // and the stashed token stays valid so `restore` / switching back
            // still works. This matches what claude-swap and Symbioose do
            // (local `security delete`, never a server-revoking logout).
            std::fs::remove_file(paths.claude_credentials()).ok();
            crate::adapters::claude::keychain_delete();
            if let Ok(bytes) = std::fs::read(paths.claude_config_json()) {
                if let Ok(mut cfg) = serde_json::from_slice::<Value>(&bytes) {
                    if let Some(obj) = cfg.as_object_mut() {
                        obj.remove("oauthAccount");
                        if let Ok(out) = serde_json::to_vec(&cfg) {
                            let _ = crate::atomic::write_secret(&paths.claude_config_json(), &out);
                        }
                    }
                }
            }
        }
        "codex" => {
            std::fs::remove_file(paths.codex_auth()).ok();
        }
        "gemini" => {
            std::fs::remove_file(paths.gemini_oauth()).ok();
            std::fs::remove_file(paths.gemini_accounts()).ok();
        }
        _ => {
            std::fs::remove_file(paths.antigravity_token()).ok();
        }
    }
}

/// Ask a question and read a trimmed line; empty input yields `default`.
/// Ask on stdout, read a line. `None` means the input stream ENDED (Ctrl-D or
/// a closed pipe) - callers must stop asking, or the wizard would spin forever
/// re-prompting into a stream that can never answer.
fn prompt(question: &str, default: &str) -> Option<String> {
    use std::io::Write;
    print!("{question}");
    let _ = std::io::stdout().flush();
    let mut line = String::new();
    match std::io::stdin().read_line(&mut line) {
        Ok(0) | Err(_) => return None, // EOF or broken stream
        Ok(_) => {}
    }
    let t = line.trim();
    Some(if t.is_empty() {
        default.to_string()
    } else {
        t.to_string()
    })
}

/// Why the sign-out did not take, and what actually fixes THAT.
///
/// Two independent checks guard it, and one remedy was printed for both. When a
/// CREDENTIAL is still readable the account is not signed in anywhere - it is
/// another profile's Keychain item answering - and sending the user to sign out
/// in their browser cannot help.
fn sign_out_blocked_remedy(identity_survived: bool, tool: &str) -> String {
    if identity_survived {
        return same_account_hint(tool);
    }
    "a credential is still readable after the sign-out, which usually means \
     another CLAUDE_CONFIG_DIR profile's Keychain item is answering - signing out \
     in a browser will not change that. `swapdex doctor` names what it found."
        .to_string()
}

/// What removing this slot costs, when it is the last one a running proxy has.
///
/// The proxy refuses a turn it has no slot for, and sessions are pinned to its
/// address rather than reaching the vendor directly - so the moment the last one
/// goes, every session on it fails. `rm` reported only what it did to the slot.
fn last_slot_warning(remaining: usize, proxy_running: bool, tool: &str) -> Option<String> {
    (remaining == 0 && proxy_running).then(|| {
        format!(
            "  the {} proxy has no account left to serve - sessions on it will fail \
             with \"no account slots yet\" until one is back (`swapdex run <name> \
             --tool {}`, or `swapdex adopt <name> <dir>`)",
            pretty_tool(tool),
            pretty_tool_flag(tool)
        )
    })
}

/// What `doctor` should say about a proxy still running an older build.
///
/// `install_verdict` already notes that a proxy started outside the service
/// "never picked up an upgrade" - and nothing checked. The build id sits beside
/// the pid in the marker, so the comparison costs a read that already happens.
fn stale_proxy_note(running: &str, current: &str, tool: &str) -> Option<String> {
    fn ver(b: &str) -> &str {
        b.rsplit_once('-').map_or(b, |(v, _)| v)
    }
    (!running.is_empty() && running != current).then(|| {
        // The comparison is on the build id; `ver` drops exactly the part that
        // differs. Printing only the version then contrasted two identical
        // strings - "running 0.165.9 while this swapdex is 0.165.9" - and left
        // the row unactionable for the case it matters most in: one version
        // installed twice.
        let difference = if ver(running) == ver(current) {
            format!("a different build of {}", ver(current))
        } else {
            format!("{} while this swapdex is {}", ver(running), ver(current))
        };
        format!(
            "running {difference} - an upgrade does not restart it, \
             so it still behaves like the older build: `swapdex service install \
             --tool {}`",
            crate::commands::tool_binary(tool)
        )
    })
}

/// What to offer as the name for an account you have NOT signed into yet.
///
/// Nothing. The only identity to hand is the login being signed out of, so a
/// suggestion built from it names the new profile after the old account - and
/// that name is usually already saved, so Enter answered "already exists -
/// replace it?" instead of adding anything.
fn new_account_prompt() -> &'static str {
    "name for the new account (e.g. personal): "
}

/// The name to offer for a profile that will hold the login you are signed into.
///
/// The CLI prompt worked this out inline and the dashboard's box had nothing, so
/// the same question came with an answer in one place and a blank in the other.
fn suggested_profile_name(paths: &Paths) -> String {
    let who = adapters::all()
        .iter()
        .find_map(|a| a.identity(paths).ok().flatten())
        .map(|id| id.email.unwrap_or(id.display))
        .unwrap_or_else(|| "account".into());
    suggest_name(&who)
}

/// A default profile name from an email/display (its local part, sanitized).
fn suggest_name(who: &str) -> String {
    let base = who.split('@').next().unwrap_or(who);
    let clean: String = base
        .chars()
        .filter(|c| c.is_alphanumeric() || *c == '-' || *c == '_')
        .collect();
    if crate::store::valid_profile_name(&clean) {
        clean
    } else {
        "account".to_string()
    }
}

/// A friendly tool label for prompts.
/// How to actually reach a DIFFERENT account when the tool keeps signing you
/// back into the same one from a cached browser session. swapdex removes the
/// local credential but cannot control the tool's own OAuth prompt.
fn same_account_hint(tool: &str) -> String {
    match tool {
        "claude-code" => "To add a different account: sign out at claude.ai in your browser \
             first (or use /logout then /login inside Claude Code and pick the other \
             account), then run this again."
            .to_string(),
        "codex" => "Codex re-used your ChatGPT browser session. Sign out at chatgpt.com \
             (or open the login in a different browser / private window), then run this \
             again."
            .to_string(),
        _ => "The tool re-used your signed-in Google account. Choose the OTHER account at \
             Google's account picker (or sign the first one out in your browser), then \
             run this again."
            .to_string(),
    }
}

fn pretty_tool(tool: &str) -> &str {
    match tool {
        "claude-code" => "Claude Code",
        "codex" => "Codex",
        "gemini" => "Gemini CLI",
        "antigravity" => "Antigravity",
        other => other,
    }
}

/// A yes/no prompt; empty input takes `default_yes`.
fn yes_no(question: &str, default_yes: bool) -> bool {
    // EOF answers "no": never take an irreversible step on a dead stream.
    let Some(a) = prompt(question, if default_yes { "y" } else { "n" }) else {
        return false;
    };
    matches!(a.to_ascii_lowercase().as_str(), "y" | "yes")
}

/// Ask for a profile name, re-prompting until it is valid (or the user skips).
/// An existing name asks whether to replace it. Returns None on skip.
fn ask_name(
    store: &Store,
    question: &str,
    default: &str,
    holder: Option<NameHolder<'_>>,
) -> Option<String> {
    loop {
        let ans = prompt(question, default)?; // EOF -> skip, never loop
        if ans.eq_ignore_ascii_case("skip") || ans.is_empty() {
            return None;
        }
        if !crate::store::valid_profile_name(&ans) {
            println!("  '{ans}' can't be a name (1-64 bytes, not all spaces; no '/', '\\\\', leading '.', or control chars). Try again.");
            continue;
        }
        // ask_name only ever names a NEW profile, so reject the reserved "-"
        // here too - `valid_profile_name` intentionally allows it (legacy "-"
        // profiles must stay rm/rename-able), but CREATION must not, or setup
        // would mint a "-" that breaks `use -`. `add`/`rename` reject it via a
        // separate post-check; setup had none.
        if ans == "-" {
            println!(
                "  '-' is reserved (`swapdex use -` toggles to the previous profile). Try again."
            );
            continue;
        }
        // A slot holds a name as surely as a profile does, and `ls` warns on
        // every listing when one name means two accounts. Refuse and re-ask,
        // the way an invalid name is handled - aborting mid-wizard is worse.
        if let Some(h) = &holder {
            let mine = Some(h.account_id).filter(|s| !s.is_empty());
            let slot = slot_account_under(h.paths, h.tool, &ans);
            if name_means_two_accounts(mine, slot.as_deref()) {
                println!(
                    "  '{ans}' is already a {} slot holding a different account \
                     (`swapdex slots` shows it). Try again.",
                    pretty_tool(h.tool)
                );
                continue;
            }
        }
        if store.list().iter().any(|p| p.name == ans)
            && !yes_no(
                &format!("  '{ans}' already exists - replace it? [y/N]: "),
                false,
            )
        {
            continue;
        }
        return Some(ans);
    }
}

/// Guided first-run onboarding: save the accounts you're logged into, offer to
/// add more, and show how to switch. Interactive (needs a TTY).
pub fn setup(paths: &Paths) -> Result<i32> {
    use std::io::IsTerminal;
    crate::atomic::ensure_not_root()?;
    // SWAPDEX_ASSUME_TTY lets the test suite drive the prompts over a pipe.
    if !std::io::stdin().is_terminal() && std::env::var_os("SWAPDEX_ASSUME_TTY").is_none() {
        eprintln!(
            "swapdex setup is interactive - run it in a terminal, or use `swapdex login <name>`."
        );
        return Ok(1);
    }
    let store = Store::open(paths)?;
    println!(
        "swapdex keeps several Claude Code / Codex / Gemini / Antigravity logins and switches between them."
    );
    println!(
        "Let's save the accounts you use. Press Enter to accept a [default], Ctrl-C to quit.\n"
    );

    // 1) Save the accounts you're currently logged into.
    for adapter in adapters::all() {
        let tool = adapter.name();
        // A corrupt/unreadable login for ONE tool (e.g. a hand-edited
        // ~/.claude.json) must not abort the whole wizard before the other,
        // valid tools get saved. Treat an error like "not logged in": warn
        // and continue to the next tool.
        let id = match adapter.identity(paths) {
            Ok(Some(id)) => id,
            Ok(None) => {
                println!("{}: not logged in - skipping.\n", pretty_tool(tool));
                continue;
            }
            Err(e) => {
                println!(
                    "{}: login present but unreadable ({}) - skipping.\n",
                    pretty_tool(tool),
                    crate::util::redact_path(&format!("{e:#}"))
                );
                continue;
            }
        };
        if let Some(existing) = matched_profile_name(&store, tool, &id.account_id) {
            println!("{}: already saved as '{existing}'.\n", pretty_tool(tool));
            continue;
        }
        let who = id.email.clone().unwrap_or_else(|| id.display.clone());
        let default = suggest_name(&who);
        println!("{}: you're logged in as {who}.", pretty_tool(tool));
        // Attaching this tool to an existing profile of the same suggested
        // name is the NORMAL multi-tool case (`swapdex add <name>` semantics)
        // - never scare with "replace it?" for it, and never skip it.
        if let Some(p) = store.list().into_iter().find(|p| p.name == default) {
            // This early attach bypasses `ask_name`, so perform its slot guard
            // here too. Otherwise a profile holding another tool causes the
            // current login to be filed over a different slot account's name.
            let slot_id = slot_account_under(paths, tool, &default);
            let crosses_slot = name_means_two_accounts(Some(&id.account_id), slot_id.as_deref());
            if !p.tools.iter().any(|t| t == tool) && !crosses_slot {
                // One unreadable tool must not abort the whole wizard.
                match adapter.capture(paths) {
                    Ok(snap) => {
                        store.save(&default, &snap)?;
                        println!("  attached {} to '{default}'.\n", pretty_tool(tool));
                    }
                    Err(e) => {
                        eprintln!("  could not read this login ({e:#}) - skipped.\n");
                    }
                }
                continue;
            }
        }
        match ask_name(
            &store,
            &format!("  save it as [{default}] (Enter to accept, 'skip' to skip): "),
            &default,
            Some(NameHolder {
                paths,
                tool,
                account_id: &id.account_id,
            }),
        ) {
            Some(name) => match adapter.capture(paths) {
                Ok(snap) => {
                    store.save(&name, &snap)?;
                    println!("  saved as '{name}'.\n");
                }
                Err(e) => {
                    eprintln!("  could not read this login ({e:#}) - skipped.\n");
                }
            },
            None => println!("  skipped.\n"),
        }
    }

    // 2) Offer to add more accounts - ANY tool, through the same one-flow
    //    login (save current, sign out locally, fresh sign-in, capture).
    println!("You can keep several accounts per tool (e.g. work and personal).");
    loop {
        if !yes_no("  add another account now? [y/N]: ", false) {
            break;
        }
        println!("  which tool?  1) Claude Code   2) Codex   3) Gemini CLI   4) Antigravity");
        let sel = loop {
            match prompt("  pick [1-4] (Enter cancels): ", "").as_deref() {
                Some("1") => break Some(ToolSel::Claude),
                Some("2") => break Some(ToolSel::Codex),
                Some("3") => break Some(ToolSel::Gemini),
                Some("4") => break Some(ToolSel::Antigravity),
                Some("") | None => break None,
                _ => println!("  pick a number between 1 and 4 (Enter cancels)"),
            }
        };
        let Some(sel) = sel else {
            println!("  skipped.\n");
            continue;
        };
        let name = match ask_name(&store, "  name for it (e.g. personal): ", "", None) {
            Some(n) => n,
            None => {
                println!("  skipped.\n");
                continue;
            }
        };
        let _ = login(paths, &name, Some(sel))?;
        println!();
    }

    // 3) Summary. Existing slots are already usable accounts even when this
    // run captured no snapshot; calling that machine empty contradicts every
    // account-facing command the summary points at.
    let accounts = merged_accounts(paths, &store).0;
    let names: Vec<String> = accounts.iter().map(|p| p.name.clone()).collect();
    println!();
    if names.is_empty() {
        println!(
            "No accounts saved yet. Log into Claude Code or Codex, then run `swapdex setup` again."
        );
    } else {
        println!("You're set - saved: {}.", names.join(", "));
        println!("  switch:   swapdex use <name>");
        println!("  see all:  swapdex ls");
        if names.len() > 1 {
            let mut described_managed_session = false;
            for tool in ["claude-code", "codex"] {
                let has_slots = crate::slots::Slots::open_for(paths, tool)
                    .map(|slots| !slots.list().is_empty())
                    .unwrap_or(false);
                if !has_slots {
                    continue;
                }
                described_managed_session = true;
                let bin = tool_binary(tool);
                if crate::shim::shim_path_for(paths, tool).exists() {
                    println!(
                        "  {bin}: launch or relaunch a plain `{bin}` through its installed shim; \
                         that is a managed session."
                    );
                } else if crate::shim::real_tool(paths, tool).is_some() {
                    println!(
                        "  {bin}: run `swapdex shim`, then launch or relaunch a plain `{bin}`; \
                         a launch through the shim is a managed session."
                    );
                } else {
                    println!(
                        "  {bin}: install the client, run `swapdex shim`, then launch it through \
                         the shim to start a managed session."
                    );
                }
                println!(
                    "    choose the payer for managed sessions: `swapdex serve <name>{}`",
                    tool_flag(tool)
                );
                println!(
                    "    a `{bin}` session opened directly outside Swapdex keeps its own login; \
                     relaunch it through the shim once before `serve` can manage it."
                );
            }
            if !described_managed_session {
                println!(
                    "  saved profiles apply when you launch the client again; an already-running \
                     direct session keeps its current login."
                );
            }
        }
    }
    Ok(0)
}

fn now_ms() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_millis() as i64)
        .unwrap_or(0)
}

fn now_secs() -> u64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

pub fn usage(paths: &Paths, json: bool) -> Result<i32> {
    let rows = crate::usage::tool_usage(paths);
    if json {
        let out: Vec<Value> = rows
            .iter()
            .map(|r| {
                let accounts: serde_json::Map<String, Value> = r
                    .accounts
                    .iter()
                    .map(|(name, (t5, t7))| {
                        (
                            name.clone(),
                            serde_json::json!({"last_5h_tokens": t5, "last_7d_tokens": t7}),
                        )
                    })
                    .collect();
                serde_json::json!({
                    "tool": r.tool,
                    "last_5h": {"sessions": r.w5h.sessions, "tokens": r.w5h.tokens},
                    "last_7d": {"sessions": r.w7d.sessions, "tokens": r.w7d.tokens},
                    "accounts": accounts,
                })
            })
            .collect();
        println!("{}", serde_json::to_string(&out)?);
        return Ok(0);
    }
    if rows.iter().all(|r| r.w7d.sessions == 0) {
        println!("No recent session activity found (reads ~/.claude and ~/.codex, locally).");
        return Ok(0);
    }
    println!("Local usage - this machine, approximate (not the billed quota):");
    for r in &rows {
        if r.w7d.sessions == 0 {
            continue;
        }
        println!(
            "  {:<12} 5h: {:>7} tok / {} sess    7d: {:>8} tok / {} sess",
            r.tool,
            crate::usage::human(r.w5h.tokens),
            r.w5h.sessions,
            crate::usage::human(r.w7d.tokens),
            r.w7d.sessions,
        );
        // Per-account rows via the switch timeline; the untagged remainder is
        // whatever predates the first switch.
        for (name, (t5, t7)) in &r.accounts {
            println!(
                "    @{:<11} 5h: {:>7} tok           7d: {:>8} tok",
                name,
                crate::usage::human(*t5),
                crate::usage::human(*t7),
            );
        }
        let attributed7: u64 = r.accounts.values().map(|(_, t7)| *t7).sum();
        let rest = r.w7d.tokens.saturating_sub(attributed7);
        if !r.accounts.is_empty() && rest > 0 {
            println!(
                "    {:<12} 5h:                       7d: {:>8} tok (before your first switch)",
                "(untagged)",
                crate::usage::human(rest),
            );
        }
    }
    // Honesty for the two tools usage CANNOT cover: they keep no token
    // transcripts on disk, so a gemini/antigravity-heavy user must not read
    // the silence as "no usage".
    let uncovered: Vec<&str> = ["gemini", "antigravity"]
        .into_iter()
        .filter(|t| {
            adapters::by_name(t)
                .map(|a| a.present(paths))
                .unwrap_or(false)
        })
        .collect();
    if !uncovered.is_empty() {
        println!(
            "note: {} not shown - those CLIs keep no local token transcripts to read",
            uncovered.join(" and ")
        );
    }
    println!("(summed locally from session transcripts; accounts via the switch timeline)");
    Ok(0)
}

/// The address a Codex home is signed in as - a label for the row, read with the
/// same decoder the adapter uses, which keeps only the `email` claim.
fn codex_slot_email(dir: &std::path::Path) -> Option<String> {
    let bytes = std::fs::read(dir.join("auth.json")).ok()?;
    let v: Value = serde_json::from_slice(&bytes).ok()?;
    adapters::codex::decode_email_from_id_token(v["tokens"]["id_token"].as_str())
}

/// The config dir of the slot registered under `name`, if there is one.
fn slot_dir_named(paths: &Paths, name: &str) -> Option<std::path::PathBuf> {
    crate::slots::Slots::open(paths)
        .ok()?
        .list()
        .into_iter()
        .find(|r| r.name == name)
        .map(|r| r.config_dir)
}

/// `swapdex quota` reads each account's provider-reported usage without sending
/// a model message. Slot credentials remain authoritative, but quota never renews
/// or rewrites them: expired tokens are reported locally and are not sent. A
/// running native Claude owner may supply its current token for the same account.
/// Provider transport and response parsing live in the quota modules; this
/// function selects each credential and renders.
pub fn quota(paths: &Paths, json: bool) -> Result<i32> {
    use crate::quota::{self as q, Fetch};

    struct Row {
        /// Display label (may carry an "(active)" marker).
        label: String,
        /// The plain profile name - what `--json` reports and `use` hints take.
        name: String,
        email: Option<String>,
        token: Option<String>,
        active: bool,
        /// The saved token has already lapsed. Sending it earns a refusal that
        /// looks like the endpoint being busy, so it is never sent.
        expired: bool,
        /// Set when the login could not be READ, carrying why - a locked
        /// keychain is not an account without a login.
        unreadable: Option<String>,
    }

    struct SlotQuotaState {
        email: Option<String>,
        uuid: Option<String>,
        identity: Option<crate::live_login::LoginIdentity>,
        token: Option<String>,
        expired: bool,
        unreadable: Option<String>,
    }

    struct SlotQuotaRead {
        email: Option<String>,
        uuid: Option<String>,
        token: Option<String>,
        expired: bool,
        unreadable: Option<String>,
    }

    fn slot_quota_state(paths: &Paths, dir: &std::path::Path, now: i64) -> SlotQuotaState {
        use crate::adapters::claude::KeychainReadError as K;

        let identity_path = dir.join(".claude.json");
        let identity_before = std::fs::read(&identity_path).ok();
        let credential = crate::claude_authority::credential(paths, dir);
        let identity_after = std::fs::read(&identity_path).ok();
        let identity_value = identity_after
            .as_deref()
            .and_then(|bytes| serde_json::from_slice::<Value>(bytes).ok());
        let email = identity_value.as_ref().and_then(|value| {
            value["oauthAccount"]["emailAddress"]
                .as_str()
                .map(str::to_string)
        });
        let uuid = identity_value.as_ref().and_then(|value| {
            value["oauthAccount"]["accountUuid"]
                .as_str()
                .map(str::to_string)
        });
        let identity = identity_after
            .as_deref()
            .and_then(|bytes| crate::live_login::identity_from_credential(bytes, "claude-code"));
        if identity_before != identity_after {
            return SlotQuotaState {
                email,
                uuid,
                identity,
                token: None,
                expired: false,
                unreadable: Some("slot identity changed while quota was reading its login".into()),
            };
        }
        match credential {
            Ok(credential) => SlotQuotaState {
                email,
                uuid,
                identity,
                token: q::token_from_credentials(credential.bytes()),
                // Match the serving path's one-minute slack without reading a
                // second credential generation after the access token.
                expired: q::credentials_expired(credential.bytes(), now.saturating_add(60_000)),
                unreadable: None,
            },
            Err(error) => SlotQuotaState {
                email,
                uuid,
                identity,
                token: None,
                expired: false,
                unreadable: Some(match error {
                    K::Locked => "signed in, but this shell cannot read the keychain".into(),
                    K::Missing | K::NotApplicable => "no saved token".into(),
                }),
            },
        }
    }

    fn slot_quota_read(paths: &Paths, dir: &std::path::Path) -> SlotQuotaRead {
        let now = now_ms();
        let native = crate::live_login::resolve(paths, dir, "claude-code", now);
        let initial = slot_quota_state(paths, dir, now);
        if let Some(native) = native {
            if initial.identity.as_ref() == Some(&native.identity) {
                return SlotQuotaRead {
                    email: initial.email,
                    uuid: initial.uuid,
                    token: Some(String::from_utf8_lossy(native.access_token.expose()).to_string()),
                    expired: false,
                    unreadable: None,
                };
            }
            return SlotQuotaRead {
                email: initial.email,
                uuid: initial.uuid,
                token: None,
                expired: false,
                unreadable: Some(
                    "slot identity changed while quota was reading its native login".into(),
                ),
            };
        }
        SlotQuotaRead {
            email: initial.email,
            uuid: initial.uuid,
            token: initial.token,
            expired: initial.expired,
            unreadable: initial.unreadable,
        }
    }

    let live_id = adapters::claude::Claude.identity(paths).ok().flatten();
    let live_uuid = live_id
        .as_ref()
        .map(|a| a.account_id.clone())
        .filter(|s| !s.is_empty());
    let live_credential = adapters::claude::live_credentials(paths);
    let live_token = live_credential
        .as_deref()
        .and_then(q::token_from_credentials);
    let live_expired = live_credential
        .as_deref()
        .is_some_and(|credential| q::credentials_expired(credential, now_ms()));

    let mut rows: Vec<Row> = Vec::new();
    let mut matched_live = false;
    if let Ok(store) = Store::open(paths) {
        for p in store.list() {
            if !p.tools.iter().any(|t| t == "claude-code") {
                continue;
            }
            let snap = store.load(&p.name, "claude-code").ok().flatten();
            let (mut email, mut uuid, mut token) = (None, None, None);
            let mut expired = false;
            if let Some(s) = &snap {
                if let Some(o) = s
                    .part("oauth_account")
                    .and_then(|o| serde_json::from_slice::<Value>(o.expose()).ok())
                {
                    email = o["emailAddress"].as_str().map(str::to_string);
                    uuid = o["accountUuid"].as_str().map(str::to_string);
                }
                token = s
                    .part("credentials")
                    .and_then(|c| q::token_from_credentials(c.expose()));
                expired = s
                    .part("credentials")
                    .is_some_and(|c| q::credentials_expired(c.expose(), now_ms()));
            }
            // A profile and a slot can carry the same name: the profile is the
            // old copied snapshot, the slot is where that account lives now.
            // Only one of the two is alive - the tool refreshes the slot's
            // credential in place, while nothing refreshes a copy - so the slot
            // answers for the account and the snapshot is not consulted at all.
            let mut unreadable: Option<String> = None;
            let slot = slot_dir_named(paths, &p.name);
            if let Some(dir) = &slot {
                // The name can have been reused for a different account. Even
                // when the slot is unreadable, neither its credential nor its
                // identity may fall back to the old snapshot.
                let current = slot_quota_read(paths, dir);
                email = current.email;
                uuid = current.uuid;
                token = current.token;
                expired = current.expired;
                unreadable = current.unreadable;
            }
            let matches_live = live_uuid.is_some() && uuid == live_uuid;
            let active = if slot.is_some() {
                slot_default_name(paths, "claude-code")
                    .map_or(matches_live, |pointed| pointed == p.name)
            } else {
                matches_live
            };
            // A selected slot remains authoritative even if the native default
            // home holds the same identity or an older unrelated login.
            let use_live = slot.is_none() && matches_live;
            matched_live |= matches_live;
            rows.push(Row {
                label: if active {
                    format!("{} (active)", p.name)
                } else {
                    p.name.clone()
                },
                name: p.name.clone(),
                email: if use_live {
                    live_id.as_ref().and_then(|a| a.email.clone()).or(email)
                } else {
                    email
                },
                token: if use_live { live_token.clone() } else { token },
                active,
                expired: if use_live { live_expired } else { expired },
                unreadable,
            });
        }
    }
    // Slot accounts too: they hold their own credential (that is the point of the
    // model), so a quota list without them omits exactly the accounts the proxy
    // rotates between. Their token is read from the slot, never copied.
    if let Ok(slots) = crate::slots::Slots::open(paths) {
        for r in slots.list() {
            if rows.iter().any(|x| x.name == r.name) {
                continue;
            }
            let current = slot_quota_read(paths, &r.config_dir);
            let uuid = current.uuid;
            // The pointer decides this wherever there is one. Matching against
            // the tool's own config dir - which a slot switch never writes -
            // called every slot inactive on a machine that has only slots, so
            // the account paying for every turn lost its `(active)` marker and
            // a rejected token was explained as a dead snapshot curable with
            // `swapdex use <name>`, which for a slot moves a pointer and
            // refreshes nothing.
            let active = match slot_default_name(paths, "claude-code") {
                Some(pointed) => pointed == r.name,
                None => live_uuid.is_some() && uuid == live_uuid,
            };
            matched_live |= live_uuid.is_some() && uuid == live_uuid;
            rows.push(Row {
                label: if active {
                    format!("{} (active)", r.name)
                } else {
                    r.name.clone()
                },
                name: r.name.clone(),
                email: current.email,
                token: current.token,
                active,
                expired: current.expired,
                unreadable: current.unreadable,
            });
        }
    }
    // A live login that is not saved as any profile still deserves a line.
    if !matched_live && live_token.is_some() {
        rows.insert(
            0,
            Row {
                label: "(active login, not saved)".into(),
                name: "(active login, not saved)".into(),
                email: live_id.as_ref().and_then(|a| a.email.clone()),
                token: live_token.clone(),
                active: true,
                expired: live_expired,
                unreadable: None,
            },
        );
    }
    rows.sort_by_key(|r| !r.active);

    if rows.is_empty() {
        if json {
            // A machine can hold only Codex accounts. Reporting no accounts at
            // all on one of those was the JSON half of the same blind spot the
            // human path below fixed.
            let now = now_secs() as i64;
            let codex = codex_quota_json(&read_codex_accounts(paths, now), now);
            println!(
                "{}",
                serde_json::json!({"accounts": [], "codex": codex, "offline": null})
            );
        } else {
            println!(
                "No Claude accounts found. Log in with `claude`, or `swapdex add` to save one."
            );
            // A machine can hold only Codex accounts, and returning here left
            // it with nothing to show but a note about a tool it does not use.
            println!();
            print_codex_quota(paths, now_secs() as i64);
        }
        return Ok(0);
    }

    let now = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs() as i64)
        .unwrap_or(0);

    // Fetch each account. If the first attempt that actually leaves the machine
    // fails at the transport layer, we are almost certainly offline - stop
    // rather than fire every account's token at an unreachable endpoint.
    let mut results: Vec<(usize, Fetch)> = Vec::new();
    let mut to_fetch: Vec<(usize, String)> = Vec::new();
    let mut offline: Option<String> = None;
    for (i, r) in rows.iter().enumerate() {
        match &r.token {
            None => results.push((
                i,
                Fetch::Offline(
                    r.unreadable
                        .clone()
                        .unwrap_or_else(|| "no saved token".into()),
                ),
            )),
            // Do not ask on behalf of a token that has already lapsed. The
            // endpoint refuses it the same way it refuses a burst, so the answer
            // would read as "busy, try again in a moment" - advice that can never
            // come true, and three retries per dead account that make the
            // endpoint busier for the accounts that CAN answer.
            Some(_) if r.expired => results.push((
                i,
                Fetch::Offline(match slot_dir_named(paths, &r.name) {
                    Some(dir) if crate::refresh::claude_renewal_deferred(paths, &dir, now_ms()) => {
                        "login expired · renewal deferred to native session - \
                         wait for the owning Claude session to refresh this login or exit"
                            .into()
                    }
                    Some(_) => "slot access expired - renewal has not completed; \
                        retry after background refresh or sign in to this slot"
                        .into(),
                    None => "saved token expired - snapshots go stale as refresh tokens rotate; \
                        `swapdex run <name>` gives this account a slot that stays fresh"
                        .into(),
                }),
            )),
            // An unusable token is a PER-ACCOUNT problem (corrupt snapshot),
            // not a transport failure - it must never masquerade as "the
            // network is down" and abort the whole run.
            Some(t) if !q::token_usable(t) => results.push((
                i,
                Fetch::Offline(unusable_token_reason(t, r.unreadable.as_deref())),
            )),
            // Collected and read together below: one round trip per account in
            // sequence was most of the wait.
            Some(t) => to_fetch.push((i, t.clone())),
        }
    }
    if !to_fetch.is_empty() {
        let got = q::fetch_many(paths, to_fetch);
        // If NOTHING reached the endpoint, this is the machine being offline
        // rather than a per-account problem, and saying so once beats saying it
        // per account.
        let any_reached = got.iter().any(|(_, f)| !matches!(f, Fetch::Offline(_)));
        if !any_reached {
            if let Some((_, Fetch::Offline(msg))) = got.first() {
                offline = Some(msg.clone());
            }
        }
        results.extend(got);
    }
    results.sort_by_key(|(i, _)| *i);

    // Remember what came back, here where the reading is actually taken - every
    // caller of this command then benefits, including the dashboard, which cannot
    // record a reading it never received.
    let remembered: Vec<(String, crate::quota_cache::Entry)> = results
        .iter()
        .filter_map(|(i, f)| match f {
            Fetch::Ok(qd) => Some((
                rows[*i].name.clone(),
                crate::quota_cache::Entry {
                    five_h: qd.five_hour.map(|w| w.used_pct),
                    five_h_reset: qd.five_hour.and_then(|w| w.resets_at),
                    seven_d: qd.seven_day.map(|w| w.used_pct),
                    seven_d_reset: qd.seven_day.and_then(|w| w.resets_at),
                    at: now,
                    on_credits: qd.can_serve_past_windows(),
                    refused: None,
                    // A reading arrived, so the token works.
                    token_rejected_at: None,
                },
            )),
            _ => None,
        })
        .collect();
    crate::quota_cache::update(paths, &remembered);

    if json {
        let accounts: Vec<Value> = results
            .iter()
            .map(|(i, f)| {
                quota_json(
                    &rows[*i].name,
                    rows[*i].email.as_deref(),
                    rows[*i].active,
                    f,
                )
            })
            .collect();
        // The Codex rows point the reader at `--json` - a row with no windows
        // says so in as many words - so this is where those accounts have to be.
        let codex = codex_quota_json(&read_codex_accounts(paths, now), now);
        println!(
            "{}",
            serde_json::json!({"accounts": accounts, "codex": codex, "offline": offline})
        );
        return Ok(0);
    }

    if let Some(msg) = offline {
        println!("swapdex quota: could not reach api.anthropic.com - {msg}");
        println!(
            "(this live quota lookup needs the network; `swapdex usage` reads local activity)"
        );
        return Ok(0);
    }

    println!("quota - remaining on your Claude accounts");
    println!("live from Anthropic's usage endpoint; opt-in network, spends 0 message quota.\n");
    for (i, f) in &results {
        let r = &rows[*i];
        match &r.email {
            Some(e) => println!("{}   {}", r.label, e),
            None => println!("{}", r.label),
        }
        match f {
            Fetch::Ok(qd) => {
                let mut any = false;
                if let Some(w) = qd.five_hour {
                    println!("  {}", win_line("5h", &w, now));
                    any = true;
                }
                if let Some(w) = qd.seven_day {
                    println!("  {}", win_line("7d", &w, now));
                    any = true;
                }
                for (label, w) in &qd.scoped {
                    println!("  {}", win_line(label, w, now));
                    any = true;
                }
                if !any {
                    println!(
                        "  (endpoint reported no windows - `swapdex quota --json` to inspect)"
                    );
                }
            }
            Fetch::Unauthorized => {
                println!(
                    "  usage endpoint rejected this credential - check `swapdex doctor`; \
                     renew or sign in to this account before retrying"
                );
            }
            Fetch::Unexpected(code, _) => {
                println!(
                    "  unexpected response (HTTP {code}) - run `swapdex quota --json` to see it"
                );
            }
            Fetch::Offline(msg) => println!("  {msg}"),
            Fetch::Coordination(msg) => {
                println!("  usage lookup coordination unavailable - {msg}")
            }
            Fetch::Throttled => println!("  {}", throttled_note()),
        }
        println!();
    }
    print_codex_quota(paths, now);
    println!("quota reads provider usage; `swapdex usage` shows local session activity.");
    Ok(0)
}

/// What to say when the usage endpoint declined to answer.
///
/// A 429 is the ENDPOINT being busy, and `quota.rs` classifies it that way with
/// a test named for it. This line then said "the account is fine" - the same
/// mistake mirrored: avoiding a false alarm by making a false reassurance. A
/// real account that was spent and refusing every turn printed exactly that
/// while the user tried to work out why nothing went through. A declined read
/// is no reading; it is not evidence in either direction.
fn throttled_note() -> &'static str {
    "usage endpoint declined to answer just now - that is no reading, \
     not a verdict on this account either way; try again in a moment"
}

/// The Codex login held in a saved snapshot, for accounts with no slot.
///
/// A snapshot is a copy, so its token can be older than the account's live one
/// and the endpoint may refuse it - which is reported as a refusal rather than
/// as an account with no numbers.
fn snapshot_codex_auth(paths: &Paths, name: &str) -> Option<crate::proxy::codex::Auth> {
    let snap = Store::open(paths).ok()?.load(name, "codex").ok()??;
    let v: Value = serde_json::from_slice(snap.part("auth")?.expose()).ok()?;
    let token = v["tokens"]["access_token"]
        .as_str()
        .filter(|s| !s.is_empty())?;
    let id = v["tokens"]["account_id"].as_str().unwrap_or_default();
    Some(crate::proxy::codex::Auth {
        token: crate::secret::Secret::new(token.as_bytes().to_vec()),
        account_id: id.to_string(),
    })
}

/// Every Codex account this machine knows, and where to read it from.
///
/// An account can be a SLOT (its own directory, the live login) or a saved
/// SNAPSHOT (a copy in swapdex's store). The report walked slots only, so a
/// machine that keeps its accounts as snapshots got no Codex section at all and
/// not a word saying why - found on a real one, where `ls` listed three Codex
/// accounts and `quota` printed nothing about any of them.
///
/// `Some(dir)` is a slot and is preferred where an account is held both ways:
/// the slot is what the tool refreshes, the snapshot a copy that goes stale.
pub fn codex_account_sources(
    slots: &[(String, std::path::PathBuf)],
    snapshots: &[String],
) -> Vec<(String, Option<std::path::PathBuf>)> {
    let mut out: Vec<(String, Option<std::path::PathBuf>)> = slots
        .iter()
        .map(|(n, d)| (n.clone(), Some(d.clone())))
        .collect();
    for n in snapshots {
        if !out.iter().any(|(have, _)| have == n) {
            out.push((n.clone(), None));
        }
    }
    out
}

/// What `quota` says about a Codex account that came back with no number.
///
/// "token rejected" is the endpoint's word, and for a token that has simply
/// LAPSED it reads as a broken account - which is how a machine with two dead
/// slots looked. The deadline is in the token itself, so when it has passed,
/// say the thing the reader can act on. Codex renews its own token when Codex
/// RUNS, so the remedy is to run it once in that slot.
fn codex_no_number(
    f: &crate::codex_usage::Fetch,
    name: &str,
    expired: bool,
    src: CodexSource<'_>,
) -> String {
    if !matches!(f, crate::codex_usage::Fetch::Unauthorized) {
        return f.why_no_number().unwrap_or("no reading").to_string();
    }
    match src {
        // The same login, signed in here under another name and answering. The
        // copy's token lapsed; the account did not, and saying "token rejected"
        // about a row directly above a healthy one condemns a working account.
        CodexSource::Snapshot { twin: Some(t) } => format!(
            "saved copy of the account signed in as '{t}' - this copy's token lapsed, \
             which says nothing about that account; `swapdex add {name} --tool codex --update` \
             saves a fresh copy, or leave it"
        ),
        // A copy cannot renew itself: only the live login rotates the token,
        // and `swapdex run` on a name with no slot would build an empty one and
        // ask for a fresh sign-in rather than renewing anything.
        CodexSource::Snapshot { twin: None } if expired => format!(
            "saved login expired - log in to that account and \
             `swapdex add {name} --tool codex --update` saves it again \
             (a saved copy cannot renew itself; only the live login does)"
        ),
        CodexSource::Slot if expired => format!(
            "login expired - `swapdex run {name} --tool codex` once renews it \
             (Codex renews its token when it runs, and this slot has not been opened since)"
        ),
        _ => f.why_no_number().unwrap_or("no reading").to_string(),
    }
}

/// Where a Codex credential was read from - which decides what can renew it.
///
/// A SLOT is the copy Codex itself renews when it runs. A SNAPSHOT is a copy in
/// swapdex's store; nothing renews it, so it goes stale by design, and its
/// remedy is a fresh capture rather than a run. `twin` names another account on
/// this machine holding the SAME login that read fine.
#[derive(Clone, Copy)]
enum CodexSource<'a> {
    Slot,
    Snapshot { twin: Option<&'a str> },
}

/// The Codex half of `swapdex quota`.
///
/// Kept as its own pass rather than folded into the Claude loop above: the two
/// answer different endpoints with different shapes, and the only thing they
/// share is how a window is drawn. Silent when there are no Codex accounts, so
/// a Claude-only machine sees no empty heading.
/// One Codex account this machine knows, read once.
struct CodexRow {
    name: String,
    /// `Some` for a slot (the copy Codex itself renews), `None` for a saved
    /// snapshot in the store (a copy, which nothing renews).
    dir: Option<std::path::PathBuf>,
    auth: Option<crate::proxy::codex::Auth>,
    fetch: Option<crate::codex_usage::Fetch>,
}

/// Read every Codex account, then ask the endpoint about each.
///
/// Gathered before anything is rendered because a row's honest answer can depend
/// on ANOTHER row - a saved copy of a login that is signed in here under a
/// different name - which a single pass cannot see. Both `quota` and
/// `quota --json` read through here, so they cannot answer differently.
fn read_codex_accounts(paths: &Paths, now: i64) -> Vec<CodexRow> {
    let slots: Vec<(String, std::path::PathBuf)> = crate::slots::Slots::open_for(paths, "codex")
        .map(|s| {
            s.list()
                .into_iter()
                .map(|r| (r.name, r.config_dir))
                .collect()
        })
        .unwrap_or_default();
    let snapshots: Vec<String> = Store::open(paths)
        .map(|st| {
            st.list()
                .into_iter()
                .filter(|p| p.tools.iter().any(|t| t == "codex"))
                .map(|p| p.name)
                .collect()
        })
        .unwrap_or_default();
    codex_account_sources(&slots, &snapshots)
        .into_iter()
        .map(|(name, dir)| {
            // A slot reads from its own directory; a snapshot from the copy in
            // the store. Reading only the first left snapshot-only machines
            // with an empty section and no reason for it.
            let auth = match &dir {
                Some(d) => crate::proxy::codex::slot_auth(d),
                None => snapshot_codex_auth(paths, &name),
            };
            let fetch = auth.as_ref().map(crate::codex_usage::fetch);
            if let Some(f) = &fetch {
                // This command already says "token rejected" on screen. Writing
                // it down is what lets the status line say the same thing
                // without a network read of its own.
                crate::codex_usage::note_reading(paths, &name, f, now);
            }
            CodexRow {
                name,
                dir,
                auth,
                fetch,
            }
        })
        .collect()
}

/// The Codex half of `swapdex quota`.
///
/// Kept as its own pass rather than folded into the Claude loop above: the two
/// answer different endpoints with different shapes, and the only thing they
/// share is how a window is drawn. Silent when there are no Codex accounts, so
/// a Claude-only machine sees no empty heading.
fn print_codex_quota(paths: &Paths, now: i64) {
    let rows = read_codex_accounts(paths, now);
    if rows.is_empty() {
        return;
    }
    println!("codex - remaining on your Codex accounts");
    println!("live from ChatGPT's usage endpoint; opt-in network, spends 0 message quota.\n");
    let healthy = codex_healthy_by_account(&rows);

    for r in &rows {
        let name = &r.name;
        let saved = r.dir.as_deref().and_then(codex_slot_email);
        match (&r.auth, &r.fetch) {
            (None, _) | (_, None) => {
                println!("{name}");
                println!(
                    "  no readable Codex login - `swapdex run {name} --tool codex` once signs it in"
                );
            }
            (Some(_), Some(crate::codex_usage::Fetch::Ok(a))) => {
                println!(
                    "{name}   {}",
                    codex_identity(a.email.as_deref(), a.plan.as_deref(), saved.as_deref())
                );
                for line in codex_quota_lines(a, now) {
                    println!("  {line}");
                }
            }
            // Each failure keeps its own name for the same reason it does on
            // the Claude side: a busy endpoint and a dead login are different
            // news, and one silence for both hides whichever matters.
            (Some(auth), Some(f)) => {
                let (expired, src) = codex_row_source(r.dir.as_deref(), auth, name, &healthy, now);
                println!("{name}   {}", saved.unwrap_or_default());
                println!("  {}", codex_no_number(f, name, expired, src));
            }
        }
        println!();
    }
}

/// The same accounts as `quota`, for `quota --json`.
///
/// The Codex rows send the reader here - a row with no windows says "`swapdex
/// quota --json` to inspect", and `Fetch::Unexpected` is kept whole so this can
/// show what came back - but the JSON branch returned before Codex was read at
/// all, so a Codex-only machine reported no accounts and no reason.
fn codex_quota_json(rows: &[CodexRow], now: i64) -> Vec<Value> {
    fn win(w: &crate::codex_limits::Window) -> Value {
        serde_json::json!({
            "used_pct": (w.used_pct * 10.0).round() / 10.0,
            "remaining_pct": ((100.0 - w.used_pct).max(0.0) * 10.0).round() / 10.0,
            "window_minutes": w.window_minutes,
            "resets_at": w.resets_at,
        })
    }
    let healthy = codex_healthy_by_account(rows);
    rows.iter()
        .map(|r| {
            let name = &r.name;
            let saved = r.dir.as_deref().and_then(codex_slot_email);
            let mut o = serde_json::json!({
                "name": name,
                "email": saved,
                "slot": r.dir.is_some(),
            });
            let m = o.as_object_mut().expect("json object");
            match (&r.auth, &r.fetch) {
                (None, _) | (_, None) => {
                    m.insert("status".into(), Value::String("unreadable".into()));
                }
                (Some(_), Some(crate::codex_usage::Fetch::Ok(a))) => {
                    m.insert("status".into(), Value::String("ok".into()));
                    if let Some(e) = &a.email {
                        m.insert("email".into(), Value::String(e.clone()));
                    }
                    m.insert(
                        "plan".into(),
                        a.plan.clone().map(Value::String).unwrap_or(Value::Null),
                    );
                    let placed = crate::codex_limits::place(&a.limits);
                    m.insert(
                        "five_hour".into(),
                        placed.five_h.as_ref().map(win).unwrap_or(Value::Null),
                    );
                    m.insert(
                        "seven_day".into(),
                        placed.seven_d.as_ref().map(win).unwrap_or(Value::Null),
                    );
                    let scoped: Vec<Value> = a
                        .scoped
                        .iter()
                        .map(|(n, w)| {
                            let mut wj = win(w);
                            wj.as_object_mut()
                                .expect("json object")
                                .insert("label".into(), Value::String(n.clone()));
                            wj
                        })
                        .collect();
                    m.insert("scoped".into(), Value::Array(scoped));
                }
                (Some(auth), Some(f)) => {
                    let (expired, src) =
                        codex_row_source(r.dir.as_deref(), auth, name, &healthy, now);
                    match f {
                        crate::codex_usage::Fetch::Unauthorized => {
                            m.insert(
                                "status".into(),
                                Value::String(if expired { "expired" } else { "rejected" }.into()),
                            );
                        }
                        crate::codex_usage::Fetch::Throttled => {
                            m.insert("status".into(), Value::String("throttled".into()));
                            m.insert(
                                "note".into(),
                                Value::String(
                                    "the usage endpoint is rate-limited, not this account".into(),
                                ),
                            );
                        }
                        crate::codex_usage::Fetch::Unexpected(code, body) => {
                            m.insert("status".into(), Value::String("unexpected".into()));
                            m.insert("http".into(), Value::from(*code));
                            m.insert("raw".into(), Value::String(body.clone()));
                        }
                        crate::codex_usage::Fetch::Offline(msg) => {
                            m.insert("status".into(), Value::String("offline".into()));
                            m.insert("detail".into(), Value::String(msg.clone()));
                        }
                        crate::codex_usage::Fetch::Ok(_) => unreachable!("handled above"),
                    }
                    // A copy is not the account. Saying which login it copies is
                    // what keeps a stale copy from reading as a dead account.
                    if let CodexSource::Snapshot { twin: Some(t) } = src {
                        m.insert("copy_of".into(), Value::String(t.to_string()));
                    }
                }
            }
            o
        })
        .collect()
}

/// Whether this row's credential has lapsed, and what can renew it.
///
/// The deadline used to be read from the slot DIRECTORY, so a saved copy - which
/// has none - could never be seen to have expired, and the one source that goes
/// stale by design was the one that could not say so. The deadline lives in the
/// credential, and both sources hand one over.
fn codex_row_source<'a>(
    dir: Option<&std::path::Path>,
    auth: &crate::proxy::codex::Auth,
    name: &str,
    healthy: &std::collections::BTreeMap<&'a str, &'a str>,
    now: i64,
) -> (bool, CodexSource<'a>) {
    let expired = crate::proxy::codex::auth_token_expired(auth, now);
    let src = match dir {
        Some(_) => CodexSource::Slot,
        None => CodexSource::Snapshot {
            twin: healthy
                .get(auth.account_id.as_str())
                .filter(|t| ***t != *name)
                .copied(),
        },
    };
    (expired, src)
}

/// Which login on this machine answered, by account id.
///
/// A saved copy carries the same account id as the live login it was taken
/// from, so this is what lets a stale copy say whose account it is a copy OF
/// instead of reporting that account as rejected.
fn codex_healthy_by_account(rows: &[CodexRow]) -> std::collections::BTreeMap<&str, &str> {
    let mut out = std::collections::BTreeMap::new();
    for r in rows {
        if let (Some(auth), Some(crate::codex_usage::Fetch::Ok(_))) = (&r.auth, &r.fetch) {
            out.entry(auth.account_id.as_str())
                .or_insert(r.name.as_str());
        }
    }
    out
}

/// What `swapdex quota` prints for one Codex account, beyond its name.
///
/// A dashboard row is one line, so the endpoint's per-model windows, its credit
/// balance and its refusal reason had nowhere to go. They go here, on the
/// surface that already prints a line per window.
///
/// Nothing is claimed that the response did not say. An account it said nothing
/// about prints that it said nothing, rather than an encouraging blank.
fn codex_quota_lines(a: &crate::codex_usage::Account, now: i64) -> Vec<String> {
    let as_window = |w: &crate::codex_limits::Window| crate::quota::Window {
        used_pct: w.used_pct,
        resets_at: w.resets_at,
    };
    let mut out = Vec::new();
    let placed = crate::codex_limits::place(&a.limits);
    // Per-model names run far past the width a window label is normally given
    // ("GPT-5.3-Codex-Spark" against "7d"), so the labels are padded to the
    // widest of THIS account's before they are drawn. Without it the bars step
    // sideways down the block and stop reading as one column.
    let pad = a
        .scoped
        .iter()
        .map(|(l, _)| l.chars().count())
        .chain(std::iter::once(9))
        .max()
        .unwrap_or(9);
    let line = |label: &str, w: &crate::codex_limits::Window| {
        win_line(&format!("{label:<pad$}"), &as_window(w), now)
    };
    for (label, w) in [("5h", placed.five_h), ("7d", placed.seven_d)] {
        if let Some(w) = w {
            out.push(line(label, &w));
        }
    }
    for (label, w) in &a.scoped {
        out.push(line(label, w));
    }
    if out.is_empty() {
        out.push("(the endpoint reported no windows - `swapdex quota --json` to inspect)".into());
    }
    // Whether a full window is a pause or the end of this account.
    if let Some(c) = &a.credits {
        out.push(match c {
            _ if c.unlimited => "credits: unlimited".to_string(),
            _ if c.overage_limit_reached => {
                "credits: spend limit reached - a full window is the end until it is raised".into()
            }
            _ if c.has_credits => match &c.balance {
                Some(b) => format!("credits: {b} - a full window is not the end"),
                None => "credits available - a full window is not the end".into(),
            },
            _ => "no credits - a full window is the end of this account".to_string(),
        });
    }
    if let Some(kind) = &a.refused {
        out.push(format!(
            "refusing turns: {}",
            crate::codex_usage::refusal_words(kind)
        ));
    }
    out
}

/// Render one window as a remaining-percent bar with its reset countdown.
fn win_line(label: &str, w: &crate::quota::Window, now: i64) -> String {
    let rem = w.remaining_pct();
    let filled = ((rem / 100.0) * 10.0).round().clamp(0.0, 10.0) as usize;
    let bar: String = "\u{2593}".repeat(filled) + &"\u{2591}".repeat(10 - filled);
    // The time, not the wait. A countdown has to be recomputed to stay true, so
    // it decays the moment this output is scrolled back to or piped to a file,
    // while a clock stays right - and the hour it resets at stays in the head
    // better than the hours left do. Both first-party CLIs print reset times
    // this way.
    let reset = match w.resets_at {
        Some(ts) => format!(
            "   resets {}",
            crate::proxy::pick::reset_clock(ts, now, crate::proxy::tz_offset())
        ),
        None => String::new(),
    };
    format!("{label:<9} {bar}  {rem:>3.0}% left{reset}")
}

/// One account's quota as JSON (for `swapdex quota --json`). An unexpected shape
/// carries the raw body so the exact endpoint schema is never lost.
fn quota_json(label: &str, email: Option<&str>, active: bool, f: &crate::quota::Fetch) -> Value {
    use crate::quota::{Fetch, Window};
    fn win(w: &Window) -> Value {
        serde_json::json!({
            "used_pct": (w.used_pct * 10.0).round() / 10.0,
            "remaining_pct": (w.remaining_pct() * 10.0).round() / 10.0,
            "resets_at": w.resets_at,
        })
    }
    let mut o = serde_json::json!({"name": label, "email": email, "active": active});
    let m = o.as_object_mut().expect("json object");
    match f {
        Fetch::Ok(q) => {
            m.insert("status".into(), Value::String("ok".into()));
            // Full windows are not the end of an account that can bill credits.
            m.insert("on_credits".into(), Value::Bool(q.can_serve_past_windows()));
            m.insert(
                "five_hour".into(),
                q.five_hour.as_ref().map(win).unwrap_or(Value::Null),
            );
            m.insert(
                "seven_day".into(),
                q.seven_day.as_ref().map(win).unwrap_or(Value::Null),
            );
            let scoped: Vec<Value> = q
                .scoped
                .iter()
                .map(|(n, w)| {
                    let mut wj = win(w);
                    wj.as_object_mut()
                        .unwrap()
                        .insert("label".into(), Value::String(n.clone()));
                    wj
                })
                .collect();
            m.insert("scoped".into(), Value::Array(scoped));
        }
        Fetch::Unauthorized => {
            m.insert("status".into(), Value::String("expired".into()));
        }
        Fetch::Unexpected(code, body) => {
            m.insert("status".into(), Value::String("unexpected".into()));
            m.insert("http".into(), Value::from(*code));
            m.insert("raw".into(), Value::String(body.clone()));
        }
        Fetch::Throttled => {
            m.insert("status".into(), Value::String("throttled".into()));
            m.insert(
                "note".into(),
                Value::String("the usage endpoint is rate-limited, not this account".into()),
            );
        }
        Fetch::Offline(msg) => {
            m.insert("status".into(), Value::String("offline".into()));
            m.insert("detail".into(), Value::String(msg.clone()));
        }
        Fetch::Coordination(msg) => {
            m.insert("status".into(), Value::String("unavailable".into()));
            m.insert("detail".into(), Value::String(msg.clone()));
        }
    }
    o
}

pub fn sessions(paths: &Paths, json: bool) -> Result<i32> {
    if json {
        // Scripting parity with the human view: {"accounts": {...}, "total": N}.
        // available=false distinguishes "no sessionwiki" from "zero sessions".
        let out = match crate::session_link::sessions_by_account(paths) {
            None => serde_json::json!({"available": false, "accounts": {}, "total": 0}),
            Some(counts) => {
                let total: usize = counts.values().sum();
                serde_json::json!({"available": true, "accounts": counts, "total": total})
            }
        };
        println!("{}", serde_json::to_string(&out)?);
        return Ok(0);
    }
    match crate::session_link::sessions_by_account(paths) {
        None => {
            println!(
                "session data unavailable - install sessionwiki to group sessions by account \
                 (`swapdex ui` already lists your recent sessions without it)"
            );
        }
        Some(counts) if counts.is_empty() => {
            // sessionwiki responded but its index is empty - the fresh-install
            // landmine. Say the one command that fixes it.
            println!("no sessions found (sessionwiki index empty - run `sessionwiki sync` once)");
        }
        Some(counts) => {
            for (account, n) in &counts {
                println!("{:<20} {n}", account);
            }
        }
    }
    Ok(0)
}

fn identity_line(id: &Account) -> String {
    let who = id.email.clone().unwrap_or_else(|| id.display.clone());
    match &id.tier {
        Some(t) => format!("{who} [{t}]"),
        None => who,
    }
}

fn expiry_note(expires_at: Option<i64>, tool: &str) -> String {
    // Codex is the exception the rest of this reasoning does not cover. Its
    // token lives about ten days, not an hour, and nothing renews it silently -
    // Codex renews only when Codex RUNS. So a lapsed Codex token is not noise
    // to be waited out; it is the reason turns are failing right now.
    if tool == "codex" {
        return match expires_at {
            Some(ms) if ms <= now_ms() => {
                " - login expired; `swapdex refresh` renews it (or run codex once)".to_string()
            }
            _ => String::new(),
        };
    }
    // expiresAt is epoch millis. An OAuth ACCESS token lapses about hourly and
    // the tool refreshes it silently, so "expired" for a just-lapsed token is
    // pure noise (this is the `status` twin of the 0.20.0 ls/marker fix that
    // this line was missed by). Only note a snapshot older than STALE_DAYS,
    // where the refresh token itself may be dead and a re-login is plausible.
    match expires_at {
        Some(ms) if now_ms() - ms > STALE_DAYS * 86400 * 1000 => {
            " - login is old; may re-prompt if its refresh token has expired".to_string()
        }
        _ => String::new(),
    }
}

/// The (account, refresh token) a Codex credential blob carries, when both read.
fn codex_cred_pair(bytes: &[u8]) -> Option<(String, String)> {
    let v: Value = serde_json::from_slice(bytes).ok()?;
    let t = v.get("tokens")?;
    Some((
        t["account_id"].as_str()?.to_string(),
        t["refresh_token"].as_str()?.to_string(),
    ))
}

/// Whether a rotation some live slot redeemed has already retired this
/// snapshot's refresh token.
///
/// These tokens are single-use: the server retires the outgoing one the moment
/// a holder redeems it. So two holders of ONE account that differ in the
/// refresh token are not two copies of a login - one of them is dead, and
/// restoring it hands the tool credentials it cannot renew. The slot need not
/// belong to this profile; what matters is that some slot redeemed a rotation
/// this copy did not get.
///
/// This is what the wall-clock staleness check cannot see. That one asks how
/// long ago the snapshot was written, and a rotation can retire a token minutes
/// later - a real machine sat six days between the rotation and the failure,
/// because the access token kept working until it lapsed and only the renewal
/// it then attempted was refused.
///
/// Claude and Codex both rotate, so both are checked. An unreadable file on
/// either side is not a verdict - a switch must never be blocked by something
/// that could not be parsed.
fn snapshot_rotated_away(paths: &Paths, target: &crate::adapters::Snapshot, tool: &str) -> bool {
    let Some((account, refresh)) = snapshot_cred_pair(target, tool) else {
        return false;
    };
    let Ok(slots) = crate::slots::Slots::open_for(paths, tool) else {
        return false;
    };
    slots.list().into_iter().any(|r| {
        slot_cred_pair(&r.config_dir, tool).is_some_and(|(a, rt)| a == account && rt != refresh)
    })
}

/// The (account, refresh token) a SNAPSHOT carries. Codex keeps both in one
/// blob; Claude splits them across two parts of the same snapshot.
fn snapshot_cred_pair(snap: &crate::adapters::Snapshot, tool: &str) -> Option<(String, String)> {
    match tool {
        "codex" => snap.part("auth").and_then(|s| codex_cred_pair(s.expose())),
        "claude-code" => {
            let id: Value = serde_json::from_slice(snap.part("oauth_account")?.expose()).ok()?;
            let cred: Value = serde_json::from_slice(snap.part("credentials")?.expose()).ok()?;
            claude_pair(&id["accountUuid"], &cred["claudeAiOauth"]["refreshToken"])
        }
        _ => None,
    }
}

/// The same pair, read out of a live slot directory.
fn slot_cred_pair(dir: &std::path::Path, tool: &str) -> Option<(String, String)> {
    match tool {
        "codex" => codex_cred_pair(&std::fs::read(dir.join("auth.json")).ok()?),
        "claude-code" => {
            let id: Value =
                serde_json::from_slice(&std::fs::read(dir.join(".claude.json")).ok()?).ok()?;
            let cred: Value =
                serde_json::from_slice(&std::fs::read(dir.join(".credentials.json")).ok()?).ok()?;
            claude_pair(
                &id["oauthAccount"]["accountUuid"],
                &cred["claudeAiOauth"]["refreshToken"],
            )
        }
        _ => None,
    }
}

fn claude_pair(account: &Value, refresh: &Value) -> Option<(String, String)> {
    let a = account.as_str().filter(|s| !s.is_empty())?;
    let r = refresh.as_str().filter(|s| !s.is_empty())?;
    Some((a.to_string(), r.to_string()))
}

fn warn_if_expired(target: &crate::adapters::Snapshot, tool: &str) {
    if !snapshot_is_stale(target, tool) {
        return;
    }
    let who = match tool {
        "claude-code" => "Claude",
        "codex" => "Codex",
        "gemini" => "Gemini",
        "antigravity" => "Antigravity",
        other => other,
    };
    eprintln!(
        "swapdex: note - this saved login is old; {who} may re-prompt for login if its \
         refresh token has expired"
    );
}

#[cfg(test)]
mod tests {
    use super::{
        best_identity, classify_migration_profile, codex_account_sources, codex_identity,
        codex_quota_lines, codex_row, codex_usage_row, home_note, keychain_verdict,
        last_slot_warning, listable, login_is_ancient, name_means_two_accounts, new_account_prompt,
        payer_line, payer_note, payer_of_any, pick_active, quota_brief, row_needs_login,
        row_suffix, sign_in_remedy, sign_out_blocked_remedy, stale_hint, stale_marker,
        stale_proxy_note, suggested_profile_name, switch_line, unhonoured_ask, unknown_account,
        win_line, MigrationClass,
    };

    fn s(items: &[&str]) -> Vec<String> {
        items.iter().map(|i| i.to_string()).collect()
    }

    #[test]
    fn cached_claude_numbers_keep_the_failed_refresh_reason_and_original_time() {
        use crate::quota_cache::Entry;
        use crate::tui::Usage;

        let mut readings = vec![
            (
                "expired".to_string(),
                Usage {
                    note: Some("login expired".into()),
                    ..Default::default()
                },
            ),
            (
                "throttled".to_string(),
                Usage {
                    note: Some("endpoint busy".into()),
                    ..Default::default()
                },
            ),
            (
                "offline".to_string(),
                Usage {
                    note: Some("network offline".into()),
                    ..Default::default()
                },
            ),
            (
                "current".to_string(),
                Usage {
                    five_h: Some(12.0),
                    ..Default::default()
                },
            ),
        ];
        let cached = ["expired", "throttled", "offline", "current"]
            .into_iter()
            .map(|name| {
                (
                    name.to_string(),
                    Entry {
                        five_h: Some(93.0),
                        at: 123,
                        on_credits: name == "throttled",
                        ..Default::default()
                    },
                )
            })
            .collect();
        super::merge_cached_claude_usage(&mut readings, cached);

        for (name, reason) in [
            ("expired", "login expired"),
            ("throttled", "endpoint busy"),
            ("offline", "network offline"),
        ] {
            let u = &readings.iter().find(|(n, _)| n == name).unwrap().1;
            assert_eq!(u.five_h, Some(93.0), "{name}");
            assert_eq!(u.observed_at, Some(123), "{name}");
            assert_eq!(u.note.as_deref(), Some(reason), "{name}");
        }
        assert!(
            readings
                .iter()
                .find(|(n, _)| n == "throttled")
                .unwrap()
                .1
                .on_credits
        );
        let current = &readings.iter().find(|(n, _)| n == "current").unwrap().1;
        assert_eq!(current.five_h, Some(12.0));
        assert_eq!(current.observed_at, None);
        assert_eq!(current.note, None);
    }

    #[test]
    fn migration_classifier_matches_accounts_before_names() {
        let slots = vec![
            ("same".to_string(), Some("account-a".to_string())),
            ("slot-b".to_string(), Some("account-b".to_string())),
            ("unknown".to_string(), None),
        ];

        assert_eq!(
            classify_migration_profile("same", Some("account-a"), &slots),
            MigrationClass::AlreadySlotted
        );
        assert_eq!(
            classify_migration_profile("copy", Some("account-b"), &slots),
            MigrationClass::CopyOfSlot("slot-b".to_string())
        );
        assert_eq!(
            classify_migration_profile("same", Some("account-b"), &slots),
            MigrationClass::CopyOfSlot("slot-b".to_string())
        );
        assert_eq!(
            classify_migration_profile("new", Some("account-c"), &slots),
            MigrationClass::NeedsSlot
        );
        assert_eq!(
            classify_migration_profile("broken", None, &slots),
            MigrationClass::Unreadable
        );
        assert_eq!(
            classify_migration_profile("empty", Some(""), &slots),
            MigrationClass::Unreadable
        );
    }

    #[test]
    fn win_line_shows_remaining_bar_and_reset() {
        let w = crate::quota::Window {
            used_pct: 61.0,
            resets_at: Some(2 * 3600 + 14 * 60),
        };
        // A clock, not a countdown: this output is written once and may be
        // read, scrolled back to, or piped long after. "resets in 2h 14m" is
        // true for one second; the time it names stays true.
        let line = win_line("5h", &w, 0);
        assert!(line.contains("39% left"), "{line}");
        assert!(line.contains("resets"), "{line}");
        assert!(
            line.contains("am") || line.contains("pm"),
            "the reset is a time: {line}"
        );
        assert!(!line.contains("in 2h"), "no countdown: {line}");
        let full = crate::quota::Window {
            used_pct: 0.0,
            resets_at: None,
        };
        let line = win_line("7d", &full, 0);
        assert!(line.contains("100% left"), "{line}");
        assert!(!line.contains("resets"), "no reset when absent: {line}");
    }

    /// The check fails two ways; the remedy named only one of them.
    ///
    /// `still_same || managed_present` - the account still resolving, or a
    /// credential still readable - and the message printed the browser-session
    /// story for both. On a machine blocked by the second, signing out at
    /// claude.ai does nothing at all, which is the worst kind of advice: it
    /// looks like a fix and costs the user a round trip to find out it is not.
    #[test]
    fn the_sign_out_remedy_names_the_check_that_actually_failed() {
        let browser = sign_out_blocked_remedy(true, "claude-code");
        assert!(
            browser.contains("claude.ai") || browser.contains("browser"),
            "the account is still signed in, so the session is the thing: {browser}"
        );

        let leftover = sign_out_blocked_remedy(false, "claude-code");
        assert!(
            leftover.contains("Keychain") || leftover.contains("doctor"),
            "a credential still readable is not a browser session: {leftover}"
        );
        assert!(
            !leftover.contains("claude.ai"),
            "and must not send them somewhere that cannot help: {leftover}"
        );
    }

    /// Removing the last slot takes every session with it, in silence.
    ///
    /// The proxy refuses a turn it has no slot for - "no account slots yet" -
    /// and sessions are pinned to its address, so the moment the last slot goes
    /// every one of them fails with a 502. `rm` says "stopped managing 'x'. its
    /// login is untouched", which is true and is not the part that matters.
    /// swapdex knows both halves already: the registry says how many remain, and
    /// the marker file says whether a proxy is running.
    #[test]
    fn removing_the_last_slot_says_what_it_costs() {
        let w = last_slot_warning(0, true, "claude-code")
            .expect("the last one, with a proxy running on it");
        assert!(w.contains("502") || w.contains("no account slots"), "{w}");
        assert!(
            w.contains("swapdex run") || w.contains("adopt"),
            "and how to get one back: {w}"
        );

        assert_eq!(
            last_slot_warning(1, true, "claude-code"),
            None,
            "another slot remains - the proxy still has something to serve"
        );
        assert_eq!(
            last_slot_warning(0, false, "claude-code"),
            None,
            "no proxy running - nothing is pinned to it, so nothing breaks"
        );
    }

    /// The listing shows one account and `use` selects the other.
    ///
    /// A name can be a saved profile AND a registered slot. `use <name>` sets the
    /// slot pointer, so the account it selects is the SLOT's; `ls` fills the row
    /// from the profile's snapshot. When those two hold different accounts the
    /// row names one account and switching produces the other, silently. swapdex
    /// already reports the harmless direction - "saved profile 'k' is a copy of
    /// slot 'y'", the same account under two names - and said nothing about this
    /// one.
    #[test]
    fn a_name_that_means_two_accounts_is_worth_saying() {
        assert!(name_means_two_accounts(Some("uuid-a"), Some("uuid-b")));
        assert!(
            !name_means_two_accounts(Some("uuid-a"), Some("uuid-a")),
            "the same account under one name is the ordinary case"
        );
        assert!(
            !name_means_two_accounts(Some("uuid-a"), None),
            "a profile with no slot of that name is not a conflict"
        );
        assert!(
            !name_means_two_accounts(None, Some("uuid-b")),
            "nor a slot with no profile"
        );
        assert!(
            !name_means_two_accounts(None, None),
            "and unknown is never a conflict - swapdex does not condemn on a blank"
        );
    }

    /// The boundary the other two paths already use.
    #[test]
    fn a_login_is_only_ancient_past_the_stale_window() {
        let day = 86_400_000i64;
        let now = 1_800_000_000_000i64;
        assert_eq!(login_is_ancient(None, now), None, "no deadline, no verdict");
        assert_eq!(
            login_is_ancient(Some(now - 3_600_000), now),
            Some(false),
            "an hour ago is the ordinary state of a working login"
        );
        assert_eq!(
            login_is_ancient(Some(now - 29 * day), now),
            Some(false),
            "still inside the window"
        );
        assert_eq!(
            login_is_ancient(Some(now - 31 * day), now),
            Some(true),
            "past it the refresh token may be gone"
        );
    }

    /// A proxy that never picked up the upgrade is reported as healthy.
    ///
    /// `install_verdict`'s own note already says a hand-started proxy "never
    /// picked up an upgrade"; nothing checked for it. On a real machine the
    /// Codex proxy ran five days on the build from BEFORE the fix for the very
    /// symptom being reported, and `doctor` said "installed and running". The
    /// build id is already written down beside the pid - only the comparison was
    /// missing.
    #[test]
    fn a_proxy_running_an_older_build_is_not_called_healthy() {
        let note = stale_proxy_note("0.141.0-1788417540", "0.153.0-1788850863", "codex")
            .expect("an older build is worth saying out loud");
        assert!(note.contains("0.141.0"), "names what is running: {note}");
        assert!(note.contains("0.153.0"), "and what would start now: {note}");
        assert!(
            note.contains("swapdex service install --tool codex"),
            "and the command that replaces it: {note}"
        );

        assert_eq!(
            stale_proxy_note("0.153.0-1788850863", "0.153.0-1788850863", "codex"),
            None,
            "the current build is not news"
        );
        assert_eq!(
            stale_proxy_note("", "0.153.0-1788850863", "codex"),
            None,
            "a marker with no build id says nothing about age"
        );
    }

    /// Two builds of the SAME version are the case the table skipped.
    ///
    /// The comparison is on the build id and the sentence printed only the
    /// version, so `doctor` rendered "running 0.165.9 while this swapdex is
    /// 0.165.9" - it contrasts two values and prints them identically, leaving
    /// nothing to act on. Seen on a machine with the npm install and a local
    /// build of one version, which is the shape `one installer per machine`
    /// exists to warn about.
    #[test]
    fn a_different_build_of_one_version_says_what_actually_differs() {
        let note = stale_proxy_note("0.165.9-1700000000", "0.165.9-1800000000", "codex")
            .expect("a different build is still a different build");
        assert!(
            !note.contains("running 0.165.9 while this swapdex is 0.165.9"),
            "the sentence contrasts two values it prints identically: {note}"
        );
        assert!(
            note.contains("0.165.9"),
            "the version is still worth naming: {note}"
        );
        assert!(
            note.contains("swapdex service install --tool codex"),
            "and the command that replaces it: {note}"
        );
    }

    /// The dashboard's "add an account" prompt offered the account you are leaving.
    ///
    /// Pressing `a` leaves the dashboard and asks for a name, and the only
    /// identity to hand there is the CURRENT login - the one the new account is
    /// meant to sit beside. On a real machine that name was already saved, so
    /// Enter answered "'bsgong' already exists - replace it? [y/N]" instead of
    /// adding anything, every time, because the suggestion never changed.
    #[test]
    fn the_new_account_prompt_does_not_offer_the_account_you_are_leaving() {
        let p = new_account_prompt();
        assert!(
            !p.contains('['),
            "no default, because the only one available is the wrong account: {p}"
        );
        assert!(
            p.contains("e.g."),
            "it still says what shape a name takes: {p}"
        );
    }

    /// The dashboard's name box and the CLI's name prompt ask the same question.
    ///
    /// The CLI computed a suggestion from the live login and took Enter as
    /// acceptance; the dashboard opened the same question with an empty box, and
    /// an empty box plus Enter closes without a word - which its own note already
    /// records people doing. One function now, so the answer cannot exist in one
    /// place and not the other.
    #[test]
    fn the_name_to_offer_comes_from_the_login_you_are_signed_into() {
        let dir = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(dir.path());
        // Nobody signed in: a name is still offered, because the box has to
        // start somewhere.
        assert_eq!(suggested_profile_name(&paths), "account");

        std::fs::create_dir_all(dir.path().join(".claude")).unwrap();
        std::fs::write(
            dir.path().join(".claude/.credentials.json"),
            br#"{"claudeAiOauth":{"accessToken":"T","expiresAt":9999999999000}}"#,
        )
        .unwrap();
        std::fs::write(
            dir.path().join(".claude.json"),
            br#"{"oauthAccount":{"accountUuid":"u","emailAddress":"you@example.com"}}"#,
        )
        .unwrap();
        assert_eq!(
            suggested_profile_name(&paths),
            "you",
            "the local part of the address you are signed in as"
        );
    }

    /// The two row builders asked this question differently, and the lossy one
    /// won on any account with both a profile and a slot: `rnd` said "no login"
    /// beside its own live usage figures, because a Keychain that would not open
    /// read as an account nobody had signed into. One helper now, so they cannot
    /// drift apart again.
    #[test]
    fn a_row_with_a_readable_login_does_not_ask_for_one() {
        let dir = tempfile::tempdir().unwrap();
        // Nothing there yet: it needs a login, and says so.
        assert!(row_needs_login(
            &crate::paths::Paths::rooted(dir.path()),
            "claude-code",
            Some(dir.path())
        ));
        // A credential in the slot: nothing to ask for.
        std::fs::write(
            dir.path().join(".credentials.json"),
            br#"{"claudeAiOauth":{"accessToken":"T"}}"#,
        )
        .unwrap();
        assert!(!row_needs_login(
            &crate::paths::Paths::rooted(dir.path()),
            "claude-code",
            Some(dir.path())
        ));
        // A row with no slot behind it has nothing to sign into.
        assert!(!row_needs_login(
            &crate::paths::Paths::rooted(std::path::Path::new("/nonexistent")),
            "claude-code",
            None
        ));
    }

    /// Codex prints the provider name and nothing else about identity, so that
    /// one field has to answer "which account am I on". It carried the SLOT
    /// NAME - `swapdex: work` - which is a label its owner chose and says
    /// nothing about the login being billed. Its owner asked exactly that question
    /// looking straight at the line meant to answer it.
    #[test]
    fn the_payer_line_names_the_account_not_just_the_slot() {
        assert_eq!(
            payer_line("work", Some("work@example.com"), true),
            "work (work@example.com)"
        );
        // No email to show (Codex slot never signed in, or Claude before its
        // first read): the name alone, never a blank or a lie.
        assert_eq!(payer_line("work", None, true), "work");
        // A name that IS the address does not repeat itself.
        assert_eq!(payer_line("me@x.com", Some("me@x.com"), true), "me@x.com");
        // The state still rides along, in the shape callers already read.
        assert_eq!(
            payer_line("work", Some("a@b.c"), false),
            "work (a@b.c, no login)"
        );
        assert_eq!(payer_line("work", None, false), "work (no login)");
    }

    /// Two pointers on purpose - `serve` decides who pays, `use` decides where
    /// sessions live - but Codex shows ONE field, so a session billed to `work`
    /// while its history piled up in `codex-main` read as though it were running
    /// as `work`. Its owner asked whether it had actually gone into that slot.
    #[test]
    fn the_home_is_named_only_when_it_differs_from_the_payer() {
        assert_eq!(home_note("work", Some("codex-main")), " - home: codex-main");
        assert_eq!(
            home_note("work", Some("work")),
            "",
            "nothing to disambiguate when they agree"
        );
        assert_eq!(home_note("work", None), "", "no pointer, nothing to say");
    }

    /// A Codex account can be a slot OR a saved snapshot, and the report used
    /// to walk slots only - so a machine that keeps its accounts as snapshots
    /// got no Codex section at all, and not a word saying why. Found on a real
    /// one: `swapdex ls` listed three Codex accounts and `swapdex quota`
    /// printed nothing about any of them.
    #[test]
    fn codex_accounts_are_gathered_from_slots_and_snapshots_alike() {
        let got = codex_account_sources(
            &[("live".into(), std::path::PathBuf::from("/slots/live"))],
            &["saved".into(), "live".into()],
        );
        let names: Vec<&str> = got.iter().map(|(n, _)| n.as_str()).collect();
        assert!(names.contains(&"live"), "{names:?}");
        assert!(
            names.contains(&"saved"),
            "a snapshot is an account too: {names:?}"
        );
        // An account held both ways is one account, listed once - and the slot
        // is the live copy, so it wins.
        assert_eq!(names.iter().filter(|n| **n == "live").count(), 1);
        assert!(
            got.iter().any(|(n, src)| n == "live" && src.is_some()),
            "the slot keeps its directory: {got:?}"
        );
        assert!(
            got.iter().any(|(n, src)| n == "saved" && src.is_none()),
            "a snapshot has no directory to read: {got:?}"
        );
    }

    /// The status bar needs the payer's remaining quota without a network call.
    ///
    /// Going through the proxy costs the tool its own `rate_limits` block, so a
    /// status line that reads them prints "weekly N/A | 5h N/A" while swapdex
    /// holds a reading from a minute ago. That reading should be available
    /// instantly - a bar redraws constantly and cannot wait on a request.
    #[test]
    fn the_payer_quota_renders_from_cache_without_a_request() {
        assert_eq!(quota_brief(Some(17.0), Some(98.0)), "5h 83% | 7d 2%");
        // One window unknown: report the one that is known.
        assert_eq!(quota_brief(None, Some(50.0)), "7d 50%");
        assert_eq!(quota_brief(Some(0.0), None), "5h 100%");
        // Nothing measured: empty, so the bar can omit the segment entirely
        // rather than print a placeholder that looks like a reading.
        // Silence here is indistinguishable from a broken status bar - which is
        // exactly how it read when the numbers stopped appearing.
        assert_eq!(quota_brief(None, None), "usage unread");
    }

    /// Whoever pays for ANY tool gets marked, not just Claude's payer.
    ///
    /// `ls` asked `Slots::open_for(paths, "claude-code")` who pays, so serving a
    /// Codex account moved the turns correctly and the listing marked nobody -
    /// the same "the switch did nothing" appearance that was fixed for Claude in
    /// 0.80.0, still live on the Codex side.
    #[test]
    fn a_payer_of_any_tool_is_marked() {
        // Claude pays: as before.
        assert_eq!(
            payer_of_any(&[("claude-code", Some("alpha")), ("codex", None)]).as_deref(),
            Some("alpha")
        );
        // Only Codex has a payer: it gets marked.
        assert_eq!(
            payer_of_any(&[("claude-code", None), ("codex", Some("cx"))]).as_deref(),
            Some("cx")
        );
        // Both: Claude's answer is the one a single mark can carry, and it is
        // the tool `ls` is otherwise about.
        assert_eq!(
            payer_of_any(&[("claude-code", Some("alpha")), ("codex", Some("cx"))]).as_deref(),
            Some("alpha")
        );
        // Nobody: nothing marked.
        assert_eq!(
            payer_of_any(&[("claude-code", None), ("codex", None)]),
            None
        );
        assert_eq!(payer_of_any(&[]), None);
    }

    /// The remedy must name the TOOL, or it sends the reader to the wrong one.
    ///
    /// 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 advice has to carry the tool it
    /// is about.
    #[test]
    fn the_sign_in_remedy_names_the_tool() {
        assert_eq!(
            sign_in_remedy("codex-test", "codex"),
            "`swapdex run codex-test --tool codex` signs it in once"
        );
        // Claude is the default, so naming it would be noise.
        assert_eq!(
            sign_in_remedy("alpha", "claude-code"),
            "`swapdex run alpha` signs it in once"
        );
        assert_eq!(
            sign_in_remedy("g", "gemini"),
            "`swapdex run g --tool gemini` signs it in once"
        );
    }

    /// A name that does not match should show the names that do.
    ///
    /// A typo answered "no account named 'alicee' - `swapdex ui` lists them",
    /// sending the user to open another screen to read four words. The list is
    /// right there; and when one candidate is an obvious near-miss, saying so
    /// is the whole answer.
    #[test]
    fn a_wrong_name_is_answered_with_the_right_ones() {
        // Near-miss: name it, because that is almost certainly the intent.
        assert_eq!(
            unknown_account("alicee", &["alice", "bob"]),
            "no account named 'alicee' - did you mean 'alice'? (also: bob)"
        );
        // No near-miss: just list them.
        assert_eq!(
            unknown_account("zzz", &["alice", "bob"]),
            "no account named 'zzz' - you have: alice, bob"
        );
        // Nothing saved at all: say that, not an empty list.
        assert_eq!(
            unknown_account("alice", &[]),
            "no accounts saved yet - `swapdex add <name>` saves the login you are on"
        );
    }

    /// Switching should not need a second command to confirm it.
    ///
    /// `serve rnd` printed "turns -> rnd" and two lines of explanation, and
    /// said nothing about the account itself - so every switch was followed by
    /// `ls` to see whether it took, and by `usage` to see whether that account
    /// had any room. The confirmation belongs in the switch.
    #[test]
    fn a_switch_confirms_itself_with_the_account_it_moved_to() {
        // Identity and room both known: one line carries both.
        assert_eq!(
            switch_line("rnd", Some("rnd@x.com"), Some(68.0)),
            "now rnd (rnd@x.com) - 68% of the week left"
        );
        // Room unknown - never measured, or the window has not been read.
        // Say the identity and stay silent about what is not known.
        assert_eq!(
            switch_line("rnd", Some("rnd@x.com"), None),
            "now rnd (rnd@x.com)"
        );
        // A slot with no config to name it: the name is all there is.
        assert_eq!(
            switch_line("bsgong", None, Some(12.0)),
            "now bsgong - 12% of the week left"
        );
        assert_eq!(switch_line("bsgong", None, None), "now bsgong");
        // Spent: worth saying plainly rather than printing "0% left".
        assert_eq!(
            switch_line("kong", Some("k@x.com"), Some(0.0)),
            "now kong (k@x.com) - no week left"
        );
    }

    /// An account listed from its slot still shows whose it is.
    ///
    /// Identity was read from the saved snapshot only, so an account that
    /// exists as a slot and was never snapshotted had an empty name column -
    /// the row was there and switching worked, but there was no way to tell
    /// which login it was. The slot's own `.claude.json` says.
    #[test]
    fn a_slot_only_account_still_shows_its_email() {
        // Snapshot knows: that answer stands.
        assert_eq!(
            best_identity(Some("snap@x.com".into()), Some("slot@x.com".into())).as_deref(),
            Some("snap@x.com")
        );
        // Snapshot silent, slot knows: use the slot.
        assert_eq!(
            best_identity(None, Some("slot@x.com".into())).as_deref(),
            Some("slot@x.com")
        );
        // Neither knows: still nothing, rather than a guess.
        assert_eq!(best_identity(None, None), None);
    }

    /// Every switchable account needs a row, or a switch to it shows nothing.
    ///
    /// `ls` listed saved snapshots only. On a machine whose accounts live as
    /// SLOTS, `serve personal` moved the turns correctly and the list had no
    /// row for `personal` at all - so the mark saying who pays had nowhere to
    /// appear, and two of three switches looked like they did nothing.
    #[test]
    fn every_switchable_account_gets_a_row() {
        // Snapshots and slots are merged, and neither is listed twice.
        assert_eq!(
            listable(&["claude", "rnd", "work"], &["rnd", "personal", "bsgong"]),
            vec!["bsgong", "claude", "personal", "rnd", "work"]
        );
        // Slots only: still a full list.
        assert_eq!(listable(&[], &["personal"]), vec!["personal"]);
        // Snapshots only: unchanged from before.
        assert_eq!(listable(&["claude"], &[]), vec!["claude"]);
        assert!(listable(&[], &[]).is_empty());
    }

    /// The list must show the switch that was just made.
    ///
    /// `serve rnd` says "turns -> rnd", and then `ls` starred a different
    /// account - the one holding the login on disk - with the paying account
    /// named nowhere. Switching looked like it had not taken, which is exactly
    /// what its owner concluded, repeatedly.
    #[test]
    fn the_list_shows_which_account_pays() {
        // Signed in as kong, paying with rnd: the row for rnd says so.
        assert_eq!(row_suffix("rnd", Some("kong"), Some("rnd")), Some("pays"));
        // ...and the row for kong is not marked as paying.
        assert_eq!(row_suffix("kong", Some("kong"), Some("rnd")), None);
        // The payer is marked EVEN WHEN it also holds the login. Suppressing
        // it there meant that of three accounts, switching to one of them
        // produced no visible change at all - reading as that switch failing.
        assert_eq!(row_suffix("kong", Some("kong"), Some("kong")), Some("pays"));
        // Nothing paying (no proxy): nothing to say.
        assert_eq!(row_suffix("kong", Some("kong"), None), None);
        // A row that is neither is never marked.
        assert_eq!(row_suffix("bsgong", Some("kong"), Some("rnd")), None);
    }

    /// `ls` marks the account Claude is signed in AS. When a proxy is paying
    /// with a different one, that mark is true and misleading at once: the
    /// owner switched to bsgong, the proxy served every turn from bsgong, and
    /// the list went on starring kong because that is whose login the tool
    /// holds locally. Both facts are real; showing only one reads as the switch
    /// having failed.
    #[test]
    fn the_list_separates_who_is_signed_in_from_who_pays() {
        // Different accounts: both are named, and which is which is explicit.
        assert_eq!(
            payer_note(Some("kong"), Some("bsgong")).as_deref(),
            Some("bsgong pays")
        );
        // The same account: nothing to disambiguate, so nothing is added.
        assert_eq!(payer_note(Some("kong"), Some("kong")), None);
        // No proxy paying: the login is the whole story.
        assert_eq!(payer_note(Some("kong"), None), None);
        // Signed into nothing, but a proxy is paying - still worth saying.
        assert_eq!(
            payer_note(None, Some("bsgong")).as_deref(),
            Some("bsgong pays")
        );
    }

    /// Naming the stale tool was half the job: the reader still has to know
    /// what to DO. `add --update` re-saves a snapshot from a live login, which
    /// is no help when the login itself is what has lapsed - the tool has to be
    /// signed into first, and that is per-tool.
    ///
    /// It also has to say the account is still usable for its OTHER tools,
    /// because a lone marker beside an account reads as "this account is
    /// broken" when Claude and Codex are working perfectly well.
    #[test]
    fn a_stale_hint_says_what_to_do_per_tool_and_what_still_works() {
        let h = stale_hint(&["gemini", "antigravity"], &["claude-code", "codex"]);
        assert!(h.contains("gemini"), "{h}");
        assert!(h.contains("antigravity"), "{h}");
        // Re-saving alone is not offered as the fix: running the tool comes
        // first, because that is what can produce a fresh login. (It used to
        // assert that re-saving "cannot refresh a login that has already
        // lapsed" - true only if it HAS lapsed, which is the thing swapdex
        // cannot know and `status` is careful not to claim.)
        assert!(
            h.contains("run that tool once"),
            "signing the tool in is the first step: {h}"
        );
        let (run_at, save_at) = (
            h.find("run that tool once").unwrap(),
            h.find("add --update").expect("and re-saving is the second"),
        );
        assert!(run_at < save_at, "in that order: {h}");
        // And it says the account still serves its healthy tools.
        assert!(
            h.contains("claude-code") && h.contains("codex"),
            "must say what still works: {h}"
        );
    }

    /// Nothing stale, nothing said.
    #[test]
    fn no_stale_tool_means_no_hint() {
        assert!(stale_hint(&[], &["claude-code"]).is_empty());
    }

    /// It says the token is dead; it only knows the copy is old.
    ///
    /// `status`, looking at the same account, hedges - "login is old; MAY
    /// re-prompt if its refresh token has expired" - and `profile_detail`'s own
    /// note says the refresh token "may have rotated". Only the line the user
    /// actually reads asserted the lapse as fact, next to a Codex login that was
    /// answering the server perfectly well, which reads as "this account is
    /// broken" about one that works.
    #[test]
    fn the_stale_hint_does_not_assert_a_lapse_it_cannot_know() {
        let h = stale_hint(&["g-cli"], &["codex"]);
        assert!(h.contains("g-cli"), "{h}");
        assert!(
            h.contains("may"),
            "what is known is that the copy is old, not that the token is dead: {h}"
        );
        assert!(
            !h.contains("has already lapsed"),
            "a lapse swapdex has not established: {h}"
        );
        // The reassurance still has to be there: this is the line that stops an
        // old login from reading as a broken account.
        assert!(h.contains("still serves codex"), "{h}");
    }

    /// Every tool stale: there is nothing to reassure the reader about, and
    /// claiming otherwise would be the opposite failure.
    #[test]
    fn all_tools_stale_promises_nothing() {
        let h = stale_hint(&["gemini"], &[]);
        assert!(h.contains("gemini"), "{h}");
        assert!(!h.contains("still"), "nothing is still working: {h}");
    }

    /// One tool going stale is not the account going stale. A profile holding
    /// four logins was marked `(stale)` whole because gemini had not been
    /// refreshed in 37 days, while the Codex login added minutes earlier
    /// answered the server perfectly well - so the row said "unusable" about an
    /// account that was working.
    #[test]
    fn a_stale_marker_names_the_tool_it_belongs_to() {
        assert_eq!(
            stale_marker(&[("claude-code", None), ("gemini", Some("stale"))]).as_deref(),
            Some("gemini stale"),
            "name the one that is stale, not the account"
        );
        // Several: named together, so the reader knows the whole extent.
        assert_eq!(
            stale_marker(&[("gemini", Some("stale")), ("codex", Some("expired"))]).as_deref(),
            Some("gemini stale, codex expired")
        );
        // Every tool stale IS the account being stale, and says so plainly.
        assert_eq!(
            stale_marker(&[("gemini", Some("stale")), ("codex", Some("stale"))]).as_deref(),
            Some("gemini stale, codex stale")
        );
        // Nothing wrong: nothing said.
        assert_eq!(stale_marker(&[("claude-code", None)]), None);
        assert_eq!(stale_marker(&[]), None);
    }

    /// Everything the endpoint says that a one-line row has no room for: the
    /// per-model windows, the credit balance, and the refusal reason.
    #[test]
    fn the_codex_report_prints_what_a_row_cannot_hold() {
        let w = |pct: f64, mins: i64| crate::codex_limits::Window {
            used_pct: pct,
            window_minutes: mins,
            resets_at: Some(1_787_196_620),
        };
        let a = crate::codex_usage::Account {
            email: Some("someone@example.com".into()),
            plan: Some("pro".into()),
            limits: crate::codex_limits::Limits {
                short: Some(w(84.0, 10080)),
                long: None,
                observed_at: None,
            },
            scoped: vec![("GPT-5.3-Codex-Spark".into(), w(40.0, 10080))],
            credits: Some(crate::codex_usage::Credits {
                has_credits: false,
                unlimited: false,
                overage_limit_reached: false,
                balance: Some("0".into()),
            }),
            refused: Some("workspace_member_credits_depleted".into()),
        };
        let out = codex_quota_lines(&a, 1_786_600_000).join("\n");

        // The plan window, labelled by its LENGTH rather than by which field
        // carried it.
        assert!(out.contains("7d"), "{out}");
        assert!(!out.contains("5h"), "a window Codex did not send: {out}");
        // The per-model window, under the name the endpoint gave it.
        assert!(out.contains("GPT-5.3-Codex-Spark"), "{out}");
        // Every bar starts at one column, whatever the labels' lengths.
        let starts: Vec<_> = out
            .lines()
            .filter(|l| l.contains('\u{2593}') || l.contains('\u{2591}'))
            .map(|l| l.find(['\u{2593}', '\u{2591}']).unwrap())
            .collect();
        assert_eq!(starts.len(), 2, "{out}");
        assert_eq!(starts[0], starts[1], "bars must line up: {out}");
        // A balance of zero is a fact worth printing: it is the difference
        // between a full window being a pause and being the end.
        assert!(out.contains("no credits"), "{out}");
        // And who can clear the refusal.
        assert!(out.contains("its owner has to top them up"), "{out}");
    }

    /// Silence is not the same as good news. An account the endpoint said
    /// nothing about must not print a reassuring blank.
    #[test]
    fn a_codex_report_with_no_windows_says_so() {
        let a = crate::codex_usage::Account::default();
        let out = codex_quota_lines(&a, 1_786_600_000).join("\n");
        assert!(out.contains("no windows"), "{out}");
        // Nothing was said about credits, so nothing is claimed about them.
        assert!(!out.contains("credits"), "{out}");
    }

    /// Asking for an account and getting it are different things. The ask wins
    /// at first, so pressing Enter shows the choice immediately instead of
    /// lagging a turn behind. But when the proxy has SERVED someone else since
    /// the ask, the ask did not take - and a row that goes on naming it is
    /// telling the user their key worked when it did not.
    ///
    /// Seen on a real machine: `rnd` was asked for at 13:45, every turn after
    /// went to `bsgong` because rnd refuses on overage, and the dashboard said
    /// `rnd active 95% left` for half an hour.
    #[test]
    fn reality_outranks_the_ask_once_the_proxy_has_acted_on_it() {
        let ask = || Some("rnd".to_string());
        let did = || Some("bsgong".to_string());

        // Just asked, proxy has not served since: show the choice.
        assert_eq!(
            pick_active(ask(), did(), None, false).as_deref(),
            Some("rnd")
        );
        // The proxy served someone else AFTER the ask: that is what is happening.
        assert_eq!(
            pick_active(ask(), did(), None, true).as_deref(),
            Some("bsgong")
        );
        // Agreement needs no adjudication.
        assert_eq!(
            pick_active(ask(), ask(), None, true).as_deref(),
            Some("rnd")
        );
        // Nobody asked: the proxy's own record is the only answer there is.
        assert_eq!(
            pick_active(None, did(), Some("x".into()), false).as_deref(),
            Some("bsgong")
        );
        // Nothing anywhere: fall back to where sessions start.
        assert_eq!(
            pick_active(None, None, Some("x".into()), false).as_deref(),
            Some("x")
        );
    }

    /// And the divergence is stated, not merely resolved silently: the user
    /// asked for something and needs to know it is not happening, and why the
    /// screen names a different account than the one they picked.
    #[test]
    fn a_thwarted_ask_is_said_out_loud() {
        assert_eq!(
            unhonoured_ask(Some("rnd"), Some("bsgong"), true).as_deref(),
            Some("asked for rnd - it cannot serve, so turns are going to bsgong")
        );
        // Honoured, or not yet acted on: nothing to say.
        assert_eq!(unhonoured_ask(Some("rnd"), Some("bsgong"), false), None);
        assert_eq!(unhonoured_ask(Some("rnd"), Some("rnd"), true), None);
        assert_eq!(unhonoured_ask(None, Some("bsgong"), true), None);
    }

    /// The endpoint says whose token this is; the local `id_token` says whose
    /// the home believes it is. When they disagree the LIVE answer is the true
    /// one, and the disagreement itself is the news - it is the shape of the
    /// identity mix-up where signing in as one account leaves another connected.
    #[test]
    fn a_live_identity_outranks_the_saved_one_and_a_mismatch_is_reported() {
        assert_eq!(
            codex_identity(Some("a@example.com"), Some("pro"), Some("a@example.com")),
            "a@example.com [pro]"
        );
        assert_eq!(
            codex_identity(
                Some("live@example.com"),
                Some("pro"),
                Some("saved@example.com")
            ),
            "live@example.com [pro] (saved as saved@example.com)"
        );

        // With no live answer the saved label stands, unqualified - it is all
        // there is, and marking it as suspect would be inventing a doubt.
        assert_eq!(
            codex_identity(None, None, Some("saved@example.com")),
            "saved@example.com"
        );

        // A live answer with no saved one to compare is not a mismatch.
        assert_eq!(
            codex_identity(Some("live@example.com"), None, None),
            "live@example.com"
        );

        // The plan is the column Codex rows have always left empty; the
        // endpoint is the only thing that has ever stated it.
        assert!(codex_identity(Some("a@example.com"), Some("pro"), None).ends_with("[pro]"));
    }

    /// A reading the proxy took carries the refusal and the credits it came
    /// with, not just the numbers. Dropping them left a row able to say an
    /// account was refusing and unable to say what would clear it.
    #[test]
    fn a_proxy_reading_brings_its_reason_and_its_credits_along() {
        let seen = crate::quota_cache::Entry {
            seven_d: Some(100.0),
            at: 1_786_590_000,
            on_credits: true,
            refused: Some("out of quota".into()),
            ..Default::default()
        };
        let (_, u) =
            codex_row("work", None, None, Some(seen), None, 1_786_600_000).expect("a reading");
        assert_eq!(u.note.as_deref(), Some("out of quota"));
        assert!(u.on_credits);
    }

    /// Three sources can answer, and between the two LOCAL ones the newer wins
    /// rather than a fixed rank. A reading the proxy took off a response is
    /// bound to the account that served the turn; a transcript is bound to the
    /// home. Both are honest, and the stale one is simply older.
    #[test]
    fn between_two_local_readings_the_newer_one_answers() {
        let w = |pct: f64| crate::codex_limits::Window {
            used_pct: pct,
            window_minutes: 10080,
            resets_at: Some(1_787_011_538),
        };
        let transcript = crate::codex_limits::Limits {
            short: Some(w(12.0)),
            long: None,
            observed_at: Some(1_786_500_000),
        };
        let seen_by_proxy = crate::quota_cache::Entry {
            seven_d: Some(55.0),
            seven_d_reset: Some(1_787_011_538),
            at: 1_786_590_000,
            ..Default::default()
        };
        let now = 1_786_600_000;

        // The proxy saw it more recently than the transcript was written.
        let (_, u) = codex_row(
            "work",
            None,
            None,
            Some(seen_by_proxy.clone()),
            Some(transcript),
            now,
        )
        .expect("a reading");
        assert_eq!(u.seven_d, Some(55.0));
        assert_eq!(u.observed_at, Some(1_786_590_000));

        // ... and when the transcript is the newer of the two, it answers.
        let older_proxy = crate::quota_cache::Entry {
            at: 1_786_400_000,
            ..seen_by_proxy.clone()
        };
        let (_, u) = codex_row(
            "work",
            None,
            None,
            Some(older_proxy.clone()),
            Some(transcript),
            now,
        )
        .expect("a reading");
        assert_eq!(u.seven_d, Some(12.0));

        // A proxy reading alone still answers - this is the source that works
        // for a home holding no transcripts while the machine is offline.
        let (_, u) = codex_row("work", None, None, Some(seen_by_proxy.clone()), None, now)
            .expect("a reading");
        assert_eq!(u.seven_d, Some(55.0));

        // The live endpoint outranks both, being taken just now.
        let live = crate::codex_usage::Account {
            limits: crate::codex_limits::Limits {
                short: Some(w(84.0)),
                long: None,
                observed_at: None,
            },
            ..Default::default()
        };
        let (_, u) = codex_row(
            "work",
            Some(&live),
            None,
            Some(seen_by_proxy.clone()),
            Some(transcript),
            now,
        )
        .expect("a reading");
        assert_eq!(u.seven_d, Some(84.0));
        assert_eq!(u.observed_at, Some(now));
    }

    /// A live answer from the account beats a transcript, and the transcript
    /// still answers when there is no live one. An account with neither is
    /// absent rather than shown at zero - zero is a number, and it would read
    /// as a full account sitting idle.
    #[test]
    fn a_live_reading_wins_over_a_transcript_and_a_transcript_over_nothing() {
        let w = |pct: f64| crate::codex_limits::Window {
            used_pct: pct,
            window_minutes: 10080,
            resets_at: Some(1_787_011_538),
        };
        let live = crate::codex_usage::Account {
            email: Some("someone@example.com".into()),
            limits: crate::codex_limits::Limits {
                short: Some(w(84.0)),
                long: None,
                observed_at: None,
            },
            ..Default::default()
        };
        let stale = crate::codex_limits::Limits {
            short: Some(w(12.0)),
            long: None,
            observed_at: Some(1_786_000_000),
        };
        let now = 1_786_600_000;

        let (who, u) =
            codex_row("work", Some(&live), None, None, Some(stale), now).expect("live answers");
        assert_eq!(who, "work");
        assert_eq!(u.seven_d, Some(84.0));
        // A live answer is stamped now, not left to inherit the transcript age.
        assert_eq!(u.observed_at, Some(now));

        let (_, u) =
            codex_row("work", None, None, None, Some(stale), now).expect("transcript answers");
        assert_eq!(u.seven_d, Some(12.0));
        assert_eq!(u.observed_at, Some(1_786_000_000));

        // The case this whole change exists for: a home with no transcripts at
        // all, whose account can still answer for itself.
        let (_, u) =
            codex_row("work", Some(&live), None, None, None, now).expect("live alone answers");
        assert_eq!(u.seven_d, Some(84.0));

        assert!(codex_row("work", None, None, None, None, now).is_none());
    }

    /// A Codex reading is keyed by the home it was read from, and by nothing
    /// else. The previous version captioned it with whoever the switch timeline
    /// said was paying, which put a reading on an account holding no transcripts
    /// while the one holding every transcript showed none. Passing the home as the
    /// only argument is what makes that impossible to reintroduce here. A live
    /// reading from `codex_usage` names its own account and needs no such care;
    /// it comes through here only to share one shape with the transcript path.
    #[test]
    fn a_codex_reading_is_keyed_by_the_home_it_came_from() {
        let l = crate::codex_limits::Limits {
            short: None,
            long: Some(crate::codex_limits::Window {
                used_pct: 45.0,
                window_minutes: 10080,
                resets_at: Some(1_787_011_538),
            }),
            observed_at: Some(1_786_600_000),
        };
        let (who, u) = codex_usage_row("codex-main", &l);
        assert_eq!(who, "codex-main");
        // A weekly-only reading fills the weekly column and leaves 5h empty,
        // rather than being forced into the session slot.
        assert_eq!(u.seven_d, Some(45.0));
        assert_eq!(u.five_h, None);
        assert_eq!(u.seven_d_reset, Some(1_787_011_538));
    }

    const BARE: &str = "Claude Code-credentials";

    // The real-world multi-profile layout (one user, three CLAUDE_CONFIG_DIR
    // profiles): bare + two suffixed items, all LIVE logins.
    fn three_profiles() -> Vec<String> {
        s(&[
            BARE,
            "Claude Code-credentials-5953ba74",
            "Claude Code-credentials-feeb5ea6",
        ])
    }

    #[test]
    fn keychain_verdict_silent_when_no_item() {
        assert!(
            keychain_verdict(&[], Some(BARE), BARE).is_none(),
            "nothing to report if Claude has no Keychain item"
        );
    }

    #[test]
    fn keychain_verdict_manages_own_env_profile_among_aliased_siblings() {
        // No env -> swapdex manages the bare item; the suffixed items are
        // OTHER profiles (claude-work aliases) and must be called that - not
        // "stale strays" to delete.
        let (ok, msg) = keychain_verdict(&three_profiles(), Some(BARE), BARE).unwrap();
        assert!(ok, "coexisting aliased profiles are healthy: {msg}");
        assert!(msg.contains("other CLAUDE_CONFIG_DIR profiles"), "{msg}");
        assert!(msg.contains("never touches"), "{msg}");
    }

    #[test]
    fn keychain_verdict_single_profile_is_plain_ok() {
        let (ok, msg) = keychain_verdict(&s(&[BARE]), Some(BARE), BARE).unwrap();
        assert!(ok);
        assert!(msg.contains("managing this environment's profile"), "{msg}");
    }

    // Device-code login policy: on by default, SWAPDEX_CODEX_LOGIN=browser opts
    // out. (That the flag actually reaches `codex login` is the argv test below.)
    #[test]
    fn device_auth_policy() {
        use super::codex_device_auth;
        assert!(codex_device_auth(false), "device-auth by default");
        assert!(!codex_device_auth(true), "opt-out -> browser flow");
    }

    // #4: a restore whose apply FAILS must not strand the requested backup. The
    // outgoing login is backed up only AFTER apply succeeds; otherwise it becomes
    // the newest backup and a retry sees it as "already active", never restoring
    // the target we were asked for.
    #[test]
    fn failed_restore_keeps_the_requested_backup_newest() {
        use crate::adapters::claude::Claude;
        use crate::adapters::AuthTool;
        use crate::paths::Paths;
        use crate::store::Store;

        fn seed(p: &Paths, uuid: &str, email: &str) {
            std::fs::create_dir_all(p.claude_credentials().parent().unwrap()).unwrap();
            std::fs::write(
                p.claude_credentials(),
                serde_json::to_vec(&serde_json::json!({"claudeAiOauth": {
                    "accessToken": "AT", "refreshToken": "RT", "expiresAt": 9999999999999i64,
                    "scopes": ["x"], "subscriptionType": "max", "rateLimitTier": "default"}}))
                .unwrap(),
            )
            .unwrap();
            std::fs::write(
                p.claude_config_json(),
                serde_json::to_vec(&serde_json::json!({
                    "oauthAccount": {"accountUuid": uuid, "emailAddress": email}}))
                .unwrap(),
            )
            .unwrap();
        }

        // Backup A (the target) lives in the LIVE machine's store.
        let liveroot = tempfile::tempdir().unwrap();
        let plive = Paths::rooted(liveroot.path());
        let aroot = tempfile::tempdir().unwrap();
        let pa = Paths::rooted(aroot.path());
        seed(&pa, "uuid-A", "a@x.com");
        let snap_a = Claude.capture(&pa).unwrap();
        let store = Store::open(&plive).unwrap();
        store.backup(&snap_a).unwrap();

        // The live login is B (a different account).
        seed(&plive, "uuid-B", "b@y.com");

        // Force apply(A) to fail. Planting a directory at the atomic temp path
        // used to work, but that path now carries a pid and a counter so two
        // writers cannot collide - a test that knows the temp name is testing
        // the name. Make the DESTINATION unwritable, which is the condition
        // this test is actually about.
        let cfg = plive.claude_config_json();
        std::fs::remove_file(&cfg).ok();
        std::fs::create_dir(&cfg).unwrap();

        assert!(
            super::restore(&plive, None, false).is_err(),
            "apply must fail (planted temp dir)"
        );

        // A must still be the NEWEST backup: B was never promoted, so a retry
        // restores A instead of hitting "already active".
        let (_stamp, newest) = store.load_backup("claude-code").unwrap().unwrap();
        assert_eq!(
            super::snapshot_account_id(&newest, "claude-code").as_deref(),
            Some("uuid-A"),
            "a failed restore must not strand A by making B the newest backup"
        );
    }

    #[test]
    fn keychain_verdict_flags_refused_ambiguity() {
        // The derived item does not exist and several profiles are present:
        // resolution refuses to guess (target None) and doctor explains.
        let found = s(&[
            "Claude Code-credentials-5953ba74",
            "Claude Code-credentials-feeb5ea6",
        ]);
        let (ok, msg) = keychain_verdict(&found, None, BARE).unwrap();
        assert!(!ok, "refused ambiguity is a finding");
        assert!(msg.contains("refuses to guess"), "{msg}");
        assert!(msg.contains("CLAUDE_CONFIG_DIR"), "{msg}");
        assert!(msg.contains(BARE), "names the missing derived item: {msg}");
    }

    #[test]
    fn keychain_verdict_single_item_fallback_is_ok_with_note() {
        // Alias-only setup: env derives bare (missing), the only login is a
        // suffixed item - swapdex manages it, with a pointer to the env.
        let (ok, msg) = keychain_verdict(
            &s(&["Claude Code-credentials-5953ba74"]),
            Some("Claude Code-credentials-5953ba74"),
            BARE,
        )
        .unwrap();
        assert!(ok, "managing the only existing login works: {msg}");
        assert!(msg.contains("only"), "{msg}");
        assert!(msg.contains("CLAUDE_CONFIG_DIR"), "{msg}");
    }

    #[test]
    fn keychain_verdict_flags_target_not_in_found() {
        // Defensive: the two keychain reads disagreed.
        let (ok, msg) =
            keychain_verdict(&s(&["Claude Code-credentials-5953ba74"]), Some(BARE), BARE).unwrap();
        assert!(!ok);
        assert!(msg.contains("re-run"), "{msg}");
    }
}

#[cfg(test)]
mod short_absence_tests {
    use super::*;

    /// An empty short status must say which kind of nothing it is.
    ///
    /// `short_line` returns None both when no tool is signed in and when the
    /// logins cannot be read from this shell, and the caller printed a blank
    /// line for both. A locked macOS Keychain over SSH produces the second, and
    /// reading that as the first is exactly how a working account gets reported
    /// as signed out.
    #[test]
    fn an_empty_short_status_distinguishes_unreadable_from_signed_out() {
        assert_eq!(absence_reason(true), "logins unreadable from this shell");
        assert_eq!(absence_reason(false), "not signed in to any tool");
    }
}

#[cfg(test)]
mod bar_age_tests {
    use super::*;

    /// The status bar must not present an old number as the current one.
    ///
    /// The bar reads the cache, which carries the moment each number was taken,
    /// and threw that away. An account read before its window filled showed
    /// "5h 100%" for hours - the same shape as the reading that made a spent
    /// account look fine. The bar refreshes about once a minute, so anything
    /// past ten minutes means the readings stopped arriving, which is the one
    /// thing worth a few characters.
    #[test]
    fn the_bar_marks_a_number_that_stopped_being_refreshed() {
        // An account with plenty left is re-read every 15 minutes BY DESIGN, so
        // a flat ten-minute threshold flagged it during normal operation - a
        // warning that appears when nothing is wrong is one the reader learns
        // to skip. Late means late for THIS account's own schedule.
        let roomy = 900; // >50% headroom: read every 15 minutes
        assert_eq!(
            bar_age(840, roomy),
            None,
            "14m old on a 15m schedule is fine"
        );
        assert_eq!(bar_age(1_799, roomy), None);
        assert_eq!(bar_age(1_800, roomy), Some(" · 30m old".to_string()));

        // A spent account is re-read every minute, but never nag before ten.
        let tight = 60;
        assert_eq!(bar_age(300, tight), None);
        assert_eq!(bar_age(599, tight), None);
        assert_eq!(bar_age(600, tight), Some(" · 10m old".to_string()));
        assert_eq!(bar_age(9_000, tight), Some(" · 2h old".to_string()));
    }

    #[test]
    fn status_says_a_codex_login_has_lapsed_and_stays_quiet_for_claude() {
        let hour_ago = now_ms() - 3_600_000;
        let long_ago = now_ms() - 40 * 86_400 * 1000;

        // Codex: ten-day token, renewed only when Codex runs. An hour past its
        // deadline is not noise - it is why turns are failing.
        assert!(
            expiry_note(Some(hour_ago), "codex").contains("login expired"),
            "{}",
            expiry_note(Some(hour_ago), "codex")
        );
        assert_eq!(expiry_note(Some(now_ms() + 86_400_000), "codex"), "");
        assert_eq!(expiry_note(None, "codex"), "", "unknown is not expired");

        // Claude: hourly token the tool refreshes silently, so the same hour
        // must stay quiet - only a snapshot old enough to have a dead REFRESH
        // token is worth a word.
        assert_eq!(expiry_note(Some(hour_ago), "claude-code"), "");
        assert!(expiry_note(Some(long_ago), "claude-code").contains("login is old"));
    }

    #[test]
    fn a_lapsed_codex_login_is_not_reported_as_a_rejected_account() {
        use crate::codex_usage::Fetch;
        // Four slots on two machines were in exactly this state: the token had
        // simply run out - Codex renews it when Codex runs, and nobody had run
        // it - and `quota` called every one of them "token rejected".
        let lapsed = codex_no_number(&Fetch::Unauthorized, "work", true, CodexSource::Slot);
        assert!(lapsed.contains("login expired"), "{lapsed}");
        assert!(
            lapsed.contains("swapdex run work --tool codex"),
            "and names the remedy: {lapsed}"
        );

        // A 401 on a token that has NOT expired is a different fact, and the
        // endpoint's own word is the honest one for it.
        assert_eq!(
            codex_no_number(&Fetch::Unauthorized, "work", false, CodexSource::Slot),
            "token rejected"
        );
        // Everything else is untouched by the deadline either way.
        for expired in [true, false] {
            assert_eq!(
                codex_no_number(&Fetch::Throttled, "work", expired, CodexSource::Slot),
                "usage endpoint throttled"
            );
        }
    }

    /// Every tool records its last refresh somewhere different, and one reader
    /// now answers for all four. A field name that drifts in any one of them
    /// silently turns that tool's staleness off - in `ls` AND in the note the
    /// switch prints, since both read through here.
    #[test]
    fn every_tool_reports_when_its_snapshot_was_last_refreshed() {
        use crate::adapters::Snapshot;
        use crate::secret::Secret;
        let now = now_ms() / 1000;
        let old_secs = now - 60 * 86400;
        let old_ms = old_secs * 1000;
        let stamp = |secs: i64| crate::refresh::rfc3339_utc(secs);
        let snap = |tool: &'static str, part: &str, body: String| Snapshot {
            tool,
            blobs: vec![(part.into(), Secret::new(body.into_bytes()))],
        };

        let cases = [
            snap(
                "claude-code",
                "credentials",
                format!(r#"{{"claudeAiOauth":{{"expiresAt":{old_ms}}}}}"#),
            ),
            snap(
                "codex",
                "auth",
                format!(r#"{{"last_refresh":"{}"}}"#, stamp(old_secs)),
            ),
            snap("gemini", "oauth", format!(r#"{{"expiry_date":{old_ms}}}"#)),
            snap(
                "antigravity",
                "token",
                format!(r#"{{"token":{{"expiry":"{}"}}}}"#, stamp(old_secs)),
            ),
        ];
        for c in &cases {
            let read = snapshot_refreshed_at(c, c.tool)
                .unwrap_or_else(|| panic!("{} reports its refresh time", c.tool));
            assert!(
                (read - old_secs).abs() <= 1,
                "{}: read {read}, expected {old_secs}",
                c.tool
            );
            assert!(snapshot_is_stale(c, c.tool), "{} is 60 days old", c.tool);
        }

        // A snapshot refreshed today is not stale for any of them - the note
        // exists because an access token lapsing hourly is not news.
        let fresh_ms = now * 1000;
        let fresh = [
            snap(
                "claude-code",
                "credentials",
                format!(r#"{{"claudeAiOauth":{{"expiresAt":{fresh_ms}}}}}"#),
            ),
            snap(
                "codex",
                "auth",
                format!(r#"{{"last_refresh":"{}"}}"#, stamp(now)),
            ),
            snap(
                "gemini",
                "oauth",
                format!(r#"{{"expiry_date":{fresh_ms}}}"#),
            ),
            snap(
                "antigravity",
                "token",
                format!(r#"{{"token":{{"expiry":"{}"}}}}"#, stamp(now)),
            ),
        ];
        for c in &fresh {
            assert!(!snapshot_is_stale(c, c.tool), "{} is current", c.tool);
        }
    }

    /// A saved copy is not the account, and `quota` said it was.
    ///
    /// Found on a real machine: `codex-main` printed "7d 100% left" and the row
    /// under it, `codex`, printed "token rejected" - the SAME login, one live
    /// and one a 42-day-old copy. The copy is the only thing that lapsed.
    #[test]
    fn a_stale_copy_of_a_live_login_does_not_report_that_login_as_rejected() {
        use crate::codex_usage::Fetch;
        let twin = codex_no_number(
            &Fetch::Unauthorized,
            "codex",
            true,
            CodexSource::Snapshot {
                twin: Some("codex-main"),
            },
        );
        assert!(
            twin.contains("codex-main"),
            "it names the account that answered: {twin}"
        );
        assert!(
            !twin.starts_with("token rejected"),
            "and does not lead with the account being rejected: {twin}"
        );
        // `swapdex run` on a name with no slot builds an EMPTY one and asks for
        // a fresh sign-in, so it must not be offered as the way to renew a copy.
        assert!(
            !twin.contains("swapdex run"),
            "a copy is not renewed by running it: {twin}"
        );
    }

    /// A copy with no live twin still must not be told to run a slot it has not
    /// got. The Claude half of this same command has always said "snapshot"; the
    /// Codex half sent every stale copy to `swapdex run`.
    #[test]
    fn a_stale_copy_with_no_live_twin_is_told_how_a_copy_is_actually_refreshed() {
        use crate::codex_usage::Fetch;
        let lone = codex_no_number(
            &Fetch::Unauthorized,
            "old",
            true,
            CodexSource::Snapshot { twin: None },
        );
        assert!(lone.contains("expired"), "{lone}");
        assert!(
            lone.contains("swapdex add old --tool codex --update"),
            "a copy is refreshed by capturing it again: {lone}"
        );
        assert!(
            !lone.contains("swapdex run"),
            "and not by running a slot that does not exist: {lone}"
        );
    }

    /// The wiring the bug lived in: the deadline was read from the slot
    /// DIRECTORY, so a snapshot - which has none - could never be seen to have
    /// expired at all, and the source that goes stale by design was the one
    /// source that could not say so.
    #[test]
    fn a_saved_copy_can_be_seen_to_have_expired() {
        use crate::proxy::codex::{auth_token_expired, Auth};
        let now = 1_788_743_000i64;
        let jwt = |exp: i64| {
            use base64::Engine;
            let b64 = |b: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b);
            format!(
                "{}.{}.sig",
                b64(b"{\"alg\":\"none\"}"),
                b64(format!("{{\"exp\":{exp}}}").as_bytes())
            )
        };
        let auth = |exp: i64| Auth {
            token: crate::secret::Secret::new(jwt(exp).into_bytes()),
            account_id: "acct".into(),
        };
        assert!(auth_token_expired(&auth(now - 1), now), "a lapsed copy");
        assert!(!auth_token_expired(&auth(now + 3600), now), "a live one");
        // Unknown is never "expired": swapdex must not condemn a login on a
        // deadline it could not read.
        assert!(!auth_token_expired(
            &Auth {
                token: crate::secret::Secret::new(b"not-a-jwt".to_vec()),
                account_id: "acct".into(),
            },
            now
        ));
    }

    /// The same wiring at the call site: a saved copy has no directory, and the
    /// row must still learn both that it lapsed and whose account it copies.
    #[test]
    fn a_row_with_no_slot_directory_still_gets_its_deadline_and_its_twin() {
        use crate::proxy::codex::Auth;
        let now = 1_788_743_000i64;
        let lapsed = |acct: &str| {
            use base64::Engine;
            let b64 = |b: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b);
            Auth {
                token: crate::secret::Secret::new(
                    format!(
                        "{}.{}.sig",
                        b64(b"{\"alg\":\"none\"}"),
                        b64(format!("{{\"exp\":{}}}", now - 1).as_bytes())
                    )
                    .into_bytes(),
                ),
                account_id: acct.into(),
            }
        };
        let healthy = std::collections::BTreeMap::from([("acct-a", "codex-main")]);

        let (expired, src) = codex_row_source(None, &lapsed("acct-a"), "codex", &healthy, now);
        assert!(
            expired,
            "a saved copy has no directory but does have a deadline"
        );
        assert!(
            matches!(
                src,
                CodexSource::Snapshot {
                    twin: Some("codex-main")
                }
            ),
            "and it is a copy of the login that answered"
        );

        // A copy of an account nothing else here holds has no twin to name.
        let (_, lone) = codex_row_source(None, &lapsed("acct-b"), "old", &healthy, now);
        assert!(matches!(lone, CodexSource::Snapshot { twin: None }));

        // A row is never its own twin - that would tell the reader this account
        // is a copy of itself.
        let self_named = std::collections::BTreeMap::from([("acct-a", "codex")]);
        let (_, own) = codex_row_source(None, &lapsed("acct-a"), "codex", &self_named, now);
        assert!(matches!(own, CodexSource::Snapshot { twin: None }));

        // A slot is still a slot: it is the copy Codex itself renews.
        let (_, slot) = codex_row_source(
            Some(std::path::Path::new("/nonexistent")),
            &lapsed("acct-a"),
            "work",
            &healthy,
            now,
        );
        assert!(matches!(slot, CodexSource::Slot));
    }

    #[test]
    fn a_rejected_token_replaces_the_number_it_can_no_longer_refresh() {
        let now = 1_788_743_000i64;
        let read = crate::quota_cache::Entry {
            seven_d: Some(5.0),
            at: now - 6300,
            ..Default::default()
        };
        // Before: a number the reader cannot act on, and an age that will grow.
        assert_eq!(cached_brief(&read, now), "7d 95% \u{b7} 1h old");

        let rejected = crate::quota_cache::Entry {
            token_rejected_at: Some(now - 60),
            ..read.clone()
        };
        assert_eq!(cached_brief(&rejected, now), "token rejected");

        // A reading taken AFTER the rejection wins - the token started working.
        let recovered = crate::quota_cache::Entry {
            at: now - 30,
            token_rejected_at: Some(now - 60),
            ..read.clone()
        };
        assert_eq!(cached_brief(&recovered, now), "7d 95%");
    }
}

#[cfg(test)]
mod throttled_note_tests {
    use super::*;

    /// A throttled endpoint is not a verdict on the account - in either direction.
    ///
    /// `quota.rs` already guards this on the way in: a 429 is classified as the
    /// ENDPOINT being busy, with a test named for it. The line printed on the
    /// way out then said "the account is fine", which is the same mistake
    /// mirrored - avoiding a false alarm by making a false reassurance. A real
    /// account that was spent and refusing every turn showed exactly this line.
    #[test]
    fn a_throttled_read_claims_nothing_about_the_account() {
        let n = throttled_note();
        assert!(
            !n.contains("account is fine"),
            "a declined read is not evidence the account is healthy: {n}"
        );
        assert!(
            n.contains("no reading"),
            "say what actually happened - there is no reading: {n}"
        );
        assert!(
            n.contains("try again"),
            "the remedy still belongs here: {n}"
        );
    }
}

#[cfg(test)]
mod install_verdict_tests {
    use super::*;

    /// Installing a service that cannot start is not a successful install.
    ///
    /// `service install` wrote the unit and announced "it starts at login, comes
    /// back if it stops" without ever checking that it had. On a Mac whose
    /// launchd context cannot open the Keychain, the proxy refuses to run - by
    /// design, because it would forward the user's own login and never say so -
    /// so the unit failed every start while swapdex reported it as installed.
    /// The only proxy on that machine was one somebody had started by hand,
    /// which is why it also never picked up an upgrade.
    #[test]
    fn an_install_that_never_came_up_is_reported_as_a_failure() {
        let (ok, msg) = install_verdict(true, "claude-code");
        assert!(ok, "it came up: {msg}");
        assert!(msg.contains("running"), "say it is running: {msg}");

        let (ok, msg) = install_verdict(false, "claude-code");
        assert!(
            !ok,
            "a service that did not start is not installed successfully"
        );
        assert!(
            msg.contains("did not start"),
            "say plainly that it did not start: {msg}"
        );
        assert!(
            msg.to_lowercase().contains("keychain"),
            "name the usual cause on this platform: {msg}"
        );
        assert!(
            msg.contains("swapdex proxy --ensure"),
            "give the way that does work: {msg}"
        );
    }
}

#[cfg(test)]
mod serving_reach_tests {
    use super::*;

    /// A tool with accounts but no proxy must say switching cannot reach a
    /// running session.
    ///
    /// swapdex reported the Codex login, listed three Codex accounts, and never
    /// mentioned that nothing was carrying Codex traffic - no proxy, no pinned
    /// address. A session opened believing swapdex was "on" for it was talking
    /// straight to the vendor, and switching accounts changed nothing it could
    /// see. Not a fault, but a fact the tool alone knows and did not say.
    #[test]
    fn a_tool_with_no_proxy_says_what_switching_can_and_cannot_do() {
        let served = serving_reach(true, 3).expect("a tool with accounts has something to say");
        assert!(
            served.contains("running session"),
            "say a running session can be moved: {served}"
        );

        let unserved = serving_reach(false, 3).unwrap();
        assert!(
            unserved.to_lowercase().contains("next session"),
            "say when a switch takes effect: {unserved}"
        );
        assert!(
            !unserved.to_lowercase().contains("problem"),
            "not having a proxy is a choice, not a fault: {unserved}"
        );

        // Nothing to say about a tool with no accounts at all.
        assert_eq!(serving_reach(false, 0), None);
    }
}

#[cfg(test)]
mod codex_snapshot_rows_tests {
    use super::*;

    /// A Codex account with no slot still has usage to show.
    ///
    /// The dashboard built its Codex rows by walking the slot registry, so an
    /// account that lives only as a saved snapshot was never asked about and its
    /// windows sat empty. `swapdex quota` reads exactly that case through
    /// `snapshot_codex_auth` and prints real numbers - so the two commands gave
    /// different answers about the same account, and the one people look at was
    /// the one that said nothing.
    #[test]
    fn codex_accounts_without_a_slot_are_still_asked_about() {
        let slots = ["youdie".to_string()];
        let store = ["work".to_string(), "youdie".to_string(), "kong".to_string()];
        let mut missing = codex_names_without_a_slot(&store, &slots);
        missing.sort();
        assert_eq!(
            missing,
            vec!["kong".to_string(), "work".to_string()],
            "every stored Codex account that has no slot"
        );
        // Nothing to add when the registry already covers them.
        assert!(codex_names_without_a_slot(&slots, &slots).is_empty());
    }

    /// A name is unique only WITHIN a tool, and a second row under it shadows
    /// the first.
    ///
    /// `kong` holds both a Claude and a Codex login. Adding the snapshot-only
    /// Codex rows without checking put a second `kong` in the list, and the
    /// lookup by name found the Codex windows where the Claude ones belonged -
    /// its 5h went blank and its 7d showed the Codex account's number. Shipped
    /// and caught on the dashboard within minutes.
    #[test]
    fn a_name_already_shown_is_not_given_a_second_row() {
        let already = ["kong".to_string(), "rnd".to_string()];
        let stored = ["kong".to_string(), "work".to_string()];
        let add: Vec<String> = codex_names_without_a_slot(&stored, &[])
            .into_iter()
            .filter(|n| !already.contains(n))
            .collect();
        assert_eq!(
            add,
            vec!["work".to_string()],
            "only the account that has no row yet"
        );
    }
}

#[cfg(test)]
mod cached_quota_tools_tests {
    use super::*;

    /// The first frame must read every tool's cache, not just Claude's.
    ///
    /// The dashboard fills its first frame from `cached_quota`, which called
    /// `quota_cache::load` - hardcoded to claude-code. So a remembered Codex
    /// reading was written and never read back: those rows stayed empty until a
    /// live network read returned, which is the whole delay. Dropping the
    /// "checking..." note made the wait quieter, not shorter.
    #[test]
    fn the_first_frame_reads_a_cache_per_tool() {
        let tools = cached_quota_tools();
        assert!(
            tools.contains(&CLAUDE_TOOL),
            "claude was always read: {tools:?}"
        );
        assert!(
            tools.contains(&CODEX_TOOL),
            "a remembered reading has to be read back too: {tools:?}"
        );
    }
}

#[cfg(test)]
mod slot_capture_tests {

    fn write_credentials(dir: &std::path::Path, who: &str) {
        std::fs::create_dir_all(dir).unwrap();
        let value = serde_json::json!({
            "claudeAiOauth": {
                "accessToken": format!("AT-{who}"),
                "refreshToken": "RT",
                "expiresAt": 9999999999999i64
            }
        });
        std::fs::write(dir.join(".credentials.json"), value.to_string()).unwrap();
    }

    /// Capturing from a slot must read THAT slot, never the default home.
    ///
    /// This is the check that could not be written before: a SWAPDEX_ROOT
    /// fixture ignores the environment variables the real resolver honours, so
    /// pointing a capture at a slot through the environment was unverifiable -
    /// and an unverified capture files whoever happens to be live under someone
    /// else's name. Pointing the Paths directly is testable.
    #[test]
    fn a_slot_capture_reads_the_slot_not_the_default_home() {
        let td = tempfile::tempdir().unwrap();
        let root = td.path();
        let paths = crate::paths::Paths::rooted(root);
        write_credentials(paths.claude_dir(), "DEFAULT");
        std::fs::write(
            paths.claude_config_json(),
            serde_json::json!({
                "oauthAccount": {
                    "accountUuid": "UUID-DEFAULT",
                    "emailAddress": "default@example.com"
                }
            })
            .to_string(),
        )
        .unwrap();
        let slot = root.join("slotdir");
        write_credentials(&slot, "SLOT");
        std::fs::write(
            slot.join(".claude.json"),
            serde_json::json!({
                "oauthAccount": {
                    "accountUuid": "UUID-SLOT",
                    "emailAddress": "slot@example.com"
                }
            })
            .to_string(),
        )
        .unwrap();

        let at = paths.with_tool_dir("claude-code", &slot);
        let snap = crate::adapters::by_name("claude-code")
            .unwrap()
            .capture(&at)
            .expect("the slot has a login");
        let creds = String::from_utf8_lossy(snap.part("credentials").unwrap().expose()).to_string();
        assert!(creds.contains("AT-SLOT"), "must read the slot: {creds}");
        assert!(
            !creds.contains("AT-DEFAULT"),
            "must NOT read the default home: {creds}"
        );
        let oauth: serde_json::Value = serde_json::from_slice(
            snap.part("oauth_account")
                .expect("capture always includes identity metadata")
                .expose(),
        )
        .unwrap();
        assert_eq!(oauth["accountUuid"], "UUID-SLOT");
        assert_eq!(oauth["emailAddress"], "slot@example.com");
    }

    #[test]
    fn missing_slot_metadata_is_absent_instead_of_borrowed_from_default() {
        let td = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(td.path());
        write_credentials(paths.claude_dir(), "DEFAULT");
        std::fs::write(
            paths.claude_config_json(),
            r#"{"oauthAccount":{"accountUuid":"UUID-DEFAULT","emailAddress":"default@example.com"}}"#,
        )
        .unwrap();
        let slot = td.path().join("slotdir");
        write_credentials(&slot, "SLOT");

        let at = paths.with_tool_dir("claude-code", &slot);
        let snap = crate::adapters::by_name("claude-code")
            .unwrap()
            .capture(&at)
            .unwrap();
        let oauth: serde_json::Value =
            serde_json::from_slice(snap.part("oauth_account").unwrap().expose()).unwrap();

        assert!(
            oauth.is_null(),
            "default metadata leaked into slot: {oauth}"
        );
    }

    #[test]
    fn corrupt_slot_metadata_is_reported_instead_of_borrowing_default() {
        let td = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(td.path());
        write_credentials(paths.claude_dir(), "DEFAULT");
        std::fs::write(
            paths.claude_config_json(),
            r#"{"oauthAccount":{"accountUuid":"UUID-DEFAULT","emailAddress":"default@example.com"}}"#,
        )
        .unwrap();
        let slot = td.path().join("slotdir");
        write_credentials(&slot, "SLOT");
        std::fs::write(slot.join(".claude.json"), b"not json {").unwrap();

        let at = paths.with_tool_dir("claude-code", &slot);
        let error = match crate::adapters::by_name("claude-code")
            .unwrap()
            .capture(&at)
        {
            Ok(_) => panic!("corrupt slot identity must stop capture"),
            Err(error) => error,
        };

        assert!(error.to_string().contains("corrupt"), "{error:#}");
    }
}

#[cfg(test)]
mod from_slot_flag_tests {
    /// Refreshing a stale saved copy must not require signing in again.
    ///
    /// The account's slot already holds a good login - that is why it serves
    /// turns fine. Only the SAVED COPY is old, and the one path that could
    /// refresh it ran inside the interactive sign-in key, so the only way to
    /// clear the marker was to log in again for no reason. Capturing from the
    /// slot is the whole fix, and it needs to be reachable on its own.
    #[test]
    fn capture_source_is_the_slot_when_asked() {
        assert_eq!(
            super::capture_source(true),
            super::CaptureSource::Slot,
            "--from-slot reads the account own directory"
        );
        assert_eq!(
            super::capture_source(false),
            super::CaptureSource::LiveHome,
            "the default stays the live login, as every other capture"
        );
    }
}

#[cfg(test)]
mod unusable_token_tests {
    use super::*;

    /// An empty token is not a corrupt one, and must not invite an overwrite.
    ///
    /// `token_usable` rejects both, so a credential that came back EMPTY -
    /// which on macOS means the Keychain would not open for this shell - was
    /// reported as a corrupt snapshot, with `add --update` offered as the fix.
    /// That would overwrite a perfectly good saved copy with whatever this
    /// shell could see, which is nothing. The other accounts in the same
    /// listing said plainly that the keychain could not be read; only this
    /// branch guessed, and guessed destructively.
    #[test]
    fn an_empty_token_says_it_was_not_read_not_that_it_is_corrupt() {
        let empty = unusable_token_reason("", None);
        assert!(
            !empty.contains("corrupt") && !empty.contains("--update"),
            "nothing was read - do not call it corrupt or offer to overwrite: {empty}"
        );
        // When the caller knows WHY it could not be read, that reason wins.
        let why = unusable_token_reason(
            "",
            Some("signed in, but this shell cannot read the keychain"),
        );
        assert!(why.contains("keychain"), "the known reason is used: {why}");
        // A token that really is malformed keeps the original advice.
        let bad = unusable_token_reason("abc\ndef", None);
        assert!(
            bad.contains("corrupt"),
            "a malformed token is still corrupt: {bad}"
        );
    }
}

#[cfg(test)]
mod tool_binary_tests {
    use super::*;

    /// The same fact was written twice: `exec_tool` had the right table and
    /// `tool_binary` had a wrong one where everything that was not codex
    /// became "claude". Fourteen call sites use `tool_binary`, including the
    /// one that resolves the real executable, so for gemini and antigravity
    /// swapdex looked for - and named - Claude.
    #[test]
    fn tool_binary_names_the_binary_each_tool_actually_has() {
        assert_eq!(tool_binary("claude-code"), "claude");
        assert_eq!(tool_binary("codex"), "codex");
        assert_eq!(tool_binary("gemini"), "gemini");
        assert_eq!(tool_binary("antigravity"), "agy");
    }

    /// And nothing collapses onto another tool's name.
    #[test]
    fn no_two_tools_report_the_same_binary() {
        let tools = ["claude-code", "codex", "gemini", "antigravity"];
        for i in 0..tools.len() {
            for j in (i + 1)..tools.len() {
                assert_ne!(
                    tool_binary(tools[i]),
                    tool_binary(tools[j]),
                    "{} and {} both resolve to the same binary",
                    tools[i],
                    tools[j]
                );
            }
        }
    }
}

#[cfg(test)]
mod shared_source_tests {
    use super::*;

    /// Where a new slot borrows from has to be the tool's own dir. Gemini and
    /// antigravity both resolved to Claude's, so even an empty shared list
    /// would have pointed at the wrong tree the moment one was added.
    #[test]
    fn a_slot_borrows_from_its_own_tools_dir() {
        let d = tempfile::tempdir().unwrap();
        let paths = crate::paths::Paths::rooted(d.path());
        assert_eq!(shared_source(&paths, "claude-code"), paths.claude_dir());
        assert_eq!(shared_source(&paths, "codex"), paths.codex_dir());
        assert_ne!(
            shared_source(&paths, "gemini"),
            paths.claude_dir(),
            "gemini borrowed from Claude's dir"
        );
        assert_ne!(
            shared_source(&paths, "antigravity"),
            paths.claude_dir(),
            "antigravity borrowed from Claude's dir"
        );
    }
}