pitboard-core 0.14.0

The engine behind Pitboard: switches Claude Code, Codex and Claude Desktop between accounts by parking and restoring their logins. Its API serves Pitboard's own front ends.
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
//! Putting away the login Claude Code left in a file behind the keychain, when somebody asks.
//!
//! A sign-in where the keychain could not be read leaves its login in `.credentials.json` and
//! the keychain's where it was (the register's `locked_sign_in_writes_fallback`), and nothing
//! of Claude Code's deletes the file while the keychain holds a login
//! (`fallback_outlives_keychain_writes`). While it is there, sessions already running take a
//! switch only at their login's next renewal (`fallback_file_pins_session_login`).
//!
//! The file goes only once the login it held is somewhere Pitboard can switch to it from, or
//! is shown to be there already, by its refresh token's fingerprint, or to be dead, by
//! Anthropic refusing its refresh token. Whose it is comes from that fingerprint where it is a
//! login Pitboard knows, and otherwise from Anthropic, asked with the login's own access token.
//! Where that has expired, the login is renewed as Claude Code renews it and written back to
//! the file before anything else ([`super::refresh`]). Claude Code's refresh lock is held from
//! the last reading of the file until it is gone, so no session spends the refresh token
//! counted on meanwhile (`refresh_lock`). So a run that stops anywhere leaves the login in the
//! file, in a park, or in both, or, between Anthropic answering a renewal and the answer
//! reaching the file, in the vault copy the next change saves there. One that cannot be saved,
//! as where a sign-in replaced the file's login meanwhile, is said to be spent. Left in both,
//! the park is written down as a copy of the file's login (`State::from_file`), and the next
//! run parks what the file holds by then in its place: a session that signs in with the file
//! may have renewed it since, spending the park's refresh token. Any other park the account
//! can be switched to is kept, and the file's login goes with the file.

use super::refresh::{self, Place, Progress, Refreshing, Renewed, Stop};
use super::{Settled, identify, live_store, purge, read_stored, shape, write_lock};
use crate::context::Context;
use crate::error::{Cause, Error, Partway, Result};
use crate::provider::Owner;
use crate::provider::claude::live;
use crate::provider::{self, ProviderError, ProviderId};
use crate::service::{Permit, Warning};
use crate::state::{self, Account, State};
use crate::store::{self, RawStore};
use crate::{fault, lock, park};
use serde_json::Value;
use std::path::{Path, PathBuf};

/// The one tool that keeps a file behind the store it keeps its login in.
const TOOL: ProviderId = ProviderId::Claude;

/// What is left in the file behind the store Claude Code keeps its login in, as putting it
/// away is confirmed for.
#[derive(Debug, Clone, PartialEq)]
pub struct Left {
    pub path: PathBuf,
    /// A handle on what the file holds, byte for byte, never what it holds: it is put away
    /// only while it still holds what this was taken of.
    pub seen: String,
    /// What putting it away would do with the login it holds, as far as can be told without
    /// renewing it.
    pub login: Foreseen,
    /// Its other keys, by name, such as `mcpOAuth`, which are not Pitboard's to move.
    pub dropped: Vec<String>,
}

impl Left {
    /// What putting it away is refused with where the look says so already: a login of an
    /// account nobody enrolled here, which nothing is asked about.
    pub fn refusal(&self) -> Option<Error> {
        match &self.login {
            Foreseen::NotEnrolled(owner) => Some(not_enrolled(&self.path, owner)),
            Foreseen::Kept(_) | Foreseen::Untold => None,
        }
    }
}

/// What putting the file away would do with the login it holds.
#[derive(Debug, Clone, PartialEq)]
pub enum Foreseen {
    Kept(Kept),
    /// The login of an account nobody enrolled here: it is refused, deleting nothing.
    NotEnrolled(Owner),
    /// Its access token has expired, so whose it is can be asked only once it is renewed,
    /// which only putting it away does.
    Untold,
}

/// What putting the file away did with the login it held. `label` is the account's name as a
/// command takes it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Kept {
    /// It held none.
    NoLogin,
    /// It can no longer be used: Anthropic refuses its refresh token for good, or it has none
    /// and its access token has expired.
    Refused,
    /// The very login Claude Code has stored, `label`'s where that account is enrolled.
    Stored { label: Option<String> },
    /// The very login Pitboard keeps parked for `label`.
    AlreadyParked { label: String },
    /// Another login of `label`, the account whose login Claude Code has stored: a second
    /// sign-in of it, dropped.
    SecondSignIn { label: String },
    /// `label`'s, which held no parked login it could be switched to in its place: parked for
    /// it.
    ParkedNow { label: String },
    /// Another login of `label`, which keeps the parked login it can be switched to.
    ParkKept { label: String },
}

impl Kept {
    /// Stable, for a program to branch on, and the outcome the activity log records.
    pub fn code(&self) -> &'static str {
        match self {
            Kept::NoLogin => "no_login",
            Kept::Refused => "login_refused",
            Kept::Stored { .. } => "stored",
            Kept::AlreadyParked { .. } => "already_parked",
            Kept::SecondSignIn { .. } => "second_sign_in",
            Kept::ParkedNow { .. } => "parked",
            Kept::ParkKept { .. } => "park_kept",
        }
    }

    /// The enrolled account the login is of, by its name, where that is known.
    pub fn account(&self) -> Option<&str> {
        match self {
            Kept::NoLogin | Kept::Refused => None,
            Kept::Stored { label } => label.as_deref(),
            Kept::AlreadyParked { label }
            | Kept::SecondSignIn { label }
            | Kept::ParkedNow { label }
            | Kept::ParkKept { label } => Some(label),
        }
    }
}

/// The file put away: what became of the login it held, and the keys that went with it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Stowed {
    pub path: PathBuf,
    pub kept: Kept,
    pub dropped: Vec<String>,
}

/// What is left in the file behind Claude Code's store, and what putting it away would do
/// with it: `None` where nothing is behind that store, which is always so where the file is
/// the store, as on Linux. Takes no lock and writes nothing. It asks Anthropic whose the login
/// in the file is, with that login's own access token, where neither its fingerprint nor its
/// expiry already says; and where that names an enrolled account, whose the login stored is,
/// as a read asks it, where that has changed since Anthropic last named it. Where telling
/// that needs the login stored renewed, which only putting the file away does, whose Pitboard
/// last recorded it to be stands in.
pub(crate) fn find(ctx: &Context, state: &State) -> Result<Option<Left>> {
    let tool = provider::claude_code();
    let path = live::credential_file(ctx);
    let live = live_store(ctx, tool)?;
    let Some((_, raw)) = read_left(&live)? else {
        return Ok(None);
    };
    let held = contents(&raw)?;
    let stored = read_stored(tool, &live)?.map(|(_, document)| document);
    let login = match judge(ctx, state, &held, stored.as_ref(), &path)? {
        Whose::Kept(kept) => Foreseen::Kept(kept),
        Whose::Untold => Foreseen::Untold,
        Whose::Owner(owner) => match state.account_of(TOOL, &owner) {
            None => Foreseen::NotEnrolled(owner),
            Some(account) => {
                let told = stored
                    .map(|document| identify::told(ctx, state, tool, &document))
                    .transpose()
                    .map_err(|e| super::unidentified(TOOL, e))?;
                let stored = match told {
                    None => None,
                    Some(Some(found)) => Some(found.owner),
                    Some(None) => state.in_use(TOOL).and_then(|known| known.owner.clone()),
                };
                Foreseen::Kept(kept_for(ctx, state, account, stored.as_ref())?)
            }
        },
    };
    Ok(Some(Left {
        path,
        seen: store::fingerprint(&raw),
        login,
        dropped: held.dropped,
    }))
}

/// Puts away the file behind Claude Code's store, while it holds what `seen` was taken of:
/// keeps the login it holds where it is not kept already or dead, then deletes the file.
/// Whatever stops it is said with how far it had gone ([`Error::StowStopped`]). A renewal of
/// the login stored that is lost is said by itself ([`Error::RenewalLost`]): it is lost
/// before anything of the file's moves.
///
/// Under Pitboard's lock throughout. A renewal of Claude Code's login left waiting is saved
/// first, and where it cannot be yet, why stops it with nothing changed
/// ([`refresh::finished`]). Whose the login is, where that can be asked as it is, is asked
/// next, holding up nobody. From the file's last reading until it is gone, under
/// Claude Code's refresh lock too, which a session takes before it sends a refresh token, so
/// none spends the file's meanwhile. Claude Code's write lock is taken after it, as Claude
/// Code takes them, around the renewed login's write and the file's deletion only, and once
/// before a renewal to find it free, so no network round trip holds up its writes. The file,
/// and the login stored where the file goes because of it, are read again under it as the
/// file goes, since a `/logout` that gave up waiting writes with no lock held.
pub(crate) fn stow(settled: Settled, seen: &str) -> Result<(Stowed, Vec<Warning>)> {
    let Settled {
        _exclusive,
        mut state,
        ctx,
        permit,
    } = settled;
    let mut stowing = Stowing {
        ctx: &ctx,
        permit,
        path: live::credential_file(&ctx),
        partway: Partway::Nothing,
        warnings: Vec::new(),
        lock_lost: false,
    };
    let done = stowing.run(&mut state, seen);
    let Stowing {
        partway, warnings, ..
    } = stowing;
    match done {
        Ok(stowed) => {
            purge(&ctx, permit, &mut state);
            Ok((stowed, warnings))
        }
        // Telling whose login is stored lost its renewal, before anything of the file's, and
        // the error says what became of that login.
        Err(lost @ Error::RenewalLost { .. }) => Err(lost),
        // Not purged: a park that could not be recorded in place of another leaves the other
        // released here and still named in the file.
        Err(error) => Err(Error::StowStopped {
            partway,
            warnings,
            error: Box::new(error),
        }),
    }
}

/// One run of [`stow`]: how far it has gone, and what it warned of, as it goes.
struct Stowing<'a> {
    ctx: &'a Context,
    permit: Permit,
    path: PathBuf,
    partway: Partway,
    warnings: Vec<Warning>,
    /// A lock of Claude Code's stopped being Pitboard's while it held it.
    lock_lost: bool,
}

impl Stowing<'_> {
    fn run(&mut self, state: &mut State, seen: &str) -> Result<Stowed> {
        let (ctx, permit) = (self.ctx, self.permit);
        let tool = provider::claude_code();
        refresh::finished(ctx, permit, state, TOOL)?;
        let live = live_store(ctx, tool)?;
        let (_, mut raw) = read_left(&live)?
            .filter(|(_, raw)| store::fingerprint(raw) == seen)
            .ok_or_else(|| self.changed())?;
        let mut held = contents(&raw)?;
        let stored = read_stored(tool, &live)?.map(|(_, document)| document);
        let judged = judge(ctx, state, &held, stored.as_ref(), &self.path)?;
        if let Whose::Owner(owner) = &judged
            && state.account_of(TOOL, owner).is_none()
        {
            return Err(not_enrolled(&self.path, owner));
        }
        // Whose login Claude Code has stored, told and recorded as a switch tells it, where a
        // second sign-in of the account in use is to be told apart. Either way `stored` is the
        // login stored that the file's was told by.
        let (stored, stored_owner) = match judged {
            Whose::Kept(_) => (stored, None),
            Whose::Owner(_) | Whose::Untold => match self.told(state)? {
                identify::Live::Login(login) => {
                    self.lock_lost |= login.lock_lost;
                    (Some(login.document), Some(login.owner))
                }
                identify::Live::Nothing => (None, None),
            },
        };
        fault::point("stow.identified");

        let refreshing = Refreshing::take(ctx, permit, tool)?;
        if unchanged(&live, &raw)?.is_none() {
            return Err(self.changed());
        }
        let kept = match judged {
            Whose::Kept(kept) => kept,
            Whose::Owner(owner) => self.keep(state, &owner, stored_owner.as_ref(), &held)?,
            Whose::Untold => match self.renew(state, &live, &mut raw, &mut held)? {
                None => Kept::Refused,
                Some(owner) => self.keep(state, &owner, stored_owner.as_ref(), &held)?,
            },
        };
        fault::point("stow.kept");

        let writing = write_lock(ctx, permit, tool)?;
        let file = unchanged(&live, &raw)?.ok_or_else(|| self.changed())?;
        // A file that goes because of the login stored, as that very login or a second
        // sign-in of its account, goes only while Claude Code has still stored the login it
        // was told by.
        if matches!(kept, Kept::Stored { .. } | Kept::SecondSignIn { .. })
            && !still_stored(&live, stored.as_ref())?
        {
            return Err(Error::StoredLoginChanged {
                path: self.path.clone(),
            });
        }
        file.delete(permit, &live.service)?;
        // Unsaved, a park stays written down as a copy of a file that has gone, and the next
        // file's login of that account is parked in its place: nothing is lost by it.
        if state.file_gone() {
            let _ = state::save(ctx, permit, state);
        }
        self.lock_lost |= let_go(writing) | Refreshing::let_go(refreshing);
        if self.lock_lost {
            self.warnings.push(Warning::LockCompromised { tool: TOOL });
        }
        Ok(Stowed {
            path: self.path.clone(),
            kept,
            dropped: held.dropped,
        })
    }

    /// Whose login Claude Code has stored, told as a change tells it ([`identify::now`]).
    /// Telling may renew that login, and a renewal whose answer could not be saved there
    /// waits in the vault, which is how far this run went. Nothing waited for that slot
    /// before, as [`refresh::finished`] saw first.
    fn told(&mut self, state: &mut State) -> Result<identify::Live> {
        let told = identify::now(self.ctx, self.permit, state, provider::claude_code());
        if told.is_err() && state.renewing.iter().any(|left| left.tool == TOOL) {
            self.partway = Partway::StoredRenewedKept;
        }
        told
    }

    /// Renews the login in `held` and writes the renewed login back into the file before
    /// anything else, as [`refresh::renew`] does, read from the file itself, since the store
    /// in front of it need not answer for this. Then asks whose it is. `None` where Anthropic
    /// refuses the refresh token for good.
    fn renew(
        &mut self,
        state: &mut State,
        live: &provider::LiveStore,
        raw: &mut String,
        held: &mut Contents,
    ) -> Result<Option<Owner>> {
        let tool = provider::claude_code();
        let slice = held.slice.clone().expect("only a login is renewed");
        let file = self.ctx.host().file(self.path.clone());
        let place = Place {
            store: file.as_ref(),
            service: &live.service,
        };
        let mut progress = Progress::default();
        let renewed = refresh::renew(
            self.ctx,
            self.permit,
            state,
            tool,
            place,
            raw,
            &slice,
            &mut progress,
        );
        self.lock_lost |= progress.lock_lost;
        if progress.saved {
            self.partway = Partway::Renewed;
        } else if progress.kept {
            self.partway = Partway::RenewedKept;
        } else if progress.spent {
            self.partway = Partway::RenewedUnwritten;
        }
        let renewed = match renewed {
            Ok(Renewed::Saved(renewed)) => renewed,
            Ok(Renewed::Refused) => return Ok(None),
            Err(Stop::Changed) => return Err(self.changed()),
            Err(Stop::Unrenewed(error)) => return Err(not_identified(&self.path, &error)),
            Err(Stop::Failed(error)) => return Err(error),
        };
        *held = contents(&renewed)?;
        *raw = renewed;
        let login = held.slice.clone().expect("a renewed login");
        tool.identify(self.ctx, &provider::Credential::new(TOOL, login))
            .map(Some)
            .map_err(|error| not_identified(&self.path, &error))
    }

    /// What putting away `owner`'s login comes to, where Claude Code has `stored`'s login
    /// stored, parking it where that is what keeps it.
    fn keep(
        &mut self,
        state: &mut State,
        owner: &Owner,
        stored: Option<&Owner>,
        held: &Contents,
    ) -> Result<Kept> {
        let account = state
            .account_of(TOOL, owner)
            .ok_or_else(|| not_enrolled(&self.path, owner))?;
        let kept = kept_for(self.ctx, state, account, stored)?;
        if let (Kept::ParkedNow { label }, Some(slice)) = (&kept, &held.slice) {
            let parking = park_for(self.ctx, self.permit, state, owner, slice)?;
            self.warnings.extend(parking);
            self.partway = Partway::Parked {
                label: label.clone(),
            };
        }
        Ok(kept)
    }

    fn changed(&self) -> Error {
        Error::LeftLoginChanged {
            path: self.path.clone(),
        }
    }
}

/// Lets go of Claude Code's write lock, saying whether it stopped being Pitboard's meanwhile.
fn let_go(writing: Option<lock::Guard>) -> bool {
    writing.as_ref().is_some_and(lock::Guard::compromised)
}

/// What the file behind the store in use holds, with the store it is in, or `None` where
/// nothing is behind that store.
fn read_left(live: &provider::LiveStore) -> Result<Option<(&dyn RawStore, String)>> {
    let Some(file) = store::behind(&live.chain, &live.service)? else {
        return Ok(None);
    };
    Ok(file.read(&live.service)?.map(|raw| (file, raw)))
}

/// The store the file is in, where it still holds `raw` byte for byte.
fn unchanged<'a>(live: &'a provider::LiveStore, raw: &str) -> Result<Option<&'a dyn RawStore>> {
    Ok(read_left(live)?
        .filter(|(_, now)| now == raw)
        .map(|(file, _)| file))
}

/// Whether Claude Code has still stored `judged`, the login stored that the file's was told
/// by.
fn still_stored(live: &provider::LiveStore, judged: Option<&Value>) -> Result<bool> {
    let tool = provider::claude_code();
    let login = |document: &Value| tool.slice(document).ok();
    let now = read_stored(tool, live)?.map(|(_, document)| document);
    Ok(now.as_ref().and_then(login) == judged.and_then(login))
}

/// What the file holds: the account's login in it, where there is one, and its other keys by
/// name.
struct Contents {
    slice: Option<Value>,
    dropped: Vec<String>,
}

/// What the file holds, told as every warning and doctor tell it ([`live::holds_a_login`]):
/// a file that is not a JSON object holds no login and no key, and one with no token holds
/// keys and no login.
fn contents(raw: &str) -> Result<Contents> {
    let document = live::document_in(raw);
    let slice = live::holds_a_login(&document)
        .then(|| provider::claude_code().slice(&document))
        .transpose()
        .map_err(|e| shape(TOOL, e))?;
    let login = slice.as_ref().and_then(Value::as_object);
    let dropped = document
        .as_object()
        .into_iter()
        .flat_map(serde_json::Map::keys)
        .filter(|key| !login.is_some_and(|login| login.contains_key(*key)))
        .cloned()
        .collect();
    Ok(Contents { slice, dropped })
}

/// Whose the login in the file is, as far as can be told without renewing it.
enum Whose {
    /// Kept already, or nothing to keep.
    Kept(Kept),
    Owner(Owner),
    /// Its access token has expired, or Anthropic refuses it as expired: renewing it tells
    /// whose it is.
    Untold,
}

/// By its refresh token's fingerprint first: the login `stored` is, the one parked for an
/// account, where that park reads back, or the one whose owner the record holds. Otherwise
/// Anthropic is asked with its own access token, where that has not expired.
fn judge(
    ctx: &Context,
    state: &State,
    held: &Contents,
    stored: Option<&Value>,
    path: &Path,
) -> Result<Whose> {
    let Some(slice) = &held.slice else {
        return Ok(Whose::Kept(Kept::NoLogin));
    };
    let tool = provider::claude_code();
    let login = tool.fingerprint(slice);
    // A login with no refresh token has no fingerprint, and matches nothing by it.
    if !login.is_empty() {
        if stored.is_some_and(|stored| tool.fingerprint(stored) == login) {
            let label = state
                .in_use(TOOL)
                .filter(|record| record.login == login)
                .and_then(|_| state.account_in_use(TOOL))
                .map(|account| state.typed(&account.key()));
            return Ok(Whose::Kept(Kept::Stored { label }));
        }
        if let Some((account, parked)) = state.accounts.iter().find_map(|account| {
            account
                .parked
                .as_ref()
                .filter(|park| account.provider() == TOOL && park.login == login)
                .map(|park| (account, park))
        }) {
            // A park that does not read back keeps nothing: the login is that account's, and
            // is parked in its place.
            return Ok(if reads_back(ctx, account, parked)? {
                Whose::Kept(Kept::AlreadyParked {
                    label: state.typed(&account.key()),
                })
            } else {
                Whose::Owner(account.owner())
            });
        }
        if let Some(owner) = state
            .in_use(TOOL)
            .filter(|record| record.login == login)
            .and_then(|record| record.owner.clone())
        {
            return Ok(Whose::Owner(owner));
        }
    }
    // Renewing it settles whose it is, where it has a refresh token to renew it with.
    let untold = || {
        if login.is_empty() {
            Whose::Kept(Kept::Refused)
        } else {
            Whose::Untold
        }
    };
    if tool
        .expiry(slice)
        .access_expires_at
        .is_some_and(|at| at <= ctx.now())
    {
        return Ok(untold());
    }
    match tool.identify(ctx, &provider::Credential::new(TOOL, slice.clone())) {
        Ok(found) => Ok(Whose::Owner(found)),
        // Expired earlier than its own expiry said, or with no access token at all.
        Err(ProviderError::Unauthorized | ProviderError::ShapeUnexpected { .. }) => Ok(untold()),
        Err(error) => Err(not_identified(path, &error)),
    }
}

/// What putting away `held`'s login, `account`'s, comes to, where Claude Code has `stored`'s
/// login stored.
fn kept_for(
    ctx: &Context,
    state: &State,
    account: &Account,
    stored: Option<&Owner>,
) -> Result<Kept> {
    let label = state.typed(&account.key());
    Ok(if stored.is_some_and(|stored| account.owned_by(stored)) {
        Kept::SecondSignIn { label }
    } else if switchable(ctx, state, account)? {
        Kept::ParkKept { label }
    } else {
        Kept::ParkedNow { label }
    })
}

/// Whether `account` holds a parked login to keep in place of the one in the file: one that
/// reads back as recorded, has not expired, and is not a copy an earlier put-away made of the
/// file's login before it stopped. A session that signs in with the file renews the login
/// there, which spends such a copy, and nothing here can tell that it did.
fn switchable(ctx: &Context, state: &State, account: &Account) -> Result<bool> {
    match account
        .parked
        .as_ref()
        .filter(|parked| parked.restorable_at(ctx.now()) && !state.is_from_file(&parked.service))
    {
        Some(parked) => reads_back(ctx, account, parked),
        None => Ok(false),
    }
}

/// Whether `parked`, `account`'s park, reads back as recorded. A vault that cannot be read
/// says nothing either way, and stops it.
fn reads_back(ctx: &Context, account: &Account, parked: &state::Park) -> Result<bool> {
    match park::load(ctx, provider::claude_code(), &account.key(), parked) {
        Ok(_) => Ok(true),
        Err(Error::Store(unreadable)) => Err(Error::Store(unreadable)),
        Err(_) => Ok(false),
    }
}

/// Parks `slice`, `owner`'s login, for that account, the way a sign-in of an account not in
/// use is parked, in place of any park it held, and records it. That the park copies the
/// file's login is written down before the copy is, so a run killed between the two leaves
/// no copy the next run would keep in place of what the file holds by then. What parking it
/// warned of.
fn park_for(
    ctx: &Context,
    permit: Permit,
    state: &mut State,
    owner: &Owner,
    slice: &Value,
) -> Result<Option<Warning>> {
    let account = state
        .account_of(TOOL, owner)
        .expect("parked only for an enrolled account");
    let (key, id, label) = (
        account.key(),
        account.id.clone(),
        state.typed(&account.key()),
    );
    let parking = park::price(
        ctx,
        TOOL,
        &label,
        &park::service_name(&id, ctx.now_millis()),
        slice,
    )?;
    let service = park::reserve(ctx, permit, &id)?;
    state.copying_from_file(&service);
    state::save(ctx, permit, state)?;
    let parked = park::store_at(ctx, permit, provider::claude_code(), &service, slice)?;
    fault::point("stow.park_stored");
    state.park(&key, parked);
    // Unrecorded, the park would be an item nothing refers to, never deleted.
    state::save(ctx, permit, state).inspect_err(|_| {
        let _ = store::vault_delete(ctx, permit, &service);
    })?;
    Ok(parking)
}

fn not_enrolled(path: &Path, owner: &Owner) -> Error {
    Error::LeftLoginNotEnrolled {
        path: path.to_path_buf(),
        email: owner.email.clone(),
        organization: owner.organization_uuid.clone(),
    }
}

/// Why nobody could say whose the login in the file is.
fn not_identified(path: &Path, error: &ProviderError) -> Error {
    Error::LeftLoginUnidentified {
        path: path.to_path_buf(),
        cause: Cause::of_provider(error),
        detail: error.to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::super::harness::{
        Machine, NOW, Session, account, audit_lines, document, lapsed, lets_go_of_the_write_lock,
        lock_dir, machine, oauth, owner, renews, renews_meanwhile, saves, state_file,
        takes_the_write_lock, write_target,
    };
    use super::super::settle;
    use super::*;
    use crate::api::scripted::{Asked, Trouble};
    use crate::service::Pitboard;
    use crate::store::memory::Fault;
    use serde_json::json;

    /// `contents` left in `.credentials.json` behind the keychain, as a sign-in where the
    /// keychain could not be read leaves it.
    fn leave(m: &Machine, contents: &Value) {
        left_file(m).plant(&m.service, &contents.to_string());
    }

    fn left_file(m: &Machine) -> std::sync::Arc<store::memory::MemoryStore> {
        m.mem.file_at(live::credential_file(&m.ctx))
    }

    /// What the file holds now, as its fingerprint, or `None` where it is gone.
    fn in_the_file(m: &Machine) -> Option<String> {
        let held = left_file(m).peek(&m.service)?;
        let document: Value = serde_json::from_str(&held).expect("JSON");
        Some(provider::document(TOOL).fingerprint(&document))
    }

    /// `label`, enrolled with nothing parked.
    fn enrolled(m: &Machine, label: &str) {
        let mut state = state::load(&m.ctx).expect("state");
        state.accounts.push(account(label, label, None));
        state::save(&m.ctx, Permit::for_a_test(), &state).expect("saved");
    }

    fn found(m: &Machine) -> Left {
        let state = state::load(&m.ctx).expect("state");
        find(&m.ctx, &state)
            .expect("a look")
            .expect("something left")
    }

    /// Putting away what is in the file now, confirmed as the look found it.
    fn stow_now(m: &Machine) -> Result<(Stowed, Vec<Warning>)> {
        let seen = found(m).seen;
        stow_seen(m, &seen)
    }

    fn stow_seen(m: &Machine, seen: &str) -> Result<(Stowed, Vec<Warning>)> {
        let settled = settle(&m.ctx, Permit::for_a_test(), Some(TOOL))?.0;
        stow(settled, seen)
    }

    /// [`stow_now`], with `elsewhere` writing at `point`, as another program writing at that
    /// moment would.
    fn stow_while(
        m: &Machine,
        point: &'static str,
        elsewhere: impl FnOnce() + 'static,
    ) -> Result<(Stowed, Vec<Warning>)> {
        let seen = found(m).seen;
        fault::meanwhile(point, elsewhere, || stow_seen(m, &seen))
    }

    /// Plants `contents` in the file at the moment it is called, as Claude Code writes it.
    fn rewrites_the_file(m: &Machine, contents: &Value) -> impl FnOnce() + 'static {
        let (file, service, contents) = (left_file(m), m.service.clone(), contents.to_string());
        move || file.plant(&service, &contents)
    }

    /// Locks the keychain at the moment it is called, as one locks under a session started
    /// over SSH.
    fn locks_the_keychain(m: &Machine) -> impl FnOnce() + 'static {
        let (keychain, service) = m.live_store();
        move || keychain.fault(&service, Fault::Locked)
    }

    /// Plants `document` in the keychain at the moment it is called, as a sign-in writes it.
    fn signs_in(m: &Machine, document: &Value) -> impl FnOnce() + 'static {
        let (keychain, service) = (std::sync::Arc::clone(m.mem.live()), m.service.clone());
        let document = document.to_string();
        move || keychain.plant(&service, &document)
    }

    /// `refresh`'s login as a renewal an hour after [`document`]'s gives it: its access token
    /// expires an hour later.
    fn renewed_later(refresh: &str) -> Value {
        let mut login = document(refresh);
        login["claudeAiOauth"]["expiresAt"] = json!((NOW + 7200) * 1000);
        login
    }

    fn parked_fingerprint(m: &Machine, label: &str) -> Option<String> {
        let state = state::load(&m.ctx).expect("state");
        let parked = state.get(&m.key(label))?.parked.clone()?;
        Some(parked.login)
    }

    fn fingerprint(refresh: &str) -> String {
        store::fingerprint(refresh)
    }

    /// The login Claude Code has stored, left in the file too, goes with the file: the
    /// keychain holds it, known by its fingerprint, so nobody is asked.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn the_login_claude_code_has_stored_goes_with_the_file() {
        let m = machine("stow-stored");
        leave(&m, &document("here-refresh"));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::Stored {
                label: Some("here".into())
            }
        );
        assert_eq!(stowed.dropped, ["mcpOAuth"]);
        assert_eq!(in_the_file(&m), None);
        assert_eq!(m.live(), Some(document("here-refresh")));
        assert!(m.api.asked().is_empty(), "{:?}", m.api.asked());
    }

    /// A login Pitboard keeps parked, left in the file too, goes with the file, and the park
    /// stays as it was.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_pitboard_keeps_parked_goes_with_the_file() {
        let m = machine("stow-already-parked");
        leave(&m, &json!({"claudeAiOauth": oauth("there-refresh", 30)}));
        let vault = m.mem.vault().services();

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::AlreadyParked {
                label: "there".into()
            }
        );
        assert_eq!(in_the_file(&m), None);
        assert_eq!(m.mem.vault().services(), vault);
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-refresh"))
        );
    }

    /// A park that does not read back keeps nothing, so the same login left in the file is
    /// parked in its place before the file goes: the park's record alone is not a login.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_whose_park_does_not_read_back_is_parked_in_its_place() {
        let m = machine("stow-park-gone");
        m.mem.vault().delete_everything();
        leave(&m, &json!({"claudeAiOauth": oauth("there-refresh", 30)}));
        let there = Kept::ParkedNow {
            label: "there".into(),
        };
        assert_eq!(found(&m).login, Foreseen::Kept(there.clone()));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(stowed.kept, there);
        assert_eq!(in_the_file(&m), None);
        let state = state::load(&m.ctx).expect("state");
        let parked = state
            .get(&m.key("there"))
            .and_then(|a| a.parked.clone())
            .expect("parked");
        let held = park::load(&m.ctx, provider::document(TOOL), &m.key("there"), &parked)
            .expect("it reads back");
        assert_eq!(held["claudeAiOauth"]["refreshToken"], "there-refresh");
        assert!(m.api.asked().is_empty(), "{:?}", m.api.asked());
    }

    /// Another login of the account in use is a second sign-in of it: the keychain holds a
    /// login of that account already, so this one is dropped with the file and nothing is
    /// parked.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn another_login_of_the_account_in_use_is_dropped_as_a_second_sign_in() {
        let m = machine("stow-second-sign-in");
        m.api.owned_by("access-here-again", owner("here"));
        leave(&m, &document("here-again"));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::SecondSignIn {
                label: "here".into()
            }
        );
        assert_eq!(in_the_file(&m), None);
        assert_eq!(m.live(), Some(document("here-refresh")));
        assert_eq!(parked_fingerprint(&m, "here"), None);
    }

    /// The login of an enrolled account Pitboard holds no login of is parked for it, and the
    /// file goes only once the park is recorded.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_of_an_account_with_nothing_parked_is_parked_before_the_file_goes() {
        let m = machine("stow-parks");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(in_the_file(&m), None);
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("elsewhere-refresh"))
        );
        let state = state::load(&m.ctx).expect("state");
        let parked = state
            .get(&m.key("elsewhere"))
            .and_then(|a| a.parked.clone())
            .expect("parked");
        let held = park::load(
            &m.ctx,
            provider::document(TOOL),
            &m.key("elsewhere"),
            &parked,
        )
        .expect("it reads back");
        assert_eq!(held["claudeAiOauth"]["refreshToken"], "elsewhere-refresh");
        assert!(
            held.get("mcpOAuth").is_none(),
            "the machine's keys are not the account's"
        );
    }

    /// An account whose park has expired holds no login it can be switched to, so the login
    /// in the file is parked in its place.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_of_an_account_whose_park_has_expired_takes_its_place() {
        let m = machine("stow-expired-park");
        let mut state = state::load(&m.ctx).expect("state");
        let expired = state
            .accounts
            .iter_mut()
            .find(|a| a.label == "there")
            .and_then(|a| a.parked.as_mut())
            .expect("there is parked");
        expired.refresh_expires_at = Some(NOW - 1);
        state::save(&m.ctx, Permit::for_a_test(), &state).expect("saved");
        m.api.owned_by("access-there-again", owner("there"));
        leave(&m, &document("there-again"));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "there".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-again"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// An account holding a park it can be switched to keeps that park, and the other login
    /// of it goes with the file.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn an_account_with_a_park_it_can_switch_to_keeps_that_park() {
        let m = machine("stow-park-kept");
        m.api.owned_by("access-there-again", owner("there"));
        leave(&m, &document("there-again"));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::ParkKept {
                label: "there".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-refresh"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// A park the account can be switched to is kept whichever login is the newer: a login of
    /// that account signed in to since goes with the file, and so does one whose access token
    /// had expired and was renewed to tell whose it is, which then expires later than any park.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_park_it_can_switch_to_is_kept_though_the_files_login_is_newer() {
        let kept = Kept::ParkKept {
            label: "there".into(),
        };
        let m = machine("stow-park-kept-newer");
        m.api.owned_by("access-there-again", owner("there"));
        leave(&m, &renewed_later("there-again"));
        let vault = m.mem.vault().services();
        assert_eq!(found(&m).login, Foreseen::Kept(kept.clone()));

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(stowed.kept, kept);
        assert_eq!(m.mem.vault().services(), vault);
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-refresh"))
        );
        assert_eq!(in_the_file(&m), None);

        let m = machine("stow-park-kept-renewed");
        m.api.renews(
            "there-again",
            provider::claude::api::Renewed {
                access_token: "access-there-renewed".into(),
                refresh_token: Some("there-renewed".into()),
                expires_in: 28_800,
                refresh_token_expires_in: Some(30 * 86_400),
                scopes: None,
                at: None,
            },
        );
        m.api.owned_by("access-there-renewed", owner("there"));
        leave(&m, &lapsed("there-again"));
        let vault = m.mem.vault().services();

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(stowed.kept, kept);
        assert_eq!(m.mem.vault().services(), vault);
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-refresh"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// The copy a put-away makes is left out only while the file it was copied from is there.
    /// Once the file has gone it is the account's park as any other, and another login of that
    /// account left in a file later goes with that file.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_parked_from_the_file_is_kept_once_that_file_has_gone() {
        let m = machine("stow-parked-then-kept");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        m.api.owned_by("access-elsewhere-again", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));
        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert!(state::load(&m.ctx).expect("state").from_file.is_empty());

        leave(&m, &renewed_later("elsewhere-again"));
        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(
            stowed.kept,
            Kept::ParkKept {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("elsewhere-refresh"))
        );
    }

    /// That a park is a copy of the file's login is written down before the copy is. A run
    /// killed before it recorded the copy leaves one the next change gives to the account,
    /// and a session that signs in with the file can renew the login there meanwhile, which
    /// spends the copy: the renewed login is parked in its place.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_copy_a_killed_run_never_recorded_is_not_kept_over_the_login_renewed_since() {
        let m = machine("stow-killed-unrecorded");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));
        let seen = found(&m).seen;
        let died = fault::killing("stow.park_stored", || stow_seen(&m, &seen));
        assert_eq!(died.unwrap_err(), "stow.park_stored");
        assert_eq!(parked_fingerprint(&m, "elsewhere"), None);

        m.api
            .renew_trouble("elsewhere-refresh", Trouble::InvalidGrant);
        m.api
            .owned_by("access-elsewhere-renewed", owner("elsewhere"));
        leave(&m, &renewed_later("elsewhere-renewed"));
        let (stowed, _) = stow_now(&m).expect("put away again");

        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("elsewhere-renewed"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// The login of an account nobody enrolled is refused, naming the account by its email
    /// and organisation, and nothing is deleted or parked.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn the_login_of_an_account_not_enrolled_is_refused_and_named() {
        let m = machine("stow-not-enrolled");
        m.api.owned_by("access-stranger-refresh", owner("stranger"));
        leave(&m, &document("stranger-refresh"));
        let vault = m.mem.vault().services();

        let left = found(&m);
        assert_eq!(
            left.login,
            Foreseen::NotEnrolled(owner("stranger")),
            "the look says so first"
        );
        assert_eq!(
            left.refusal().map(|refused| refused.code()),
            Some("left_login_not_enrolled")
        );
        let refused = stow_now(&m).expect_err("refused");

        assert_eq!(refused.code(), "left_login_not_enrolled");
        let said = refused.to_string();
        assert!(
            said.contains("stranger@example.com")
                && said.contains("org-stranger")
                && said.contains("pitboard enroll <label> --sign-in")
                && said.contains("pitboard stow"),
            "{said}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("stranger-refresh")));
        assert_eq!(m.mem.vault().services(), vault);
    }

    /// A file with no login in it holds nothing to keep, and goes. Its other keys are named.
    /// A file that is not a JSON object, empty or not, holds no login either, nor does one
    /// whose `claudeAiOauth` holds no token, as every warning and doctor tell it: the look,
    /// the warning and putting it away agree, and nothing is sent anywhere.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_file_with_no_login_in_it_is_deleted() {
        let mcp = json!({"mcpOAuth": {"some-server": {"token": "t"}}}).to_string();
        for (contents, dropped) in [
            ("{}", Vec::<&str>::new()),
            (mcp.as_str(), vec!["mcpOAuth"]),
            ("", Vec::new()),
            ("not json", Vec::new()),
            ("[]", Vec::new()),
            (r#"{"claudeAiOauth": {}}"#, vec!["claudeAiOauth"]),
        ] {
            let m = machine("stow-no-login");
            left_file(&m).plant(&m.service, contents);

            assert_eq!(
                provider::document(TOOL)
                    .behind(&m.ctx)
                    .map(|behind| behind.held),
                Some(provider::Held::NoLogin),
                "{contents:?}"
            );
            assert_eq!(
                found(&m).login,
                Foreseen::Kept(Kept::NoLogin),
                "{contents:?}"
            );
            let (stowed, _) = stow_now(&m).expect("put away");

            assert_eq!(stowed.kept, Kept::NoLogin, "{contents:?}");
            assert_eq!(stowed.dropped, dropped, "{contents:?}");
            assert!(left_file(&m).peek(&m.service).is_none(), "{contents:?}");
            assert!(m.api.asked().is_empty());
        }
    }

    /// A login whose access token has expired is renewed before anything else, as a park is,
    /// and one whose refresh token Anthropic refuses for good was no longer valid: the file
    /// goes.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_anthropic_refuses_for_good_goes_with_the_file() {
        let m = machine("stow-refused");
        m.api.renew_trouble("gone-refresh", Trouble::InvalidGrant);
        leave(&m, &lapsed("gone-refresh"));
        assert_eq!(found(&m).login, Foreseen::Untold);
        assert!(m.api.asked().is_empty(), "an expired token is not sent");

        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(stowed.kept, Kept::Refused);
        assert_eq!(in_the_file(&m), None);
    }

    /// The renewed login is written back to the file before anything is asked of it, so a
    /// refresh token the exchange rotated is never lost: refused as an account nobody
    /// enrolled, which says it renewed it, the file holds the renewed login, with the
    /// machine's keys kept.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn an_expired_login_is_renewed_and_written_back_before_anything_else() {
        let m = machine("stow-renewed");
        renews(&m, "left-refresh", "left-renewed");
        m.api.owned_by("access-left-renewed", owner("stranger"));
        leave(&m, &lapsed("left-refresh"));

        let refused = stow_now(&m).expect_err("not enrolled");

        assert_eq!(refused.code(), "left_login_not_enrolled");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having renewed the login in the file and written it \
                 back there."
            ),
            "{refused}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));
        let held: Value =
            serde_json::from_str(&left_file(&m).peek(&m.service).expect("still there"))
                .expect("JSON");
        assert_eq!(held["mcpOAuth"], document("x")["mcpOAuth"]);

        enrolled(&m, "stranger");
        let (stowed, _) = stow_now(&m).expect("put away once enrolled");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "stranger".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "stranger"),
            Some(fingerprint("left-renewed"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// With Anthropic out of reach nobody can say whose the login is, so nothing changes:
    /// neither when it is asked about, nor when it needs renewing first. There the copy's
    /// name, written down before the refresh token is sent, is let go of, and Pitboard's
    /// record ends as it was.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn with_anthropic_out_of_reach_nothing_changes() {
        let m = machine("stow-offline");
        m.api
            .token_trouble("access-unknown-refresh", Trouble::Offline);
        leave(&m, &document("unknown-refresh"));
        let before = state_file(&m);

        let state = state::load(&m.ctx).expect("state");
        let looked = find(&m.ctx, &state).expect_err("nobody to ask");
        assert_eq!(looked.code(), "left_login_unidentified");
        assert_eq!(looked.cause(), Some(Cause::Unreachable));
        let seen = store::fingerprint(&left_file(&m).peek(&m.service).expect("there"));
        let refused = stow_seen(&m, &seen).expect_err("nobody to ask");
        assert_eq!(refused.code(), "left_login_unidentified");
        assert_eq!(in_the_file(&m), Some(fingerprint("unknown-refresh")));
        assert_eq!(state_file(&m), before);

        let m = machine("stow-offline-renewing");
        m.api.renew_trouble("lapsed-refresh", Trouble::Offline);
        leave(&m, &lapsed("lapsed-refresh"));
        let before = state_file(&m);
        let refused = stow_now(&m).expect_err("nobody to renew it");
        assert_eq!(refused.code(), "left_login_unidentified");
        assert_eq!(in_the_file(&m), Some(fingerprint("lapsed-refresh")));
        assert_eq!(state_file(&m).0, before.0);
    }

    /// A keychain that cannot be read, or a file that cannot, says why, and nothing changes.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_locked_keychain_or_an_unreadable_file_changes_nothing() {
        let m = machine("stow-locked");
        m.api.owned_by("access-there-again", owner("there"));
        leave(&m, &document("there-again"));
        let seen = found(&m).seen;
        m.fault_live(Fault::Locked);
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(
            find(&m.ctx, &state).expect_err("locked").code(),
            "credential_store_locked"
        );
        assert_eq!(
            stow_seen(&m, &seen).expect_err("locked").code(),
            "credential_store_locked"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("there-again")));

        let m = machine("stow-unreadable");
        leave(&m, &document("there-again"));
        left_file(&m).fault(
            &m.service,
            Fault::UnreadableContents("permission denied".into()),
        );
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(
            find(&m.ctx, &state).expect_err("unreadable").code(),
            "credential_store_unreadable"
        );
        left_file(&m).heal(&m.service);
        assert_eq!(in_the_file(&m), Some(fingerprint("there-again")));
    }

    /// The file is put away only while it holds what was confirmed: one that changed since,
    /// or went, is left as it is, and so is everything else.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_file_that_changed_since_it_was_confirmed_is_left_alone() {
        let m = machine("stow-changed");
        leave(&m, &document("here-refresh"));
        let seen = found(&m).seen;
        leave(&m, &document("here-again"));

        let refused = stow_seen(&m, &seen).expect_err("it changed");

        assert_eq!(refused.code(), "left_login_changed");
        assert_eq!(in_the_file(&m), Some(fingerprint("here-again")));

        left_file(&m).delete_everything();
        assert_eq!(
            stow_seen(&m, &seen).expect_err("it went").code(),
            "left_login_changed"
        );
    }

    /// Read again under Claude Code's lock, and again as it goes: a session renewing the
    /// login in the file while Pitboard waits for that lock, or a `/logout` that took none
    /// rewriting it before it goes, leaves the file as they wrote it, and nothing else changes.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_file_rewritten_meanwhile_is_left_as_it_was_written() {
        // Before Claude Code's lock, a login that would be parked; before the file goes, one
        // whose account keeps its park.
        for (point, label, left, parked) in [
            ("stow.identified", "elsewhere", "elsewhere-refresh", None),
            (
                "stow.kept",
                "there",
                "there-again",
                Some(fingerprint("there-refresh")),
            ),
        ] {
            let m = machine(&format!("stow-rewritten-{point}"));
            enrolled(&m, "elsewhere");
            m.api.owned_by(&format!("access-{left}"), owner(label));
            leave(&m, &document(left));
            let vault = m.mem.vault().services();

            let refused = stow_while(&m, point, rewrites_the_file(&m, &document("new")))
                .expect_err("it changed");

            assert_eq!(refused.code(), "left_login_changed", "{point}");
            assert!(
                refused.to_string().ends_with("Pitboard changed nothing."),
                "{point}: {refused}"
            );
            assert_eq!(in_the_file(&m), Some(fingerprint("new")), "{point}");
            assert_eq!(m.mem.vault().services(), vault, "{point}");
            assert_eq!(parked_fingerprint(&m, label), parked, "{point}");
        }
    }

    /// The login Claude Code has stored, which the file's login was told to be, or told to be
    /// another login of the same account, is read again as the file goes: a sign-in that took
    /// Claude Code's lock first replaced it, so the file, which may hold the only copy of that
    /// account's login, stays.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_sign_in_before_the_file_goes_keeps_the_file_whose_login_it_counted_on() {
        for (name, left) in [
            ("stow-stored-replaced", "here-refresh"),
            ("stow-second-sign-in-replaced", "here-again"),
        ] {
            let m = machine(name);
            m.api.owned_by("access-here-again", owner("here"));
            m.api
                .owned_by("access-elsewhere-refresh", owner("elsewhere"));
            leave(&m, &document(left));

            let refused = stow_while(
                &m,
                "stow.identified",
                signs_in(&m, &document("elsewhere-refresh")),
            )
            .expect_err("the login stored changed");

            assert_eq!(refused.code(), "stored_login_changed", "{name}");
            assert!(
                refused.to_string().ends_with("Pitboard changed nothing."),
                "{name}: {refused}"
            );
            assert_eq!(in_the_file(&m), Some(fingerprint(left)), "{name}");
            assert_eq!(m.live(), Some(document("elsewhere-refresh")), "{name}");
            assert_eq!(parked_fingerprint(&m, "here"), None, "{name}");
        }
    }

    /// Whatever stops it after the login was renewed and written back, or parked, says so,
    /// its own refusals and a keychain that locks alike: the file holds the renewed login, or
    /// the park stays, and the file is not deleted.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_refusal_after_the_login_was_renewed_or_parked_says_so() {
        let m = machine("stow-renewed-then-offline");
        renews(&m, "left-refresh", "left-renewed");
        m.api.token_trouble("access-left-renewed", Trouble::Offline);
        leave(&m, &lapsed("left-refresh"));

        let refused = stow_now(&m).expect_err("nobody to ask");

        assert_eq!(refused.code(), "left_login_unidentified");
        assert_eq!(refused.cause(), Some(Cause::Unreachable));
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having renewed the login in the file and written it \
                 back there."
            ),
            "{refused}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));

        let m = machine("stow-parked-then-rewritten");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));

        let refused = stow_while(
            &m,
            "stow.kept",
            rewrites_the_file(&m, &json!({"mcpOAuth": {}})),
        )
        .expect_err("it changed");

        assert_eq!(refused.code(), "left_login_changed");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having parked the login in the file for `elsewhere`."
            ),
            "{refused}"
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("elsewhere-refresh"))
        );
        assert!(left_file(&m).peek(&m.service).is_some(), "left as written");

        let m = machine("stow-parked-then-locked");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));

        let refused = stow_while(&m, "stow.kept", locks_the_keychain(&m))
            .expect_err("the keychain is locked");

        assert_eq!(refused.code(), "credential_store_locked");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having parked the login in the file for `elsewhere`."
            ),
            "{refused}"
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("elsewhere-refresh"))
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("elsewhere-refresh")));
    }

    /// `elsewhere` enrolled with nothing parked, and its login left in the file with its
    /// access token expired, which Anthropic renews.
    fn lapsed_login_left(name: &str) -> Machine {
        let m = machine(name);
        enrolled(&m, "elsewhere");
        renews(&m, "left-refresh", "left-renewed");
        m.api.owned_by("access-left-renewed", owner("elsewhere"));
        leave(&m, &lapsed("left-refresh"));
        m
    }

    fn renewed(m: &Machine) -> bool {
        m.api.asked().contains(&Asked::Renew("left-refresh".into()))
    }

    /// The renewed login is saved under Claude Code's write lock, and the exchange spends the
    /// refresh token the file holds. So that lock is taken once before the token is sent:
    /// held by a session then, nothing is sent, and nothing has changed.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_write_lock_held_before_a_renewal_stops_it_with_the_refresh_token_unsent() {
        let m = lapsed_login_left("stow-write-lock-before");
        let writing = lock_dir(&write_target(&m));

        let refused = stow_while(&m, "stow.identified", takes_the_write_lock(&m))
            .expect_err("Claude Code is writing");

        assert_eq!(refused.code(), "switch_in_progress");
        assert!(
            refused.to_string().ends_with("Pitboard changed nothing."),
            "{refused}"
        );
        assert!(!renewed(&m), "{:?}", m.api.asked());
        assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));

        std::fs::remove_dir(&writing).expect("the session lets go");
        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
    }

    /// Once the refresh token is spent, giving up on Claude Code's write lock would drop the
    /// only login left of that grant. So it is waited for longer than a change waits: here a
    /// session holds it until a change would have given up on it.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_write_lock_held_once_the_refresh_token_is_spent_is_waited_for() {
        let m = lapsed_login_left("stow-write-lock-after");

        let (stowed, warnings) =
            fault::meanwhile("refresh.waited", lets_go_of_the_write_lock(&m), || {
                stow_while(&m, "refresh.exchanged", takes_the_write_lock(&m))
            })
            .expect("put away");

        assert!(warnings.is_empty(), "saved under the lock: {warnings:?}");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// A write lock that never comes free is not waited on for ever, nor is the renewed login
    /// dropped over it: the login is saved without the lock, as Claude Code writes on once
    /// its own is lost. Here the lock is a file, which taking it over fails on at once.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_write_lock_never_let_go_of_does_not_cost_the_renewed_login() {
        let m = lapsed_login_left("stow-write-lock-stuck");
        let stuck = lock_dir(&write_target(&m));

        let refused = stow_while(&m, "refresh.exchanged", move || {
            let parent = stuck.parent().expect("the storage directory");
            std::fs::create_dir_all(parent).expect("the storage directory is made");
            let long_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
            std::fs::File::create(&stuck)
                .and_then(|lock| lock.set_modified(long_ago))
                .expect("something in the lock's place");
        })
        .expect_err("the lock is never had, to delete the file under");

        assert_eq!(refused.code(), "switch_in_progress");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having parked the login in the file for `elsewhere`."
            ),
            "{refused}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
    }

    /// The renewed login goes back into the file as Claude Code saves a renewal: wherever the
    /// file still holds the refresh token that was sent, whatever else it has come to hold. A
    /// session that cannot read the keychain saves an MCP token to the file, and that is kept
    /// beside the renewed login.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_file_whose_other_keys_were_written_meanwhile_takes_the_renewed_login() {
        let m = machine("stow-other-keys-written");
        renews(&m, "left-refresh", "left-renewed");
        m.api.owned_by("access-left-renewed", owner("stranger"));
        leave(&m, &lapsed("left-refresh"));
        let mut saved = lapsed("left-refresh");
        saved["mcpOAuth"] = json!({"another-server": {"token": "saved meanwhile"}});

        let refused = stow_while(&m, "refresh.exchanged", rewrites_the_file(&m, &saved))
            .expect_err("not enrolled");

        assert_eq!(refused.code(), "left_login_not_enrolled");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having renewed the login in the file and written it \
                 back there."
            ),
            "{refused}"
        );
        let held: Value =
            serde_json::from_str(&left_file(&m).peek(&m.service).expect("still there"))
                .expect("JSON");
        assert_eq!(held["claudeAiOauth"]["refreshToken"], "left-renewed");
        assert_eq!(held["mcpOAuth"], saved["mcpOAuth"]);
    }

    /// The renewed login is written into the file itself, which a keychain that locks while
    /// Anthropic answers does not stand in the way of: what stops then says the login was
    /// kept, and putting away again finishes.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_keychain_that_locks_while_the_login_is_renewed_does_not_lose_it() {
        let m = lapsed_login_left("stow-locks-while-renewing");

        let refused = stow_while(&m, "refresh.exchanged", locks_the_keychain(&m))
            .expect_err("the keychain is locked");

        assert_eq!(refused.code(), "credential_store_locked");
        assert!(
            refused.to_string().ends_with(
                "Pitboard deleted nothing, having parked the login in the file for `elsewhere`."
            ),
            "{refused}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));

        m.mem.live().heal(&m.service);
        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::AlreadyParked {
                label: "elsewhere".into()
            }
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// Where a sign-in replaced the login in the file while it was renewed, the renewed login
    /// has nowhere to go, and what stops it says that login is spent, never that nothing
    /// changed.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_renewed_login_that_cannot_be_written_back_is_said_to_be_spent() {
        const SPENT: &str = "Pitboard deleted nothing. It renewed the login the file held and \
                             could not write the renewed login back there, so that login no \
                             longer works.";
        let m = lapsed_login_left("stow-signed-in-while-renewing");
        let refused = stow_while(
            &m,
            "refresh.exchanged",
            rewrites_the_file(&m, &document("signed-in")),
        )
        .expect_err("another login is in the file");
        assert_eq!(refused.code(), "left_login_changed");
        assert!(refused.to_string().ends_with(SPENT), "{refused}");
        assert_eq!(in_the_file(&m), Some(fingerprint("signed-in")));
        assert_eq!(parked_fingerprint(&m, "elsewhere"), None);
        assert!(
            !m.mem
                .vault()
                .services()
                .iter()
                .any(|service| service.contains("-renewing-")),
            "the copy is let go of: {:?}",
            m.mem.vault().services()
        );
    }

    /// A renewed login whose write into the file fails is kept in the vault, and what stops
    /// says so. The next change writes it into the file, and putting it away again finishes
    /// with it.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_renewed_login_the_file_cannot_take_yet_is_kept_for_the_next_change() {
        const KEPT: &str = "Pitboard deleted nothing. It renewed the login the file held and \
                            keeps the renewed login until the next change writes it back \
                            there.";
        let m = lapsed_login_left("stow-unwritable-while-renewing");
        let (file, service) = (left_file(&m), m.service.clone());
        let fails = {
            let (file, service) = (std::sync::Arc::clone(&file), service.clone());
            move || file.fault(&service, Fault::FailWrite("disk full".into()))
        };

        let refused =
            stow_while(&m, "refresh.exchanged", fails).expect_err("the file cannot be written");

        assert_eq!(refused.code(), "credential_write_failed");
        assert!(refused.to_string().ends_with(KEPT), "{refused}");
        assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));
        m.api.renew_trouble("left-refresh", Trouble::InvalidGrant);
        file.heal(&service);
        let refused = stow_now(&m).expect_err("the next change wrote the file");
        assert_eq!(refused.code(), "left_login_changed");
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));
        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
        assert_eq!(in_the_file(&m), None);
    }

    /// Nothing behind the keychain is nothing to put away, and nor is the file where it is
    /// the store Claude Code keeps its login in: on Linux always, and on macOS where the
    /// keychain holds none.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn nothing_behind_the_store_is_nothing_to_put_away() {
        let m = machine("stow-nothing");
        let state = state::load(&m.ctx).expect("state");
        assert_eq!(find(&m.ctx, &state).expect("a look"), None);

        leave(&m, &document("here-refresh"));
        m.mem.live().delete_everything();
        assert_eq!(find(&m.ctx, &state).expect("a look"), None);
    }

    /// The look says what putting the file away would do, and changes nothing: no file is
    /// written, nothing is parked, and an expired access token is not sent anywhere.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn the_look_says_what_putting_away_would_do_and_changes_nothing() {
        let m = machine("stow-look");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));
        let before = state_file(&m);
        let vault = m.mem.vault().services();

        let left = found(&m);

        assert_eq!(left.path, live::credential_file(&m.ctx));
        assert_eq!(
            left.login,
            Foreseen::Kept(Kept::ParkedNow {
                label: "elsewhere".into()
            })
        );
        assert_eq!(left.dropped, ["mcpOAuth"]);
        assert_eq!(
            left.seen,
            store::fingerprint(&document("elsewhere-refresh").to_string())
        );
        assert_eq!(state_file(&m), before);
        assert_eq!(m.mem.vault().services(), vault);
        assert_eq!(in_the_file(&m), Some(fingerprint("elsewhere-refresh")));
    }

    /// Killed anywhere, a login is left somewhere: in the file, renewed or not, in a park, or
    /// in both. Putting it away again finishes the job.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn killed_anywhere_the_login_is_left_somewhere_and_putting_away_again_finishes() {
        for point in ["stow.identified", "refresh.saved", "stow.kept"] {
            let m = machine(&format!("stow-killed-{point}"));
            enrolled(&m, "elsewhere");
            renews(&m, "left-refresh", "left-renewed");
            m.api.owned_by("access-left-renewed", owner("elsewhere"));
            leave(&m, &lapsed("left-refresh"));
            let seen = found(&m).seen;

            let died = fault::killing(point, || stow_seen(&m, &seen));
            assert_eq!(died.unwrap_err(), point);

            let renewed = Some(fingerprint("left-renewed"));
            let held = in_the_file(&m);
            assert!(
                held == Some(fingerprint("left-refresh"))
                    || held == renewed
                    || parked_fingerprint(&m, "elsewhere") == renewed,
                "{point}: the login is nowhere"
            );
            let (stowed, _) = stow_now(&m).expect("put away again");
            assert!(
                matches!(
                    stowed.kept,
                    Kept::ParkedNow { .. } | Kept::AlreadyParked { .. }
                ),
                "{point}: {:?}",
                stowed.kept
            );
            assert_eq!(parked_fingerprint(&m, "elsewhere"), renewed, "{point}");
            assert_eq!(in_the_file(&m), None, "{point}");
        }
    }

    /// Killed once Anthropic has answered and before the answer reached the file, which
    /// holds the spent refresh token then, the renewed login waits in Pitboard's vault. The
    /// next change writes it into the file, so the file has changed since the look, and
    /// putting it away again finishes with the renewed login.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn killed_before_the_renewed_login_reached_the_file_the_next_change_writes_it_there() {
        let m = lapsed_login_left("stow-killed-after-the-exchange");
        let seen = found(&m).seen;

        let died = fault::killing("refresh.exchanged", || stow_seen(&m, &seen));
        assert_eq!(died.unwrap_err(), "refresh.exchanged");
        m.api.renew_trouble("left-refresh", Trouble::InvalidGrant);
        assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));

        let refused = stow_seen(&m, &seen).expect_err("the file changed");
        assert_eq!(refused.code(), "left_login_changed");
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));

        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
        assert_eq!(in_the_file(&m), None);
        assert!(
            !m.mem
                .vault()
                .services()
                .iter()
                .any(|service| service.contains("-renewing-")),
            "the copy is let go of: {:?}",
            m.mem.vault().services()
        );
        assert_eq!(state::load(&m.ctx).expect("state").renewing, []);
    }

    /// A renewal of the file's login left in the vault is saved before that login is renewed
    /// again, since the file still holds the refresh token it spent. Where it cannot be saved
    /// yet, putting the file away stops with why, sending and deleting nothing.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_renewal_left_unsaved_is_saved_before_the_file_is_put_away() {
        let m = lapsed_login_left("stow-left-unsaved");
        let seen = found(&m).seen;
        let died = fault::killing("refresh.exchanged", || stow_seen(&m, &seen));
        assert_eq!(died.unwrap_err(), "refresh.exchanged");
        m.api.renew_trouble("left-refresh", Trouble::InvalidGrant);
        let (file, service) = (left_file(&m), m.service.clone());
        file.fault(&service, Fault::FailWrite("disk full".into()));

        let refused = stow_seen(&m, &seen).expect_err("the copy cannot be saved");

        assert_eq!(refused.code(), "credential_write_failed");
        assert!(
            refused.to_string().ends_with("Pitboard changed nothing."),
            "{refused}"
        );
        let sent = Asked::Renew("left-refresh".into());
        assert_eq!(m.api.asked().iter().filter(|a| **a == sent).count(), 1);
        assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));
        file.heal(&service);
        stow_seen(&m, &seen).expect_err("the next change wrote the file");
        assert_eq!(in_the_file(&m), Some(fingerprint("left-renewed")));
    }

    /// A login in the file whose access token Anthropic refused before its expiry is renewed,
    /// and a write into the file that fails leaves the renewed login waiting in the vault,
    /// with the spent refresh token in the file. Putting the file away stops while it waits,
    /// though Anthropic names the file's login by its access token by then, so the spent
    /// login is never parked and the renewed one never let go of.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_file_whose_renewal_waits_is_not_put_away_once_its_login_is_named() {
        let m = machine("stow-renewal-waits-named");
        enrolled(&m, "elsewhere");
        renews(&m, "left-refresh", "left-renewed");
        m.api.owned_by("access-left-renewed", owner("elsewhere"));
        m.api
            .token_trouble("access-left-refresh", Trouble::Unauthorized);
        leave(&m, &document("left-refresh"));
        let (file, service) = (left_file(&m), m.service.clone());
        file.fault(&service, Fault::FailWrite("disk full".into()));
        let refused = stow_now(&m).expect_err("the file cannot be written");
        assert_eq!(refused.code(), "credential_write_failed");
        m.api.renew_trouble("left-refresh", Trouble::InvalidGrant);
        m.api.owned_by("access-left-refresh", owner("elsewhere"));

        let refused = stow_now(&m).expect_err("a renewal of the file's login waits");

        assert_eq!(refused.code(), "credential_write_failed");
        assert!(
            refused.to_string().ends_with("Pitboard changed nothing."),
            "{refused}"
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));
        assert_eq!(parked_fingerprint(&m, "elsewhere"), None);
        file.heal(&service);
        let refused = stow_now(&m).expect_err("the next change wrote the file");
        assert_eq!(refused.code(), "left_login_changed");
        let (stowed, _) = stow_now(&m).expect("put away");
        assert_eq!(
            stowed.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            parked_fingerprint(&m, "elsewhere"),
            Some(fingerprint("left-renewed"))
        );
        let sent = Asked::Renew("left-refresh".into());
        assert_eq!(m.api.asked().iter().filter(|a| **a == sent).count(), 1);
    }

    /// The front ends' way in: the activity log records it as `stow`, with the account the
    /// login was found to be and what became of it, and a refusal with its code. A read after
    /// it no longer finds the file.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn putting_away_is_recorded_in_the_activity_log() {
        let m = machine("stow-audit");
        enrolled(&m, "elsewhere");
        m.api
            .owned_by("access-elsewhere-refresh", owner("elsewhere"));
        leave(&m, &document("elsewhere-refresh"));
        let pitboard = Pitboard::new(m.ctx.clone());

        let left = pitboard.left_login().expect("a look").expect("left");
        let done = pitboard.stow(&left.seen).expect("put away");

        assert_eq!(
            done.value.kept,
            Kept::ParkedNow {
                label: "elsewhere".into()
            }
        );
        assert_eq!(
            audit_lines(&m, "stow"),
            [("elsewhere".to_string(), "parked".to_string())]
        );
        let read = pitboard.status(false).expect("a read");
        assert!(
            read.warnings.iter().all(|w| w.code() != "fallback_login"),
            "{:?}",
            read.warnings
        );

        m.api.owned_by("access-stranger-refresh", owner("stranger"));
        leave(&m, &document("stranger-refresh"));
        let left = pitboard.left_login().expect("a look").expect("left");
        let refused = pitboard.stow(&left.seen).expect_err("not enrolled");
        assert_eq!(refused.error.code(), "left_login_not_enrolled");
        assert_eq!(
            audit_lines(&m, "stow").last(),
            Some(&(String::new(), "left_login_not_enrolled".to_string()))
        );
    }

    /// A run that stops after parking the file's login, killed or refused, leaves that login
    /// in the park and in the file both. A session that signs in with the file renews it
    /// there, spending the park's refresh token. The park is written down as a copy of the
    /// file's login, so the next run parks the renewed login in its place, rather than keep
    /// the spent park and delete the only login that still works.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_renewed_in_the_file_after_a_run_stopped_takes_the_spent_parks_place() {
        for stop in ["killed", "locked"] {
            let m = machine(&format!("stow-renewed-after-{stop}"));
            enrolled(&m, "elsewhere");
            m.api
                .owned_by("access-elsewhere-refresh", owner("elsewhere"));
            leave(&m, &document("elsewhere-refresh"));
            let seen = found(&m).seen;
            if stop == "killed" {
                let died = fault::killing("stow.kept", || stow_seen(&m, &seen));
                assert_eq!(died.unwrap_err(), "stow.kept");
            } else {
                let refused =
                    fault::meanwhile("stow.kept", locks_the_keychain(&m), || stow_seen(&m, &seen))
                        .expect_err("the keychain is locked");
                assert_eq!(refused.code(), "credential_store_locked");
                m.mem.live().heal(&m.service);
            }
            assert_eq!(
                parked_fingerprint(&m, "elsewhere"),
                Some(fingerprint("elsewhere-refresh")),
                "{stop}"
            );
            assert_eq!(
                in_the_file(&m),
                Some(fingerprint("elsewhere-refresh")),
                "{stop}"
            );

            m.api
                .renew_trouble("elsewhere-refresh", Trouble::InvalidGrant);
            m.api
                .owned_by("access-elsewhere-renewed", owner("elsewhere"));
            leave(&m, &renewed_later("elsewhere-renewed"));
            let (stowed, _) = stow_now(&m).expect("put away again");

            assert_eq!(
                stowed.kept,
                Kept::ParkedNow {
                    label: "elsewhere".into()
                },
                "{stop}"
            );
            assert_eq!(
                parked_fingerprint(&m, "elsewhere"),
                Some(fingerprint("elsewhere-renewed")),
                "{stop}"
            );
            assert_eq!(in_the_file(&m), None, "{stop}");
            let state = state::load(&m.ctx).expect("state");
            let parked = state
                .get(&m.key("elsewhere"))
                .and_then(|a| a.parked.clone())
                .expect("parked");
            let held = park::load(
                &m.ctx,
                provider::document(TOOL),
                &m.key("elsewhere"),
                &parked,
            )
            .expect("it reads back");
            assert_eq!(
                held["claudeAiOauth"]["refreshToken"], "elsewhere-renewed",
                "{stop}"
            );
        }
    }

    /// A session renewing the login in the file takes Claude Code's refresh lock before it
    /// sends the refresh token, and saves the renewed login only where the file still holds
    /// the token it sent (the register's `refresh_lock`). Putting the file away holds that
    /// lock from the file's last reading until it is gone, so a session renewing meanwhile
    /// waits: the login Pitboard parks, renewed by Pitboard first or as it was, is never one a
    /// session spent with its renewal lost when the file went.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_session_renewing_the_login_in_the_file_meanwhile_waits_for_it() {
        for (point, left, parked) in [
            ("refresh.saved", lapsed("left-refresh"), "left-renewed"),
            ("stow.kept", document("left-refresh"), "left-refresh"),
        ] {
            let m = machine(&format!("stow-session-{point}"));
            enrolled(&m, "elsewhere");
            renews(&m, "left-refresh", "left-renewed");
            m.api.owned_by("access-left-refresh", owner("elsewhere"));
            m.api.owned_by("access-left-renewed", owner("elsewhere"));
            leave(&m, &left);
            let session = Session::new();

            let done = stow_while(&m, point, renews_meanwhile(&m, left_file(&m), &session));
            saves(&m, &left_file(&m), &session);

            assert!(
                session.waited.get(),
                "{point}: a session renewed the login while Pitboard counted on it"
            );
            let (stowed, _) = done.expect("put away");
            assert_eq!(
                stowed.kept,
                Kept::ParkedNow {
                    label: "elsewhere".into()
                },
                "{point}"
            );
            assert_eq!(
                parked_fingerprint(&m, "elsewhere"),
                Some(fingerprint(parked)),
                "{point}"
            );
            assert_eq!(in_the_file(&m), None, "{point}");
            assert!(
                !lock_dir(&provider::claude::paths::refresh_lock(&m.ctx)).exists(),
                "{point}: the refresh lock is let go of"
            );
        }

        // A session that renewed before Pitboard took the lock has saved what it renewed to by
        // then, so the file has changed since it was confirmed, and stays as it saved it.
        let m = machine("stow-session-before");
        enrolled(&m, "elsewhere");
        m.api.owned_by("access-left-refresh", owner("elsewhere"));
        leave(&m, &document("left-refresh"));
        let session = Session::new();

        let refused = stow_while(
            &m,
            "stow.identified",
            renews_meanwhile(&m, left_file(&m), &session),
        )
        .expect_err("it changed");

        assert!(!session.waited.get());
        assert_eq!(refused.code(), "left_login_changed");
        assert_eq!(
            in_the_file(&m),
            Some(fingerprint("left-refresh-by-a-session"))
        );
        assert_eq!(parked_fingerprint(&m, "elsewhere"), None);
    }

    /// A login of an account nobody enrolled is named from what Anthropic said of it alone:
    /// whose the login stored is matters only for an enrolled account, so it is not asked,
    /// and Anthropic out of reach for it does not stand in the way.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_of_an_account_not_enrolled_is_named_without_asking_whose_the_login_stored_is() {
        let m = machine("stow-not-enrolled-stored-unknown");
        m.sign_in(&document("here-renewed"));
        m.api.token_trouble("access-here-renewed", Trouble::Offline);
        m.api.owned_by("access-stranger-refresh", owner("stranger"));
        leave(&m, &document("stranger-refresh"));

        let left = found(&m);
        let refused = stow_seen(&m, &left.seen).expect_err("not enrolled");

        assert_eq!(left.login, Foreseen::NotEnrolled(owner("stranger")));
        assert_eq!(refused.code(), "left_login_not_enrolled");
        assert!(
            m.api
                .asked()
                .iter()
                .all(|asked| *asked != Asked::Owner("access-here-renewed".into())),
            "{:?}",
            m.api.asked()
        );
        assert_eq!(in_the_file(&m), Some(fingerprint("stranger-refresh")));
    }

    /// The owner's machine on 10 October 2026: the file held another login of an account
    /// with a park, and the keychain's login had changed since Anthropic last named it and
    /// lapsed, since every session was signed in with the file. Putting it away refused with
    /// `session_expired`. The look stands on whose Pitboard last recorded the login stored to
    /// be, renewing nothing, and putting it away renews that login as Claude Code would to
    /// tell whose it is, then goes on.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_lapsed_stored_login_is_renewed_to_tell_whose_it_is_and_the_file_put_away() {
        let kept = Kept::ParkKept {
            label: "there".into(),
        };
        let m = machine("stow-stored-lapsed");
        m.sign_in(&lapsed("here-renewed"));
        renews(&m, "here-renewed", "here-again");
        m.api.owned_by("access-here-again", owner("here"));
        m.api.owned_by("access-there-again", owner("there"));
        leave(&m, &document("there-again"));

        let left = found(&m);
        assert_eq!(left.login, Foreseen::Kept(kept.clone()));
        assert!(
            !m.api.asked().contains(&Asked::Renew("here-renewed".into())),
            "the look renews nothing"
        );
        let (stowed, _) = stow_seen(&m, &left.seen).expect("put away");

        assert_eq!(stowed.kept, kept);
        assert_eq!(in_the_file(&m), None);
        assert_eq!(
            m.live()
                .and_then(|stored| stored["claudeAiOauth"]["refreshToken"]
                    .as_str()
                    .map(str::to_owned)),
            Some("here-again".into())
        );
        assert_eq!(
            parked_fingerprint(&m, "there"),
            Some(fingerprint("there-refresh"))
        );
    }

    /// Whose login Claude Code has stored is told by renewing it, and the keychain locks once
    /// Anthropic has answered, so the refresh token stored is spent and the renewed login is
    /// not saved there. What stops `stow` never says it changed nothing. The renewed login
    /// waits in the vault, as the message says, and the next run saves it and puts the file
    /// away. Where the vault could not keep it either, it is lost, and the message says to
    /// sign in.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_renewal_of_the_login_stored_that_stops_stow_is_said() {
        for lost in [false, true] {
            let m = machine(&format!("stow-stored-renewal-lost-{lost}"));
            enrolled(&m, "elsewhere");
            m.sign_in(&lapsed("here-renewed"));
            renews(&m, "here-renewed", "here-again");
            m.api.owned_by("access-here-again", owner("here"));
            m.api.owned_by("access-left-refresh", owner("elsewhere"));
            leave(&m, &document("left-refresh"));
            if lost {
                // A copy would go on the argument line, so none is made.
                m.mem.vault().takes_on_stdin(16);
            }

            let refused = stow_while(&m, "refresh.exchanged", locks_the_keychain(&m))
                .expect_err("the keychain is locked");

            assert_eq!(refused.code(), "credential_store_locked", "lost: {lost}");
            let ending = if lost {
                "Run `claude`, sign in, then try again."
            } else {
                "Pitboard deleted nothing. It renewed the login Claude Code has stored and keeps \
                 the renewed login until the next change saves it there."
            };
            assert!(refused.to_string().ends_with(ending), "{refused}");
            assert_eq!(in_the_file(&m), Some(fingerprint("left-refresh")));
            if lost {
                continue;
            }
            let (keychain, service) = m.live_store();
            keychain.heal(&service);
            m.api.renew_trouble("here-renewed", Trouble::InvalidGrant);
            let (stowed, _) = stow_now(&m).expect("put away");
            assert_eq!(
                stowed.kept,
                Kept::ParkedNow {
                    label: "elsewhere".into()
                }
            );
            assert_eq!(in_the_file(&m), None);
            let sent = Asked::Renew("here-renewed".into());
            assert_eq!(m.api.asked().iter().filter(|a| **a == sent).count(), 1);
        }
    }

    /// A login with no refresh token whose access token has expired can never be used again:
    /// it is dead, and goes with the file, with nothing sent anywhere.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn a_login_with_no_refresh_token_left_to_expire_is_dead() {
        let m = machine("stow-no-refresh-token");
        leave(
            &m,
            &json!({"claudeAiOauth": {
                "accessToken": "access-without-a-refresh-token",
                "expiresAt": (NOW - 60) * 1000,
            }}),
        );

        assert_eq!(found(&m).login, Foreseen::Kept(Kept::Refused));
        let (stowed, _) = stow_now(&m).expect("put away");

        assert_eq!(stowed.kept, Kept::Refused);
        assert_eq!(in_the_file(&m), None);
        assert!(m.api.asked().is_empty(), "{:?}", m.api.asked());
    }

    /// Settled as any change of Claude Code's login is but for the file, which is what it puts
    /// away: something that signs Claude Code in some other way is said beside it, since
    /// sessions then follow no switch, file or no file.
    #[test]
    #[cfg_attr(
        windows,
        ignore = "W23: Claude Code's Credential Manager store, which a machine in memory plays"
    )]
    fn putting_away_says_what_signs_claude_code_in_some_other_way() {
        let m = machine("stow-overridden");
        let config = m.ctx_home().join(".claude");
        std::fs::create_dir_all(&config).expect("a config dir");
        std::fs::write(
            config.join("settings.json"),
            json!({"apiKeyHelper": "/usr/local/bin/get-key"}).to_string(),
        )
        .expect("settings");
        leave(&m, &document("here-refresh"));
        let pitboard = Pitboard::new(m.ctx.clone());

        let left = pitboard.left_login().expect("a look").expect("left");
        let done = pitboard.stow(&left.seen).expect("put away");

        let codes: Vec<&str> = done.warnings.iter().map(Warning::code).collect();
        assert_eq!(codes, ["auth_overridden"]);
        assert_eq!(in_the_file(&m), None);
    }
}