swapdex 0.163.0

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
//! Renewing a slot's access token.
//!
//! An access token lives about an hour, and only the account's own refresh token
//! can renew it. Until now swapdex would not do that - it read credentials and
//! never wrote them - so any account idle for an hour looked expired: the proxy
//! stepped over it and `quota` reported it dead. Those are exactly the accounts
//! with quota left, which made the tool least useful precisely when it was needed.
//!
//! Refreshing means writing a credential, and that is a line worth naming. Two
//! properties make it safe to cross:
//!
//! 1. **Never while the tool is running there.** A refresh token ROTATES: the
//!    server issues a new one and retires the old. A Claude running in that slot
//!    holds the old one in memory, and when it later refreshes with a token that
//!    has already been spent, the server can revoke the whole chain - which is
//!    the logout this project exists to prevent. So a slot in use is never
//!    touched.
//! 2. **The new credential replaces the old one in place**, in whichever store
//!    the account already keeps it, so the tool's next run reads what swapdex
//!    wrote rather than a second, competing copy.
//!
//! No token value is ever logged, and the request carries it on curl's stdin -
//! the same discipline `quota` uses, so it never reaches `ps`.

use crate::{paths::Paths, secret::Secret};
use fs2::FileExt;
use sha2::{Digest, Sha256};
use std::collections::HashMap;
use std::io::{Read, Seek, Write};
use std::path::{Path, PathBuf};
use std::sync::{Condvar, Mutex, OnceLock};
use std::time::{Duration, Instant};

/// Where an OAuth refresh is exchanged. `SWAPDEX_OAUTH_URL` redirects it for
/// tests, honored ONLY under `SWAPDEX_ROOT` so a production run can never be
/// pointed at another host with a live refresh token.
pub fn token_url() -> String {
    if std::env::var_os("SWAPDEX_ROOT").is_some() {
        if let Some(u) = std::env::var_os("SWAPDEX_OAUTH_URL") {
            return u.to_string_lossy().into_owned();
        }
    }
    "https://console.anthropic.com/v1/oauth/token".to_string()
}

/// Claude Code's public OAuth client, as its own authorize URL carries it.
pub const CLIENT_ID: &str = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";

/// Why a refresh did not happen. Each is a different thing to tell the user, and
/// none of them should read as "your account is gone".
#[derive(Clone, Debug, PartialEq)]
pub enum RefreshError {
    /// The slot has no readable credential to renew.
    NoCredential,
    /// The tool is running in this slot right now. Refreshing would retire the
    /// refresh token it holds in memory, and its next renewal would fail.
    InUse,
    /// The refresh token itself has expired - only a fresh sign-in fixes that.
    Expired,
    /// The login server is rate-limiting; the account itself is fine.
    Busy,
    /// Another caller may have renewed this account, but its exact result could
    /// not be established safely. Spending the same refresh token twice is what
    /// logs an account out, so ambiguity remains a conservative stand-down.
    AlreadyRefreshing,
    /// The server refused the exchange.
    Refused(String),
    /// The request could not be made at all.
    Offline(String),
}

/// A successful refresh request either rotated the saved credential or proved
/// that the native client already owns a usable access token for this account.
/// Keeping those outcomes separate prevents a no-op from being reported as an
/// OAuth exchange and credential write.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RefreshOutcome {
    Renewed,
    NativeManaged,
}

type RefreshResult = Result<RefreshOutcome, RefreshError>;

impl RefreshError {
    /// What the user should do about it, in one line.
    ///
    /// `run` defaults to Claude, so every remedy naming it must name the tool
    /// too - otherwise a dead Codex account is told to launch Claude.
    pub fn remedy(&self, name: &str, tool: &str) -> String {
        let flag = match tool {
            "claude-code" | "claude" => String::new(),
            other => format!(" --tool {other}"),
        };
        match self {
            Self::NoCredential => {
                format!("'{name}' has no login yet - `swapdex run {name}{flag}` signs it in")
            }
            Self::InUse => format!(
                "'{name}' {tool} renewal deferred - refresh unverified while a {tool} session \
                 is using this account; retry after the session exits"
            ),
            Self::Expired => format!(
                "'{name}' has been idle too long to renew - \
                 `swapdex run {name}{flag}` signs it in again"
            ),
            Self::Busy => format!(
                "the login server is busy - '{name}' is fine, renewing again shortly will work"
            ),
            Self::AlreadyRefreshing => format!(
                "'{name}' is already being renewed by another turn - nothing to do; \
                 spending its refresh token twice is what logs an account out"
            ),
            Self::Refused(why) => format!("'{name}' could not be renewed: {why}"),
            Self::Offline(why) => format!("could not reach the login server: {why}"),
        }
    }
}

/// Has the refresh token itself expired? Then nothing here can help and only a
/// sign-in will - saying so is the difference between a fixable state and a
/// mysterious one.
fn refresh_token_expired(blob: &[u8], now_ms: i64) -> bool {
    serde_json::from_slice::<serde_json::Value>(blob)
        .ok()
        .and_then(|v| v["claudeAiOauth"]["refreshTokenExpiresAt"].as_i64())
        .is_some_and(|exp| exp <= now_ms)
}

/// Build the renewed credential blob by merging the server's answer into the one
/// on disk, so fields swapdex does not understand survive untouched.
///
/// The new refresh token REPLACES the old one when the server sends it. Keeping
/// the old one would leave a spent token on disk and the account unusable on the
/// renewal after this one.
pub fn merge_response(old: &[u8], response: &str, now_ms: i64) -> Option<Vec<u8>> {
    let mut blob: serde_json::Value = serde_json::from_slice(old).ok()?;
    let r: serde_json::Value = serde_json::from_str(response).ok()?;
    let access = r["access_token"].as_str().filter(|s| !s.is_empty())?;
    let o = blob.get_mut("claudeAiOauth")?.as_object_mut()?;
    o.insert("accessToken".into(), access.into());
    if let Some(rt) = r["refresh_token"].as_str().filter(|s| !s.is_empty()) {
        o.insert("refreshToken".into(), rt.into());
        // The deadline on disk belonged to the token this one replaces. The
        // server retired that one, so the recorded moment now describes
        // something that does not exist - and it is exactly what decides
        // whether renewing is worth trying. Left in place it made every
        // renewal leave the account one day nearer a sign-in swapdex would
        // demand while holding a refresh token the server had just issued.
        //
        // Record the new lifetime when the server states it. When it does not,
        // drop the stale one rather than apply it to a different token: the
        // server is then the one that says no, which is the only party that
        // knows.
        match r["refresh_token_expires_in"].as_i64() {
            Some(secs) => {
                o.insert(
                    "refreshTokenExpiresAt".into(),
                    (now_ms + secs * 1000).into(),
                );
            }
            None => {
                o.remove("refreshTokenExpiresAt");
            }
        }
    }
    // `expires_in` is seconds from now; the file records an absolute moment.
    if let Some(secs) = r["expires_in"].as_i64() {
        o.insert("expiresAt".into(), (now_ms + secs * 1000).into());
    }
    serde_json::to_vec(&blob).ok()
}

/// The request body for an exchange. Kept separate so a test can assert its
/// shape without a network call.
pub fn request_body(refresh_token: &str) -> String {
    serde_json::json!({
        "grant_type": "refresh_token",
        "refresh_token": refresh_token,
        "client_id": CLIENT_ID,
    })
    .to_string()
}

/// How close together two refreshes count as the same burst.
pub const BURST_SECS: i64 = 30;

/// Lets one leader refresh an account while followers wait for its result.
///
/// Refresh tokens rotate: each use mints a new one and retires the old. So N
/// concurrent turns each refreshing the same slot spend the same token N times,
/// and every result but one is already invalid when it lands - the account ends
/// up logged out by its own renewal. teamclaude hit this as "don't rotate the
/// token family once per 401 in a burst".
///
/// Per-account, so one account's burst never blocks another's genuine refresh,
/// and time-bounded, so a refresh minutes later is a new event rather than the
/// same burst still being suppressed.
const WAIT_FOR_REFRESH: Duration = Duration::from_secs(20);

#[derive(Clone)]
struct CompletedRefresh {
    generation: String,
    result_generation: Option<String>,
    source: String,
    completed_at: Instant,
    result: RefreshResult,
}

enum GateEntry {
    Running {
        generation: String,
        source: String,
        started: Instant,
    },
    Complete(CompletedRefresh),
}

enum GateDecision {
    Leader,
    Shared(RefreshResult),
}

#[derive(Default)]
struct RefreshGate {
    entries: Mutex<HashMap<PathBuf, GateEntry>>,
    changed: Condvar,
}

impl RefreshGate {
    fn begin(&self, key: &Path, generation: &str, source: &str) -> GateDecision {
        let wait_started = Instant::now();
        let mut entries = self
            .entries
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        loop {
            match entries.get(key) {
                None => {
                    entries.insert(
                        key.to_path_buf(),
                        GateEntry::Running {
                            generation: generation.to_string(),
                            source: source.to_string(),
                            started: Instant::now(),
                        },
                    );
                    return GateDecision::Leader;
                }
                Some(GateEntry::Running { started, .. }) => {
                    let elapsed = wait_started.elapsed();
                    if elapsed >= WAIT_FOR_REFRESH || started.elapsed() >= WAIT_FOR_REFRESH {
                        // The filesystem lock remains the final exclusion layer.
                        // Removing an abandoned local claim cannot overlap a live
                        // exchange in this or another process.
                        entries.remove(key);
                        self.changed.notify_all();
                        return GateDecision::Shared(Err(RefreshError::AlreadyRefreshing));
                    }
                    let remaining = WAIT_FOR_REFRESH.saturating_sub(elapsed);
                    let waited = self
                        .changed
                        .wait_timeout(entries, remaining)
                        .unwrap_or_else(|poisoned| poisoned.into_inner());
                    entries = waited.0;
                }
                Some(GateEntry::Complete(completed)) => {
                    let recent =
                        completed.completed_at.elapsed() <= Duration::from_secs(BURST_SECS as u64);
                    if !recent {
                        entries.remove(key);
                        continue;
                    }
                    if completed.source != source {
                        // Two directories carrying one provider identity may be
                        // stale copies. They share exclusion, but never inherit a
                        // success that was persisted somewhere else.
                        return GateDecision::Shared(Err(RefreshError::AlreadyRefreshing));
                    }
                    if completed.generation == generation
                        || completed.result_generation.as_deref() == Some(generation)
                    {
                        return GateDecision::Shared(completed.result.clone());
                    }
                    // A replacement generation after a failure is a new login,
                    // so an old refusal must not poison it.
                    entries.insert(
                        key.to_path_buf(),
                        GateEntry::Running {
                            generation: generation.to_string(),
                            source: source.to_string(),
                            started: Instant::now(),
                        },
                    );
                    return GateDecision::Leader;
                }
            }
        }
    }

    fn finish(
        &self,
        key: &Path,
        generation: &str,
        source: &str,
        result: Option<(RefreshResult, Option<String>)>,
    ) {
        let mut entries = self
            .entries
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner());
        let owns_entry = matches!(
            entries.get(key),
            Some(GateEntry::Running {
                generation: current_generation,
                source: current_source,
                ..
            }) if current_generation == generation && current_source == source
        );
        if owns_entry {
            match result {
                Some((result, result_generation)) => {
                    entries.insert(
                        key.to_path_buf(),
                        GateEntry::Complete(CompletedRefresh {
                            generation: generation.to_string(),
                            result_generation,
                            source: source.to_string(),
                            completed_at: Instant::now(),
                            result,
                        }),
                    );
                }
                None => {
                    entries.remove(key);
                }
            }
        }
        self.changed.notify_all();
    }
}

/// The one gate every refresh passes through.
///
/// `RefreshGate` was created for this and then applied at a single call site,
/// while two other paths - the keep-alive sweep and `has_usable_login` - reached
/// `refresh_slot` unguarded. A rule enforced at one caller is a rule the next
/// caller does not know exists, so it lives here now, where the token is
/// actually spent.
fn gate() -> &'static RefreshGate {
    static GATE: OnceLock<RefreshGate> = OnceLock::new();
    GATE.get_or_init(RefreshGate::default)
}

/// The account a slot holds, however its tool records it.
/// The provider is part of the identity, not just the id under it.
///
/// A Claude `accountUuid` and a ChatGPT `account_id` are drawn from different
/// namespaces, and one person's email can hold a subscription to both. Keying
/// on the bare id would let two unrelated accounts share one claim - the same
/// correction KarpelesLab/teamclaude made in its own pool (#349).
fn identity_file(dir: &Path, name: &str) -> Option<Vec<u8>> {
    let path = dir.join(name);
    let meta = std::fs::symlink_metadata(&path).ok()?;
    if meta.file_type().is_symlink() || !meta.is_file() {
        return None;
    }
    std::fs::read(path).ok()
}

fn account_from_identity(path: &Path, tool: &str) -> Option<String> {
    let (field, prefix) = match tool {
        "claude-code" => (&["oauthAccount", "accountUuid"][..], "claude"),
        "codex" => (&["tokens", "account_id"][..], "codex"),
        _ => return None,
    };
    let parent = path.parent()?;
    let name = path.file_name()?.to_str()?;
    let bytes = identity_file(parent, name)?;
    let v: serde_json::Value = serde_json::from_slice(&bytes).ok()?;
    field
        .iter()
        .try_fold(&v, |value, key| value.get(key))?
        .as_str()
        .filter(|s| !s.is_empty())
        .map(|id| format!("{prefix}:{id}"))
}

fn account_of(dir: &Path, tool: &str) -> Option<String> {
    let name = match tool {
        "claude-code" => ".claude.json",
        "codex" => "auth.json",
        _ => return None,
    };
    account_from_identity(&dir.join(name), tool)
}

/// The key a claim is held under: the ACCOUNT, not the directory.
///
/// Two directories can hold one login - `doctor` reports exactly that - and
/// these tokens are single-use, so one claim per directory let a sweep spend
/// one account's token once per copy. That is the double-spend this gate
/// exists to stop, reached from the other side: the gate was made per-caller
/// once already, and the note above records why that failed.
///
/// An identity that cannot be read falls back to the path. Two unknowns are
/// not one account, and per-path is the stricter answer anyway.
fn claim_key(dir: &Path, tool: &str) -> std::path::PathBuf {
    match account_of(dir, tool) {
        Some(a) => std::path::PathBuf::from(format!("account:{a}")),
        None => std::path::PathBuf::from(format!("{tool}:{}", dir.display())),
    }
}

fn fingerprint(bytes: &[u8]) -> String {
    let digest = Sha256::digest(bytes);
    let mut encoded = String::with_capacity(digest.len() * 2);
    for byte in digest {
        use std::fmt::Write as _;
        let _ = write!(encoded, "{byte:02x}");
    }
    encoded
}

/// A non-secret identifier for one exact Claude credential generation.
/// Callers that already hold the blob use this instead of racing another read
/// of the selected file or Keychain item.
pub(crate) fn claude_credential_fingerprint_from_blob(bytes: &[u8]) -> String {
    fingerprint(bytes)
}

fn source_fingerprint(dir: &Path) -> String {
    let source = std::fs::canonicalize(dir).unwrap_or_else(|_| dir.to_path_buf());
    fingerprint(source.as_os_str().as_encoded_bytes())
}

fn coordination_now_ms() -> i64 {
    let millis = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .unwrap_or_default()
        .as_millis();
    i64::try_from(millis).unwrap_or(i64::MAX)
}

#[derive(serde::Deserialize, serde::Serialize)]
struct DiskCompletion {
    version: u8,
    generation: String,
    #[serde(default)]
    result_generation: Option<String>,
    source: String,
    completed_at_ms: i64,
    result: DiskResult,
}

#[derive(serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
enum DiskResult {
    Renewed,
    Busy,
    Expired,
    Refused,
    Offline,
    Superseded,
    NoAttempt,
}

impl DiskResult {
    fn from_result(result: &RefreshResult) -> Option<Self> {
        match result {
            Ok(RefreshOutcome::Renewed) => Some(Self::Renewed),
            Ok(RefreshOutcome::NativeManaged) => None,
            Err(RefreshError::Busy) => Some(Self::Busy),
            Err(RefreshError::Expired) => Some(Self::Expired),
            Err(RefreshError::Refused(_)) => Some(Self::Refused),
            Err(RefreshError::Offline(_)) => Some(Self::Offline),
            Err(RefreshError::AlreadyRefreshing) => Some(Self::Superseded),
            Err(RefreshError::NoCredential | RefreshError::InUse) => None,
        }
    }

    fn into_result(self) -> RefreshResult {
        match self {
            Self::Renewed => Ok(RefreshOutcome::Renewed),
            Self::Busy => Err(RefreshError::Busy),
            Self::Expired => Err(RefreshError::Expired),
            Self::Refused => Err(RefreshError::Refused("the login server refused it".into())),
            Self::Offline => Err(RefreshError::Offline(
                "the refresh request did not complete".into(),
            )),
            Self::Superseded | Self::NoAttempt => Err(RefreshError::AlreadyRefreshing),
        }
    }
}

struct Attempt {
    result: RefreshResult,
    result_generation: Option<String>,
    cache: bool,
}

impl Attempt {
    fn before_exchange(result: RefreshResult) -> Self {
        Self {
            result,
            result_generation: None,
            cache: false,
        }
    }

    fn after_exchange(result: RefreshResult) -> Self {
        Self {
            result,
            result_generation: None,
            cache: true,
        }
    }

    fn after_exchange_with_generation(result: RefreshResult, generation: Option<String>) -> Self {
        Self {
            result,
            result_generation: generation,
            cache: true,
        }
    }
}

fn open_refresh_lock(paths: &Paths, key: &Path) -> std::io::Result<std::fs::File> {
    let lock_dir = paths.store_dir().join(".refresh-locks");
    std::fs::create_dir_all(&lock_dir)?;
    let lock_name = format!("{}.lock", fingerprint(key.as_os_str().as_encoded_bytes()));
    let mut options = std::fs::OpenOptions::new();
    options.create(true).read(true).write(true);
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        options.mode(0o600).custom_flags(libc::O_NOFOLLOW);
    }
    options.open(lock_dir.join(lock_name))
}

fn read_disk_completion(file: &mut std::fs::File) -> Option<DiskCompletion> {
    file.rewind().ok()?;
    let mut bytes = Vec::new();
    file.take(4097).read_to_end(&mut bytes).ok()?;
    if bytes.len() > 4096 {
        return None;
    }
    serde_json::from_slice(&bytes).ok()
}

fn write_disk_completion(file: &mut std::fs::File, completion: &DiskCompletion) {
    let Ok(bytes) = serde_json::to_vec(completion) else {
        return;
    };
    if file.set_len(0).is_err() || file.rewind().is_err() {
        return;
    }
    if file.write_all(&bytes).is_ok() {
        let _ = file.sync_data();
    }
}

enum DiskDecision {
    Shared(RefreshResult),
    RetryAllowed,
}

fn disk_decision_for(
    completion: DiskCompletion,
    generation: &str,
    source: &str,
) -> Option<DiskDecision> {
    if completion.version != 1 {
        return None;
    }
    let age = coordination_now_ms().checked_sub(completion.completed_at_ms)?;
    if !(0..=BURST_SECS.saturating_mul(1000)).contains(&age) {
        return None;
    }
    if matches!(completion.result, DiskResult::NoAttempt) {
        return Some(DiskDecision::RetryAllowed);
    }
    if completion.source != source {
        return Some(DiskDecision::Shared(Err(RefreshError::AlreadyRefreshing)));
    }
    if completion.generation == generation
        || completion.result_generation.as_deref() == Some(generation)
    {
        return Some(DiskDecision::Shared(completion.result.into_result()));
    }
    None
}

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

    /// Keep-alive and request recovery pass the token-observation time into the
    /// refresh API. That timestamp may be fixed or captured long before a
    /// follower acquires the disk lock, so it cannot date coordination records.
    #[test]
    fn completion_freshness_ignores_the_callers_token_clock() {
        let fixed_token_clock = 1_i64;
        let completed_at_ms = coordination_now_ms();
        assert!(completed_at_ms > fixed_token_clock);
        let decision = disk_decision_for(
            DiskCompletion {
                version: 1,
                generation: "old".into(),
                result_generation: Some("new".into()),
                source: "slot".into(),
                completed_at_ms,
                result: DiskResult::Renewed,
            },
            "old",
            "slot",
        );
        assert!(matches!(
            decision,
            Some(DiskDecision::Shared(Ok(RefreshOutcome::Renewed)))
        ));
    }
}

fn coordinate_across_processes<F>(
    paths: &Paths,
    key: &Path,
    generation: &str,
    source: &str,
    action: F,
) -> Attempt
where
    F: FnOnce() -> Attempt,
{
    let mut file = match open_refresh_lock(paths, key) {
        Ok(file) => file,
        Err(_) => {
            return Attempt::before_exchange(Err(RefreshError::Offline(
                "could not coordinate the refresh safely".into(),
            )))
        }
    };
    let started = Instant::now();
    let mut contended = false;
    loop {
        match file.try_lock_exclusive() {
            Ok(()) => break,
            Err(error) if error.kind() == std::io::ErrorKind::WouldBlock => {
                contended = true;
                if started.elapsed() >= WAIT_FOR_REFRESH {
                    return Attempt::before_exchange(Err(RefreshError::AlreadyRefreshing));
                }
                std::thread::sleep(Duration::from_millis(10));
            }
            Err(_) => {
                return Attempt::before_exchange(Err(RefreshError::Offline(
                    "could not coordinate the refresh safely".into(),
                )))
            }
        }
    }

    let disk_decision = read_disk_completion(&mut file).and_then(|completion| {
        // A follower that actually waited receives the leader's full outcome.
        // A later independent command may retry a refusal, while a recorded
        // success still protects stale duplicate copies from spending the token
        // the successful exchange retired.
        let reusable_without_contention = matches!(
            completion.result,
            DiskResult::Renewed | DiskResult::Superseded
        );
        (contended
            || reusable_without_contention
            || matches!(completion.result, DiskResult::NoAttempt))
        .then(|| disk_decision_for(completion, generation, source))
        .flatten()
    });
    if let Some(DiskDecision::Shared(result)) = disk_decision {
        return Attempt::after_exchange(result);
    }
    if contended && !matches!(disk_decision, Some(DiskDecision::RetryAllowed)) {
        // The previous holder may have exited after sending the request but
        // before recording its answer. Retrying here could spend the same
        // rotating token twice, so ambiguity is a conservative stand-down.
        return Attempt::before_exchange(Err(RefreshError::AlreadyRefreshing));
    }

    let _ = file.set_len(0);
    let attempt = action();
    if attempt.cache {
        if let Some(result) = DiskResult::from_result(&attempt.result) {
            write_disk_completion(
                &mut file,
                &DiskCompletion {
                    version: 1,
                    generation: generation.to_string(),
                    result_generation: attempt.result_generation.clone(),
                    source: source.to_string(),
                    completed_at_ms: coordination_now_ms(),
                    result,
                },
            );
        }
    } else {
        // A waiting process can distinguish a clean guard refusal from a holder
        // that may have disappeared after sending OAuth. It re-runs every guard
        // rather than turning a preflight InUse into AlreadyRefreshing.
        write_disk_completion(
            &mut file,
            &DiskCompletion {
                version: 1,
                generation: generation.to_string(),
                result_generation: None,
                source: source.to_string(),
                completed_at_ms: coordination_now_ms(),
                result: DiskResult::NoAttempt,
            },
        );
    }
    attempt
}

fn coordinate_refresh<F>(
    paths: &Paths,
    dir: &Path,
    tool: &str,
    generation: &str,
    action: F,
) -> RefreshResult
where
    F: FnOnce() -> Attempt,
{
    let key = claim_key(dir, tool);
    let source = source_fingerprint(dir);
    match gate().begin(&key, generation, &source) {
        GateDecision::Shared(result) => result,
        GateDecision::Leader => {
            let attempt = coordinate_across_processes(paths, &key, generation, &source, action);
            let cached = attempt
                .cache
                .then(|| (attempt.result.clone(), attempt.result_generation.clone()));
            gate().finish(&key, generation, &source, cached);
            attempt.result
        }
    }
}

fn native_managed(paths: &Paths, dir: &Path, tool: &str, now_ms: i64) -> Option<RefreshResult> {
    let login = crate::live_login::resolve(paths, dir, tool, now_ms)?;
    if login.refresh_rejected_at_ms.is_some() {
        return Some(Err(RefreshError::Expired));
    }
    Some(Ok(RefreshOutcome::NativeManaged))
}

pub fn refresh_slot(paths: &Paths, dir: &Path, now_ms: i64) -> RefreshResult {
    refresh_slot_inner(paths, dir, now_ms, None, None, None)
}

/// Renew only when both the credential source generation and every available
/// selected-account identity field still name the rejected request's owner.
pub(crate) fn refresh_slot_if_current(
    paths: &Paths,
    dir: &Path,
    now_ms: i64,
    expected_fingerprint: &str,
    expected_account_uuid: Option<&str>,
    expected_identity: Option<&crate::live_login::LoginIdentity>,
) -> RefreshResult {
    refresh_slot_inner(
        paths,
        dir,
        now_ms,
        Some(expected_fingerprint),
        expected_account_uuid,
        expected_identity,
    )
}

fn claude_identity_matches(
    dir: &Path,
    expected_account_uuid: Option<&str>,
    expected_identity: Option<&crate::live_login::LoginIdentity>,
) -> bool {
    if expected_account_uuid.is_none() && expected_identity.is_none() {
        return true;
    }
    let Some(blob) = identity_file(dir, ".claude.json") else {
        return false;
    };
    let account_uuid = serde_json::from_slice::<serde_json::Value>(&blob)
        .ok()
        .and_then(|value| {
            value["oauthAccount"]["accountUuid"]
                .as_str()
                .map(str::to_string)
        });
    if expected_account_uuid.is_some_and(|expected| account_uuid.as_deref() != Some(expected)) {
        return false;
    }
    !expected_identity.is_some_and(|expected| {
        crate::live_login::identity_from_credential(&blob, "claude-code").as_ref() != Some(expected)
    })
}

fn refresh_slot_inner(
    paths: &Paths,
    dir: &Path,
    now_ms: i64,
    expected_fingerprint: Option<&str>,
    expected_account_uuid: Option<&str>,
    expected_identity: Option<&crate::live_login::LoginIdentity>,
) -> RefreshResult {
    if !claude_identity_matches(dir, expected_account_uuid, expected_identity) {
        return Err(RefreshError::AlreadyRefreshing);
    }
    if expected_fingerprint.is_none() {
        if let Some(result) = native_managed(paths, dir, "claude-code", now_ms) {
            return result;
        }
    }
    // Preflight before joining the gate: an attempt that never reaches OAuth
    // must not suppress the next caller after the native process exits.
    if slot_in_use(paths, dir, "claude-code") {
        return Err(RefreshError::InUse);
    }
    let credential = read_credential(dir).map_err(|_| RefreshError::NoCredential)?;
    if expected_fingerprint.is_some_and(|expected| fingerprint(credential.bytes()) != expected) {
        return Err(RefreshError::AlreadyRefreshing);
    }
    if !claude_identity_matches(dir, expected_account_uuid, expected_identity) {
        return Err(RefreshError::AlreadyRefreshing);
    }
    if let Some(result) = native_managed(paths, dir, "claude-code", now_ms) {
        if !credential_unchanged(dir, &credential)
            || !claude_identity_matches(dir, expected_account_uuid, expected_identity)
        {
            return Err(RefreshError::AlreadyRefreshing);
        }
        return result;
    }
    if refresh_token_expired(credential.bytes(), now_ms) {
        return Err(RefreshError::Expired);
    }
    let token = refresh_token(credential.bytes()).ok_or(RefreshError::NoCredential)?;
    let generation = fingerprint(credential.bytes());

    coordinate_refresh(paths, dir, "claude-code", &generation, || {
        if !credential_unchanged(dir, &credential)
            || !claude_identity_matches(dir, expected_account_uuid, expected_identity)
        {
            return Attempt::before_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        if let Some(result) = native_managed(paths, dir, "claude-code", now_ms) {
            return Attempt::before_exchange(result);
        }
        if slot_in_use(paths, dir, "claude-code") {
            return Attempt::before_exchange(Err(RefreshError::InUse));
        }

        let response = post(&token);
        // A login may replace the blob while the request is in flight. Its
        // generation owns every later verdict, so neither a success nor a
        // refusal for the old token may overwrite or poison it.
        if !credential_unchanged(dir, &credential)
            || !claude_identity_matches(dir, expected_account_uuid, expected_identity)
        {
            return Attempt::after_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        let (body, status) = match response {
            Ok(response) => response,
            Err(error) => return Attempt::after_exchange(Err(error)),
        };
        if status == 429 {
            return Attempt::after_exchange(Err(RefreshError::Busy));
        }
        if status == 401 || status == 400 {
            return Attempt::after_exchange(Err(RefreshError::Refused(short_reason(&body))));
        }
        if !(200..300).contains(&status) {
            return Attempt::after_exchange(Err(RefreshError::Refused(format!("HTTP {status}"))));
        }
        let Some(merged) = merge_response(credential.bytes(), &body, now_ms) else {
            return Attempt::after_exchange(Err(RefreshError::Refused(
                "the server's answer had no access token".into(),
            )));
        };
        if !credential_unchanged(dir, &credential)
            || !claude_identity_matches(dir, expected_account_uuid, expected_identity)
        {
            return Attempt::after_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        let result = write_credential(dir, credential.source(), &merged)
            .map(|()| RefreshOutcome::Renewed)
            .map_err(|error| RefreshError::Refused(error.to_string()));
        let result_generation = result.is_ok().then(|| fingerprint(&merged));
        Attempt::after_exchange_with_generation(result, result_generation)
    })
}

/// One short clause from an error body, for a message a person reads. Never the
/// whole body: it can be long, and it is not the user's problem to parse.
fn short_reason(body: &str) -> String {
    serde_json::from_str::<serde_json::Value>(body)
        .ok()
        .and_then(|v| {
            v["error_description"]
                .as_str()
                .or_else(|| v["error"].as_str())
                .or_else(|| v["error"]["message"].as_str())
                .map(str::to_string)
        })
        .unwrap_or_else(|| "the login server refused it".into())
}

/// Is a tool currently running with this slot as its home? Checked by the
/// environment of the running processes, since that is what actually decides
/// which credential a process holds.
fn same_dir(a: &Path, b: &Path) -> bool {
    a == b
        || std::fs::canonicalize(a)
            .ok()
            .zip(std::fs::canonicalize(b).ok())
            .is_some_and(|(a, b)| a == b)
}

fn inside_paths(paths: &Paths, dir: &Path) -> bool {
    std::fs::canonicalize(paths.home())
        .ok()
        .zip(std::fs::canonicalize(dir).ok())
        .is_some_and(|(root, dir)| dir.starts_with(root))
}

fn slot_in_use(paths: &Paths, dir: &Path, tool: &str) -> bool {
    let running = crate::proc::running_config_dirs(tool);
    if running.iter().any(|active| same_dir(active, dir)) {
        return true;
    }
    let Some(candidate) = account_of(dir, tool) else {
        return false;
    };
    // A default Claude process reads identity from HOME/.claude.json, not from
    // ~/.claude/.claude.json. The usable-login resolver intentionally returns
    // None for expired or unverified access, but that must never erase the
    // holder guard: the process can still have the selected refresh token in
    // memory. Use the native accessor's exact identity path for this check.
    if crate::proc::running_native_login_processes(paths, tool)
        .into_iter()
        .any(|process| {
            account_from_identity(&process.identity_path, tool).is_some_and(|id| id == candidate)
        })
    {
        return true;
    }
    running.into_iter().any(|active| {
        (!paths.sandboxed() || inside_paths(paths, &active))
            && account_of(&active, tool).is_some_and(|id| id == candidate)
    })
}

fn refresh_token(blob: &[u8]) -> Option<String> {
    serde_json::from_slice::<serde_json::Value>(blob)
        .ok()
        .and_then(|value| {
            value["claudeAiOauth"]["refreshToken"]
                .as_str()
                .filter(|token| !token.is_empty())
                .map(str::to_string)
        })
}

/// The one credential generation Claude Code uses for this slot.
fn read_credential(
    dir: &Path,
) -> std::result::Result<
    crate::adapters::claude::SlotCredential,
    crate::adapters::claude::KeychainReadError,
> {
    crate::adapters::claude::slot_credential(dir)
}

fn credential_unchanged(dir: &Path, expected: &crate::adapters::claude::SlotCredential) -> bool {
    read_credential(dir).is_ok_and(|current| current == *expected)
}

/// Put the renewed blob back where the old one was, so the tool's next run reads
/// what was written rather than a second, competing copy.
fn write_credential(
    dir: &Path,
    source: crate::adapters::claude::SlotCredentialSource,
    blob: &[u8],
) -> anyhow::Result<()> {
    write_credential_with(
        source,
        blob,
        |value| crate::atomic::write_secret(&dir.join(".credentials.json"), value),
        |value| crate::adapters::claude::slot_keychain_write(dir, value),
    )
}

fn write_credential_with<F, K>(
    source: crate::adapters::claude::SlotCredentialSource,
    blob: &[u8],
    write_file: F,
    write_keychain: K,
) -> anyhow::Result<()>
where
    F: FnOnce(&[u8]) -> anyhow::Result<()>,
    K: FnOnce(&[u8]) -> anyhow::Result<()>,
{
    match source {
        crate::adapters::claude::SlotCredentialSource::File => write_file(blob),
        crate::adapters::claude::SlotCredentialSource::Keychain => write_keychain(blob),
    }
}

#[cfg(test)]
mod claude_credential_source_tests {
    use super::*;
    use crate::adapters::claude::{
        choose_slot_credential, KeychainReadError, SlotCredentialSource,
    };
    use std::cell::Cell;

    fn blob(access: &str, refresh: &str, expires_at: i64) -> Vec<u8> {
        serde_json::to_vec(&serde_json::json!({
            "claudeAiOauth": {
                "accessToken": access,
                "refreshToken": refresh,
                "expiresAt": expires_at,
                "refreshTokenExpiresAt": 9_999_999_999_999i64
            }
        }))
        .unwrap()
    }

    #[test]
    fn renewal_uses_and_writes_the_selected_keychain_generation() {
        let selected = choose_slot_credential(
            Some(blob("OLD-AT", "OLD-RT", 9_999_999_999_999)),
            Ok(blob("NEW-AT", "NEW-RT", 1_000)),
        )
        .expect("Keychain credential");
        assert_eq!(refresh_token(selected.bytes()).as_deref(), Some("NEW-RT"));

        let file_writes = Cell::new(0);
        let keychain_writes = Cell::new(0);
        write_credential_with(
            selected.source(),
            b"renewed",
            |_| {
                file_writes.set(file_writes.get() + 1);
                Ok(())
            },
            |_| {
                keychain_writes.set(keychain_writes.get() + 1);
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(file_writes.get(), 0);
        assert_eq!(keychain_writes.get(), 1);
    }

    #[test]
    fn a_file_generation_writes_back_to_the_file() {
        let selected = choose_slot_credential(
            Some(blob("FILE-AT", "FILE-RT", 1_000)),
            Err(KeychainReadError::NotApplicable),
        )
        .expect("file credential");
        let file_writes = Cell::new(0);
        let keychain_writes = Cell::new(0);
        write_credential_with(
            selected.source(),
            b"renewed",
            |_| {
                file_writes.set(file_writes.get() + 1);
                Ok(())
            },
            |_| {
                keychain_writes.set(keychain_writes.get() + 1);
                Ok(())
            },
        )
        .unwrap();
        assert_eq!(file_writes.get(), 1);
        assert_eq!(keychain_writes.get(), 0);
    }

    #[test]
    fn keep_alive_uses_the_selected_keychain_expiry() {
        let now = 1_800_000_000_000;
        let selected = choose_slot_credential(
            Some(blob("OLD-AT", "OLD-RT", now + KEEP_ALIVE_WINDOW_MS * 2)),
            Ok(blob("NEW-AT", "NEW-RT", now + 1_000)),
        )
        .expect("Keychain credential");
        assert_eq!(selected.source(), SlotCredentialSource::Keychain);
        assert!(wants_keep_alive(selected.bytes(), now));
    }
}

/// POST the exchange with the token on stdin, never in argv.
fn post(refresh_token: &str) -> Result<(String, u32), RefreshError> {
    let body = request_body(refresh_token);
    // The same config shape `quota` uses, including how the status is reported:
    // run_curl reads the LAST line as the code, so decorating it broke the parse
    // and every renewal came back as HTTP 0.
    let cfg = format!(
        "url = \"{}\"\n\
         request = POST\n\
         header = \"content-type: application/json\"\n\
         header = \"Accept: application/json\"\n\
         header = \"User-Agent: swapdex\"\n\
         data = \"{}\"\n\
         silent\n\
         show-error\n\
         connect-timeout = 6\n\
         max-time = 15\n\
         write-out = \"\\n%{{http_code}}\"\n",
        token_url(),
        body.replace('\\', "\\\\").replace('"', "\\\"")
    );
    let out = crate::quota::run_curl_cfg(&cfg).map_err(RefreshError::Offline)?;
    Ok(out)
}

/// Codex's public OAuth client id, and where its exchange happens.
///
/// Not guessed: `icoretech/codex-pooler`, an Elixir gateway that keeps a pool of
/// Codex accounts alive, carries both as constants, and the issuer matches the
/// `iss` claim on every access token in a real slot here
/// (`https://auth.openai.com`).
pub const CODEX_CLIENT_ID: &str = "app_EMoamEEZ73f0CkXaXp7hrann";

/// Where a Codex refresh is exchanged. Redirected only under `SWAPDEX_ROOT`,
/// the same rule the Claude URL follows, so a production run can never be
/// pointed at another host holding a live refresh token.
pub fn codex_token_url() -> String {
    if std::env::var_os("SWAPDEX_ROOT").is_some() {
        if let Some(u) = std::env::var_os("SWAPDEX_CODEX_OAUTH_URL") {
            return u.to_string_lossy().into_owned();
        }
    }
    "https://auth.openai.com/oauth/token".to_string()
}

/// The form body for a Codex exchange. Form-encoded, not JSON: that is what
/// RFC 6749 specifies and what the working implementation sends.
///
/// Probed against the real endpoint with a deliberately invalid token, which
/// spends nothing: it answers a clean JSON 401 to a bare `User-Agent: swapdex`,
/// so the URL, the form shape and the client id are all accepted and no
/// browser fingerprint is needed.
pub fn codex_request_body(refresh_token: &str) -> String {
    // A JWT is unreserved characters only, but encode anyway rather than depend
    // on the shape of someone else's token.
    let enc = |s: &str| -> String {
        s.bytes()
            .map(|b| match b {
                b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                    (b as char).to_string()
                }
                _ => format!("%{b:02X}"),
            })
            .collect()
    };
    format!(
        "grant_type=refresh_token&refresh_token={}&client_id={}",
        enc(refresh_token),
        enc(CODEX_CLIENT_ID)
    )
}

/// Fold a Codex exchange's answer back into the slot's `auth.json`, keeping
/// every field it already had.
///
/// The rotated refresh token is written when the server sends one. Dropping it
/// would leave the slot holding a token the server has already retired - the
/// logout this project exists to prevent, arrived at from the other direction.
pub fn merge_codex_response(old: &[u8], response: &str, now_rfc3339: &str) -> Option<Vec<u8>> {
    let mut blob: serde_json::Value = serde_json::from_slice(old).ok()?;
    let r: serde_json::Value = serde_json::from_str(response).ok()?;
    let access = r["access_token"].as_str().filter(|s| !s.is_empty())?;
    let t = blob.get_mut("tokens")?.as_object_mut()?;
    t.insert("access_token".into(), access.into());
    for (from, to) in [("refresh_token", "refresh_token"), ("id_token", "id_token")] {
        if let Some(v) = r[from].as_str().filter(|s| !s.is_empty()) {
            t.insert(to.into(), v.into());
        }
    }
    blob.as_object_mut()?
        .insert("last_refresh".into(), now_rfc3339.into());
    serde_json::to_vec_pretty(&blob).ok()
}

/// `last_refresh` the way Codex writes it: RFC 3339, UTC. Only this field needs
/// it, so the civil-date arithmetic lives here rather than pulling in a clock
/// crate the rest of the tool does not use.
pub fn rfc3339_utc(secs: i64) -> String {
    let (days, rem) = (secs.div_euclid(86_400), secs.rem_euclid(86_400));
    // days-from-civil, inverted (Howard Hinnant's algorithm).
    let z = days + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z - era * 146_097;
    let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
    let mp = (5 * doy + 2) / 153;
    let d = doy - (153 * mp + 2) / 5 + 1;
    let m = if mp < 10 { mp + 3 } else { mp - 9 };
    let y = if m <= 2 { y + 1 } else { y };
    format!(
        "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z",
        rem / 3_600,
        (rem % 3_600) / 60,
        rem % 60
    )
}

/// Renew a Codex slot's access token in place.
///
/// The guards are the Claude path's, for the same reasons: never while Codex is
/// running in that slot (its session holds the refresh token, and retiring it
/// would break the session's own next renewal), and the claim is taken here -
/// where the token is SPENT - so two callers cannot spend it twice.
pub fn refresh_codex_slot(paths: &Paths, dir: &Path, now_ms: i64) -> RefreshResult {
    refresh_codex_slot_inner(paths, dir, now_ms, None)
}

/// Renew only when the slot still contains the credential generation and
/// provider identity that supplied the rejected request.
pub fn refresh_codex_slot_if_current(
    paths: &Paths,
    dir: &Path,
    now_ms: i64,
    expected_fingerprint: &str,
    expected_identity: Option<&crate::live_login::LoginIdentity>,
) -> RefreshResult {
    let blob = read_codex_credential(dir)?;
    let fingerprint = crate::refresh_health::codex_credential_fingerprint_from_blob(blob.expose())
        .ok_or(RefreshError::NoCredential)?;
    if fingerprint != expected_fingerprint
        || expected_identity.is_some_and(|expected| {
            crate::live_login::identity_from_credential(blob.expose(), "codex").as_ref()
                != Some(expected)
        })
    {
        return Err(RefreshError::AlreadyRefreshing);
    }
    refresh_codex_slot_inner(paths, dir, now_ms, Some(blob))
}

fn read_codex_credential(dir: &Path) -> Result<Secret, RefreshError> {
    std::fs::read(dir.join("auth.json"))
        .ok()
        .filter(|blob| !blob.is_empty())
        .map(Secret::new)
        .ok_or(RefreshError::NoCredential)
}

fn refresh_codex_slot_inner(
    paths: &Paths,
    dir: &Path,
    now_ms: i64,
    prechecked_blob: Option<Secret>,
) -> RefreshResult {
    let path = dir.join("auth.json");
    let blob = match prechecked_blob {
        Some(blob) => {
            if !std::fs::read(&path).is_ok_and(|current| current.as_slice() == blob.expose()) {
                return Err(RefreshError::AlreadyRefreshing);
            }
            if let Some(result) = native_managed(paths, dir, "codex", now_ms) {
                if !std::fs::read(&path).is_ok_and(|current| current.as_slice() == blob.expose()) {
                    return Err(RefreshError::AlreadyRefreshing);
                }
                return result;
            }
            if slot_in_use(paths, dir, "codex") {
                return Err(RefreshError::InUse);
            }
            blob
        }
        None => {
            if let Some(result) = native_managed(paths, dir, "codex", now_ms) {
                return result;
            }
            if slot_in_use(paths, dir, "codex") {
                return Err(RefreshError::InUse);
            }
            read_codex_credential(dir)?
        }
    };
    let token = serde_json::from_slice::<serde_json::Value>(blob.expose())
        .ok()
        .and_then(|v| {
            v["tokens"]["refresh_token"]
                .as_str()
                .filter(|s| !s.is_empty())
                .map(str::to_string)
        })
        .ok_or(RefreshError::NoCredential)?;
    let fingerprint = crate::refresh_health::codex_credential_fingerprint_from_blob(blob.expose())
        .ok_or(RefreshError::NoCredential)?;
    let generation = fingerprint.clone();

    coordinate_refresh(paths, dir, "codex", &generation, || {
        if !std::fs::read(&path).is_ok_and(|current| current.as_slice() == blob.expose()) {
            return Attempt::before_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        if let Some(result) = native_managed(paths, dir, "codex", now_ms) {
            return Attempt::before_exchange(result);
        }
        if slot_in_use(paths, dir, "codex") {
            return Attempt::before_exchange(Err(RefreshError::InUse));
        }

        let response = post_codex(&token);
        if !std::fs::read(&path).is_ok_and(|current| current.as_slice() == blob.expose()) {
            return Attempt::after_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        let (body, status) = match response {
            Ok(response) => response,
            Err(error) => return Attempt::after_exchange(Err(error)),
        };
        if status == 429 {
            return Attempt::after_exchange(Err(RefreshError::Busy));
        }
        if matches!(status, 400 | 401 | 403) {
            let _ = crate::refresh_health::record_codex_rejection(dir, &fingerprint, now_ms);
            return Attempt::after_exchange(Err(RefreshError::Expired));
        }
        if !(200..300).contains(&status) {
            return Attempt::after_exchange(Err(RefreshError::Refused(format!("HTTP {status}"))));
        }
        let Some(merged) = merge_codex_response(blob.expose(), &body, &rfc3339_utc(now_ms / 1000))
        else {
            return Attempt::after_exchange(Err(RefreshError::Refused(
                "the server's answer had no access token".into(),
            )));
        };
        if !std::fs::read(&path).is_ok_and(|current| current.as_slice() == blob.expose()) {
            return Attempt::after_exchange(Err(RefreshError::AlreadyRefreshing));
        }
        let result = crate::atomic::write_secret(&path, &merged)
            .map(|()| RefreshOutcome::Renewed)
            .map_err(|error| RefreshError::Refused(error.to_string()));
        if result.is_ok() {
            let _ = crate::refresh_health::clear_codex_rejection_before(dir, &fingerprint, now_ms);
        }
        let result_generation = result
            .is_ok()
            .then(|| crate::refresh_health::codex_credential_fingerprint_from_blob(&merged));
        Attempt::after_exchange_with_generation(result, result_generation.flatten())
    })
}

fn post_codex(refresh_token: &str) -> Result<(String, u32), RefreshError> {
    let body = codex_request_body(refresh_token);
    let cfg = format!(
        "url = \"{}\"\n\
         request = POST\n\
         header = \"content-type: application/x-www-form-urlencoded\"\n\
         header = \"Accept: application/json\"\n\
         header = \"User-Agent: swapdex\"\n\
         data = \"{}\"\n\
         silent\n\
         show-error\n\
         connect-timeout = 6\n\
         max-time = 15\n\
         write-out = \"\\n%{{http_code}}\"\n",
        codex_token_url(),
        body.replace('\\', "\\\\").replace('"', "\\\"")
    );
    crate::quota::run_curl_cfg(&cfg).map_err(RefreshError::Offline)
}

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

    const BLOB: &str = r#"{"claudeAiOauth":{"accessToken":"OLD-AT","refreshToken":"OLD-RT",
        "expiresAt":1000,"refreshTokenExpiresAt":9999999999999,"subscriptionType":"max"},
        "mcpOAuth":{"keep":"me"}}"#;

    #[test]
    fn a_renewal_replaces_the_refresh_token_the_server_retired() {
        let now = 1_800_000_000_000i64;
        let resp = r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#;
        let merged = merge_response(BLOB.as_bytes(), resp, now).expect("merged");
        let v: serde_json::Value = serde_json::from_slice(&merged).unwrap();
        let o = &v["claudeAiOauth"];
        assert_eq!(o["accessToken"], "NEW-AT");
        assert_eq!(
            o["refreshToken"], "NEW-RT",
            "keeping the old one would leave a spent token on disk"
        );
        assert_eq!(o["expiresAt"], now + 3_600_000, "an absolute moment");
        // Everything swapdex does not understand survives.
        assert_eq!(o["subscriptionType"], "max");
        assert_eq!(v["mcpOAuth"]["keep"], "me");
    }

    // Some servers renew the access token without issuing a new refresh token.
    // Dropping the old one then would leave the account unable to renew again.
    #[test]
    fn a_response_without_a_new_refresh_token_keeps_the_old_one() {
        let resp = r#"{"access_token":"NEW-AT","expires_in":3600}"#;
        let merged = merge_response(BLOB.as_bytes(), resp, 0).expect("merged");
        let v: serde_json::Value = serde_json::from_slice(&merged).unwrap();
        assert_eq!(v["claudeAiOauth"]["refreshToken"], "OLD-RT");
    }

    #[test]
    fn an_answer_with_no_access_token_is_not_merged() {
        assert!(merge_response(BLOB.as_bytes(), r#"{"error":"invalid_grant"}"#, 0).is_none());
        assert!(merge_response(BLOB.as_bytes(), "not json", 0).is_none());
        assert!(merge_response(b"not json", r#"{"access_token":"X"}"#, 0).is_none());
    }

    #[test]
    fn an_expired_refresh_token_is_named_rather_than_retried() {
        let now = 1_800_000_000_000i64;
        let blob = format!(
            r#"{{"claudeAiOauth":{{"refreshToken":"R","refreshTokenExpiresAt":{}}}}}"#,
            now - 1
        );
        assert!(refresh_token_expired(blob.as_bytes(), now));
        let msg = RefreshError::Expired.remedy("work", "claude-code");
        assert!(msg.contains("swapdex run work"), "names the way out: {msg}");
        // Unknown is not expired.
        assert!(!refresh_token_expired(br#"{"claudeAiOauth":{}}"#, now));
    }

    #[test]
    fn the_request_names_the_grant_and_the_client() {
        let b = request_body("RT-1");
        let v: serde_json::Value = serde_json::from_str(&b).unwrap();
        assert_eq!(v["grant_type"], "refresh_token");
        assert_eq!(v["refresh_token"], "RT-1");
        assert_eq!(v["client_id"], CLIENT_ID);
    }

    // A refusal has to read as something the user can act on, never as data loss.
    #[test]
    fn a_refusal_is_reported_in_the_users_terms() {
        assert_eq!(
            short_reason(r#"{"error":"invalid_grant","error_description":"token revoked"}"#),
            "token revoked"
        );
        assert_eq!(
            short_reason(r#"{"error":{"type":"rate_limit_error","message":"Rate limited."}}"#),
            "Rate limited."
        );
        assert_eq!(
            short_reason("<html>502</html>"),
            "the login server refused it"
        );
        // Rate limiting is a wait, not a verdict: telling someone to sign in
        // again over it would cost them a login they did not need.
        let busy = RefreshError::Busy.remedy("work", "claude-code");
        assert!(busy.contains("is fine"), "{busy}");
        assert!(!busy.contains("swapdex run"), "not a sign-in: {busy}");
        let msg = RefreshError::InUse.remedy("work", "claude-code");
        assert!(msg.contains("renewal deferred"), "name the outcome: {msg}");
        assert!(
            msg.contains("refresh unverified"),
            "name uncertainty: {msg}"
        );
        assert!(!msg.contains("re-login"), "not a rejection verdict: {msg}");
    }
}

/// How long before an access token lapses a keep-alive sweep renews it.
///
/// Deliberately wide. "Is this token unusable right NOW" is a different
/// question, asked when a turn is waiting, and answered on the serving path by
/// `slot_token_expired` and `has_usable_login`. This one answers "will this
/// account still work tomorrow", and the sweep runs whether or not anybody is
/// using the account.
pub const KEEP_ALIVE_WINDOW_MS: i64 = 6 * 60 * 60 * 1000;

/// Should a keep-alive sweep renew this credential now?
///
/// An OAuth refresh token is not a key that sits still - it is exercised, and it
/// rotates. Leave an account idle long enough and its refresh token goes stale,
/// and then only a browser sign-in brings it back. Three of this machine's
/// accounts died exactly that way and stayed dead for a week.
///
/// So the sweep renews ahead of expiry rather than at it. Nothing to renew, or a
/// refresh token already gone, is not this function's problem: renewing needs a
/// refresh token, and a dead one needs a human.
pub fn wants_keep_alive(blob: &[u8], now_ms: i64) -> bool {
    let Ok(v) = serde_json::from_slice::<serde_json::Value>(blob) else {
        return false;
    };
    let oauth = &v["claudeAiOauth"];
    if oauth["refreshToken"].as_str().is_none_or(str::is_empty) {
        return false;
    }
    if refresh_token_expired(blob, now_ms) {
        return false;
    }
    oauth["expiresAt"]
        .as_i64()
        .is_some_and(|exp| exp - now_ms <= KEEP_ALIVE_WINDOW_MS)
}

/// How long before a Codex access token lapses the sweep renews it.
///
/// Claude's token lives an hour, so any daily use renews it and the sweep is a
/// safety net. Codex's lives ten days and ONLY a Codex run renews it, so for an
/// account nobody has opened the sweep is the only thing standing between it and
/// a re-login. Two days is late enough that a daily sweep renews about once a
/// week rather than every pass - each renewal rotates the refresh token, and
/// rotating one more often than needed is its own risk.
pub const KEEP_ALIVE_CODEX_WINDOW_SECS: i64 = 2 * 24 * 60 * 60;

/// Should a keep-alive sweep renew this Codex credential now?
///
/// The deadline is in the access token's own `exp` claim. A credential with no
/// refresh token cannot be renewed from here, and a deadline that could not be
/// read is not an expired one - neither is grounds for spending a refresh token.
pub fn wants_keep_alive_codex(blob: &[u8], now_secs: i64) -> bool {
    let Ok(v) = serde_json::from_slice::<serde_json::Value>(blob) else {
        return false;
    };
    if v["tokens"]["refresh_token"]
        .as_str()
        .is_none_or(str::is_empty)
    {
        return false;
    }
    v["tokens"]["access_token"]
        .as_str()
        .and_then(crate::proxy::codex::jwt_expiry)
        .is_some_and(|exp| exp - now_secs <= KEEP_ALIVE_CODEX_WINDOW_SECS)
}

/// A keep-alive pass distinguishes an OAuth renewal from a native client that
/// already owns usable access. A deferred account is due, but the safety guard
/// could not prove that the live holder can serve it.
#[derive(Debug, Default)]
pub(crate) struct KeepAliveReport {
    pub(crate) renewed: Vec<String>,
    pub(crate) native_managed: Vec<String>,
    pub(crate) deferred: Vec<String>,
    pub(crate) failed: Vec<(String, RefreshError)>,
}

/// Whether current local evidence says this Codex slot is due for renewal but
/// held by a live session. This deliberately uses the same deadline predicate
/// and account-aware process guard as the refresh path itself.
pub(crate) fn codex_renewal_deferred(paths: &Paths, dir: &Path, now_secs: i64) -> bool {
    std::fs::read(dir.join("auth.json")).is_ok_and(|blob| {
        wants_keep_alive_codex(&blob, now_secs) && slot_in_use(paths, dir, "codex")
    })
}

/// The Codex half of the keep-alive sweep.
///
/// The sweep was written because an idle account's refresh token goes stale, and
/// it looked at Claude alone. A Codex account is idle BY DESIGN between runs -
/// which is the case the sweep exists for, and the one it did not cover.
pub fn keep_alive_sweep_codex(
    paths: &Paths,
    slots: &[(String, std::path::PathBuf)],
    now_ms: i64,
) -> (Vec<String>, Vec<(String, RefreshError)>) {
    let report = keep_alive_sweep_codex_report(paths, slots, now_ms);
    (report.renewed, report.failed)
}

pub(crate) fn keep_alive_sweep_codex_report(
    paths: &Paths,
    slots: &[(String, std::path::PathBuf)],
    now_ms: i64,
) -> KeepAliveReport {
    let mut report = KeepAliveReport::default();
    for (name, dir) in slots {
        let Ok(blob) = std::fs::read(dir.join("auth.json")) else {
            continue;
        };
        if !wants_keep_alive_codex(&blob, now_ms / 1000) {
            continue;
        }
        match refresh_codex_slot(paths, dir, now_ms) {
            Ok(RefreshOutcome::Renewed) => report.renewed.push(name.clone()),
            Ok(RefreshOutcome::NativeManaged) => report.native_managed.push(name.clone()),
            Err(RefreshError::InUse) => report.deferred.push(name.clone()),
            Err(e) => report.failed.push((name.clone(), e)),
        }
    }
    report
}

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

    /// A remedy that names `run` must name the tool, because `run` defaults to
    /// Claude.
    ///
    /// `Expired` is what a retired refresh token answers with - Codex returns
    /// 400/401/403 - which is the silent logout this project exists to prevent.
    /// The person reading it has a dead Codex account and was told `swapdex run
    /// <name>`; that launches Claude and registers a second account under the
    /// same name. `sign_in_remedy` in commands.rs was written for exactly this
    /// mistake, and these strings never got it.
    #[test]
    fn a_codex_remedy_names_codex() {
        for e in [RefreshError::Expired, RefreshError::NoCredential] {
            let msg = e.remedy("cxwork", "codex");
            assert!(
                msg.contains("swapdex run cxwork"),
                "the remedy stopped naming `run`, so this test measures nothing: {msg}"
            );
            assert!(
                msg.contains("swapdex run cxwork --tool codex"),
                "a Codex remedy names a command that runs Claude: {msg}"
            );
        }
    }

    /// The other direction: Claude is `run`'s default, so naming it is noise.
    #[test]
    fn a_claude_remedy_carries_no_tool_flag() {
        for e in [RefreshError::Expired, RefreshError::NoCredential] {
            let msg = e.remedy("work", "claude-code");
            assert!(
                msg.contains("swapdex run work"),
                "the remedy stopped naming `run`: {msg}"
            );
            assert!(
                !msg.contains("--tool"),
                "Claude is run's default; spelling it out is noise: {msg}"
            );
        }
    }
}

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

    fn jwt(exp: i64) -> String {
        use base64::Engine;
        let b64 = |b: &[u8]| base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(b);
        format!(
            "{}.{}.sig",
            b64(br#"{"alg":"none"}"#),
            b64(format!(r#"{{"exp":{exp}}}"#).as_bytes())
        )
    }

    fn blob(exp: i64, refresh: &str) -> Vec<u8> {
        format!(
            r#"{{"tokens":{{"access_token":"{}","account_id":"a","refresh_token":"{refresh}"}}}}"#,
            jwt(exp)
        )
        .into_bytes()
    }

    /// The sweep exists because an idle account's refresh token goes stale. A
    /// Codex account is idle BY DESIGN between runs - Codex renews only when
    /// Codex runs, so the token dies exactly ten days later - which makes it the
    /// case the sweep was written for, and it was the one tool the sweep did not
    /// look at.
    #[test]
    fn a_codex_token_near_its_deadline_wants_renewing() {
        let now = 1_788_743_000i64;
        assert!(
            wants_keep_alive_codex(&blob(now + 3600, "R"), now),
            "an hour left"
        );
        assert!(
            wants_keep_alive_codex(&blob(now - 86_400, "R"), now),
            "already lapsed"
        );
        assert!(
            !wants_keep_alive_codex(&blob(now + 9 * 86_400, "R"), now),
            "nine days left is not the sweep's business yet"
        );
    }

    /// Renewing needs a refresh token, and a deadline swapdex could not read is
    /// not a deadline: neither is grounds for spending one.
    #[test]
    fn the_sweep_leaves_alone_what_it_cannot_renew() {
        let now = 1_788_743_000i64;
        assert!(
            !wants_keep_alive_codex(&blob(now + 60, ""), now),
            "no refresh token"
        );
        assert!(
            !wants_keep_alive_codex(
                br#"{"tokens":{"access_token":"not-a-jwt","refresh_token":"R"}}"#,
                now
            ),
            "an unreadable deadline is not an expired one"
        );
        assert!(!wants_keep_alive_codex(b"not json", now));
    }
}

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

    fn blob(expires_in_ms: i64, refresh: &str, refresh_expiry: Option<i64>) -> Vec<u8> {
        let now = 1_700_000_000_000i64;
        let mut o = serde_json::json!({
            "claudeAiOauth": {
                "accessToken": "a",
                "refreshToken": refresh,
                "expiresAt": now + expires_in_ms,
            }
        });
        if let Some(r) = refresh_expiry {
            o["claudeAiOauth"]["refreshTokenExpiresAt"] = (now + r).into();
        }
        serde_json::to_vec(&o).unwrap()
    }
    const NOW: i64 = 1_700_000_000_000;

    #[test]
    fn an_idle_account_is_renewed_before_it_lapses() {
        let hour = 60 * 60 * 1000;
        assert!(
            wants_keep_alive(&blob(2 * hour, "r", None), NOW),
            "two hours left is inside the window"
        );
        assert!(
            !wants_keep_alive(&blob(12 * hour, "r", None), NOW),
            "half a day left needs nothing yet"
        );
    }

    /// Renewing takes a refresh token. Without one - or with one already gone -
    /// the sweep has nothing to do, and only a sign-in helps.
    #[test]
    fn there_is_nothing_to_sweep_without_a_live_refresh_token() {
        let hour = 60 * 60 * 1000;
        assert!(
            !wants_keep_alive(&blob(hour, "", None), NOW),
            "no refresh token"
        );
        assert!(
            !wants_keep_alive(&blob(hour, "r", Some(-1)), NOW),
            "the refresh token itself has expired"
        );
    }

    #[test]
    fn nonsense_is_never_swept() {
        assert!(!wants_keep_alive(b"not json", NOW));
        assert!(!wants_keep_alive(br#"{"claudeAiOauth":{}}"#, NOW));
    }
}

/// Renew every idle account whose token is heading for expiry. Returns the names
/// it renewed and the ones it could not, so a caller can say what happened.
///
/// Deliberately per-account and forgiving: one account's dead refresh token must
/// not stop the sweep reaching the next. `refresh_slot` refuses a slot the tool
/// is running in, which is the guard that keeps this from logging anyone out.
pub fn keep_alive_sweep(
    paths: &Paths,
    slots: &[(String, std::path::PathBuf)],
    now_ms: i64,
) -> (Vec<String>, Vec<(String, RefreshError)>) {
    let report = keep_alive_sweep_report(paths, slots, now_ms);
    (report.renewed, report.failed)
}

pub(crate) fn keep_alive_sweep_report(
    paths: &Paths,
    slots: &[(String, std::path::PathBuf)],
    now_ms: i64,
) -> KeepAliveReport {
    let mut report = KeepAliveReport::default();
    for (name, dir) in slots {
        let Ok(credential) = read_credential(dir) else {
            continue;
        };
        if !wants_keep_alive(credential.bytes(), now_ms) {
            continue;
        }
        match refresh_slot(paths, dir, now_ms) {
            Ok(RefreshOutcome::Renewed) => report.renewed.push(name.clone()),
            Ok(RefreshOutcome::NativeManaged) => report.native_managed.push(name.clone()),
            Err(RefreshError::InUse) => report.deferred.push(name.clone()),
            Err(e) => report.failed.push((name.clone(), e)),
        }
    }
    report
}

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

    #[test]
    fn dedupe_uses_provider_qualified_account_identity() {
        let root = tempfile::tempdir().unwrap();
        let a = root.path().join("a");
        let b = root.path().join("b");
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();
        for dir in [&a, &b] {
            std::fs::write(
                dir.join(".claude.json"),
                br#"{"oauthAccount":{"accountUuid":"same-id"}}"#,
            )
            .unwrap();
            std::fs::write(
                dir.join("auth.json"),
                br#"{"tokens":{"account_id":"same-id"}}"#,
            )
            .unwrap();
        }
        assert_eq!(
            claim_key(&a, "claude-code"),
            claim_key(&b, "claude-code"),
            "two directories holding one Claude account share a claim"
        );
        assert_ne!(
            claim_key(&a, "claude-code"),
            claim_key(&b, "codex"),
            "equal provider-local ids are not the same account"
        );
    }

    /// Standing down is not the login server refusing, and must not read as it.
    #[test]
    fn standing_down_is_its_own_answer() {
        let e = RefreshError::AlreadyRefreshing;
        let r = e.remedy("rnd", "claude-code");
        assert!(
            !r.to_lowercase().contains("sign in"),
            "nobody needs to sign in: {r}"
        );
        assert!(r.contains("rnd"), "name the account: {r}");
    }
}

// The one test inside is Linux-only, so on every other platform the module is
// empty and its `use super::*` is an unused import that `-D warnings` rejects.
// Gate the MODULE, not the test: a body that can vanish takes its imports with
// it. Only a macOS runner ever saw this, and the local gate runs on Linux.
#[cfg(all(test, target_os = "linux"))]
mod codex_in_use_tests {
    use super::*;

    /// The Codex renewal refuses a slot a live session is on.
    ///
    /// This is the guard `refresh_codex_slot` documents, and the reason the
    /// keep-alive sweep cannot log an account out: the session in that slot
    /// holds the refresh token the renewal retires, so its own next renewal
    /// would fail. The slot deliberately has no `auth.json`, so a renewal that
    /// gets past the guard stops at `NoCredential` - what this asserts against -
    /// without reaching the network.
    #[test]
    fn a_running_session_refuses_the_renewal() {
        let root = std::env::temp_dir().join(format!("swapdex_cx_ref_{}", std::process::id()));
        let slot = root.join("slot");
        std::fs::create_dir_all(&slot).unwrap();
        let bin = root.join("codex");
        // Keep the requested comm without executing a freshly written file,
        // which can produce ETXTBSY while concurrent tests spawn children.
        let sleep = if std::path::Path::new("/bin/sleep").exists() {
            "/bin/sleep"
        } else {
            "/usr/bin/sleep"
        };
        std::os::unix::fs::symlink(sleep, &bin).unwrap();

        let mut child = std::process::Command::new(&bin)
            .arg("30")
            .env("CODEX_HOME", &slot)
            .spawn()
            .unwrap();
        // Wait for the exec, not for the code under test: a process is only on
        // its slot once its environment exists.
        let environ = format!("/proc/{}/environ", child.id());
        for _ in 0..300 {
            if std::fs::read(&environ).is_ok_and(|b| !b.is_empty()) {
                break;
            }
            std::thread::sleep(std::time::Duration::from_millis(10));
        }
        let paths = Paths::rooted(&root);
        let verdict = refresh_codex_slot(&paths, &slot, 1_700_000_000_000);
        let _ = child.kill();
        let _ = child.wait();
        let _ = std::fs::remove_dir_all(&root);

        assert!(
            matches!(verdict, Err(RefreshError::InUse)),
            "renewed a slot a live session holds: {verdict:?}"
        );
    }
}

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

    fn blob(refresh_exp: i64) -> String {
        format!(
            r#"{{"claudeAiOauth":{{"accessToken":"OLD-AT","refreshToken":"OLD-RT",
               "expiresAt":1000,"refreshTokenExpiresAt":{refresh_exp},
               "subscriptionType":"max"}}}}"#
        )
    }

    /// A renewal that mints a NEW refresh token must not keep the old one's
    /// deadline.
    ///
    /// The deadline describes the token it was issued with. Rotation retires
    /// that token, so the recorded moment now describes something that no
    /// longer exists - and `refresh_token_expired` reads it to decide whether
    /// renewing is even worth trying. Kept, it made every renewal leave the
    /// account one day closer to a sign-in swapdex would demand while holding
    /// a refresh token the server had just issued.
    #[test]
    fn a_rotated_refresh_token_does_not_inherit_the_old_deadline() {
        let now = 1_800_000_000_000i64;
        let dead_soon = now + 86_400_000; // tomorrow
        let out = merge_response(
            blob(dead_soon).as_bytes(),
            r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
            now,
        )
        .expect("merged");
        let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
        let o = &v["claudeAiOauth"];
        assert_eq!(o["refreshToken"], "NEW-RT", "the token rotated");
        assert!(
            !refresh_token_expired(&out, now + 2 * 86_400_000),
            "the new token inherited the retired one's deadline: {o}"
        );
    }

    /// When the server states the new token's lifetime, record it.
    #[test]
    fn a_stated_refresh_lifetime_is_recorded() {
        let now = 1_800_000_000_000i64;
        let out = merge_response(
            blob(now + 1000).as_bytes(),
            r#"{"access_token":"A","refresh_token":"R","expires_in":3600,
                "refresh_token_expires_in":604800}"#,
            now,
        )
        .expect("merged");
        let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(
            v["claudeAiOauth"]["refreshTokenExpiresAt"].as_i64(),
            Some(now + 604_800 * 1000),
            "the stated lifetime was not written"
        );
    }

    /// The sweep keeps wanting an account it has already renewed past the
    /// deadline it was signed in with.
    ///
    /// This is the whole chain the complaint was about. The sweep asks
    /// `wants_keep_alive`, which gives up when `refresh_token_expired` says the
    /// refresh token is gone - and that read the moment recorded at sign-in,
    /// which no renewal ever moved. So an account renewed every half hour for a
    /// week stopped being swept on the day its ORIGINAL token would have
    /// lapsed, while holding one the server had just issued, and the next thing
    /// the user saw was a browser sign-in.
    #[test]
    fn an_account_renewed_past_its_original_deadline_is_still_swept() {
        let now = 1_800_000_000_000i64;
        let signed_in_deadline = now + 86_400_000; // a day out, at sign-in
        let renewed = merge_response(
            blob(signed_in_deadline).as_bytes(),
            r#"{"access_token":"NEW-AT","refresh_token":"NEW-RT","expires_in":3600}"#,
            now,
        )
        .expect("merged");

        // A week later: long past the deadline the sign-in wrote down, with a
        // token that has been rotated all week.
        let later = now + 7 * 86_400_000;
        assert!(
            !refresh_token_expired(&renewed, later),
            "the sweep would call a freshly rotated token expired"
        );
        assert!(
            wants_keep_alive(&renewed, later),
            "the sweep stopped renewing an account that is still renewable"
        );
    }

    /// A renewal that does NOT rotate keeps the deadline it had.
    ///
    /// The old token is still the live one, so its deadline still describes
    /// something real. Dropping it there would throw away the one signal that
    /// says a sign-in is genuinely needed.
    #[test]
    fn a_renewal_without_rotation_keeps_the_deadline() {
        let now = 1_800_000_000_000i64;
        let deadline = now + 86_400_000;
        let out = merge_response(
            blob(deadline).as_bytes(),
            r#"{"access_token":"NEW-AT","expires_in":3600}"#,
            now,
        )
        .expect("merged");
        let v: serde_json::Value = serde_json::from_slice(&out).unwrap();
        assert_eq!(
            v["claudeAiOauth"]["refreshTokenExpiresAt"].as_i64(),
            Some(deadline),
            "the live token's deadline was discarded"
        );
    }
}