pitboard-core 0.18.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
//! Which store Codex keeps its login in, and which logins it keeps, from every layer it reads
//! outside a project, in its order (`codex_store_layers`, `codex_windows_store_layers`,
//! `codex_managed_preferences`, `codex_login_restrictions`).

// A layer that is there and cannot be read is a store nobody can tell, `Backend::Unknown`.
// Not read: a project's config, which is one folder's; Pitboard's sign-ins run from their own.
// Not read: a profile's file, which only a run given `--profile` reads, and `codex login` refuses.
// Not read: an enterprise's cloud configuration, which `codex login` does not load.
// A `profile` line chooses the table it names, as the owner decided on 7 October 2026.

use super::paths::Backend;
use crate::context::Context;
use crate::host::{Administered, Hive, Os};
use crate::words::listed_values;
use base64::prelude::{BASE64_STANDARD, Engine as _};
use std::fmt::Write as _;
use std::path::{Path, PathBuf};

/// The domain of Codex's managed preferences, and their two keys.
const PREFERENCES: &str = "com.openai.codex";
const CONFIG_KEY: &str = "config_toml_base64";
const REQUIREMENTS_KEY: &str = "requirements_toml_base64";

/// The setting that chooses the store.
const STORE: &str = "cli_auth_credentials_store";

// The policy that names Codex's requirements file on Windows, under `HKLM`.
const POLICY_KEY: &str = r"SOFTWARE\Policies\OpenAI\Codex";
const POLICY_VALUE: &str = "RequirementsPath";

/// The feature that keeps a keychain store's login in an encrypted file of secrets.
const SECRETS: &str = "secret_auth_storage";

/// What Pitboard's own sign-ins give `codex -c`: the file store, over every layer a person
/// sets. It is TOML as it stands, which is how Codex reads a `-c` value.
pub(crate) const FILE_STORE: &str = "cli_auth_credentials_store=\"file\"";

/// What Codex is built with, its `codex-rs/config/defaults.toml`, as far as the store goes.
const PACKAGED: &str = "cli_auth_credentials_store = \"file\"\n";

/// One place Codex reads its configuration from, outside a project.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub(crate) enum Layer {
    /// What Codex is built with: `cli_auth_credentials_store = "file"`.
    Packaged,
    /// `/etc/codex/config.toml`: this machine's defaults, which a person's own replace.
    System,
    /// `config.toml` in Codex's home, the person's own.
    Own,
    /// `-c` on Codex's command line, as Pitboard's own sign-ins give it.
    CommandLine,
    /// `/etc/codex/managed_config.toml`, over everything a person sets.
    Managed,
    /// The managed preference `config_toml_base64` of `com.openai.codex`, macOS's: base64
    /// TOML, over every file.
    ManagedPreference,
    /// `/etc/codex/requirements.toml`, which pins what it sets over every layer.
    Required,
    /// The managed preference `requirements_toml_base64` of `com.openai.codex`, macOS's,
    /// which pins over the file.
    RequiredByPreference,
}

impl Layer {
    /// Whether what this layer sets is a requirement, which no layer of configuration
    /// changes.
    fn pins(self) -> bool {
        matches!(self, Layer::Required | Layer::RequiredByPreference)
    }

    fn place(self, places: &Places) -> String {
        let file = |name: &str| places.system.join(name).display().to_string();
        match self {
            Layer::Packaged => "Codex's default".into(),
            Layer::System => file("config.toml"),
            Layer::Own => places.own.display().to_string(),
            Layer::CommandLine => "the `-c` Pitboard's sign-ins give `codex login`".into(),
            Layer::Managed => file("managed_config.toml"),
            Layer::ManagedPreference => {
                format!("the managed preference `{CONFIG_KEY}` of `{PREFERENCES}`")
            }
            Layer::Required => match &places.required {
                Ok(file) => file.display().to_string(),
                Err(_) => format!("the policy `{POLICY_VALUE}` of `HKLM\\{POLICY_KEY}`"),
            },
            Layer::RequiredByPreference => {
                format!("the managed preference `{REQUIREMENTS_KEY}` of `{PREFERENCES}`")
            }
        }
    }
}

// Where the layers this machine's Codex reads are, for reading them and for the words.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Places {
    // This machine's folder of Codex's configuration.
    system: PathBuf,
    // Its requirements, or what the policy that names them holds where that is no full path.
    required: Result<PathBuf, String>,
    // The person's own `config.toml`, where a line that changes the store goes.
    own: PathBuf,
}

fn places_of(ctx: &Context, own: &Path) -> Places {
    let system = system_dir_of(ctx);
    let named = match crate::host::OS {
        Os::Windows => ctx.host().policy(Hive::Machine, POLICY_KEY, POLICY_VALUE),
        Os::MacOs | Os::Linux => Administered::Unset,
    };
    Places {
        required: required_file(&system, named, ctx.profile.as_deref().unwrap_or(ctx.home())),
        system,
        own: own.to_path_buf(),
    }
}

// The requirements file `HKLM`'s policy names on Windows (`codex_windows_store_layers`).
fn required_file(system: &Path, named: Administered, profile: &Path) -> Result<PathBuf, String> {
    let Administered::Set(named) = named else {
        return Ok(system.join("requirements.toml"));
    };
    let home = |rest: &str, separator| {
        rest.strip_prefix(separator)
            .map(|rest| profile.join(rest.trim_start_matches(separator)))
    };
    let expanded = match named.strip_prefix('~') {
        Some("") => profile.to_path_buf(),
        Some(rest) => home(rest, '/')
            .or_else(|| home(rest, '\\'))
            .unwrap_or_else(|| PathBuf::from(&named)),
        None => PathBuf::from(&named),
    };
    let expanded = crate::host::without_verbatim_prefix(expanded);
    if crate::host::windows_absolute(&expanded.to_string_lossy()) {
        Ok(expanded)
    } else {
        Err(named)
    }
}

// Codex falls back to `C:\ProgramData` where Windows cannot say `FOLDERID_ProgramData`, and
// never reads the variable (`codex_windows_store_layers`).
fn system_dir(os: Os, program_data: Option<PathBuf>) -> PathBuf {
    match os {
        Os::MacOs | Os::Linux => PathBuf::from("/etc/codex"),
        Os::Windows => program_data
            .unwrap_or_else(|| PathBuf::from(r"C:\ProgramData"))
            .join("OpenAI")
            .join("Codex"),
    }
}

fn system_dir_of(ctx: &Context) -> PathBuf {
    system_dir(crate::host::OS, ctx.host().program_data())
}

// This machine's file `name` of Codex's configuration, as `ctx`'s host finds it.
#[cfg(test)]
pub(crate) fn system_file(ctx: &Context, name: &str) -> PathBuf {
    system_dir_of(ctx).join(name)
}

// Lowest first. An enterprise's cloud layers, a profile's and a project's are not read, as the
// module says. Windows reads no `managed_config.toml` and has no managed preferences.
pub(crate) fn config_layers(os: Os) -> &'static [Layer] {
    use Layer::{CommandLine, Managed, ManagedPreference, Own, Packaged, System};
    match os {
        Os::MacOs => &[
            Packaged,
            System,
            Own,
            CommandLine,
            Managed,
            ManagedPreference,
        ],
        Os::Linux => &[Packaged, System, Own, CommandLine, Managed],
        Os::Windows => &[Packaged, System, Own, CommandLine],
    }
}

/// The layers Codex reads requirements from on `os`, lowest first (`codex_store_layers`).
// `managed_config.toml` and its managed preference are requirements only for approvals and the
// sandbox (`legacy_requirements_to_toml_value`), so they pin no store.
pub(crate) fn requirement_layers(os: Os) -> &'static [Layer] {
    match os {
        Os::MacOs => &[Layer::Required, Layer::RequiredByPreference],
        Os::Linux | Os::Windows => &[Layer::Required],
    }
}

/// Whether Codex keeps a keychain store's login in its encrypted file of secrets when
/// nothing says: `secret_auth_storage` is on by default only where `cfg!(windows)`, so off
/// on macOS and Linux, and on on Windows.
fn secrets_by_default(os: Os) -> bool {
    match os {
        Os::MacOs | Os::Linux => false,
        Os::Windows => true,
    }
}

/// The store a store setting names, as Codex spells it in `AuthCredentialsStoreMode`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Mode {
    File,
    Keyring,
    Auto,
    Ephemeral,
}

impl Mode {
    fn named(word: &str) -> Option<Mode> {
        Some(match word {
            "file" => Mode::File,
            "keyring" => Mode::Keyring,
            "auto" => Mode::Auto,
            "ephemeral" => Mode::Ephemeral,
            _ => return None,
        })
    }

    fn word(self) -> &'static str {
        match self {
            Mode::File => "file",
            Mode::Keyring => "keyring",
            Mode::Auto => "auto",
            Mode::Ephemeral => "ephemeral",
        }
    }
}

impl Backend {
    // Codex has no one word for the last two.
    pub(crate) fn word(self) -> &'static str {
        match self {
            Backend::File => Mode::File.word(),
            Backend::Keyring => Mode::Keyring.word(),
            Backend::Either => Mode::Auto.word(),
            Backend::Ephemeral => Mode::Ephemeral.word(),
            Backend::Secrets => "secrets",
            Backend::Unknown => "unknown",
        }
    }
}

// The register's `codex_keychain_stores_are_its_own`, `codex_keyring_store_on_linux` and
// `codex_windows_stores`.
pub(crate) fn file_store_only(os: Os) -> &'static str {
    match os {
        Os::MacOs => {
            "Pitboard handles Codex's file store, auth.json, and does not read an item Codex \
             created for itself, because every read would ask you for permission"
        }
        Os::Linux | Os::Windows => {
            "Pitboard handles Codex's file store, auth.json, and does not follow Codex into a \
             store it uses only when told to"
        }
    }
}

/// Where Codex keeps its login on this machine, and which layer said so.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Store {
    pub(crate) backend: Backend,
    /// The layer whose setting chose the store: [`Layer::Packaged`] for Codex's own default.
    pub(crate) chosen_by: Layer,
    /// The store as that layer names it.
    mode: Mode,
    /// Where `secret_auth_storage` was turned on, for [`Backend::Secrets`], or `None` where it
    /// is on by default.
    secrets_by: Option<Layer>,
    /// For [`Backend::Unknown`], why nobody can tell.
    unknown: Option<Unknown>,
    places: Places,
}

/// Why nobody can tell the store, for [`Backend::Unknown`].
#[derive(Debug, Clone, PartialEq, Eq)]
struct Unknown {
    /// The layer that cannot be read as Codex reads it.
    layer: Layer,
    /// What is wrong with it, in words that follow the layer's place.
    why: String,
    /// What Codex does over it.
    then: Then,
}

/// What Codex does over the layer [`Unknown`] names.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Then {
    Stops,
    /// A `profile = "<name>"` line no table defines (`codex_store_layers`).
    NoProfile(String),
}

impl Store {
    /// The setting that chose this store, in words that can follow its name in brackets:
    /// Codex's default, `` `cli_auth_credentials_store = "keyring"` in `` a file, or `pinned to
    /// keyring by` a requirement.
    pub(crate) fn setting(&self) -> String {
        let place = self.place(self.chosen_by);
        let mut said = match self.chosen_by {
            Layer::Packaged => place,
            layer if layer.pins() => format!("pinned to `{}` by {place}", self.mode.word()),
            _ => format!("`{STORE} = \"{}\"` in {place}", self.mode.word()),
        };
        if self.backend == Backend::Secrets {
            match self.secrets_by {
                Some(layer) => {
                    let _ = write!(said, ", with `{SECRETS}` in {}", self.place(layer));
                }
                None => {
                    let _ = write!(said, ", with `{SECRETS}` on by default");
                }
            }
        }
        said
    }

    /// What would put the login in the file store instead, as a sentence with no full stop,
    /// for a store that is not the file: the line to set and where, or who can.
    pub(crate) fn to_use_the_file(&self, program: &str) -> String {
        let line = format!("`{STORE} = \"file\"`");
        let place = self.place(self.chosen_by);
        match self.chosen_by {
            Layer::Packaged | Layer::System | Layer::Own | Layer::CommandLine => format!(
                "To use the file store, set {line} in {}, then sign in again with `{program} \
                 login`",
                self.places.own.display()
            ),
            Layer::Managed => format!(
                "{place} sets it over your own config.toml, so only an administrator can \
                 change it there to {line}"
            ),
            Layer::ManagedPreference => format!(
                "An administrator's configuration profile sets it in {place}, over every \
                 file, so only they can change it to {line}"
            ),
            Layer::Required | Layer::RequiredByPreference => format!(
                "No line in your own config.toml can change it: {place} pins it, and only \
                 an administrator can change that"
            ),
        }
    }

    /// Why the store cannot be told, for [`Backend::Unknown`]: the place that cannot be read
    /// as Codex reads it, and what is wrong there.
    pub(crate) fn why_unknown(&self) -> Option<String> {
        self.unknown
            .as_ref()
            .map(|unknown| format!("{} {}", self.place(unknown.layer), unknown.why))
    }

    /// What Codex does over [`Store::why_unknown`], with no last full stop (`codex_store_layers`).
    pub(crate) fn while_unknown(&self) -> Option<String> {
        self.unknown.as_ref().map(|unknown| match &unknown.then {
            Then::Stops => "Codex 0.160.0 does not start until that is put right".into(),
            Then::NoProfile(name) => format!(
                "Codex 0.160.0 does not start with that line, and an older Codex, such as \
                 0.99.0, which chooses a profile with it, refuses one no table defines: \
                 \"config profile `{name}` not found\""
            ),
        })
    }

    fn place(&self, layer: Layer) -> String {
        layer.place(&self.places)
    }
}

/// The store this machine's Codex keeps its login in, read for the home `ctx` names.
pub(crate) fn of(ctx: &Context, own: &Path) -> Store {
    let places = places_of(ctx, own);
    resolve(crate::host::OS, &places, &|layer| {
        read(ctx, &places, layer, Some(own), None)
    })
}

/// The store a sign-in Pitboard runs ends up with: in a private home, which holds no
/// `config.toml`, with [`FILE_STORE`] on its command line. `own` is the person's own
/// `config.toml`, for what the words name.
pub(crate) fn of_a_sign_in(ctx: &Context, own: &Path) -> Store {
    let places = places_of(ctx, own);
    resolve(crate::host::OS, &places, &|layer| {
        read(ctx, &places, layer, None, Some(FILE_STORE))
    })
}

// `own` is the `config.toml` of Codex's home, where there is one, and `command_line` what `-c`
// gives.
fn read(
    ctx: &Context,
    places: &Places,
    layer: Layer,
    own: Option<&Path>,
    command_line: Option<&str>,
) -> Administered {
    let host = ctx.host();
    let file = |name: &str| host.administered_file(&places.system.join(name));
    match layer {
        Layer::Packaged => Administered::Set(PACKAGED.into()),
        Layer::System => file("config.toml"),
        // In a home, so read whatever the build: a test makes a home of its own.
        Layer::Own => own.map_or(Administered::Unset, crate::host::administered::read_text),
        Layer::CommandLine => command_line.map_or(Administered::Unset, |said| {
            Administered::Set(said.to_string())
        }),
        Layer::Managed => file("managed_config.toml"),
        Layer::ManagedPreference => decoded(host.managed_preference(PREFERENCES, CONFIG_KEY)),
        Layer::Required => match &places.required {
            Ok(required) => host.administered_file(required),
            Err(named) => {
                Administered::Unreadable(format!("names `{named}`, which is no full path"))
            }
        },
        Layer::RequiredByPreference => {
            decoded(host.managed_preference(PREFERENCES, REQUIREMENTS_KEY))
        }
    }
}

// Trimmed first, as Codex trims a forced value before decode_managed_preferences_base64.
fn decoded(forced: Administered) -> Administered {
    match forced {
        Administered::Set(encoded) => match BASE64_STANDARD.decode(encoded.trim()) {
            Err(_) => Administered::Unreadable("is not base64".into()),
            Ok(bytes) => String::from_utf8(bytes).map_or_else(
                |_| Administered::Unreadable("does not decode to UTF-8 text".into()),
                Administered::Set,
            ),
        },
        other => other,
    }
}

/// What one layer says, once read.
enum Says {
    Nothing,
    Table(toml::Table),
    /// It is there and Codex cannot read it, which stops Codex from starting.
    Broken(String),
}

impl Says {
    fn of(read: Administered) -> Says {
        match read {
            Administered::Unset => Says::Nothing,
            Administered::Unreadable(why) => Says::Broken(why),
            Administered::Set(text) => match text.parse::<toml::Table>() {
                Ok(table) => Says::Table(table),
                // The line only: the error's own words quote the file, which may hold a key.
                Err(e) => Says::Broken(match e.span() {
                    Some(at) => format!(
                        "is not TOML Codex can read, at line {}",
                        text.bytes().take(at.start).filter(|&b| b == b'\n').count() + 1
                    ),
                    None => "is not TOML Codex can read".into(),
                }),
            },
        }
    }

    fn table(&self) -> Option<&toml::Table> {
        match self {
            Says::Table(table) => Some(table),
            Says::Nothing | Says::Broken(_) => None,
        }
    }
}

/// What a layer sets something to: nothing, a value Codex takes, or one it refuses, with
/// what is wrong with it in words that follow `sets`.
enum Set<T> {
    Unset,
    To(T),
    Refused(String),
}

/// The store a layer's table sets.
fn store_in(table: &toml::Table) -> Set<Mode> {
    match table.get(STORE) {
        None => Set::Unset,
        Some(toml::Value::String(word)) => {
            Mode::named(word).map_or_else(|| not_a_store(&format!("`\"{word}\"`")), Set::To)
        }
        Some(other) => not_a_store(&kind(other)),
    }
}

fn not_a_store<T>(written: &str) -> Set<T> {
    Set::Refused(format!(
        "{STORE} to {written}, which is not a store Codex has"
    ))
}

/// What kind of TOML value `value` is, as a person would say it: `an integer`.
fn kind(value: &toml::Value) -> String {
    let name = value.type_str();
    let article = if name.starts_with(['a', 'e', 'i', 'o', 'u']) {
        "an"
    } else {
        "a"
    };
    format!("{article} {name}")
}

/// The profile a layer's table chooses with `profile = "<name>"` (`codex_store_layers`).
fn profile_in(table: &toml::Table) -> Set<String> {
    match table.get("profile") {
        None => Set::Unset,
        Some(toml::Value::String(name)) => Set::To(name.clone()),
        Some(other) => Set::Refused(format!(
            "`profile` to {}, where Codex takes a profile's name",
            kind(other)
        )),
    }
}

/// Whether a layer's table defines the profile `name`, as `[profiles.<name>]`.
// Codex reads `profiles` as a map of tables, and no store in a profile's table
// (`codex_store_layers`).
fn profile_table_in(table: &toml::Table, name: &str) -> Set<()> {
    let not_a_table = |key: &str, value: &toml::Value| {
        Set::Refused(format!(
            "`{key}` to {}, where Codex takes a table",
            kind(value)
        ))
    };
    match table.get("profiles") {
        None => Set::Unset,
        Some(toml::Value::Table(profiles)) => match profiles.get(name) {
            None => Set::Unset,
            Some(toml::Value::Table(_)) => Set::To(()),
            Some(other) => not_a_table(&format!("profiles.{name}"), other),
        },
        Some(other) => not_a_table("profiles", other),
    }
}

/// Which of a layer's tables holds its features: `[features]`, or in a requirement also
/// `[feature_requirements]`, the alias `ConfigRequirementsToml` gives it. A configuration
/// layer's table of that name is none of Codex's, and sets nothing.
#[derive(Debug, Clone, Copy)]
enum Features {
    OfConfiguration,
    OfRequirement,
}

/// Whether a layer's table turns `secret_auth_storage` on or off.
fn secrets_in(table: &toml::Table, of: Features) -> Set<bool> {
    let features = table.get("features").or_else(|| match of {
        Features::OfRequirement => table.get("feature_requirements"),
        Features::OfConfiguration => None,
    });
    match features {
        None => Set::Unset,
        Some(toml::Value::Table(features)) => match features.get(SECRETS) {
            None => Set::Unset,
            Some(toml::Value::Boolean(on)) => Set::To(*on),
            Some(other) => Set::Refused(format!(
                "`{SECRETS}` to {}, where Codex takes only true or false",
                kind(other)
            )),
        },
        Some(other) => Set::Refused(format!(
            "`features` to {}, where Codex takes a table",
            kind(other)
        )),
    }
}

/// The highest of `layers`, given lowest first, that sets what `get` reads, with what it set.
fn highest<'a, T>(
    layers: impl DoubleEndedIterator<Item = &'a (Layer, Says)>,
    get: impl Fn(&toml::Table) -> Set<T>,
) -> Option<(Layer, Result<T, String>)> {
    layers
        .rev()
        .find_map(|(layer, says)| match get(says.table()?) {
            Set::Unset => None,
            Set::To(value) => Some((*layer, Ok(value))),
            Set::Refused(written) => Some((*layer, Err(written))),
        })
}

type Read = Vec<(Layer, Says)>;

// The requirements, then the configuration, each lowest first.
fn read_layers(os: Os, read: &dyn Fn(Layer) -> Administered) -> (Read, Read) {
    let read_all = |layers: &[Layer]| -> Read {
        layers
            .iter()
            .map(|&layer| (layer, Says::of(read(layer))))
            .collect()
    };
    (
        read_all(requirement_layers(os)),
        read_all(config_layers(os)),
    )
}

// The highest layer Codex cannot read, which stops it from starting.
fn broken(required: &Read, config: &Read) -> Option<(Layer, String)> {
    required
        .iter()
        .rev()
        .chain(config.iter().rev())
        .find_map(|(layer, says)| match says {
            Says::Broken(why) => Some((*layer, why.clone())),
            Says::Nothing | Says::Table(_) => None,
        })
}

pub(crate) fn resolve(os: Os, places: &Places, read: &dyn Fn(Layer) -> Administered) -> Store {
    let (required, config) = read_layers(os, read);
    let store = |backend, chosen_by, mode, secrets_by, unknown| Store {
        backend,
        chosen_by,
        mode,
        secrets_by,
        unknown,
        places: places.clone(),
    };
    let unknown = |layer: Layer, why: String, then: Then| {
        store(
            Backend::Unknown,
            layer,
            Mode::File,
            None,
            Some(Unknown { layer, why, then }),
        )
    };

    // A layer Codex cannot read stops it from starting, whatever the others say.
    if let Some((layer, why)) = broken(&required, &config) {
        return unknown(layer, why, Then::Stops);
    }

    // Codex reads the configuration whole before a requirement replaces anything in it, so a
    // value it cannot take there stops it even under a requirement.
    let refused = |layer, wrong: String| unknown(layer, format!("sets {wrong}"), Then::Stops);
    let configured = match highest(config.iter(), store_in) {
        Some((layer, Ok(mode))) => (layer, mode),
        Some((layer, Err(wrong))) => return refused(layer, wrong),
        // Every list starts with what Codex is built with, which sets it.
        None => (Layer::Packaged, Mode::File),
    };
    let (chosen_by, mode) = match highest(required.iter(), store_in) {
        Some((layer, Ok(mode))) => (layer, mode),
        Some((layer, Err(wrong))) => return refused(layer, wrong),
        None => configured,
    };

    let configured_secrets = match highest(config.iter(), |table| {
        secrets_in(table, Features::OfConfiguration)
    }) {
        Some((layer, Ok(on))) => Some((layer, on)),
        Some((layer, Err(wrong))) => return refused(layer, wrong),
        None => None,
    };
    let (secrets_by, secrets) = match highest(required.iter(), |table| {
        secrets_in(table, Features::OfRequirement)
    }) {
        Some((layer, Ok(on))) => (Some(layer), on),
        Some((layer, Err(wrong))) => return refused(layer, wrong),
        None => configured_secrets.map_or((None, secrets_by_default(os)), |(layer, on)| {
            (Some(layer), on)
        }),
    };

    // A profile chosen in any layer is the one a table in any layer defines. Its table holds no
    // store Codex reads, so the store is still the layers', but a profile no table defines is
    // one nobody can tell (`codex_store_layers`).
    match highest(config.iter(), profile_in) {
        Some((layer, Ok(name))) => {
            match highest(config.iter(), |table| profile_table_in(table, &name)) {
                Some((_, Ok(()))) => {}
                Some((defined, Err(wrong))) => return refused(defined, wrong),
                None => {
                    return unknown(
                        layer,
                        format!(
                            "sets `profile = \"{name}\"`, a profile no `[profiles.{name}]` \
                             table defines"
                        ),
                        Then::NoProfile(name),
                    );
                }
            }
        }
        Some((layer, Err(wrong))) => return refused(layer, wrong),
        None => {}
    }

    let backend = match mode {
        Mode::File => Backend::File,
        Mode::Ephemeral => Backend::Ephemeral,
        Mode::Keyring | Mode::Auto if secrets => Backend::Secrets,
        Mode::Keyring => Backend::Keyring,
        Mode::Auto => Backend::Either,
    };
    let secrets_by = secrets_by.filter(|_| backend == Backend::Secrets);
    store(backend, chosen_by, mode, secrets_by, None)
}

const FORCED_METHOD: &str = "forced_login_method";
const FORCED_WORKSPACES: &str = "forced_chatgpt_workspace_id";
const ALLOWED_METHODS: &str = "allowed_login_methods";
const ALLOWED_WORKSPACES: &str = "allowed_chatgpt_workspaces";

// As `ForcedLoginMethod` spells a way to sign in.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Method {
    Chatgpt,
    Api,
}

impl Method {
    fn named(word: &str) -> Option<Method> {
        match word {
            "chatgpt" => Some(Method::Chatgpt),
            "api" => Some(Method::Api),
            _ => None,
        }
    }

    fn word(self) -> &'static str {
        match self {
            Method::Chatgpt => "chatgpt",
            Method::Api => "api",
        }
    }
}

// Which ChatGPT logins this machine's Codex keeps (`codex_login_restrictions`). What the
// configuration forces, the interactive `codex` signs out of and deletes as it starts; what
// either leaves out, every Codex leaves unused.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Restrictions {
    method: Option<(Layer, Method)>,
    workspaces: Option<(Layer, Vec<String>)>,
    allowed_methods: Option<(Layer, Vec<Method>)>,
    allowed_workspaces: Option<(Layer, Vec<String>)>,
    // What Codex cannot take, which stops it from starting.
    unreadable: Option<(Layer, String)>,
    places: Places,
}

impl Restrictions {
    // Why Codex would not keep a ChatGPT login of the workspace its ID token names, `claimed`,
    // and its `tokens.account_id` names, `stored`, as a sentence with no full stop.
    pub(crate) fn refuses(&self, claimed: Option<&str>, stored: Option<&str>) -> Option<String> {
        if let Some((layer, why)) = &self.unreadable {
            return Some(format!(
                "{} {why}, so Codex does not start, and which logins it keeps cannot be told",
                self.place(*layer)
            ));
        }
        let signs_out = "so the interactive `codex` signs out of it as it starts, and deletes it";
        let unused = "so Codex does not use it";
        let of = |ids: &[String], workspace: Option<&str>| {
            (!workspace.is_some_and(|id| ids.iter().any(|allowed| allowed == id))).then(|| {
                format!(
                    "{}, and this login is {}",
                    listed_values(ids),
                    workspace
                        .map_or_else(|| "of no workspace".to_owned(), |id| format!("of `{id}`"))
                )
            })
        };
        if let Some((layer, Method::Api)) = self.method {
            return Some(format!(
                "{} sets `{FORCED_METHOD} = \"api\"`, {signs_out}",
                self.place(layer)
            ));
        }
        if let Some((layer, ids)) = &self.workspaces
            && let Some(outside) = of(ids, claimed)
        {
            return Some(format!(
                "{} sets `{FORCED_WORKSPACES}` to {outside}, {signs_out}",
                self.place(*layer)
            ));
        }
        if let Some((layer, methods)) = &self.allowed_methods
            && !methods.contains(&Method::Chatgpt)
        {
            return Some(format!(
                "{} sets `{ALLOWED_METHODS}` to {}, which leaves out a ChatGPT sign-in, {unused}",
                self.place(*layer),
                listed_values(&methods.iter().map(|m| m.word()).collect::<Vec<_>>())
            ));
        }
        // Its AuthManager holds `tokens.account_id`, else the claim, to what either names.
        for (key, set) in [
            (FORCED_WORKSPACES, &self.workspaces),
            (ALLOWED_WORKSPACES, &self.allowed_workspaces),
        ] {
            if let Some((layer, ids)) = set
                && let Some(outside) = of(ids, stored.or(claimed))
            {
                return Some(format!(
                    "{} sets `{key}` to {outside}, {unused}",
                    self.place(*layer)
                ));
            }
        }
        None
    }

    // Each restriction and where it is set, for `doctor`.
    pub(crate) fn said(&self) -> Vec<String> {
        let set = |layer: Layer, key: &str, to: String| {
            format!("`{key}` set to {to} in {}", self.place(layer))
        };
        let methods = |methods: &[Method]| {
            listed_values(&methods.iter().map(|m| m.word()).collect::<Vec<_>>())
        };
        if let Some((layer, why)) = &self.unreadable {
            return vec![format!("{} {why}", self.place(*layer))];
        }
        self.method
            .map(|(layer, method)| set(layer, FORCED_METHOD, listed_values(&[method.word()])))
            .into_iter()
            .chain(
                self.workspaces
                    .as_ref()
                    .map(|(layer, ids)| set(*layer, FORCED_WORKSPACES, listed_values(ids))),
            )
            .chain(
                self.allowed_methods
                    .as_ref()
                    .map(|(layer, allowed)| set(*layer, ALLOWED_METHODS, methods(allowed))),
            )
            .chain(
                self.allowed_workspaces
                    .as_ref()
                    .map(|(layer, ids)| set(*layer, ALLOWED_WORKSPACES, listed_values(ids))),
            )
            .collect()
    }

    pub(crate) fn unreadable(&self) -> bool {
        self.unreadable.is_some()
    }

    fn place(&self, layer: Layer) -> String {
        layer.place(&self.places)
    }
}

pub(crate) fn restrictions_of(ctx: &Context, own: &Path) -> Restrictions {
    let places = places_of(ctx, own);
    restrictions(crate::host::OS, &places, &|layer| {
        read(ctx, &places, layer, Some(own), None)
    })
}

fn restrictions(os: Os, places: &Places, read: &dyn Fn(Layer) -> Administered) -> Restrictions {
    let (required, config) = read_layers(os, read);
    let mut found = Restrictions {
        method: None,
        workspaces: None,
        allowed_methods: None,
        allowed_workspaces: None,
        unreadable: broken(&required, &config),
        places: places.clone(),
    };
    if found.unreadable.is_some() {
        return found;
    }
    let mut wrong = None;
    found.method = taken(&config, method_in, &mut wrong);
    // Codex reads an empty list as no restriction here, and as none allowed in a requirement.
    found.workspaces = taken(
        &config,
        |table| workspaces_in(table, FORCED_WORKSPACES),
        &mut wrong,
    )
    .filter(|(_, ids)| !ids.is_empty());
    found.allowed_methods = taken(&required, methods_in, &mut wrong);
    found.allowed_workspaces = taken(
        &required,
        |table| workspaces_in(table, ALLOWED_WORKSPACES),
        &mut wrong,
    );
    found.unreadable = wrong;
    found
}

// What the highest of `layers` to set it sets, where Codex takes it. One it cannot take goes in
// `wrong`, the first such.
fn taken<T>(
    layers: &Read,
    get: impl Fn(&toml::Table) -> Set<T>,
    wrong: &mut Option<(Layer, String)>,
) -> Option<(Layer, T)> {
    match highest(layers.iter(), get)? {
        (layer, Ok(value)) => Some((layer, value)),
        (layer, Err(said)) => {
            wrong.get_or_insert((layer, format!("sets {said}")));
            None
        }
    }
}

fn method_in(table: &toml::Table) -> Set<Method> {
    match table.get(FORCED_METHOD) {
        None => Set::Unset,
        Some(toml::Value::String(word)) => Method::named(word).map_or_else(
            || {
                Set::Refused(format!(
                    "`{FORCED_METHOD}` to `\"{word}\"`, which is not a way Codex signs in"
                ))
            },
            Set::To,
        ),
        Some(other) => Set::Refused(format!(
            "`{FORCED_METHOD}` to {}, where Codex takes `\"chatgpt\"` or `\"api\"`",
            kind(other)
        )),
    }
}

fn methods_in(table: &toml::Table) -> Set<Vec<Method>> {
    match table.get(ALLOWED_METHODS) {
        None => Set::Unset,
        Some(toml::Value::Array(items)) => items
            .iter()
            .map(|item| item.as_str().and_then(Method::named))
            .collect::<Option<Vec<_>>>()
            .map_or_else(
                || {
                    Set::Refused(format!(
                        "`{ALLOWED_METHODS}` to a list with something in it other than \
                         `\"chatgpt\"` and `\"api\"`"
                    ))
                },
                Set::To,
            ),
        Some(other) => Set::Refused(format!(
            "`{ALLOWED_METHODS}` to {}, where Codex takes a list",
            kind(other)
        )),
    }
}

// Trimmed, the empty ones dropped, as Codex reads both settings. Only `forced_chatgpt_workspace_id`
// takes one workspace on its own, and never several in one string.
fn workspaces_in(table: &toml::Table, key: &str) -> Set<Vec<String>> {
    let trimmed = |ids: Vec<&str>| {
        Set::To(
            ids.into_iter()
                .map(str::trim)
                .filter(|id| !id.is_empty())
                .map(str::to_owned)
                .collect(),
        )
    };
    match table.get(key) {
        None => Set::Unset,
        Some(toml::Value::String(id)) if key == FORCED_WORKSPACES && !id.contains(',') => {
            trimmed(vec![id.as_str()])
        }
        Some(toml::Value::Array(items)) => items
            .iter()
            .map(toml::Value::as_str)
            .collect::<Option<Vec<_>>>()
            .map_or_else(
                || {
                    Set::Refused(format!(
                        "`{key}` to a list with something in it other than workspace ids"
                    ))
                },
                trimmed,
            ),
        Some(toml::Value::String(_)) if key == FORCED_WORKSPACES => Set::Refused(format!(
            "`{key}` to workspace ids apart by commas in one string, where Codex takes a list"
        )),
        Some(other) => Set::Refused(format!(
            "`{key}` to {}, where Codex takes a list of workspace ids",
            kind(other)
        )),
    }
}

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

    const OWN: &str = "/Users/someone/.codex/config.toml";

    fn etc_codex() -> PathBuf {
        system_dir(Os::Linux, None)
    }

    // Joined as this host joins a path, which is how `Layer::place` names it.
    fn etc(name: &str) -> String {
        etc_codex().join(name).display().to_string()
    }

    fn program_data(name: &str) -> String {
        system_dir(Os::Windows, None)
            .join(name)
            .display()
            .to_string()
    }

    fn places(os: Os) -> Places {
        let system = system_dir(os, None);
        Places {
            required: Ok(system.join("requirements.toml")),
            system,
            own: PathBuf::from(OWN),
        }
    }

    /// What each layer holds, by layer, as a test says: unset where it says nothing. A managed
    /// preference is given as it is forced, in base64, and decoded as [`read`] decodes it.
    fn machine(os: Os, holds: &[(Layer, &str)]) -> Store {
        machine_at(os, &places(os), holds)
    }

    fn machine_at(os: Os, places: &Places, holds: &[(Layer, &str)]) -> Store {
        let holds: HashMap<Layer, Administered> = holds
            .iter()
            .map(|&(layer, text)| {
                let forced = Administered::Set(text.to_string());
                let holds = match layer {
                    Layer::ManagedPreference | Layer::RequiredByPreference => decoded(forced),
                    _ => forced,
                };
                (layer, holds)
            })
            .collect();
        resolve(os, places, &|layer| match layer {
            Layer::Packaged => Administered::Set(PACKAGED.into()),
            _ => holds.get(&layer).cloned().unwrap_or(Administered::Unset),
        })
    }

    const KEYRING: &str = "cli_auth_credentials_store = \"keyring\"\n";
    const FILE: &str = "cli_auth_credentials_store = \"file\"\n";
    const EPHEMERAL: &str = "cli_auth_credentials_store = \"ephemeral\"\n";

    fn base64(text: &str) -> String {
        BASE64_STANDARD.encode(text)
    }

    /// Nothing set anywhere is Codex's own default, the file.
    #[test]
    fn nothing_set_is_codex_default_the_file() {
        for os in [Os::MacOs, Os::Linux] {
            let store = machine(os, &[]);
            assert_eq!(store.backend, Backend::File);
            assert_eq!(store.chosen_by, Layer::Packaged);
            assert_eq!(store.setting(), "Codex's default");
        }
    }

    /// Each layer replaces what the ones under it set, in Codex's order, on each system.
    #[test]
    fn a_higher_layer_replaces_a_lower_one() {
        for os in [Os::MacOs, Os::Linux] {
            let store = machine(os, &[(Layer::System, KEYRING)]);
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::Keyring, Layer::System)
            );
            let store = machine(os, &[(Layer::System, KEYRING), (Layer::Own, FILE)]);
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::File, Layer::Own),
                "the person's own config.toml is over the system's"
            );
            let store = machine(os, &[(Layer::Own, FILE), (Layer::Managed, KEYRING)]);
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::Keyring, Layer::Managed),
                "managed_config.toml is over the person's"
            );
            let store = machine(
                os,
                &[(Layer::Own, KEYRING), (Layer::CommandLine, FILE_STORE)],
            );
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::File, Layer::CommandLine),
                "a -c is over the person's config.toml"
            );
            let store = machine(
                os,
                &[(Layer::Managed, KEYRING), (Layer::CommandLine, FILE_STORE)],
            );
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::Keyring, Layer::Managed),
                "and under managed_config.toml"
            );
        }
    }

    /// Only macOS has managed preferences. There, the forced config is over every file, and
    /// the forced requirements pin over the file of requirements. Linux reads neither.
    #[test]
    fn managed_preferences_are_read_on_macos_alone() {
        let forced = base64(KEYRING);
        let broken = format!("{}\n{}", &forced[..4], &forced[4..]);
        let holds = [
            (Layer::Managed, FILE),
            (Layer::ManagedPreference, forced.as_str()),
        ];
        let store = machine(Os::MacOs, &holds);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Keyring, Layer::ManagedPreference)
        );
        assert_eq!(machine(Os::Linux, &holds).backend, Backend::File);

        let holds = [
            (Layer::Own, KEYRING),
            (Layer::Required, KEYRING),
            (Layer::RequiredByPreference, broken.as_str()),
        ];
        assert_eq!(
            machine(Os::MacOs, &holds).backend,
            Backend::Unknown,
            "a forced value that is not canonical base64 is one Codex cannot read"
        );
        let file = base64(FILE);
        let holds = [
            (Layer::Own, KEYRING),
            (Layer::Required, KEYRING),
            (Layer::RequiredByPreference, file.as_str()),
        ];
        let store = machine(Os::MacOs, &holds);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::File, Layer::RequiredByPreference)
        );
        let store = machine(Os::Linux, &holds);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Keyring, Layer::Required)
        );
    }

    /// A forced value is read only where Codex 0.164.0 reads it: trimmed, then strict
    /// `BASE64_STANDARD` (codex-rs/config/src/loader/macos.rs:294).
    #[test]
    fn a_forced_value_is_decoded_as_codex_decodes_it() {
        for text in ["Zg", "Zh==", "Zm-v", "Zm9v=", "Zm 9v"] {
            assert_eq!(
                decoded(Administered::Set(text.into())),
                Administered::Unreadable("is not base64".into()),
                "{text}"
            );
        }
        assert_eq!(
            decoded(Administered::Set(" Zg== ".into())),
            Administered::Set("f".into())
        );
    }

    /// A requirement pins the store over every layer, even the forced managed config, and the
    /// words say no line of the person's own can change it.
    #[test]
    fn a_requirement_pins_the_store_over_every_layer() {
        let forced = base64(FILE);
        let store = machine(
            Os::MacOs,
            &[
                (Layer::Own, FILE),
                (Layer::CommandLine, FILE_STORE),
                (Layer::Managed, FILE),
                (Layer::ManagedPreference, forced.as_str()),
                (Layer::Required, EPHEMERAL),
            ],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Ephemeral, Layer::Required)
        );
        assert_eq!(
            store.setting(),
            format!("pinned to `ephemeral` by {}", etc("requirements.toml"))
        );
        assert_eq!(
            store.to_use_the_file("codex"),
            format!(
                "No line in your own config.toml can change it: {} pins it, and only an \
                 administrator can change that",
                etc("requirements.toml")
            )
        );
    }

    /// The person's own setting, or the system's under it, is changed with one line in the
    /// person's own config.toml, as Codex resolves it.
    #[test]
    fn a_setting_of_the_persons_own_names_the_line_and_the_file() {
        let store = machine(
            Os::Linux,
            &[(Layer::System, "cli_auth_credentials_store = 'auto'")],
        );
        assert_eq!(store.backend, Backend::Either);
        assert_eq!(
            store.setting(),
            format!(
                "`cli_auth_credentials_store = \"auto\"` in {}",
                etc("config.toml")
            )
        );
        assert_eq!(
            store.to_use_the_file("codex"),
            format!(
                "To use the file store, set `cli_auth_credentials_store = \"file\"` in {OWN}, \
                 then sign in again with `codex login`"
            )
        );
        let store = machine(Os::Linux, &[(Layer::Managed, KEYRING)]);
        assert_eq!(
            store.to_use_the_file("codex"),
            format!(
                "{} sets it over your own config.toml, so only an administrator can change it \
                 there to `cli_auth_credentials_store = \"file\"`",
                etc("managed_config.toml")
            )
        );
    }

    /// `secret_auth_storage` makes a keychain store an encrypted file of secrets, read from
    /// the same layers in the same order and pinned the same way. It is off by default on
    /// macOS and Linux, and changes nothing for the file store.
    #[test]
    fn the_secret_store_is_read_from_the_same_layers() {
        let on = "[features]\nsecret_auth_storage = true\n";
        let off = "[features]\nsecret_auth_storage = false\n";
        for os in [Os::MacOs, Os::Linux] {
            assert_eq!(
                machine(os, &[(Layer::Own, KEYRING)]).backend,
                Backend::Keyring
            );
            let store = machine(os, &[(Layer::Own, KEYRING), (Layer::System, on)]);
            assert_eq!(store.backend, Backend::Secrets);
            assert_eq!(
                store.setting(),
                format!(
                    "`cli_auth_credentials_store = \"keyring\"` in {OWN}, with \
                     `secret_auth_storage` in {}",
                    etc("config.toml")
                )
            );
            assert_eq!(
                machine(
                    os,
                    &[
                        (Layer::Own, KEYRING),
                        (Layer::System, on),
                        (Layer::Managed, off)
                    ]
                )
                .backend,
                Backend::Keyring
            );
            assert_eq!(
                machine(
                    os,
                    &[
                        (Layer::Own, KEYRING),
                        (Layer::Managed, off),
                        (
                            Layer::Required,
                            "[feature_requirements]\nsecret_auth_storage = true\n"
                        )
                    ]
                )
                .backend,
                Backend::Secrets,
                "a requirement pins a feature too, under either name of its table"
            );
            assert_eq!(
                machine(
                    os,
                    &[
                        (Layer::Own, KEYRING),
                        (
                            Layer::System,
                            "[feature_requirements]\nsecret_auth_storage = true\n"
                        )
                    ]
                )
                .backend,
                Backend::Keyring,
                "only a requirement's table has that second name"
            );
            assert_eq!(
                machine(
                    os,
                    &[
                        (Layer::Own, KEYRING),
                        (Layer::Managed, "feature_requirements = 1\n")
                    ]
                )
                .backend,
                Backend::Keyring,
                "and a configuration layer's table of that name sets nothing"
            );
            assert_eq!(machine(os, &[(Layer::Own, on)]).backend, Backend::File);
        }
    }

    /// Where an administrator's layer chooses the file over a keychain or memory store of the
    /// person's own, Codex keeps its login in `auth.json`, and so the store is the file:
    /// `/etc/codex/managed_config.toml` replaces the person's setting, and a requirement
    /// replaces the configured one (`apply_exact_requirement`). Pitboard refused these,
    /// reading the person's `config.toml` alone. On Linux and on macOS, which also has the
    /// managed preferences.
    #[test]
    fn an_administrator_who_chooses_the_file_is_over_the_persons_own_store() {
        let forced = base64(FILE);
        for (own, alone) in [
            (KEYRING, Backend::Keyring),
            ("cli_auth_credentials_store = \"auto\"\n", Backend::Either),
            (EPHEMERAL, Backend::Ephemeral),
        ] {
            for os in [Os::Linux, Os::MacOs] {
                assert_eq!(machine(os, &[(Layer::Own, own)]).backend, alone);
                for layer in [Layer::Managed, Layer::Required] {
                    let store = machine(os, &[(Layer::Own, own), (layer, FILE)]);
                    assert_eq!(
                        (store.backend, store.chosen_by),
                        (Backend::File, layer),
                        "{os:?}: {layer:?} over {alone:?}"
                    );
                }
            }
            for layer in [Layer::ManagedPreference, Layer::RequiredByPreference] {
                let holds = [(Layer::Own, own), (layer, forced.as_str())];
                assert_eq!(
                    (
                        machine(Os::MacOs, &holds).backend,
                        machine(Os::Linux, &holds).backend
                    ),
                    (Backend::File, alone),
                    "{layer:?} over {alone:?}, which Linux does not read"
                );
            }
        }
        assert_eq!(
            machine(Os::Linux, &[(Layer::Own, KEYRING), (Layer::System, FILE)]).backend,
            Backend::Keyring,
            "/etc/codex/config.toml is under the person's own, so it lifts nothing"
        );
    }

    /// A layer that is there and that Codex cannot read stops Codex from starting, so the
    /// store is unknown, which refuses, and never the file.
    #[test]
    fn a_layer_codex_cannot_read_is_unknown_never_the_file() {
        for (layer, text, why) in [
            (
                Layer::System,
                "cli_auth_credentials_store = \n",
                "is not TOML Codex can read, at line 1",
            ),
            (
                Layer::Own,
                "model = \"o3\"\n[[[\n",
                "is not TOML Codex can read, at line 2",
            ),
            (
                Layer::Required,
                "]",
                "is not TOML Codex can read, at line 1",
            ),
            (
                Layer::Own,
                "cli_auth_credentials_store = \"nonsense\"\n",
                "sets cli_auth_credentials_store to `\"nonsense\"`, which is not a store Codex has",
            ),
            (
                Layer::Managed,
                "cli_auth_credentials_store = 1\n",
                "sets cli_auth_credentials_store to an integer, which is not a store Codex has",
            ),
            (
                Layer::System,
                "[features]\nsecret_auth_storage = \"yes\"\n",
                "sets `secret_auth_storage` to a string, where Codex takes only true or false",
            ),
        ] {
            let store = machine(Os::Linux, &[(Layer::Own, FILE), (layer, text)]);
            assert_eq!(store.backend, Backend::Unknown, "{text}");
            assert_eq!(
                store.why_unknown(),
                Some(format!("{} {why}", layer.place(&places(Os::Linux)))),
                "{text}"
            );
        }
        let unreadable = resolve(Os::Linux, &places(Os::Linux), &|layer| match layer {
            Layer::Packaged => Administered::Set(PACKAGED.into()),
            Layer::Required => Administered::Unreadable("cannot be read: denied".into()),
            _ => Administered::Unset,
        });
        assert_eq!(unreadable.backend, Backend::Unknown);
        assert_eq!(
            unreadable.why_unknown(),
            Some(format!(
                "{} cannot be read: denied",
                etc("requirements.toml")
            ))
        );
    }

    /// A line that chooses the profile `work`, and the table that defines it.
    const PROFILED: &str = "profile = \"work\"\n[profiles.work]\nmodel = \"o3\"\n";

    /// A `profile = "<name>"` line in a layer chooses the profile `[profiles.<name>]`
    /// defines, as the owner's answer of 7 October 2026 reads it, wherever each is set: Codex
    /// merges the layers before it looks a profile up. A profile's table holds no store
    /// Codex 0.99.0 or 0.160.0 reads, so the store is still the one the layers choose, and
    /// where that is the file, the account is taken, where Pitboard refused every profile
    /// line.
    #[test]
    fn a_profile_line_chooses_its_profile_and_the_store_is_still_the_layers() {
        let chosen_over_a_file = format!("profile = \"work\"\n{FILE}");
        for os in [Os::MacOs, Os::Linux] {
            for layer in [Layer::System, Layer::Own, Layer::Managed] {
                let store = machine(os, &[(layer, PROFILED)]);
                assert_eq!(
                    (store.backend, store.chosen_by),
                    (Backend::File, Layer::Packaged),
                    "{os:?}: {layer:?}"
                );
                assert_eq!(store.setting(), "Codex's default");
                assert_eq!(store.why_unknown(), None);
            }
            let store = machine(
                os,
                &[
                    (Layer::System, "[profiles.work]\nmodel = \"o3\"\n"),
                    (Layer::Own, chosen_over_a_file.as_str()),
                ],
            );
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::File, Layer::Own),
                "{os:?}: a profile one layer defines and another chooses"
            );
        }
    }

    /// What a chosen profile's table says of the store is not read, as neither Codex 0.99.0
    /// nor 0.160.0 reads one there: neither one's `ConfigProfile` has
    /// `cli_auth_credentials_store`, so serde drops the key, and 0.160.0 does not apply a
    /// profile's `[features]`, while 0.99.0 has no `secret_auth_storage` to apply. So a
    /// keychain store or the secret store there changes nothing, a store Codex does not have
    /// there stops nothing, a file store there lifts no keychain store of the person's own,
    /// which is refused naming the person's own line, and a table nothing chooses changes
    /// nothing either.
    #[test]
    fn a_chosen_profiles_table_holds_no_store_codex_reads() {
        for os in [Os::MacOs, Os::Linux] {
            let keychain_in_profile = "profile = \"work\"\n[profiles.work]\n\
                                       cli_auth_credentials_store = \"keyring\"\n\
                                       [profiles.work.features]\nsecret_auth_storage = true\n";
            let store = machine(os, &[(Layer::Own, keychain_in_profile)]);
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::File, Layer::Packaged),
                "{os:?}"
            );
            let nonsense_in_profile = "profile = \"work\"\n[profiles.work]\n\
                                       cli_auth_credentials_store = \"nonsense\"\n";
            assert_eq!(
                machine(os, &[(Layer::Own, nonsense_in_profile)]).backend,
                Backend::File,
                "{os:?}: a key Codex drops stops nothing"
            );
            let file_in_profile = "cli_auth_credentials_store = \"keyring\"\nprofile = \"work\"\n\
                                   [profiles.work]\ncli_auth_credentials_store = \"file\"\n";
            let store = machine(os, &[(Layer::Own, file_in_profile)]);
            assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::Keyring, Layer::Own),
                "{os:?}"
            );
            assert_eq!(
                store.setting(),
                format!("`cli_auth_credentials_store = \"keyring\"` in {OWN}")
            );
            assert_eq!(
                store.to_use_the_file("codex"),
                format!(
                    "To use the file store, set `cli_auth_credentials_store = \"file\"` in \
                     {OWN}, then sign in again with `codex login`"
                )
            );
            let tables_alone = "[profiles.work]\ncli_auth_credentials_store = \"keyring\"\n";
            assert_eq!(
                machine(os, &[(Layer::Own, tables_alone)]).backend,
                Backend::File,
                "{os:?}: a profile's table that nothing chooses changes nothing"
            );
        }
    }

    /// With a profile chosen, a store the layers choose other than the file is refused as
    /// that store, as it is with no profile: the person's own keyring, a managed file's
    /// memory store, a requirement's pin.
    #[test]
    fn a_chosen_profile_leaves_a_store_that_is_not_the_file_to_be_refused_as_itself() {
        let keyring_chosen = format!("profile = \"work\"\n{KEYRING}[profiles.work]\n");
        let store = machine(Os::Linux, &[(Layer::Own, keyring_chosen.as_str())]);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Keyring, Layer::Own)
        );
        let store = machine(
            Os::Linux,
            &[(Layer::Own, PROFILED), (Layer::Managed, EPHEMERAL)],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Ephemeral, Layer::Managed)
        );
        let store = machine(
            Os::MacOs,
            &[(Layer::Own, PROFILED), (Layer::Required, KEYRING)],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Keyring, Layer::Required)
        );
        assert_eq!(
            store.setting(),
            format!("pinned to `keyring` by {}", etc("requirements.toml"))
        );
    }

    /// A line that chooses a profile no layer defines is a store nobody can tell, which
    /// refuses, and never the file: Codex 0.160.0 does not start with the line at all, and an
    /// older Codex that chooses a profile with it, such as 0.99.0, refuses one it cannot
    /// find. A table of another name defines nothing, and the words say what each Codex does.
    #[test]
    fn a_profile_no_table_defines_is_unknown_never_the_file() {
        for (layer, holds) in [
            (Layer::Own, vec![(Layer::Own, "profile = \"work\"\n")]),
            (
                Layer::System,
                vec![
                    (
                        Layer::System,
                        "profile = \"work\"\n[profiles.home]\nmodel = \"o3\"\n",
                    ),
                    (Layer::Own, FILE),
                ],
            ),
            (
                Layer::Managed,
                vec![
                    (Layer::Managed, "profile = \"work\"\n"),
                    (Layer::Own, "[profiles.home]\nmodel = \"o3\"\n"),
                ],
            ),
        ] {
            let store = machine(Os::Linux, &holds);
            assert_eq!(store.backend, Backend::Unknown, "{layer:?}");
            assert_eq!(
                store.why_unknown(),
                Some(format!(
                    "{} sets `profile = \"work\"`, a profile no `[profiles.work]` table defines",
                    layer.place(&places(Os::Linux))
                )),
                "{layer:?}"
            );
            assert_eq!(
                store.while_unknown().as_deref(),
                Some(
                    "Codex 0.160.0 does not start with that line, and an older Codex, such as \
                     0.99.0, which chooses a profile with it, refuses one no table defines: \
                     \"config profile `work` not found\""
                ),
                "{layer:?}"
            );
        }
    }

    /// A profile line, or a table of profiles, that Codex cannot read stops 0.160.0 from
    /// starting, as a store it does not have does: a `profile` that is not a name, and a
    /// `profiles` or a `[profiles.<name>]` that is not a table, which its
    /// `HashMap<String, ConfigProfile>` cannot take. A store Codex does not have is told
    /// first, as 0.160.0 reads the configuration whole before it looks at the line.
    #[test]
    fn a_profile_codex_cannot_read_stops_it_as_any_value_it_cannot_take() {
        for (text, why) in [
            (
                "profile = 3\n",
                "sets `profile` to an integer, where Codex takes a profile's name",
            ),
            (
                "profile = \"work\"\nprofiles = 3\n",
                "sets `profiles` to an integer, where Codex takes a table",
            ),
            (
                "profile = \"work\"\n[profiles]\nwork = \"o3\"\n",
                "sets `profiles.work` to a string, where Codex takes a table",
            ),
            (
                "profile = \"work\"\ncli_auth_credentials_store = \"nonsense\"\n",
                "sets cli_auth_credentials_store to `\"nonsense\"`, which is not a store \
                 Codex has",
            ),
        ] {
            let store = machine(Os::Linux, &[(Layer::Own, text)]);
            assert_eq!(store.backend, Backend::Unknown, "{text}");
            assert_eq!(store.why_unknown(), Some(format!("{OWN} {why}")), "{text}");
            assert_eq!(
                store.while_unknown().as_deref(),
                Some("Codex 0.160.0 does not start until that is put right"),
                "{text}"
            );
        }
    }

    /// A value Codex cannot take is replaced by a higher layer's, as Codex merges them before
    /// it reads the store, so only the one that wins has to be one Codex has.
    #[test]
    fn a_value_codex_cannot_take_is_replaced_by_a_higher_one() {
        let store = machine(
            Os::Linux,
            &[
                (Layer::System, "cli_auth_credentials_store = \"nonsense\"\n"),
                (Layer::Own, FILE),
            ],
        );
        assert_eq!(store.backend, Backend::File);
    }

    /// A sign-in Pitboard runs has no config.toml of its own and the file store on its
    /// command line, so only what an administrator set over that keeps it from the file.
    #[test]
    fn a_sign_in_takes_the_file_store_unless_an_administrator_set_another() {
        let host = crate::host::memory::MemoryHost::new();
        let ctx = Context::for_unit_test().with_memory_stores(host.clone());
        let (own, at) = (Path::new(OWN), |name| system_file(&ctx, name));
        assert_eq!(of_a_sign_in(&ctx, own).backend, Backend::File);
        host.administers(at("config.toml"), KEYRING);
        let store = of_a_sign_in(&ctx, own);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::File, Layer::CommandLine),
            "the -c is over the system's config"
        );
        host.administers(at("managed_config.toml"), KEYRING);
        let managed = match crate::host::OS {
            Os::MacOs | Os::Linux => Backend::Keyring,
            Os::Windows => Backend::File,
        };
        assert_eq!(of_a_sign_in(&ctx, own).backend, managed);
        host.administers(at("managed_config.toml"), FILE);
        host.administers(at("requirements.toml"), EPHEMERAL);
        let store = of_a_sign_in(&ctx, own);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Ephemeral, Layer::Required)
        );
    }

    /// What the host says an administrator set is what is read, at Codex's paths, and a
    /// managed preference is read as the base64 Codex reads it as.
    #[test]
    fn what_an_administrator_set_is_read_through_the_host() {
        let host = crate::host::memory::MemoryHost::new();
        let ctx = Context::for_unit_test().with_memory_stores(host.clone());
        let own = Path::new(OWN);
        assert_eq!(of(&ctx, own).chosen_by, Layer::Packaged);
        host.administers(system_file(&ctx, "requirements.toml"), KEYRING);
        assert_eq!(of(&ctx, own).chosen_by, Layer::Required);
        host.administers_unreadably(system_file(&ctx, "config.toml"), "cannot be read: denied");
        assert_eq!(of(&ctx, own).backend, Backend::Unknown);

        let host = crate::host::memory::MemoryHost::new();
        let ctx = Context::for_unit_test().with_memory_stores(host.clone());
        host.forces(
            PREFERENCES,
            CONFIG_KEY,
            &format!("  {}\n", base64(EPHEMERAL)),
        );
        let store = of(&ctx, own);
        match crate::host::OS {
            Os::MacOs => assert_eq!(
                (store.backend, store.chosen_by),
                (Backend::Ephemeral, Layer::ManagedPreference)
            ),
            Os::Linux | Os::Windows => assert_eq!(store.backend, Backend::File),
        }
    }

    // Codex 0.163.0 on Windows: OpenAI\Codex's config.toml and requirements.toml around the
    // person's own, no managed_config.toml, and the secret store on by default.
    #[test]
    fn on_windows_codex_reads_its_machine_folder_and_keeps_a_keyring_login_in_secrets() {
        let store = machine(Os::Windows, &[]);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::File, Layer::Packaged)
        );
        let store = machine(Os::Windows, &[(Layer::System, KEYRING)]);
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Secrets, Layer::System)
        );
        assert_eq!(
            store.setting(),
            format!(
                "`cli_auth_credentials_store = \"keyring\"` in {}, with `secret_auth_storage` on \
                 by default",
                program_data("config.toml")
            )
        );
        assert_eq!(
            store.to_use_the_file("codex"),
            format!(
                "To use the file store, set `cli_auth_credentials_store = \"file\"` in {OWN}, \
                 then sign in again with `codex login`"
            )
        );
        let auto = "cli_auth_credentials_store = \"auto\"\n";
        assert_eq!(
            machine(Os::Windows, &[(Layer::Own, auto)]).backend,
            Backend::Secrets
        );
        let off = "[features]\nsecret_auth_storage = false\n";
        assert_eq!(
            machine(Os::Windows, &[(Layer::Own, KEYRING), (Layer::System, off)]).backend,
            Backend::Keyring
        );
        assert_eq!(
            machine(Os::Windows, &[(Layer::Own, auto), (Layer::System, off)]).backend,
            Backend::Either
        );
        assert_eq!(
            machine(
                Os::Windows,
                &[(Layer::Own, FILE), (Layer::Managed, KEYRING)]
            )
            .backend,
            Backend::File,
            "no managed_config.toml"
        );
        let store = machine(
            Os::Windows,
            &[
                (Layer::Own, KEYRING),
                (Layer::System, KEYRING),
                (Layer::CommandLine, FILE_STORE),
            ],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::File, Layer::CommandLine),
            "a sign-in's -c"
        );

        let store = machine(
            Os::Windows,
            &[(Layer::Own, FILE), (Layer::Required, EPHEMERAL)],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Ephemeral, Layer::Required)
        );
        let required = program_data("requirements.toml");
        assert_eq!(
            store.setting(),
            format!("pinned to `ephemeral` by {required}")
        );
        assert_eq!(
            store.to_use_the_file("codex"),
            format!(
                "No line in your own config.toml can change it: {required} pins it, and only an \
                 administrator can change that"
            )
        );
        let store = machine(
            Os::Windows,
            &[(Layer::Own, KEYRING), (Layer::Required, FILE)],
        );
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::File, Layer::Required)
        );
        let store = machine(Os::Windows, &[(Layer::Own, FILE), (Layer::System, "]")]);
        assert_eq!(store.backend, Backend::Unknown);
        assert_eq!(
            store.why_unknown(),
            Some(format!(
                "{} is not TOML Codex can read, at line 1",
                program_data("config.toml")
            ))
        );
    }

    // Codex 0.164.0 on Windows reads its requirements from the file `HKLM`'s `RequirementsPath`
    // names, `~` its profile folder, past a policy it cannot read, and does not start where the
    // policy names no full path (codex_windows_store_layers).
    #[test]
    fn a_policy_on_windows_names_codexs_requirements_file() {
        let system = system_dir(Os::Windows, None);
        let beside = Ok(system.join("requirements.toml"));
        let profile = Path::new(r"C:\Users\someone");
        let named = |text: &str| required_file(&system, Administered::Set(text.into()), profile);
        assert_eq!(required_file(&system, Administered::Unset, profile), beside);
        assert_eq!(
            required_file(&system, Administered::Unreadable("denied".into()), profile),
            beside
        );
        assert_eq!(
            named(r"D:\Policy\codex.toml"),
            Ok(PathBuf::from(r"D:\Policy\codex.toml"))
        );
        assert_eq!(named(r"~\codex.toml"), Ok(profile.join("codex.toml")));
        assert_eq!(
            named(r"\\?\D:\codex.toml"),
            Ok(PathBuf::from(r"D:\codex.toml"))
        );
        for full in [
            r"\\server\share\codex.toml",
            "//server/share/codex.toml",
            r"/\server\share",
            r"\\.\D:\codex.toml",
            r"\\?\Volume{0}\codex.toml",
            "//?/D:/codex.toml",
        ] {
            assert_eq!(named(full), Ok(PathBuf::from(full)), "{full}");
        }
        for relative in [
            "",
            "codex.toml",
            r"C:codex.toml",
            r"\codex.toml",
            r"\\server",
            r"\\server\",
            r"\\.",
            r"\\?/",
        ] {
            assert_eq!(named(relative), Err(relative.to_owned()), "{relative}");
        }

        let elsewhere = Places {
            required: Ok(PathBuf::from(r"D:\Policy\codex.toml")),
            ..places(Os::Windows)
        };
        let store = machine_at(
            Os::Windows,
            &elsewhere,
            &[(Layer::Own, FILE), (Layer::Required, EPHEMERAL)],
        );
        assert_eq!(
            store.setting(),
            r"pinned to `ephemeral` by D:\Policy\codex.toml"
        );
        let nowhere = Places {
            required: Err("codex.toml".into()),
            ..places(Os::Windows)
        };
        let ctx =
            Context::for_unit_test().with_memory_stores(crate::host::memory::MemoryHost::new());
        let store = resolve(Os::Windows, &nowhere, &|layer| {
            read(&ctx, &nowhere, layer, None, None)
        });
        assert_eq!(store.backend, Backend::Unknown);
        assert_eq!(
            store.why_unknown().as_deref(),
            Some(
                "the policy `RequirementsPath` of `HKLM\\SOFTWARE\\Policies\\OpenAI\\Codex` \
                 names `codex.toml`, which is no full path"
            )
        );
    }

    // On Windows alone, where the host reads the policy.
    #[cfg(windows)]
    #[test]
    fn codex_on_windows_takes_its_requirements_from_the_file_the_policy_names() {
        let host = crate::host::memory::MemoryHost::new();
        let ctx = Context::for_unit_test().with_memory_stores(host.clone());
        let named = PathBuf::from(r"D:\Policy\codex.toml");
        host.sets_policy(
            Hive::Machine,
            r"SOFTWARE\Policies\OpenAI\Codex",
            "RequirementsPath",
            &named.display().to_string(),
        );
        host.administers(&named, EPHEMERAL);
        let store = of(&ctx, Path::new(OWN));
        assert_eq!(
            (store.backend, store.chosen_by),
            (Backend::Ephemeral, Layer::Required)
        );
        assert_eq!(
            store.setting(),
            format!("pinned to `ephemeral` by {}", named.display())
        );
    }

    #[test]
    fn codexs_machine_folder_on_windows_is_in_the_known_program_data_folder() {
        let data = PathBuf::from(r"D:\Data");
        assert_eq!(
            system_dir(Os::Windows, Some(data.clone())),
            data.join("OpenAI").join("Codex")
        );
        assert_eq!(
            system_dir(Os::Windows, None),
            PathBuf::from(r"C:\ProgramData")
                .join("OpenAI")
                .join("Codex"),
            "Codex's own fallback"
        );
        for os in [Os::MacOs, Os::Linux] {
            assert_eq!(
                system_dir(os, Some(data.clone())),
                PathBuf::from("/etc/codex")
            );
        }
    }

    fn restricted(os: Os, holds: &[(Layer, &str)]) -> Restrictions {
        let holds: HashMap<Layer, Administered> = holds
            .iter()
            .map(|&(layer, text)| (layer, Administered::Set(text.to_string())))
            .collect();
        restrictions(os, &places(os), &|layer| {
            holds.get(&layer).cloned().unwrap_or(Administered::Unset)
        })
    }

    // Codex 0.164.0's enforce_login_restrictions holds the ID token's workspace to what the
    // configuration forces, trimmed, and signs out of any other.
    #[test]
    fn codex_signs_out_of_a_workspace_its_configuration_leaves_out() {
        let none = restricted(Os::Linux, &[]);
        assert_eq!(none.refuses(Some("a"), Some("a")), None);
        assert!(none.said().is_empty());

        let one = restricted(
            Os::Linux,
            &[(Layer::Own, "forced_chatgpt_workspace_id = \" a \"\n")],
        );
        assert_eq!(one.refuses(Some("a"), Some("a")), None);
        assert_eq!(
            one.refuses(Some("b"), Some("b")).as_deref(),
            Some(
                "/Users/someone/.codex/config.toml sets `forced_chatgpt_workspace_id` to `a`, and \
                 this login is of `b`, so the interactive `codex` signs out of it as it starts, \
                 and deletes it"
            )
        );
        assert!(
            one.refuses(None, Some("a"))
                .is_some_and(|said| said.contains("this login is of no workspace")),
            "the ID token's workspace is the one held to it"
        );
        assert_eq!(
            one.refuses(Some("a"), Some("b")).as_deref(),
            Some(
                "/Users/someone/.codex/config.toml sets `forced_chatgpt_workspace_id` to `a`, and \
                 this login is of `b`, so Codex does not use it"
            ),
            "and its AuthManager holds `tokens.account_id` to it"
        );

        let two = restricted(
            Os::Linux,
            &[(Layer::Own, "forced_chatgpt_workspace_id = [\"a\", \"b\"]\n")],
        );
        assert_eq!(two.refuses(Some("b"), Some("b")), None);
        assert!(two.refuses(Some("c"), Some("c")).is_some());

        for os in [Os::MacOs, Os::Linux, Os::Windows] {
            let replaced = restricted(
                os,
                &[
                    (Layer::System, "forced_chatgpt_workspace_id = \"a\"\n"),
                    (Layer::Own, "forced_chatgpt_workspace_id = []\n"),
                ],
            );
            assert_eq!(
                replaced.refuses(Some("b"), Some("b")),
                None,
                "{os:?}: an empty list over another is no restriction"
            );
        }
        let managed = [
            (Layer::Own, "forced_chatgpt_workspace_id = \"a\"\n"),
            (Layer::Managed, "forced_chatgpt_workspace_id = \"b\"\n"),
        ];
        assert!(
            restricted(Os::Linux, &managed)
                .refuses(Some("a"), Some("a"))
                .is_some()
        );
        assert_eq!(
            restricted(Os::Windows, &managed).refuses(Some("a"), Some("a")),
            None,
            "Windows reads no managed_config.toml"
        );

        let api = restricted(
            Os::MacOs,
            &[(Layer::System, "forced_login_method = \"api\"\n")],
        );
        assert!(
            api.refuses(Some("a"), Some("a"))
                .is_some_and(|said| said.contains("`forced_login_method = \"api\"`"))
        );
        let chatgpt = restricted(
            Os::MacOs,
            &[(Layer::System, "forced_login_method = \"chatgpt\"\n")],
        );
        assert_eq!(chatgpt.refuses(Some("a"), Some("a")), None);
        assert_eq!(
            chatgpt.said(),
            [format!(
                "`forced_login_method` set to `chatgpt` in {}",
                etc("config.toml")
            )]
        );
    }

    // Codex 0.164.0's AuthManager leaves unused a login its requirements leave out, looking at
    // `tokens.account_id` first, and an empty list of workspaces allows none.
    #[test]
    fn codex_leaves_unused_what_its_requirements_leave_out() {
        let required = |text: &str| restricted(Os::Linux, &[(Layer::Required, text)]);
        let workspaces = required("allowed_chatgpt_workspaces = [\"a\"]\n");
        assert_eq!(workspaces.refuses(Some("b"), Some("a")), None);
        assert!(
            workspaces.refuses(Some("a"), Some("b")).is_some_and(
                |said| said.ends_with("this login is of `b`, so Codex does not use it")
            )
        );
        assert!(
            required("allowed_chatgpt_workspaces = []\n")
                .refuses(Some("a"), Some("a"))
                .is_some()
        );
        assert!(
            required("allowed_login_methods = [\"api\"]\n")
                .refuses(Some("a"), Some("a"))
                .is_some()
        );
        assert_eq!(
            required("allowed_login_methods = [\"api\", \"chatgpt\"]\n")
                .refuses(Some("a"), Some("a")),
            None
        );
        assert!(
            restricted(
                Os::Linux,
                &[(Layer::Own, "allowed_chatgpt_workspaces = [\"a\"]\n")]
            )
            .refuses(Some("b"), Some("b"))
            .is_none(),
            "a requirement in a file of configuration is none of Codex's"
        );
        let preference = restricted(
            Os::MacOs,
            &[
                (Layer::Required, "allowed_chatgpt_workspaces = [\"a\"]\n"),
                (
                    Layer::RequiredByPreference,
                    "allowed_chatgpt_workspaces = [\"b\"]\n",
                ),
            ],
        );
        assert_eq!(preference.refuses(Some("b"), Some("b")), None);
    }

    // Codex 0.164.0 does not start over any of these, so which logins it keeps is not known.
    #[test]
    fn a_restriction_codex_cannot_take_refuses_every_login() {
        for (layer, text) in [
            (Layer::Own, "forced_chatgpt_workspace_id = \"a,b\"\n"),
            (Layer::Own, "forced_chatgpt_workspace_id = 7\n"),
            (Layer::System, "forced_login_method = \"sso\"\n"),
            (Layer::Required, "allowed_login_methods = \"chatgpt\"\n"),
            (Layer::Required, "allowed_chatgpt_workspaces = [1]\n"),
            (Layer::Required, "allowed_chatgpt_workspaces = [\n"),
        ] {
            let found = restricted(Os::Linux, &[(layer, text)]);
            assert!(found.unreadable(), "{text}");
            assert!(
                found
                    .refuses(Some("a"), Some("a"))
                    .is_some_and(|said| said.contains("so Codex does not start")),
                "{text}"
            );
        }
    }

    #[test]
    fn the_file_store_alone_is_said_in_each_systems_words() {
        assert_eq!(
            file_store_only(Os::MacOs),
            "Pitboard handles Codex's file store, auth.json, and does not read an item Codex \
             created for itself, because every read would ask you for permission"
        );
        for os in [Os::Linux, Os::Windows] {
            assert_eq!(
                file_store_only(os),
                "Pitboard handles Codex's file store, auth.json, and does not follow Codex into \
                 a store it uses only when told to",
                "{os:?}"
            );
        }
    }
}