mbx 1.18.0

A build cache for Rust projects
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
//! Configuration, resolved from environment variables over optional files.
//!
//! Precedence is environment, then the workspace policy, then the platform
//! configuration file, then defaults.

use crate::util::parse_duration;
use bytesize::ByteSize;
use eyre::{Context, Result, bail};
use mbx_cache_core::{RemoteCacheMode, S3ConditionalWrites};
use std::collections::BTreeMap;
use std::path::{Component, Path, PathBuf};
use std::time::Duration;
use usage_config::{EnvLayer, FileLayer, FileScope, Layers};

const DEFAULT_HTTP_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_HTTP_DOWNLOAD_TIMEOUT: Duration = Duration::from_secs(600);
const DEFAULT_HTTP_READ_STALL_BUDGET: Duration = Duration::from_secs(90);
const DEFAULT_HTTP_RETRIES: i64 = 3;
const DEFAULT_GC_INTERVAL: Duration = Duration::from_secs(60 * 60);
/// How long a managed target directory may sit unused before collection.
const DEFAULT_TARGET_MAX_AGE: Duration = Duration::from_secs(30 * 24 * 60 * 60);

const GIB: u64 = 1024 * 1024 * 1024;

/// The largest the action-store budget nobody configured will grow to.
const MAX_STORE_BUDGET: u64 = 500 * GIB;

/// The largest the managed-target budget nobody configured will grow to.
const MAX_TARGET_BUDGET: u64 = 100 * GIB;
/// The largest learned-incremental budget nobody configured will grow to.
const MAX_INCREMENTAL_BUDGET: u64 = 100 * GIB;

/// Scaled budgets are rounded down to a multiple of this.
///
/// 5% of a disk is a number like 16.65GiB, which reads like a measurement
/// rather than a decision. Rounding down to whole increments makes the budget
/// mbx reports back look like something chosen on purpose, and never rounds a
/// budget up past the share it was allowed.
const BUDGET_INCREMENT: u64 = 5 * GIB;

/// A default budget as a share of the disk, bounded at both ends.
///
/// A budget nobody configured should be generous on a large disk and modest on
/// a small one, but neither unbounded nor uselessly tiny: the floor keeps a
/// small disk from a cache too small to hit in. Sizes are stated in IEC units
/// so they read the way `mbx gc` reports them back.
#[derive(Debug, Clone, Copy)]
struct ScaledBudget {
    /// Percent of the whole disk.
    percent: u64,
    floor: u64,
    ceiling: u64,
    /// Used when the disk cannot be measured. Guessing a disk size would be
    /// worse: this is the budget mbx shipped with before it scaled them.
    fallback: u64,
}

const STORE_BUDGET: ScaledBudget = ScaledBudget {
    percent: 5,
    floor: 5 * GIB,
    ceiling: MAX_STORE_BUDGET,
    fallback: 20 * GIB,
};

/// Twice the store's share: target directories hold the linked outputs of every
/// live checkout, and they are what fills a disk in practice.
const TARGET_BUDGET: ScaledBudget = ScaledBudget {
    percent: 10,
    floor: 10 * GIB,
    ceiling: MAX_TARGET_BUDGET,
    fallback: 30 * GIB,
};

/// Private incremental state is valuable to active edit loops but is not
/// shared, so it gets the action store's disk share with a larger floor.
const INCREMENTAL_BUDGET: ScaledBudget = ScaledBudget {
    percent: 5,
    floor: 10 * GIB,
    ceiling: MAX_INCREMENTAL_BUDGET,
    fallback: 20 * GIB,
};

impl ScaledBudget {
    fn resolve(self, disk_total_bytes: Option<u64>) -> u64 {
        let Some(total) = disk_total_bytes.filter(|total| *total > 0) else {
            return self.fallback;
        };
        let share = (total / 100).saturating_mul(self.percent);
        // Floors and the ceiling are whole increments themselves, so clamping
        // cannot reintroduce a ragged number.
        let whole = share - (share % BUDGET_INCREMENT);
        whole.clamp(self.floor, self.ceiling)
    }
}

/// Share of physical memory the compile scheduler budgets by default.
///
/// Deliberately less than the whole machine: the editor, the browser, and the
/// page cache are spending memory the budget cannot see, and a budget equal to
/// physical RAM would schedule compilations into exactly the pressure the
/// scheduler exists to avoid.
const SCHEDULER_MEMORY_PERCENT: u64 = 85;

/// Memory budget used when physical memory cannot be measured.
const SCHEDULER_MEMORY_FALLBACK: u64 = 16 * GIB;

/// The single declaration used to resolve and document mbx configuration.
#[derive(Debug, usage::Config)]
#[usage(file(
    path = "<config directory>/mbx/config.toml",
    scope = "global",
    format = "toml"
))]
pub(crate) struct RawConfig {
    /// Cache root. NFS is unsupported for local build storage.
    #[usage(env = "MBX_CACHE_DIR", default_note = "platform cache directory")]
    cache_dir: Option<PathBuf>,
    /// Persistent compiler shims. Containers sharing a cache should each use a
    /// private, dedicated local directory that survives builds and contains no real compilers.
    /// Relative paths use the cache root and cannot traverse above it with `..`
    /// or normalize to an empty path.
    #[usage(env = "MBX_SHIMS_DIR", default_note = "<cache_dir>/shims")]
    shims_dir: Option<PathBuf>,
    /// Write a JSON build report to this path.
    #[usage(env = "MBX_STATS_REPORT")]
    stats_report: Option<PathBuf>,
    /// Detail printed after a build. Auto uses an explanatory CI report in CI
    /// and one line locally; short, ci, full, and off select a fixed style.
    #[usage(
        env = "MBX_SUMMARY",
        default = "auto",
        choices("auto", "off", "short", "ci", "full")
    )]
    summary: String,
    /// Open the terminal warning browser after a successful Cargo build.
    #[usage(env = "MBX_PRETTY_INSPECT", default = false)]
    pretty_inspect: bool,
    /// Cargo display mode. Plain disables animated output even in a terminal.
    #[usage(env = "MBX_DISPLAY", default = "auto", choices("auto", "plain"))]
    display: String,
    /// Compile and consult the cache, then compare outputs.
    #[usage(env = "MBX_VERIFY", default = false, scope = "env")]
    verify: bool,
    /// Percentage of compilation identities to verify (0–100), selected deterministically.
    #[usage(env = "MBX_VERIFY_SAMPLE_RATE", default = 0)]
    verify_sample_rate: i64,
    /// Let local workspace members compile incrementally.
    #[usage(env = "MBX_INCREMENTAL", default = false)]
    incremental: bool,
    /// Compile crates that keep missing the cache with changed content
    /// incrementally, keeping their outputs out of the shared cache.
    #[usage(
        key = "learned_incremental",
        env = "MBX_LEARNED_INCREMENTAL",
        default = true
    )]
    _learned_incremental: bool,
    /// How much learned incremental state one crate may keep, or "none". State
    /// past this is discarded before the crate compiles again.
    #[usage(
        key = "learned_incremental_max_size",
        env = "MBX_LEARNED_INCREMENTAL_MAX_SIZE",
        default = "8GiB"
    )]
    learned_incremental_max_size: String,
    /// How much per-compilation history one build may record, or "none" for no
    /// limit. Past this the counters carry on but the rows stop, and
    /// `mbx explain` says so.
    #[usage(
        key = "events_max_size",
        env = "MBX_EVENTS_MAX_SIZE",
        default = "16MiB"
    )]
    events_max_size: String,
    /// Reuse Rust compilations across checkouts with matching build-script
    /// output by giving rustc a shared, content-addressed `OUT_DIR` under the
    /// cache. Also remap generated source paths in Rust and C/C++ debug
    /// information. Disable to preserve Cargo's original `OUT_DIR` and paths.
    #[usage(env = "MBX_SHARE_OUT_DIR", default = true)]
    share_out_dir: bool,
    /// Remap the workspace root so rustc does not record which checkout a
    /// compilation ran in, which lets a crate rebuilt in a second checkout come
    /// out byte-identical so its dependents still share. Source paths in debug
    /// information and panic messages then name a placeholder. This may also be
    /// set in workspace `.mbx.toml`; the environment variable wins.
    #[usage(env = "MBX_SHARE_WORKSPACE_ROOT", default = false)]
    share_workspace_root: bool,
    /// Restore cached outputs by hard link when the filesystem cannot clone
    /// them, instead of copying their bytes. Filesystems with clone support
    /// (APFS, Btrfs, XFS with reflink, ZFS) are unaffected: they clone either
    /// way. Elsewhere -- ext4 above all -- this is the difference between a
    /// restore that writes nothing and one that writes every cached byte.
    /// A hard-linked output is the store's object, so it is read-only; mbx
    /// unlinks it before a compiler rewrites it, but `cargo` run directly in
    /// the same target directory reports that the output is not writeable.
    /// Disable to give every restored output a file of its own.
    #[usage(env = "MBX_RESTORE_HARDLINK", default = true)]
    restore_hardlink: bool,
    /// Cache executions of build scripts using Cargo's freshness inputs. This may
    /// also be set in workspace `.mbx.toml`; the environment variable wins.
    #[usage(env = "MBX_BUILD_SCRIPT_EXECUTION", default = true)]
    build_script_execution: bool,
    /// Record a per-compilation event stream for `mbx tui` to watch.
    #[usage(env = "MBX_EVENTS", default = true)]
    events: bool,
    /// Cache C and C++ compilations run by build scripts.
    #[usage(env = "MBX_CC", default = true)]
    cc: bool,
    /// Store C objects that embed absolute paths under checkout-specific keys.
    /// Disable for disposable worktrees to avoid storing objects that cannot be
    /// reused at another path. Existing entries may still be restored.
    #[usage(env = "MBX_CC_STORE_PATH_SPECIFIC", default = true)]
    cc_store_path_specific: bool,
    /// Set `ZERO_AR_DATE` for build scripts so native archives stop embedding a
    /// timestamp. Without it, tools like CMake's `ar` rewrite an archive's
    /// header on every build, moving its digest and missing every cached action
    /// downstream even when no member changed. Auto normalizes every profile
    /// except `release`, leaving published artifacts byte-for-byte as the host
    /// toolchain made them; always covers `release` too; off leaves the
    /// toolchain alone. A `ZERO_AR_DATE` you set yourself always wins.
    #[usage(
        env = "MBX_AR_DETERMINISM",
        default = "auto",
        choices("auto", "always", "off")
    )]
    ar_determinism: String,
    /// Forward rustc's diagnostics and artifact notifications to Cargo as the
    /// compiler prints them, so Cargo can start a dependent against this
    /// crate's metadata while its code generation continues. Turn it off to
    /// hold the compiler's output until mbx has stored the result, which is
    /// useful when diagnosing the shim itself.
    #[usage(env = "MBX_FORWARD_COMPILER_NOTIFICATIONS", default = true)]
    forward_compiler_notifications: bool,
    /// How the savings line after a build reads.
    #[usage(
        env = "MBX_SAVINGS",
        default = "quips",
        choices("quips", "plain", "off")
    )]
    savings: String,
    /// Cache natively linked test binaries, executables, and proc macros. On macOS this
    /// also passes ld64 `-oso_prefix` so a debug-info link's debug map stops
    /// naming this checkout, which is what lets it cache. Supported on Linux,
    /// macOS, and Windows; a link mbx cannot describe exactly still links normally.
    #[usage(
        key = "cache_links",
        env = "MBX_CACHE_LINKS",
        default = true,
        scope = "env"
    )]
    cache_links: bool,
    /// Append the full reason for every bypassed compilation to this path.
    #[usage(key = "bypass_log", env = "MBX_BYPASS_LOG", scope = "env")]
    _bypass_log: Option<PathBuf>,
    /// Log filter such as `debug` or `mbx=trace`. It covers every log the mbx
    /// process emits, its own and those of the libraries it builds on. The
    /// default keeps the pty library behind the inline build view quiet,
    /// because mbx falls back to plain Cargo when that view cannot start.
    #[usage(
        key = "log",
        env = "MBX_LOG",
        default = "info,portable_pty=off",
        scope = "env"
    )]
    _log: String,
    #[usage(flatten)]
    remote: RawRemote,
    #[usage(flatten)]
    http: RawHttp,
    #[usage(flatten)]
    gc: RawGc,
    #[usage(flatten)]
    target: RawTarget,
    #[usage(flatten)]
    scheduler: RawScheduler,
    #[usage(flatten)]
    linker: RawLinker,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "linker")]
struct RawLinker {
    /// Linker used when the active Cargo profile has no matching selection.
    #[usage(default = "system")]
    default: String,
    /// Linkers selected by Cargo profile and target triple.
    profiles: Option<BTreeMap<String, BTreeMap<String, String>>>,
    /// Override the configured linker for this invocation.
    #[usage(key = "selection", env = "MBX_LINKER", scope = "env")]
    _selection: Option<String>,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "scheduler")]
struct RawScheduler {
    /// Coordinate real compilations machine-wide through a permit pool.
    #[usage(env = "MBX_SCHEDULER", default = true)]
    enabled: bool,
    /// Machine-wide concurrent compile permits.
    #[usage(env = "MBX_SCHEDULER_CPUS", default_note = "logical CPUs")]
    cpus: Option<i64>,
    /// Logical CPUs to leave free for the rest of the machine.
    #[usage(env = "MBX_SCHEDULER_RESERVE_CPUS", default = 0)]
    reserve_cpus: i64,
    /// Memory budget the permits divide, or "none" for plain CPU permits.
    #[usage(env = "MBX_SCHEDULER_MEMORY", default_note = "85% of physical memory")]
    memory: Option<String>,
    /// Permit priority of this build's compilations.
    #[usage(
        env = "MBX_SCHEDULER_PRIORITY",
        default = "normal",
        choices("normal", "low")
    )]
    priority: String,
    /// Delay additional compilations while the machine is under memory pressure.
    #[usage(env = "MBX_SCHEDULER_PRESSURE", default = true)]
    pressure: bool,
    /// Experimentally suspend Linux compiler trees under memory pressure.
    #[usage(env = "MBX_SCHEDULER_SUSPEND", default = false)]
    suspend: bool,
    /// Writable delegated cgroup v2 directory for compiler supervision.
    #[usage(env = "MBX_SCHEDULER_CGROUP_ROOT")]
    cgroup_root: Option<PathBuf>,
    /// Run `cargo test` binaries under the same permit pool.
    #[usage(env = "MBX_SCHEDULER_TESTS", default = false)]
    tests: bool,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "remote")]
struct RawRemote {
    /// Remote cache URL.
    #[usage(env = "MBX_REMOTE_URL", ty = "url")]
    url: Option<String>,
    /// Remote namespace; required when a URL is configured.
    #[usage(env = "MBX_REMOTE_NAMESPACE")]
    namespace: Option<String>,
    /// Bearer token for the remote cache.
    #[usage(env = "MBX_REMOTE_TOKEN")]
    token: Option<String>,
    /// File containing a bearer token.
    #[usage(env = "MBX_REMOTE_TOKEN_FILE")]
    token_file: Option<PathBuf>,
    /// CI OIDC audience.
    #[usage(env = "MBX_REMOTE_OIDC_AUDIENCE")]
    oidc_audience: Option<String>,
    /// Remote access mode.
    #[usage(
        env = "MBX_REMOTE_MODE",
        default = "read-write",
        choices("read-write", "read-only", "write-only")
    )]
    mode: String,
    /// S3 endpoint for a store that is not AWS, such as MinIO or R2.
    #[usage(env = "MBX_REMOTE_S3_ENDPOINT", ty = "url")]
    s3_endpoint: Option<String>,
    /// S3 region; Cloudflare R2 uses "auto".
    #[usage(env = "MBX_REMOTE_S3_REGION")]
    s3_region: Option<String>,
    /// Address S3 buckets in the path rather than the host.
    #[usage(env = "MBX_REMOTE_S3_FORCE_PATH_STYLE")]
    s3_force_path_style: Option<bool>,
    /// How to treat an S3 store that does not implement conditional writes.
    #[usage(
        env = "MBX_REMOTE_S3_CONDITIONAL_WRITES",
        default = "auto",
        choices("auto", "required", "off")
    )]
    s3_conditional_writes: String,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "target")]
struct RawTarget {
    /// Let mbx place eligible target directories under the managed root.
    #[usage(env = "MBX_TARGET_VIEWS", default = true)]
    views: bool,
    /// Copy registry build units from another checkout's managed target into
    /// a profile this checkout has not built yet (Cargo 1.100 or later).
    #[usage(env = "MBX_TARGET_SEED", default = true)]
    seed: bool,
    /// Managed target root. NFS is unsupported for build outputs.
    #[usage(env = "MBX_TARGET_ROOT", default_note = "<cache_dir>/targets")]
    root: Option<PathBuf>,
    /// Managed-target budget, or "none". Live views are collected oldest-first.
    #[usage(
        env = "MBX_TARGET_MAX_SIZE",
        default_note = "10% of the cache disk, from 10GiB to 100GiB"
    )]
    max_size: Option<String>,
    /// Collect live managed targets, and build units inside them, unused this
    /// long, or "none".
    #[usage(env = "MBX_TARGET_MAX_AGE", default = "30d", ty = "duration")]
    max_age: String,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "gc")]
struct RawGc {
    /// Sweep after a build when collection is due.
    #[usage(env = "MBX_GC_AUTO", default = true)]
    auto: bool,
    /// Action-store and per-session remote-download budget.
    #[usage(
        env = "MBX_GC_MAX_SIZE",
        default_note = "5% of the cache disk, from 5GiB to 500GiB"
    )]
    max_size: Option<String>,
    /// Combined action-store, managed-target, and learned-incremental budget,
    /// or "none".
    #[usage(env = "MBX_GC_MAX_TOTAL_SIZE")]
    max_total_size: Option<String>,
    /// Aggregate learned-incremental budget, or "none". Inactive checkouts are
    /// collected oldest-first while the most recently used checkout is kept.
    #[usage(
        env = "MBX_GC_INCREMENTAL_MAX_SIZE",
        default_note = "5% of the cache disk, from 10GiB to 100GiB"
    )]
    incremental_max_size: Option<String>,
    /// Collect learned incremental state unused this long, or "none".
    #[usage(env = "MBX_GC_INCREMENTAL_MAX_AGE", default = "30d", ty = "duration")]
    incremental_max_age: String,
    /// Minimum interval between automatic sweeps.
    #[usage(env = "MBX_GC_INTERVAL", default = "1h", ty = "duration")]
    interval: String,
}

#[derive(Debug, usage::Config)]
#[usage(prefix = "http")]
struct RawHttp {
    /// Connect and request timeout.
    #[usage(env = "MBX_HTTP_TIMEOUT", default = "30s", ty = "duration")]
    timeout: String,
    /// Deadline for one blob download, retries and backoff included.
    #[usage(env = "MBX_HTTP_DOWNLOAD_TIMEOUT", default = "10m", ty = "duration")]
    download_timeout: String,
    /// Wall clock a build may lose to failed remote reads before it stops
    /// reading and just compiles. "0" keeps reading however long it takes.
    #[usage(env = "MBX_HTTP_READ_STALL_BUDGET", default = "90s", ty = "duration")]
    read_stall_budget: String,
    /// Request retries.
    #[usage(env = "MBX_HTTP_RETRIES", default = 3)]
    retries: i64,
}

#[derive(Debug, Clone)]
pub struct Config {
    pub cache_dir: PathBuf,
    /// Persistent executable wrappers, separate from shared build artifacts.
    pub shims_dir: PathBuf,
    pub stats_report: Option<PathBuf>,
    pub verify: bool,
    pub verify_sample_rate: u8,
    /// Let cargo compile workspace members incrementally, rather than forcing
    /// `CARGO_INCREMENTAL=0` for the whole build.
    pub incremental: bool,
    /// Share compilations that read `OUT_DIR` between checkouts.
    ///
    /// Enabled by default. When the source scan finds `OUT_DIR`, rustc receives
    /// a copy of the build-script output under the cache, in a directory named
    /// for its contents. Matching output trees give rustc the same path across
    /// checkouts, allowing a cache hit when the other inputs also match.
    /// Different output trees use different paths and cache keys. If the scan
    /// misses the reference or the output cannot be copied, rustc keeps Cargo's
    /// original `OUT_DIR`.
    ///
    /// Also remap generated source paths in Rust and C/C++ debug information.
    /// Disabling this preserves Cargo's original `OUT_DIR` and literal paths,
    /// so Rust compilations that read `OUT_DIR` remain checkout-specific.
    pub share_out_dir: bool,
    /// Restore cached outputs by hard link where the filesystem cannot clone
    /// them.
    ///
    /// Reflinks are always preferred: a cloned output is its own inode and
    /// behaves like a copy that happened to be cheap. A hard link is the store
    /// object itself, so it is read-only and every checkout holding one shares
    /// its modification time. That is a narrower guarantee, and on a
    /// filesystem without clone support it is the only alternative to writing
    /// every restored byte.
    pub restore_hardlink: bool,
    /// Remap the workspace root so rustc does not record the checkout a
    /// compilation ran in.
    ///
    /// Off by default. Cargo gives rustc the crate's own directory to work in,
    /// and rustc records it, so a workspace member rebuilt in a second checkout
    /// produces a different artifact even when everything it read was the same
    /// -- and every crate above it rebuilds with it. Remapping the root removes
    /// that difference, at the cost of naming a placeholder wherever a source
    /// path is recorded: debug information, `file!()`, and panic locations.
    pub share_workspace_root: bool,
    /// Cache build-script execution when the script declares rerun inputs.
    pub build_script_execution: bool,
    /// Append a per-compilation event stream to the store, for `mbx tui`.
    ///
    /// On by default: one small buffered append per accounted compilation, with
    /// no flush of its own, against a compile or restore measured in
    /// milliseconds. Turn it off to keep the store free of build history.
    pub events: bool,
    /// Point build scripts at a caching `CC` and `CXX`.
    ///
    /// On by default: the shim never changes the compilation, and anything it
    /// cannot model exactly bypasses to the real compiler.
    pub cc: bool,
    /// Store path-specific C outputs for reuse at the same checkout path.
    pub cc_store_path_specific: bool,
    /// When to normalize native archive timestamps for build scripts.
    pub ar_determinism: String,
    /// Forward the compiler's diagnostics and artifact notifications as they
    /// arrive instead of after the result is stored.
    ///
    /// On by default. Cargo reads the metadata notification from rustc's
    /// standard error and starts dependents against the `.rmeta` right away,
    /// which the shim would otherwise delay until publication finished. The
    /// bytes are still captured for the cache entry and for verification.
    pub forward_compiler_notifications: bool,
    pub remote: RemoteSettings,
    pub http: HttpSettings,
    pub gc: GcSettings,
    pub target: TargetSettings,
    pub scheduler: SchedulerSettings,
    pub linker: LinkerSettings,
}

/// Linker selectors keyed first by Cargo profile, then by target triple.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LinkerSettings {
    pub default: String,
    pub profiles: BTreeMap<String, BTreeMap<String, String>>,
}

impl Default for LinkerSettings {
    fn default() -> Self {
        Self {
            default: "system".into(),
            profiles: BTreeMap::new(),
        }
    }
}

impl LinkerSettings {
    pub(crate) fn for_build(&self, profile: &str, target: Option<&str>) -> Option<String> {
        let selections = self.selections(profile)?;
        target
            .and_then(|target| selections.get(target))
            .or_else(|| selections.get("default"))
            .cloned()
    }

    /// The profile's selector table. Cargo 1.99's built-in `debug` profile
    /// inherits `dev`, so it uses the `dev` table unless it has its own.
    pub(crate) fn selections(&self, profile: &str) -> Option<&BTreeMap<String, String>> {
        self.profiles.get(profile).or_else(|| {
            (profile == "debug")
                .then(|| self.profiles.get("dev"))
                .flatten()
        })
    }
}

impl Config {
    /// A configuration with everything defaulted, for tests that care about one
    /// setting and should not have to spell out the rest.
    #[cfg(test)]
    pub fn for_test(cache_dir: &std::path::Path) -> Self {
        Self {
            cache_dir: cache_dir.to_path_buf(),
            shims_dir: cache_dir.join("shims"),
            stats_report: None,
            verify: false,
            verify_sample_rate: 0,
            incremental: false,
            share_out_dir: false,
            restore_hardlink: true,
            share_workspace_root: false,
            build_script_execution: false,
            events: false,
            // Off like the rest: a test that says nothing about C compilation
            // should not have compiler shims installed underneath it.
            cc: false,
            cc_store_path_specific: true,
            ar_determinism: "auto".into(),
            forward_compiler_notifications: true,
            remote: Default::default(),
            http: Default::default(),
            gc: Default::default(),
            target: TargetSettings {
                views: true,
                seed: false,
                root: cache_dir.join("targets"),
            },
            scheduler: Default::default(),
            linker: Default::default(),
        }
    }
}

/// How real compilations draw from the machine-wide permit pool.
#[derive(Debug, Clone)]
pub struct SchedulerSettings {
    /// Whether compilations take permits at all.
    pub enabled: bool,
    /// Machine-wide concurrent compile permits.
    pub cpus: u64,
    /// Permits withheld from the configured CPU count.
    pub reserve_cpus: u64,
    /// Memory the permits divide; `None` leaves plain CPU permits.
    pub memory_bytes: Option<u64>,
    /// Priority of this build's compilations against other builds.
    pub priority: SchedulerPriority,
    /// Whether `cargo test` binaries take permits too.
    pub tests: bool,
    /// Gate new compilations on live memory pressure.
    pub pressure: bool,
    /// Opt in to Linux compiler supervision and suspension.
    pub suspend: bool,
    /// An explicitly delegated cgroup v2 directory.
    pub cgroup_root: Option<PathBuf>,
}

impl SchedulerSettings {
    /// Compile permits left after preserving capacity for interactive work.
    pub(crate) fn permits(&self) -> u64 {
        self.cpus.saturating_sub(self.reserve_cpus).max(1)
    }
}

/// The scheduling a hand-built `Config` gets: none.
///
/// Deliberately not the declared configuration default, which is enabled. A
/// `Config` assembled in code rather than resolved from the environment has
/// not been told where a machine-wide pool should live or how large the
/// machine is, and guessing would have tests and embedders contending over a
/// real pool they never asked for. Resolution always states every field.
impl Default for SchedulerSettings {
    fn default() -> Self {
        Self {
            enabled: false,
            cpus: 1,
            reserve_cpus: 0,
            memory_bytes: None,
            priority: SchedulerPriority::Normal,
            tests: false,
            pressure: false,
            suspend: false,
            cgroup_root: None,
        }
    }
}

/// Whose compilations wait when the machine is contended.
///
/// `Low` is for builds nobody is sitting at -- CI on a shared box, an editor's
/// background check -- which leave a share of the permit pool free whenever a
/// normal-priority build is waiting for it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SchedulerPriority {
    #[default]
    Normal,
    Low,
}

impl SchedulerPriority {
    /// The spelling the configuration and the session environment use.
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Normal => "normal",
            Self::Low => "low",
        }
    }
}

impl std::str::FromStr for SchedulerPriority {
    type Err = eyre::Report;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "normal" => Ok(Self::Normal),
            "low" => Ok(Self::Low),
            other => Err(eyre::eyre!("priority must be normal or low, not {other:?}")),
        }
    }
}

#[derive(Debug, Clone, Default)]
pub struct RemoteSettings {
    pub url: Option<String>,
    pub namespace: Option<String>,
    pub token: Option<String>,
    pub token_file: Option<PathBuf>,
    pub oidc_audience: Option<String>,
    pub mode: RemoteCacheMode,
    pub s3_endpoint: Option<String>,
    pub s3_region: Option<String>,
    pub s3_force_path_style: Option<bool>,
    pub s3_conditional_writes: S3ConditionalWrites,
}

#[derive(Debug, Clone)]
pub struct HttpSettings {
    pub timeout: Duration,
    pub download_timeout: Duration,
    pub read_stall_budget: Duration,
    pub retries: i64,
}

/// Where build outputs are written, and whether mbx places them.
#[derive(Debug, Clone)]
pub struct TargetSettings {
    pub views: bool,
    pub seed: bool,
    pub root: PathBuf,
}

/// How the store is kept inside its budget.
#[derive(Debug, Clone)]
pub struct GcSettings {
    pub auto: bool,
    pub max_bytes: u64,
    pub interval: Duration,
}

#[derive(Debug, Clone)]
pub(crate) struct RetentionSettings {
    pub target_max_bytes: Option<u64>,
    pub target_max_age: Option<Duration>,
    pub incremental_max_bytes: Option<u64>,
    pub incremental_max_age: Option<Duration>,
    pub max_total_bytes: Option<u64>,
}

/// Settings only the command line consumes.
///
/// The library target is semver-checked, and `Config` is a public struct
/// callers can construct, so a knob the binary alone reads does not belong on
/// it: adding a field there is a breaking change to an API this crate does not
/// mean to offer.
/// The declared default of `learned_incremental_max_size`.
///
/// A crate's incremental state is roughly proportional to the crate, not to
/// how often it is edited, because rustc discards superseded sessions itself.
/// A large workspace binary with line tables keeps a few GiB, so the budget is
/// generous enough that ordinary crates never hit it; discarding state on
/// every edit would silently turn the edit loop back into full recompilation.
pub(crate) const DEFAULT_LEARNED_INCREMENTAL_MAX_SIZE: u64 = 8 * 1024 * 1024 * 1024;

/// The declared default of `events_max_size`.
///
/// The cap exists so the TUI can read a session's tail without reading a
/// build-sized file first. A row carrying key details runs to several KiB, so a
/// large workspace reaches this partway through a build and keeps only the part
/// that fit -- enough for the TUI, and raisable for anyone diagnosing a miss
/// with `mbx explain`.
pub(crate) const DEFAULT_EVENTS_MAX_SIZE: u64 = 16 * 1024 * 1024;

#[derive(Debug, Clone)]
pub(crate) struct CliSettings {
    pub retention: RetentionSettings,
    pub savings: SavingsStyle,
    pub summary: SummaryStyle,
    pub pretty_inspect: bool,
    pub plain_output: bool,
    /// Whether a churning crate may compile with its own incremental state.
    pub learned_incremental: bool,
    /// How much of that state one crate may keep, in bytes; `None` is no limit.
    pub learned_incremental_max_size: Option<u64>,
    /// Whether natively linked programs may be cached.
    pub cache_links: bool,
    /// How many bytes of per-compilation rows one build may record; `None` is
    /// no limit.
    pub events_max_size: Option<u64>,
}

/// Matches the declared defaults: a derived `Default` would silence the savings
/// line, which is the opposite of what an unconfigured machine should get.
impl Default for CliSettings {
    fn default() -> Self {
        Self {
            retention: RetentionSettings::default(),
            savings: SavingsStyle::default(),
            summary: SummaryStyle::default(),
            pretty_inspect: false,
            plain_output: false,
            learned_incremental: true,
            learned_incremental_max_size: Some(DEFAULT_LEARNED_INCREMENTAL_MAX_SIZE),
            cache_links: true,
            events_max_size: Some(DEFAULT_EVENTS_MAX_SIZE),
        }
    }
}

/// How much of the per-build cache summary is printed.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum SummaryStyle {
    #[default]
    Auto,
    Off,
    Short,
    Ci,
    Full,
}

impl SummaryStyle {
    /// Select the environment's default report while preserving explicit styles.
    pub(crate) fn resolve(self, ci: bool) -> Self {
        match self {
            Self::Auto if ci => Self::Ci,
            Self::Auto => Self::Short,
            style => style,
        }
    }
}

impl std::str::FromStr for SummaryStyle {
    type Err = eyre::Report;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "auto" => Ok(Self::Auto),
            "off" => Ok(Self::Off),
            "short" => Ok(Self::Short),
            "ci" => Ok(Self::Ci),
            "full" => Ok(Self::Full),
            other => Err(eyre::eyre!(
                "summary must be auto, off, short, ci, or full, not {other:?}"
            )),
        }
    }
}

/// How the line about accumulated savings reads.
///
/// The quips are the product's voice and the default; `plain` is the same
/// facts in the register of the `mbx[cache]:` and `mbx[gc]:` lines beside them, for
/// people who want their build logs to keep a straight face; `off` keeps the
/// totals without printing anything.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub(crate) enum SavingsStyle {
    #[default]
    Quips,
    Plain,
    Off,
}

impl std::str::FromStr for SavingsStyle {
    type Err = eyre::Report;

    fn from_str(value: &str) -> Result<Self> {
        match value {
            "quips" => Ok(Self::Quips),
            "plain" => Ok(Self::Plain),
            "off" => Ok(Self::Off),
            other => Err(eyre::eyre!(
                "savings must be quips, plain, or off, not {other:?}"
            )),
        }
    }
}

/// The retention a run gets when nobody resolved configuration for it.
///
/// These are the unmeasured fallbacks rather than the disk-scaled budgets: a
/// `Default` cannot probe a disk it has not been told about. Collection still
/// happens, which is the property that matters -- a default that pruned nothing
/// would make every unconfigured path a leak.
impl Default for RetentionSettings {
    fn default() -> Self {
        Self {
            target_max_bytes: Some(TARGET_BUDGET.fallback),
            target_max_age: Some(DEFAULT_TARGET_MAX_AGE),
            incremental_max_bytes: Some(INCREMENTAL_BUDGET.fallback),
            incremental_max_age: Some(DEFAULT_TARGET_MAX_AGE),
            max_total_bytes: None,
        }
    }
}

impl Default for GcSettings {
    fn default() -> Self {
        Self {
            auto: true,
            max_bytes: STORE_BUDGET.fallback,
            interval: DEFAULT_GC_INTERVAL,
        }
    }
}

impl Default for HttpSettings {
    fn default() -> Self {
        Self {
            timeout: DEFAULT_HTTP_TIMEOUT,
            download_timeout: DEFAULT_HTTP_DOWNLOAD_TIMEOUT,
            read_stall_budget: DEFAULT_HTTP_READ_STALL_BUDGET,
            retries: DEFAULT_HTTP_RETRIES,
        }
    }
}

impl Config {
    /// Load configuration for this machine.
    pub fn load() -> Result<Self> {
        Self::load_for_cli().map(|(config, _)| config)
    }

    pub(crate) fn load_for_cli() -> Result<(Self, CliSettings)> {
        let env = EnvLayer::from_process();
        let file = config_file_path().map(|path| FileLayer::at(path, FileScope::Global));
        Self::from_layers_for_cli(&env, file.as_ref())
    }

    fn from_layers_for_cli(
        env: &EnvLayer,
        file: Option<&FileLayer>,
    ) -> Result<(Self, CliSettings)> {
        Self::from_layers_measuring(
            env,
            file,
            crate::util::disk_total_bytes,
            crate::util::memory_total_bytes,
        )
    }

    fn from_layers_measuring(
        env: &EnvLayer,
        file: Option<&FileLayer>,
        measure_disk: impl Fn(&Path) -> Option<u64>,
        measure_memory: impl Fn() -> Option<u64>,
    ) -> Result<(Self, CliSettings)> {
        let mut layers = Layers::new().then(env);
        if let Some(file) = file {
            layers = layers.then(file);
        }
        let resolved = usage_config::resolve(RawConfig::SETTINGS_REGISTRY, layers)?;
        if !resolved.warnings.is_empty() {
            let problems = resolved
                .warnings
                .iter()
                .map(|warning| match &warning.origin {
                    Some(origin) => format!("{} ({})", warning.message, origin.describe()),
                    None => warning.message.clone(),
                })
                .collect::<Vec<_>>()
                .join("\n");
            bail!("invalid configuration:\n{problems}");
        }
        let raw = RawConfig::read(&resolved)?;
        Self::from_raw_measuring(raw, measure_disk, measure_memory)
    }

    /// Resolve settings, measuring the machine with the given probes.
    ///
    /// The probes are parameters so tests can state a disk or memory size
    /// rather than asserting against whatever machine happens to run them.
    fn from_raw_measuring(
        raw: RawConfig,
        measure_disk: impl Fn(&Path) -> Option<u64>,
        measure_memory: impl Fn() -> Option<u64>,
    ) -> Result<(Self, CliSettings)> {
        let cache_dir = raw.cache_dir.or_else(default_cache_dir).ok_or_else(|| {
            eyre::eyre!("could not determine a cache directory; set MBX_CACHE_DIR")
        })?;
        let shims_dir = match raw.shims_dir {
            Some(directory) if directory.is_absolute() => directory,
            Some(directory) => {
                let mut relative = PathBuf::new();
                for component in directory.components() {
                    match component {
                        Component::Normal(part) => relative.push(part),
                        Component::CurDir => (),
                        Component::ParentDir if relative.pop() => (),
                        _ => bail!(
                            "invalid shims_dir: relative paths must stay beneath cache_dir; \
                             use an absolute path for a directory outside the cache"
                        ),
                    }
                }
                if relative.as_os_str().is_empty() {
                    bail!(
                        "invalid shims_dir: relative paths must name a directory beneath cache_dir"
                    );
                }
                cache_dir.join(relative)
            }
            None => cache_dir.join("shims"),
        };
        let target_root = match raw.target.root {
            Some(root) if root.is_absolute() => root,
            Some(root) => cache_dir.join(root),
            None => cache_dir.join("targets"),
        };
        let store_budget = raw
            .gc
            .max_size
            .as_deref()
            .map(parse_store_budget)
            .transpose()
            .wrap_err("invalid gc.max_size")?;
        let target_budget = raw
            .target
            .max_size
            .as_deref()
            .map(parse_optional_byte_size)
            .transpose()
            .wrap_err("invalid target.max_size")?;
        let incremental_budget = raw
            .gc
            .incremental_max_size
            .as_deref()
            .map(parse_optional_byte_size)
            .transpose()
            .wrap_err("invalid gc.incremental_max_size")?;
        // Measured only where a budget actually needs scaling, so a fully
        // configured machine pays for no syscall at all. The two budgets are
        // measured separately because `target.root` can be on another volume,
        // and sizing a 4TB scratch disk from a 128GB home directory would prune
        // it to the floor.
        let store_disk = (store_budget.is_none() || incremental_budget.is_none())
            .then(|| measure_disk(&cache_dir))
            .flatten();
        let target_disk = target_budget
            .is_none()
            .then(|| measure_disk(&target_root))
            .flatten();
        let retention = RetentionSettings {
            target_max_bytes: target_budget
                .unwrap_or_else(|| Some(TARGET_BUDGET.resolve(target_disk))),
            target_max_age: parse_optional_duration(&raw.target.max_age)
                .wrap_err("invalid target.max_age")?,
            incremental_max_bytes: incremental_budget
                .unwrap_or_else(|| Some(INCREMENTAL_BUDGET.resolve(store_disk))),
            incremental_max_age: parse_optional_duration(&raw.gc.incremental_max_age)
                .wrap_err("invalid gc.incremental_max_age")?,
            max_total_bytes: raw
                .gc
                .max_total_size
                .as_deref()
                .map(parse_optional_byte_size)
                .transpose()
                .wrap_err("invalid gc.max_total_size")?
                .flatten(),
        };
        let mode = raw.remote.mode.parse().wrap_err("invalid remote.mode")?;
        let s3_conditional_writes = raw
            .remote
            .s3_conditional_writes
            .parse()
            .wrap_err("invalid remote.s3_conditional_writes")?;
        let http = HttpSettings {
            timeout: parse_duration(&raw.http.timeout).wrap_err("invalid http.timeout")?,
            download_timeout: parse_duration(&raw.http.download_timeout)
                .wrap_err("invalid http.download_timeout")?,
            read_stall_budget: parse_duration(&raw.http.read_stall_budget)
                .wrap_err("invalid http.read_stall_budget")?,
            retries: raw.http.retries,
        };
        let gc = GcSettings {
            auto: raw.gc.auto,
            max_bytes: store_budget.unwrap_or_else(|| STORE_BUDGET.resolve(store_disk)),
            interval: parse_duration(&raw.gc.interval).wrap_err("invalid gc.interval")?,
        };
        let target = TargetSettings {
            views: raw.target.views,
            seed: raw.target.seed,
            root: target_root,
        };
        let scheduler_cpus = match raw.scheduler.cpus {
            Some(cpus) => u64::try_from(cpus)
                .ok()
                .filter(|cpus| *cpus > 0)
                .ok_or_else(|| eyre::eyre!("invalid scheduler.cpus: must be a positive count"))?,
            None => std::thread::available_parallelism().map_or(1, |cpus| cpus.get() as u64),
        };
        let scheduler_reserve_cpus = u64::try_from(raw.scheduler.reserve_cpus).map_err(|_| {
            eyre::eyre!("invalid scheduler.reserve_cpus: must be a non-negative count")
        })?;
        let scheduler_memory = match raw.scheduler.memory.as_deref() {
            Some(value) => parse_optional_byte_size(value).wrap_err("invalid scheduler.memory")?,
            // Measured only when the scheduler would use the answer, like the
            // disk budgets above.
            None => Some(
                raw.scheduler
                    .enabled
                    .then(&measure_memory)
                    .flatten()
                    .map_or(SCHEDULER_MEMORY_FALLBACK, |total| {
                        total / 100 * SCHEDULER_MEMORY_PERCENT
                    }),
            ),
        };
        let scheduler = SchedulerSettings {
            enabled: raw.scheduler.enabled,
            cpus: scheduler_cpus,
            reserve_cpus: scheduler_reserve_cpus,
            memory_bytes: scheduler_memory,
            priority: raw
                .scheduler
                .priority
                .parse()
                .wrap_err("invalid scheduler.priority")?,
            tests: raw.scheduler.tests,
            pressure: raw.scheduler.pressure,
            suspend: raw.scheduler.suspend,
            cgroup_root: raw.scheduler.cgroup_root,
        };
        let config = Self {
            cache_dir,
            shims_dir,
            gc,
            target,
            scheduler,
            linker: LinkerSettings {
                default: raw.linker.default,
                profiles: raw.linker.profiles.unwrap_or_default(),
            },
            stats_report: raw.stats_report,
            verify: raw.verify,
            verify_sample_rate: u8::try_from(raw.verify_sample_rate)
                .ok()
                .filter(|rate| *rate <= 100)
                .ok_or_else(|| eyre::eyre!("invalid verify_sample_rate: expected 0–100"))?,
            incremental: raw.incremental,
            share_out_dir: raw.share_out_dir,
            restore_hardlink: raw.restore_hardlink,
            share_workspace_root: raw.share_workspace_root,
            build_script_execution: raw.build_script_execution,
            events: raw.events,
            cc: raw.cc,
            cc_store_path_specific: raw.cc_store_path_specific,
            ar_determinism: raw.ar_determinism,
            forward_compiler_notifications: raw.forward_compiler_notifications,
            remote: RemoteSettings {
                url: raw.remote.url,
                namespace: raw.remote.namespace,
                token: raw.remote.token,
                token_file: raw.remote.token_file,
                oidc_audience: raw.remote.oidc_audience,
                mode,
                s3_endpoint: raw.remote.s3_endpoint,
                s3_region: raw.remote.s3_region,
                s3_force_path_style: raw.remote.s3_force_path_style,
                s3_conditional_writes,
            },
            http,
        };
        Ok((
            config,
            CliSettings {
                retention,
                savings: raw.savings.parse().wrap_err("invalid savings")?,
                summary: raw.summary.parse().wrap_err("invalid summary")?,
                pretty_inspect: raw.pretty_inspect,
                plain_output: raw.display == "plain",
                learned_incremental: raw._learned_incremental,
                learned_incremental_max_size: parse_optional_byte_size(
                    &raw.learned_incremental_max_size,
                )
                .wrap_err("invalid learned_incremental_max_size")?,
                cache_links: raw.cache_links,
                events_max_size: parse_optional_byte_size(&raw.events_max_size)
                    .wrap_err("invalid events_max_size")?,
            },
        ))
    }

    /// Apply the deliberately small, safe policy surface from `.mbx.toml` at
    /// the resolved Cargo workspace root.
    pub fn apply_workspace_policy(&mut self, workspace_root: &Path) -> Result<()> {
        self.apply_workspace_policy_with(workspace_root, |name| std::env::var_os(name).is_some())
    }

    fn apply_workspace_policy_with(
        &mut self,
        workspace_root: &Path,
        environment_contains: impl Fn(&str) -> bool,
    ) -> Result<()> {
        let path = workspace_root.join(".mbx.toml");
        let contents = match std::fs::read_to_string(&path) {
            Ok(contents) => contents,
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
            Err(error) => {
                return Err(error).wrap_err_with(|| format!("failed to read {}", path.display()));
            }
        };
        let document = contents
            .parse::<toml_edit::DocumentMut>()
            .wrap_err_with(|| format!("failed to parse {}", path.display()))?;

        for (key, value) in document.iter() {
            if key == "linker" {
                if environment_contains("MBX_LINKER") {
                    continue;
                }
                let table = value
                    .as_table()
                    .ok_or_else(|| eyre::eyre!("{}.linker must be a table", path.display()))?;
                for (linker_key, value) in table.iter() {
                    match linker_key {
                        "default" => {
                            let selection = value.as_str().ok_or_else(|| {
                                eyre::eyre!("{}.linker.default must be a string", path.display())
                            })?;
                            crate::managed_linker::validate_workspace_selector(selection)
                                .wrap_err_with(|| {
                                    format!("invalid {}.linker.default", path.display())
                                })?;
                            self.linker.default = selection.to_owned();
                        }
                        "profiles" => {
                            for (profile, selections) in workspace_linker_profiles(&path, value)? {
                                self.linker
                                    .profiles
                                    .entry(profile)
                                    .or_default()
                                    .extend(selections);
                            }
                        }
                        _ => bail!(
                            "{} contains unsupported workspace setting \"linker.{linker_key}\"; only linker.default and linker.profiles are allowed",
                            path.display()
                        ),
                    }
                }
                continue;
            }
            if key == "scheduler" {
                let table = value
                    .as_table()
                    .ok_or_else(|| eyre::eyre!("{}.scheduler must be a table", path.display()))?;
                for (scheduler_key, value) in table.iter() {
                    let setting = format!("scheduler.{scheduler_key}");
                    match scheduler_key {
                        "enabled" if !environment_contains("MBX_SCHEDULER") => {
                            self.scheduler.enabled = workspace_bool(&path, &setting, value)?;
                        }
                        "cpus" if !environment_contains("MBX_SCHEDULER_CPUS") => {
                            self.scheduler.cpus = workspace_count(&path, &setting, value, false)?;
                        }
                        "reserve_cpus" if !environment_contains("MBX_SCHEDULER_RESERVE_CPUS") => {
                            self.scheduler.reserve_cpus =
                                workspace_count(&path, &setting, value, true)?;
                        }
                        "memory" if !environment_contains("MBX_SCHEDULER_MEMORY") => {
                            let memory = value.as_str().ok_or_else(|| {
                                eyre::eyre!("{}.{} must be a string", path.display(), setting)
                            })?;
                            self.scheduler.memory_bytes = parse_optional_byte_size(memory)
                                .wrap_err_with(|| {
                                    format!("invalid {}.{setting}", path.display())
                                })?;
                        }
                        "priority" if !environment_contains("MBX_SCHEDULER_PRIORITY") => {
                            let priority = value.as_str().ok_or_else(|| {
                                eyre::eyre!("{}.{} must be a string", path.display(), setting)
                            })?;
                            self.scheduler.priority = priority.parse().wrap_err_with(|| {
                                format!("invalid {}.{setting}", path.display())
                            })?;
                        }
                        "pressure" if !environment_contains("MBX_SCHEDULER_PRESSURE") => {
                            self.scheduler.pressure = workspace_bool(&path, &setting, value)?;
                        }
                        "tests" if !environment_contains("MBX_SCHEDULER_TESTS") => {
                            self.scheduler.tests = workspace_bool(&path, &setting, value)?;
                        }
                        "enabled" | "cpus" | "reserve_cpus" | "memory" | "priority" | "tests"
                        | "pressure" => {}
                        _ => bail!(
                            "{} contains unsupported workspace setting {setting:?}; only scheduler.enabled, scheduler.cpus, scheduler.reserve_cpus, scheduler.memory, scheduler.priority, scheduler.pressure, and scheduler.tests are allowed",
                            path.display()
                        ),
                    }
                }
                continue;
            }
            if !matches!(
                key,
                "incremental"
                    | "share_out_dir"
                    | "share_workspace_root"
                    | "build_script_execution"
                    | "cc"
            ) {
                bail!(
                    "{} contains unsupported workspace setting {key:?}; only incremental, share_out_dir, share_workspace_root, build_script_execution, cc, linker, and scheduler are allowed",
                    path.display()
                );
            }
            let value = value
                .as_bool()
                .ok_or_else(|| eyre::eyre!("{}.{} must be a boolean", path.display(), key))?;
            match key {
                "incremental" if !environment_contains("MBX_INCREMENTAL") => {
                    self.incremental = value;
                }
                "share_out_dir" if !environment_contains("MBX_SHARE_OUT_DIR") => {
                    self.share_out_dir = value;
                }
                "share_workspace_root" if !environment_contains("MBX_SHARE_WORKSPACE_ROOT") => {
                    self.share_workspace_root = value;
                }
                "build_script_execution" if !environment_contains("MBX_BUILD_SCRIPT_EXECUTION") => {
                    self.build_script_execution = value;
                }
                "cc" if !environment_contains("MBX_CC") => {
                    self.cc = value;
                }
                "incremental"
                | "share_out_dir"
                | "share_workspace_root"
                | "build_script_execution"
                | "cc" => {}
                _ => unreachable!("workspace policy keys were validated above"),
            }
        }
        Ok(())
    }

    /// Where cached actions and blobs live.
    pub fn store_dir(&self) -> PathBuf {
        self.cache_dir.join("actions")
    }
}

fn workspace_bool(path: &Path, setting: &str, value: &toml_edit::Item) -> Result<bool> {
    value
        .as_bool()
        .ok_or_else(|| eyre::eyre!("{}.{} must be a boolean", path.display(), setting))
}

fn workspace_linker_profiles(
    path: &Path,
    value: &toml_edit::Item,
) -> Result<BTreeMap<String, BTreeMap<String, String>>> {
    let profiles = value
        .as_table()
        .ok_or_else(|| eyre::eyre!("{}.linker.profiles must be a table", path.display()))?;
    let mut resolved = BTreeMap::new();
    for (profile, targets) in profiles {
        let targets = targets.as_table().ok_or_else(|| {
            eyre::eyre!(
                "{}.linker.profiles.{profile} must be a table of target selectors",
                path.display()
            )
        })?;
        let mut selections = BTreeMap::new();
        for (target, selection) in targets {
            let selection = selection.as_str().ok_or_else(|| {
                eyre::eyre!(
                    "{}.linker.profiles.{profile}.{target} must be a string",
                    path.display()
                )
            })?;
            crate::managed_linker::validate_workspace_selector(selection).wrap_err_with(|| {
                format!(
                    "invalid {}.linker.profiles.{profile}.{target}",
                    path.display()
                )
            })?;
            selections.insert(target.to_owned(), selection.to_owned());
        }
        resolved.insert(profile.to_owned(), selections);
    }
    Ok(resolved)
}

fn workspace_count(
    path: &Path,
    setting: &str,
    value: &toml_edit::Item,
    zero_allowed: bool,
) -> Result<u64> {
    let count = value
        .as_integer()
        .and_then(|count| u64::try_from(count).ok())
        .filter(|count| zero_allowed || *count > 0);
    count.ok_or_else(|| {
        let requirement = if zero_allowed {
            "non-negative"
        } else {
            "positive"
        };
        eyre::eyre!(
            "{}.{} must be a {requirement} count",
            path.display(),
            setting
        )
    })
}

/// Resolve a byte size, written either plainly or with a unit.
///
/// Both IEC and SI spellings parse -- `20GiB` and `20GB` are different numbers,
/// and sizes are reported back in IEC, so the two are not interchangeable.
fn parse_byte_size(value: &str) -> Result<u64> {
    // `ByteSize`'s parse error is a bare `String`, so it cannot be a source.
    value
        .trim()
        .parse::<ByteSize>()
        .map(|size| size.as_u64())
        .map_err(|error| eyre::eyre!(error))
}

/// The spelling that turns a limit off outright.
///
/// A limit needs an off switch that is not "unset", because unset now means the
/// scaled default. Only this exact word does it: anything else that fails to
/// parse is still an error, so a typo cannot quietly disable collection.
const NO_LIMIT: &str = "none";

fn is_no_limit(value: &str) -> bool {
    value.trim().eq_ignore_ascii_case(NO_LIMIT)
}

/// Parse the store budget, which alone has no off switch.
///
/// An unbounded action store is the problem collection exists to prevent, so
/// `"none"` is refused -- but it has to be refused in words, since the sibling
/// size settings accept it and `bytesize` would otherwise blame a float.
fn parse_store_budget(value: &str) -> Result<u64> {
    if is_no_limit(value) {
        eyre::bail!("the action store budget cannot be disabled; set a size such as 20GiB");
    }
    parse_byte_size(value)
}

pub(crate) fn parse_optional_byte_size(value: &str) -> Result<Option<u64>> {
    if is_no_limit(value) {
        return Ok(None);
    }
    parse_byte_size(value).map(Some)
}

fn parse_optional_duration(value: &str) -> Result<Option<Duration>> {
    if is_no_limit(value) {
        return Ok(None);
    }
    parse_duration(value).map(Some)
}

fn config_file_path() -> Option<PathBuf> {
    dirs::config_dir().map(|dir| dir.join("mbx").join("config.toml"))
}

fn default_cache_dir() -> Option<PathBuf> {
    dirs::cache_dir().map(|dir| dir.join("mbx"))
}

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

    /// The disk size the tests below resolve scaled budgets against, so an
    /// assertion describes the scaling rule rather than the disk running it.
    const TEST_DISK: u64 = 400 * GIB;

    fn configured(file: Option<&str>, values: &[(&str, &str)]) -> Result<Config> {
        configured_for_cli(file, values).map(|(config, _)| config)
    }

    fn configured_for_cli(
        file: Option<&str>,
        values: &[(&str, &str)],
    ) -> Result<(Config, CliSettings)> {
        configured_on_disk(file, values, Some(TEST_DISK))
    }

    fn configured_retention(
        file: Option<&str>,
        values: &[(&str, &str)],
    ) -> Result<(Config, RetentionSettings)> {
        configured_for_cli(file, values).map(|(config, settings)| (config, settings.retention))
    }

    fn configured_on_disk(
        file: Option<&str>,
        values: &[(&str, &str)],
        disk_total_bytes: Option<u64>,
    ) -> Result<(Config, CliSettings)> {
        configured_measuring(file, values, move |_| disk_total_bytes)
    }

    /// Resolve with a stated size per path, for the budgets that are measured
    /// against different disks.
    fn configured_measuring(
        file: Option<&str>,
        values: &[(&str, &str)],
        measure_disk: impl Fn(&Path) -> Option<u64>,
    ) -> Result<(Config, CliSettings)> {
        let env = EnvLayer::new(
            values
                .iter()
                .map(|(name, value)| ((*name).to_string(), (*value).to_string())),
        );
        let directory = tempfile::tempdir().unwrap();
        let file = file.map(|contents| {
            let path = directory.path().join("config.toml");
            std::fs::write(&path, contents).unwrap();
            FileLayer::at(path, FileScope::Global)
        });
        Config::from_layers_measuring(&env, file.as_ref(), measure_disk, || Some(32 * GIB))
    }

    #[test]
    fn repository_policy_cannot_opt_into_process_supervision() {
        let directory = tempfile::tempdir().unwrap();
        for policy in ["suspend = true", "cgroup_root = '/delegated'"] {
            std::fs::write(
                directory.path().join(".mbx.toml"),
                format!("[scheduler]\n{policy}\n"),
            )
            .unwrap();
            let mut config = configured(None, &[]).unwrap();
            assert!(
                config
                    .apply_workspace_policy_with(directory.path(), |_| false)
                    .is_err()
            );
        }
    }

    #[test]
    fn suspension_requires_explicit_opt_in() {
        let config = configured(None, &[]).unwrap();
        assert!(!config.scheduler.suspend);
        assert!(config.scheduler.cgroup_root.is_none());
        let config = configured(
            None,
            &[
                ("MBX_SCHEDULER_SUSPEND", "1"),
                ("MBX_SCHEDULER_CGROUP_ROOT", "/delegated"),
            ],
        )
        .unwrap();
        assert!(config.scheduler.suspend);
        assert_eq!(
            config.scheduler.cgroup_root,
            Some(PathBuf::from("/delegated"))
        );
    }

    #[test]
    fn pressure_setting_defaults_and_overrides() {
        assert!(configured(None, &[]).unwrap().scheduler.pressure);
        assert!(
            !configured(Some("[scheduler]\npressure = false"), &[])
                .unwrap()
                .scheduler
                .pressure
        );
        assert!(
            !configured(None, &[("MBX_SCHEDULER_PRESSURE", "0")])
                .unwrap()
                .scheduler
                .pressure
        );
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[scheduler]\npressure = false",
        )
        .unwrap();
        let mut config = configured(None, &[]).unwrap();
        config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap();
        assert!(!config.scheduler.pressure);
    }

    #[test]
    fn environment_overrides_the_file() {
        let file = r#"
            cache_dir = "/from/file"
            [remote]
            url = "https://file.example"
            namespace = "file"
            mode = "read-only"
            s3_conditional_writes = "required"
            [http]
            timeout = "5s"
            retries = 9
            [gc]
            auto = false
            max_size = "1GiB"
            interval = "6h"
            [target]
            views = true
            root = "/from/file/targets"
            "#;
        let config = configured(
            Some(file),
            &[
                ("MBX_CACHE_DIR", "/from/env"),
                ("MBX_REMOTE_URL", "https://env.example"),
                ("MBX_REMOTE_MODE", "write-only"),
                ("MBX_HTTP_TIMEOUT", "250ms"),
                ("MBX_GC_MAX_SIZE", "2GiB"),
                ("MBX_TARGET_ROOT", "/from/env/targets"),
            ],
        )
        .unwrap();

        assert_eq!(config.cache_dir, PathBuf::from("/from/env"));
        assert_eq!(config.remote.url.unwrap(), "https://env.example");
        assert_eq!(config.remote.mode, RemoteCacheMode::WriteOnly);
        assert_eq!(config.http.timeout, Duration::from_millis(250));
        assert_eq!(config.gc.max_bytes, 2 * 1024 * 1024 * 1024);
        // Values absent from the environment still come from the file.
        assert_eq!(config.remote.namespace.unwrap(), "file");
        assert_eq!(
            config.remote.s3_conditional_writes,
            S3ConditionalWrites::Required
        );
        assert_eq!(config.http.retries, 9);
        assert!(!config.gc.auto);
        assert_eq!(config.gc.interval, Duration::from_secs(6 * 60 * 60));
        assert_eq!(config.target.root, PathBuf::from("/from/env/targets"));
        assert!(config.target.views);
    }

    #[test]
    fn private_shims_resolve_relative_to_the_cache_and_environment_overrides_the_file() {
        let directory = tempfile::tempdir().unwrap();
        let cache = directory.path().join("cache");
        let private = directory.path().join("private shims");
        let cache_text = cache.to_str().unwrap();
        let from_file = configured(
            Some("shims_dir = 'worker/shims'"),
            &[("MBX_CACHE_DIR", cache_text)],
        )
        .unwrap();
        assert_eq!(from_file.shims_dir, cache.join("worker/shims"));
        let from_environment = configured(
            Some("shims_dir = 'worker/shims'"),
            &[
                ("MBX_CACHE_DIR", cache_text),
                ("MBX_SHIMS_DIR", private.to_str().unwrap()),
            ],
        )
        .unwrap();
        assert_eq!(from_environment.shims_dir, private);
        assert_eq!(from_environment.store_dir(), cache.join("actions"));
        let relative = configured(
            None,
            &[("MBX_CACHE_DIR", cache_text), ("MBX_SHIMS_DIR", "local")],
        )
        .unwrap();
        assert_eq!(relative.shims_dir, cache.join("local"));
    }

    #[test]
    fn relative_shims_cannot_traverse_above_the_cache_root() {
        for path in ["../private", "worker/../../private", "../cache/private"] {
            let error = configured(None, &[("MBX_SHIMS_DIR", path)]).unwrap_err();
            assert!(error.to_string().contains("invalid shims_dir"), "{error}");
            let file = format!("shims_dir = '{path}'");
            assert!(configured(Some(&file), &[]).is_err());
        }
    }

    #[test]
    fn shims_reject_empty_and_empty_normalizing_paths() {
        for path in ["", ".", "./", "a/.."] {
            let file = format!("shims_dir = '{path}'");
            for result in [
                configured(None, &[("MBX_SHIMS_DIR", path)]),
                configured(Some(&file), &[]),
            ] {
                let error = result.unwrap_err();
                assert!(error.to_string().contains("invalid shims_dir"), "{error}");
            }
        }
    }

    #[test]
    fn relative_shims_normalize_parent_components_within_the_cache_root() {
        let config = configured(None, &[("MBX_SHIMS_DIR", "worker/../private/./shims")]).unwrap();
        assert_eq!(config.shims_dir, config.cache_dir.join("private/shims"));
    }

    #[test]
    fn defaults_apply_without_configuration() {
        let (config, retention) = configured_retention(None, &[]).unwrap();
        assert_eq!(
            config.remote.s3_conditional_writes,
            S3ConditionalWrites::Auto
        );
        assert_eq!(config.http.timeout, DEFAULT_HTTP_TIMEOUT);
        assert_eq!(config.http.download_timeout, DEFAULT_HTTP_DOWNLOAD_TIMEOUT);
        assert_eq!(config.http.retries, DEFAULT_HTTP_RETRIES);
        assert_eq!(config.remote.mode, RemoteCacheMode::ReadWrite);
        assert!(config.remote.url.is_none());
        assert!(!config.verify);
        assert!(!config.incremental);
        assert!(config.share_out_dir);
        assert!(config.build_script_execution);
        assert!(config.store_dir().ends_with("actions"));
        assert_eq!(config.shims_dir, config.cache_dir.join("shims"));
        assert!(config.gc.auto, "collection runs until it is turned off");
        assert_eq!(config.gc.max_bytes, 20 * GIB, "5% of a 400GiB disk");
        assert_eq!(config.gc.interval, DEFAULT_GC_INTERVAL);
        assert!(
            config.target.views,
            "eligible target directories are managed"
        );
        assert_eq!(config.target.root, config.cache_dir.join("targets"));
        // Collection of live target directories is on by default; leaving these
        // unset is what used to let a disk fill up indefinitely.
        assert_eq!(
            retention.target_max_bytes,
            Some(40 * GIB),
            "10% of a 400GiB disk"
        );
        assert_eq!(retention.target_max_age, Some(DEFAULT_TARGET_MAX_AGE));
        assert_eq!(retention.incremental_max_bytes, Some(20 * GIB));
        assert_eq!(retention.incremental_max_age, Some(DEFAULT_TARGET_MAX_AGE));
        assert_eq!(
            retention.max_total_bytes, None,
            "a combined budget stays opt-in"
        );
    }

    #[test]
    fn path_specific_storage_defaults_on_and_environment_overrides_file() {
        let (config, _) = configured_retention(None, &[]).unwrap();
        assert!(config.cc_store_path_specific);
        let (config, _) =
            configured_retention(Some("cc_store_path_specific = false"), &[]).unwrap();
        assert!(!config.cc_store_path_specific);
        let (config, _) = configured_retention(
            Some("cc_store_path_specific = false"),
            &[("MBX_CC_STORE_PATH_SPECIFIC", "1")],
        )
        .unwrap();
        assert!(config.cc_store_path_specific);
    }

    #[test]
    fn budgets_scale_with_the_disk_within_bounds() {
        let cases = [
            // A small disk lands on the floors rather than a cache too small
            // to ever hit in.
            (Some(32 * GIB), STORE_BUDGET.floor, TARGET_BUDGET.floor),
            (Some(400 * GIB), 20 * GIB, 40 * GIB),
            // 5% and 10% of 1TiB are 51.2 and 102.4 GiB: the first rounds down
            // to a whole increment, the second meets its ceiling.
            (Some(1_024 * GIB), 50 * GIB, MAX_TARGET_BUDGET),
            // A large shared disk can give the store more than the old 100GiB
            // ceiling while managed targets remain capped there.
            (Some(8_000 * GIB), 400 * GIB, MAX_TARGET_BUDGET),
            // The store still has a ceiling on exceptionally large disks.
            (Some(20_000 * GIB), MAX_STORE_BUDGET, MAX_TARGET_BUDGET),
            // An unmeasurable disk uses the fixed fallbacks.
            (None, STORE_BUDGET.fallback, TARGET_BUDGET.fallback),
        ];
        for (disk, store, target) in cases {
            let (config, settings) = configured_on_disk(None, &[], disk).unwrap();
            let retention = settings.retention;
            assert_eq!(config.gc.max_bytes, store, "store budget for {disk:?}");
            assert_eq!(
                retention.target_max_bytes,
                Some(target),
                "target budget for {disk:?}"
            );
        }
    }

    #[test]
    fn a_scaled_budget_is_always_a_whole_increment() {
        // Awkward disk sizes are the point: 5% of 333GiB is 16.65GiB, which
        // should be reported as a number somebody could have chosen.
        for disk_gib in [17_u64, 63, 333, 500, 999, 1_500, 4_000] {
            for budget in [STORE_BUDGET, TARGET_BUDGET, INCREMENTAL_BUDGET] {
                let resolved = budget.resolve(Some(disk_gib * GIB));
                assert_eq!(
                    resolved % BUDGET_INCREMENT,
                    0,
                    "{resolved} is not a whole increment for a {disk_gib}GiB disk"
                );
                assert!(resolved >= budget.floor);
                assert!(resolved <= budget.ceiling);
            }
        }
    }

    #[test]
    fn rounding_never_hands_out_more_than_the_share() {
        // Rounded down, never to nearest: a budget must not exceed the share of
        // the disk it was allowed, floors aside.
        for disk_gib in [200_u64, 333, 617, 1_000] {
            let total = disk_gib * GIB;
            let resolved = STORE_BUDGET.resolve(Some(total));
            let share = (total / 100) * STORE_BUDGET.percent;
            assert!(
                resolved <= share.max(STORE_BUDGET.floor),
                "{resolved} exceeds the {share} share of a {disk_gib}GiB disk"
            );
        }
    }

    #[test]
    fn configured_budgets_outrank_the_disk() {
        let (config, settings) = configured_on_disk(
            None,
            &[("MBX_GC_MAX_SIZE", "3GiB"), ("MBX_TARGET_MAX_SIZE", "7GiB")],
            Some(8_000 * GIB),
        )
        .unwrap();
        let retention = settings.retention;

        assert_eq!(config.gc.max_bytes, 3 * GIB);
        assert_eq!(retention.target_max_bytes, Some(7 * GIB));
        assert_eq!(
            retention.incremental_max_bytes,
            Some(MAX_INCREMENTAL_BUDGET)
        );
    }

    #[test]
    fn each_budget_is_sized_from_the_disk_that_holds_it() {
        // A scratch volume for targets is exactly why these are measured apart:
        // sizing a 4TiB disk from a 64GiB home directory would prune it to the
        // floor.
        let (config, settings) = configured_measuring(
            None,
            &[("MBX_CACHE_DIR", "/cache"), ("MBX_TARGET_ROOT", "/scratch")],
            |path| {
                Some(if path.starts_with("/scratch") {
                    4_000 * GIB
                } else {
                    64 * GIB
                })
            },
        )
        .unwrap();

        assert_eq!(config.gc.max_bytes, STORE_BUDGET.floor, "5% of 64GiB");
        assert_eq!(
            settings.retention.incremental_max_bytes,
            Some(INCREMENTAL_BUDGET.floor),
            "5% of 64GiB, at the floor"
        );
        assert_eq!(
            settings.retention.target_max_bytes,
            Some(MAX_TARGET_BUDGET),
            "10% of 4TiB, at the ceiling"
        );
    }

    #[test]
    fn the_store_budget_cannot_be_disabled() {
        let error = configured(None, &[("MBX_GC_MAX_SIZE", "none")])
            .expect_err("an unbounded store is what collection exists to prevent");
        let message = format!("{error:#}");
        assert!(
            message.contains("cannot be disabled"),
            "the error should say why rather than blame a float: {message}"
        );
    }

    #[test]
    fn none_turns_a_retention_limit_off() {
        let (_, retention) = configured_retention(
            None,
            &[
                ("MBX_TARGET_MAX_SIZE", "none"),
                ("MBX_TARGET_MAX_AGE", "NONE"),
                ("MBX_GC_INCREMENTAL_MAX_SIZE", "none"),
                ("MBX_GC_INCREMENTAL_MAX_AGE", "none"),
                ("MBX_GC_MAX_TOTAL_SIZE", "None"),
            ],
        )
        .unwrap();

        assert_eq!(retention.target_max_bytes, None);
        assert_eq!(retention.target_max_age, None);
        assert_eq!(retention.incremental_max_bytes, None);
        assert_eq!(retention.incremental_max_age, None);
        assert_eq!(retention.max_total_bytes, None);
    }

    #[test]
    fn the_unconfigured_retention_default_still_collects() {
        // Paths that resolve no configuration must not silently stop pruning.
        let retention = RetentionSettings::default();
        assert_eq!(retention.target_max_bytes, Some(TARGET_BUDGET.fallback));
        assert_eq!(retention.target_max_age, Some(DEFAULT_TARGET_MAX_AGE));
        assert_eq!(
            retention.incremental_max_bytes,
            Some(INCREMENTAL_BUDGET.fallback)
        );
        assert_eq!(retention.incremental_max_age, Some(DEFAULT_TARGET_MAX_AGE));
    }

    #[test]
    fn reads_target_and_whole_cache_retention_limits() {
        let (_, retention) = configured_retention(
            None,
            &[
                ("MBX_TARGET_MAX_SIZE", "8GiB"),
                ("MBX_TARGET_MAX_AGE", "14d"),
                ("MBX_GC_INCREMENTAL_MAX_SIZE", "9GiB"),
                ("MBX_GC_INCREMENTAL_MAX_AGE", "21d"),
                ("MBX_GC_MAX_TOTAL_SIZE", "12GiB"),
            ],
        )
        .unwrap();

        assert_eq!(retention.target_max_bytes, Some(8 * 1024 * 1024 * 1024));
        assert_eq!(
            retention.target_max_age,
            Some(Duration::from_secs(14 * 86_400))
        );
        assert_eq!(retention.incremental_max_bytes, Some(9 * GIB));
        assert_eq!(
            retention.incremental_max_age,
            Some(Duration::from_secs(21 * 86_400))
        );
        assert_eq!(retention.max_total_bytes, Some(12 * 1024 * 1024 * 1024));
    }

    #[test]
    fn managed_targets_can_be_turned_off() {
        for value in ["0", "false", "no", "off", ""] {
            let config = configured(None, &[("MBX_TARGET_VIEWS", value)]).unwrap();
            assert!(
                !config.target.views,
                "MBX_TARGET_VIEWS={value:?} should disable managed targets"
            );
        }
    }

    #[test]
    fn relative_target_roots_are_anchored_to_the_cache_directory() {
        let config = configured(
            None,
            &[
                ("MBX_CACHE_DIR", "/cache"),
                ("MBX_TARGET_ROOT", "target-views"),
            ],
        )
        .unwrap();

        assert_eq!(config.target.root, PathBuf::from("/cache/target-views"));
    }

    #[test]
    fn rejects_unparseable_values() {
        assert!(configured(None, &[("MBX_REMOTE_MODE", "sideways")]).is_err());
        assert!(configured(None, &[("MBX_HTTP_TIMEOUT", "later")]).is_err());
        assert!(configured(None, &[("MBX_HTTP_RETRIES", "many")]).is_err());
        assert!(configured(None, &[("MBX_GC_MAX_SIZE", "lots")]).is_err());
        assert!(configured(None, &[("MBX_GC_MAX_TOTAL_SIZE", "lots")]).is_err());
        assert!(configured(None, &[("MBX_GC_INTERVAL", "later")]).is_err());
        assert!(configured(None, &[("MBX_TARGET_MAX_SIZE", "lots")]).is_err());
        assert!(configured(None, &[("MBX_TARGET_MAX_AGE", "later")]).is_err());
        // A budget that cannot be read must not be guessed at, and neither must
        // a switch: silently collecting to the wrong number, or not at all, is
        // worse than saying so.
        assert!(configured(None, &[("MBX_GC_AUTO", "maybe")]).is_err());
        assert!(configured(None, &[("MBX_TARGET_VIEWS", "sometimes")]).is_err());
    }

    #[test]
    fn collection_runs_until_it_is_turned_off() {
        for value in ["0", "false", "no", "off", ""] {
            let config = configured(None, &[("MBX_GC_AUTO", value)]).unwrap();
            assert!(!config.gc.auto, "MBX_GC_AUTO={value:?} should disable");
        }
        for value in ["1", "true", "yes", "on", "ON"] {
            let config = configured(None, &[("MBX_GC_AUTO", value)]).unwrap();
            assert!(config.gc.auto, "MBX_GC_AUTO={value:?} should enable");
        }
    }

    #[test]
    fn reads_a_budget_in_either_unit_convention() {
        // `20GB` and `20GiB` are different numbers and sizes are reported back
        // in IEC, so both spellings have to mean exactly what they say.
        for (value, expected) in [
            ("20GiB", 20 * 1024 * 1024 * 1024),
            ("20GB", 20_000_000_000),
            ("1024", 1024),
        ] {
            let config = configured(None, &[("MBX_GC_MAX_SIZE", value)]).unwrap();
            assert_eq!(config.gc.max_bytes, expected, "{value} should parse");
        }
    }

    #[test]
    fn the_environment_can_turn_off_what_the_file_turned_on() {
        let file = "incremental = true";
        let config = configured(Some(file), &[]).unwrap();
        assert!(config.incremental);
        let config = configured(Some(file), &[("MBX_INCREMENTAL", "0")]).unwrap();
        assert!(!config.incremental);
    }

    /// On by default: a crate nobody is editing never reaches the threshold, so
    /// the setting only matters to the one the developer is working in.
    #[test]
    fn learned_incremental_is_on_until_it_is_turned_off() {
        let (_, settings) = configured_for_cli(None, &[]).unwrap();
        assert!(settings.learned_incremental);

        let (_, settings) = configured_for_cli(None, &[("MBX_LEARNED_INCREMENTAL", "0")]).unwrap();
        assert!(!settings.learned_incremental);
    }

    /// The budget has to hold a real crate's state: rustc keeps one session's
    /// worth per crate, and a large binary's session is a few GiB.
    #[test]
    fn learned_incremental_state_budget_is_generous_and_can_be_lifted() {
        let (_, settings) = configured_for_cli(None, &[]).unwrap();
        assert_eq!(
            settings.learned_incremental_max_size,
            Some(DEFAULT_LEARNED_INCREMENTAL_MAX_SIZE)
        );

        let (_, settings) =
            configured_for_cli(None, &[("MBX_LEARNED_INCREMENTAL_MAX_SIZE", "2GiB")]).unwrap();
        assert_eq!(
            settings.learned_incremental_max_size,
            Some(2 * 1024 * 1024 * 1024)
        );

        let (_, settings) =
            configured_for_cli(None, &[("MBX_LEARNED_INCREMENTAL_MAX_SIZE", "none")]).unwrap();
        assert_eq!(settings.learned_incremental_max_size, None);

        let error =
            configured_for_cli(None, &[("MBX_LEARNED_INCREMENTAL_MAX_SIZE", "lots")]).unwrap_err();
        assert!(error.to_string().contains("learned_incremental_max_size"));
    }

    /// The default keeps the TUI's read cheap; diagnosing a miss on a large
    /// workspace needs more history than it allows.
    #[test]
    fn recorded_history_is_capped_by_default_and_can_be_lifted() {
        let (_, settings) = configured_for_cli(None, &[]).unwrap();
        assert_eq!(settings.events_max_size, Some(DEFAULT_EVENTS_MAX_SIZE));

        let (_, settings) = configured_for_cli(None, &[("MBX_EVENTS_MAX_SIZE", "256MiB")]).unwrap();
        assert_eq!(settings.events_max_size, Some(256 * 1024 * 1024));

        let (_, settings) = configured_for_cli(None, &[("MBX_EVENTS_MAX_SIZE", "none")]).unwrap();
        assert_eq!(settings.events_max_size, None);

        let error = configured_for_cli(None, &[("MBX_EVENTS_MAX_SIZE", "lots")]).unwrap_err();
        assert!(error.to_string().contains("events_max_size"));
    }

    #[test]
    fn workspace_policy_overrides_global_safe_settings() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "incremental = true\nshare_out_dir = true\nbuild_script_execution = true\n",
        )
        .unwrap();
        let mut config = configured(
            Some("incremental = false\nshare_out_dir = false\nbuild_script_execution = false"),
            &[],
        )
        .unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap();

        assert!(config.incremental);
        assert!(config.share_out_dir);
        assert!(config.build_script_execution);
    }

    #[test]
    fn linkers_are_selected_by_profile_and_target() {
        let file = r#"
[linker]
default = "system"

[linker.profiles.dev]
default = "wild@0.10.0"
aarch64-apple-darwin = "rust-lld"

[linker.profiles.release]
default = "rust-lld"
"#;
        let config = configured(Some(file), &[]).unwrap();

        assert_eq!(
            config.linker.for_build("dev", Some("aarch64-apple-darwin")),
            Some("rust-lld".into())
        );
        assert_eq!(
            config
                .linker
                .for_build("dev", Some("x86_64-unknown-linux-gnu")),
            Some("wild@0.10.0".into())
        );
        assert_eq!(
            config.linker.for_build("release", None),
            Some("rust-lld".into())
        );
        assert_eq!(config.linker.for_build("bench", None), None);
        assert_eq!(
            config
                .linker
                .for_build("debug", Some("x86_64-unknown-linux-gnu")),
            Some("wild@0.10.0".into()),
            "Cargo's debug profile inherits dev"
        );
    }

    #[test]
    fn workspace_linker_policy_overrides_the_global_selection() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[linker.profiles.dev]\ndefault = \"mold@2.42.0\"\n",
        )
        .unwrap();
        let mut config = configured(
            Some(
                "[linker.profiles.dev]\ndefault = \"system\"\naarch64-apple-darwin = \"rust-lld\"",
            ),
            &[],
        )
        .unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap();

        assert_eq!(
            config
                .linker
                .for_build("dev", Some("x86_64-unknown-linux-gnu")),
            Some("mold@2.42.0".into())
        );
        assert_eq!(
            config.linker.for_build("dev", Some("aarch64-apple-darwin")),
            Some("rust-lld".into())
        );
    }

    #[test]
    fn workspace_linker_policy_preserves_unrelated_global_profiles() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[linker.profiles.dev]\ndefault = \"mold@2.42.0\"\n",
        )
        .unwrap();
        let mut config = configured(
            Some("[linker.profiles.release]\ndefault = \"rust-lld\""),
            &[],
        )
        .unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap();

        assert_eq!(
            config.linker.for_build("release", None),
            Some("rust-lld".into())
        );
        assert_eq!(
            config.linker.for_build("dev", None),
            Some("mold@2.42.0".into())
        );
    }

    #[test]
    fn workspace_linker_policy_rejects_executable_paths() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[linker.profiles.dev]\ndefault = \"path:./linker\"\n",
        )
        .unwrap();
        let mut config = configured(None, &[]).unwrap();

        let error = config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap_err();

        assert!(
            format!("{error:?}")
                .contains("workspace linker policy may not select an executable path")
        );
    }

    #[test]
    fn workspace_policy_accepts_scheduler_settings() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[scheduler]\nenabled = true\ncpus = 8\nreserve_cpus = 2\nmemory = \"6GiB\"\npriority = \"low\"\ntests = true\n",
        )
        .unwrap();
        let mut config = configured(None, &[("MBX_SCHEDULER", "false")]).unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |name| name == "MBX_SCHEDULER")
            .unwrap();

        assert!(!config.scheduler.enabled, "the environment still wins");
        assert_eq!(config.scheduler.cpus, 8);
        assert_eq!(config.scheduler.reserve_cpus, 2);
        assert_eq!(config.scheduler.permits(), 6);
        assert_eq!(config.scheduler.memory_bytes, Some(6 * GIB));
        assert_eq!(config.scheduler.priority, SchedulerPriority::Low);
        assert!(config.scheduler.tests);
    }

    #[test]
    fn environment_overrides_workspace_scheduler_policy() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "[scheduler]\ncpus = 8\nreserve_cpus = 2\nmemory = \"6GiB\"\npriority = \"low\"\n",
        )
        .unwrap();
        let environment = [
            ("MBX_SCHEDULER_CPUS", "5"),
            ("MBX_SCHEDULER_RESERVE_CPUS", "1"),
            ("MBX_SCHEDULER_MEMORY", "4GiB"),
            ("MBX_SCHEDULER_PRIORITY", "normal"),
        ];
        let mut config = configured(None, &environment).unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |name| {
                environment.iter().any(|(key, _)| *key == name)
            })
            .unwrap();

        assert_eq!(config.scheduler.cpus, 5);
        assert_eq!(config.scheduler.reserve_cpus, 1);
        assert_eq!(config.scheduler.memory_bytes, Some(4 * GIB));
        assert_eq!(config.scheduler.priority, SchedulerPriority::Normal);
    }

    #[test]
    fn workspace_policy_validates_scheduler_settings() {
        for setting in [
            "[scheduler]\ncpus = 0",
            "[scheduler]\nreserve_cpus = -1",
            "[scheduler]\nmemory = \"plenty\"",
            "[scheduler]\npriority = \"urgent\"",
            "[scheduler]\nunknown = true",
        ] {
            let directory = tempfile::tempdir().unwrap();
            std::fs::write(directory.path().join(".mbx.toml"), setting).unwrap();
            let mut config = configured(None, &[]).unwrap();
            assert!(
                config
                    .apply_workspace_policy_with(directory.path(), |_| false)
                    .is_err(),
                "{setting:?} should be rejected"
            );
        }
    }

    #[test]
    fn environment_overrides_workspace_policy() {
        let directory = tempfile::tempdir().unwrap();
        std::fs::write(
            directory.path().join(".mbx.toml"),
            "incremental = true\nshare_out_dir = true\nbuild_script_execution = true\n",
        )
        .unwrap();
        let mut config = configured(
            None,
            &[
                ("MBX_SHARE_OUT_DIR", "0"),
                ("MBX_BUILD_SCRIPT_EXECUTION", "0"),
            ],
        )
        .unwrap();

        config
            .apply_workspace_policy_with(directory.path(), |_| true)
            .unwrap();

        assert!(!config.incremental);
        assert!(!config.share_out_dir);
        assert!(!config.build_script_execution);
    }

    #[test]
    fn workspace_policy_rejects_every_setting_outside_the_allowlist() {
        for setting in [
            "cache_dir = \"elsewhere\"",
            "verify = true",
            "[remote]\nurl = \"https://example.com\"",
            // Credentials and the store they authenticate to are a machine's
            // business, never a repository's.
            "[remote]\ns3_endpoint = \"https://store.example.com\"",
            "[remote]\ns3_region = \"us-west-2\"",
            "[gc]\nauto = false",
            "[target]\nviews = false",
        ] {
            let directory = tempfile::tempdir().unwrap();
            std::fs::write(directory.path().join(".mbx.toml"), setting).unwrap();
            let mut config = configured(None, &[]).unwrap();
            let error = config
                .apply_workspace_policy_with(directory.path(), |_| false)
                .unwrap_err();
            assert!(
                error.to_string().contains("unsupported workspace setting"),
                "{error}"
            );
        }
    }

    #[test]
    fn missing_workspace_policy_is_ignored() {
        let directory = tempfile::tempdir().unwrap();
        let mut config = configured(None, &[]).unwrap();
        config
            .apply_workspace_policy_with(directory.path(), |_| false)
            .unwrap();
    }

    #[test]
    fn unknown_file_keys_are_rejected() {
        let error = configured(Some("not_a_setting = true"), &[]).unwrap_err();
        assert!(error.to_string().contains("not_a_setting"), "{error}");
    }

    #[test]
    fn verification_sample_rate_is_a_percentage() {
        assert_eq!(configured(None, &[]).unwrap().verify_sample_rate, 0);
        for rate in ["0", "1", "25", "100"] {
            let config = configured(None, &[("MBX_VERIFY_SAMPLE_RATE", rate)]).unwrap();
            assert_eq!(config.verify_sample_rate.to_string(), rate);
        }
        assert_eq!(
            configured(Some("verify_sample_rate = 5"), &[])
                .unwrap()
                .verify_sample_rate,
            5
        );
        for rate in ["-1", "101", "256", "bad"] {
            assert!(configured(None, &[("MBX_VERIFY_SAMPLE_RATE", rate)]).is_err());
        }
    }

    #[test]
    fn verify_is_off_for_empty_and_zero() {
        for value in ["", "0"] {
            let config = configured(None, &[("MBX_VERIFY", value)]).unwrap();
            assert!(!config.verify, "MBX_VERIFY={value:?} should not enable");
        }
        let config = configured(None, &[("MBX_VERIFY", "1")]).unwrap();
        assert!(config.verify);
    }

    #[test]
    fn savings_default_to_quips_with_plain_and_off_as_choices() {
        let (_, settings) = configured_for_cli(None, &[]).unwrap();
        assert_eq!(
            settings.savings,
            SavingsStyle::Quips,
            "an unconfigured machine gets the voice"
        );
        let (_, settings) = configured_for_cli(None, &[("MBX_SAVINGS", "plain")]).unwrap();
        assert_eq!(settings.savings, SavingsStyle::Plain);
        let (_, settings) = configured_for_cli(None, &[("MBX_SAVINGS", "off")]).unwrap();
        assert_eq!(settings.savings, SavingsStyle::Off);
        assert!(
            configured_for_cli(None, &[("MBX_SAVINGS", "sarcastic")]).is_err(),
            "an unknown style is an error, not a silent default"
        );
    }

    #[test]
    fn summaries_default_to_auto_and_allow_fixed_styles() {
        let (_, settings) = configured_for_cli(None, &[]).unwrap();
        assert_eq!(settings.summary, SummaryStyle::Auto);
        assert_eq!(settings.summary.resolve(false), SummaryStyle::Short);
        assert_eq!(settings.summary.resolve(true), SummaryStyle::Ci);
        for (value, style) in [
            ("off", SummaryStyle::Off),
            ("short", SummaryStyle::Short),
            ("ci", SummaryStyle::Ci),
            ("full", SummaryStyle::Full),
        ] {
            let (_, settings) = configured_for_cli(None, &[("MBX_SUMMARY", value)]).unwrap();
            assert_eq!(settings.summary.resolve(false), style);
            assert_eq!(settings.summary.resolve(true), style);
            let (_, settings) =
                configured_for_cli(Some(&format!("summary = {value:?}")), &[]).unwrap();
            assert_eq!(settings.summary.resolve(true), style);
        }
        assert!(
            configured_for_cli(None, &[("MBX_SUMMARY", "verbose")]).is_err(),
            "an unknown style is an error, not a silent default"
        );
    }

    #[test]
    fn the_scheduler_defaults_on_with_most_of_the_measured_memory() {
        let config = configured(None, &[]).unwrap();
        assert!(config.scheduler.enabled);
        assert_eq!(
            config.scheduler.cpus,
            std::thread::available_parallelism().unwrap().get() as u64
        );
        // 85% of the 32GiB the test harness reports.
        assert_eq!(
            config.scheduler.memory_bytes,
            Some(32 * GIB / 100 * 85),
            "the budget leaves headroom for what it cannot see"
        );
        assert_eq!(config.scheduler.priority, SchedulerPriority::Normal);
        assert_eq!(config.scheduler.reserve_cpus, 0);
    }

    #[test]
    fn the_scheduler_is_configurable_and_refuses_nonsense() {
        let config = configured(
            None,
            &[
                ("MBX_SCHEDULER_CPUS", "3"),
                ("MBX_SCHEDULER_RESERVE_CPUS", "1"),
                ("MBX_SCHEDULER_MEMORY", "4GiB"),
                ("MBX_SCHEDULER_PRIORITY", "low"),
            ],
        )
        .unwrap();
        assert_eq!(config.scheduler.cpus, 3);
        assert_eq!(config.scheduler.reserve_cpus, 1);
        assert_eq!(config.scheduler.permits(), 2);
        assert_eq!(config.scheduler.memory_bytes, Some(4 * GIB));
        assert_eq!(config.scheduler.priority, SchedulerPriority::Low);

        let config = configured(None, &[("MBX_SCHEDULER", "false")]).unwrap();
        assert!(!config.scheduler.enabled);

        let config = configured(None, &[("MBX_SCHEDULER_MEMORY", "none")]).unwrap();
        assert_eq!(
            config.scheduler.memory_bytes, None,
            "\"none\" keeps plain CPU permits"
        );

        let config = configured(
            None,
            &[
                ("MBX_SCHEDULER_CPUS", "3"),
                ("MBX_SCHEDULER_RESERVE_CPUS", "9"),
            ],
        )
        .unwrap();
        assert_eq!(config.scheduler.permits(), 1, "one permit always remains");

        let error = configured(None, &[("MBX_SCHEDULER_CPUS", "0")]).unwrap_err();
        assert!(error.to_string().contains("scheduler.cpus"), "{error}");
        let error = configured(None, &[("MBX_SCHEDULER_RESERVE_CPUS", "-1")]).unwrap_err();
        assert!(
            error.to_string().contains("scheduler.reserve_cpus"),
            "{error}"
        );
        let error = configured(None, &[("MBX_SCHEDULER_PRIORITY", "loud")]).unwrap_err();
        assert!(error.to_string().contains("scheduler.priority"), "{error}");
    }

    #[test]
    fn a_disabled_scheduler_needs_no_memory_measurement() {
        let env = EnvLayer::new([("MBX_SCHEDULER".to_string(), "false".to_string())]);
        let (config, _) = Config::from_layers_measuring(
            &env,
            None,
            |_| None,
            || panic!("a disabled scheduler must not probe memory"),
        )
        .unwrap();
        assert!(!config.scheduler.enabled);
    }

    #[test]
    fn the_usage_spec_declares_files_environment_and_defaults() {
        let spec = RawConfig::spec_kdl();
        assert!(spec.contains(r#"file "<config directory>/mbx/config.toml""#));
        assert!(spec.contains(r#"env "MBX_GC_MAX_SIZE""#));
        assert!(spec.contains(r#"prop "gc.max_size""#));
        assert!(spec.contains(r#"prop "target.max_size""#));
        assert!(spec.contains(r#"env "MBX_TARGET_MAX_AGE""#));
        assert!(spec.contains(r#"default="30d""#));
        // The scaled budgets have no literal default to declare, so the
        // generated reference has to describe them instead.
        assert!(spec.contains("5% of the cache disk"));
        assert!(spec.contains("10% of the cache disk"));
        assert!(spec.contains(r#"env "MBX_SAVINGS""#));
        assert!(spec.contains(r#"default="quips""#));
        // The declared log default is the filter the logger actually installs.
        assert!(spec.contains(&format!(r#"default="{}""#, crate::logging::DEFAULT_FILTER)));
    }
}