microsandbox 0.6.9

`microsandbox` is the core library for the microsandbox project.
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
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
//! Fluent builder for [`SandboxConfig`].

use std::collections::{BTreeMap, HashSet};
#[cfg(feature = "net")]
use std::net::{IpAddr, Ipv4Addr};
use std::path::{Path, PathBuf};
use std::time::Duration;

use microsandbox_image::{PullProgressHandle, RegistryAuth};
#[cfg(feature = "net")]
use microsandbox_network::builder::{NetworkBuilder, SecretBuilder};
#[cfg(feature = "net")]
use microsandbox_network::policy::{NetworkPolicy, Rule};
use microsandbox_types::{CpuPlacement, EnvVar, PullPolicy, VsockRouteSpec, VsockSocketType};
#[cfg(feature = "net")]
use microsandbox_types::{PortProtocol, PublishedPortSpec};

use super::{
    SandboxSpec,
    config::{SandboxConfig, sandbox_log_level_from_runtime},
    exec::{Rlimit, RlimitResource},
    init::{HandoffInit, InitOptionsBuilder},
    types::{
        DeploymentProfile, ImageBuilder, IntoImage, MountBuilder, Patch, PatchBuilder,
        RootDiskBuilder, RootfsSource, SecurityProfile, VolumeMount,
    },
};
use crate::{
    LogLevel, MicrosandboxError, MicrosandboxResult, Operation, UnsupportedReason,
    config::LocalConfig, size::Mebibytes,
};

//--------------------------------------------------------------------------------------------------
// Types
//--------------------------------------------------------------------------------------------------

/// Builder for constructing a [`SandboxConfig`] with a fluent API.
pub struct SandboxBuilder {
    config: SandboxConfig,
    detached: bool,
    build_error: Option<crate::MicrosandboxError>,
    max_cpus_explicit: bool,
    max_memory_explicit: bool,
    /// Raw script snippets supplied through construction patches. They are materialized only when
    /// building so later shell overrides determine their shebang.
    config_scripts: BTreeMap<String, String>,
    #[cfg(feature = "net")]
    configured_network_rules: Vec<Rule>,
    /// Pending snapshot reference (path or bare name) supplied via
    /// [`from_snapshot`]. Resolved during async `create()`.
    pending_snapshot: Option<String>,
    /// Distinguishes a sparse-patch snapshot, which later builder calls may override, from an
    /// explicit `from_snapshot` call that retains the established mutual-exclusion validation.
    pending_snapshot_from_config: bool,
}

/// Sub-builder for registry connection settings.
#[derive(Default)]
pub struct RegistryConfigBuilder {
    pub(crate) auth: Option<RegistryAuth>,
    pub(crate) insecure: bool,
    pub(crate) ca_certs: Vec<Vec<u8>>,
}

impl RegistryConfigBuilder {
    /// Set authentication credentials.
    pub fn auth(mut self, auth: RegistryAuth) -> Self {
        self.auth = Some(auth);
        self
    }

    /// Access the registry over plain HTTP instead of HTTPS.
    pub fn insecure(mut self) -> Self {
        self.insecure = true;
        self
    }

    /// Add PEM-encoded CA root certificates to trust.
    pub fn ca_certs(mut self, pem_data: Vec<u8>) -> Self {
        self.ca_certs.push(pem_data);
        self
    }
}

//--------------------------------------------------------------------------------------------------
// Methods
//--------------------------------------------------------------------------------------------------

impl SandboxBuilder {
    /// Start building a sandbox configuration.
    ///
    /// The name must be unique among existing sandboxes (unless
    /// [`replace`](Self::replace) is set) and no longer than 128 UTF-8 bytes.
    /// This low-level constructor starts from built-in defaults; prefer
    /// [`Sandbox::builder`](super::Sandbox::builder) when backend-owned global defaults should apply.
    pub fn new(name: impl Into<String>) -> Self {
        let mut config = SandboxConfig::default();
        config.spec.name = name.into();

        Self {
            config,
            detached: false,
            build_error: None,
            max_cpus_explicit: false,
            max_memory_explicit: false,
            config_scripts: BTreeMap::new(),
            #[cfg(feature = "net")]
            configured_network_rules: Vec::new(),
            pending_snapshot: None,
            pending_snapshot_from_config: false,
        }
    }

    /// Apply defaults owned by the selected local backend.
    ///
    /// This runs before caller-supplied builder methods, so explicit SDK and CLI options retain
    /// ordinary last-write-wins behavior. Root-disk defaults remain unresolved until local create,
    /// where the runtime knows the rootfs is OCI-backed and can persist the effective disk shape.
    pub(crate) fn with_local_defaults(mut self, local: &LocalConfig) -> Self {
        if let Err(error) = local.validate_sandbox_defaults() {
            self.build_error = Some(error);
            return self;
        }

        let defaults = &local.sandbox_defaults;
        self.config.spec.resources.cpus = defaults.cpus;
        self.config.spec.resources.max_cpus = defaults.cpus;
        self.config.spec.resources.memory_mib = defaults.memory_mib;
        self.config.spec.resources.max_memory_mib = defaults.memory_mib;
        self.config.spec.resources.cpu_placement = defaults.cpu_placement;
        self.config.spec.resources.placement_profile = defaults.placement_profile.clone();
        self.config.spec.resources.thp = defaults.thp;
        self.config.spec.runtime.shell = Some(defaults.shell.clone());
        self.config.spec.runtime.workdir = defaults.workdir.clone();
        self.config.spec.runtime.metrics_sample_interval_ms = defaults
            .metrics_sample_interval_ms
            .map(std::num::NonZero::get);
        self.config.spec.runtime.disable_metrics_sample = defaults.disable_metrics_sample;
        self.config.spec.runtime.log_level = local.log_level.map(sandbox_log_level_from_runtime);
        self
    }

    /// Seed a builder from a full [`SandboxSpec`] JSON.
    ///
    /// Options chained afterwards override individual fields (last-wins), just as
    /// on a builder from [`new`](Self::new). This is the Rust entry the FFI
    /// `create_from_spec` path calls into, so both share one implementation.
    pub fn from_spec_json(json: &str) -> MicrosandboxResult<Self> {
        let spec: SandboxSpec = serde_json::from_str(json)
            .map_err(|e| MicrosandboxError::InvalidConfig(e.to_string()))?;
        Ok(Self::from(SandboxConfig::from(spec)))
    }

    /// Set the root filesystem image source.
    ///
    /// - **`&str` / `String`**: Paths starting with `/`, `./`, or `../` are treated as local
    ///   paths. Everything else is treated as an OCI image reference. Disk image extensions
    ///   (`.qcow2`, `.raw`, `.vmdk`) resolve to virtio-blk block device rootfs.
    /// - **`PathBuf`**: Always treated as a local path.
    ///
    /// For explicit disk image configuration, see [`image_with`](Self::image_with).
    ///
    /// ```ignore
    /// .image("python:3.12")       // OCI image
    /// .image("./rootfs")          // local directory (bind mount)
    /// .image("./ubuntu.qcow2")   // disk image (auto-detect fs)
    /// ```
    pub fn image(mut self, image: impl IntoImage) -> Self {
        if self.pending_snapshot_from_config {
            self.pending_snapshot = None;
            self.pending_snapshot_from_config = false;
        }
        match image.into_rootfs_source() {
            Ok(rootfs) => self.config.spec.image = rootfs,
            Err(e) => {
                if self.build_error.is_none() {
                    self.build_error = Some(e);
                }
            }
        }
        self
    }

    /// Set the root filesystem image using a builder closure.
    ///
    /// ```ignore
    /// .image_with(|i| i.oci("python:3.12").root_disk(8.gib()))
    /// .image_with(|i| i.disk("./ubuntu.qcow2").fstype("ext4"))
    /// ```
    pub fn image_with(mut self, f: impl FnOnce(ImageBuilder) -> ImageBuilder) -> Self {
        if self.pending_snapshot_from_config {
            self.pending_snapshot = None;
            self.pending_snapshot_from_config = false;
        }
        match f(ImageBuilder::new()).build() {
            Ok(rootfs) => self.config.spec.image = rootfs,
            Err(e) => {
                if self.build_error.is_none() {
                    self.build_error = Some(e);
                }
            }
        }
        self
    }

    /// Apply a CLI-selected image after discarding a lower-precedence configured snapshot.
    #[doc(hidden)]
    pub fn override_image(mut self, image: impl IntoImage) -> Self {
        self.pending_snapshot = None;
        self.pending_snapshot_from_config = false;
        self.image(image)
    }

    /// Apply a CLI-selected image builder after discarding a configured snapshot.
    #[doc(hidden)]
    pub fn override_image_with(
        mut self,
        configure: impl FnOnce(ImageBuilder) -> ImageBuilder,
    ) -> Self {
        self.pending_snapshot = None;
        self.pending_snapshot_from_config = false;
        self.image_with(configure)
    }

    /// Apply a CLI-selected snapshot after discarding a lower-precedence configured image.
    #[doc(hidden)]
    pub fn override_snapshot(mut self, snapshot: impl Into<String>) -> Self {
        self.config.spec.image = RootfsSource::oci("");
        self.pending_snapshot = Some(snapshot.into());
        self.pending_snapshot_from_config = false;
        self
    }

    pub(super) fn config_snapshot(mut self, snapshot: impl Into<String>) -> Self {
        self.config.spec.image = RootfsSource::oci("");
        self.pending_snapshot = Some(snapshot.into());
        self.pending_snapshot_from_config = true;
        self
    }

    /// Set a managed root disk of the given size for an OCI rootfs.
    ///
    /// Sugar for `root_disk_with(|d| d.size(size))`.
    pub fn root_disk(self, size: impl Into<Mebibytes>) -> Self {
        let size = size.into();
        self.root_disk_with(|d| d.size(size))
    }

    /// Configure the writable rootfs layer (root disk) for an OCI rootfs.
    ///
    /// The root disk is a property of the OCI rootfs source, so this is sugar
    /// over [`image_with`](Self::image_with) and requires an OCI image to be
    /// set first. Prefer `image_with` when configuring the image and root disk
    /// together; this method exists for call sites, such as CLIs, where the
    /// image reference and its options are parsed separately.
    ///
    /// ```ignore
    /// .image("python").root_disk_with(|d| d.tmpfs().size(2.gib()))
    /// .image("python").root_disk_with(|d| d.disk_image("./scratch.img"))
    /// ```
    pub fn root_disk_with(
        mut self,
        configure: impl FnOnce(RootDiskBuilder) -> RootDiskBuilder,
    ) -> Self {
        let root_disk = match configure(RootDiskBuilder::default()).build() {
            Ok(root_disk) => root_disk,
            Err(e) => {
                if self.build_error.is_none() {
                    self.build_error = Some(e);
                }
                return self;
            }
        };
        match &mut self.config.spec.image {
            RootfsSource::Oci(oci) if !oci.reference.is_empty() => {
                oci.root_disk = Some(root_disk);
            }
            RootfsSource::Oci(_) => {
                if self.build_error.is_none() {
                    self.build_error = Some(crate::MicrosandboxError::InvalidConfig(
                        "root_disk() requires an OCI image to be set first".into(),
                    ));
                }
            }
            _ => {
                if self.build_error.is_none() {
                    self.build_error = Some(crate::MicrosandboxError::InvalidConfig(
                        "root_disk() is only valid for OCI images".into(),
                    ));
                }
            }
        }
        self
    }

    /// Set the writable overlay upper size for an OCI rootfs.
    #[deprecated(since = "0.6.0", note = "use `root_disk` instead")]
    pub fn oci_upper_size(self, size: impl Into<Mebibytes>) -> Self {
        self.root_disk(size)
    }

    /// Allocate virtual CPUs for this sandbox (default: 1).
    pub fn cpus(mut self, count: u8) -> Self {
        self.config.spec.resources.cpus = count;
        if !self.max_cpus_explicit || self.config.spec.resources.max_cpus < count {
            self.config.spec.resources.max_cpus = count;
        }
        self
    }

    /// Set the boot-time maximum possible virtual CPUs.
    ///
    /// This reserves the CPU hotplug capacity the sandbox may use after live
    /// resize support lands. It does not increase the effective vCPU count by
    /// itself; use [`cpus`](Self::cpus) for the initial effective count.
    pub fn max_cpus(mut self, count: u8) -> Self {
        self.config.spec.resources.max_cpus = count;
        self.max_cpus_explicit = true;
        self
    }

    /// Select how vCPU threads are placed on host processors.
    pub fn cpu_placement(mut self, policy: CpuPlacement) -> Self {
        self.config.spec.resources.cpu_placement = policy;
        self
    }

    /// Select a host-defined placement profile by name.
    pub fn placement_profile(mut self, profile: impl Into<String>) -> Self {
        self.config.spec.resources.placement_profile = Some(profile.into());
        self
    }

    /// Set guest memory size.
    ///
    /// Accepts bare `u32` (interpreted as MiB) or a [`SizeExt`](crate::size::SizeExt) helper:
    /// ```ignore
    /// .memory(512)         // 512 MiB
    /// .memory(512.mib())   // 512 MiB (explicit)
    /// .memory(1.gib())     // 1 GiB = 1024 MiB
    /// ```
    pub fn memory(mut self, size: impl Into<Mebibytes>) -> Self {
        let memory_mib = size.into().as_u32();
        self.config.spec.resources.memory_mib = memory_mib;
        if !self.max_memory_explicit || self.config.spec.resources.max_memory_mib < memory_mib {
            self.config.spec.resources.max_memory_mib = memory_mib;
        }
        self
    }

    /// Set the boot-time maximum hotpluggable guest memory.
    ///
    /// This reserves memory hotplug capacity for future live resize support.
    /// It does not increase the effective guest memory by itself; use
    /// [`memory`](Self::memory) for the initial effective memory.
    pub fn max_memory(mut self, size: impl Into<Mebibytes>) -> Self {
        self.config.spec.resources.max_memory_mib = size.into().as_u32();
        self.max_memory_explicit = true;
        self
    }

    /// Select the guest transparent huge-page policy applied at boot.
    ///
    /// `Madvise` is the default and uses huge pages only for mappings that
    /// request them. `Always` can improve large anonymous-memory workloads at
    /// the cost of coarser memory allocation, while `Never` disables THP.
    pub fn thp(mut self, policy: super::TransparentHugePagePolicy) -> Self {
        self.config.spec.resources.thp = policy;
        self
    }

    /// Set the runtime log level for the sandbox process.
    ///
    /// This controls the verbosity of the `msb sandbox` process.
    pub fn log_level(mut self, level: LogLevel) -> Self {
        self.config.spec.runtime.log_level = Some(sandbox_log_level_from_runtime(level));
        self
    }

    /// Disable runtime logs for this sandbox, even if a global default exists.
    pub fn quiet_logs(mut self) -> Self {
        self.config.spec.runtime.log_level = None;
        self
    }

    /// Configure whether the sandbox process is created in detached/background mode.
    ///
    /// Detached sandboxes survive the creating process. Defaults to `false`.
    pub fn detached(mut self, detached: bool) -> Self {
        self.detached = detached;
        self
    }

    /// Force-disable metrics sampling regardless of `metrics_sample_interval`.
    pub fn disable_metrics_sample(mut self) -> Self {
        self.config.spec.runtime.disable_metrics_sample = true;
        self
    }

    /// Override the metrics sampling interval; pass `Duration::ZERO` to disable.
    pub fn metrics_sample_interval(mut self, interval: Duration) -> Self {
        let ms = interval.as_millis();
        if ms > u128::from(u64::MAX) {
            if self.build_error.is_none() {
                self.build_error = Some(MicrosandboxError::InvalidConfig(format!(
                    "metrics sample interval {interval:?} overflows u64 milliseconds"
                )));
            }
            return self;
        }
        self.config.spec.runtime.metrics_sample_interval_ms =
            std::num::NonZero::new(ms as u64).map(std::num::NonZero::get);
        self
    }

    /// Default working directory for commands executed in this sandbox
    /// (e.g., `/app`). Used by [`exec`](super::Sandbox::exec),
    /// [`shell`](super::Sandbox::shell), and [`attach`](super::Sandbox::attach)
    /// unless overridden per-command.
    pub fn workdir(mut self, path: impl Into<String>) -> Self {
        self.config.spec.runtime.workdir = Some(path.into());
        self
    }

    /// Shell used by [`shell()`](super::Sandbox::shell) to interpret
    /// commands (default: `/bin/sh`).
    pub fn shell(mut self, shell: impl Into<String>) -> Self {
        self.config.spec.runtime.shell = Some(shell.into());
        self
    }

    /// Configure registry connection settings (auth, TLS, insecure).
    ///
    /// ```rust,ignore
    /// use microsandbox::{RegistryAuth, sandbox::Sandbox};
    ///
    /// let sb = Sandbox::builder("worker")
    ///     .image("localhost:5050/my-app:latest")
    ///     .registry(|r| r
    ///         .auth(RegistryAuth::Basic {
    ///             username: "user".into(),
    ///             password: "pass".into(),
    ///         })
    ///         .insecure()
    ///     )
    ///     .create()
    ///     .await
    ///     .unwrap();
    /// ```
    pub fn registry(
        mut self,
        f: impl FnOnce(RegistryConfigBuilder) -> RegistryConfigBuilder,
    ) -> Self {
        let builder = f(RegistryConfigBuilder::default());
        if let Some(auth) = builder.auth {
            self.config.registry_auth = Some(auth);
        }
        self.config.insecure = builder.insecure;
        self.config.ca_certs = builder.ca_certs;
        self
    }

    /// Request a globally-unique slug for the sandbox (cloud backends only).
    ///
    /// Lowercase letters, digits, and single hyphens. When unset, the cloud
    /// assigns one; create fails when the slug is already taken. The local
    /// backend has no slugs and ignores this with a warning.
    pub fn slug(mut self, slug: impl Into<String>) -> Self {
        self.config.slug = Some(slug.into());
        self
    }

    /// Replace an existing sandbox with the same name during create.
    ///
    /// If a sandbox with this name is already active, microsandbox stops
    /// the prior instance before recreating it: SIGTERM, wait up to ten
    /// seconds for a graceful exit, then SIGKILL. When the prior sandbox
    /// is owned by an in-process `Sandbox` handle, the handle's
    /// underlying child is signalled and reaped directly.
    ///
    /// To override the ten-second timeout, use [`replace_with_timeout`];
    /// pass `Duration::ZERO` to skip SIGTERM and SIGKILL immediately.
    ///
    /// [`replace_with_timeout`]: Self::replace_with_timeout
    pub fn replace(mut self) -> Self {
        self.config.replace_existing = true;
        self
    }

    /// Replace an existing sandbox, overriding the SIGTERM-to-SIGKILL
    /// timeout. Implies [`replace`](Self::replace) — calling this alone
    /// is enough.
    ///
    /// - `timeout > 0`: SIGTERM, wait up to `timeout`, then SIGKILL.
    /// - `timeout == Duration::ZERO`: SIGKILL immediately (skip SIGTERM).
    ///
    /// The default timeout used by [`replace`](Self::replace) is ten
    /// seconds. An expired timeout does not surface an error — the
    /// existing sandbox is force-killed and `create()` proceeds.
    pub fn replace_with_timeout(mut self, timeout: std::time::Duration) -> Self {
        self.config.replace_existing = true;
        self.config.replace_with_timeout = timeout;
        self
    }

    /// Override the OCI image entrypoint.
    pub fn entrypoint(mut self, cmd: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.config.spec.runtime.entrypoint = Some(cmd.into_iter().map(Into::into).collect());
        self
    }

    /// Override the OCI image command used by default-workload execution.
    ///
    /// An empty array clears the image CMD. This describes durable configuration and does not
    /// execute the command during sandbox creation.
    pub fn cmd(mut self, cmd: impl IntoIterator<Item = impl Into<String>>) -> Self {
        self.config.spec.runtime.cmd = Some(cmd.into_iter().map(Into::into).collect());
        self
    }

    /// Select the foreground command for attached CLI `run`.
    #[doc(hidden)]
    pub fn foreground_command(
        mut self,
        command: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.config
            .set_foreground_command(command.into_iter().map(Into::into).collect());
        self
    }

    /// Select the background command for detached CLI `run`.
    ///
    /// An empty command uses the image's default CMD. A non-empty command replaces CMD while
    /// preserving the effective OCI entrypoint.
    #[doc(hidden)]
    pub fn background_command(
        mut self,
        command: impl IntoIterator<Item = impl Into<String>>,
    ) -> Self {
        self.config
            .set_background_command(command.into_iter().map(Into::into).collect());
        self
    }

    /// Hand off PID 1 to a guest init binary after agentd's setup.
    ///
    /// `cmd` is either an absolute path inside the guest rootfs or
    /// the literal `"auto"`. Auto first honors a known init path at
    /// the start of the image ENTRYPOINT, preserving attached
    /// init-entrypoint commands when needed, then falls back to
    /// guest-side probing of common distro init paths.
    ///
    /// ```ignore
    /// .init("auto")
    /// .init("/lib/systemd/systemd")
    /// ```
    ///
    /// For init binaries that take argv or extra env (rare in
    /// practice), use [`init_with`](Self::init_with).
    ///
    /// `init` and `entrypoint` are orthogonal: `init` is the guest's
    /// PID 1; `entrypoint` is the user workload that agentd exec's
    /// per request. They can be combined freely.
    pub fn init(mut self, cmd: impl Into<String>) -> Self {
        self.config.spec.init = Some(HandoffInit {
            cmd: cmd.into(),
            args: Vec::new(),
            env: Vec::new(),
        });
        self
    }

    /// Hand off PID 1 with a closure-builder for argv and env. Use this
    /// when the init binary takes flags (e.g. systemd's
    /// `--unit=multi-user.target`) or needs extra env vars.
    ///
    /// ```ignore
    /// .init_with("/lib/systemd/systemd", |i| {
    ///     i.args(["--unit=multi-user.target"])
    ///      .env("container", "microsandbox")
    /// })
    /// ```
    ///
    /// Calling `.init` or `.init_with` more than once overwrites
    /// (different from `.env`, which appends). The init is
    /// pre-boot and one-shot.
    pub fn init_with(
        mut self,
        cmd: impl Into<String>,
        f: impl FnOnce(InitOptionsBuilder) -> InitOptionsBuilder,
    ) -> Self {
        let (args, env) = f(InitOptionsBuilder::default()).build();
        self.config.spec.init = Some(HandoffInit {
            cmd: cmd.into(),
            args,
            env,
        });
        self
    }

    /// Set the guest hostname. Limited to 64 UTF-8 bytes (the Linux UTS
    /// limit). Defaults to a sandbox-name-derived form when unset.
    pub fn hostname(mut self, hostname: impl Into<String>) -> Self {
        self.config.spec.runtime.hostname = Some(hostname.into());
        self
    }

    /// Set the user identity inside the sandbox (e.g., `"1000"`, `"appuser"`, `"1000:1000"`).
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.config.spec.runtime.user = Some(user.into());
        self
    }

    /// Set the pull policy for OCI images.
    pub fn pull_policy(mut self, policy: PullPolicy) -> Self {
        self.config.spec.pull_policy = policy;
        self
    }

    /// Disable all network access for this sandbox.
    ///
    /// Disables the network device entirely and sets the policy to
    /// [`NetworkPolicy::none()`](microsandbox_network::policy::NetworkPolicy::none)
    /// so the serialized config also reflects that networking is off.
    ///
    /// ```ignore
    /// .disable_network()
    /// ```
    #[cfg(feature = "net")]
    pub fn disable_network(mut self) -> Self {
        match self.config.local_network_config() {
            Ok(mut network) => {
                network.enabled = false;
                network.policy = microsandbox_network::policy::NetworkPolicy::none();
                if let Err(err) = self.config.set_local_network_config(network)
                    && self.build_error.is_none()
                {
                    self.build_error = Some(err);
                }
            }
            Err(err) => {
                if self.build_error.is_none() {
                    self.build_error = Some(err);
                }
            }
        }
        self
    }

    /// Configure networking via a closure.
    ///
    /// ```ignore
    /// .network(|n| n
    ///     .port(8080, 80)
    ///     .policy(NetworkPolicy::default())
    ///     .tls(|t| t.bypass("*.internal.com"))
    /// )
    /// ```
    #[cfg(feature = "net")]
    pub fn network(mut self, f: impl FnOnce(NetworkBuilder) -> NetworkBuilder) -> Self {
        let network = match self.config.local_network_config() {
            Ok(network) => network,
            Err(err) => {
                if self.build_error.is_none() {
                    self.build_error = Some(err);
                }
                return self;
            }
        };
        match f(NetworkBuilder::from_config(network)).build() {
            Ok(net) => {
                if let Err(err) = self.config.set_local_network_config(net)
                    && self.build_error.is_none()
                {
                    self.build_error = Some(err);
                }
            }
            Err(err) => {
                if self.build_error.is_none() {
                    self.build_error = Some(err.into());
                }
            }
        }
        self
    }

    /// Prepend explicit rules while preserving a configured policy's defaults and existing rules.
    #[cfg(feature = "net")]
    #[doc(hidden)]
    pub fn prepend_network_policy_rules(mut self, mut rules: Vec<Rule>) -> Self {
        match self.config.local_network_config() {
            Ok(mut network) => {
                rules.append(&mut network.policy.rules);
                network.policy.rules = rules;
                if let Err(error) = self.config.set_local_network_config(network)
                    && self.build_error.is_none()
                {
                    self.build_error = Some(error);
                }
            }
            Err(error) if self.build_error.is_none() => self.build_error = Some(error),
            Err(_) => {}
        }
        self
    }

    /// Replace policy defaults/profile rules while retaining rules supplied by a config patch.
    #[cfg(feature = "net")]
    #[doc(hidden)]
    pub fn replace_network_policy_preserving_config_rules(
        mut self,
        mut policy: NetworkPolicy,
    ) -> Self {
        policy.rules.extend(self.configured_network_rules.clone());
        match self.config.local_network_config() {
            Ok(mut network) => {
                network.policy = policy;
                if let Err(error) = self.config.set_local_network_config(network)
                    && self.build_error.is_none()
                {
                    self.build_error = Some(error);
                }
            }
            Err(error) if self.build_error.is_none() => self.build_error = Some(error),
            Err(_) => {}
        }
        self
    }

    /// Publish a TCP port directly on the sandbox builder.
    ///
    /// Repeatable: call multiple times to expose multiple ports.
    ///
    /// ```ignore
    /// .port(8080, 80)
    /// .port(3000, 3000)
    /// ```
    #[cfg(feature = "net")]
    pub fn port(mut self, host_port: u16, guest_port: u16) -> Self {
        self.push_port(
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            host_port,
            guest_port,
            PortProtocol::Tcp,
        );
        self
    }

    /// Publish a TCP port on a specific host bind address.
    ///
    /// ```ignore
    /// .port_bind("0.0.0.0".parse().unwrap(), 8080, 80)
    /// ```
    #[cfg(feature = "net")]
    pub fn port_bind(mut self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self {
        self.push_port(host_bind, host_port, guest_port, PortProtocol::Tcp);
        self
    }

    #[cfg(feature = "net")]
    fn push_port(
        &mut self,
        host_bind: IpAddr,
        host_port: u16,
        guest_port: u16,
        protocol: PortProtocol,
    ) {
        self.config.spec.network.ports.push(PublishedPortSpec {
            host_port,
            guest_port,
            protocol,
            host_bind: host_bind.to_string(),
        });
    }

    /// Publish a UDP port directly on the sandbox builder.
    ///
    /// Repeatable: call multiple times to expose multiple ports.
    ///
    /// ```ignore
    /// .port_udp(5353, 53)
    /// .port_udp(8125, 8125)
    /// ```
    #[cfg(feature = "net")]
    pub fn port_udp(mut self, host_port: u16, guest_port: u16) -> Self {
        self.push_port(
            IpAddr::V4(Ipv4Addr::LOCALHOST),
            host_port,
            guest_port,
            PortProtocol::Udp,
        );
        self
    }

    /// Publish a UDP port on a specific host bind address.
    #[cfg(feature = "net")]
    pub fn port_udp_bind(mut self, host_bind: IpAddr, host_port: u16, guest_port: u16) -> Self {
        self.push_port(host_bind, host_port, guest_port, PortProtocol::Udp);
        self
    }

    /// Expose a host Unix stream socket or local Windows named pipe on a guest-to-host vsock port.
    ///
    /// Guest applications connect directly to host CID 2 and `port`. No
    /// in-guest proxy or agentd integration is required.
    pub fn vsock(mut self, host_path: impl AsRef<Path>, port: u32) -> Self {
        self.config.spec.vsock.routes.push(VsockRouteSpec {
            host_socket: host_path.as_ref().to_path_buf(),
            port,
            socket_type: VsockSocketType::Stream,
        });
        self
    }

    /// Expose a host Unix datagram socket on a guest-to-host vsock port.
    ///
    /// Datagram boundaries are preserved end to end. Delivery remains
    /// best-effort, matching Unix and vsock datagram semantics. Windows does
    /// not support datagram routes.
    pub fn vsock_dgram(mut self, host_path: impl AsRef<Path>, port: u32) -> Self {
        self.config.spec.vsock.routes.push(VsockRouteSpec {
            host_socket: host_path.as_ref().to_path_buf(),
            port,
            socket_type: VsockSocketType::Dgram,
        });
        self
    }

    /// Add a fully specified guest-to-host vsock route.
    pub fn vsock_route(mut self, route: VsockRouteSpec) -> Self {
        self.config.spec.vsock.routes.push(route);
        self
    }

    /// Add a secret with placeholder-based protection via a closure.
    ///
    /// The sandbox receives a placeholder; the real value is substituted
    /// by the TLS proxy only for allowed hosts.
    ///
    /// ```ignore
    /// .secret(|s| s
    ///     .env("OPENAI_API_KEY")
    ///     .value(api_key)
    ///     .allow_host("api.openai.com")
    /// )
    /// ```
    ///
    /// Automatically enables TLS interception if not already enabled.
    #[cfg(feature = "net")]
    pub fn secret(self, f: impl FnOnce(SecretBuilder) -> SecretBuilder) -> Self {
        self.secret_entry(f(SecretBuilder::new()).build())
    }

    /// Add a materialized secret entry.
    #[cfg(feature = "net")]
    pub fn secret_entry(
        mut self,
        entry: microsandbox_network::secrets::config::SecretEntry,
    ) -> Self {
        match self.config.local_network_config() {
            Ok(mut network) => {
                network.secrets.secrets.push(entry);
                if !network.tls.enabled {
                    network.tls.enabled = true;
                }
                if let Err(err) = self.config.set_local_network_config(network)
                    && self.build_error.is_none()
                {
                    self.build_error = Some(err);
                }
            }
            Err(err) => {
                if self.build_error.is_none() {
                    self.build_error = Some(err);
                }
            }
        }
        self
    }

    /// Shorthand: add a secret with env var, value, and allowed host.
    ///
    /// Placeholder is auto-generated as `$MSB_<env_var>`.
    /// Automatically enables TLS interception.
    ///
    /// ```ignore
    /// .secret_env("OPENAI_API_KEY", api_key, "api.openai.com")
    /// ```
    ///
    /// **Plaintext at rest.** The value is persisted verbatim in the durable
    /// sandbox config and stays there until a later `modify` rotate with a
    /// source reference migrates the entry. This path exists for embedders
    /// who hold only a value (e.g. from their own vault); prefer
    /// `.secret(|s| s.source(..))` when the value can be referenced instead.
    /// Downstream behavior is identical either way: the guest sees only the
    /// placeholder, the proxy injects the value for allowed hosts, and
    /// in-memory copies are zeroized. When a host-side secret store lands,
    /// this method will import the value and store a reference — same
    /// signature, no more raw value at rest.
    #[cfg(feature = "net")]
    pub fn secret_env(
        self,
        env_var: impl Into<String>,
        value: impl Into<String>,
        allowed_host: impl Into<String>,
    ) -> Self {
        let env_var = env_var.into();
        let value = value.into();
        let allowed_host = allowed_host.into();
        self.secret(|s| s.env(&env_var).value(value).allow_host(allowed_host))
    }

    /// Set an environment variable visible to all commands in this sandbox.
    /// Can be called multiple times. Per-command env vars (on exec/shell)
    /// are merged on top.
    pub fn env(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        let key = key.into();
        if key.starts_with("MSB_") {
            if self.build_error.is_none() {
                self.build_error = Some(crate::MicrosandboxError::InvalidConfig(format!(
                    "environment variable {key:?} uses the reserved MSB_ prefix"
                )));
            }
            return self;
        }
        self.config.spec.env.push(EnvVar::new(key, value));
        self
    }

    /// Set multiple environment variables at once. See [`env`](Self::env).
    pub fn envs(
        mut self,
        vars: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (k, v) in vars {
            self = self.env(k, v);
        }
        self
    }

    /// Attach a label (`key`/`value`) to the sandbox for attribution.
    pub fn label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.config.spec.labels.insert(key.into(), value.into());
        self
    }

    /// Attach multiple labels at once. See [`label`](Self::label).
    pub fn labels(
        mut self,
        labels: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (k, v) in labels {
            self.config.spec.labels.insert(k.into(), v.into());
        }
        self
    }

    /// Set a sandbox-wide resource limit inherited by all guest processes.
    ///
    /// This is applied during agentd PID 1 startup, so bootstrap scripts and
    /// long-lived daemons inherit the raised baseline without needing explicit
    /// per-exec rlimits.
    pub fn rlimit(mut self, resource: RlimitResource, limit: u64) -> Self {
        self.config.spec.rlimits.push(Rlimit {
            resource,
            soft: limit,
            hard: limit,
        });
        self
    }

    /// Set a sandbox-wide resource limit with different soft/hard values.
    pub fn rlimit_range(mut self, resource: RlimitResource, soft: u64, hard: u64) -> Self {
        self.config.spec.rlimits.push(Rlimit {
            resource,
            soft,
            hard,
        });
        self
    }

    /// Register a script that will be mounted at `/.msb/scripts/<name>` in
    /// the guest. Scripts are added to `PATH` so they can be invoked by name
    /// via [`exec`](super::Sandbox::exec).
    pub fn script(mut self, name: impl Into<String>, content: impl Into<String>) -> Self {
        let name = name.into();
        self.config_scripts.remove(&name);
        self.config
            .spec
            .runtime
            .scripts
            .insert(name, content.into());
        self
    }

    /// Register multiple scripts at once. See [`script`](Self::script).
    pub fn scripts(
        mut self,
        scripts: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
    ) -> Self {
        for (name, content) in scripts {
            let name = name.into();
            self.config_scripts.remove(&name);
            self.config
                .spec
                .runtime
                .scripts
                .insert(name, content.into());
        }
        self
    }

    /// Mark the sandbox as ephemeral (or persistent).
    ///
    /// Ephemeral sandboxes are one-off: the host runtime that owns the
    /// process removes the persisted DB row and on-disk state once the VM
    /// reaches a terminal status, and other host runtimes opportunistically
    /// clean up leftovers from runtimes that died first. This sets policy
    /// intent only; enforcement is runtime-owned, never an SDK/CLI reaper.
    /// Defaults to persistent (`false`).
    ///
    /// Note: removing an ephemeral sandbox also drops its logs and captured
    /// output, since those live under the sandbox directory.
    pub fn ephemeral(mut self, ephemeral: bool) -> Self {
        self.config.spec.lifecycle.ephemeral = ephemeral;
        self
    }

    /// Set a maximum sandbox lifetime in seconds.
    pub fn max_duration(mut self, secs: u64) -> Self {
        self.config.spec.lifecycle.max_duration_secs = Some(secs);
        self
    }

    /// Auto-stop the sandbox after this many seconds of inactivity.
    /// Inactivity is detected via agentd heartbeat. Omit to disable (default).
    pub fn idle_timeout(mut self, secs: u64) -> Self {
        self.config.spec.lifecycle.idle_timeout_secs = Some(secs);
        self
    }

    /// Set the in-guest security profile.
    pub fn security(mut self, profile: SecurityProfile) -> Self {
        self.config.spec.security_profile = profile;
        self
    }

    /// Set the host-runtime deployment profile.
    ///
    /// Managed backends may replace this request with a platform-owned profile
    /// before launch. The cloud create wire does not transmit this value.
    pub fn deployment_profile(mut self, profile: DeploymentProfile) -> Self {
        self.config.spec.deployment_profile = profile;
        self
    }

    /// Add a volume mount using a closure-based builder.
    ///
    /// ```ignore
    /// .volume("/data", |m| m.bind("/host/data"))
    /// .volume("/config", |m| m.bind("/host/config").readonly())
    /// .volume("/cache", |m| m.named("my-cache"))
    /// .volume("/tmp", |m| m.tmpfs().size(100))
    /// ```
    pub fn volume(
        mut self,
        guest_path: impl Into<String>,
        f: impl FnOnce(MountBuilder) -> MountBuilder,
    ) -> Self {
        match f(MountBuilder::new(guest_path)).build() {
            Ok(mount) => self.config.spec.mounts.push(mount),
            Err(e) => {
                if self.build_error.is_none() {
                    self.build_error = Some(e);
                }
            }
        }
        self
    }

    /// Apply rootfs patches using a builder closure.
    ///
    /// Patches are applied before VM start. OCI roots bake patches into
    /// `upper.ext4`; bind roots patch the host directory directly. Returns an
    /// error at create time if used with block device roots (Qcow2, Raw).
    ///
    /// ```ignore
    /// .patch(|p| p
    ///     .text("/etc/app.conf", config_str, None, false)
    ///     .copy_file("./cert.pem", "/etc/ssl/cert.pem", None, false)
    ///     .mkdir("/var/cache/app", None)
    /// )
    /// ```
    pub fn patch(mut self, f: impl FnOnce(PatchBuilder) -> PatchBuilder) -> Self {
        self.config
            .spec
            .patches
            .extend(f(PatchBuilder::new()).build());
        self
    }

    /// Add a single patch directly.
    pub fn add_patch(mut self, patch: Patch) -> Self {
        self.config.spec.patches.push(patch);
        self
    }

    /// Add one already-materialized volume mount.
    #[doc(hidden)]
    pub fn add_volume_mount(mut self, mount: VolumeMount) -> Self {
        self.config.spec.mounts.push(mount);
        self
    }

    /// Boot a fresh sandbox from a snapshot artifact.
    ///
    /// The snapshot already pins the image reference and digest, so
    /// this method is mutually exclusive with [`image`](Self::image)
    /// and [`image_with`](Self::image_with). The snapshot is structurally
    /// opened at `create()` time; content verification stays explicit.
    ///
    /// `path_or_name` accepts either a path to a snapshot artifact
    /// directory (or a bare name resolved under the default snapshots
    /// directory).
    pub fn from_snapshot(mut self, path_or_name: impl Into<String>) -> Self {
        self.pending_snapshot = Some(path_or_name.into());
        self.pending_snapshot_from_config = false;
        self
    }

    /// Pre-populate the snapshot resolution for callers that opened
    /// the artifact synchronously and don't want the async manifest
    /// read that [`build`](Self::build) would otherwise perform.
    ///
    /// Used by the Python SDK helpers, where kwargs-style config
    /// construction has to stay synchronous. Callers that take this
    /// route are expected to also call [`image`](Self::image) with
    /// the snapshot's pinned image reference.
    pub fn snapshot_resolved(
        mut self,
        image_manifest_digest: impl Into<String>,
        upper_source: impl Into<std::path::PathBuf>,
    ) -> Self {
        self.config.manifest_digest = Some(image_manifest_digest.into());
        self.config.snapshot_upper_source = Some(upper_source.into());
        self
    }

    /// Build the configuration without creating the sandbox.
    ///
    /// If [`from_snapshot`](Self::from_snapshot) was called, the snapshot
    /// manifest is opened here and its pinned image reference, manifest
    /// digest, and upper-layer source path are populated onto the config.
    /// Backend-owned defaults were seeded before explicit builder methods were applied.
    pub async fn build(mut self) -> MicrosandboxResult<SandboxConfig> {
        self.materialize_config_scripts();
        self.resolve_pending().await?;
        self.validate()?;
        Ok(self.config)
    }

    pub(super) fn config_scripts(mut self, scripts: BTreeMap<String, String>) -> Self {
        self.config_scripts.extend(scripts);
        self
    }

    #[cfg(feature = "net")]
    pub(super) fn config_network_rules(mut self, rules: Vec<Rule>) -> Self {
        self.configured_network_rules = rules;
        self
    }

    pub(super) fn config_error(mut self, message: impl Into<String>) -> Self {
        if self.build_error.is_none() {
            self.build_error = Some(MicrosandboxError::InvalidConfig(message.into()));
        }
        self
    }

    fn materialize_config_scripts(&mut self) {
        let shell = self.config.spec.runtime.shell.as_deref();
        for (name, body) in std::mem::take(&mut self.config_scripts) {
            if let Err(message) = validate_config_script_name(&name) {
                if self.build_error.is_none() {
                    self.build_error = Some(MicrosandboxError::InvalidConfig(message));
                }
                continue;
            }
            self.config
                .spec
                .runtime
                .scripts
                .insert(name, wrap_config_script(shell, &body));
        }
    }

    /// Open the deferred snapshot artifact and copy its pinned image
    /// reference, manifest digest, and upper-layer source path into the
    /// config. Internal — driven by [`build`](Self::build).
    async fn resolve_pending(&mut self) -> MicrosandboxResult<()> {
        let Some(snapshot_ref) = self.pending_snapshot.take() else {
            return Ok(());
        };
        self.pending_snapshot_from_config = false;

        if self.has_explicit_rootfs_source() {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "from_snapshot is mutually exclusive with explicit rootfs configuration".into(),
            ));
        }

        let snap = crate::snapshot::Snapshot::open(&snapshot_ref).await?;
        if snap.manifest().scope != crate::snapshot::SnapshotScope::Disk {
            return Err(crate::MicrosandboxError::unsupported(
                Operation::SnapshotOps,
                UnsupportedReason::NotAvailable(
                    "restoring non-disk snapshots requires resumable restore support".into(),
                ),
            ));
        }
        let unsupported = snap.manifest().unsupported_requires();
        if !unsupported.is_empty() {
            return Err(crate::MicrosandboxError::unsupported(
                Operation::SnapshotOps,
                UnsupportedReason::NotAvailable(format!(
                    "snapshot requires unsupported runtime capabilities: {}",
                    unsupported.join(", ")
                )),
            ));
        }
        let file_state = match &snap.manifest().state {
            crate::snapshot::SnapshotState::File(state) => state,
            crate::snapshot::SnapshotState::Checkpoint(_) => {
                return Err(crate::MicrosandboxError::unsupported(
                    Operation::SnapshotOps,
                    UnsupportedReason::NotAvailable(
                        "checkpoint-state restore providers are not available".into(),
                    ),
                ));
            }
        };
        if file_state.format != crate::snapshot::SnapshotFormat::Raw || file_state.fstype != "ext4"
        {
            return Err(crate::MicrosandboxError::unsupported(
                Operation::SnapshotOps,
                UnsupportedReason::NotAvailable(format!(
                    "snapshot file state {:?}/{} is not qualified for restore",
                    file_state.format, file_state.fstype
                )),
            ));
        }
        let snap_ref = snap.manifest().image.reference.clone();

        self.config.spec.image = RootfsSource::oci(snap_ref);
        self.config.manifest_digest = Some(snap.manifest().image.manifest_digest.clone());
        self.config.snapshot_upper_source = Some(snap.path().join(&file_state.upper.file));
        Ok(())
    }

    fn has_explicit_rootfs_source(&self) -> bool {
        match &self.config.spec.image {
            RootfsSource::Oci(oci) => !oci.reference.is_empty() || oci.root_disk.is_some(),
            RootfsSource::Bind { path, .. } => !path.as_os_str().is_empty(),
            RootfsSource::DiskImage { .. } => true,
        }
    }

    /// Create the sandbox. Boots the VM with agentd ready.
    pub async fn create(self) -> MicrosandboxResult<super::Sandbox> {
        if self.detached {
            return self.create_detached().await;
        }
        let config = self.build().await?;
        super::Sandbox::create(config).await
    }

    /// Create the sandbox for detached/background use.
    pub async fn create_detached(self) -> MicrosandboxResult<super::Sandbox> {
        let config = self.build().await?;
        super::Sandbox::create_detached(config).await
    }

    /// Create the sandbox with pull progress reporting.
    ///
    /// Returns a progress handle for per-layer pull events and a task handle
    /// for the sandbox creation result. Useful for CLI commands that want to
    /// display per-layer download/materialization progress during sandbox creation.
    ///
    /// If the builder was configured via
    /// [`from_snapshot`](Self::from_snapshot), snapshot resolution
    /// happens inside the spawned task so this entry point stays
    /// synchronous.
    pub fn create_with_pull_progress(
        self,
    ) -> crate::MicrosandboxResult<(
        PullProgressHandle,
        tokio::task::JoinHandle<crate::MicrosandboxResult<super::Sandbox>>,
    )> {
        let (handle, sender) = microsandbox_image::progress_channel();
        let task = tokio::spawn(async move {
            let detached = self.detached;
            let config = self.build().await?;
            let backend = crate::backend::default_backend();
            match backend.kind() {
                crate::backend::BackendKind::Local => {
                    let mode = if detached {
                        crate::runtime::SpawnMode::Detached
                    } else {
                        crate::runtime::SpawnMode::Attached
                    };
                    // Pull progress is a local-only extension that is not part of
                    // SandboxBackend::create, so dispatch to the local backend's
                    // canonical create entry point explicitly.
                    let local = backend
                        .as_local()
                        .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxCreate))?;
                    local
                        .create_sandbox(backend.clone(), config, mode, Some(sender))
                        .await
                }
                crate::backend::BackendKind::Cloud => {
                    drop(sender);
                    if detached {
                        backend
                            .sandboxes()
                            .create_detached(backend.clone(), config)
                            .await
                    } else {
                        backend
                            .sandboxes()
                            .create(backend.clone(), config, true)
                            .await
                    }
                }
            }
        });
        Ok((handle, task))
    }

    /// Like `create_with_pull_progress` but spawns the sandbox process in detached
    /// mode so the sandbox survives after the creating process exits.
    pub fn create_detached_with_pull_progress(
        self,
    ) -> crate::MicrosandboxResult<(
        PullProgressHandle,
        tokio::task::JoinHandle<crate::MicrosandboxResult<super::Sandbox>>,
    )> {
        let (handle, sender) = microsandbox_image::progress_channel();
        let task = tokio::spawn(async move {
            let config = self.build().await?;
            let backend = crate::backend::default_backend();
            match backend.kind() {
                crate::backend::BackendKind::Local => {
                    let local = backend
                        .as_local()
                        .ok_or_else(|| MicrosandboxError::local_only(Operation::SandboxCreate))?;
                    local
                        .create_sandbox(
                            backend.clone(),
                            config,
                            crate::runtime::SpawnMode::Detached,
                            Some(sender),
                        )
                        .await
                }
                crate::backend::BackendKind::Cloud => {
                    drop(sender);
                    backend
                        .sandboxes()
                        .create_detached(backend.clone(), config)
                        .await
                }
            }
        });
        Ok((handle, task))
    }
}

impl SandboxBuilder {
    /// Validate the configuration before building.
    fn validate(&mut self) -> MicrosandboxResult<()> {
        if let Some(err) = self.build_error.take() {
            return Err(err);
        }

        if self.config.spec.name.is_empty() {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "sandbox name is required".into(),
            ));
        }
        super::validate_sandbox_name(&self.config.spec.name)?;
        super::validate_hostname(self.config.spec.runtime.hostname.as_deref())?;
        if self.config.spec.resources.cpus == 0 {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "cpus must be greater than 0".into(),
            ));
        }
        if self.config.spec.resources.memory_mib == 0 {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "memory must be greater than 0".into(),
            ));
        }
        if self.config.spec.resources.max_cpus == 0 {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "max_cpus must be greater than 0".into(),
            ));
        }
        if self.config.spec.resources.max_memory_mib == 0 {
            return Err(crate::MicrosandboxError::InvalidConfig(
                "max_memory must be greater than 0".into(),
            ));
        }
        if self.config.spec.resources.max_cpus < self.config.spec.resources.cpus {
            return Err(crate::MicrosandboxError::InvalidConfig(format!(
                "max_cpus {} must be greater than or equal to cpus {}",
                self.config.spec.resources.max_cpus, self.config.spec.resources.cpus
            )));
        }
        if self.config.spec.resources.max_memory_mib < self.config.spec.resources.memory_mib {
            return Err(crate::MicrosandboxError::InvalidConfig(format!(
                "max_memory {} MiB must be greater than or equal to memory {} MiB",
                self.config.spec.resources.max_memory_mib, self.config.spec.resources.memory_mib
            )));
        }

        // Check that image is set (non-empty OCI string or Bind path).
        match &self.config.spec.image {
            RootfsSource::Oci(oci) if oci.reference.is_empty() => {
                return Err(crate::MicrosandboxError::InvalidConfig(
                    "image source is required".into(),
                ));
            }
            RootfsSource::Oci(oci) => {
                self.validate_root_disk(oci.root_disk.as_ref())?;
            }
            RootfsSource::DiskImage { .. } if !self.config.spec.patches.is_empty() => {
                return Err(crate::MicrosandboxError::InvalidConfig(
                    "patches are not compatible with disk image rootfs".into(),
                ));
            }
            _ => {}
        }

        for rlimit in &self.config.spec.rlimits {
            if rlimit.soft > rlimit.hard {
                return Err(crate::MicrosandboxError::InvalidConfig(format!(
                    "rlimit {}: soft ({}) must not exceed hard ({})",
                    rlimit.resource.as_str(),
                    rlimit.soft,
                    rlimit.hard
                )));
            }
        }

        super::types::validate_volume_mounts(&self.config.spec.mounts)?;
        super::validate_env(&self.config.spec.env)?;
        super::validate_labels(&self.config.spec.labels)?;
        self.validate_vsock_routes()?;

        if let Err(error) = microsandbox_types::resolve_default_command(
            self.config.spec.runtime.entrypoint.as_deref(),
            self.config.spec.runtime.cmd.as_deref(),
            None,
        ) && !matches!(
            error,
            microsandbox_types::CommandResolutionError::NoDefaultCommand
        ) {
            return Err(error.into());
        }

        if let Some(spec) = &self.config.spec.init {
            super::init::validate(spec)?;
        }

        #[cfg(feature = "net")]
        self.config
            .local_network_config()?
            .secrets
            .validate()
            .map_err(|err| {
                crate::MicrosandboxError::InvalidConfig(format!("invalid network secrets: {err}"))
            })?;

        // Reject any two DiskImage mounts pointing at the same host file.
        // Each virtio-blk device caches independently on the host, so any
        // mix of writable+writable, writable+read-only, or even two
        // read-only mounts of the same image will diverge from the
        // kernel's view (RW invalidates the RO cache; RO+RO doubles the
        // page-cache footprint with no benefit). Compare against the
        // canonical path so symlinks and `./` prefixes don't bypass the
        // check.
        let mut seen: Vec<PathBuf> = Vec::new();
        for mount in &self.config.spec.mounts {
            if let VolumeMount::DiskImage { host, .. } = mount {
                let canonical = std::fs::canonicalize(host).map_err(|e| {
                    crate::MicrosandboxError::InvalidConfig(format!(
                        "disk image host path does not exist: {} ({e})",
                        host.display()
                    ))
                })?;
                if seen.contains(&canonical) {
                    return Err(crate::MicrosandboxError::InvalidConfig(format!(
                        "disk-image volumes cannot share the same host path: {}",
                        canonical.display()
                    )));
                }
                seen.push(canonical);
            }
        }

        Ok(())
    }

    /// Validate the stable route key and the host resources it references.
    fn validate_vsock_routes(&self) -> MicrosandboxResult<()> {
        if self.config.spec.deployment_profile == DeploymentProfile::MultiTenant
            && !self.config.spec.vsock.is_empty()
        {
            return Err(MicrosandboxError::InvalidConfig(
                "host vsock routes are disabled for multi-tenant deployments".into(),
            ));
        }

        let mut routes = HashSet::new();

        for route in &self.config.spec.vsock.routes {
            #[cfg(unix)]
            if !route.host_socket.is_absolute() {
                return Err(crate::MicrosandboxError::InvalidConfig(format!(
                    "vsock host path must be absolute: {}",
                    route.host_socket.display()
                )));
            }
            #[cfg(windows)]
            {
                let path = route.host_socket.as_os_str().to_string_lossy();
                let prefix = r"\\.\pipe\";
                let local = path
                    .get(..prefix.len())
                    .is_some_and(|candidate| candidate.eq_ignore_ascii_case(prefix));
                let name = path.get(prefix.len()..).unwrap_or_default();
                if !local
                    || name.is_empty()
                    || name
                        .split(['\\', '/'])
                        .any(|part| part.is_empty() || part == "." || part == "..")
                {
                    return Err(crate::MicrosandboxError::InvalidConfig(format!(
                        "vsock host path must be a local Windows named pipe such as \\\\.\\pipe\\api: {}",
                        route.host_socket.display()
                    )));
                }
                if route.socket_type == VsockSocketType::Dgram {
                    return Err(MicrosandboxError::unsupported(
                        Operation::SandboxCreate,
                        UnsupportedReason::RequiresUnixHost,
                    ));
                }
            }
            if route.port == 0 || route.port == u32::MAX {
                return Err(crate::MicrosandboxError::InvalidConfig(format!(
                    "vsock port {} must be between 1 and {}",
                    route.port,
                    u32::MAX - 1
                )));
            }
            // libkrun uses datagram port 123 for host-to-guest clock updates
            // on macOS. Reserving it everywhere keeps configurations portable.
            if route.socket_type == VsockSocketType::Dgram && route.port == 123 {
                return Err(crate::MicrosandboxError::InvalidConfig(
                    "vsock datagram port 123 is reserved for guest clock synchronization".into(),
                ));
            }
            if !routes.insert((route.socket_type, route.port)) {
                return Err(crate::MicrosandboxError::InvalidConfig(format!(
                    "duplicate vsock {:?} route for port {}",
                    route.socket_type, route.port
                )));
            }
        }

        Ok(())
    }

    /// Kind-specific root disk guards for an OCI rootfs.
    fn validate_root_disk(
        &self,
        root_disk: Option<&super::types::RootDisk>,
    ) -> MicrosandboxResult<()> {
        use super::types::RootDisk;

        match root_disk {
            None | Some(RootDisk::Managed { size_mib: None }) => Ok(()),
            Some(RootDisk::Managed { size_mib: Some(0) }) => {
                Err(crate::MicrosandboxError::InvalidConfig(
                    "root disk size must be greater than 0".into(),
                ))
            }
            Some(RootDisk::Managed { .. }) => Ok(()),
            Some(RootDisk::Tmpfs { size_mib }) => {
                if *size_mib == Some(0) {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "root disk size must be greater than 0".into(),
                    ));
                }
                // tmpfs pages come from guest RAM and the guest has no swap:
                // writes past memory are an OOM kill, not ENOSPC.
                if let Some(size) = size_mib
                    && *size > self.config.spec.resources.memory_mib
                {
                    return Err(crate::MicrosandboxError::InvalidConfig(format!(
                        "tmpfs root disk size ({size} MiB) must not exceed sandbox memory ({} MiB)",
                        self.config.spec.resources.memory_mib
                    )));
                }
                if !self.config.spec.patches.is_empty() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "patches require a managed root disk (they are baked into the upper at create time)".into(),
                    ));
                }
                if self.config.snapshot_upper_source.is_some() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "from_snapshot requires a managed root disk".into(),
                    ));
                }
                Ok(())
            }
            Some(RootDisk::DiskImage { path, .. }) => {
                if path.as_os_str().is_empty() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "disk-image root disk path must not be empty".into(),
                    ));
                }
                if !self.config.spec.patches.is_empty() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "patches require a managed root disk (they are baked into the upper at create time)".into(),
                    ));
                }
                if self.config.snapshot_upper_source.is_some() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "from_snapshot requires a managed root disk".into(),
                    ));
                }
                Ok(())
            }
            Some(RootDisk::Flat {
                size_mib, fstype, ..
            }) => {
                if *size_mib == Some(0) {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "flat root disk size must be greater than 0".into(),
                    ));
                }
                if fstype.as_deref().unwrap_or("ext4") != "ext4" {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "flat root disks currently support only fstype=ext4".into(),
                    ));
                }
                if !self.config.spec.patches.is_empty() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "patches are not yet compatible with flat OCI rootfs".into(),
                    ));
                }
                if self.config.snapshot_upper_source.is_some() {
                    return Err(crate::MicrosandboxError::InvalidConfig(
                        "from_snapshot is not yet compatible with flat OCI rootfs".into(),
                    ));
                }
                Ok(())
            }
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Functions
//--------------------------------------------------------------------------------------------------

fn validate_config_script_name(name: &str) -> Result<(), String> {
    let path = std::path::Path::new(name);
    if name.is_empty()
        || name == "."
        || name == ".."
        || name.as_bytes().contains(&0)
        || name.contains(['/', '\\'])
        || path.file_name().and_then(|part| part.to_str()) != Some(name)
    {
        return Err(format!(
            "script name {name:?} must be a single non-empty filename"
        ));
    }
    Ok(())
}

fn wrap_config_script(shell: Option<&str>, body: &str) -> String {
    let shell = shell.unwrap_or("/bin/sh");
    let mut script = if shell.contains('/') {
        format!("#!{shell}")
    } else {
        format!("#!/usr/bin/env {shell}")
    };
    script.push('\n');
    script.push_str(body);
    if !script.ends_with('\n') {
        script.push('\n');
    }
    script
}

//--------------------------------------------------------------------------------------------------
// Trait Implementations
//--------------------------------------------------------------------------------------------------

impl From<SandboxConfig> for SandboxBuilder {
    fn from(config: SandboxConfig) -> Self {
        Self {
            config,
            detached: false,
            build_error: None,
            max_cpus_explicit: true,
            max_memory_explicit: true,
            config_scripts: BTreeMap::new(),
            #[cfg(feature = "net")]
            configured_network_rules: Vec::new(),
            pending_snapshot: None,
            pending_snapshot_from_config: false,
        }
    }
}

//--------------------------------------------------------------------------------------------------
// Tests
//--------------------------------------------------------------------------------------------------

#[cfg(test)]
mod tests {
    use super::SandboxBuilder;
    use crate::LogLevel;
    use crate::sandbox::{MAX_HOSTNAME_BYTES, MAX_SANDBOX_NAME_BYTES, RlimitResource};
    #[cfg(feature = "net")]
    use microsandbox_network::secrets::config::{HostPattern, SecretEntry, SecretInjection};
    #[cfg(feature = "net")]
    use microsandbox_types::PortProtocol;
    use microsandbox_types::{
        CpuPlacement, DeploymentProfile, SandboxLogLevel, TransparentHugePagePolicy,
        VsockSocketType,
    };
    #[cfg(feature = "net")]
    use std::net::{IpAddr, Ipv4Addr};

    #[test]
    fn deployment_profile_sets_sandbox_spec() {
        let builder =
            SandboxBuilder::new("profile-test").deployment_profile(DeploymentProfile::MultiTenant);

        assert_eq!(
            builder.config.spec.deployment_profile,
            DeploymentProfile::MultiTenant
        );
    }

    #[tokio::test]
    async fn test_builder_sets_runtime_log_level() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .log_level(LogLevel::Debug)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.runtime.log_level, Some(SandboxLogLevel::Debug));
    }

    #[tokio::test]
    async fn test_builder_builds_config_with_shared_spec() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .cpus(2)
            .max_cpus(4)
            .cpu_placement(CpuPlacement::Spread)
            .memory(1024)
            .max_memory(4096)
            .thp(TransparentHugePagePolicy::Always)
            .log_level(LogLevel::Info)
            .env("A", "B")
            .script("setup", "echo hi")
            .max_duration(60)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.name, "test");
        assert_eq!(config.spec.resources.cpus, 2);
        assert_eq!(config.spec.resources.max_cpus, 4);
        assert_eq!(config.spec.resources.cpu_placement, CpuPlacement::Spread);
        assert_eq!(config.spec.resources.memory_mib, 1024);
        assert_eq!(config.spec.resources.max_memory_mib, 4096);
        assert_eq!(config.spec.resources.thp, TransparentHugePagePolicy::Always);
        assert_eq!(config.spec.runtime.log_level, Some(SandboxLogLevel::Info));
        assert_eq!(config.spec.env.len(), 1);
        assert_eq!(
            config.spec.runtime.scripts.get("setup"),
            Some(&"echo hi".into())
        );
        assert_eq!(config.spec.lifecycle.max_duration_secs, Some(60));
    }

    #[tokio::test]
    async fn test_builder_preserves_cmd_override_and_explicit_clears() {
        let configured = SandboxBuilder::new("test")
            .image("alpine")
            .cmd(["worker.py", "--once"])
            .build()
            .await
            .unwrap();
        assert_eq!(
            configured.spec.runtime.cmd,
            Some(vec!["worker.py".to_string(), "--once".to_string()])
        );

        let cleared = SandboxBuilder::new("test")
            .image("alpine")
            .entrypoint(Vec::<String>::new())
            .cmd(Vec::<String>::new())
            .build()
            .await
            .unwrap();
        assert_eq!(cleared.spec.runtime.entrypoint, Some(Vec::new()));
        assert_eq!(cleared.spec.runtime.cmd, Some(Vec::new()));
    }

    #[tokio::test]
    async fn test_builder_accepts_128_byte_sandbox_name() {
        let name = "x".repeat(MAX_SANDBOX_NAME_BYTES);
        let config = SandboxBuilder::new(name.clone())
            .image("alpine")
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.name, name);
    }

    #[tokio::test]
    async fn test_builder_rejects_over_128_byte_sandbox_name() {
        let name = "x".repeat(MAX_SANDBOX_NAME_BYTES + 1);
        let err = SandboxBuilder::new(name)
            .image("alpine")
            .build()
            .await
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "invalid config: sandbox name must be at most 128 characters: got 129"
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_zero_cpus() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .cpus(0)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("cpus must be greater than 0"));
    }

    #[tokio::test]
    async fn test_builder_rejects_zero_memory() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .memory(0)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("memory must be greater than 0"));
    }

    #[tokio::test]
    async fn test_builder_rejects_max_cpus_below_effective_cpus() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .cpus(4)
            .max_cpus(2)
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("max_cpus 2 must be greater than or equal to cpus 4")
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_max_memory_below_effective_memory() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .memory(2048)
            .max_memory(1024)
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("max_memory 1024 MiB must be greater than or equal to memory 2048 MiB")
        );
    }

    #[tokio::test]
    async fn test_builder_accepts_64_byte_hostname() {
        let hostname = "y".repeat(MAX_HOSTNAME_BYTES);
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .hostname(hostname.clone())
            .build()
            .await
            .unwrap();

        assert_eq!(
            config.spec.runtime.hostname.as_deref(),
            Some(hostname.as_str())
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_over_64_byte_hostname() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .hostname("y".repeat(MAX_HOSTNAME_BYTES + 1))
            .build()
            .await
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "invalid config: hostname is too long: 65 bytes (max 64)"
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_empty_hostname() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .hostname("")
            .build()
            .await
            .unwrap_err();

        assert_eq!(
            err.to_string(),
            "invalid config: hostname must not be empty"
        );
    }

    #[tokio::test]
    async fn test_builder_image_with_root_disk() {
        let config = SandboxBuilder::new("test")
            .image_with(|i| i.oci("alpine").root_disk(8192u32))
            .build()
            .await
            .unwrap();

        match &config.spec.image {
            super::RootfsSource::Oci(oci) => {
                assert_eq!(oci.reference, "alpine");
                assert_eq!(oci.root_disk, Some(crate::sandbox::RootDisk::managed(8192)));
            }
            other => panic!("expected Oci, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn test_builder_leaves_backend_root_disk_default_unmaterialized() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .build()
            .await
            .unwrap();

        assert!(config.spec.image.oci_root_disk().is_none());
    }

    #[tokio::test]
    async fn test_local_defaults_are_seeded_before_explicit_builder_options() {
        let mut local = crate::config::LocalConfig::default();
        local.sandbox_defaults.cpus = 4;
        local.sandbox_defaults.memory_mib = 2048;
        local.sandbox_defaults.cpu_placement = CpuPlacement::Spread;
        local.sandbox_defaults.thp = TransparentHugePagePolicy::Always;
        local.sandbox_defaults.shell = "/bin/bash".into();
        local.sandbox_defaults.workdir = Some("/workspace".into());
        local.log_level = Some(microsandbox_runtime::logging::LogLevel::Info);

        let config = SandboxBuilder::new("test")
            .with_local_defaults(&local)
            .image("alpine")
            .cpus(2)
            .thp(TransparentHugePagePolicy::Never)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.resources.cpus, 2);
        assert_eq!(config.spec.resources.max_cpus, 2);
        assert_eq!(config.spec.resources.memory_mib, 2048);
        assert_eq!(config.spec.resources.cpu_placement, CpuPlacement::Spread);
        assert_eq!(config.spec.resources.thp, TransparentHugePagePolicy::Never);
        assert_eq!(config.spec.runtime.shell.as_deref(), Some("/bin/bash"));
        assert_eq!(config.spec.runtime.workdir.as_deref(), Some("/workspace"));
        assert_eq!(
            config.spec.runtime.log_level,
            Some(microsandbox_types::SandboxLogLevel::Info)
        );
    }

    #[tokio::test]
    async fn test_builder_root_disk_rejects_bind_rootfs() {
        let err = SandboxBuilder::new("test")
            .image("/tmp/rootfs")
            .root_disk(8192u32)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("only valid for OCI images"));
    }

    #[tokio::test]
    async fn test_builder_root_disk_rejects_disk_image_rootfs() {
        let err = SandboxBuilder::new("test")
            .image_with(|i| i.disk("./rootfs.qcow2"))
            .root_disk(8192u32)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("only valid for OCI images"));
    }

    #[tokio::test]
    async fn test_builder_tmpfs_root_disk_rejects_size_over_memory() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .memory(1024u32)
            .root_disk_with(|d| d.tmpfs().size(2048u32))
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("must not exceed sandbox memory"));
    }

    #[tokio::test]
    async fn test_builder_tmpfs_root_disk_rejects_patches() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .root_disk_with(|d| d.tmpfs())
            .patch(|p| p.text("/etc/motd", "hello", None, true))
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("require a managed root disk"));
    }

    #[tokio::test]
    async fn test_builder_accepts_flat_root_disk() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .root_disk_with(|disk| {
                disk.flat()
                    .size(8192u32)
                    .clone_strategy(crate::sandbox::FlatClone::Copy)
            })
            .build()
            .await
            .unwrap();

        assert_eq!(
            config.spec.image.oci_root_disk(),
            Some(&crate::sandbox::RootDisk::Flat {
                size_mib: Some(8192),
                fstype: None,
                clone: crate::sandbox::FlatClone::Copy,
            })
        );
    }

    #[tokio::test]
    async fn test_builder_flat_root_disk_rejects_patches() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .root_disk_with(|disk| disk.flat())
            .patch(|patch| patch.text("/etc/motd", "hello", None, true))
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("not yet compatible with flat"));
    }

    #[tokio::test]
    async fn test_builder_deprecated_oci_upper_size_alias() {
        #[allow(deprecated)]
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .oci_upper_size(8192u32)
            .build()
            .await
            .unwrap();

        assert_eq!(
            config.spec.image.oci_root_disk(),
            Some(&crate::sandbox::RootDisk::managed(8192))
        );
    }

    #[tokio::test]
    async fn test_builder_from_snapshot_rejects_explicit_oci_image() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .from_snapshot("/tmp/missing-snapshot")
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("from_snapshot is mutually exclusive")
        );
    }

    #[tokio::test]
    async fn test_builder_from_snapshot_rejects_explicit_root_disk() {
        let err = SandboxBuilder::new("test")
            .image_with(|i| i.oci("").root_disk(8192u32))
            .from_snapshot("/tmp/missing-snapshot")
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("from_snapshot is mutually exclusive")
        );
    }

    #[tokio::test]
    async fn test_builder_from_snapshot_rejects_explicit_disk_image() {
        let err = SandboxBuilder::new("test")
            .image_with(|i| i.disk("./rootfs.raw"))
            .from_snapshot("/tmp/missing-snapshot")
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("from_snapshot is mutually exclusive")
        );
    }

    #[tokio::test]
    async fn test_builder_from_snapshot_rejects_explicit_bind_rootfs() {
        let err = SandboxBuilder::new("test")
            .image("/tmp/rootfs")
            .from_snapshot("/tmp/missing-snapshot")
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("from_snapshot is mutually exclusive")
        );
    }

    #[tokio::test]
    async fn test_builder_quiet_logs_clears_runtime_log_level() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .log_level(LogLevel::Trace)
            .quiet_logs()
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.runtime.log_level, None);
    }

    #[tokio::test]
    async fn test_builder_metrics_sample_interval_sets_ms() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .metrics_sample_interval(std::time::Duration::from_millis(750))
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.runtime.metrics_sample_interval_ms, Some(750));
    }

    #[tokio::test]
    async fn test_builder_metrics_sample_interval_zero_is_disabled() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .metrics_sample_interval(std::time::Duration::ZERO)
            .build()
            .await
            .unwrap();

        assert!(config.spec.runtime.metrics_sample_interval_ms.is_none());
        assert!(config.effective_metrics_interval().is_none());
    }

    #[tokio::test]
    async fn test_builder_disable_metrics_sample_overrides_interval() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .metrics_sample_interval(std::time::Duration::from_millis(5000))
            .disable_metrics_sample()
            .build()
            .await
            .unwrap();

        assert!(config.spec.runtime.disable_metrics_sample);
        assert_eq!(config.spec.runtime.metrics_sample_interval_ms, Some(5000));
        assert!(config.effective_metrics_interval().is_none());
    }

    #[tokio::test]
    async fn test_builder_replace_sets_replace_existing() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .replace()
            .build()
            .await
            .unwrap();

        assert!(config.replace_existing);
    }

    #[tokio::test]
    async fn test_builder_defaults_to_persistent() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .build()
            .await
            .unwrap();

        assert!(!config.spec.lifecycle.ephemeral);
    }

    #[tokio::test]
    async fn test_builder_ephemeral_sets_policy() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .ephemeral(true)
            .build()
            .await
            .unwrap();

        assert!(config.spec.lifecycle.ephemeral);
    }

    #[tokio::test]
    async fn test_builder_rlimit_sets_sandbox_wide_limit() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .rlimit(RlimitResource::Nofile, 65_535)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.rlimits.len(), 1);
        assert_eq!(config.spec.rlimits[0].resource, RlimitResource::Nofile);
        assert_eq!(config.spec.rlimits[0].soft, 65_535);
        assert_eq!(config.spec.rlimits[0].hard, 65_535);
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_ports_are_repeatable() {
        let bind = "0.0.0.0".parse().unwrap();
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .port(8080, 80)
            .port(3000, 3000)
            .port_udp(5353, 53)
            .port_bind(bind, 8081, 81)
            .port_udp_bind(bind, 5354, 54)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.network.ports.len(), 5);
        assert_eq!(config.spec.network.ports[0].host_port, 8080);
        assert_eq!(config.spec.network.ports[0].guest_port, 80);
        assert_eq!(config.spec.network.ports[0].protocol, PortProtocol::Tcp);
        assert_eq!(
            config.spec.network.ports[0].host_bind,
            IpAddr::V4(Ipv4Addr::LOCALHOST).to_string()
        );
        assert_eq!(config.spec.network.ports[1].host_port, 3000);
        assert_eq!(config.spec.network.ports[1].guest_port, 3000);
        assert_eq!(config.spec.network.ports[1].protocol, PortProtocol::Tcp);
        assert_eq!(config.spec.network.ports[2].host_port, 5353);
        assert_eq!(config.spec.network.ports[2].guest_port, 53);
        assert_eq!(config.spec.network.ports[2].protocol, PortProtocol::Udp);
        assert_eq!(config.spec.network.ports[3].host_bind, bind.to_string());
        assert_eq!(config.spec.network.ports[3].host_port, 8081);
        assert_eq!(config.spec.network.ports[3].guest_port, 81);
        assert_eq!(config.spec.network.ports[3].protocol, PortProtocol::Tcp);
        assert_eq!(config.spec.network.ports[4].host_bind, bind.to_string());
        assert_eq!(config.spec.network.ports[4].host_port, 5354);
        assert_eq!(config.spec.network.ports[4].guest_port, 54);
        assert_eq!(config.spec.network.ports[4].protocol, PortProtocol::Udp);
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_builder_vsock_routes_preserve_socket_type() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .vsock("/run/host-api.sock", 5000)
            // Stream and datagram namespaces are independent.
            .vsock_dgram("/run/events.sock", 5000)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.vsock.routes.len(), 2);
        assert_eq!(
            config.spec.vsock.routes[0].socket_type,
            VsockSocketType::Stream
        );
        assert_eq!(
            config.spec.vsock.routes[1].socket_type,
            VsockSocketType::Dgram
        );
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_builder_rejects_duplicate_vsock_route_key() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .vsock("/run/one.sock", 5000)
            .vsock("/run/two.sock", 5000)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("duplicate vsock Stream route"));
    }

    #[cfg(unix)]
    #[tokio::test]
    async fn test_builder_rejects_reserved_timesync_datagram_port() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .vsock_dgram("/run/events.sock", 123)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("reserved for guest clock"));
    }

    #[tokio::test]
    async fn test_builder_rejects_vsock_for_multi_tenant_deployments() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .deployment_profile(DeploymentProfile::MultiTenant)
            .vsock("/run/host-api.sock", 5000)
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("multi-tenant"));
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn test_builder_accepts_local_named_pipe_stream_route() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .vsock(r"\\.\pipe\host-api", 5000)
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.vsock.routes.len(), 1);
        assert_eq!(
            config.spec.vsock.routes[0].socket_type,
            VsockSocketType::Stream
        );
    }

    #[cfg(windows)]
    #[tokio::test]
    async fn test_builder_rejects_remote_named_pipe_and_datagram() {
        let remote = SandboxBuilder::new("test")
            .image("alpine")
            .vsock(r"\\server\pipe\host-api", 5000)
            .build()
            .await
            .unwrap_err();
        assert!(remote.to_string().contains("local Windows named pipe"));

        let datagram = SandboxBuilder::new("test")
            .image("alpine")
            .vsock_dgram(r"\\.\pipe\events", 5001)
            .build()
            .await
            .unwrap_err();
        assert!(datagram.to_string().contains("Unix host"));
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_disable_network_denies_all() {
        use microsandbox_network::policy::Action;

        let config = SandboxBuilder::new("test")
            .image("alpine")
            .disable_network()
            .build()
            .await
            .unwrap();

        let network = config.local_network_config().unwrap();
        assert!(!network.enabled);
        // `disable_network()` uses `NetworkPolicy::none()` which is deny-all
        // in both directions with no rules.
        assert_eq!(network.policy.default_egress, Action::Deny);
        assert_eq!(network.policy.default_ingress, Action::Deny);
        assert!(network.policy.rules.is_empty());
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_network_preserves_top_level_settings() {
        let config = SandboxBuilder::new("test")
            .image("alpine")
            .port(8080, 80)
            .secret_env("OPENAI_API_KEY", "secret", "api.openai.com")
            .network(|n| n.max_connections(128))
            .build()
            .await
            .unwrap();

        assert_eq!(config.spec.network.ports.len(), 1);
        assert_eq!(config.spec.network.ports[0].host_port, 8080);
        assert_eq!(config.spec.network.ports[0].guest_port, 80);
        assert_eq!(config.spec.network.ports[0].protocol, PortProtocol::Tcp);
        let network = config.local_network_config().unwrap();
        assert_eq!(network.secrets.secrets.len(), 1);
        assert_eq!(network.max_connections, Some(128));
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_network_rate_limiters_land_in_the_spec() {
        use std::time::Duration;

        use microsandbox_utils::size::SizeExt;

        let config = SandboxBuilder::new("test")
            .image("alpine")
            .network(|n| {
                n.rate_limiter(|r| {
                    r.egress(|r| {
                        r.bandwidth(1.mib(), Duration::from_secs(1))
                            .bandwidth_burst(512.kib())
                            .ops(1_000, Duration::from_secs(1))
                            .ops_burst(500)
                    })
                })
            })
            .build()
            .await
            .unwrap();

        let rate_limiter = config
            .spec
            .network
            .rate_limiter
            .as_ref()
            .expect("network rate limiter persisted");
        let egress = rate_limiter
            .egress
            .as_ref()
            .expect("egress limiter persisted");
        let bandwidth = egress.bandwidth.as_ref().unwrap();
        assert_eq!(bandwidth.size, 1024 * 1024);
        assert_eq!(bandwidth.refill_time_ms, 1000);
        assert_eq!(bandwidth.one_time_burst, 512 * 1024);
        assert_eq!(egress.ops.as_ref().unwrap().one_time_burst, 500);
        assert!(rate_limiter.ingress.is_none());
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_rejects_invalid_rate_limiter() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .network(|n| n.rate_limiter(|r| r.ingress(|r| r)))
            .build()
            .await
            .unwrap_err();

        assert!(
            err.to_string()
                .contains("rate limiter must configure at least one of bandwidth or ops"),
            "unexpected error: {err}"
        );
    }

    #[cfg(feature = "net")]
    #[tokio::test]
    async fn test_builder_rejects_invalid_secret_config() {
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .secret_entry(SecretEntry {
                env_var: "API\0KEY".into(),
                value: zeroize::Zeroizing::new("secret".into()),
                source: None,
                placeholder: "$MSB_API_KEY".into(),
                allowed_hosts: vec![HostPattern::Exact("api.example.com".into())],
                injection: SecretInjection::default(),
                on_violation: None,
                require_tls_identity: true,
            })
            .build()
            .await
            .unwrap_err();

        assert!(err.to_string().contains("env_var must not contain NUL"));
    }

    //----------------------------------------------------------------------------------------------
    // DiskImage host-path validation
    //----------------------------------------------------------------------------------------------

    /// Helper: stage two files in a tempdir, return absolute paths.
    fn two_disk_files() -> (tempfile::TempDir, std::path::PathBuf, std::path::PathBuf) {
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("a.qcow2");
        let b = dir.path().join("b.qcow2");
        std::fs::write(&a, []).unwrap();
        std::fs::write(&b, []).unwrap();
        (dir, a, b)
    }

    #[tokio::test]
    async fn test_builder_rejects_two_writable_same_host() {
        let (_dir, a, _) = two_disk_files();
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(a.clone()))
            .volume("/y", |v| v.disk(a.clone()))
            .build()
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("disk-image volumes cannot share the same host path")
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_writable_plus_readonly_same_host() {
        // Mixed writable+readonly still corrupts because the writable side's
        // host page cache invalidates the readonly side's view.
        let (_dir, a, _) = two_disk_files();
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(a.clone()))
            .volume("/y", |v| v.disk(a.clone()).readonly())
            .build()
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("disk-image volumes cannot share the same host path")
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_two_readonly_same_host() {
        let (_dir, a, _) = two_disk_files();
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(a.clone()).readonly())
            .volume("/y", |v| v.disk(a.clone()).readonly())
            .build()
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("disk-image volumes cannot share the same host path")
        );
    }

    #[tokio::test]
    async fn test_builder_accepts_two_writable_different_hosts() {
        let (_dir, a, b) = two_disk_files();
        SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(a))
            .volume("/y", |v| v.disk(b))
            .build()
            .await
            .unwrap();
    }

    #[tokio::test]
    async fn test_builder_canonicalizes_host_paths() {
        // /foo/./bar resolves to the same canonical as /foo/bar; the check
        // must catch this even though the byte strings differ.
        let dir = tempfile::tempdir().unwrap();
        let a = dir.path().join("a.qcow2");
        std::fs::write(&a, []).unwrap();
        let parent = a.parent().unwrap();
        let dotted = parent.join(".").join("a.qcow2");

        let err = SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(a))
            .volume("/y", |v| v.disk(dotted))
            .build()
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("disk-image volumes cannot share the same host path")
        );
    }

    #[tokio::test]
    async fn test_builder_rejects_missing_disk_host() {
        let dir = tempfile::tempdir().unwrap();
        let nonexistent = dir.path().join("nope.qcow2");
        let err = SandboxBuilder::new("test")
            .image("alpine")
            .volume("/x", |v| v.disk(nonexistent))
            .build()
            .await
            .unwrap_err();
        assert!(
            err.to_string()
                .contains("disk image host path does not exist")
        );
    }

    //----------------------------------------------------------------------------------------------
    // Sandbox name validation
    //----------------------------------------------------------------------------------------------

    #[test]
    fn sandbox_name_accepts_typical() {
        for name in [
            "foo",
            "foo-bar",
            "foo.bar",
            "foo_bar",
            "FooBar",
            "abc123",
            "a",
            "0",
            "agent-1",
            "my.app_2026",
        ] {
            assert!(
                crate::sandbox::validate_sandbox_name(name).is_ok(),
                "expected {name:?} to be accepted"
            );
        }
    }

    #[test]
    fn sandbox_name_rejects_empty() {
        assert!(crate::sandbox::validate_sandbox_name("").is_err());
    }

    #[test]
    fn sandbox_name_rejects_too_long() {
        let long = "a".repeat(MAX_SANDBOX_NAME_BYTES + 1);
        assert!(crate::sandbox::validate_sandbox_name(&long).is_err());
    }

    #[test]
    fn sandbox_name_accepts_at_max_length() {
        let max = "a".repeat(MAX_SANDBOX_NAME_BYTES);
        assert!(crate::sandbox::validate_sandbox_name(&max).is_ok());
    }

    #[test]
    fn sandbox_name_rejects_disallowed_chars() {
        for name in [
            "foo bar", "foo/bar", "foo:bar", "foo!", "foo@bar", "foo#1", "",
        ] {
            assert!(
                crate::sandbox::validate_sandbox_name(name).is_err(),
                "expected {name:?} to be rejected"
            );
        }
    }

    #[test]
    fn sandbox_name_rejects_non_alphanumeric_start() {
        for name in [".foo", "-foo", "_foo"] {
            assert!(
                crate::sandbox::validate_sandbox_name(name).is_err(),
                "expected {name:?} to be rejected (non-alphanumeric start)"
            );
        }
    }

    #[tokio::test]
    async fn builder_validate_rejects_bad_name() {
        let err = SandboxBuilder::new("bad name!")
            .image("alpine")
            .build()
            .await
            .unwrap_err();
        assert!(err.to_string().contains("alphanumeric"), "got: {err}");
    }
}