pitboard-core 0.8.0

The engine behind Pitboard: parking and restoring Claude Code and Codex logins. 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
//! Pitboard's operations, each run the way every front end must run it: a change settles any
//! interrupted switch first and is recorded in the audit log, and what went wrong on the way
//! is reported alongside the result, whether or not the change then succeeds.

use crate::context::Context;
use crate::doctor::{self, Diagnosis};
use crate::error::{Error, Result};
use crate::holder::{self, capitalised};
use crate::host::Elevation;
use crate::provider::ProviderId;
use crate::state::{self, Account, Key};
use crate::switch::{self, Enrolled, Outcome, Recovered, Renewal, Settled, SignIn};
use crate::{audit, readings, schedule, status, statusline};
use std::fmt;

/// Proof that this process may change something on this machine, which only the one gate
/// every change passes makes ([`Pitboard::permit`]).
///
/// Everything that changes anything takes one as an argument: the durable write of a file,
/// every private file or directory made and every one removed, a write to or a delete from
/// any store of logins, the keychain among them, a change to the system's scheduler, a
/// tool's sign-in started, and the token exchange that renews a parked login. So a change
/// that did not ask the gate does not compile, and nothing rotates a refresh token it could
/// not then write down.
#[derive(Debug, Clone, Copy)]
pub struct Permit {
    _only_the_gate_makes_one: (),
}

#[cfg(test)]
impl Permit {
    /// One for a unit test of what takes it, below the gate. A test of the gate itself, or
    /// of a change through [`Pitboard`], asks the gate.
    pub(crate) fn for_a_test() -> Permit {
        Permit {
            _only_the_gate_makes_one: (),
        }
    }
}

/// The one gate every change passes: whether this process may change anything here, as the
/// host says. A process that runs as root or under sudo changes nothing, and nor does one
/// the host cannot place: a file it wrote would be root's, and a keychain item might be,
/// where the person's own runs might never read, replace or remove it again.
///
/// Nor does one whose environment names a home that is empty or relative
/// ([`crate::home::check_absolute`]): what it wrote would land under whichever folder it
/// was run from. Asked after elevation, so `sudo` is what a run under it is told first.
///
/// Before either, a build that may do nothing at all changes nothing: a Windows build of a
/// release made before Pitboard for Windows is released ([`crate::release`]). So no writer
/// and no token exchange runs there, even for a caller that forgot to ask.
pub(crate) fn gate(ctx: &Context) -> Result<Permit> {
    crate::release::check()?;
    match ctx.host().elevation(ctx) {
        Elevation::Normal => {}
        Elevation::Elevated { why } => return Err(Error::Elevated { why: Some(why) }),
        Elevation::Unknown => return Err(Error::Elevated { why: None }),
    }
    crate::home::check_absolute(ctx)?;
    Ok(Permit {
        _only_the_gate_makes_one: (),
    })
}

/// Something to know about that did not stop the operation.
#[derive(Debug)]
#[non_exhaustive]
pub enum Warning {
    /// An earlier switch had been interrupted; this run found what it did and recorded it.
    Recovered(Recovered),
    /// The login moved, but what the tool caches about who is signed in still names the
    /// previous account.
    ConfigNotUpdated(Error),
    /// Parked logins no longer in use that could not be deleted yet.
    ParksPendingRemoval(usize),
    /// The service refuses a parked login for good, so it was dropped.
    ParkedLoginRefused {
        tool: ProviderId,
        label: String,
    },
    RenewalFailed(Error),
    /// The tool's write lock stopped being Pitboard's while a change was under way.
    LockCompromised {
        tool: ProviderId,
    },
    /// The environment authenticates the tool some other way, so the login Pitboard moved
    /// is not the one a session will use.
    AuthOverridden {
        tool: ProviderId,
        names: Vec<String>,
    },
    /// The login was too large for `security`'s stdin, so it went on the argument line.
    WrittenOnTheCommandLine {
        tool: ProviderId,
        bytes: usize,
        limit: usize,
    },
    /// Sessions of a tool that never follows a switch on its own were running when it
    /// happened, and go on using the account they started with until they are restarted.
    /// `holding` is what was running, by kind, never empty.
    SessionsStillRunning {
        from: String,
        holding: Vec<crate::holder::Holding>,
    },
    /// A sign-in put a new login in use in place of the old one of the same account, and
    /// sessions of a tool that never reads its login again were running with the old one.
    SessionsKeepTheOldLogin {
        label: String,
        holding: Vec<crate::holder::Holding>,
    },
    /// A switch of a tool that never follows one on its own, where the process list could
    /// not be read: nobody can say whether anything of the tool started before it is still
    /// running, and still using `from`. Not the same as nothing running, which says nothing.
    SessionsUnknown {
        tool: ProviderId,
        from: String,
    },
    /// A sign-in that put a new login of `label` in use, of a tool that never reads its login
    /// again, where the process list could not be read: nobody can say whether anything of
    /// the tool is still running with the old login.
    SessionsUnknownAfterSignIn {
        tool: ProviderId,
        label: String,
    },
    /// A sign-in to the account Pitboard last recorded in use was parked rather than put in
    /// use, because nobody could say whose login the tool has in use, for `why`.
    SignInParkedNotInUse {
        tool: ProviderId,
        label: String,
        why: String,
    },
    /// An interrupted switch is waiting that the next change cannot finish, and every change
    /// stops at it until it can be finished or is given up on. The refusal that change would
    /// make, said by a read so that nobody has to make a change to find out.
    SwitchStuck(Error),
    /// This process may change nothing, because it runs as root or under sudo, or nobody
    /// could tell whether it does, so a read answers from what Pitboard last measured: it
    /// renews nothing, asks nobody and writes nothing. `why` is how it runs, as the host
    /// said it, and `None` where the host could not say.
    ReadOnly {
        why: Option<&'static str>,
    },
}

impl Warning {
    /// Stable, for a program to branch on.
    pub fn code(&self) -> &'static str {
        match self {
            Warning::Recovered(r) => r.code(),
            Warning::LockCompromised { .. } => "lock_compromised",
            Warning::ConfigNotUpdated(e) | Warning::RenewalFailed(e) | Warning::SwitchStuck(e) => {
                e.code()
            }
            Warning::ParksPendingRemoval(_) => "parks_pending_removal",
            Warning::ParkedLoginRefused { .. } => "parked_login_refused",
            Warning::AuthOverridden { .. } => "auth_overridden",
            Warning::WrittenOnTheCommandLine { .. } => "written_on_the_command_line",
            Warning::SessionsStillRunning { .. } => "sessions_still_running",
            Warning::SessionsKeepTheOldLogin { .. } => "sessions_keep_old_login",
            Warning::SessionsUnknown { .. } | Warning::SessionsUnknownAfterSignIn { .. } => {
                "sessions_unknown"
            }
            Warning::SignInParkedNotInUse { .. } => "sign_in_parked_not_in_use",
            Warning::ReadOnly { .. } => "read_only",
        }
    }
}

impl fmt::Display for Warning {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Warning::Recovered(r) => write!(f, "{r}"),
            Warning::LockCompromised { tool } => write!(
                f,
                "{} reclaimed the credential write lock while this change was under way, so \
                 it may have written the login at the same time. Pitboard read the slot back \
                 and the change stood, but check with `pitboard` that the right account is \
                 signed in.",
                tool.name()
            ),
            Warning::ConfigNotUpdated(e) | Warning::RenewalFailed(e) | Warning::SwitchStuck(e) => {
                write!(f, "{e}")
            }
            Warning::ParksPendingRemoval(count) => write!(
                f,
                "{count} parked login(s) no longer in use could not be removed yet; Pitboard \
                 tries again on its next change"
            ),
            Warning::ParkedLoginRefused { tool, label } => write!(
                f,
                "{} no longer accepts the parked login for `{label}`. Run `pitboard enroll \
                 {label} --sign-in` to sign in to it again.",
                tool.service()
            ),
            Warning::WrittenOnTheCommandLine { tool, bytes, limit } => {
                write!(
                    f,
                    "this login needs {bytes} bytes and `security` reads {limit} from stdin, \
                     so it was written on the argument line, where a process running as you \
                     could have read it while the call lasted."
                )?;
                if *tool == ProviderId::Claude {
                    write!(
                        f,
                        " Claude Code writes this same login the same way whenever it \
                         refreshes the token."
                    )?;
                }
                Ok(())
            }
            Warning::AuthOverridden { tool, names } => write!(
                f,
                "{} is set, so {} signs in with it and not with the login Pitboard moved. \
                 Unset it for the switch to take effect.",
                names.join(" and "),
                tool.name()
            ),
            Warning::SessionsStillRunning { from, holding } => write!(
                f,
                "{} started before this switch {} still running and still using `{from}`. {} \
                 Do not sign out in {}: signing out there revokes `{from}`'s login, which \
                 Pitboard has just parked.",
                capitalised(&holder::described(holding)),
                if holder::plural(holding) { "are" } else { "is" },
                holder::remedies(holding, "to use the new account"),
                if holder::plural(holding) {
                    "any of them"
                } else {
                    "it"
                },
            ),
            Warning::SessionsKeepTheOldLogin { label, holding } => write!(
                f,
                "{} started before this sign-in {} still running and still using `{label}`'s \
                 old login. {} Otherwise one of them can put the old login back in place of \
                 the new one when it refreshes its token.",
                capitalised(&holder::described(holding)),
                if holder::plural(holding) { "are" } else { "is" },
                holder::remedies(holding, "to use the new one"),
            ),
            Warning::SessionsUnknown { tool, from } => write!(
                f,
                "Pitboard could not tell whether {} sessions started before this switch are \
                 still running, because it could not read the list of processes. Do not sign \
                 out in one that is: signing out there revokes `{from}`'s login, which \
                 Pitboard has just parked.",
                tool.name()
            ),
            Warning::SessionsUnknownAfterSignIn { tool, label } => write!(
                f,
                "Pitboard could not tell whether {} sessions started before this sign-in are \
                 still running, because it could not read the list of processes. Quit any \
                 that are still using `{label}`'s old login and start them again. Otherwise \
                 one of them can put the old login back in place of the new one when it \
                 refreshes its token.",
                tool.name()
            ),
            Warning::SignInParkedNotInUse { tool, label, why } => write!(
                f,
                "{} goes on with the login it has: Pitboard could not tell whose it is \
                 ({why}), so it parked the new login for `{label}` rather than write over \
                 that one. If that login no longer works, run `{}` and sign in to `{label}` \
                 there.",
                tool.name(),
                tool.login_command()
            ),
            Warning::ReadOnly { why } => write!(
                f,
                "{}, so it changes nothing: these are the numbers it last measured, and it \
                 renews no parked login and asks nobody. Run it as yourself to ask again.",
                match why {
                    Some(why) => format!("Pitboard runs {why}"),
                    None => "Pitboard cannot tell whether it runs as root or with sudo".into(),
                }
            ),
        }
    }
}

#[derive(Debug)]
pub struct Done<T> {
    pub value: T,
    pub warnings: Vec<Warning>,
}

/// A change that failed, with what was found on the way: recovering an interrupted switch
/// is reported even when the change that followed it fails.
#[derive(Debug)]
pub struct Failed {
    pub error: Error,
    pub warnings: Vec<Warning>,
}

pub type Changing<T> = std::result::Result<Done<T>, Failed>;

pub struct Pitboard {
    ctx: Context,
}

impl Pitboard {
    pub fn new(ctx: Context) -> Pitboard {
        Pitboard { ctx }
    }

    /// Whether this process may change anything here, as the one gate every change passes
    /// says, with the proof it hands out where it may. Every change below asks it first,
    /// before it reads, locks or records anything, so a change refused here leaves the
    /// Pitboard directory, the stores of logins and the scheduler exactly as they were, the
    /// audit log included. A front end asks it too before it writes a file of its own
    /// through [`crate::app::write_file`], or before it asks a question whose answer could
    /// only be refused.
    pub fn permit(&self) -> Result<Permit> {
        gate(&self.ctx)
    }

    /// Whether every home the environment names is a full path, as the gate and every read
    /// of the accounts ask. A front end asks it before anything else that reads under one,
    /// such as the audit log, the schedule's file or the status line's session records, so
    /// a home that is empty or relative is refused there too, never read as the folder the
    /// front end runs in.
    pub fn check_homes(&self) -> Result<()> {
        crate::home::check_absolute(&self.ctx)
    }

    /// The gate's answer as the refusal of a change, which has found nothing on the way.
    fn permitted(&self) -> std::result::Result<Permit, Failed> {
        self.permit().map_err(|error| Failed {
            error,
            warnings: Vec::new(),
        })
    }

    /// Who is signed in and what every account has left. Parked logins whose access has
    /// lapsed are renewed first, so every account is asked live.
    ///
    /// `fresh` asks Anthropic about every account whatever was asked recently. Ordinarily
    /// false: a number is only asked for again once the tightest limit it describes could
    /// have moved by a percentage point, which collapses several front ends on one machine
    /// to one request per account per few minutes.
    ///
    /// An interrupted switch the next change cannot finish is said as that change would
    /// refuse over it, and nothing is done about it: every change stops at it until it can
    /// be finished or is given up on, and a front end that waited for a change to be
    /// refused could not offer to give up on it until then. One the next change finishes by
    /// itself is not said. Nobody has anything to do about it: the rows already say who is
    /// signed in from each tool's login rather than from Pitboard's record, and the change
    /// that finishes it says what it found.
    ///
    /// Where this process may change nothing, it answers what [`status_offline`] answers,
    /// with a `read_only` warning that says why: renewing a parked login rotates its refresh
    /// token, a live read records what it measured, and neither may happen then.
    ///
    /// [`status_offline`]: Pitboard::status_offline
    pub fn status(&self, fresh: bool) -> Result<Done<status::Report>> {
        let permit = match self.permit() {
            Ok(permit) => permit,
            Err(Error::Elevated { why }) => {
                let mut read = self.status_offline()?;
                read.warnings.push(Warning::ReadOnly { why });
                return Ok(read);
            }
            Err(other) => return Err(other),
        };
        let renewed = switch::renew_parked(&self.ctx, permit);
        // Unreadable is not the same as empty: reporting it as empty would say the enrolled
        // logins are gone.
        let state = state::load(&self.ctx)?;
        // Alongside the report rather than before it. Where only the service can say whose
        // the live login is, both ask it, and asked one after the other, a service that did
        // not answer held the read for its timeout twice.
        let (stuck, report) = std::thread::scope(|scope| {
            let stuck = scope.spawn(|| switch::stuck(&self.ctx, &state, switch::Asking::Service));
            let report = status::gather(&self.ctx, permit, &state, fresh);
            (stuck.join().ok().flatten(), report)
        });
        let mut warnings: Vec<Warning> = stuck.map(Warning::SwitchStuck).into_iter().collect();
        for (key, outcome) in renewed {
            audit::record(&self.ctx, permit, "renew", &key.typed(), outcome.code());
            match outcome {
                Renewal::Refused => warnings.push(Warning::ParkedLoginRefused {
                    tool: key.provider,
                    label: state.typed(&key),
                }),
                Renewal::Failed(e) => warnings.push(Warning::RenewalFailed(e)),
                Renewal::Renewed | Renewal::Deferred => {}
            }
        }
        Ok(Done {
            value: report,
            warnings,
        })
    }

    pub fn doctor(&self) -> Diagnosis {
        doctor::run(&self.ctx)
    }

    /// The same report without asking anyone: the last numbers Pitboard measured, and who
    /// each tool's own files say is signed in. Nothing is renewed and nothing is asked, so
    /// it answers at once wherever there is no network.
    ///
    /// An interrupted switch the next change cannot finish is said here too, as [`status`]
    /// says it, wherever that can be told without a request: a Claude Code login renewed
    /// since the switch stopped is one only Anthropic can say whose it is, and then nothing
    /// is said. Telling reads the tool's login and the copy the switch parked, which on
    /// macOS are keychain items, and only while a switch is waiting: otherwise one look at
    /// whether its record is there is the whole of it.
    ///
    /// [`status`]: Pitboard::status
    pub fn status_offline(&self) -> Result<Done<status::Report>> {
        let state = state::load(&self.ctx)?;
        let warnings = switch::stuck(&self.ctx, &state, switch::Asking::Nobody)
            .map(Warning::SwitchStuck)
            .into_iter()
            .collect();
        Ok(Done {
            value: status::gather_offline(&self.ctx, &state),
            warnings,
        })
    }

    /// The status line for Claude Code's session JSON. Reads only files, and writes only
    /// Pitboard's own: what the session passed, for its next run to compare with, and the
    /// usage readings, which keep what moved since its last run where it is newer. Where
    /// this process may change nothing it writes neither, and draws the line from the files
    /// as they are.
    pub fn statusline(&self, session: &str) -> statusline::StatusLine {
        statusline::read(&self.ctx, self.permit().ok(), session)
    }

    /// The enrolled account under `typed`, if any, read without taking the lock.
    pub fn account(&self, typed: &str) -> Option<Account> {
        let state = state::load(&self.ctx).ok()?;
        crate::label::resolve(&state, typed).ok().cloned()
    }

    pub fn switch_to(&self, typed: &str) -> Changing<Outcome> {
        let permit = self.permitted()?;
        let key = self.named(permit, "use", typed)?;
        self.changing(permit, "use", &key.typed(), Some(key.provider), |settled| {
            switch::switch(settled, &key)
        })
    }

    /// Switches Claude Code by itself where a limit of the account in use has reached
    /// `threshold` and another account has room, as [`crate::autoswitch`] says. For a front
    /// end somebody asked to do that: the app with its setting on, or `pitboard watch`.
    ///
    /// Looks first from files alone, so a look that finds nothing to do takes no lock, asks
    /// nobody and records nothing. A switch is decided again under the lock, and is recorded
    /// in the audit log as `auto-switch`, with what it came to; nothing else here is.
    pub fn auto_switch(
        &self,
        threshold: crate::autoswitch::Threshold,
    ) -> Changing<crate::autoswitch::Auto> {
        let permit = self.permitted()?;
        let state = state::load(&self.ctx).map_err(|error| Failed {
            error,
            warnings: Vec::new(),
        })?;
        let plan = match crate::autoswitch::look(&self.ctx, &state, threshold) {
            crate::autoswitch::Next::Say(auto) => {
                return Ok(Done {
                    value: auto,
                    warnings: Vec::new(),
                });
            }
            crate::autoswitch::Next::Switch(plan) => plan,
        };
        let subject = state.typed(&plan.to);
        self.changing(
            permit,
            "auto-switch",
            &subject,
            Some(ProviderId::Claude),
            |settled| switch::automatically(settled, &plan, threshold),
        )
    }

    /// Which account somebody meant, as the key the engine looks accounts up by.
    ///
    /// Resolving here rather than deeper down means every command takes `codex/work` and
    /// a bare `work` on the same terms, and the one place that decides what an ambiguous
    /// bare label does is the one place that knows every provider's accounts.
    fn named(&self, permit: Permit, verb: &str, typed: &str) -> std::result::Result<Key, Failed> {
        let state = state::load(&self.ctx).map_err(|error| Failed {
            error,
            warnings: Vec::new(),
        })?;
        crate::label::resolve(&state, typed)
            .map(Account::key)
            .map_err(|error| self.refused(permit, verb, typed, error.code(), error))
    }

    /// `typed` may name a tool, as in `claude/work`. A bare name means the default tool.
    pub fn enroll_current(&self, typed: &str) -> Changing<Enrolled> {
        let permit = self.permitted()?;
        let key = self.chosen(permit, "enroll", typed)?;
        self.changing(
            permit,
            "enroll",
            &key.typed(),
            Some(key.provider),
            |settled| switch::enroll(settled, &key, None),
        )
    }

    /// Which tool a new account is for, and what it is called there.
    ///
    /// Split here rather than deeper down so nothing below ever sees a name with a tool
    /// still stuck to the front of it, which would enrol an account literally called
    /// `claude/work`.
    fn chosen(&self, permit: Permit, verb: &str, typed: &str) -> std::result::Result<Key, Failed> {
        self.enrolling(typed)
            .map_err(|error| self.refused(permit, verb, typed, "label_unusable", error))
    }

    /// A change refused over the name it was given, which happens before it settles.
    ///
    /// A mistyped name takes no lock and writes nothing but its line in the audit log. But
    /// every change settles an interrupted switch first, and one refused here would leave
    /// that switch for whatever runs next and say nothing about it. So where a switch was
    /// interrupted, this settles for the tool that switch was of, which a custom OAuth
    /// endpoint allows or refuses exactly as it would a change to that tool, and reports what
    /// it found beside the refusal. Only as far as it can: a recovery that cannot finish is
    /// the next change's to report, and what this one reports is why it was refused.
    fn refused(
        &self,
        permit: Permit,
        verb: &str,
        subject: &str,
        code: &str,
        error: Error,
    ) -> Failed {
        let recovered = if switch::interrupted(&self.ctx) {
            switch::settle(&self.ctx, permit, switch::interrupted_tool(&self.ctx))
                .ok()
                .and_then(|(_, recovered)| recovered)
        } else {
            None
        };
        let mut warnings = Vec::new();
        if let Some(r) = recovered {
            audit::record(&self.ctx, permit, "recover", &r.to, r.code());
            warnings.push(Warning::Recovered(r));
        }
        audit::record(&self.ctx, permit, verb, subject, code);
        Failed { error, warnings }
    }

    /// The account `pitboard enroll <typed>` is about: the one already enrolled under that
    /// exact name, or a new one of the tool the name says.
    ///
    /// A label written by 0.1.x could contain a slash, which a new name cannot, and signing
    /// in to such an account again is exactly what every message about a lapsed park tells
    /// somebody to do. So an existing account is found by its whole name first.
    fn enrolling(&self, typed: &str) -> Result<Key> {
        if typed.contains(crate::label::SEPARATOR)
            && let Ok(state) = state::load(&self.ctx)
            && let Some(existing) = state.accounts.iter().find(|a| a.label == typed)
        {
            return Ok(existing.key());
        }
        crate::label::choose(typed)
            .map(|chosen| Key::new(chosen.provider, chosen.label))
            .map_err(Error::Usage)
    }

    /// The enrolled account `pitboard enroll <typed>` would sign in to again, if it names
    /// one, for saying whose login to sign in with before a browser opens.
    pub fn account_to_enroll(&self, typed: &str) -> Option<Account> {
        let key = self.enrolling(typed).ok()?;
        state::load(&self.ctx).ok()?.get(&key).cloned()
    }

    /// What to type to name the account `pitboard enroll <typed>` is about, on this
    /// machine: bare where that names it alone, qualified where another tool shares it.
    pub fn name_to_type(&self, typed: &str) -> String {
        let Ok(key) = self.enrolling(typed) else {
            return typed.to_string();
        };
        state::load(&self.ctx).map_or_else(|_| key.typed(), |state| state.typed(&key))
    }

    /// The tool's own sign-in in a private directory, for the tool `typed` names. It takes
    /// no lock but its own, so a person taking their time in a browser never holds up a
    /// switch.
    pub fn sign_in(&self, typed: &str) -> std::result::Result<SignIn, Failed> {
        let permit = self.permitted()?;
        let key = self.signing_in(permit, typed)?;
        switch::sign_in(&self.ctx, permit, key.provider)
            .map_err(|error| self.not_started(permit, typed, error))
    }

    /// The same sign-in with its output piped, for a front end that has no terminal to
    /// hand over. The caller shows what the tool says and can type a code back.
    pub fn sign_in_watched(
        &self,
        typed: &str,
    ) -> std::result::Result<switch::WatchedSignIn, Failed> {
        let permit = self.permitted()?;
        let key = self.signing_in(permit, typed)?;
        switch::sign_in_watched_as(&self.ctx, permit, &key)
            .map_err(|error| self.not_started(permit, typed, error))
    }

    /// Which account a sign-in is for, once everything that could refuse it has been asked.
    ///
    /// A name no account could have is refused the way every change refuses one, settling
    /// an interrupted switch on the way; anything else refused here is recorded and nothing
    /// more, since nothing was about to change.
    fn signing_in(&self, permit: Permit, typed: &str) -> std::result::Result<Key, Failed> {
        let key = self.chosen(permit, "enroll", typed)?;
        self.ready_to_sign_in(key.provider)
            .map_err(|error| self.not_started(permit, typed, error))?;
        Ok(key)
    }

    /// A sign-in that did not start, or did not finish, for a reason other than its name.
    fn not_started(&self, permit: Permit, typed: &str, error: Error) -> Failed {
        audit::record(&self.ctx, permit, "enroll", typed, error.code());
        Failed {
            error,
            warnings: Vec::new(),
        }
    }

    /// Checked before a sign-in starts, so a person does not sign in through a browser
    /// only to be told the state file belongs to another machine, that the tool is not
    /// installed, or that the account could never be switched to afterwards.
    fn ready_to_sign_in(&self, tool: crate::provider::ProviderId) -> Result<()> {
        if tool == crate::provider::ProviderId::Claude && self.ctx.custom_oauth() {
            return Err(Error::CustomOauthEndpoint);
        }
        state::load(&self.ctx)?;
        let driver = crate::provider::of(tool);
        // An account signed in here is one to switch to later, which needs a live store
        // Pitboard can write. Asked now rather than after a browser round trip.
        switch::live_store(&self.ctx, tool)?;
        // A private sign-in works by pointing the tool's own login at a scratch directory
        // through its home variable. Where that does not really isolate it, running one
        // would write over the login somebody is using, and there is no override: forcing
        // past "this could touch your live login" is what the rule exists to prevent.
        if let crate::provider::Isolation::NotIsolated { reason } =
            driver.private_signin_isolation(&self.ctx)
        {
            return Err(Error::SignInNotIsolated { reason });
        }
        if driver.program(&self.ctx).is_none() {
            return Err(Error::ProgramMissing {
                tool,
                program: self.ctx.program_for(tool).display().to_string(),
            });
        }
        Ok(())
    }

    pub fn enroll_signed_in(&self, typed: &str, login: SignIn) -> Changing<Enrolled> {
        let permit = self.permitted()?;
        let key = self.chosen(permit, "enroll", typed)?;
        self.changing(
            permit,
            "enroll",
            &key.typed(),
            Some(key.provider),
            |settled| switch::enroll(settled, &key, Some(login)),
        )
    }

    /// Returns the account's email.
    pub fn forget(&self, typed: &str) -> Changing<String> {
        let permit = self.permitted()?;
        let key = self.named(permit, "forget", typed)?;
        self.changing(
            permit,
            "forget",
            &key.typed(),
            Some(key.provider),
            |settled| switch::forget(settled, &key),
        )
    }

    /// Throws away a record of an interrupted switch that cannot be finished, keeping
    /// every login it names. The way out when recovery cannot reach Anthropic.
    pub fn abandon_recovery(&self) -> Result<Option<switch::Abandoned>> {
        let permit = self.permit()?;
        let outcome = switch::abandon(&self.ctx, permit);
        audit::record(
            &self.ctx,
            permit,
            "abandon",
            "",
            match &outcome {
                Ok(_) => "ok",
                Err(e) => e.code(),
            },
        );
        outcome
    }

    /// Renew every parked login that is due, and nothing else. No switch, no usage, and
    /// no request but the token exchange. This is what the schedule runs.
    ///
    /// Refused where this process may change nothing, as every change is, so a run that
    /// renewed nothing for that reason says so rather than reading as one where nothing was
    /// due.
    ///
    /// A run the schedule started renews the default home, whatever `PITBOARD_HOME` says
    /// ([`schedule::for_its_run`]): the schedule is that home's alone.
    pub fn renew(&self) -> Result<Vec<(Key, Renewal)>> {
        let ctx = schedule::for_its_run(&self.ctx);
        let permit = gate(&ctx)?;
        let outcomes = switch::renew_due(&ctx, permit, switch::Due::ToStayAlive);
        for (key, outcome) in &outcomes {
            audit::record(&ctx, permit, "renew", &key.typed(), outcome.code());
        }
        Ok(outcomes)
    }

    /// Whether anything is keeping parked logins alive on this machine without somebody
    /// running a command.
    pub fn schedule(&self) -> schedule::Installed {
        schedule::status(&self.ctx)
    }

    /// Whether the schedule renews this Pitboard's own parked logins: whether its home is
    /// the default home, `~/.pitboard`, compared as a path. The schedule renews that home
    /// alone, and `schedule_install` is refused from any other.
    pub fn schedule_renews_this_home(&self) -> bool {
        schedule::serves(&self.ctx)
    }

    /// Ask the platform's own scheduler to run `renew` daily. Opt-in, and stays opt-in.
    /// Refused with `schedule_not_default_home` where this is not the default home
    /// ([`Pitboard::schedule_renews_this_home`]).
    pub fn schedule_install(&self) -> Result<std::path::PathBuf> {
        schedule::install(&self.ctx, self.permit()?)
    }

    /// Take it away. `false` when there was nothing installed.
    pub fn schedule_uninstall(&self) -> Result<bool> {
        schedule::uninstall(&self.ctx, self.permit()?)
    }

    /// Point a schedule an app up to 0.3.0 wrote, which runs the app itself, at the command
    /// line this context names. `true` when it did; nothing changes otherwise.
    pub fn schedule_repair(&self) -> Result<bool> {
        schedule::repair(&self.ctx, self.permit()?)
    }

    /// Take over a Pitboard directory another machine wrote: keep the accounts, drop the
    /// logins that came with them. `None` when the directory was already this machine's.
    ///
    /// The one change that does not settle first, because a stamp from elsewhere is what
    /// stops settling. Everything after it settles normally.
    pub fn adopt(&self) -> Result<Option<switch::Adopted>> {
        switch::adopt(&self.ctx, self.permit()?)
    }

    /// Ask the credential store what parked logins are on this machine, and give back or
    /// delete every one Pitboard's own records do not name. Ordinarily there is nothing to
    /// do: every change resolves the names it wrote down. This is for a machine whose state
    /// file was lost or restored from a backup, where the store is the only record left.
    pub fn repair(&self) -> Changing<switch::Reclaimed> {
        let permit = self.permitted()?;
        self.changing(permit, "repair", "", None, |settled| {
            switch::repair(settled).map(|r| (r, Vec::new()))
        })
    }

    /// What is running `which`'s tool with a login in memory that a switch would leave it
    /// on, by kind: for a front end to say so, or to offer to quit an app, before switching.
    /// Empty where nothing is, where the tool follows a switch by itself, or where nobody
    /// could tell. Reads the process list and nothing else.
    pub fn holding(&self, which: ProviderId) -> Vec<holder::Holding> {
        match switch::still_holding(&self.ctx, which) {
            switch::StillHolding::These(holding) => holding,
            switch::StillHolding::Nothing | switch::StillHolding::Unknown => Vec::new(),
        }
    }

    /// When Pitboard's account index last changed, for a front end that wants to know
    /// whether another one has done something without asking Anthropic about it.
    pub fn changed_at(&self) -> i64 {
        state::changed_at(&self.ctx)
    }

    /// When Pitboard's usage readings last changed, in epoch milliseconds, for a front end
    /// that shows them to follow what the others record without asking anyone.
    pub fn readings_changed_at(&self) -> i64 {
        readings::changed_at(&self.ctx)
    }

    /// What the app keeps in `file` in Pitboard's directory, or `None` where it keeps nothing
    /// there. One that is there and cannot be read is an error.
    pub fn app_file(&self, file: crate::app::AppFile) -> std::io::Result<Option<String>> {
        crate::app::read_app_file(&self.ctx, file)
    }

    /// Keeps `body` in the app's `file` in Pitboard's directory, private and whole, as the
    /// core writes its own files.
    pub fn keep_app_file(&self, file: crate::app::AppFile, body: &str) -> Result<()> {
        crate::app::write_app_file(&self.ctx, self.permit()?, file, body)
    }

    /// The changes Pitboard has made, newest last.
    pub fn log(&self, limit: usize) -> Vec<audit::Entry> {
        audit::read(&self.ctx, limit)
    }

    /// Takes away the daily renewal schedule, deletes every parked login this Pitboard
    /// wrote, and removes Pitboard's own directory. Each tool's login is left alone: whoever
    /// is signed in stays signed in.
    pub fn uninstall(&self) -> Changing<switch::Removed> {
        let permit = self.permitted()?;
        self.changing(permit, "uninstall", "", None, |settled| {
            switch::uninstall(settled).map(|r| (r, Vec::new()))
        })
    }

    /// Returns the account's email.
    /// `from` may be qualified; `to` is a plain name, and stays inside whichever provider
    /// the account already belongs to. Renaming cannot move an account between tools.
    pub fn rename(&self, from: &str, to: &str) -> Changing<String> {
        let permit = self.permitted()?;
        let from = self.named(permit, "rename", from)?;
        let chosen = self.chosen(permit, "rename", to)?;
        // Only a prefix somebody actually typed can disagree: a bare new name stays inside
        // the account's own tool whatever tool a bare name would mean for a new account.
        if to.contains(crate::label::SEPARATOR) && chosen.provider != from.provider {
            let error = Error::Usage(format!(
                "`{from}` is a {} account, and a rename cannot move it to {}. Sign in to that \
                 tool and enrol the account there instead.",
                from.provider, chosen.provider
            ));
            return Err(self.refused(permit, "rename", &from.typed(), error.code(), error));
        }
        let to = chosen.label;
        self.changing(
            permit,
            "rename",
            &format!("{from} -> {to}"),
            Some(from.provider),
            |settled| switch::rename(settled, &from, &to).map(|email| (email, Vec::new())),
        )
    }

    /// Settles, runs the change, and records it in the audit log.
    ///
    /// `tool` is the tool whose login the change is about, where it is about one: its own
    /// ways of being signed in by something else are what is worth warning about, and a
    /// refusal that is one tool's business does not stop a change to another's.
    fn changing<T: Audited>(
        &self,
        permit: Permit,
        verb: &str,
        subject: &str,
        tool: Option<ProviderId>,
        run: impl FnOnce(Settled) -> Result<(T, Vec<Warning>)>,
    ) -> Changing<T> {
        let (settled, recovered) = switch::settle(&self.ctx, permit, tool).map_err(|error| {
            audit::record(&self.ctx, permit, verb, subject, error.code());
            Failed {
                error,
                warnings: Vec::new(),
            }
        })?;
        let mut warnings = Vec::new();
        // Read from files as well as from this process's environment, so the app, which
        // has no shell environment at all, gets the same answer as the command line.
        if let Some(tool) = tool {
            let names = crate::provider::of(tool).overridden_by(&self.ctx);
            if !names.is_empty() {
                warnings.push(Warning::AuthOverridden { tool, names });
            }
        }
        if let Some(r) = recovered {
            audit::record(&self.ctx, permit, "recover", &r.to, r.code());
            warnings.push(Warning::Recovered(r));
        }
        match run(settled) {
            Ok((value, more)) => {
                if value.recorded() {
                    audit::record(&self.ctx, permit, verb, subject, value.audit_code());
                }
                warnings.extend(more);
                Ok(Done { value, warnings })
            }
            Err(mut error) => {
                audit::record(&self.ctx, permit, verb, subject, error.code());
                warnings.extend(error.take_warnings());
                Err(Failed { error, warnings })
            }
        }
    }
}

/// How a successful change is written in the audit log.
trait Audited {
    fn audit_code(&self) -> &'static str {
        "ok"
    }

    /// Whether it changed anything worth a line. A change that found, once it held the lock,
    /// that there was nothing to do, did nothing.
    fn recorded(&self) -> bool {
        true
    }
}

impl Audited for crate::autoswitch::Auto {
    fn recorded(&self) -> bool {
        matches!(self, crate::autoswitch::Auto::Switched { .. })
    }
}

impl Audited for Outcome {
    fn audit_code(&self) -> &'static str {
        match self {
            Outcome::Switched { .. } => "ok",
            Outcome::AlreadyActive { .. } => "already_active",
        }
    }
}

impl Audited for switch::Reclaimed {}
impl Audited for Enrolled {}
impl Audited for String {}

impl Audited for switch::Removed {
    fn audit_code(&self) -> &'static str {
        if self.pending > 0 {
            "parks_pending_removal"
        } else {
            "ok"
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::switch::harness::{Machine, codex_machine, hold, machine};
    use std::collections::BTreeMap;
    use std::sync::Arc;

    type Make = fn(&str) -> Machine;

    /// A name is refused the same way whichever tool it is for.
    const MACHINES: [(&str, Make); 2] = [("claude", machine), ("codex", codex_machine)];

    type Refuse = fn(&Pitboard, ProviderId) -> Option<Failed>;

    /// Every way a change is refused over the name it was given, with the verb the audit
    /// log records it under, the code it is refused with and the one the log records: a
    /// name nobody enrolled, a name no account could have, whether the account signed in
    /// now is being enrolled or one is being signed in to, and a new name that would move
    /// an account to another tool.
    const REFUSALS: [(&str, &str, &str, &str, Refuse); 4] = [
        (
            "use",
            "use",
            "account_unknown",
            "account_unknown",
            |p, _| p.switch_to("nobody").err(),
        ),
        ("enroll", "enroll", "usage", "label_unusable", |p, _| {
            p.enroll_current("codx/work").err()
        }),
        ("sign-in", "enroll", "usage", "label_unusable", |p, _| {
            p.sign_in("codx/work").err()
        }),
        ("rename", "rename", "usage", "usage", |p, tool| {
            let other = if tool == ProviderId::Claude {
                ProviderId::Codex
            } else {
                ProviderId::Claude
            };
            p.rename(
                &Key::new(tool, "here").qualified(),
                &Key::new(other, "moved").qualified(),
            )
            .err()
        }),
    ];

    /// A switch from `here` to `there` killed after parking `here` and before installing
    /// `there`, so its record is all that says it happened.
    fn interrupted(make: Make, name: &str) -> Machine {
        let m = make(name);
        let settled = switch::settle(&m.ctx, Permit::for_a_test(), None)
            .expect("nothing to recover yet")
            .0;
        let died = crate::fault::killing("switch.park_recorded", || {
            switch::switch(settled, &m.key("there"))
        });
        assert_eq!(died.unwrap_err(), "switch.park_recorded");
        assert!(switch::interrupted(&m.ctx));
        m
    }

    /// The same switch, which the next change cannot finish: nothing is signed in to the
    /// tool any more, so nothing says which side of the switch won. Told apart without
    /// asking anyone, for either tool.
    fn stuck(make: Make, name: &str) -> Machine {
        let m = interrupted(make, name);
        m.fault_live(crate::store::memory::Fault::Vanish);
        m
    }

    /// The switch interrupted on a Claude Code machine, which the next change cannot finish
    /// either, though only Anthropic could tell: Claude Code has since renewed the login, so
    /// it matches neither side the record kept, and its session has expired, so Anthropic
    /// will not say whose it is. An access token the scripted service does not know is one
    /// it refuses.
    fn stuck_unless_asked(name: &str) -> Machine {
        let m = interrupted(machine, name);
        m.sign_in(&crate::switch::harness::document("renewed-since"));
        m
    }

    /// The warnings a read gives, by code and words.
    fn said(read: &Done<status::Report>) -> Vec<(&'static str, String)> {
        read.warnings
            .iter()
            .map(|w| (w.code(), w.to_string()))
            .collect()
    }

    /// Everything a read must leave as it found it: Pitboard's files but the records a
    /// live read keeps by design (what it measured, the history its runways are worked out
    /// from, and when to ask again), every parked login and the live one.
    type Untouched = (
        BTreeMap<String, Vec<u8>>,
        Vec<(String, Option<String>)>,
        Option<serde_json::Value>,
    );

    fn untouched(m: &Machine) -> Untouched {
        let kept_by_a_read = ["usage.json", "usage.lock", "readings", "asking.json"];
        let mut files = files(m);
        files.retain(|path, _| !kept_by_a_read.iter().any(|kept| path.ends_with(kept)));
        let vault = m.mem.vault();
        let parked = vault
            .services()
            .into_iter()
            .map(|service| {
                let held = vault.peek(&service);
                (service, held)
            })
            .collect();
        (files, parked, m.live())
    }

    /// A switch nothing can finish was said only by a change refused over it. The app looks
    /// for it in what a read says, so it never offered to give up on one, and `pitboard
    /// status` never said it at all. A read says it now, in the words of the refusal, and
    /// changes nothing: the record is kept for whatever finishes it or gives up on it.
    #[test]
    fn a_read_says_an_interrupted_switch_it_cannot_finish_is_waiting() {
        for (tool, make) in MACHINES {
            let m = stuck(make, &format!("read-stuck-{tool}"));
            let pitboard = Pitboard::new(m.ctx.clone());
            let before = untouched(&m);

            let read = pitboard
                .status(false)
                .expect("a read is not refused over it");

            assert_eq!(untouched(&m), before, "{tool}: a read changes nothing");
            assert!(switch::interrupted(&m.ctx), "{tool}: the record is kept");
            let refused = pitboard
                .switch_to(&m.key("there").typed())
                .expect_err("every change stops at it");
            assert_eq!(refused.error.code(), "recovery_undetermined", "{tool}");
            assert_eq!(
                said(&read),
                [("recovery_undetermined", refused.error.to_string())],
                "{tool}: said in the refusal's own words"
            );
        }
    }

    /// Where only the service can say whose the live login is, a read asks it, as the next
    /// change would.
    #[test]
    fn a_read_asks_whose_the_login_is_where_only_the_service_can_say() {
        let m = stuck_unless_asked("read-stuck-asked");
        let pitboard = Pitboard::new(m.ctx.clone());
        let before = untouched(&m);

        let read = pitboard.status(false).expect("a read");

        assert_eq!(untouched(&m), before, "a read changes nothing");
        let refused = pitboard.switch_to("there").expect_err("it stops at it");
        assert_eq!(
            said(&read),
            [("recovery_undetermined", refused.error.to_string())]
        );
        assert!(
            refused.error.to_string().contains("has expired"),
            "{}",
            refused.error
        );
    }

    /// A switch the next change finishes by itself is not one anybody has to do anything
    /// about. The rows already say who is signed in, from the tool's login and not from
    /// Pitboard's record, and the change that finishes it says what it found.
    #[test]
    fn a_read_says_nothing_of_a_switch_the_next_change_finishes() {
        for (tool, make) in MACHINES {
            let m = interrupted(make, &format!("read-settles-{tool}"));
            let before = untouched(&m);

            let read = Pitboard::new(m.ctx.clone()).status(false).expect("a read");

            assert_eq!(said(&read), [], "{tool}");
            assert_eq!(untouched(&m), before, "{tool}: a read finishes nothing");
            assert!(switch::interrupted(&m.ctx), "{tool}");
        }
    }

    /// The read never says a switch is waiting that the next change would not stop at for
    /// that reason, and never offers to give up on one that giving up cannot reach. Under a
    /// custom Claude Code endpoint every change is refused over the endpoint before it comes
    /// to a Claude Code switch, and giving up on one is refused too. A Codex switch is
    /// settled under one as anywhere else, and given up on as anywhere else: giving up
    /// refused it, so the read offered a way out that could not be taken.
    #[test]
    fn a_read_says_a_switch_is_waiting_only_where_a_change_would_stop_at_it() {
        for (tool, make) in MACHINES {
            let m = stuck(make, &format!("read-stuck-custom-{tool}"));
            let mut ctx = m.ctx.clone();
            ctx.custom_oauth = true;
            let pitboard = Pitboard::new(ctx);

            let read = pitboard.status(false).expect("a read");
            let known = pitboard.status_offline().expect("a read");
            let refused = pitboard
                .switch_to(&m.key("there").typed())
                .expect_err("refused");

            let codes: Vec<&str> = read.warnings.iter().map(Warning::code).collect();
            let expected: &[&str] = match m.which {
                ProviderId::Claude => &[],
                ProviderId::Codex => &["recovery_undetermined"],
            };
            assert_eq!(codes, expected, "{tool}: {}", refused.error);
            let codes: Vec<&str> = known.warnings.iter().map(Warning::code).collect();
            assert_eq!(codes, expected, "{tool}: the read that asks nobody too");
            assert_eq!(
                refused.error.code() == "recovery_undetermined",
                !expected.is_empty(),
                "{tool}"
            );

            let gave_up = pitboard.abandon_recovery();
            match m.which {
                ProviderId::Claude => assert_eq!(
                    gave_up.expect_err("refused").code(),
                    "custom_oauth_endpoint",
                    "{tool}"
                ),
                ProviderId::Codex => {
                    assert!(gave_up.expect("given up").is_some(), "{tool}");
                    assert!(!switch::interrupted(&m.ctx), "{tool}: nothing waits");
                }
            }
        }
    }

    /// Every read says it, the one that asks nobody too: what an app reads each time the
    /// account index moves, and what `pitboard status --offline` prints. It sends no request,
    /// so it says it wherever the record and the logins tell it without one, in the words of
    /// the refusal, and changes nothing. Where only Anthropic could say whose the login is,
    /// it does not say what it cannot know.
    #[test]
    fn a_read_that_asks_nobody_says_a_switch_is_waiting_wherever_it_can_tell() {
        for (tool, make) in MACHINES {
            let m = stuck(make, &format!("known-stuck-{tool}"));
            let pitboard = Pitboard::new(m.ctx.clone());
            let (before, asked) = (untouched(&m), m.api.calls());

            let read = pitboard.status_offline().expect("a read");

            assert_eq!(untouched(&m), before, "{tool}: a read changes nothing");
            assert_eq!(m.api.calls(), asked, "{tool}: and asks nobody");
            assert!(switch::interrupted(&m.ctx), "{tool}: the record is kept");
            let refused = pitboard
                .switch_to(&m.key("there").typed())
                .expect_err("every change stops at it");
            assert_eq!(
                said(&read),
                [("recovery_undetermined", refused.error.to_string())],
                "{tool}"
            );
        }

        let m = stuck_unless_asked("known-stuck-unasked");
        let asked = m.api.calls();
        let read = Pitboard::new(m.ctx.clone())
            .status_offline()
            .expect("a read");
        assert_eq!(m.api.calls(), asked, "asks nobody");
        assert_eq!(said(&read), [], "only Anthropic could tell");
    }

    /// A tool whose login names its own account is identified from the login, which asks
    /// nobody, so a read that sends no request can still tell whether the next change
    /// finishes its switch. Here Codex has renewed its login since the switch stopped, so the
    /// login matches neither side the record kept, and the copy the switch parked cannot be
    /// read. `doctor` and the read that asks nobody said nothing of it, as though only OpenAI
    /// could say whose the login is.
    #[test]
    fn whose_a_codex_login_is_is_told_without_asking_anyone() {
        let m = interrupted(codex_machine, "codex-renewed-since");
        m.sign_in(&crate::switch::harness::codex_login(
            "here",
            "renewed-since",
        ));
        m.mem.vault().fault(
            &reserved(&m),
            crate::store::memory::Fault::Unreadable("locked".into()),
        );
        let pitboard = Pitboard::new(m.ctx.clone());
        let asked = m.api.calls();

        let read = pitboard.status_offline().expect("a read");
        let checks = pitboard.doctor().checks;

        assert_eq!(m.api.calls(), asked, "asks nobody");
        let refused = pitboard
            .switch_to("codex/there")
            .expect_err("it stops at it");
        assert_eq!(refused.error.code(), "recovery_undetermined");
        assert_eq!(
            said(&read),
            [("recovery_undetermined", refused.error.to_string())]
        );
        let check = checks
            .iter()
            .find(|c| c.code == "interrupted_switch")
            .expect("said");
        assert_eq!(check.detail, refused.error.to_string());
    }

    /// A Codex store that `/etc/codex/requirements.toml` pins is refused before a sign-in
    /// starts, naming that file, as it is for a switch: no line of the person's own changes
    /// it, and the `-c` Pitboard's sign-ins give is under it, so the login would be kept where
    /// Pitboard cannot read it back. Pitboard used to read only `$CODEX_HOME/config.toml`, and
    /// started the sign-in.
    #[test]
    fn a_codex_store_a_requirement_pins_is_refused_before_a_sign_in() {
        let m = codex_machine("codex-pinned");
        // Named where nothing is, so a sign-in that got past the refusal would find no
        // program to run rather than this machine's own `codex`.
        let ctx = m.ctx.clone().with_codex_program("/nowhere/codex".into());
        m.mem.administers(
            "/etc/codex/requirements.toml",
            "cli_auth_credentials_store = \"keyring\"\n",
        );
        let pitboard = Pitboard::new(ctx);
        for refused in [
            pitboard.sign_in("codex/new").err().expect("refused"),
            pitboard
                .sign_in_watched("codex/new")
                .err()
                .expect("refused"),
        ] {
            assert_eq!(refused.error.code(), "live_store_unsupported");
            let said = refused.error.to_string();
            assert!(
                said.contains("pinned to `keyring` by /etc/codex/requirements.toml"),
                "{said}"
            );
            assert!(
                said.contains("No line in your own config.toml can change it"),
                "{said}"
            );
        }
        let switched = pitboard.switch_to("codex/there").expect_err("refused too");
        assert_eq!(switched.error.code(), "live_store_unsupported");
        let file = m
            .mem
            .file_at(crate::provider::codex::paths::auth_file(&m.ctx));
        let kept = crate::store::RawStore::read(&file, "auth.json")
            .expect("readable")
            .expect("there");
        let kept: serde_json::Value = serde_json::from_str(&kept).expect("JSON");
        assert_eq!(
            kept["tokens"]["refresh_token"], "here-refresh",
            "the auth.json Codex does not use is left as it was"
        );
    }

    /// The park the interrupted switch reserved, as its record names it.
    fn reserved(m: &Machine) -> String {
        let raw = std::fs::read_to_string(crate::home::dir(&m.ctx).join("journal.json"))
            .expect("a record");
        serde_json::from_str::<serde_json::Value>(&raw).expect("a record is JSON")["park_service"]
            .as_str()
            .expect("a park")
            .to_owned()
    }

    /// `doctor` sends no request, and says what a read says wherever it can tell without
    /// one: the refusal, and the way out. Where only the service could tell, it says what
    /// it always said, that a switch did not finish.
    #[test]
    fn doctor_says_a_switch_is_stuck_where_it_can_tell_without_asking() {
        for (tool, make) in MACHINES {
            let m = stuck(make, &format!("doctor-stuck-{tool}"));
            let pitboard = Pitboard::new(m.ctx.clone());
            let before = untouched(&m);

            let checks = pitboard.doctor().checks;

            assert_eq!(untouched(&m), before, "{tool}: doctor changes nothing");
            let refused = pitboard
                .switch_to(&m.key("there").typed())
                .expect_err("refused");
            let check = checks
                .iter()
                .find(|c| c.code == "interrupted_switch")
                .expect("said");
            assert_eq!(check.level, doctor::Level::Warn, "{tool}");
            assert_eq!(check.detail, refused.error.to_string(), "{tool}");
            assert!(check.advice.contains("pitboard abandon"), "{tool}");
        }

        let m = stuck_unless_asked("doctor-stuck-unasked");
        let asked = m.api.calls();
        let checks = Pitboard::new(m.ctx.clone()).doctor().checks;
        assert_eq!(m.api.calls(), asked, "doctor asks nobody");
        let check = checks
            .iter()
            .find(|c| c.code == "interrupted_switch")
            .expect("said");
        assert_eq!(check.detail, "a switch did not finish");
    }

    /// Every file in Pitboard's own directory but the audit log.
    fn files(m: &Machine) -> BTreeMap<String, Vec<u8>> {
        std::fs::read_dir(crate::home::dir(&m.ctx))
            .expect("a Pitboard home")
            .map(|entry| entry.expect("an entry").path())
            .filter(|path| path.file_name() != Some("audit.log".as_ref()))
            .map(|path| {
                let body = std::fs::read(&path).unwrap_or_default();
                (path.display().to_string(), body)
            })
            .collect()
    }

    /// The last two lines of the audit log, as verb and outcome.
    fn last_audited(m: &Machine) -> Vec<(String, String)> {
        audit::read(&m.ctx, 2)
            .into_iter()
            .map(|entry| (entry.verb, entry.outcome))
            .collect()
    }

    /// Every other change settles an interrupted switch before anything else, and one
    /// refused over its name did not, so the switch stayed unrecovered and the refusal was
    /// all anybody was told. It is settled now, recorded the way any recovery is, and
    /// reported beside the refusal.
    #[test]
    fn a_change_refused_over_its_name_still_recovers_an_interrupted_switch() {
        for (tool, make) in MACHINES {
            for (change, verb, code, audited, refuse) in REFUSALS {
                let at = format!("{tool}, {change}");
                let m = interrupted(make, &format!("refused-{tool}-{change}"));

                let failed = refuse(&Pitboard::new(m.ctx.clone()), m.which)
                    .unwrap_or_else(|| panic!("{at}: the name must still be refused"));

                assert_eq!(failed.error.code(), code, "{at}: {}", failed.error);
                let said: Vec<&str> = failed.warnings.iter().map(Warning::code).collect();
                assert_eq!(said, ["interrupted_switch_undone"], "{at}");
                assert!(!switch::interrupted(&m.ctx), "{at}: the record is resolved");
                hold(&m, &at);
                assert_eq!(
                    last_audited(&m),
                    [
                        (
                            "recover".to_string(),
                            "interrupted_switch_undone".to_string()
                        ),
                        (verb.to_string(), audited.to_string()),
                    ],
                    "{at}"
                );
            }
        }
    }

    /// A mistyped name with nothing to recover takes no lock and writes nothing but its
    /// line in the audit log.
    #[test]
    fn a_change_refused_over_its_name_with_nothing_interrupted_changes_nothing() {
        for (tool, make) in MACHINES {
            for (change, verb, code, audited, refuse) in REFUSALS {
                let at = format!("{tool}, {change}");
                let m = make(&format!("refused-quietly-{tool}-{change}"));
                let (before, parked, live) = (files(&m), m.mem.vault().services(), m.live());

                let failed = refuse(&Pitboard::new(m.ctx.clone()), m.which)
                    .unwrap_or_else(|| panic!("{at}: the name must still be refused"));

                assert_eq!(failed.error.code(), code, "{at}: {}", failed.error);
                assert!(failed.warnings.is_empty(), "{at}: {:?}", failed.warnings);
                assert_eq!(files(&m), before, "{at}: not even the lock file is made");
                assert_eq!(m.mem.vault().services(), parked, "{at}");
                assert_eq!(m.live(), live, "{at}");
                assert_eq!(
                    last_audited(&m).last(),
                    Some(&(verb.to_string(), audited.to_string())),
                    "{at}"
                );
            }
        }
    }

    /// A new login that did not hold after it was written is parked rather than lost, and
    /// parking a login too big for `security`'s standard input puts it on the argument line.
    /// The change then fails, and that is still said beside the failure.
    #[test]
    fn a_new_login_parked_after_it_did_not_hold_says_how_it_was_parked() {
        for (tool, make) in MACHINES {
            let m = make(&format!("not-installed-said-{tool}"));
            m.mem.vault().takes_on_stdin(64);
            let login = crate::switch::harness::signed_in(&m, "here", "here-refresh-2");
            m.fault_live(crate::store::memory::Fault::DeletedAfterWrite);

            let failed = Pitboard::new(m.ctx.clone())
                .enroll_signed_in(&m.key("here").typed(), login)
                .expect_err("it did not hold");

            assert_eq!(failed.error.code(), "sign_in_not_installed", "{tool}");
            let said: Vec<&str> = failed.warnings.iter().map(Warning::code).collect();
            assert_eq!(said, ["written_on_the_command_line"], "{tool}");
        }
    }

    /// The recovery settles for the tool whose switch was interrupted, not for no tool in
    /// particular, so a custom Claude Code endpoint stops exactly what it stops for any
    /// change: the recovery of a Claude Code switch, and not of a Codex one. What it stops
    /// is left for a later run, and the refusal is reported as it always was.
    #[test]
    fn a_custom_claude_endpoint_stops_only_the_recovery_of_a_claude_code_switch() {
        let codex = interrupted(codex_machine, "refused-custom-codex");
        let mut ctx = codex.ctx.clone();
        ctx.custom_oauth = true;
        let failed = Pitboard::new(ctx).switch_to("nobody").expect_err("refused");
        assert_eq!(failed.error.code(), "account_unknown");
        let said: Vec<&str> = failed.warnings.iter().map(Warning::code).collect();
        assert_eq!(said, ["interrupted_switch_undone"]);
        assert!(!switch::interrupted(&codex.ctx));

        let claude = interrupted(machine, "refused-custom-claude");
        let mut ctx = claude.ctx.clone();
        ctx.custom_oauth = true;
        let failed = Pitboard::new(ctx).switch_to("nobody").expect_err("refused");
        assert_eq!(
            failed.error.code(),
            "account_unknown",
            "the refusal, not the recovery that could not run"
        );
        assert!(failed.warnings.is_empty(), "{:?}", failed.warnings);
        assert!(
            switch::interrupted(&claude.ctx),
            "the record is kept for a run that can finish it"
        );
    }

    /// Every way the host can say this process may change nothing: as root, under sudo,
    /// and with rights nobody could tell.
    const REFUSED_AS: [Elevation; 3] = [
        Elevation::Elevated { why: "as root" },
        Elevation::Elevated { why: "with sudo" },
        Elevation::Unknown,
    ];

    /// What one change came to, as a change refused at the gate is reported: its error,
    /// and the warnings found on the way, of which there must be none.
    fn failed<T>(outcome: Result<T>) -> Option<Failed> {
        outcome.err().map(|error| Failed {
            error,
            warnings: Vec::new(),
        })
    }

    type Change = fn(&Pitboard, &Machine) -> Option<Failed>;

    /// Every change a front end can ask for, by its name. `enroll_signed_in` is asked apart,
    /// since it takes a sign-in made before.
    const CHANGES: [(&str, Change); 15] = [
        ("switch_to", |p, m| {
            p.switch_to(&m.key("there").typed()).err()
        }),
        ("enroll_current", |p, m| {
            p.enroll_current(&m.key("here").typed()).err()
        }),
        ("sign_in", |p, m| p.sign_in(&m.key("new").typed()).err()),
        ("sign_in_watched", |p, m| {
            p.sign_in_watched(&m.key("new").typed()).err()
        }),
        ("forget", |p, m| p.forget(&m.key("there").typed()).err()),
        ("rename", |p, m| {
            p.rename(&m.key("there").typed(), "elsewhere").err()
        }),
        ("abandon_recovery", |p, _| failed(p.abandon_recovery())),
        ("renew", |p, _| failed(p.renew())),
        ("schedule_install", |p, _| failed(p.schedule_install())),
        ("schedule_uninstall", |p, _| failed(p.schedule_uninstall())),
        ("schedule_repair", |p, _| failed(p.schedule_repair())),
        ("adopt", |p, _| failed(p.adopt())),
        ("repair", |p, _| p.repair().err()),
        ("keep_app_file", |p, _| {
            failed(p.keep_app_file(crate::app::AppFile::Preferences, "{}"))
        }),
        ("uninstall", |p, _| p.uninstall().err()),
    ];

    /// Everything on a machine a change could leave different: every directory and file
    /// under its home, the audit log among them and the scheduler's files with them, every
    /// item in its keychain, every login parked and the one in use. The private directory
    /// a sign-in made before is not counted: dropping that sign-in takes it away again.
    type Everything = (
        BTreeMap<String, Option<Vec<u8>>>,
        Vec<(String, Option<String>)>,
        Vec<(String, Option<String>)>,
        Option<serde_json::Value>,
    );

    fn everything(m: &Machine) -> Everything {
        fn walk(dir: &std::path::Path, into: &mut BTreeMap<String, Option<Vec<u8>>>) {
            for entry in std::fs::read_dir(dir).expect("a directory to read") {
                let path = entry.expect("an entry").path();
                if path.ends_with(".pitboard/signin") {
                    continue;
                }
                if path.is_dir() {
                    into.insert(path.display().to_string(), None);
                    walk(&path, into);
                } else {
                    let body = std::fs::read(&path).expect("a file to read");
                    into.insert(path.display().to_string(), Some(body));
                }
            }
        }
        let mut files = BTreeMap::new();
        walk(&m.ctx_home(), &mut files);
        let items = |store: &crate::store::memory::MemoryStore| {
            store
                .services()
                .into_iter()
                .map(|service| {
                    let held = store.peek(&service);
                    (service, held)
                })
                .collect()
        };
        (files, items(m.mem.live()), items(m.mem.vault()), m.live())
    }

    /// Running as root or under sudo, Pitboard changed things as root: a state file, a
    /// schedule or a lock it made was root's, and a park might be, where the person's own
    /// runs might never read or replace it again. Every change is refused now, at one gate, before it
    /// reads, locks or records anything, and leaves the machine byte for byte as it was,
    /// the audit log included. The machine has an interrupted switch waiting, which every
    /// change that settles would otherwise finish, and asks nobody.
    #[test]
    fn every_change_is_refused_where_pitboard_runs_as_root_or_with_sudo_and_changes_nothing() {
        for (tool, make) in MACHINES {
            for elevation in REFUSED_AS {
                for (change, run) in CHANGES {
                    let at = format!("{tool}, {change}, {elevation:?}");
                    let m = interrupted(make, &format!("gate-{tool}-{change}"));
                    m.mem.runs_with(elevation);
                    let (before, asked) = (everything(&m), m.api.calls());

                    let failed = run(&Pitboard::new(m.ctx.clone()), &m)
                        .unwrap_or_else(|| panic!("{at}: refused"));

                    assert_eq!(failed.error.code(), "elevated", "{at}: {}", failed.error);
                    assert!(failed.warnings.is_empty(), "{at}: {:?}", failed.warnings);
                    assert!(everything(&m) == before, "{at}: nothing changes");
                    assert_eq!(m.api.calls(), asked, "{at}: nobody is asked");
                }

                let at = format!("{tool}, enroll_signed_in, {elevation:?}");
                let m = interrupted(make, &format!("gate-{tool}-enroll-signed-in"));
                let login = crate::switch::harness::signed_in(&m, "new", "new-refresh");
                m.mem.runs_with(elevation);
                let before = everything(&m);
                let failed = Pitboard::new(m.ctx.clone())
                    .enroll_signed_in(&m.key("new").typed(), login)
                    .expect_err("refused");
                assert_eq!(failed.error.code(), "elevated", "{at}");
                assert!(everything(&m) == before, "{at}: nothing changes");
            }
        }
    }

    /// The gate's refusal says what to do, the same for root and for sudo, and says it
    /// apart where nobody could tell.
    #[test]
    fn the_gate_says_why_it_refuses_and_lets_a_person_through() {
        let m = machine("gate-words");
        let pitboard = Pitboard::new(m.ctx.clone());
        assert!(pitboard.permit().is_ok(), "as the person");
        for elevation in REFUSED_AS {
            m.mem.runs_with(elevation);
            let refused = pitboard.permit().expect_err("refused");
            assert_eq!(refused.code(), "elevated");
            assert_eq!(refused.exit_code(), 1);
            assert_eq!(
                refused.to_string(),
                match elevation {
                    Elevation::Unknown => {
                        "Pitboard changes nothing when it cannot tell whether it runs as root \
                         or with sudo. Run it as yourself."
                    }
                    _ => {
                        "Pitboard changes nothing when it runs as root or with sudo. Run it \
                         as yourself."
                    }
                },
            );
        }
    }

    /// An empty or relative `HOME` made every path under it lead into the folder Pitboard
    /// was run from: its own files where `PITBOARD_HOME` was not set, and the scheduler's
    /// and each tool's default folder whatever was. The gate refuses it now, and so does
    /// every read of the accounts, with `home_not_absolute`, and nothing changes. Asked of
    /// the gate and the reads first, which change nothing whatever they answer.
    #[test]
    fn every_change_and_read_is_refused_where_the_home_is_not_a_full_path() {
        for home in ["", "relative"] {
            for (tool, make) in MACHINES {
                let at = format!("{tool}, HOME={home:?}");
                let m = make(&format!("unplaced-{tool}-{}", home.len()));
                let mut ctx = m.ctx.clone();
                ctx.home = std::path::PathBuf::from(home);
                let pitboard = Pitboard::new(ctx);
                let refused = |error: Error| {
                    assert_eq!(error.code(), "home_not_absolute", "{at}: {error}");
                    assert!(error.to_string().starts_with("HOME is "), "{at}: {error}");
                };

                refused(pitboard.permit().expect_err("the gate refuses"));
                refused(pitboard.status_offline().err().expect("refused"));
                refused(pitboard.status(false).err().expect("refused"));
                let before = (everything(&m), m.api.calls());
                for (change, run) in CHANGES {
                    let failed = run(&pitboard, &m).unwrap_or_else(|| panic!("{at}: {change}"));
                    refused(failed.error);
                    assert!(failed.warnings.is_empty(), "{at}, {change}");
                }
                assert!(
                    (everything(&m), m.api.calls()) == before,
                    "{at}: nothing changes and nobody is asked"
                );
            }
        }
    }

    /// What a read says, account by account: enough to tell a live read from one of what
    /// was last measured.
    type Read = Vec<(
        ProviderId,
        Option<String>,
        bool,
        Option<crate::usage::Snapshot>,
        Option<status::Stale>,
    )>;

    fn rows(report: &status::Report) -> Read {
        report
            .rows
            .iter()
            .map(|row| {
                (
                    row.provider,
                    row.label.clone(),
                    row.signed_in,
                    row.usage.clone(),
                    row.stale,
                )
            })
            .collect()
    }

    /// A read renewed every parked login whose access had lapsed, asked each service about
    /// every account and wrote what it measured down, as root too. Where this process may
    /// change nothing it answers what the read that asks nobody answers, and says why: it
    /// renews nothing, asks nobody and writes nothing. A park whose access has lapsed is
    /// there to be renewed, so a read that renewed would show it.
    #[test]
    fn a_read_where_pitboard_may_change_nothing_asks_nobody_and_says_why() {
        for (tool, make) in MACHINES {
            for elevation in REFUSED_AS {
                let at = format!("{tool}, {elevation:?}");
                let m = make(&format!("gate-read-{tool}"));
                let later = m
                    .ctx
                    .clone()
                    .with_clock(Arc::new(crate::time::FixedClock::at(
                        crate::switch::harness::NOW + 11 * 86_400,
                    )));
                let pitboard = Pitboard::new(later);
                m.mem.runs_with(elevation);
                let (before, asked) = (everything(&m), m.api.calls());

                let read = pitboard.status(false).expect("a read");
                let known = pitboard.status_offline().expect("a read");

                assert!(everything(&m) == before, "{at}: nothing is written");
                assert_eq!(m.api.calls(), asked, "{at}: nobody is asked");
                assert_eq!(rows(&read.value), rows(&known.value), "{at}");
                let codes: Vec<&str> = read.warnings.iter().map(Warning::code).collect();
                assert_eq!(codes.last(), Some(&"read_only"), "{at}");
                assert_eq!(read.warnings.len(), known.warnings.len() + 1, "{at}");
                let said = read.warnings.last().expect("said").to_string();
                match elevation {
                    Elevation::Elevated { why } => assert!(
                        said.starts_with(&format!("Pitboard runs {why}, so it changes nothing")),
                        "{at}: {said}"
                    ),
                    _ => assert!(said.starts_with("Pitboard cannot tell"), "{at}: {said}"),
                }

                m.mem.runs_with(Elevation::Normal);
                let live = pitboard.status(false).expect("a read");
                assert!(m.api.calls() > asked, "{at}: as the person, it asks");
                assert!(
                    !live.warnings.iter().any(|w| w.code() == "read_only"),
                    "{at}"
                );
            }
        }
    }

    /// The status line kept what each session passed it and the readings it moved, as root
    /// too. Where this process may change nothing it draws the same line from the files as
    /// they are, and writes neither.
    #[test]
    fn the_status_line_where_pitboard_may_change_nothing_draws_the_same_line_and_writes_nothing() {
        let session = serde_json::json!({
            "session_id": "a-session",
            "rate_limits": {
                "five_hour": {"used_percentage": 40.0, "resets_at": crate::switch::harness::NOW + 3_600},
                "seven_day": {"used_percentage": 20.0, "resets_at": crate::switch::harness::NOW + 86_400},
            },
        })
        .to_string();
        for elevation in REFUSED_AS {
            let m = machine("gate-statusline");
            let pitboard = Pitboard::new(m.ctx.clone());
            m.mem.runs_with(elevation);
            let before = everything(&m);

            let refused = pitboard.statusline(&session);

            assert!(
                everything(&m) == before,
                "{elevation:?}: nothing is written"
            );
            m.mem.runs_with(Elevation::Normal);
            assert_eq!(pitboard.statusline(&session), refused, "{elevation:?}");
            assert!(
                crate::home::dir(&m.ctx).join("sessions.json").exists(),
                "{elevation:?}: as the person, the session is kept"
            );
        }
    }

    /// `renew` returned an empty list when it renewed nothing, whatever the reason, so a
    /// run that could not renew read as one where nothing was due. Refused, it says so, and
    /// asks nobody, with a park that is due to be renewed.
    #[test]
    fn a_renewal_where_pitboard_may_change_nothing_is_refused_and_asks_nobody() {
        for (tool, make) in MACHINES {
            for elevation in REFUSED_AS {
                let at = format!("{tool}, {elevation:?}");
                let m = make(&format!("gate-renew-{tool}"));
                crate::switch::harness::renews(&m, "there-refresh", "there-refresh-2");
                let later = m
                    .ctx
                    .clone()
                    .with_clock(Arc::new(crate::time::FixedClock::at(
                        crate::switch::harness::NOW + 11 * 86_400,
                    )));
                let pitboard = Pitboard::new(later);
                m.mem.runs_with(elevation);
                let (before, asked) = (everything(&m), m.api.calls());

                let refused = pitboard.renew().expect_err("refused");

                assert_eq!(refused.code(), "elevated", "{at}");
                assert!(everything(&m) == before, "{at}: nothing changes");
                assert_eq!(m.api.calls(), asked, "{at}: nobody is asked");

                m.mem.runs_with(Elevation::Normal);
                let renewed = pitboard.renew().expect("as the person, it renews");
                let codes: Vec<&str> = renewed.iter().map(|(_, r)| r.code()).collect();
                assert_eq!(codes, ["renewed"], "{at}");
            }
        }
    }

    /// `doctor` says why every change is refused, first, as a check that fails, and says
    /// nothing of it where Pitboard runs as the person.
    #[test]
    fn doctor_says_why_pitboard_changes_nothing() {
        let m = machine("gate-doctor");
        let pitboard = Pitboard::new(m.ctx.clone());
        assert!(
            !pitboard
                .doctor()
                .checks
                .iter()
                .any(|c| c.code == "elevated"),
            "as the person"
        );
        for elevation in REFUSED_AS {
            m.mem.runs_with(elevation);
            let checks = pitboard.doctor().checks;
            let check = checks.first().expect("checks");
            assert_eq!(check.code, "elevated", "{elevation:?}");
            assert_eq!(check.level, doctor::Level::Fail, "{elevation:?}");
            assert_eq!(
                check.detail,
                match elevation {
                    Elevation::Elevated { why } => format!("Pitboard runs {why}"),
                    _ => "Pitboard cannot tell whether it runs as root or with sudo".into(),
                }
            );
            assert!(
                check.advice.ends_with("Run it as yourself."),
                "{}",
                check.advice
            );
        }
    }
}