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
//! Every way Pitboard can fail. Each variant has a message naming the cause and an action,
//! a stable code for programs to branch on, and an exit code.

use crate::provider::ProviderId;
use crate::state::Key;
use std::path::PathBuf;

/// The labels an account list holds, rendered for a message: " Enrolled: `a`, `b`." or
/// nothing at all when none are.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Enrolled(pub Vec<String>);

impl std::fmt::Display for Enrolled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.0.is_empty() {
            return write!(f, " Nothing is enrolled yet.");
        }
        let labels: Vec<String> = self.0.iter().map(|l| format!("`{l}`")).collect();
        write!(f, " Enrolled: {}.", labels.join(", "))
    }
}

/// How far putting away the file behind a tool's store had gone when something stopped it.
/// Never as far as deleting the file, and never further than keeping the login it held.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Partway {
    /// Nothing was changed.
    Nothing,
    /// The login Claude Code has stored was renewed to tell whose it is, which spent its
    /// refresh token, and the renewed one waits in Pitboard's vault for the next change to
    /// save it there.
    StoredRenewedKept,
    /// The login the file held was renewed, which spent its refresh token, and the renewed
    /// one could not be written back there, nor kept.
    RenewedUnwritten,
    /// The login the file held was renewed, which spent its refresh token, and the renewed
    /// one waits in Pitboard's vault for the next change to write it back there.
    RenewedKept,
    /// The login in the file was renewed, and the renewed one written back there.
    Renewed,
    /// The login in the file was parked for `label`.
    Parked { label: String },
}

impl std::fmt::Display for Partway {
    /// What Pitboard did, after "Pitboard".
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Partway::Nothing => write!(f, "changed nothing"),
            Partway::StoredRenewedKept => write!(
                f,
                "deleted nothing. It renewed the login Claude Code has stored and keeps the \
                 renewed login until the next change saves it there"
            ),
            Partway::RenewedUnwritten => write!(
                f,
                "deleted nothing. It renewed the login the file held and could not write the \
                 renewed login back there, so that login no longer works"
            ),
            Partway::RenewedKept => write!(
                f,
                "deleted nothing. It renewed the login the file held and keeps the renewed login \
                 until the next change writes it back there"
            ),
            Partway::Renewed => write!(
                f,
                "deleted nothing, having renewed the login in the file and written it back there"
            ),
            Partway::Parked { label } => write!(
                f,
                "deleted nothing, having parked the login in the file for `{label}`"
            ),
        }
    }
}

/// Why a request to Anthropic did not produce an answer Pitboard could use.
///
/// The code on an error says what Pitboard was doing; this says what went wrong underneath
/// it, and whether trying again is worth anything. Without it every failure that was not a
/// 401 arrived at a front end as one code with a sentence of prose, so neither the command
/// line nor the app could tell being offline from being rate limited from a login Anthropic
/// has finished with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum Cause {
    /// Anthropic could not be reached at all.
    Unreachable,
    /// Anthropic asked for less traffic.
    RateLimited,
    /// Anthropic answered, badly, and may answer well later.
    ServerError,
    /// Anthropic answered something Pitboard does not understand, which means its shape
    /// moved. Trying again will produce the same thing.
    AnswerNotUnderstood,
    /// This login is finished: revoked, or already used somewhere else.
    LoginRefused,
    /// The token has expired. For the signed-in login that is ordinary and Claude Code
    /// renews it; for a parked one it means the park needs renewing first.
    TokenExpired,
}

impl Cause {
    pub(crate) fn of(error: &crate::provider::claude::api::ApiError) -> Cause {
        use crate::provider::claude::api::ApiError;
        match error {
            ApiError::Unauthorized => Cause::TokenExpired,
            ApiError::RateLimited { .. } => Cause::RateLimited,
            ApiError::Network(_) => Cause::Unreachable,
            ApiError::Unexpected { .. } => Cause::ServerError,
            ApiError::Malformed(_) => Cause::AnswerNotUnderstood,
            ApiError::InvalidGrant => Cause::LoginRefused,
        }
    }

    /// The same question asked of a provider rather than of Anthropic directly.
    pub(crate) fn of_provider(error: &crate::provider::ProviderError) -> Cause {
        use crate::provider::ProviderError as P;
        match error {
            P::Unauthorized => Cause::TokenExpired,
            P::RateLimited { .. } => Cause::RateLimited,
            P::Network { .. } => Cause::Unreachable,
            P::Unexpected { .. } => Cause::ServerError,
            P::Malformed { .. }
            | P::ShapeUnexpected { .. }
            | P::Unsupported { .. }
            | P::NoLogin { .. } => Cause::AnswerNotUnderstood,
            P::InvalidGrant { .. } => Cause::LoginRefused,
        }
    }

    /// Stable, for a program to branch on; the same as its JSON form.
    pub fn code(self) -> &'static str {
        match self {
            Cause::Unreachable => "unreachable",
            Cause::RateLimited => "rate_limited",
            Cause::ServerError => "server_error",
            Cause::AnswerNotUnderstood => "answer_not_understood",
            Cause::LoginRefused => "login_refused",
            Cause::TokenExpired => "token_expired",
        }
    }

    /// Whether the same request, later, could answer differently. A front end deciding
    /// whether to back off or to give up reads this and nothing else.
    pub fn worth_retrying(self) -> bool {
        match self {
            Cause::Unreachable | Cause::RateLimited | Cause::ServerError => true,
            Cause::AnswerNotUnderstood | Cause::LoginRefused | Cause::TokenExpired => false,
        }
    }
}

#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    #[error(
        "{path} looks like it is inside {marker}, which syncs to other machines. \
         Parked logins belong to one machine; set PITBOARD_HOME to a local folder."
    )]
    StateOnSyncedDrive { path: PathBuf, marker: String },

    /// A home the environment names is empty or relative, so what it leads to would depend
    /// on the folder each program runs in. `variable` is the one that named it.
    #[error("{}", not_absolute(variable, path))]
    HomeNotAbsolute {
        variable: &'static str,
        path: PathBuf,
    },

    #[error(
        "the login for `{label}` needs {bytes} bytes and `security` reads {limit} from \
         stdin, so it can only be written on the argument line, which PITBOARD_NO_ARGV \
         forbids. {}",
        smaller(*tool)
    )]
    CredentialTooLarge {
        tool: ProviderId,
        label: String,
        bytes: usize,
        limit: usize,
    },

    #[error(
        "`{program}` is not on this machine, and Pitboard signs in with {}'s own sign-in. \
         Install {}, or point Pitboard at it.",
        tool.name(),
        tool.name()
    )]
    ProgramMissing { tool: ProviderId, program: String },

    #[error(
        "CLAUDE_CODE_CUSTOM_OAUTH_URL is set, so Claude Code keeps its login under a \
         different name than the one Pitboard reads. Unset it to use Pitboard."
    )]
    CustomOauthEndpoint,

    #[error("could not read Pitboard's account list at {path}: {source}")]
    StateUnreadable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Pitboard's account list at {path} is corrupt ({source}). \
         Delete it and enroll your accounts again; parked logins will be lost."
    )]
    StateCorrupt {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error(
        "{path} was written by a newer Pitboard (its format is {found}, this one reads \
         {expected}). Update this Pitboard the way you installed it. The app, and the command \
         line inside it, update with the app's Check for Updates."
    )]
    StateFromNewerVersion {
        path: PathBuf,
        found: u32,
        expected: u32,
    },

    #[error(
        "{path} is in a format ({found}) no version of Pitboard has ever written. Delete it \
         and enroll your accounts again."
    )]
    StateVersionUnknown { path: PathBuf, found: u32 },

    #[error("could not read which accounts Pitboard warms up, at {path}: {source}")]
    WarmSettingUnreadable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "which accounts Pitboard warms up, at {path}, cannot be read ({detail}). Delete it, \
         then turn warm-up on again for each account you want it for."
    )]
    WarmSettingCorrupt { path: PathBuf, detail: String },

    #[error("{}", warm_up_unsupported(*tool, label))]
    WarmUpUnsupported { tool: ProviderId, label: String },

    #[error("`{label}` was not warmed up: {}.", crate::words::warm_failed(.why))]
    WarmUpFailed {
        label: String,
        why: crate::duty::warm::Failure,
    },

    #[error("`{label}` {why}, so it is not warmed up now.")]
    WarmUpNotDue {
        label: String,
        why: String,
        code: &'static str,
    },

    #[error("Pitboard warms up no account now: {}.", crate::words::not_warming(.halt))]
    WarmUpHalted { halt: crate::duty::warm::Halt },

    #[error("another Pitboard is warming up an account. Try again in a minute.")]
    WarmUpInProgress,

    #[error(
        "{path} has an account for `{tool}`, a tool this Pitboard does not know, so it was \
         written by a newer one. Update this Pitboard the way you installed it. The app, and \
         the command line inside it, update with the app's Check for Updates."
    )]
    StateNamesUnknownTool { path: PathBuf, tool: String },

    #[error(
        "{path} was written on another computer. Parked logins do not move between \
         machines, because two machines taking turns presenting one refresh token ends the \
         login for both. Run `pitboard adopt` to keep your accounts here and drop the \
         logins they came with; each then needs one `pitboard enroll <label> --sign-in`."
    )]
    StateWrongMachine { path: PathBuf },

    #[error(
        "this platform has no scheduler Pitboard knows how to write. Keeping parked logins \
         alive here means running `pitboard` yourself from time to time."
    )]
    ScheduleUnsupported,

    #[error("the scheduler refused: {detail}")]
    ScheduleRefused { detail: String },

    /// The schedule renews the default home alone, so it is installed only where
    /// `PITBOARD_HOME` names that home or nothing. `home` is the directory it names, and
    /// `default` the default home, `~/.pitboard`.
    #[error(
        "the renewal schedule renews only the parked logins in {}, not those in {}, which \
         PITBOARD_HOME names. Nothing was scheduled. To schedule it for {}, unset \
         PITBOARD_HOME and install it again.",
        default.display(),
        home.display(),
        default.display()
    )]
    ScheduleNotDefaultHome { home: PathBuf, default: PathBuf },

    #[error("the renewal schedule would run {path}, which is not there. Nothing was scheduled.")]
    ScheduleProgramMissing { path: PathBuf },

    /// macOS runs an app opened where it was downloaded from a copy it makes somewhere
    /// temporary, which is there while the app runs and gone once it quits.
    #[error(
        "the renewal schedule would run {path}, which is in a temporary copy macOS made of \
         the app and is gone once the app quits. Move Pitboard to your Applications folder, \
         open it from there, and turn on daily renewal again."
    )]
    ScheduleProgramTemporary { path: PathBuf },

    /// An app that names no command line for the schedule, where the only other thing to
    /// schedule is the app itself, which renews nothing.
    #[error("this copy of Pitboard has no command line inside it for the renewal schedule to run.")]
    ScheduleProgramUnnamed,

    #[error("could not write to Pitboard's directory at {path}: {source}")]
    HomeUnwritable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("could not save Pitboard's account list at {path}: {source}")]
    StateWriteFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Claude Code has not run on this machine yet ({path} does not exist). \
         Run `claude` once, sign in, then try again."
    )]
    ClaudeConfigMissing { path: PathBuf },

    #[error("could not read Claude Code's config at {path}: {source}")]
    ClaudeConfigUnreadable {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "Claude Code's config at {path} is not valid JSON right now ({source}). \
         It may be mid-write; wait a few seconds and try again."
    )]
    ClaudeConfigNotJson {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error("{}", crate::words::nothing_signed_in(*tool, label.as_deref()))]
    LiveCredentialAbsent {
        tool: ProviderId,
        // the label typed, where a sentence names the command to run for it
        label: Option<String>,
    },

    #[error(
        "Claude Code's config says {email} is signed in, but Pitboard cannot find that \
         login in the keychain or in the file it also reads. It will not write a login \
         where nobody reads it. This usually means Claude Code has started keeping logins \
         somewhere Pitboard does not know about yet: check for a Pitboard update, and \
         report it with `pitboard doctor --json` if there is none."
    )]
    LiveCredentialElsewhere { email: String },

    #[error(
        "the signed-in credential is not shaped like a {} login ({detail}). \
         Run `pitboard doctor` before switching again.",
        tool.name()
    )]
    LiveCredentialShapeUnexpected { tool: ProviderId, detail: String },

    /// The tool is configured to keep its login somewhere Pitboard does not handle.
    #[error("{reason}.")]
    LiveStoreUnsupported { tool: ProviderId, reason: String },

    #[error(
        "no account is enrolled as `{label}`.{enrolled} Run `pitboard enroll {label} \
         --sign-in` to add it."
    )]
    AccountUnknown {
        label: String,
        /// The labels that do exist, so a typo costs no second command.
        enrolled: Enrolled,
    },

    #[error(
        "`{label}` has no parked login to switch to: the last one went back into use and \
         {} has moved on from it. Run `pitboard enroll {label} --sign-in` to sign in to it \
         again.",
        tool.name()
    )]
    NothingParked { tool: ProviderId, label: String },

    #[error(
        "the parked login for `{label}` has expired. Run `pitboard enroll {label} --sign-in` \
         to sign in to it again."
    )]
    ParkedLoginExpired { label: String },

    #[error("{}", not_enrolled(*tool, who))]
    LiveAccountNotEnrolled { tool: ProviderId, who: String },

    #[error("{}", already_enrolled(*tool, email, label, asked, *waited))]
    AlreadyEnrolled {
        tool: ProviderId,
        email: String,
        label: String,
        // the label typed
        asked: String,
        // a sign-in inside the app was waited for under `asked`
        waited: bool,
    },

    #[error("`{label}` already refers to {who}. Choose a different label.")]
    LabelTaken { label: String, who: String },

    #[error(
        "`{typed}` is not a tool Pitboard knows. It knows: {}.",
        known.join(", ")
    )]
    ProviderUnknown { typed: String, known: Vec<String> },

    #[error(
        "`{label}` is enrolled for more than one tool: {}. Say which one.",
        matches.iter().map(|m| format!("`{m}`")).collect::<Vec<_>>().join(", ")
    )]
    LabelAmbiguous { label: String, matches: Vec<String> },

    #[error("`{label}` is signed in; switch to another account before forgetting it.")]
    CannotForgetActiveAccount { label: String },

    /// Asked to write an account into its tool's config as the one in use, once another
    /// account's login is stored, as after a switch made since somebody asked.
    #[error(
        "`{label}` is not signed in now, so Pitboard left {}'s config as it is. A switch \
         writes the account it puts in use there.",
        tool.name()
    )]
    AccountNotInUse { tool: ProviderId, label: String },

    #[error("could not find a free place to park this login. Run `pitboard doctor`.")]
    ParkSlotExhausted,

    #[error(
        "the parked login for `{label}` is missing. Run `pitboard enroll {label} --sign-in` \
         to sign in to it again."
    )]
    ParkedCredentialMissing { label: String },

    #[error(
        "the parked login for `{label}` is not the one Pitboard recorded ({detail}). Run \
         `pitboard enroll {label} --sign-in` to replace it."
    )]
    ParkedCredentialCorrupt { label: String, detail: String },

    #[error("could not back up Claude Code's config ({path}): {source}. Nothing was changed.")]
    ConfigBackupFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    /// Claude Code fetches its profile again only once the config's is a day old (the
    /// register's `config_identity_is_the_last_writers`), so this does not correct itself
    /// sooner.
    #[error(
        "Claude Code's config at {path} could not be updated ({detail}), so Claude Code may \
         show another account's name than the one in use. `pitboard use` with the account in \
         use writes it there."
    )]
    ConfigWriteFailed { path: PathBuf, detail: String },

    /// The service refused the login's access token as expired. `refused` where Pitboard
    /// tried to renew the login and its service refuses its refresh token for good, or it
    /// has none, so only signing in again mends it.
    #[error("{}", session_expired(*tool, *refused))]
    SessionExpired { tool: ProviderId, refused: bool },

    #[error(
        "Pitboard could not confirm with {} which account is signed in ({detail}), and will \
         not move a login it cannot identify. Check the connection and try again.",
        tool.service()
    )]
    IdentityUnverifiable {
        tool: ProviderId,
        cause: Cause,
        detail: String,
    },

    #[error("the signed-in account changed while switching. Nothing was moved; try again.")]
    SignedInAccountChanged,

    #[error("{}", recovery_undetermined(*tool, from, to, detail))]
    RecoveryUndetermined {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "could not sign in as `{to}` ({detail}); `{from}` is still signed in, nothing was lost."
    )]
    SwitchRolledBack {
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "{} no longer accepts `{label}`'s parked login, so Pitboard did not move anything. \
         The copy has been dropped; sign in to that account again with \
         `pitboard enroll {label} --sign-in`.",
        tool.service()
    )]
    ParkedLoginRefused { tool: ProviderId, label: String },

    #[error(
        "`{label}`'s parked login belongs to {who}, not to the account Pitboard has \
         under that label. Nothing was moved. Run `pitboard doctor`, then \
         `pitboard enroll {label} --sign-in` to replace it."
    )]
    ParkedLoginBelongsElsewhere { label: String, who: String },

    #[error(
        "signed in as `{to}`, and the login was gone again before Pitboard finished. {}",
        after_it_did_not_hold(*tool, from, to)
    )]
    SwitchDidNotHold {
        tool: ProviderId,
        from: String,
        to: String,
    },

    #[error(
        "could not sign in as `{to}` ({detail}), and could not read the credential store \
         back to find out whether anything changed. Nothing has been deleted and both \
         logins are still here. {} and run `pitboard use {to}` again; it finishes or \
         undoes this before doing anything else.",
        make_readable(*tool)
    )]
    SwitchUnverified {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "could not sign in as `{to}`, and could not put `{from}` back either ({detail}). \
         `{from}`'s login is still parked: {} and sign in to any enrolled account, then \
         `pitboard use {from}`.",
        crate::words::sign_in_yourself(*tool, false)
    )]
    SwitchCorrupted {
        tool: ProviderId,
        from: String,
        to: String,
        detail: String,
    },

    #[error(
        "signed in to `{label}` again, and Pitboard could not confirm that its new login \
         took the place of the one in use ({detail}), so {} may have no login for it now. {}",
        tool.name(),
        not_in_use(*tool, label, *parked)
    )]
    SignInNotInstalled {
        tool: ProviderId,
        label: String,
        detail: String,
        /// Whether the new login was parked instead, which keeps the one copy of it.
        parked: bool,
        /// What writing it and parking it warned about, which is still true of a change
        /// that failed afterwards. Taken out by the service and reported beside the error.
        warnings: Vec<crate::service::Warning>,
    },

    #[error(
        "the new login for `{label}` could not be put in use ({detail}), so it was not \
         kept, and {} keeps the login it has. Run `pitboard enroll {label} --sign-in` to \
         sign in again.",
        tool.name()
    )]
    SignInNotKept {
        tool: ProviderId,
        label: String,
        detail: String,
    },

    #[error(
        "the record of an interrupted switch at {path} is damaged ({source}), so Pitboard \
         cannot tell what that switch did. Nothing was changed. Check that `pitboard status` \
         shows the account you expect, then delete the file to continue."
    )]
    RecoveryRecordCorrupt {
        path: PathBuf,
        #[source]
        source: serde_json::Error,
    },

    #[error("{}", recovery_elsewhere(*tool, from, to, slot))]
    RecoveryElsewhere {
        tool: ProviderId,
        from: String,
        to: String,
        slot: String,
    },

    #[error("could not read or write Pitboard's recovery record at {path}: {source}")]
    RecoveryFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error(
        "`{}` was not found on PATH. Install {}, run it once, then try again.",
        tool.program(),
        tool.name()
    )]
    ProgramNotFound { tool: ProviderId },

    #[error(
        "could not renew the parked login for `{label}` ({detail}); its last reading is shown \
         instead. Run `pitboard doctor` if this keeps happening."
    )]
    RenewalFailed {
        label: String,
        cause: Option<Cause>,
        detail: String,
    },

    #[error("the sign-in did not finish, so nothing was enrolled.")]
    SignInIncomplete,

    /// The file behind the store in use holds something else than what putting it away was
    /// confirmed for, or is gone.
    #[error(
        "{} has changed since putting it away was confirmed. Putting it away again says first \
         what it holds now.",
        path.display()
    )]
    LeftLoginChanged { path: PathBuf },

    /// The login stored changed before the file behind it could go, where it was going
    /// because of that login: the file held that very login, or another of the same account.
    #[error(
        "the login {} has stored changed while {} was being put away, and whether the file's \
         login is kept somewhere depended on it. Putting it away again says first what it does \
         now.",
        ProviderId::Claude.name(),
        path.display()
    )]
    StoredLoginChanged { path: PathBuf },

    /// The login left in the file is an account's nobody enrolled, so there is no account to
    /// keep it for, and deleting the file would lose it.
    #[error(
        "{} holds {email}'s login{}, an account not enrolled here, so Pitboard has no account to \
         keep it for. Enrol that account first, with `pitboard enroll <label> --sign-in`, or \
         with `pitboard enroll <label>` while Claude Code is signed in to it, then run \
         `pitboard stow` again.",
        path.display(),
        crate::words::in_organisation(organization)
    )]
    LeftLoginNotEnrolled {
        path: PathBuf,
        email: String,
        organization: String,
    },

    #[error(
        "Pitboard could not ask {} whose the login left in {} is ({detail}). Check the \
         connection and try again.",
        ProviderId::Claude.service(),
        path.display()
    )]
    LeftLoginUnidentified {
        path: PathBuf,
        cause: Cause,
        detail: String,
    },

    /// What stopped putting away the file behind a tool's store, said with how far that had
    /// gone, which is never as far as deleting the file. Its code, cause and exit status are
    /// `error`'s, so a program branches on what stopped it.
    #[error("{} Pitboard {partway}.", sentence(error))]
    StowStopped {
        partway: Partway,
        /// What parking the login warned about, where it was parked first. Taken out by the
        /// service and reported beside the error.
        warnings: Vec<crate::service::Warning>,
        error: Box<Error>,
    },

    /// What stopped Pitboard saving a login of a tool's own it had just renewed, where no copy
    /// of the renewed login could be kept either, so the refresh token the tool's store holds
    /// is spent. Its code, cause and exit status are `error`'s.
    #[error(
        "{} Pitboard renewed {}'s login and could not save the renewed login, so the refresh \
         token stored is spent. {}, sign in, then try again.",
        sentence(error),
        tool.name(),
        crate::words::sign_in_yourself(*tool, true)
    )]
    RenewalLost { tool: ProviderId, error: Box<Error> },

    // A refusal after the change had done what `said` says. The service takes it apart.
    #[error("{error}")]
    SaidFirst {
        said: Vec<crate::service::Warning>,
        error: Box<Error>,
    },

    /// Signing in to a second account works by pointing the tool's own login at a scratch
    /// directory. Where that does not isolate it from the live login, running one would
    /// write over the account somebody is using, so Pitboard will not.
    #[error(
        "Pitboard will not sign in to a second account on this machine: {reason} Signing \
         in would write over the login you are using."
    )]
    SignInNotIsolated { reason: String },

    #[error(
        "another `pitboard enroll --sign-in` is already waiting for its sign-in. Finish or \
         cancel that one first."
    )]
    SignInInProgress,

    #[error("{}", app_open(app, still))]
    AppOpen {
        app: &'static str,
        // what of the app still runs once its own program has quit, as `ShipIt (pid 812)`
        still: Vec<String>,
    },

    #[error(
        "Pitboard could not tell whether {app} is open ({why}), so nothing has changed. Run \
         this again."
    )]
    AppStateUnknown { app: &'static str, why: String },

    #[error(
        "{}'s data folder {what}, so Pitboard moves no {} login. {}Nothing has changed.",
        tool.program(),
        tool.name(),
        then.said()
    )]
    LoginFolderUnknown {
        tool: ProviderId,
        what: String,
        then: Then,
    },

    #[error(
        "Pitboard could not read {program}'s cookie store ({detail}). Open {program}, quit it \
         with Command-Q, then run this again. Nothing has changed.",
        program = tool.program()
    )]
    LoginFolderUnreadable { tool: ProviderId, detail: String },

    #[error(
        "{program} has not finished signing in. Open {program}, wait until it shows your \
         chats, quit it with Command-Q, then run this again. Nothing has changed.",
        program = tool.program()
    )]
    SignInUnfinished { tool: ProviderId },

    #[error("{}", in_doubt(*tool, why))]
    LoginInDoubt { tool: ProviderId, why: LoginDoubt },

    #[error(
        "Another Pitboard is changing {app}'s login now, so nothing has changed. Run this \
         again once it has finished."
    )]
    LoginFolderBusy { app: &'static str },

    #[error(
        "Pitboard parks a Claude Desktop login by renaming it into {}, which is on another \
         volume than {}, and it never copies one. Keep Pitboard's folder on the volume your \
         home is on. Nothing has changed.",
        parks.display(),
        root.display()
    )]
    DifferentVolume { parks: PathBuf, root: PathBuf },

    #[error("{}", parks_not_private(path, *why))]
    ParksNotPrivate {
        path: PathBuf,
        why: crate::host::Private,
    },

    #[error(
        "Pitboard could not read this Mac's identity, which it writes beside every parked \
         Claude Desktop login so it never puts back one parked on another Mac. Nothing has \
         changed."
    )]
    MachineUnknown,

    #[error("{}", opened_midway(app, label.as_deref()))]
    AppOpenedMidway {
        app: &'static str,
        // the account whose login was moving; None from the start of a sign-in
        label: Option<String>,
    },

    #[error(
        "Pitboard could not park `{label}`'s login ({detail}) and undid what it had done. \
         `{label}` is in use, and nothing was lost. Run this again."
    )]
    MoveUndone { label: String, detail: String },

    #[error(
        "Pitboard stopped while moving `{label}`'s login ({detail}). Keep Claude closed and \
         run this again: Pitboard settles the move first."
    )]
    MoveStopped { label: String, detail: String },

    // A settle or a give-up that failed partway: coded `recovery_undetermined`, given up alike.
    #[error(
        "Pitboard stopped while settling an interrupted move of `{label}`'s login ({detail}). \
         Nothing is lost. Keep Claude closed and run this again: Pitboard settles the move \
         first. If it stops again, `pitboard abandon` keeps every folder and moves on."
    )]
    RecoveryStopped { label: String, detail: String },

    #[error("{}", left_signed_out(from.as_deref(), to, detail))]
    SwitchLeftSignedOut {
        from: Option<String>,
        to: String,
        detail: String,
    },

    #[error("{}", move_mixed(label, places))]
    MoveMixed { label: String, places: Vec<String> },

    // the account parked last, if any, and each folder set aside that holds a login
    #[error("{}", would_strand(label.as_deref(), set_aside))]
    UninstallWouldStrand {
        label: Option<String>,
        set_aside: Vec<PathBuf>,
    },

    #[error(
        "Another Pitboard command finished, put back or removed the sign-in this one waited \
         for, so it enrolled nothing. Run `pitboard` to see who is signed in."
    )]
    SignInSettledElsewhere { label: String },

    /// This process runs as root or under sudo, or elevated on Windows, or the system could
    /// not say whether it does, so Pitboard changes nothing: the one gate every change passes
    /// refused it. `why` is how it runs, as the host said it, and `None` where the host could
    /// not say.
    #[error("{}", crate::words::elevated(crate::host::OS, *why).refusal)]
    Elevated { why: Option<&'static str> },

    #[error("{}", crate::words::too_old(*build).refusal)]
    SystemTooOld { build: Option<u32> },

    /// This is a Windows build of a release made before Pitboard for Windows is released, so
    /// it does nothing ([`crate::release`]). Kept once Windows is released, where it never
    /// occurs.
    #[error("Pitboard for Windows is not released yet. This build changes nothing.")]
    WindowsNotReleased,

    /// The command line itself was wrong; the message is clap's.
    #[error("{0}")]
    Usage(String),

    /// A command that deletes something was run with nobody to ask, without `--yes`.
    #[error(
        "`pitboard {command}` asks before it deletes anything, and can ask only in a terminal \
         without `--json`. Nothing was changed. Run it in a terminal, or add `--yes`."
    )]
    ConfirmationNeeded { command: &'static str },

    #[error(transparent)]
    Store(#[from] crate::store::Error),

    #[error(transparent)]
    Lock(#[from] crate::lock::LockError),
}

impl Error {
    /// A stable identifier a program can branch on. Adding one is safe; renaming one is not.
    pub fn code(&self) -> &'static str {
        use Error::*;
        match self {
            StateOnSyncedDrive { .. } => "state_on_synced_drive",
            HomeNotAbsolute { .. } => "home_not_absolute",
            ProgramMissing { tool, .. } => match tool {
                ProviderId::Claude => "claude_program_missing",
                ProviderId::Codex => "codex_program_missing",
                ProviderId::Desktop => "desktop_program_missing",
            },
            CredentialTooLarge { .. } => "credential_too_large",
            CustomOauthEndpoint => "custom_oauth_endpoint",
            StateUnreadable { .. } => "state_unreadable",
            StateCorrupt { .. } => "state_corrupt",
            StateFromNewerVersion { .. } => "state_from_newer_version",
            StateVersionUnknown { .. } => "state_version_unknown",
            WarmSettingUnreadable { .. } => "warm_setting_unreadable",
            WarmSettingCorrupt { .. } => "warm_setting_corrupt",
            WarmUpUnsupported { .. } => "warm_up_unsupported",
            WarmUpFailed { why, .. } => why.code(),
            WarmUpNotDue { code, .. } => code,
            WarmUpHalted { halt } => halt.code(),
            WarmUpInProgress => "warm_up_in_progress",
            StateNamesUnknownTool { .. } => "state_names_unknown_tool",
            StateWrongMachine { .. } => "state_wrong_machine",
            StateWriteFailed { .. } => "state_write_failed",
            ScheduleUnsupported => "schedule_unsupported",
            ScheduleRefused { .. } => "schedule_refused",
            ScheduleNotDefaultHome { .. } => "schedule_not_default_home",
            ScheduleProgramMissing { .. } => "schedule_program_missing",
            ScheduleProgramTemporary { .. } => "schedule_program_temporary",
            ScheduleProgramUnnamed => "schedule_program_unnamed",
            HomeUnwritable { .. } => "home_unwritable",
            ClaudeConfigMissing { .. } => "claude_config_missing",
            ClaudeConfigUnreadable { .. } => "claude_config_unreadable",
            ClaudeConfigNotJson { .. } => "claude_config_not_json",
            LiveCredentialAbsent { .. } => "live_credential_absent",
            LiveStoreUnsupported { .. } => "live_store_unsupported",
            LiveCredentialElsewhere { .. } => "live_credential_elsewhere",
            LiveCredentialShapeUnexpected { .. } => "live_credential_shape_unexpected",
            AccountUnknown { .. } => "account_unknown",
            NothingParked { .. } => "nothing_parked",
            ParkedLoginExpired { .. } => "parked_login_expired",
            ParkedLoginRefused { .. } => "parked_login_refused",
            ParkedLoginBelongsElsewhere { .. } => "parked_login_belongs_elsewhere",
            LiveAccountNotEnrolled { .. } => "live_account_not_enrolled",
            AlreadyEnrolled { .. } => "already_enrolled",
            LabelTaken { .. } => "label_taken",
            ProviderUnknown { .. } => "provider_unknown",
            LabelAmbiguous { .. } => "label_ambiguous",
            CannotForgetActiveAccount { .. } => "cannot_forget_active_account",
            AccountNotInUse { .. } => "account_not_in_use",
            ParkSlotExhausted => "park_slot_exhausted",
            ParkedCredentialMissing { .. } => "parked_credential_missing",
            ParkedCredentialCorrupt { .. } => "parked_credential_corrupt",
            ConfigBackupFailed { .. } => "config_backup_failed",
            ConfigWriteFailed { .. } => "config_write_failed",
            SwitchRolledBack { .. } => "switch_rolled_back",
            SwitchDidNotHold { .. } => "switch_did_not_hold",
            SwitchUnverified { .. } => "switch_unverified",
            SwitchCorrupted { .. } => "switch_corrupted",
            SignInNotInstalled { .. } => "sign_in_not_installed",
            SignInNotKept { .. } => "sign_in_not_kept",
            RecoveryFailed { .. } => "recovery_failed",
            RecoveryRecordCorrupt { .. } => "recovery_record_corrupt",
            SessionExpired { .. } => "session_expired",
            IdentityUnverifiable { .. } => "identity_unverifiable",
            SignedInAccountChanged => "signed_in_account_changed",
            RecoveryUndetermined { .. } | RecoveryStopped { .. } => "recovery_undetermined",
            RecoveryElsewhere { .. } => "recovery_elsewhere",
            ProgramNotFound { tool } => match tool {
                ProviderId::Claude => "claude_not_found",
                ProviderId::Codex => "codex_not_found",
                ProviderId::Desktop => "desktop_not_found",
            },
            SignInIncomplete => "sign_in_incomplete",
            LeftLoginChanged { .. } => "left_login_changed",
            StoredLoginChanged { .. } => "stored_login_changed",
            LeftLoginNotEnrolled { .. } => "left_login_not_enrolled",
            LeftLoginUnidentified { .. } => "left_login_unidentified",
            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
                error.code()
            }
            SignInNotIsolated { .. } => "sign_in_not_isolated",
            RenewalFailed { .. } => "renewal_failed",
            SignInInProgress => "sign_in_in_progress",
            AppOpen { .. } => "app_open",
            AppStateUnknown { .. } => "app_state_unknown",
            LoginFolderUnknown { .. } => "login_folder_unknown",
            LoginFolderUnreadable { .. } => "login_folder_unreadable",
            SignInUnfinished { .. } => "sign_in_unfinished",
            LoginInDoubt { .. } => "login_in_doubt",
            LoginFolderBusy { .. } => "login_folder_busy",
            DifferentVolume { .. } => "different_volume",
            ParksNotPrivate { .. } => "parks_not_private",
            MachineUnknown => "machine_unknown",
            AppOpenedMidway { .. } => "app_opened_midway",
            MoveUndone { .. } => "move_undone",
            MoveStopped { .. } => "move_stopped",
            SwitchLeftSignedOut { .. } => "switch_left_signed_out",
            MoveMixed { .. } => "move_mixed",
            UninstallWouldStrand { .. } => "uninstall_would_strand",
            SignInSettledElsewhere { .. } => "sign_in_settled_elsewhere",
            Elevated { .. } => "elevated",
            SystemTooOld { .. } => "system_too_old",
            WindowsNotReleased => "windows_not_released",
            Usage(_) => "usage",
            ConfirmationNeeded { .. } => "confirmation_needed",
            Store(e) => e.code(),
            Lock(e) => e.code(),
        }
    }

    /// What went wrong underneath, where the failure came from a request to Anthropic.
    /// `None` where nothing was asked.
    pub fn cause(&self) -> Option<Cause> {
        use Error::*;
        match self {
            IdentityUnverifiable { cause, .. } | LeftLoginUnidentified { cause, .. } => {
                Some(*cause)
            }
            RenewalFailed { cause, .. } => *cause,
            SessionExpired { refused: true, .. } => Some(Cause::LoginRefused),
            SessionExpired { .. } => Some(Cause::TokenExpired),
            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
                error.cause()
            }
            _ => None,
        }
    }

    /// Warnings a failed change carries in itself, for the caller to report beside it. Only
    /// a failure that happened after something worth warning about was done carries any.
    pub(crate) fn take_warnings(&mut self) -> Vec<crate::service::Warning> {
        let mut said = self.take_said_first();
        if let Error::SignInNotInstalled { warnings, .. } | Error::StowStopped { warnings, .. } =
            self
        {
            said.append(warnings);
        }
        said
    }

    // What the change had done before it refused, outermost first. What is left is the refusal
    // itself.
    pub(crate) fn take_said_first(&mut self) -> Vec<crate::service::Warning> {
        let mut said = Vec::new();
        while let Error::SaidFirst { said: first, error } = self {
            said.append(first);
            *self = std::mem::replace(error.as_mut(), Error::SignInIncomplete);
        }
        said
    }

    // This refusal, after a change that had done what `said` says.
    pub(crate) fn after(self, said: Vec<crate::service::Warning>) -> Error {
        if said.is_empty() {
            return self;
        }
        Error::SaidFirst {
            said,
            error: Box::new(self),
        }
    }

    /// 1 when a request could not be met; 2 when the command line was wrong, or lacks the
    /// `--yes` a command that deletes needs with nobody to ask; 3 when a login or Claude
    /// Code's files are in a state Pitboard cannot safely act on: an unexpected format, or a
    /// login that could not be put back.
    pub fn exit_code(&self) -> u8 {
        use Error::*;
        match self {
            // A login or Claude Code's files in a state Pitboard will not act on, which is
            // what exit 3 means: not a failure of the attempt, a refusal to attempt.
            LiveCredentialShapeUnexpected { .. }
            | LiveStoreUnsupported { .. }
            | ClaudeConfigNotJson { .. }
            | SwitchCorrupted { .. }
            | SwitchUnverified { .. }
            | SwitchDidNotHold { .. }
            | SignInNotInstalled { .. }
            | LiveCredentialElsewhere { .. }
            | CredentialTooLarge { .. }
            | CustomOauthEndpoint
            | RecoveryRecordCorrupt { .. }
            | LoginFolderUnknown { .. }
            | LoginInDoubt { .. }
            | DifferentVolume { .. }
            | ParksNotPrivate { .. }
            | MachineUnknown
            | MoveMixed { .. } => 3,
            Usage(_) | ConfirmationNeeded { .. } => 2,
            Store(e) => e.exit_code(),
            StowStopped { error, .. } | RenewalLost { error, .. } | SaidFirst { error, .. } => {
                error.exit_code()
            }
            _ => 1,
        }
    }
}

/// `error`'s message as a sentence, ending with a full stop as some do not, for more to be
/// said after it.
fn sentence(error: &Error) -> String {
    let said = error.to_string();
    if said.ends_with('.') {
        said
    } else {
        format!("{said}.")
    }
}

pub type Result<T> = std::result::Result<T, Error>;

/// What Pitboard says of a home that is not a full path: which variable named it, and what
/// it holds.
fn not_absolute(variable: &str, path: &std::path::Path) -> String {
    let holds = if path.as_os_str().is_empty() {
        "empty".to_string()
    } else {
        format!("`{}`, which is not a full path", path.display())
    };
    format!(
        "{variable} is {holds}, so the folder it names would depend on where each program \
         runs. Set it to a full path, or unset it; Pitboard reads and changes nothing until \
         then."
    )
}

/// [`Error::SessionExpired`]'s words.
fn session_expired(tool: ProviderId, refused: bool) -> String {
    if refused {
        return format!(
            "{}'s login in use has expired and cannot be renewed, so Pitboard cannot confirm \
             which account is signed in. {}, sign in, then try again.",
            tool.name(),
            crate::words::sign_in_yourself(tool, true)
        );
    }
    format!(
        "{}'s session has expired, so Pitboard cannot confirm which account is signed in. \
         {} once so it refreshes, then try again.",
        tool.name(),
        crate::words::run_it(tool, true)
    )
}

/// What makes a tool's live login readable again, where it could not be read.
fn make_readable(tool: ProviderId) -> &'static str {
    match tool {
        ProviderId::Claude => "Unlock the keychain",
        ProviderId::Codex => "Make Codex's auth.json readable to you again",
        ProviderId::Desktop => "Quit Claude",
    }
}

/// What makes a login smaller, where anything does.
fn smaller(tool: ProviderId) -> &'static str {
    match tool {
        ProviderId::Claude => {
            "Unset it, or sign out of MCP servers you no longer use to make the login smaller."
        }
        ProviderId::Codex | ProviderId::Desktop => "Unset it to let Pitboard write it.",
    }
}

/// Which write took a switched-in login away again, as far as each tool is known to make
/// one, and what that leaves.
fn after_it_did_not_hold(tool: ProviderId, from: &str, to: &str) -> String {
    match tool {
        ProviderId::Claude => format!(
            "Claude Code removes a login without taking the write lock when `/logout` has \
             given up waiting, which is the one write Pitboard cannot exclude. Nothing was \
             lost: both `{from}` and `{to}` are parked. Run `claude` and sign in to any \
             enrolled account, then `pitboard use {to}`."
        ),
        // Not "nothing was lost": the likeliest writer is a codex session refreshing the
        // outgoing account, which spends the token in that account's park, and `codex
        // login` would revoke whatever login is left in auth.json.
        ProviderId::Codex => format!(
            "Codex takes no lock, so a codex session still running from before the switch, \
             refreshing or signing out, rewrote auth.json underneath it. `{to}` is still \
             parked. `{from}`'s park may hold a token that refresh spent. Quit every running \
             codex, then run `pitboard` to see what is signed in; do not run `codex login` \
             or `codex logout` until you have, because either revokes the login they find."
        ),
        ProviderId::Desktop => "Claude was opened before Pitboard finished and wrote its own \
                                login back. Quit Claude, then run `pitboard` to see which \
                                account it holds."
            .into(),
    }
}

/// Where a new login that could not be put in use went, and the way back from there.
fn not_in_use(tool: ProviderId, label: &str, parked: bool) -> String {
    if parked {
        format!(
            "The new login is parked, so it is not lost. Run `pitboard` to see what is \
             signed in; if nothing is, {} and sign in to any enrolled account, then \
             `pitboard use {label}`.",
            crate::words::sign_in_yourself(tool, false)
        )
    } else {
        format!(
            "It could not be parked either: {} and sign in to `{label}` again.",
            crate::words::sign_in_yourself(tool, false)
        )
    }
}

// What a step of a Claude Desktop change says to do once it has refused.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Then {
    Nothing,
    OpenAndQuit,
    UpdatePitboard,
    CopyAside,
    SignInAndEnrol,
}

impl Then {
    // With a space after it, where it says anything.
    pub(crate) fn said(self) -> &'static str {
        match self {
            Then::Nothing => "",
            Then::OpenAndQuit => "Open Claude, quit it with Command-Q, then run this again. ",
            Then::UpdatePitboard => {
                "Update Pitboard, or report it at https://github.com/datlechin/pitboard/issues if \
                 no release reads it yet. "
            }
            Then::CopyAside => {
                "Claude resets a settings file it cannot read when it opens, so copy it aside, \
                 open Claude, quit it with Command-Q, then run this again. "
            }
            Then::SignInAndEnrol => {
                "Open Claude. If it asks you to sign in, sign in. Quit it with Command-Q, then \
                 run `pitboard enroll desktop/<label>` for the account it shows. "
            }
        }
    }
}

// Why the login Claude holds cannot be taken as any account's without the person's word.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum LoginDoubt {
    // `named`: the account Claude names, as typed; None for one Pitboard has not enrolled
    NamedAnother {
        recorded: String,
        named: Option<String>,
    },
    // `label` was signed in to outside Pitboard, beside the login it parked
    SignedInOutside {
        label: String,
    },
}

fn app_open(app: &str, still: &[String]) -> String {
    if still.is_empty() {
        return format!(
            "{app} is open, and Pitboard changes its login only while it is closed. Quit {app} \
             with Command-Q, then run this again. Nothing has changed."
        );
    }
    format!(
        "{app} has quit, and {} from it is still running, and Pitboard changes {app}'s login \
         only while all of it is closed. {} Nothing has changed.",
        crate::words::listed(still.to_vec()),
        crate::words::wait_for_still("run this again")
    )
}

fn in_doubt(tool: ProviderId, why: &LoginDoubt) -> String {
    let enroll = Key::new(tool, "<label>").typed();
    match why {
        LoginDoubt::NamedAnother { recorded, named } => {
            let named = named.as_ref().map_or_else(
                || "an account Pitboard has not enrolled".to_string(),
                |label| format!("`{label}`"),
            );
            format!(
                "Pitboard recorded this {program} login as `{recorded}`'s, and {program} names \
                 {named} for it. Open {program}, check which account it shows, quit it with \
                 Command-Q, then run `pitboard enroll {enroll}` under that account's name. \
                 Nothing has changed.",
                program = tool.program()
            )
        }
        LoginDoubt::SignedInOutside { label } => format!(
            "{program} was signed in to `{label}` outside Pitboard, so Pitboard cannot tell this \
             login from the one it parked. Open {program}, check which account it shows, and \
             quit it with Command-Q. If it shows `{label}`, run `pitboard enroll {label}`, then \
             this again. If it shows another account, run `pitboard enroll {enroll}` under that \
             account's name. Nothing has changed.",
            program = tool.program()
        ),
    }
}

fn not_enrolled(tool: ProviderId, who: &str) -> String {
    let enroll = Key::new(tool, "<label>").typed();
    match tool {
        ProviderId::Claude | ProviderId::Codex => format!(
            "{who} is signed in but not enrolled, so it cannot be parked. Run `pitboard enroll \
             {enroll}` for it first."
        ),
        ProviderId::Desktop => format!(
            "Claude is signed in to an account Pitboard has not enrolled, so it cannot be \
             parked. Run `pitboard enroll {enroll}` for it first."
        ),
    }
}

fn already_enrolled(
    tool: ProviderId,
    email: &str,
    label: &str,
    asked: &str,
    waited: bool,
) -> String {
    match tool {
        ProviderId::Claude | ProviderId::Codex => format!(
            "{email} is already enrolled as `{label}`. To add a different account, run \
             `pitboard enroll {} --sign-in`.",
            Key::new(tool, "<label>").typed()
        ),
        ProviderId::Desktop if waited => format!(
            "Claude is signed in to `{label}`. Run `pitboard enroll {label}` to record that \
             login, then add another with `pitboard enroll {asked} --sign-in`."
        ),
        ProviderId::Desktop => format!(
            "Claude is signed in to `{label}`, which is enrolled already. To add `{asked}`, run \
             `pitboard enroll {asked} --sign-in`."
        ),
    }
}

fn parks_not_private(path: &std::path::Path, why: crate::host::Private) -> String {
    use crate::host::Private;
    let path = path.display();
    let own = "Point `PITBOARD_HOME` at a folder of your own on this volume, then run this again.";
    let said = match why {
        Private::Shared => {
            format!("{path} can be reached by others. Run `chmod 700 {path}`, then run this again.")
        }
        Private::Link => {
            format!("{path} is a link, so Pitboard parks no Claude Desktop login there. {own}")
        }
        Private::NotOwn => {
            format!("{path} is not yours, so Pitboard parks no Claude Desktop login there. {own}")
        }
        Private::NotADirectory | Private::Missing | Private::Yes => format!(
            "{path} is not a folder, so Pitboard parks no Claude Desktop login there. {own}"
        ),
    };
    format!("{said} Nothing has changed.")
}

fn opened_midway(app: &str, label: Option<&str>) -> String {
    match label {
        Some(label) => format!(
            "{app} was opened while Pitboard moved `{label}`'s login, so Pitboard stopped. \
             Nothing is lost. Quit {app} with Command-Q, then run this again: Pitboard settles \
             the move first."
        ),
        None => format!(
            "{app} was opened while Pitboard set aside the account name {app} kept, so \
             Pitboard stopped. Nothing is lost. Quit {app} with Command-Q, then run this again."
        ),
    }
}

fn would_strand(label: Option<&str>, set_aside: &[PathBuf]) -> String {
    let every = "so uninstalling would delete every Claude Desktop login Pitboard holds.";
    match label {
        Some(label) => format!(
            "No Claude Desktop account is in use, and `{label}` is parked, {every} Run `pitboard \
             use {label}`, then uninstall, or `pitboard forget` each Claude Desktop account first."
        ),
        None => {
            let held = match set_aside {
                [_] => "holds a Claude Desktop login",
                _ => "hold Claude Desktop logins",
            };
            let folders = set_aside
                .iter()
                .map(|path| path.display().to_string())
                .collect();
            format!(
                "No Claude Desktop account is in use, and {} {held} Pitboard set aside, {every} \
                 Run `pitboard enroll desktop/<label> --sign-in` to sign in to an account you \
                 keep, then uninstall.",
                crate::words::listed(folders)
            )
        }
    }
}

fn move_mixed(label: &str, places: &[String]) -> String {
    format!(
        "Giving up would leave parts of `{label}` beside another login in Claude's folder: {}. \
         Nothing has changed. {}",
        places.join(", "),
        crate::words::mixed_way_out(label)
    )
}

fn left_signed_out(from: Option<&str>, to: &str, detail: &str) -> String {
    match from {
        Some(from) => format!(
            "`{from}` is parked, and `{to}` could not be put in use ({detail}). Claude is \
             signed out and both logins are parked. Run `pitboard use {to}` again, or `pitboard \
             use {from}` to go back."
        ),
        None => format!(
            "`{to}` could not be put in use ({detail}). Claude is signed out and `{to}` is \
             still parked. Run `pitboard use {to}` again."
        ),
    }
}

fn warm_up_unsupported(tool: ProviderId, label: &str) -> String {
    match tool {
        ProviderId::Claude | ProviderId::Codex => format!(
            "`{label}` is a {name} account, and Pitboard warms up Claude Code accounts only: when \
             a {name} period starts has not been measured.",
            name = tool.name()
        ),
        ProviderId::Desktop => format!(
            "`{label}` is a Claude Desktop account, and Pitboard sends no request for one, so it \
             warms up none."
        ),
    }
}

fn recovery_undetermined(tool: ProviderId, from: &str, to: &str, detail: &str) -> String {
    match tool {
        ProviderId::Claude | ProviderId::Codex => format!(
            "an earlier switch from `{from}` to `{to}` was interrupted, and Pitboard cannot yet \
             tell whether it finished ({detail}). Nothing was changed. {} once so its session \
             is current, then try again.",
            crate::words::run_it(tool, true)
        ),
        ProviderId::Desktop => format!(
            "An earlier move of `{to}`'s login was interrupted, and Pitboard cannot tell where it \
             stopped ({detail}). Nothing has changed. {}",
            crate::words::undetermined_way_out()
        ),
    }
}

fn recovery_elsewhere(tool: ProviderId, from: &str, to: &str, slot: &str) -> String {
    match tool {
        ProviderId::Claude | ProviderId::Codex => format!(
            "an earlier switch of {} from `{from}` to `{to}` was interrupted while its login was \
             at {slot}, and this run reads it from somewhere else, so it cannot tell what that \
             switch did. Nothing was changed. {} to finish it, or `pitboard abandon` to keep \
             every login it names and move on.",
            tool.name(),
            crate::words::pointing_where_it_did(tool)
        ),
        ProviderId::Desktop => format!(
            "An earlier move of `{to}`'s login was interrupted while Claude kept its data in \
             {slot}, and this run finds it somewhere else. Nothing has changed. {}",
            crate::words::elsewhere_way_out(tool)
        ),
    }
}

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

    // Word for word what each said before a tool could be an app.
    #[test]
    fn every_claude_code_and_codex_sentence_reads_as_it_did() {
        let said = |tool: ProviderId| {
            let moved = |make: fn(ProviderId, String, String, String) -> Error| {
                make(tool, "a".into(), "b".into(), "d".into()).to_string()
            };
            let not_installed = |parked| Error::SignInNotInstalled {
                tool,
                label: "l".into(),
                detail: "d".into(),
                parked,
                warnings: Vec::new(),
            };
            vec![
                Error::LiveCredentialAbsent { tool, label: None }.to_string(),
                moved(|tool, from, to, detail| Error::RecoveryUndetermined {
                    tool,
                    from,
                    to,
                    detail,
                }),
                moved(|tool, from, to, detail| Error::SwitchCorrupted {
                    tool,
                    from,
                    to,
                    detail,
                }),
                moved(|tool, from, to, slot| Error::RecoveryElsewhere {
                    tool,
                    from,
                    to,
                    slot,
                }),
                Error::RenewalLost {
                    tool,
                    error: Box::new(Error::SignedInAccountChanged),
                }
                .to_string(),
                Error::SessionExpired {
                    tool,
                    refused: true,
                }
                .to_string(),
                Error::SessionExpired {
                    tool,
                    refused: false,
                }
                .to_string(),
                not_installed(true).to_string(),
                not_installed(false).to_string(),
                crate::service::Warning::SignInParkedNotInUse {
                    tool,
                    label: "l".into(),
                    why: "w".into(),
                }
                .to_string(),
                Error::LiveAccountNotEnrolled {
                    tool,
                    who: "a@b.c".into(),
                }
                .to_string(),
                Error::AlreadyEnrolled {
                    tool,
                    email: "a@b.c".into(),
                    label: "l".into(),
                    asked: "other".into(),
                    waited: false,
                }
                .to_string(),
            ]
        };
        let before = |name: &str, sign_in: &str, run: &str, home: &str, enroll: &str| {
            vec![
                format!(
                    "nothing is signed in to {name} right now. Run `{sign_in}`, sign in, then try again."
                ),
                format!(
                    "an earlier switch from `a` to `b` was interrupted, and Pitboard cannot yet \
                     tell whether it finished (d). Nothing was changed. Run `{run}` once so its \
                     session is current, then try again."
                ),
                format!(
                    "could not sign in as `b`, and could not put `a` back either (d). `a`'s login \
                     is still parked: run `{sign_in}` and sign in to any enrolled account, then \
                     `pitboard use a`."
                ),
                format!(
                    "an earlier switch of {name} from `a` to `b` was interrupted while its login \
                     was at d, and this run reads it from somewhere else, so it cannot tell what \
                     that switch did. Nothing was changed. Run Pitboard with {home} pointing \
                     where it did to finish it, or `pitboard abandon` to keep every login it \
                     names and move on."
                ),
                format!(
                    "the signed-in account changed while switching. Nothing was moved; try again. \
                     Pitboard renewed {name}'s login and could not save the renewed login, so \
                     the refresh token stored is spent. Run `{sign_in}`, sign in, then try again."
                ),
                format!(
                    "{name}'s login in use has expired and cannot be renewed, so Pitboard cannot \
                     confirm which account is signed in. Run `{sign_in}`, sign in, then try again."
                ),
                format!(
                    "{name}'s session has expired, so Pitboard cannot confirm which account is \
                     signed in. Run `{run}` once so it refreshes, then try again."
                ),
                format!(
                    "signed in to `l` again, and Pitboard could not confirm that its new login \
                     took the place of the one in use (d), so {name} may have no login for it \
                     now. The new login is parked, so it is not lost. Run `pitboard` to see what \
                     is signed in; if nothing is, run `{sign_in}` and sign in to any enrolled \
                     account, then `pitboard use l`."
                ),
                format!(
                    "signed in to `l` again, and Pitboard could not confirm that its new login \
                     took the place of the one in use (d), so {name} may have no login for it \
                     now. It could not be parked either: run `{sign_in}` and sign in to `l` again."
                ),
                format!(
                    "{name} goes on with the login it has: Pitboard could not tell whose it is \
                     (w), so it parked the new login for `l` rather than write over that one. If \
                     that login no longer works, run `{sign_in}` and sign in to `l` there."
                ),
                format!(
                    "a@b.c is signed in but not enrolled, so it cannot be parked. Run `pitboard \
                     enroll {enroll}` for it first."
                ),
                format!(
                    "a@b.c is already enrolled as `l`. To add a different account, run `pitboard \
                     enroll {enroll} --sign-in`."
                ),
            ]
        };
        let pairs = |tool, expected: Vec<String>| {
            for (now, then) in said(tool).into_iter().zip(expected) {
                assert_eq!(now, then, "{tool}");
            }
        };
        pairs(
            ProviderId::Claude,
            before(
                "Claude Code",
                "claude",
                "claude",
                "CLAUDE_CONFIG_DIR",
                "<label>",
            ),
        );
        pairs(
            ProviderId::Codex,
            before(
                "Codex",
                "codex login",
                "codex",
                "CODEX_HOME",
                "codex/<label>",
            ),
        );
        // Claude Desktop has words of its own for each, and none names a program to run.
        for sentence in said(ProviderId::Desktop) {
            assert!(!sentence.contains("Run `Claude`"), "{sentence}");
            assert!(!sentence.contains("run `Claude`"), "{sentence}");
        }
        let absent = |label: Option<&str>| {
            Error::LiveCredentialAbsent {
                tool: ProviderId::Desktop,
                label: label.map(str::to_string),
            }
            .to_string()
        };
        assert_eq!(
            absent(Some("desktop/travel")),
            "Claude is not signed in. Run `pitboard enroll desktop/travel --sign-in`, then sign \
             in inside Claude and quit it: Pitboard waits for that, and sets aside any account \
             name Claude kept first."
        );
        assert!(absent(None).contains("`pitboard enroll desktop/<label> --sign-in`"));
    }

    #[test]
    fn a_moves_refusals_say_their_code_their_exit_and_what_to_do() {
        let said = |error: Error| (error.code(), error.exit_code(), error.to_string());
        let label = || "desktop/work".to_string();
        assert_eq!(
            said(Error::MachineUnknown),
            (
                "machine_unknown",
                3,
                "Pitboard could not read this Mac's identity, which it writes beside every \
                 parked Claude Desktop login so it never puts back one parked on another Mac. \
                 Nothing has changed."
                    .into()
            )
        );
        assert_eq!(
            said(Error::AppOpenedMidway {
                app: "Claude",
                label: Some(label())
            }),
            (
                "app_opened_midway",
                1,
                "Claude was opened while Pitboard moved `desktop/work`'s login, so Pitboard \
                 stopped. Nothing is lost. Quit Claude with Command-Q, then run this again: \
                 Pitboard settles the move first."
                    .into()
            )
        );
        assert!(
            said(Error::AppOpenedMidway {
                app: "Claude",
                label: None
            })
            .2
            .contains("set aside the account name Claude kept")
        );
        assert_eq!(
            said(Error::SwitchLeftSignedOut {
                from: Some(label()),
                to: "desktop/home".into(),
                detail: "d".into()
            }),
            (
                "switch_left_signed_out",
                1,
                "`desktop/work` is parked, and `desktop/home` could not be put in use (d). \
                 Claude is signed out and both logins are parked. Run `pitboard use \
                 desktop/home` again, or `pitboard use desktop/work` to go back."
                    .into()
            )
        );
        assert!(
            said(Error::SwitchLeftSignedOut {
                from: None,
                to: "desktop/home".into(),
                detail: "d".into()
            })
            .2
            .ends_with("`desktop/home` is still parked. Run `pitboard use desktop/home` again.")
        );
        assert_eq!(
            said(Error::RecoveryStopped {
                label: label(),
                detail: "d".into()
            }),
            (
                "recovery_undetermined",
                1,
                "Pitboard stopped while settling an interrupted move of `desktop/work`'s login \
                 (d). Nothing is lost. Keep Claude closed and run this again: Pitboard settles \
                 the move first. If it stops again, `pitboard abandon` keeps every folder and \
                 moves on."
                    .into()
            )
        );
        let parks = PathBuf::from("/p/parks");
        for (why, words) in [
            (crate::host::Private::Shared, "Run `chmod 700 /p/parks`"),
            (crate::host::Private::Link, "/p/parks is a link"),
            (crate::host::Private::NotOwn, "/p/parks is not yours"),
        ] {
            let (code, exit, sentence) = said(Error::ParksNotPrivate {
                path: parks.clone(),
                why,
            });
            assert_eq!((code, exit), ("parks_not_private", 3));
            assert!(sentence.contains(words), "{sentence}");
            assert!(sentence.ends_with("Nothing has changed."), "{sentence}");
        }
        for (error, code, exit) in [
            (
                Error::DifferentVolume {
                    parks: parks.clone(),
                    root: PathBuf::from("/data"),
                },
                "different_volume",
                3,
            ),
            (
                Error::MoveUndone {
                    label: label(),
                    detail: "d".into(),
                },
                "move_undone",
                1,
            ),
            (
                Error::MoveStopped {
                    label: label(),
                    detail: "d".into(),
                },
                "move_stopped",
                1,
            ),
            (
                Error::MoveMixed {
                    label: label(),
                    places: vec!["`a` in Claude's folder".into()],
                },
                "move_mixed",
                3,
            ),
            (
                Error::UninstallWouldStrand {
                    label: Some(label()),
                    set_aside: Vec::new(),
                },
                "uninstall_would_strand",
                1,
            ),
            (
                Error::UninstallWouldStrand {
                    label: None,
                    set_aside: vec![PathBuf::from("/p/parks/pitboard-aside-1")],
                },
                "uninstall_would_strand",
                1,
            ),
            (
                Error::SignInSettledElsewhere { label: label() },
                "sign_in_settled_elsewhere",
                1,
            ),
        ] {
            assert_eq!((error.code(), error.exit_code()), (code, exit), "{error}");
            assert!(!error.to_string().contains('\u{2014}'), "{error}");
        }
        let waited = Error::AlreadyEnrolled {
            tool: ProviderId::Desktop,
            email: String::new(),
            label: "desktop/home".into(),
            asked: "desktop/travel".into(),
            waited: true,
        };
        assert_eq!(
            waited.to_string(),
            "Claude is signed in to `desktop/home`. Run `pitboard enroll desktop/home` to \
             record that login, then add another with `pitboard enroll desktop/travel \
             --sign-in`."
        );
    }

    #[test]
    fn codes_are_unique_so_a_caller_can_branch_on_them() {
        let samples = [
            Error::LiveCredentialAbsent {
                tool: ProviderId::Claude,
                label: None,
            },
            Error::ParkSlotExhausted,
            Error::SignedInAccountChanged,
            Error::AccountUnknown {
                label: "x".into(),
                enrolled: Enrolled::default(),
            },
            Error::NothingParked {
                tool: ProviderId::Claude,
                label: "x".into(),
            },
            Error::ParkedLoginExpired { label: "x".into() },
            Error::AccountNotInUse {
                tool: ProviderId::Claude,
                label: "x".into(),
            },
            Error::LabelTaken {
                label: "x".into(),
                who: "e".into(),
            },
            Error::SwitchRolledBack {
                from: "x".into(),
                to: "y".into(),
                detail: "d".into(),
            },
            Error::SignInNotKept {
                tool: ProviderId::Codex,
                label: "x".into(),
                detail: "d".into(),
            },
            Error::Elevated { why: None },
            Error::SystemTooOld { build: Some(22631) },
            Error::WindowsNotReleased,
            Error::LeftLoginChanged { path: "f".into() },
            Error::StoredLoginChanged { path: "f".into() },
            Error::Usage("u".into()),
            Error::ConfirmationNeeded { command: "stow" },
        ];
        let mut codes: Vec<&str> = samples.iter().map(Error::code).collect();
        codes.sort_unstable();
        let before = codes.len();
        codes.dedup();
        assert_eq!(codes.len(), before);
    }

    /// Whatever stops putting the file away is branched on by its own code, cause and exit
    /// status, and says after its own words how far putting it away had gone.
    #[test]
    fn what_stopped_putting_a_file_away_keeps_its_code_and_says_how_far_it_went() {
        let stopped = Error::StowStopped {
            partway: Partway::Parked {
                label: "work".into(),
            },
            warnings: Vec::new(),
            error: Box::new(Error::Store(crate::store::Error::Locked)),
        };

        assert_eq!(stopped.code(), "credential_store_locked");
        assert_eq!(
            stopped.exit_code(),
            Error::Store(crate::store::Error::Locked).exit_code()
        );
        assert!(
            stopped.to_string().ends_with(
                "desktop session. Pitboard deleted nothing, having parked the login in the file \
                 for `work`."
            ),
            "{stopped}"
        );

        let unidentified = Error::StowStopped {
            partway: Partway::Nothing,
            warnings: Vec::new(),
            error: Box::new(Error::LeftLoginUnidentified {
                path: "f".into(),
                cause: Cause::Unreachable,
                detail: "offline".into(),
            }),
        };
        assert_eq!(unidentified.code(), "left_login_unidentified");
        assert_eq!(unidentified.cause(), Some(Cause::Unreachable));
        assert!(
            unidentified
                .to_string()
                .ends_with("try again. Pitboard changed nothing."),
            "{unidentified}"
        );
    }

    #[test]
    fn a_refusal_after_what_was_said_is_given_back_as_itself() {
        let refusal = || Error::AccountNotInUse {
            tool: ProviderId::Desktop,
            label: "desktop/work".into(),
        };
        let waiting = crate::service::Warning::MoveWaiting {
            tool: ProviderId::Desktop,
            label: "desktop/work".into(),
        };
        let mut carried = refusal().after(vec![waiting]);
        assert_eq!(carried.code(), "account_not_in_use");
        assert_eq!(carried.exit_code(), refusal().exit_code());
        assert_eq!(carried.to_string(), refusal().to_string());
        let said = carried.take_warnings();
        assert_eq!(
            said.iter()
                .map(crate::service::Warning::code)
                .collect::<Vec<_>>(),
            ["move_waiting"]
        );
        assert!(
            matches!(carried, Error::AccountNotInUse { .. }),
            "{carried:?}"
        );
        assert!(carried.take_warnings().is_empty());
        let alone = refusal().after(Vec::new());
        assert!(matches!(alone, Error::AccountNotInUse { .. }), "{alone:?}");
    }

    #[test]
    fn a_broken_assumption_exits_differently_from_a_bad_request() {
        assert_eq!(
            Error::LiveCredentialShapeUnexpected {
                tool: ProviderId::Claude,
                detail: "x".into()
            }
            .exit_code(),
            3
        );
        assert_eq!(
            Error::AccountUnknown {
                label: "x".into(),
                enrolled: Enrolled::default()
            }
            .exit_code(),
            1
        );
    }

    #[test]
    fn every_message_tells_the_user_something_to_do() {
        // A message that only states a fact leaves the user stuck.
        let actionable = [
            Error::LiveCredentialAbsent {
                tool: ProviderId::Claude,
                label: None,
            }
            .to_string(),
            Error::LiveCredentialAbsent {
                tool: ProviderId::Codex,
                label: None,
            }
            .to_string(),
            Error::AccountUnknown {
                label: "work".into(),
                enrolled: Enrolled(vec!["personal".into()]),
            }
            .to_string(),
            Error::NothingParked {
                tool: ProviderId::Claude,
                label: "work".into(),
            }
            .to_string(),
            Error::ParkedLoginExpired {
                label: "work".into(),
            }
            .to_string(),
            Error::ParkedCredentialMissing {
                label: "work".into(),
            }
            .to_string(),
            Error::LiveAccountNotEnrolled {
                tool: ProviderId::Claude,
                who: "a@b.c".into(),
            }
            .to_string(),
            Error::SignInNotKept {
                tool: ProviderId::Codex,
                label: "codex/work".into(),
                detail: "the keychain is locked".into(),
            }
            .to_string(),
            Error::ConfirmationNeeded { command: "forget" }.to_string(),
        ];
        for message in actionable {
            assert!(
                message.contains("Run ") || message.contains("Sign in"),
                "no action offered: {message}"
            );
        }
    }

    /// Codex's messages name Codex and the command that signs in to it; Claude Code's name
    /// Claude Code. A message about the wrong tool sends somebody to run the wrong program.
    #[test]
    fn a_message_names_the_tool_it_is_about() {
        let codex = Error::LiveCredentialAbsent {
            tool: ProviderId::Codex,
            label: None,
        }
        .to_string();
        assert!(
            codex.contains("Codex") && codex.contains("`codex login`"),
            "{codex}"
        );
        assert!(!codex.contains("Claude"), "{codex}");

        let unverifiable = Error::IdentityUnverifiable {
            tool: ProviderId::Codex,
            cause: Cause::Unreachable,
            detail: "offline".into(),
        }
        .to_string();
        assert!(unverifiable.contains("OpenAI"), "{unverifiable}");

        let claude = Error::IdentityUnverifiable {
            tool: ProviderId::Claude,
            cause: Cause::Unreachable,
            detail: "offline".into(),
        }
        .to_string();
        assert!(claude.contains("confirm with Anthropic"), "{claude}");
    }

    /// The codes of the two tools' missing programs stay distinct, and Claude Code's keep
    /// the names they were released under.
    #[test]
    fn a_missing_program_keeps_its_released_code() {
        let missing = |tool| Error::ProgramNotFound { tool }.code();
        assert_eq!(missing(ProviderId::Claude), "claude_not_found");
        assert_eq!(missing(ProviderId::Codex), "codex_not_found");
        let absent = |tool| {
            Error::ProgramMissing {
                tool,
                program: "x".into(),
            }
            .code()
        };
        assert_eq!(absent(ProviderId::Claude), "claude_program_missing");
        assert_eq!(absent(ProviderId::Codex), "codex_program_missing");
    }

    /// A Pitboard that finds its files written by a newer one is updated by the route it
    /// came by. The app's Check for Updates moves only the app and the command line inside
    /// it, so it is not offered as another way to update this one.
    #[test]
    fn a_newer_pitboards_files_say_which_update_moves_which_pitboard() {
        let path = PathBuf::from("/home/x/.pitboard/state.json");
        for message in [
            Error::StateFromNewerVersion {
                path: path.clone(),
                found: 9,
                expected: 5,
            }
            .to_string(),
            Error::StateNamesUnknownTool {
                path,
                tool: "gemini".into(),
            }
            .to_string(),
        ] {
            assert!(
                message.contains("Update this Pitboard the way you installed it."),
                "{message}"
            );
            assert!(
                message.contains("The app, and the command line inside it, update with"),
                "{message}"
            );
            assert!(!message.contains("or with the app"), "{message}");
        }
    }

    /// Advice to enrol names the tool the account is for: a bare name would enrol a Claude
    /// Code account for a Codex login.
    #[test]
    fn enrolment_advice_keeps_the_tool() {
        let codex = Error::LiveAccountNotEnrolled {
            tool: ProviderId::Codex,
            who: "a@b.c".into(),
        }
        .to_string();
        assert!(codex.contains("pitboard enroll codex/<label>"), "{codex}");
        let claude = Error::LiveAccountNotEnrolled {
            tool: ProviderId::Claude,
            who: "a@b.c".into(),
        }
        .to_string();
        assert!(claude.contains("pitboard enroll <label>"), "{claude}");
        let already = Error::AlreadyEnrolled {
            tool: ProviderId::Codex,
            email: "a@b.c".into(),
            label: "codex/work".into(),
            asked: "codex/other".into(),
            waited: false,
        }
        .to_string();
        assert!(
            already.contains("pitboard enroll codex/<label> --sign-in"),
            "{already}"
        );
    }

    /// Only a command that changes something finishes an interrupted switch; a plain
    /// `pitboard` reads and leaves it. So the message names the switch to run again, as it
    /// would be typed here.
    #[test]
    fn an_unverified_switch_names_a_command_that_finishes_it() {
        let message = Error::SwitchUnverified {
            tool: ProviderId::Codex,
            from: "codex/personal".into(),
            to: "codex/work".into(),
            detail: "auth.json is not readable".into(),
        }
        .to_string();
        assert!(
            message.contains("run `pitboard use codex/work` again"),
            "{message}"
        );
        assert!(!message.contains("run `pitboard` again"), "{message}");
    }
}