mxc-sdk 1.0.1

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

// The Hyperlight + Unikraft micro-VM host library is x86_64-only (KVM
// on Linux, WHP on Windows) AND is an optional dependency gated by the
// `hyperlight` cargo feature. On other targets, or when the feature is
// disabled, this crate compiles to an empty library so workspace builds
// (`cargo build --workspace`) on ARM64 hosts and feature-less builds
// (e.g. `cargo build --features microvm`) succeed without pulling in
// hyperlight-host. Consumers gate their use of `HyperlightScriptRunner`
// on `target_arch = "x86_64"` and the `hyperlight` cargo feature.
#![cfg(all(feature = "hyperlight", target_arch = "x86_64"))]

//! `HyperlightScriptRunner` — executes Python code inside a Hyperlight + Unikraft
//! micro-VM, driven by the `hyperlight-unikraft` library.
//!
//! | Property            | Value                                                     |
//! |---------------------|-----------------------------------------------------------|
//! | Backing micro-VM    | Unikraft unikernel in a Hyperlight micro-VM               |
//! | Host platform       | Linux (KVM) + Windows (WHP)                               |
//! | Execution model     | Embedded library, in-process                              |
//! | Script delivery     | `AppSandbox::run`, or `submit` + `step` under a deadline  |
//! | Cold start          | Snapshot restore (~50–60 ms)                               |
//! | Filesystem          | Host dir mounts via `Mount`                               |
//! | Networking          | Disabled for supported requests                           |
//! | Script I/O          | Host's stdout/stderr (HostPrint)                          |
//! | stdlib coverage     | Full CPython + preloaded ML stack (numpy, pandas, etc.)   |
//!
//! ## Image-home resolution
//!
//! The runner looks for a warmed image in this order, first hit wins:
//!
//!   1. `$MXC_HYPERLIGHT_HOME` (searched first when set)
//!   2. `~/.local/share/mxc-hyperlight/` on Linux (XDG_DATA_HOME compliant)
//!      `%LOCALAPPDATA%\mxc-hyperlight\` on Windows
//!   3. `<exe_dir>/mxc-hyperlight/` (dev build next to the target binary)
//!   4. `<cwd>/.mxc-hyperlight/` (dev fallback)
//!
//! Path #2 is the "default". `--setup-hyperlight` installs here when nothing
//! else is already populated — so one eager install persists across
//! shell sessions, across reboots, and across `cargo install` upgrades.
//!
//! An image home holds one directory per guest runtime (`agent/`, `node/`,
//! ...), each with that runtime's rootfs (`initrd.cpio`), its warmed
//! `snapshot/` directory, and a `VERSION` stamp naming the rootfs release.
//! The Unikraft kernel is embedded in the `hyperlight-unikraft` crate, so
//! nothing else is downloaded. A snapshot loads only under a build with
//! its snapshot key (the crate's kernel and host contract), and a rootfs
//! only boots on its own release's kernel, so a home whose stamp or
//! snapshot key is another build's is treated as not installed:
//! `--setup-hyperlight` rebuilds it, and a run warms a new snapshot by
//! itself when only the snapshot is stale.
//!
//! ## Setup
//!
//! `lxc-exec --setup-hyperlight[=RUNTIME,...]` (or `wxc-exec`) pulls each
//! runtime's published rootfs straight from GHCR (no container runtime
//! needed), boots it once, and persists the warmed guest as a snapshot in
//! the default home. `agent` is the default runtime; a request's
//! `hyperlight.runtime` selects another.
//!
//! On first `run` (if setup was skipped) the runner also does a lazy
//! auto-install if `initrd.cpio` is already in the resolved home but no
//! snapshot is — cheap safety net.
//!
//! ## Filesystem policy
//!
//! `policy.readwritePaths` and `policy.readonlyPaths` are translated to
//! [`Mount`] entries — the guest sees the host directories at
//! `/host/<basename>`. `readonlyPaths` are mounted read-only, which the
//! guest kernel enforces (`EROFS`) and the host's `fs_*` functions enforce
//! again.
//!
//! The persisted snapshot is warmed without mounts; the kernel builds its
//! mount table from the mounts a restore names, so every request restores
//! the same warm image, mounts or not.
//!
//! `policy.deniedPaths` is honored: any path that appears in the denied
//! list is rejected at preflight — including paths that also appear in
//! the allow lists.
//!
//! ## I/O model
//!
//! The guest's `print(...)` goes through Hyperlight's HostPrint callback,
//! which writes to the **host process's stdout**. `ScriptResponse.standard_out`
//! and `standard_err` stay empty; consumers that need captured output
//! redirect wxc-exec's stdout/stderr at the process level.
//!
//! ## Exit codes
//!
//! Guest exit code on clean completion (0 for normal exit, non-zero for
//! `sys.exit(N)` or unhandled exceptions), -1 on any runner error
//! (preflight, install, runtime, guest crash, timeout). The specific
//! failure mode is in `error_message`.

use std::path::{Path, PathBuf};
use std::sync::mpsc::{self, RecvTimeoutError};
use std::sync::Arc;
use std::time::{Duration, Instant};

use crate::mxc_common::logger::Logger;
use crate::mxc_common::models::{ExecutionRequest, HyperlightRuntime, ScriptResponse};
use crate::mxc_common::script_runner::ScriptRunner;
use crate::mxc_common::validator::{
    validate_common, validate_network_policy_support, NetworkPolicySupport,
};

use hyperlight_unikraft::hyperlight_host::HyperlightError;
use hyperlight_unikraft::{AppSandbox, Mount, SandboxBuilder, Snapshot, Yield};

// -- Availability probe -------------------------------------------------------

/// Whether KVM is usable by this process: `/dev/kvm` opens for reading and
/// writing. Setup and a run check it before booting anything.
#[cfg(target_os = "linux")]
pub fn is_kvm_available() -> bool {
    std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open("/dev/kvm")
        .is_ok()
}

/// WHP is delay-loaded; check before setup or a run boots a VM.
#[cfg(target_os = "windows")]
pub fn is_whp_available() -> bool {
    use windows::core::w;
    use windows::Win32::System::LibraryLoader::{LoadLibraryExW, LOAD_LIBRARY_SEARCH_SYSTEM32};

    // SAFETY: LOAD_LIBRARY_SEARCH_SYSTEM32 restricts to %SystemRoot%\system32.
    let module =
        unsafe { LoadLibraryExW(w!("winhvplatform.dll"), None, LOAD_LIBRARY_SEARCH_SYSTEM32) };
    module.is_ok()
}

// -- Error classification ----------------------------------------------------

#[derive(Debug)]
enum RunnerError {
    /// Pre-spawn validation failures (missing image, unsupported policy).
    Preflight(String),
    /// Runtime construction, install, or execution failure.
    Runtime(String),
}

impl std::fmt::Display for RunnerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RunnerError::Preflight(msg) => write!(f, "hyperlight preflight error: {msg}"),
            RunnerError::Runtime(msg) => write!(f, "hyperlight runtime error: {msg}"),
        }
    }
}

impl RunnerError {
    fn to_response(&self) -> ScriptResponse {
        ScriptResponse {
            exit_code: ERROR_EXIT_CODE,
            error_message: self.to_string(),
            ..Default::default()
        }
    }
}

const ERROR_EXIT_CODE: i32 = -1;

/// Env var override for the Hyperlight image home. Set this to force a
/// specific location; otherwise the runner uses a standard OS-local
/// data path (~/.local/share/mxc-hyperlight on Linux, %LOCALAPPDATA%\mxc-hyperlight on
/// Windows).
const HOME_ENV: &str = "MXC_HYPERLIGHT_HOME";
/// Subdirectory used next to the running executable (dev builds).
const EXE_RELATIVE_HOME: &str = "mxc-hyperlight";
/// Subdirectory used in the cwd as a last resort (dev fallback).
const CWD_RELATIVE_HOME: &str = ".mxc-hyperlight";
/// Final component of the default OS-local data path.
const DEFAULT_HOME_LEAF: &str = "mxc-hyperlight";

/// The guest rootfs (a CPIO archive) inside an image home. The kernel is
/// embedded in the `hyperlight-unikraft` crate, so this is the only
/// artifact an install needs.
const INITRD_FILE: &str = "initrd.cpio";
/// The warmed snapshot (an OCI image layout) inside an image home.
const SNAPSHOT_DIR: &str = "snapshot";
/// Stamp `setup` writes beside the rootfs, naming the release it holds.
const VERSION_FILE: &str = "VERSION";

/// Pinned to the `hyperlight-unikraft` release in Cargo.toml: a rootfs
/// only boots on the kernel and driver protocol of its own release.
const ROOTFS_TAG: &str = "initrd-v0.17.0";
const ROOTFS_PATH_IN_IMAGE: &str = "/initrd.cpio";
/// Where host directories appear in the guest: `/host/<basename>`.
const GUEST_MOUNT_ROOT: &str = "/host";
/// The executor whose `--setup-hyperlight` installs an image, for hints.
const SETUP_BIN: &str = if cfg!(windows) {
    "wxc-exec"
} else {
    "lxc-exec"
};

/// What a guest runtime is built from.
struct RuntimeImage {
    /// The published rootfs, `ghcr.io/<owner>/<repo>/<image>`, named as
    /// the runtime is. Its `:initrd-<version>` tag wraps the runnable CPIO
    /// in a scratch image at [`ROOTFS_PATH_IN_IMAGE`].
    image: String,
    /// Scratch memory for it: upstream's own figure, covering rootfs
    /// extraction plus runtime start-up.
    scratch_mb: usize,
}

fn runtime_image(runtime: HyperlightRuntime) -> RuntimeImage {
    // Upstream's own scratch figures per image: rootfs extraction plus
    // runtime start-up.
    let scratch_mb = match runtime {
        HyperlightRuntime::Agent => 1536,
        HyperlightRuntime::Python | HyperlightRuntime::PythonShell | HyperlightRuntime::Bash => 256,
        HyperlightRuntime::Node => 512,
        HyperlightRuntime::DotnetJit => 768,
    };
    RuntimeImage {
        image: format!(
            "ghcr.io/hyperlight-dev/hyperlight-unikraft/{}",
            runtime.name()
        ),
        scratch_mb,
    }
}

const ERR_PROXY_POLICY: &str = "network proxy is not supported by the hyperlight backend";
const ERR_WORKDIR: &str =
    "workingDirectory is not supported by the hyperlight backend -- guest has its own filesystem namespace";

fn no_install_source(runtime: HyperlightRuntime) -> String {
    let name = runtime.name();
    format!(
        "no warmed {name} snapshot and no rootfs to install from. drop `{INITRD_FILE}` into \
         the runtime's directory of the image home (or run `--setup-hyperlight={name}`)."
    )
}

// -- Runner ------------------------------------------------------------------

/// Script runner that executes Python code inside a Hyperlight+Unikraft
/// micro-VM.
///
/// Lazily brings up the guest on the first call (loading the persisted
/// snapshot, auto-installing it first if needed) and reuses it across
/// subsequent calls on the same runner instance. Every call rewinds the
/// guest to the post-warmup snapshot first, so consecutive calls are
/// hermetic.
pub struct HyperlightScriptRunner {
    guest: Option<Guest>,
    /// The persisted warm image, loaded once per home. Outlives `guest`:
    /// a call that fails or times out drops the guest, and the next call
    /// boots a fresh one from here instead of reloading it from disk.
    rewind: Option<Arc<Snapshot>>,
    active_home: Option<PathBuf>,
    active_mounts: Vec<Mount>,
}

/// A booted guest, parked at a boundary between calls.
struct Guest {
    sandbox: AppSandbox,
    /// True until the first call: the guest is already at the rewind point.
    fresh: bool,
}

/// Wall-clock split of one call.
#[derive(Debug, Default)]
struct RunTiming {
    restore_ms: f64,
    call_ms: f64,
    exit_code: i32,
}

/// Why a call produced no exit code.
enum RunError {
    TimedOut(Duration),
    Failed(String),
}

impl Default for HyperlightScriptRunner {
    fn default() -> Self {
        Self::new()
    }
}

/// The runtimes `--setup-hyperlight` was given: the default runtime for
/// no names, otherwise each name parsed, the first unknown one reported.
pub fn parse_runtimes(names: &[String]) -> Result<Vec<HyperlightRuntime>, String> {
    if names.is_empty() {
        return Ok(vec![HyperlightRuntime::default()]);
    }
    names.iter().map(|name| name.parse()).collect()
}

/// Eagerly install the warmed snapshot so the *first* run later
/// pays no warmup cost. Intended to be called from a tool install
/// step (npm postinstall, a `--setup-hyperlight` CLI flag, CI, etc.).
///
/// Pulls the published rootfs from GHCR over the registry API, boots it
/// once, and persists the warmed guest as a snapshot.
///
/// # Destination
///
/// `$MXC_HYPERLIGHT_HOME` if set, otherwise the OS-local default
/// (`~/.local/share/mxc-hyperlight` on Linux, `%LOCALAPPDATA%\mxc-hyperlight` on
/// Windows), with one directory per runtime under it. We intentionally do NOT walk the runtime search chain
/// here — that would let a stale `<cwd>/.mxc-hyperlight/` from an old dev
/// session short-circuit the install and leave the default home
/// empty, which would make later runs from a different cwd fail.
///
/// # Force
///
/// When `force` is false, an existing install for this release is a
/// no-op; one left by another release is rebuilt. When `force` is true,
/// the snapshot is rebuilt regardless.
pub fn setup(
    force: bool,
    runtimes: &[HyperlightRuntime],
    logger: &mut Logger,
) -> Result<PathBuf, String> {
    let root = match std::env::var_os(HOME_ENV) {
        Some(v) => PathBuf::from(v),
        None => HyperlightScriptRunner::default_home(),
    };

    for &runtime in runtimes {
        let home = root.join(runtime.name());
        if !force && is_installed(&home, runtime) {
            logger.log_line(&format!(
                "hyperlight: {} snapshot already present at {:?}; nothing to do \
                 (pass --force to rebuild)",
                runtime.name(),
                home.join(SNAPSHOT_DIR)
            ));
            continue;
        }

        std::fs::create_dir_all(&home).map_err(|e| format!("create image home {home:?}: {e}"))?;

        // A rootfs of this release already in the home is kept, so a rebuild
        // (a stale snapshot, or --force after replacing it) only warms.
        if has_install_source(&home, runtime) {
            logger.log_line(&format!(
                "hyperlight setup: rootfs present at {:?}",
                home.join(INITRD_FILE)
            ));
        } else {
            logger.log_line(&format!(
                "hyperlight setup: pulling {}:{ROOTFS_TAG}",
                runtime_image(runtime).image
            ));
            pull_rootfs(&home.join(INITRD_FILE), runtime, logger)?;
            std::fs::write(home.join(VERSION_FILE), version_stamp(runtime))
                .map_err(|e| format!("write {VERSION_FILE}: {e}"))?;
        }

        let (_, persisted) = warm_snapshot(&home, runtime, logger).map_err(|e| e.to_string())?;
        if !persisted {
            return Err(format!(
                "the snapshot could not be put in place at {:?}; the log above says why",
                home.join(SNAPSHOT_DIR)
            ));
        }
    }
    Ok(root)
}

impl HyperlightScriptRunner {
    pub fn new() -> Self {
        Self {
            guest: None,
            rewind: None,
            active_home: None,
            active_mounts: Vec::new(),
        }
    }

    /// Resolve the image home for a normal run. Walks the
    /// discovery chain (see module doc) and returns the first
    /// location that has at least the rootfs — snapshot may be
    /// missing, the runner will install it.
    fn resolve_home(runtime: HyperlightRuntime) -> Result<PathBuf, RunnerError> {
        let name = runtime.name();
        let mut stale = None;
        for root in Self::search_paths() {
            let cand = root.join(name);
            if is_installed(&cand, runtime) || has_install_source(&cand, runtime) {
                return Ok(cand);
            }
            if stale.is_none() && cand.join(INITRD_FILE).is_file() {
                stale = Some(cand);
            }
        }
        let default = Self::default_home();
        let hint = match stale {
            Some(home) => format!(
                "{home:?} holds a rootfs from another hyperlight-unikraft release; \
                 run `{SETUP_BIN} --setup-hyperlight={name}` to rebuild it."
            ),
            None => format!(
                "run `{SETUP_BIN} --setup-hyperlight={name}` \
                 (or drop `{INITRD_FILE}` into {:?}).",
                default.join(name)
            ),
        };
        Err(RunnerError::Preflight(format!(
            "no hyperlight image found for the {name} runtime. searched ${HOME_ENV}, \
             {default:?}, <exe>/{EXE_RELATIVE_HOME}/, <cwd>/{CWD_RELATIVE_HOME}/, each under \
             `{name}/`. {hint}"
        )))
    }

    /// Candidate locations, in priority order.
    fn search_paths() -> Vec<PathBuf> {
        let mut paths = Vec::with_capacity(4);
        if let Some(explicit) = std::env::var_os(HOME_ENV) {
            paths.push(PathBuf::from(explicit));
        }
        paths.push(Self::default_home());
        if let Ok(exe) = std::env::current_exe() {
            if let Some(dir) = exe.parent() {
                paths.push(dir.join(EXE_RELATIVE_HOME));
            }
        }
        if let Ok(cwd) = std::env::current_dir() {
            paths.push(cwd.join(CWD_RELATIVE_HOME));
        }
        paths
    }

    /// The OS-local default data directory. Setup writes here
    /// when nothing else is already populated, and it's always second
    /// in the resolution chain (after $MXC_HYPERLIGHT_HOME).
    ///
    /// - Linux: `$XDG_DATA_HOME/mxc-hyperlight` (or `~/.local/share/mxc-hyperlight`)
    /// - Windows: `%LOCALAPPDATA%\mxc-hyperlight` (or `~\AppData\Local\mxc-hyperlight`)
    fn default_home() -> PathBuf {
        os_data_home().join(DEFAULT_HOME_LEAF)
    }

    /// Reject policies the guest cannot enforce before any sandbox is booted.
    fn validate_policies(request: &ExecutionRequest) -> Result<(), RunnerError> {
        if request.policy.network_proxy.is_enabled() {
            return Err(RunnerError::Preflight(ERR_PROXY_POLICY.to_string()));
        }
        if !request.working_directory.is_empty() {
            return Err(RunnerError::Preflight(ERR_WORKDIR.to_string()));
        }
        // Denied paths: block early if any appears in the allow lists.
        for denied in &request.policy.denied_paths {
            for allowed in request
                .policy
                .readwrite_paths
                .iter()
                .chain(request.policy.readonly_paths.iter())
            {
                match path_relationship(allowed, denied) {
                    PathRelationship::Overlaps => {
                        return Err(RunnerError::Preflight(format!(
                            "deniedPaths entry {denied:?} overlaps allow list path {allowed:?}; \
                             Hyperlight cannot safely expose overlapping allowed and denied \
                             host paths"
                        )));
                    }
                    PathRelationship::Separate => {}
                    PathRelationship::Indeterminate => {
                        return Err(RunnerError::Preflight(format!(
                            "Hyperlight: cannot verify deniedPaths against allow lists because \
                             {allowed:?} or {denied:?} could not be resolved to a canonical \
                             location. With deniedPaths present, MXC fails closed rather than \
                             risk an unenforced deny. Ensure both paths are accessible, or remove \
                             the deniedPaths entry."
                        )));
                    }
                }
            }
        }

        Ok(())
    }

    /// Translate `ContainerPolicy.{readwrite,readonly}Paths` into
    /// [`Mount`] entries. Each host path is exposed inside the guest at
    /// `/host/<basename>` so scripts can find mounts predictably.
    fn mounts_from_policy(request: &ExecutionRequest) -> Result<Vec<Mount>, RunnerError> {
        let mut mounts = Vec::new();
        let mut seen_guest_paths = std::collections::HashSet::new();

        let rw_iter = request.policy.readwrite_paths.iter().map(|p| (p, false));
        let ro_iter = request.policy.readonly_paths.iter().map(|p| (p, true));

        for (host, read_only) in rw_iter.chain(ro_iter) {
            let host_path = PathBuf::from(host);

            // Auto-create the mount dir if it doesn't exist yet. The
            // host path is canonicalized below, which fails on ENOENT —
            // so without this, a relative path like "../tmp/foo" fails
            // silently just because the dir wasn't pre-created. The
            // guest still needs a real dir to read/write against;
            // mkdir-ing now matches the "config is declaratively
            // requesting this mount" semantics.
            //
            // We only create if the parent already exists — prevents
            // accidentally materializing arbitrary paths on a typo.
            if !host_path.exists() {
                let parent_ok = host_path
                    .parent()
                    .map(|p| p.as_os_str().is_empty() || p.exists())
                    .unwrap_or(false);
                if !parent_ok {
                    return Err(RunnerError::Preflight(format!(
                        "mount path {host:?} does not exist and its parent doesn't either; \
                         refusing to auto-create (fix the path or `mkdir -p` manually)"
                    )));
                }
                std::fs::create_dir_all(&host_path).map_err(|e| {
                    RunnerError::Preflight(format!("auto-create mount dir {host:?}: {e}"))
                })?;
            }

            // Canonical so the mount set compares stably across calls and
            // so a relative path keeps meaning the same directory after a
            // cwd change.
            let host_path = std::fs::canonicalize(&host_path)
                .map_err(|e| RunnerError::Preflight(format!("resolve mount path {host:?}: {e}")))?;
            let basename = host_path
                .file_name()
                .and_then(|n| n.to_str())
                .ok_or_else(|| {
                    RunnerError::Preflight(format!("mount path {host:?} has no filename component"))
                })?;
            // The guest path travels to the kernel in its `vfs.fstab`
            // list, which these characters would break; the library
            // refuses them at boot, we refuse them before booting.
            if basename
                .chars()
                .any(|c| c.is_whitespace() || matches!(c, ':' | '[' | ']'))
            {
                return Err(RunnerError::Preflight(format!(
                    "mount path {host:?}: the directory name may not contain whitespace, \
                     ':' or brackets (it names the guest mount point)"
                )));
            }
            let guest_path = format!("{GUEST_MOUNT_ROOT}/{basename}");
            if !seen_guest_paths.insert(guest_path.clone()) {
                return Err(RunnerError::Preflight(format!(
                    "two mount paths collide on guest path {guest_path:?}; \
                     rename one of the host directories"
                )));
            }
            mounts.push(if read_only {
                Mount::ro(host_path, guest_path)
            } else {
                Mount::rw(host_path, guest_path)
            });
        }

        Ok(mounts)
    }

    /// Lazily bring up the guest for this configuration.
    ///
    /// The guest restores the persisted snapshot (warming and persisting
    /// one first if only the rootfs is present, a cold boot once per
    /// image) with the request's mounts; the kernel builds its mount table
    /// from them on resume. Later calls on the
    /// same runner rewind rather than boot.
    ///
    /// The mount set is fixed at boot; changing it boots another guest from
    /// the same image.
    fn ensure_runtime(
        &mut self,
        home: &Path,
        runtime: HyperlightRuntime,
        mounts: Vec<Mount>,
        logger: &mut Logger,
    ) -> Result<(&mut Guest, Arc<Snapshot>), RunnerError> {
        let same_config =
            self.active_home.as_deref() == Some(home) && mounts_equal(&self.active_mounts, &mounts);
        if !same_config {
            // Nothing booted so far applies to the new configuration; the
            // image still does, unless the home changed.
            self.guest = None;
            if self.active_home.as_deref() != Some(home) {
                self.rewind = None;
            }
            self.active_home = Some(home.to_path_buf());
            self.active_mounts = mounts;
        }
        let rewind = match self.rewind.clone() {
            Some(rewind) => rewind,
            None => {
                configure_surrogates();
                let rewind = load_persisted_snapshot(home, runtime, logger)?;
                self.rewind = Some(rewind.clone());
                rewind
            }
        };
        let guest = match self.guest.take() {
            Some(guest) => guest,
            None => {
                configure_surrogates();
                Self::boot_from_snapshot(rewind.clone(), &self.active_mounts)?
            }
        };
        Ok((self.guest.insert(guest), rewind))
    }

    /// Restore the warm image into a new sandbox with `mounts` and
    /// `policy`: the kernel builds its mount table from them on resume,
    /// and the host serves them.
    fn boot_from_snapshot(rewind: Arc<Snapshot>, mounts: &[Mount]) -> Result<Guest, RunnerError> {
        let builder = SandboxBuilder::from_snapshot(rewind).mounts(mounts.iter().cloned());
        let sandbox = builder
            .boot()
            .map_err(|e| RunnerError::Runtime(format!("restore hyperlight snapshot: {e}")))?;
        Ok(Guest {
            sandbox,
            fresh: true,
        })
    }

    /// One hermetic call: rewind to the warmed state (unless the guest is
    /// fresh from boot), run `code`, and report the guest's exit status.
    fn run_once(
        guest: &mut Guest,
        rewind: &Arc<Snapshot>,
        code: &str,
        timeout: Option<Duration>,
    ) -> Result<RunTiming, RunError> {
        let mut timing = RunTiming::default();
        if !guest.fresh {
            let t = Instant::now();
            guest
                .sandbox
                .restore(rewind.clone())
                .map_err(|e| RunError::Failed(format!("rewind guest: {e}")))?;
            timing.restore_ms = t.elapsed().as_secs_f64() * 1000.0;
        }
        guest.fresh = false;

        let t = Instant::now();
        let result = match timeout {
            Some(timeout) => run_with_deadline(&mut guest.sandbox, code, timeout),
            None => match guest.sandbox.run(code) {
                Ok(()) => Ok(0),
                Err(hyperlight_unikraft::Error::CallFailed { status }) => Ok(status),
                Err(e) => Err(RunError::Failed(e.to_string())),
            },
        };
        timing.call_ms = t.elapsed().as_secs_f64() * 1000.0;
        // HostPrint already wrote the guest's output to our stdout; drop
        // the copy the library keeps so it never grows across calls.
        let _ = guest.sandbox.drain_output();

        timing.exit_code = result?;
        if timing.exit_code < 0 {
            // The driver's own signal that it could not run the call; the
            // guest's output has the details.
            return Err(RunError::Failed(format!(
                "the guest driver could not run the call (status {})",
                timing.exit_code
            )));
        }
        Ok(timing)
    }

    fn execute_validated(
        &mut self,
        request: &ExecutionRequest,
        logger: &mut Logger,
    ) -> ScriptResponse {
        let runtime = request
            .hyperlight
            .as_ref()
            .map(|h| h.runtime)
            .unwrap_or_default();
        let home = match Self::resolve_home(runtime) {
            Ok(h) => h,
            Err(e) => {
                logger.log_line(&e.to_string());
                return e.to_response();
            }
        };
        let mounts = match Self::mounts_from_policy(request) {
            Ok(m) => m,
            Err(e) => {
                logger.log_line(&e.to_string());
                return e.to_response();
            }
        };
        let (guest, rewind) = match self.ensure_runtime(&home, runtime, mounts, logger) {
            Ok(pair) => pair,
            Err(e) => {
                logger.log_line(&e.to_string());
                return e.to_response();
            }
        };

        let timeout = (request.script_timeout > 0).then(|| {
            logger.log_line(&format!(
                "hyperlight: timeout set to {}ms",
                request.script_timeout
            ));
            Duration::from_millis(u64::from(request.script_timeout))
        });
        match Self::run_once(guest, &rewind, &request.script_code, timeout) {
            Ok(timing) => {
                logger.log_line(&format!(
                    "hyperlight: run ok (restore={:.1}ms call={:.1}ms exit={})",
                    timing.restore_ms, timing.call_ms, timing.exit_code
                ));
                ScriptResponse {
                    exit_code: timing.exit_code,
                    ..Default::default()
                }
            }
            Err(failure) => {
                // The guest is mid-call (blocked, killed, exited or
                // deadlocked): nothing more will run in it. Drop it; the
                // next call boots another from the rewind point.
                self.guest = None;
                let err = match failure {
                    RunError::TimedOut(timeout) => RunnerError::Runtime(format!(
                        "execution timed out after {:.1}s",
                        timeout.as_secs_f64()
                    )),
                    RunError::Failed(msg) => RunnerError::Runtime(format!("run: {msg}")),
                };
                logger.log_line(&err.to_string());
                err.to_response()
            }
        }
    }
}

impl ScriptRunner for HyperlightScriptRunner {
    fn validate_runner(&self, request: &ExecutionRequest) -> Result<(), ScriptResponse> {
        Self::validate_policies(request).map_err(|e| e.to_response())?;
        validate_network_policy_support(request, NetworkPolicySupport::default())?;
        Ok(())
    }

    fn run(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        if let Err(response) = validate_common(request) {
            return response;
        }
        if let Err(response) = self.validate_runner(request) {
            return response;
        }
        if request.dry_run {
            return ScriptResponse {
                exit_code: 0,
                ..Default::default()
            };
        }
        self.execute_validated(request, logger)
    }

    fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        if let Err(response) = self.validate_runner(request) {
            return response;
        }
        self.execute_validated(request, logger)
    }
}

// -- Guest driving -----------------------------------------------------------

/// Run `code` and wait for it, giving up at `timeout`.
///
/// The guest hands the vCPU back whenever every thread is blocked, so a
/// sleeping script is caught by bounding each `step`. A script that never
/// blocks (a busy loop) holds the vCPU inside one entry, which only an
/// interrupt from another thread can end; the watchdog fires it at the
/// deadline, and keeps firing until this thread confirms it is out, in
/// case the guest was between entries the first time. An interrupted
/// sandbox is poisoned, a merely blocked one still has the call in
/// flight: the caller discards the guest either way.
fn run_with_deadline(
    sandbox: &mut AppSandbox,
    code: &str,
    timeout: Duration,
) -> Result<i32, RunError> {
    let deadline = Instant::now() + timeout;
    // Dropped by this thread once the call is over, however it ended,
    // which wakes the watchdog at once instead of on its next tick.
    let (finished_tx, finished_rx) = mpsc::channel::<()>();
    let watchdog = {
        let handle = sandbox.interrupt_handle();
        std::thread::spawn(move || {
            let mut wait = deadline.saturating_duration_since(Instant::now());
            loop {
                match finished_rx.recv_timeout(wait) {
                    Err(RecvTimeoutError::Timeout) => {}
                    // The call is over: finished before the deadline, or
                    // the caller is gone.
                    _ => return,
                }
                // Past the deadline. `kill` breaks an entry in progress;
                // between entries (in a host call, say) it only marks the
                // next one cancelled and reports nothing, so retry until
                // the call is over either way.
                if handle.kill() {
                    return;
                }
                wait = Duration::from_millis(10);
            }
        })
    };

    let outcome = drive_until(sandbox, code, deadline);
    drop(finished_tx);
    let _ = watchdog.join();

    match outcome {
        Ok(Some(status)) => Ok(status),
        Ok(None) => Err(RunError::TimedOut(timeout)),
        // Only the watchdog kills this sandbox, and Hyperlight clears a
        // kill at the start of every entry, so a cancelled entry is this
        // call's timeout however the kill landed.
        Err(hyperlight_unikraft::Error::Hyperlight(HyperlightError::ExecutionCanceledByHost())) => {
            Err(RunError::TimedOut(timeout))
        }
        Err(e) => Err(RunError::Failed(e.to_string())),
    }
}

/// Submit `code` and step the guest until the call returns (`Some(status)`)
/// or `deadline` passes (`None`).
fn drive_until(
    sandbox: &mut AppSandbox,
    code: &str,
    deadline: Instant,
) -> Result<Option<i32>, hyperlight_unikraft::Error> {
    sandbox.submit(code)?;
    loop {
        let remaining = deadline.saturating_duration_since(Instant::now());
        if remaining.is_zero() {
            return Ok(None);
        }
        match sandbox.step(remaining)? {
            Yield::CallDone => return Ok(Some(0)),
            Yield::CallFailed { status } => return Ok(Some(status)),
            Yield::Exited { status } => {
                return Err(hyperlight_unikraft::Error::GuestExited { status })
            }
            Yield::Blocked { .. } => {}
        }
    }
}

// -- Install -----------------------------------------------------------------

/// Boot the rootfs in `home`, save the warm image beside its snapshot
/// directory and publish it there. The flag says whether the new layout
/// is what now sits in the snapshot directory; when it is not, the image
/// in memory is still this warm's and the log says what happened on disk.
fn warm_snapshot(
    home: &Path,
    runtime: HyperlightRuntime,
    logger: &mut Logger,
) -> Result<(Arc<Snapshot>, bool), RunnerError> {
    let snapshot_dir = home.join(SNAPSHOT_DIR);
    logger.log_line(&format!(
        "hyperlight: booting {:?} to warm a snapshot",
        home.join(INITRD_FILE)
    ));
    let t = Instant::now();
    configure_surrogates();
    let mut sandbox = rootfs_builder(home, runtime)
        .boot()
        .map_err(|e| RunnerError::Runtime(format!("boot hyperlight rootfs: {e}")))?;
    // Saved beside the snapshot directory, so a failed save leaves whatever
    // is there standing, then published by rename.
    let staged = home.join(format!(".{SNAPSHOT_DIR}.{}.part", std::process::id()));
    let _ = std::fs::remove_dir_all(&staged);
    let snapshot = match sandbox.snapshot_to(&staged) {
        Ok(snapshot) => snapshot,
        Err(e) => {
            let _ = std::fs::remove_dir_all(&staged);
            return Err(RunnerError::Runtime(format!(
                "save snapshot to {staged:?}: {e}"
            )));
        }
    };
    let persisted = publish_snapshot(home, &staged, &snapshot_dir, logger);
    logger.log_line(&format!(
        "hyperlight: warm-up took {:.1}ms; snapshot at {snapshot_dir:?}",
        t.elapsed().as_secs_f64() * 1000.0
    ));
    Ok((snapshot, persisted))
}

/// Move the layout saved at `staged` into `snapshot_dir`: the old layout is
/// set aside by rename first and dropped only once the new one is in place,
/// so the directory is absent only between two renames. Two warms at once
/// each save a whole layout, and the one whose move lands is the one that
/// stays. Returns whether a fresh layout is now in place: this warm's, or
/// another warm's that landed first. Otherwise the old layout is back, or,
/// if it could not be put back either, left at its `.old` path, which the
/// log names.
fn publish_snapshot(home: &Path, staged: &Path, snapshot_dir: &Path, logger: &mut Logger) -> bool {
    let old = home.join(format!(".{SNAPSHOT_DIR}.{}.old", std::process::id()));
    let had_old = match std::fs::rename(snapshot_dir, &old) {
        Ok(()) => true,
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
        Err(e) => {
            logger.log_line(&format!(
                "hyperlight: set aside old snapshot {snapshot_dir:?}: {e}"
            ));
            let _ = std::fs::remove_dir_all(staged);
            return false;
        }
    };
    let moved = std::fs::rename(staged, snapshot_dir);
    if let Err(e) = &moved {
        logger.log_line(&format!(
            "hyperlight: move snapshot into place at {snapshot_dir:?}: {e}"
        ));
        let _ = std::fs::remove_dir_all(staged);
    }
    match (moved, had_old) {
        (Ok(()), true) => {
            let _ = std::fs::remove_dir_all(&old);
            true
        }
        (Ok(()), false) => true,
        (Err(_), true) => {
            if std::fs::rename(&old, snapshot_dir).is_ok() {
                logger.log_line(&format!(
                    "hyperlight: old snapshot put back at {snapshot_dir:?}"
                ));
                return false;
            }
            if hyperlight_unikraft::load_snapshot(snapshot_dir).is_ok() {
                // Another warm landed in the meantime; its layout stays.
                logger.log_line(&format!(
                    "hyperlight: another warm published {snapshot_dir:?} first"
                ));
                let _ = std::fs::remove_dir_all(&old);
                return true;
            }
            logger.log_line(&format!("hyperlight: old snapshot left at {old:?}"));
            false
        }
        (Err(_), false) => {
            let landed = hyperlight_unikraft::load_snapshot(snapshot_dir).is_ok();
            if landed {
                logger.log_line(&format!(
                    "hyperlight: another warm published {snapshot_dir:?} first"
                ));
            }
            landed
        }
    }
}

/// The persisted snapshot in `home`, warming and persisting one first
/// when there is none this build loads.
fn load_persisted_snapshot(
    home: &Path,
    runtime: HyperlightRuntime,
    logger: &mut Logger,
) -> Result<Arc<Snapshot>, RunnerError> {
    let snapshot_dir = home.join(SNAPSHOT_DIR);
    let unloadable = match hyperlight_unikraft::load_snapshot(&snapshot_dir) {
        Ok(snapshot) => {
            logger.log_line(&format!("hyperlight: using image home {home:?}"));
            return Ok(snapshot);
        }
        Err(e) => e,
    };
    if !has_install_source(home, runtime) {
        return Err(RunnerError::Preflight(no_install_source(runtime)));
    }
    logger.log_line(&match unloadable {
        hyperlight_unikraft::Error::SnapshotRelease { saved_by, .. } => format!(
            "hyperlight: the snapshot at {snapshot_dir:?} was saved by hyperlight-unikraft \
             {saved_by}; warming one for this build from the rootfs"
        ),
        e => format!(
            "hyperlight: no snapshot to load at {snapshot_dir:?} ({e}); warming one from the \
             rootfs"
        ),
    });
    let (snapshot, persisted) = warm_snapshot(home, runtime, logger)?;
    if !persisted {
        logger.log_line(
            "hyperlight: running from the warm image in memory; the next run warms again",
        );
    }
    Ok(snapshot)
}

/// A builder for a fresh boot of the rootfs in `home`.
fn rootfs_builder(home: &Path, runtime: HyperlightRuntime) -> SandboxBuilder {
    SandboxBuilder::from_initrd(home.join(INITRD_FILE))
        .scratch_mb(runtime_image(runtime).scratch_mb)
}

/// Pull the rootfs CPIO out of the published image into `dst`, straight
/// from the registry's distribution API: no container runtime needed.
/// Staged beside `dst` and renamed into place so a failed pull leaves no
/// half-written rootfs.
fn pull_rootfs(dst: &Path, runtime: HyperlightRuntime, logger: &mut Logger) -> Result<(), String> {
    // Staged per process, so two setups at once each pull their own copy.
    let staged = dst.with_file_name(format!(".{INITRD_FILE}.{}.part", std::process::id()));
    let pulled = oci::fetch_file(
        &runtime_image(runtime).image,
        ROOTFS_TAG,
        ROOTFS_PATH_IN_IMAGE,
        &staged,
        logger,
    );
    if pulled.is_err() {
        let _ = std::fs::remove_file(&staged);
    }
    pulled?;
    // Remove the old rootfs first: on Windows, rename cannot replace an
    // existing destination.
    let _ = std::fs::remove_file(dst);
    if let Err(e) = std::fs::rename(&staged, dst) {
        let _ = std::fs::remove_file(&staged);
        return Err(format!("move rootfs into place at {dst:?}: {e}"));
    }
    Ok(())
}

/// Just enough of the OCI distribution API to take one file out of a
/// public image: an anonymous pull token, the manifest (through an index
/// if the tag names one), and the layer tarballs, extracted as they
/// stream in and checked against their digests.
mod oci {
    use std::io::Read;
    use std::path::Path;
    use std::time::Duration;

    use crate::mxc_common::encoding::lowercase_hex;
    use crate::mxc_common::logger::Logger;
    use sha2::{Digest, Sha256};

    const MANIFEST_TYPES: &str = "application/vnd.oci.image.manifest.v1+json, \
         application/vnd.oci.image.index.v1+json, \
         application/vnd.docker.distribution.manifest.v2+json, \
         application/vnd.docker.distribution.manifest.list.v2+json";

    /// Write the file at `path_in_image` inside `image:tag` to `dst`.
    /// `image` is `<registry host>/<repository>`.
    pub(super) fn fetch_file(
        image: &str,
        tag: &str,
        path_in_image: &str,
        dst: &Path,
        logger: &mut Logger,
    ) -> Result<(), String> {
        let (registry, repo) = image
            .split_once('/')
            .ok_or_else(|| format!("image {image:?} names no registry host"))?;
        // Bounded so a dead link fails instead of hanging setup; the body
        // bound covers the largest layer on a slow link.
        let agent = ureq::Agent::config_builder()
            .timeout_resolve(Some(Duration::from_secs(30)))
            .timeout_connect(Some(Duration::from_secs(30)))
            .timeout_recv_response(Some(Duration::from_secs(60)))
            .timeout_recv_body(Some(Duration::from_secs(30 * 60)))
            .build()
            .new_agent();
        let token = pull_token(&agent, registry, repo)?;
        let get = |url: String, accept: &str| -> Result<ureq::Body, String> {
            agent
                .get(&url)
                .header("Authorization", &format!("Bearer {token}"))
                .header("Accept", accept)
                .call()
                .map(|response| response.into_body())
                .map_err(|e| format!("GET {url}: {e}"))
        };

        // A tag may name an index of per-platform manifests (a buildx push
        // adds attestation manifests under an "unknown" platform too)
        // rather than the manifest itself; take the linux/amd64 one.
        let manifests_url = format!("https://{registry}/v2/{repo}/manifests");
        let mut manifest = read_json(get(format!("{manifests_url}/{tag}"), MANIFEST_TYPES)?)?;
        if let Some(entries) = manifest.get("manifests").and_then(|m| m.as_array()) {
            let digest = entries
                .iter()
                .find(|m| {
                    m["platform"]["os"] == "linux" && m["platform"]["architecture"] == "amd64"
                })
                .and_then(|m| m["digest"].as_str())
                .ok_or_else(|| format!("{image}:{tag} has no linux/amd64 manifest"))?
                .to_string();
            manifest = read_json(get(format!("{manifests_url}/{digest}"), MANIFEST_TYPES)?)?;
        }
        let layers = manifest["layers"]
            .as_array()
            .ok_or_else(|| format!("{image}:{tag}: manifest lists no layers"))?;

        let wanted = path_in_image.trim_start_matches('/');
        let mut found = false;
        for layer in layers {
            let digest = layer["digest"]
                .as_str()
                .ok_or_else(|| format!("{image}:{tag}: a layer has no digest"))?;
            let media_type = layer["mediaType"].as_str().unwrap_or_default();
            if media_type.ends_with("zstd") {
                return Err(format!(
                    "{image}:{tag}: zstd-compressed layers are not supported"
                ));
            }
            let size_mib = layer["size"].as_u64().unwrap_or(0) / (1024 * 1024);
            logger.log_line(&format!(
                "hyperlight setup: downloading {image}:{tag} layer {digest} ({size_mib} MiB)"
            ));
            let body = get(
                format!("https://{registry}/v2/{repo}/blobs/{digest}"),
                "application/octet-stream",
            )?;
            let mut blob = Digested::new(body.into_reader());
            // A later layer's copy of the file replaces an earlier one's,
            // as it does in the image.
            found |= extract(&mut blob, media_type.ends_with("gzip"), wanted, dst)?;
            // Read to the end so the digest covers the whole blob.
            std::io::copy(&mut blob, &mut std::io::sink())
                .map_err(|e| format!("read layer {digest}: {e}"))?;
            let actual = blob.digest();
            if actual != digest {
                return Err(format!("layer {digest} arrived with digest {actual}"));
            }
        }
        if found {
            Ok(())
        } else {
            Err(format!("{image}:{tag} has no {path_in_image}"))
        }
    }

    /// An anonymous pull token for `repo` from the registry's token
    /// endpoint, in the layout GHCR uses.
    fn pull_token(agent: &ureq::Agent, registry: &str, repo: &str) -> Result<String, String> {
        let url = format!("https://{registry}/token?scope=repository:{repo}:pull");
        let body = agent
            .get(&url)
            .call()
            .map(|response| response.into_body())
            .map_err(|e| format!("GET {url}: {e}"))?;
        read_json(body)?["token"]
            .as_str()
            .map(str::to_string)
            .ok_or_else(|| format!("{registry} token response carries no token"))
    }

    fn read_json(mut body: ureq::Body) -> Result<serde_json::Value, String> {
        let bytes = body
            .read_to_vec()
            .map_err(|e| format!("read response: {e}"))?;
        serde_json::from_slice(&bytes).map_err(|e| format!("parse response: {e}"))
    }

    /// Walk one layer tarball, writing the `wanted` entry to `dst` if it
    /// is there.
    fn extract(
        blob: &mut impl Read,
        gzipped: bool,
        wanted: &str,
        dst: &Path,
    ) -> Result<bool, String> {
        let reader: Box<dyn Read + '_> = if gzipped {
            Box::new(flate2::read::GzDecoder::new(blob))
        } else {
            Box::new(blob)
        };
        let mut archive = tar::Archive::new(reader);
        let mut found = false;
        for entry in archive.entries().map_err(|e| format!("read layer: {e}"))? {
            let mut entry = entry.map_err(|e| format!("read layer entry: {e}"))?;
            let is_wanted = {
                let path = entry.path().map_err(|e| format!("read layer entry: {e}"))?;
                let name = path.to_string_lossy();
                name.trim_start_matches("./").trim_start_matches('/') == wanted
            };
            if !is_wanted {
                continue;
            }
            if !entry.header().entry_type().is_file() {
                return Err(format!("{wanted} in the layer is not a regular file"));
            }
            let mut file =
                std::fs::File::create(dst).map_err(|e| format!("create {dst:?}: {e}"))?;
            let written =
                std::io::copy(&mut entry, &mut file).map_err(|e| format!("write {dst:?}: {e}"))?;
            if written == 0 {
                return Err(format!("{wanted} in the layer is empty"));
            }
            found = true;
            break;
        }
        Ok(found)
    }

    /// A reader that keeps the SHA-256 of everything read through it.
    struct Digested<R> {
        inner: R,
        hasher: Sha256,
    }

    impl<R: Read> Digested<R> {
        fn new(inner: R) -> Self {
            Self {
                inner,
                hasher: Sha256::new(),
            }
        }

        /// The digest of everything read so far, in the registry's
        /// `sha256:<hex>` form.
        fn digest(&self) -> String {
            let digest = lowercase_hex(&self.hasher.clone().finalize());
            format!("sha256:{digest}")
        }
    }

    impl<R: Read> Read for Digested<R> {
        fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
            let n = self.inner.read(buf)?;
            self.hasher.update(&buf[..n]);
            Ok(n)
        }
    }
}

/// One guest per process: the runner holds at most one sandbox, and the
/// warm boot is dropped before the restore boots, so Hyperlight's
/// single-VM mode fits and skips its 512 pre-spawned helper processes on
/// Windows (about 3.5 s on first boot). Must run before any sandbox
/// exists; later calls are no-ops.
fn configure_surrogates() {
    #[cfg(windows)]
    hyperlight_unikraft::configure_surrogates(0);
}

// -- Helpers -----------------------------------------------------------------

/// A home has a snapshot this build loads, beside no rootfs of another
/// release. The rootfs is only needed to warm, not to run.
fn is_installed(home: &Path, runtime: HyperlightRuntime) -> bool {
    stamp_matches(home, runtime)
        && hyperlight_unikraft::load_snapshot(home.join(SNAPSHOT_DIR)).is_ok()
}

/// A home has a rootfs of this release — enough to warm a snapshot from.
/// A rootfs with no stamp (dropped in by hand) is taken on trust; one
/// stamped for another release is not, since it will not boot on this
/// release's kernel.
fn has_install_source(home: &Path, runtime: HyperlightRuntime) -> bool {
    home.join(INITRD_FILE).is_file() && stamp_matches(home, runtime)
}

fn version_stamp(runtime: HyperlightRuntime) -> String {
    format!("rootfs: {}:{ROOTFS_TAG}\n", runtime_image(runtime).image)
}

fn stamp_matches(home: &Path, runtime: HyperlightRuntime) -> bool {
    match std::fs::read_to_string(home.join(VERSION_FILE)) {
        Ok(stamp) => stamp.trim() == version_stamp(runtime).trim(),
        Err(e) => e.kind() == std::io::ErrorKind::NotFound,
    }
}

/// Whether an allowed host path overlaps a denied path after canonicalization,
/// with a platform-aware lexical fallback for paths that do not exist yet.
fn path_relationship(allowed: &str, denied: &str) -> PathRelationship {
    let Ok(allowed) = anchor_policy_path(allowed) else {
        return PathRelationship::Indeterminate;
    };
    let Ok(denied) = anchor_policy_path(denied) else {
        return PathRelationship::Indeterminate;
    };
    match (
        std::fs::canonicalize(&allowed),
        std::fs::canonicalize(&denied),
    ) {
        (Ok(allowed), Ok(denied)) => PathRelationship::from_overlaps(
            denied.starts_with(&allowed) || allowed.starts_with(&denied),
        ),
        _ => path_relationship_fallback(&allowed.to_string_lossy(), &denied.to_string_lossy()),
    }
}

fn anchor_policy_path(path: &str) -> Result<PathBuf, std::io::Error> {
    let path = Path::new(path);
    if path.is_absolute() {
        Ok(path.to_path_buf())
    } else {
        Ok(std::env::current_dir()?.join(path))
    }
}

#[derive(Debug, PartialEq, Eq)]
enum PathRelationship {
    Overlaps,
    Separate,
    Indeterminate,
}

impl PathRelationship {
    fn from_overlaps(overlaps: bool) -> Self {
        if overlaps {
            Self::Overlaps
        } else {
            Self::Separate
        }
    }
}

#[cfg(target_os = "windows")]
fn path_relationship_fallback(allowed: &str, denied: &str) -> PathRelationship {
    use crate::mxc_common::filesystem_canonical::canonicalize_allowing_absent_tail;

    path_relationship_fallback_with(allowed, denied, canonicalize_allowing_absent_tail)
}

#[cfg(target_os = "windows")]
fn path_relationship_fallback_with(
    allowed: &str,
    denied: &str,
    resolve: impl Fn(&str) -> crate::mxc_common::filesystem_canonical::PathCanonical,
) -> PathRelationship {
    use crate::mxc_common::filesystem_canonical::PathCanonical;

    match (resolve(allowed), resolve(denied)) {
        (PathCanonical::Canonical(allowed_resolved), PathCanonical::Canonical(denied_resolved)) => {
            let Some(allowed_norm) =
                WindowsFallbackPath::parse_canonical(allowed, &allowed_resolved)
            else {
                return PathRelationship::Indeterminate;
            };
            let Some(denied_norm) = WindowsFallbackPath::parse_canonical(denied, &denied_resolved)
            else {
                return PathRelationship::Indeterminate;
            };
            return PathRelationship::from_overlaps(allowed_norm.overlaps(&denied_norm));
        }
        (PathCanonical::Unknown, _) | (_, PathCanonical::Unknown) => {
            return PathRelationship::Indeterminate;
        }
        _ => {}
    }

    PathRelationship::from_overlaps(
        WindowsFallbackPath::parse(allowed).overlaps(&WindowsFallbackPath::parse(denied)),
    )
}

#[cfg(target_os = "windows")]
#[derive(Debug, PartialEq, Eq)]
struct WindowsFallbackPath {
    drive: Option<String>,
    rooted: bool,
    components: Vec<String>,
}

#[cfg(target_os = "windows")]
impl WindowsFallbackPath {
    fn parse(path: &str) -> Self {
        Self::parse_with_trailing_policy(path, has_verbatim_trim_sensitive_component(path))
    }

    fn parse_canonical(source: &str, resolved: &str) -> Option<Self> {
        // Canonical components name actual objects and must retain the spelling
        // returned by the OS. The shared resolver can also append an absent
        // tail, but does not expose where that tail starts. An ordinary source
        // containing a trim-sensitive name is therefore ambiguous when that
        // name survives in the result: trimming it could corrupt the resolved
        // prefix, while preserving it could corrupt the replayed tail.
        if has_trim_sensitive_component(source)
            && !has_verbatim_trim_sensitive_component(source)
            && has_trim_sensitive_component(resolved)
        {
            return None;
        }

        Some(Self::parse_with_trailing_policy(resolved, true))
    }

    fn parse_with_trailing_policy(path: &str, preserve_trailing_dots_and_spaces: bool) -> Self {
        let (folded, verbatim) = normalize_windows_verbatim_prefix(&path.to_lowercase());
        let bytes = folded.as_bytes();
        let (drive, rest) =
            if bytes.len() >= 2 && bytes[0].is_ascii_alphabetic() && bytes[1] == b':' {
                (Some(folded[..2].to_string()), &folded[2..])
            } else {
                (None, folded.as_str())
            };

        let rooted = rest.starts_with(['\\', '/']);
        let mut components = Vec::new();
        for segment in rest.split(['\\', '/']).filter(|s| !s.is_empty()) {
            match segment {
                "." => {}
                ".." => {
                    if components.last().is_some_and(|last| last != "..") {
                        components.pop();
                    } else if !rooted {
                        components.push("..".to_string());
                    }
                }
                _ => {
                    let component = if verbatim || preserve_trailing_dots_and_spaces {
                        segment
                    } else {
                        segment.trim_end_matches(['.', ' '])
                    };
                    if !component.is_empty() {
                        components.push(component.to_string());
                    }
                }
            }
        }

        Self {
            drive,
            rooted,
            components,
        }
    }

    fn overlaps(&self, denied: &Self) -> bool {
        self.drive == denied.drive
            && self.rooted == denied.rooted
            && (denied.components.starts_with(&self.components)
                || self.components.starts_with(&denied.components))
    }
}

#[cfg(target_os = "windows")]
fn normalize_windows_verbatim_prefix(path: &str) -> (String, bool) {
    if let Some(rest) = path.strip_prefix(r"\\?\unc\") {
        (format!(r"\\{rest}"), true)
    } else if let Some(rest) = path.strip_prefix(r"\\?\") {
        (rest.to_string(), true)
    } else {
        (path.to_string(), false)
    }
}

#[cfg(target_os = "windows")]
fn has_verbatim_trim_sensitive_component(path: &str) -> bool {
    normalize_windows_verbatim_prefix(&path.to_lowercase()).1 && has_trim_sensitive_component(path)
}

#[cfg(target_os = "windows")]
fn has_trim_sensitive_component(path: &str) -> bool {
    let folded = path.to_lowercase();
    let (normalized, _) = normalize_windows_verbatim_prefix(&folded);
    normalized
        .split(['\\', '/'])
        .any(|segment| segment.ends_with(['.', ' ']))
}

#[cfg(not(target_os = "windows"))]
fn path_relationship_fallback(allowed: &str, denied: &str) -> PathRelationship {
    let Ok(allowed) = resolve_non_windows_fallback_path(Path::new(allowed)) else {
        return PathRelationship::Indeterminate;
    };
    let Ok(denied) = resolve_non_windows_fallback_path(Path::new(denied)) else {
        return PathRelationship::Indeterminate;
    };
    PathRelationship::from_overlaps(denied.starts_with(&allowed) || allowed.starts_with(&denied))
}

#[cfg(not(target_os = "windows"))]
fn resolve_non_windows_fallback_path(path: &Path) -> Result<PathBuf, std::io::Error> {
    use std::io::ErrorKind;
    use std::path::Component;

    let mut tail: Vec<Component<'_>> = Vec::new();
    let mut current = path;

    loop {
        match std::fs::canonicalize(current) {
            Ok(resolved) => return Ok(append_non_windows_tail(resolved, &tail)),
            Err(e) if e.kind() == ErrorKind::NotFound => {
                let Some(parent) = current.parent() else {
                    return Ok(normalize_non_windows_fallback_path(path));
                };
                if let Some(component) = current.components().next_back() {
                    tail.push(component);
                }
                current = parent;
            }
            Err(e) => return Err(e),
        }
    }
}

#[cfg(not(target_os = "windows"))]
fn append_non_windows_tail(base: PathBuf, tail: &[std::path::Component<'_>]) -> PathBuf {
    use std::path::Component;

    let mut path = base;
    for component in tail.iter().rev() {
        match component {
            Component::Normal(name) => path.push(name),
            Component::ParentDir => {
                path.pop();
            }
            Component::CurDir => {}
            Component::RootDir => {}
            Component::Prefix(_) => {
                unreachable!("non-Windows paths cannot contain a Windows prefix")
            }
        }
    }
    path
}

#[cfg(not(target_os = "windows"))]
fn normalize_non_windows_fallback_path(path: &Path) -> PathBuf {
    use std::path::Component;

    let mut normalized = PathBuf::new();
    let is_absolute = path.is_absolute();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                if !normalized.pop() && !is_absolute {
                    normalized.push(component.as_os_str());
                }
            }
            _ => normalized.push(component.as_os_str()),
        }
    }
    normalized
}

fn mounts_equal(a: &[Mount], b: &[Mount]) -> bool {
    a.len() == b.len()
        && a.iter().zip(b.iter()).all(|(x, y)| {
            x.host_path == y.host_path && x.guest_path == y.guest_path && x.readonly == y.readonly
        })
}

/// OS-local data directory (the "user Application Data" root).
///
/// - Linux: `$XDG_DATA_HOME` if set and absolute, else `$HOME/.local/share`.
/// - Windows: `%LOCALAPPDATA%` if set, else `$USERPROFILE\AppData\Local`.
///
/// Returns `PathBuf::from(".")` if no candidate env vars are set (degrades
/// gracefully rather than panicking; caller can still override via
/// `$MXC_HYPERLIGHT_HOME`).
fn os_data_home() -> PathBuf {
    #[cfg(windows)]
    {
        if let Some(v) = std::env::var_os("LOCALAPPDATA") {
            return PathBuf::from(v);
        }
        if let Some(v) = std::env::var_os("USERPROFILE") {
            return PathBuf::from(v).join("AppData").join("Local");
        }
        PathBuf::from(".")
    }
    #[cfg(not(windows))]
    {
        if let Some(v) = std::env::var_os("XDG_DATA_HOME") {
            let p = PathBuf::from(v);
            if p.is_absolute() {
                return p;
            }
        }
        if let Some(v) = std::env::var_os("HOME") {
            return PathBuf::from(v).join(".local").join("share");
        }
        PathBuf::from(".")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mxc_common::logger::Mode;
    use crate::mxc_common::models::ContainerPolicy;

    fn runner() -> HyperlightScriptRunner {
        HyperlightScriptRunner::new()
    }

    fn fresh_tmp(tag: &str) -> PathBuf {
        let tmp = std::env::temp_dir().join(format!("hl-runner-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        tmp
    }

    fn assert_denied_overlap_message(message: &str) {
        assert!(message.contains("deniedPaths"), "got: {message}");
        assert!(
            message.contains("overlapping allowed and denied host paths"),
            "got: {message}"
        );
    }

    #[cfg(target_os = "windows")]
    fn assert_denied_resolution_message(message: &str) {
        assert!(
            message.contains("cannot verify deniedPaths against allow lists"),
            "got: {message}"
        );
        assert!(
            message.contains("fails closed rather than risk an unenforced deny"),
            "got: {message}"
        );
    }

    #[test]
    fn is_installed_false_on_empty_dir() {
        let tmp = fresh_tmp("empty");
        assert!(!is_installed(&tmp, HyperlightRuntime::Agent));
        assert!(!has_install_source(&tmp, HyperlightRuntime::Agent));
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn has_install_source_true_when_rootfs_present() {
        let tmp = fresh_tmp("install-src");
        std::fs::write(tmp.join(INITRD_FILE), b"").unwrap();
        assert!(has_install_source(&tmp, HyperlightRuntime::Agent));
        assert!(!is_installed(&tmp, HyperlightRuntime::Agent)); // snapshot still absent
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn rootfs_stamped_for_another_release_is_not_an_install_source() {
        let tmp = fresh_tmp("stale");
        std::fs::write(tmp.join(INITRD_FILE), b"").unwrap();
        // A stamp from an earlier release than ROOTFS_TAG names.
        let agent = HyperlightRuntime::Agent;
        std::fs::write(
            tmp.join(VERSION_FILE),
            format!("rootfs: {}:initrd-v0.13.0\n", runtime_image(agent).image),
        )
        .unwrap();
        assert!(!has_install_source(&tmp, agent));
        assert!(!is_installed(&tmp, agent));

        std::fs::write(tmp.join(VERSION_FILE), version_stamp(agent)).unwrap();
        assert!(has_install_source(&tmp, agent));
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn rootfs_tag_follows_the_pinned_crate_release() {
        let manifest =
            std::fs::read_to_string(concat!(env!("CARGO_MANIFEST_DIR"), "/Cargo.toml")).unwrap();
        let line = manifest
            .lines()
            .find(|l| l.starts_with("hyperlight-unikraft = "))
            .expect("the crate dependency line");
        let version = line
            .split("version = \"")
            .nth(1)
            .and_then(|rest| rest.split('"').next())
            .expect("a pinned version");
        // A caret requirement would let a lockfile refresh take a later
        // release whose kernel no longer boots the rootfs at ROOTFS_TAG.
        let version = version
            .strip_prefix('=')
            .expect("an exact (`=`) requirement");
        assert_eq!(ROOTFS_TAG, format!("initrd-v{version}"));
    }

    #[test]
    fn a_runtime_only_takes_its_own_rootfs() {
        let tmp = fresh_tmp("runtimes");
        let agent = tmp.join(HyperlightRuntime::Agent.name());
        let node = tmp.join(HyperlightRuntime::Node.name());
        for dir in [&agent, &node] {
            std::fs::create_dir_all(dir).unwrap();
            std::fs::write(dir.join(INITRD_FILE), b"").unwrap();
            std::fs::write(
                dir.join(VERSION_FILE),
                version_stamp(HyperlightRuntime::Agent),
            )
            .unwrap();
        }
        assert!(has_install_source(&agent, HyperlightRuntime::Agent));
        assert!(!has_install_source(&node, HyperlightRuntime::Node));
        std::fs::write(
            node.join(VERSION_FILE),
            version_stamp(HyperlightRuntime::Node),
        )
        .unwrap();
        assert!(has_install_source(&node, HyperlightRuntime::Node));
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_home_errors_when_nothing_configured() {
        // Redirect every candidate away from any real install on the
        // test machine: MXC_HYPERLIGHT_HOME, XDG_DATA_HOME (Linux), LOCALAPPDATA
        // (Windows), HOME/USERPROFILE all get pointed into an empty
        // tmpdir for the duration of this test.
        let empty = fresh_tmp("resolve-empty");

        let saved: Vec<(&str, Option<std::ffi::OsString>)> = [
            HOME_ENV,
            "XDG_DATA_HOME",
            "HOME",
            "LOCALAPPDATA",
            "USERPROFILE",
        ]
        .iter()
        .map(|k| (*k, std::env::var_os(k)))
        .collect();
        // SAFETY: tests are serialized by default in this crate.
        unsafe {
            for (k, _) in &saved {
                std::env::remove_var(k);
            }
            std::env::set_var("HOME", &empty);
            std::env::set_var("USERPROFILE", &empty);
            std::env::set_var("XDG_DATA_HOME", &empty);
            std::env::set_var("LOCALAPPDATA", &empty);
        }

        let result = HyperlightScriptRunner::resolve_home(HyperlightRuntime::Agent);

        // Restore env before asserting so a failing assert can't leak.
        unsafe {
            for (k, v) in &saved {
                match v {
                    Some(val) => std::env::set_var(k, val),
                    None => std::env::remove_var(k),
                }
            }
        }
        let _ = std::fs::remove_dir_all(&empty);

        let err = result.unwrap_err();
        assert!(
            err.to_string().contains("no hyperlight image found"),
            "got: {err}"
        );
    }

    #[test]
    fn policy_accepts_readwrite_paths_and_builds_mounts() {
        // We can't end-to-end test without a real image; just verify
        // the policy→Mount mapping.
        let tmp = fresh_tmp("mount");
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                readwrite_paths: vec![tmp.to_string_lossy().to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let mounts = HyperlightScriptRunner::mounts_from_policy(&request).unwrap();
        assert_eq!(mounts.len(), 1);
        assert_eq!(
            mounts[0].guest_path,
            format!("/host/{}", tmp.file_name().unwrap().to_string_lossy())
        );
        assert!(!mounts[0].readonly);
        assert_eq!(mounts[0].host_path, std::fs::canonicalize(&tmp).unwrap());
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn policy_marks_readonly_paths() {
        let tmp = fresh_tmp("mount-ro");
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                readonly_paths: vec![tmp.to_string_lossy().to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let mounts = HyperlightScriptRunner::mounts_from_policy(&request).unwrap();
        assert_eq!(mounts.len(), 1);
        assert!(mounts[0].readonly);
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn policy_rejects_mount_collision_on_same_basename() {
        let a = std::env::temp_dir().join(format!("hl-col-a-{}/same", std::process::id()));
        let b = std::env::temp_dir().join(format!("hl-col-b-{}/same", std::process::id()));
        std::fs::create_dir_all(&a).unwrap();
        std::fs::create_dir_all(&b).unwrap();
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                readwrite_paths: vec![
                    a.to_string_lossy().to_string(),
                    b.to_string_lossy().to_string(),
                ],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::mounts_from_policy(&request).unwrap_err();
        assert!(
            err.to_string().contains("collide on guest path"),
            "got: {err}"
        );
        let _ = std::fs::remove_dir_all(a.parent().unwrap());
        let _ = std::fs::remove_dir_all(b.parent().unwrap());
    }

    #[test]
    fn policy_rejects_mount_name_the_kernel_cannot_carry() {
        let tmp = fresh_tmp("mount-bad").join("with space");
        std::fs::create_dir_all(&tmp).unwrap();
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                readwrite_paths: vec![tmp.to_string_lossy().to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::mounts_from_policy(&request).unwrap_err();
        assert!(
            err.to_string().contains("may not contain whitespace"),
            "got: {err}"
        );
        let _ = std::fs::remove_dir_all(tmp.parent().unwrap());
    }

    #[test]
    fn policy_rejects_denied_overlapping_allow() {
        let mut r = runner();
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec!["/tmp/x".to_string()],
                denied_paths: vec!["/tmp/x".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let resp = r.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert_denied_overlap_message(&resp.error_message);
    }

    #[test]
    fn policy_rejects_denied_descendant_of_allowed_mount() {
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec!["/tmp/hyperlight-allowed".to_string()],
                denied_paths: vec!["/tmp/hyperlight-allowed/secret".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
        assert_denied_overlap_message(&err.to_string());
    }

    #[test]
    fn policy_rejects_allowed_mount_inside_denied_parent() {
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec!["/tmp/hyperlight-denied-parent/child".to_string()],
                denied_paths: vec!["/tmp/hyperlight-denied-parent".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
        assert_denied_overlap_message(&err.to_string());
    }

    #[cfg(unix)]
    #[test]
    fn policy_rejects_denied_overlap_when_allow_is_symlink_alias() {
        let tmp = fresh_tmp("deny-symlink-alias");
        let real = tmp.join("real");
        let link = tmp.join("link");
        std::fs::create_dir_all(&real).unwrap();
        match std::os::unix::fs::symlink(&real, &link) {
            Ok(()) => {}
            Err(e)
                if e.kind() == std::io::ErrorKind::Unsupported
                    || e.kind() == std::io::ErrorKind::PermissionDenied =>
            {
                let _ = std::fs::remove_dir_all(&tmp);
                return;
            }
            Err(e) => panic!("create symlink {link:?} -> {real:?}: {e}"),
        }

        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![link.to_string_lossy().to_string()],
                denied_paths: vec![real.join("secret").to_string_lossy().to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
        assert_denied_overlap_message(&err.to_string());
        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn policy_rejects_denied_absolute_descendant_of_missing_relative_mount() {
        let relative_mount = format!("hyperlight-relative-{}", std::process::id());
        let denied = std::env::current_dir()
            .unwrap()
            .join(&relative_mount)
            .join("secret");
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![relative_mount],
                denied_paths: vec![denied.to_string_lossy().to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
        assert_denied_overlap_message(&err.to_string());
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn policy_rejects_denied_missing_windows_case_variant_allow_overlap() {
        let mut r = runner();
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![
                    "C:\\MXC\\HyperlightMissingCase\\temp\\..\\PRIVATECACHE\\\\".to_string()
                ],
                denied_paths: vec!["c:/mxc//hyperlightmissingcase/./privatecache".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let resp = r.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert_denied_overlap_message(&resp.error_message);
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn policy_rejects_denied_missing_windows_verbatim_allow_overlap() {
        let mut r = runner();
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![
                    "\\\\?\\C:\\MXC\\HyperlightVerbatim\\temp\\..\\PRIVATECACHE\\".to_string(),
                ],
                denied_paths: vec!["c:/mxc/hyperlightverbatim/privatecache".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let resp = r.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert_denied_overlap_message(&resp.error_message);
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn policy_rejects_denied_missing_windows_trailing_dot_allow_overlap() {
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![
                    "C:\\MXC\\HyperlightTrailingDot\\temp\\..\\PRIVATECACHE.\\".to_string()
                ],
                denied_paths: vec!["c:/mxc/hyperlighttrailingdot/privatecache".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = HyperlightScriptRunner::validate_policies(&request).unwrap_err();
        assert_denied_resolution_message(&err.to_string());
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn policy_keeps_verbatim_windows_trailing_dot_distinct() {
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec![
                    "\\\\?\\C:\\MXC\\HyperlightVerbatimDot\\PRIVATECACHE.".to_string()
                ],
                denied_paths: vec!["c:/mxc/hyperlightverbatimdot/privatecache".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        HyperlightScriptRunner::validate_policies(&request).unwrap();
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn fallback_reports_indeterminate_for_unresolved_windows_paths() {
        use crate::mxc_common::filesystem_canonical::PathCanonical;

        assert_eq!(
            path_relationship_fallback_with(
                "C:\\MXC\\HyperlightUnknown\\allow",
                "C:\\MXC\\HyperlightUnknown\\deny",
                |_| PathCanonical::Unknown,
            ),
            PathRelationship::Indeterminate
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn fallback_canonicalizes_verbatim_trailing_dot_alias_ancestors() {
        use crate::mxc_common::filesystem_canonical::PathCanonical;

        assert_eq!(
            path_relationship_fallback_with(
                "\\\\?\\C:\\link\\cache.",
                "\\\\?\\C:\\real\\cache.",
                |path| match path {
                    "\\\\?\\C:\\link\\cache." => {
                        PathCanonical::Canonical("C:\\real\\cache.".to_string())
                    }
                    "\\\\?\\C:\\real\\cache." => {
                        PathCanonical::Canonical("C:\\real\\cache.".to_string())
                    }
                    _ => PathCanonical::Absent,
                },
            ),
            PathRelationship::Overlaps
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn fallback_never_separates_mixed_spelling_of_same_dotted_canonical_tree() {
        use crate::mxc_common::filesystem_canonical::PathCanonical;

        let relationship =
            path_relationship_fallback_with("C:\\link\\child", "\\\\?\\C:\\real.\\child", |path| {
                match path {
                    "C:\\link\\child" | "\\\\?\\C:\\real.\\child" => {
                        PathCanonical::Canonical("C:\\real.\\child".to_string())
                    }
                    _ => PathCanonical::Absent,
                }
            });

        assert!(
            matches!(
                relationship,
                PathRelationship::Overlaps | PathRelationship::Indeterminate
            ),
            "same resolved tree must overlap or fail closed, got {relationship:?}"
        );
    }

    #[cfg(target_os = "windows")]
    #[test]
    fn fallback_fails_closed_when_dotted_canonical_component_provenance_is_ambiguous() {
        use crate::mxc_common::filesystem_canonical::PathCanonical;

        assert_eq!(
            path_relationship_fallback_with(
                "C:\\link.\\child",
                "\\\\?\\C:\\real.\\child",
                |path| match path {
                    "C:\\link.\\child" | "\\\\?\\C:\\real.\\child" => {
                        PathCanonical::Canonical("C:\\real.\\child".to_string())
                    }
                    _ => PathCanonical::Absent,
                },
            ),
            PathRelationship::Indeterminate
        );
    }

    #[cfg(not(target_os = "windows"))]
    #[test]
    fn fallback_path_comparison_stays_case_sensitive_off_windows() {
        assert_eq!(
            path_relationship("/tmp/mxc-missing-case", "/tmp/mxc-missing-case"),
            PathRelationship::Overlaps
        );
        assert_eq!(
            path_relationship("/tmp/MXC-MISSING-CASE", "/tmp/mxc-missing-case"),
            PathRelationship::Separate
        );
    }

    #[test]
    fn omitted_network_policy_is_valid_and_keeps_guest_disconnected() {
        runner()
            .validate_runner(&ExecutionRequest::default())
            .unwrap();
    }

    #[test]
    fn explicit_directional_allow_is_rejected_before_boot() {
        let mut request = ExecutionRequest::default();
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: crate::mxc_common::models::NetworkAction::Allow,
            ..Default::default()
        });
        let error = runner().validate_runner(&request).unwrap_err();
        assert!(error.error_message.contains("network.egress.default"));
    }

    #[test]
    fn direct_execute_rejects_network_policy_before_boot() {
        let mut request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            ..Default::default()
        };
        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: crate::mxc_common::models::NetworkAction::Allow,
            ..Default::default()
        });
        let mut r = runner();
        let mut logger = Logger::new(Mode::Buffer);
        let response = r.execute(&request, &mut logger);
        assert!(response.error_message.contains("network.egress.default"));
    }

    #[test]
    fn dry_run_validates_without_booting() {
        let mut request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            dry_run: true,
            ..Default::default()
        };
        let mut r = runner();
        let mut logger = Logger::new(Mode::Buffer);
        assert_eq!(r.run(&request, &mut logger).exit_code, 0);

        request.policy.network_egress = Some(crate::mxc_common::models::NetworkEgressPolicy {
            default: crate::mxc_common::models::NetworkAction::Allow,
            ..Default::default()
        });
        let response = r.run(&request, &mut logger);
        assert!(response.error_message.contains("network.egress.default"));
    }

    #[test]
    fn policy_rejects_working_directory() {
        let mut r = runner();
        let request = ExecutionRequest {
            script_code: "print('x')".to_string(),
            working_directory: "C:/tmp".to_string(),
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let resp = r.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert!(resp.error_message.contains(ERR_WORKDIR));
    }
}