mxc-sdk 1.0.0

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
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! `NanVixScriptRunner` -- executes code inside a NanVix micro-VM.
//!
//! The initial runtime is CPython 3.12 with a trimmed FAT32 stdlib filesystem.
//! The architecture supports additional runtimes (QuickJS, C, C++, Rust binaries).
//!
//! ## I/O model
//!
//! - **stdin**: set to `Stdio::null()` (NanVix guest does not read host stdin)
//! - **stdout**: inherited from parent via `Stdio::inherit()` (not captured)
//! - **stderr**: inherited from parent by default (kernel traces stream
//!   straight to the parent terminal). When the `MXC_NANVIX_TRACE` env var
//!   is truthy, stderr is piped and captured so it can be embedded in the
//!   wxc-exec log on non-zero exit.
//!
//! **Note for SDK consumers:** Use `usePty: false` (non-PTY mode) for the MicroVM
//! backend. PTY mode is not supported. Because stdout/stderr are inherited,
//! `ScriptResponse.standard_out` and `standard_err` are always empty strings.
//! Output is streamed directly to the parent's pipes.
//!
//! ## Diagnostics
//!
//! By default the runner sets `RUST_LOG=off` in nanvixd's environment, which
//! suppresses the per-run `%LOCALAPPDATA%\nanvix\logs\nanvixd_*.log` trace
//! file and noticeably reduces warm-start latency. Set `MXC_NANVIX_TRACE=1`
//! (or `true`/`yes`, case-insensitive) before invoking wxc-exec to let
//! nanvixd use its own `RUST_LOG` default and to capture nanvixd's stderr
//! for inclusion in the wxc-exec log.
//!
//! ## Exit codes
//!
//! `nanvixd` propagates the guest process exit code directly.
//!
//! ## Networking
//!
//! Host networking is **off by default** and is enabled per-run by passing
//! `-allow-host-networking` to `nanvixd`. The runner adds that flag when the
//! request sets `network.defaultPolicy = "allow"`, or when `allowedHosts` /
//! `blockedHosts` is present (forwarded as `-allow-host` / `-block-host`).
//! Network proxies are not supported and are rejected at validation time.
//!
//! Auto-discovery
//!
//! All required binaries (`nanvixd.exe`, `python3.initrd`, `nanvix_rootfs.img`)
//! are discovered next to the running executable. No configuration is needed.

use std::fmt::Write;
use std::net::ToSocketAddrs;
use std::path::{Path, PathBuf};
use std::process::{Child, Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::thread::JoinHandle;
use std::time::{Duration, Instant};

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

/// Multi-binary initrd (daemons + CPython) loaded by NanVix at warm start.
const INITRD_BINARY: &str = crate::nanvix_common::INITRD_BINARY;
/// NanVix daemon binary launched by the host runner (platform-conditional).
const NANVIXD_BINARY: &str = crate::nanvix_common::NANVIXD_BINARY;
/// Combined rootfs image (NanVix kernel userspace + CPython stdlib).
const RAMFS_IMAGE: &str = crate::nanvix_common::RAMFS_IMAGE;
/// Pre-built VM state snapshot (CBOR) for warm start (Windows/WHP only).
#[cfg(target_os = "windows")]
const SNAPSHOT_CBOR: &str = crate::nanvix_common::SNAPSHOT_CBOR;
/// Subdirectory holding snapshot files next to the exe (Windows/WHP only).
#[cfg(target_os = "windows")]
const SNAPSHOTS_DIR: &str = crate::nanvix_common::SNAPSHOTS_SUBDIR;
/// Subdirectory holding kernel binary.
const BIN_DIR: &str = crate::nanvix_common::BIN_SUBDIR;
/// Env var override for the NanVix snapshot home directory. Set this to
/// force a specific location; otherwise the runner uses a standard
/// OS-local data path or falls back to `<exe>/snapshots/`.
#[cfg(target_os = "windows")]
const NANVIX_HOME_ENV: &str = "NANVIX_HOME";
/// Env var that opts in to nanvixd's verbose tracing (and captured stderr).
/// When unset (the default), the runner forces `RUST_LOG=off` for nanvixd
/// and inherits stderr, which saves ~25–30 ms per warm execution by
/// avoiding nanvixd's per-run log file and the host-side stderr drain.
const NANVIX_TRACE_ENV: &str = "MXC_NANVIX_TRACE";
/// Final component of the default OS-local data path (Windows only).
#[cfg(target_os = "windows")]
const DEFAULT_HOME_LEAF: &str = "nanvix";
/// Boot grace period that is always enforced.
const BOOT_TIMEOUT_MS: u64 = 60_000;
/// Generic error exit code returned to host callers.
const ERROR_EXIT_CODE: i32 = -1;
/// Maximum age of orphaned staging dirs before cleanup (1 hour).
const ORPHAN_SWEEP_MAX_AGE_SECS: u64 = 3600;
const ERR_DENIED_PATHS: &str = concat!(
    "denied_paths is not meaningful for the microvm backend ",
    "-- the guest has no host filesystem visibility. ",
    "Only readwrite_paths and readonly_paths are supported",
);
const ERR_NETWORK_HOSTS: &str = concat!(
    "allowedHosts and blockedHosts are mutually exclusive for the NanVix backend -- ",
    "the guest egress filter is allow-XOR-block. Specify an allowlist (allowedHosts) ",
    "or a blocklist (blockedHosts), not both",
);
const ERR_HOSTS_UNRESOLVED: &str = concat!(
    "none of the specified allowedHosts/blockedHosts resolved to an IPv4 address -- ",
    "the NanVix guest filter is IPv4-only; use IPv4 literals/CIDR or hosts with A records",
);
const ERR_BLOCKED_HOST_UNRESOLVED: &str = concat!(
    "a blockedHosts entry did not resolve to any IPv4 address -- ",
    "the NanVix guest egress filter is static (resolved once at preflight) and IPv4-only, ",
    "so an unresolvable blocked host cannot be enforced. Silently dropping it would let ",
    "traffic the policy explicitly blocks flow freely, so the run is rejected (fail-closed). ",
    "Use an IPv4 literal/CIDR or a host with A records",
);
const ERR_PROXY_POLICY: &str = "network proxy is not supported by the NanVix backend";
const ERR_DIRECTIONAL_NETWORK: &str = "NanVix supports only fully isolated or explicitly \
    unrestricted directional networking: egress.default, ingress.default and ingress.hostLoopback \
    must all be deny or all be allow; independent ingress or host-loopback restrictions are not supported";
const ERR_DIRECTIONAL_FILTERS: &str = "NanVix cannot enforce directional egress rules: its legacy \
    IPv4 filter has implicit exceptions and does not implement the directional rule contract; \
    use fully isolated networking or explicitly unrestricted networking without rules";
const ERR_WORKDIR: &str = "workingDirectory is not supported by the NanVix backend -- guest has its own filesystem namespace";

/// Outcome of resolving a request's egress host lists.
///
/// `allow`/`block` are the IPv4/CIDR literals handed to nanvixd; at most one is
/// non-empty. `warnings` carries human-readable notices for allowlist entries
/// that were dropped during resolution (blocklist drops are a hard error and
/// never reach here).
#[derive(Debug)]
struct ResolvedHostLists {
    allow: Vec<String>,
    block: Vec<String>,
    warnings: Vec<String>,
}

/// Maps a finished child's [`ExitStatus`] to a host-visible exit code.
///
/// On Unix, processes terminated by a signal have no exit code (`status.code()`
/// returns `None`); we surface them as the negated signal number (e.g. SIGKILL
/// → `-9`) so callers can distinguish them from normal exits and from the
/// generic [`ERROR_EXIT_CODE`] sentinel. On Windows, `status.code()` always
/// returns `Some(_)`.
fn exit_code_from_status(status: &std::process::ExitStatus) -> i32 {
    if let Some(code) = status.code() {
        return code;
    }
    #[cfg(unix)]
    {
        use std::os::unix::process::ExitStatusExt;
        if let Some(signal) = status.signal() {
            return -signal;
        }
    }
    ERROR_EXIT_CODE
}

// -- NanVix error classification ---------------------------------------------

/// Classifies NanVix runner errors for structured error handling.
#[derive(Debug)]
enum NanVixError {
    /// Pre-spawn validation failures (missing artifacts, invalid config, unsupported policy).
    Preflight(String),
    /// OS/platform failures while spawning/managing the NanVix process (WHP/spawn/handles).
    Platform(String),
    /// Stdin broken pipe, VM crash.
    Runtime(String),
    /// Watchdog killed the process.
    Timeout {
        script_timeout_ms: u32,
        total_ms: u64,
    },
}

impl std::fmt::Display for NanVixError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            NanVixError::Preflight(msg) => write!(f, "NanVix preflight error: {}", msg),
            NanVixError::Platform(msg) => write!(f, "NanVix platform error: {}", msg),
            NanVixError::Runtime(msg) => write!(f, "NanVix runtime error: {}", msg),
            NanVixError::Timeout {
                script_timeout_ms,
                total_ms,
            } => write!(
                f,
                "NanVix execution timed out after {}ms \
                 (boot_timeout={}ms, script_timeout={}ms)",
                total_ms, BOOT_TIMEOUT_MS, script_timeout_ms
            ),
        }
    }
}

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

/// Returns the directory containing the current executable.
///
/// Inlined (rather than reusing `crate::mxc_common::process_util::exe_dir`) because
/// `process_util` is gated to `target_os = "windows"`.
fn exe_dir() -> Result<PathBuf, NanVixError> {
    std::env::current_exe()
        .map_err(|e| NanVixError::Preflight(format!("cannot determine exe path: {}", e)))
        .and_then(|exe| {
            exe.parent()
                .map(|p| p.to_path_buf())
                .ok_or_else(|| NanVixError::Preflight("exe has no parent directory".to_string()))
        })
}

/// Returns `true` when [`NANVIX_TRACE_ENV`] is set to a truthy value
/// (`"1"`, `"true"`, or `"yes"`, case-insensitive). Any other value
/// (including unset, empty, or `"0"`/`"false"`/`"no"`) means trace is off.
fn nanvix_trace_enabled() -> bool {
    match std::env::var(NANVIX_TRACE_ENV) {
        Ok(v) => matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true" | "yes"),
        Err(_) => false,
    }
}

/// Watchdog thread: waits for timeout or cancellation, then terminates the process.
///
/// On Windows, `process_id_or_handle` is a duplicated process HANDLE (as usize).
/// On Linux, `process_id_or_handle` is the child PID (as usize).
fn watchdog_thread_fn(
    process_id_or_handle: usize,
    duration: Duration,
    cancel_pair: Arc<(Mutex<bool>, Condvar)>,
    timed_out: Arc<AtomicBool>,
) {
    let (lock, cvar) = &*cancel_pair;
    let mut cancelled = lock.lock().unwrap_or_else(|e| e.into_inner());
    let start = Instant::now();
    let mut remaining = duration;
    loop {
        let result = cvar
            .wait_timeout(cancelled, remaining)
            .unwrap_or_else(|e| e.into_inner());
        cancelled = result.0;
        if *cancelled || result.1.timed_out() {
            break;
        }
        let elapsed = start.elapsed();
        if elapsed >= duration {
            break;
        }
        remaining = duration.saturating_sub(elapsed);
    }

    #[cfg(target_os = "windows")]
    {
        // Always close the duplicated handle to avoid leaks.
        let close_handle = |handle_raw: usize| {
            use windows::Win32::Foundation::{CloseHandle, HANDLE};
            let handle = HANDLE(handle_raw as *mut std::ffi::c_void);
            // SAFETY: `handle` was returned by `DuplicateHandle` in this
            // process and is closed exactly once by this watchdog thread.
            let _ = unsafe { CloseHandle(handle) };
        };

        if *cancelled {
            close_handle(process_id_or_handle);
            return;
        }

        timed_out.store(true, Ordering::SeqCst);

        use windows::Win32::Foundation::HANDLE;
        use windows::Win32::System::Threading::TerminateProcess;

        let handle = HANDLE(process_id_or_handle as *mut std::ffi::c_void);
        // SAFETY: `handle` is a valid duplicated process handle owned by
        // this thread, and passing exit code 1 is valid for termination.
        let _ = unsafe { TerminateProcess(handle, 1) };
        close_handle(process_id_or_handle);
    }

    #[cfg(target_os = "linux")]
    {
        if *cancelled {
            return;
        }

        timed_out.store(true, Ordering::SeqCst);

        // Kill the child process by PID using SIGKILL.
        let pid = process_id_or_handle as i32;
        // SAFETY: sending SIGKILL to a known child PID is always valid.
        // If the process already exited, `kill()` returns ESRCH which we ignore.
        unsafe {
            libc::kill(pid, libc::SIGKILL);
        }
    }
}

/// Components returned by [`NanVixScriptRunner::setup_watchdog`]: the watchdog
/// thread handle (if a finite timeout was requested), the cancellation pair
/// used to signal early completion, and the `timed_out` flag.
type WatchdogState = (
    Option<JoinHandle<()>>,
    Arc<(Mutex<bool>, Condvar)>,
    Arc<AtomicBool>,
);

// -- NanVixScriptRunner ------------------------------------------------------

/// Script runner that executes Python code inside a NanVix microkernel VM.
///
/// All binaries are auto-discovered next to the running executable.
pub struct NanVixScriptRunner {
    _private: (),
}

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

/// Resolved paths for NanVix invocation.
#[derive(Debug)]
struct ResolvedPaths {
    nanvixd: PathBuf,
    ramfs: PathBuf,
    initrd: PathBuf,
    /// Directory holding the `bin/` subdir next to the exe.
    exe_dir: PathBuf,
    /// Snapshot home directory — used as cwd for nanvixd so it can locate
    /// `snapshots/kernel.vmem` relative to cwd (nanvixd constraint).
    snapshot_home: PathBuf,
}

impl NanVixScriptRunner {
    pub fn new() -> Self {
        Self { _private: () }
    }

    /// Resolve and validate all required paths next to the running executable.
    fn resolve_paths(&self) -> Result<ResolvedPaths, NanVixError> {
        let dir = exe_dir()?;

        let nanvixd = dir.join(NANVIXD_BINARY);
        if !nanvixd.exists() {
            return Err(NanVixError::Preflight(format!(
                "{} not found in {:?}",
                NANVIXD_BINARY, dir
            )));
        }

        let ramfs = dir.join(RAMFS_IMAGE);
        if !ramfs.exists() {
            return Err(NanVixError::Preflight(format!(
                "{} not found in {:?}",
                RAMFS_IMAGE, dir
            )));
        }

        let initrd = dir.join(INITRD_BINARY);
        if !initrd.exists() {
            return Err(NanVixError::Preflight(format!(
                "{} not found in {:?}",
                INITRD_BINARY, dir
            )));
        }

        // Preflight-check bin/ subdir contents (nanvixd loads `./bin/kernel.elf`
        // via `-bin-dir`; missing the file here yields a clearer error than
        // letting nanvixd fail at boot time).
        let bin_subdir = dir.join(BIN_DIR);
        for name in crate::nanvix_common::BIN_SUBDIR_FILES {
            let path = bin_subdir.join(name);
            if !path.exists() {
                return Err(NanVixError::Preflight(format!(
                    "{}/{} not found in {:?}",
                    BIN_DIR, name, dir
                )));
            }
        }

        // Snapshot resolution — Windows only (WHP snapshots for warm start).
        // Linux uses cold boot via KVM every time.
        #[cfg(target_os = "windows")]
        let snapshot_home = {
            let home = Self::resolve_snapshot_home(&dir)?;
            // Warm start requires *all* snapshot files (kernel.vmem + kernel.whp.cbor);
            // a partial/corrupt set must trigger regeneration instead of a late failure
            // inside nanvixd.
            let snapshots_present = crate::nanvix_common::SNAPSHOT_FILES
                .iter()
                .all(|name| home.join(SNAPSHOTS_DIR).join(name).exists());
            if !snapshots_present {
                // No (complete) snapshot yet — generate one via cold boot
                // (one-time cost, ~400–500 ms). Subsequent runs restore directly.
                Self::generate_snapshot(&dir, &home, &nanvixd, &ramfs, &initrd)?;
            }
            home
        };

        #[cfg(target_os = "linux")]
        let snapshot_home = dir.clone();

        Ok(ResolvedPaths {
            nanvixd,
            ramfs,
            initrd,
            exe_dir: dir,
            snapshot_home,
        })
    }

    /// Resolve the snapshot home directory (Windows only — WHP snapshots).
    ///
    /// Discovery chain (first match wins):
    /// 1. `$NANVIX_HOME` env var (if set and non-empty)
    /// 2. `<exe>` directory itself, when a complete set of pre-generated
    ///    snapshots already lives in `<exe>/snapshots/` (build-time output
    ///    or shipped artifacts) — using it avoids a redundant cold boot.
    /// 3. OS-local data path (`%LOCALAPPDATA%\nanvix` on Windows)
    /// 4. `<exe>` directory itself as a last-resort fallback (dev builds —
    ///    nanvixd will write snapshots into `<exe>/snapshots/`).
    #[cfg(target_os = "windows")]
    fn resolve_snapshot_home(exe_dir: &Path) -> Result<PathBuf, NanVixError> {
        // 1. Env var override.
        if let Some(val) = std::env::var_os(NANVIX_HOME_ENV) {
            let p = PathBuf::from(val);
            if !p.as_os_str().is_empty() {
                std::fs::create_dir_all(&p).map_err(|e| {
                    NanVixError::Preflight(format!(
                        "cannot create ${} directory {:?}: {}",
                        NANVIX_HOME_ENV, p, e
                    ))
                })?;
                return Ok(p);
            }
        }

        // 2. Prefer exe-side snapshots when they're already complete, so
        //    build-time-generated artifacts shipped next to wxc-exec are
        //    actually used instead of triggering a fresh cold boot in
        //    %LOCALAPPDATA%.
        let exe_snapshots = exe_dir.join(SNAPSHOTS_DIR);
        let exe_snapshots_complete = crate::nanvix_common::SNAPSHOT_FILES
            .iter()
            .all(|name| exe_snapshots.join(name).exists());
        if exe_snapshots_complete {
            return Ok(exe_dir.to_path_buf());
        }

        // 3. OS-local data path.
        if let Some(home) = Self::default_home() {
            if home.exists() || std::fs::create_dir_all(&home).is_ok() {
                return Ok(home);
            }
        }

        // 4. Fallback: exe directory itself (nanvixd writes to <cwd>/snapshots/).
        Ok(exe_dir.to_path_buf())
    }

    /// Default OS-local snapshot home path.
    #[cfg(target_os = "windows")]
    fn default_home() -> Option<PathBuf> {
        std::env::var_os("LOCALAPPDATA").map(|d| PathBuf::from(d).join(DEFAULT_HOME_LEAF))
    }

    /// Generate a WHP snapshot via cold boot (one-time cost, Windows only).
    ///
    /// Delegates to `crate::nanvix_common::generate_snapshot` which runs nanvixd with
    /// `-kernel-args snapshot` and cwd set to `snapshot_home`. nanvixd writes
    /// snapshot files to `<snapshot_home>/snapshots/` directly. Subsequent runs
    /// restore from the snapshot (~20 ms vs ~430 ms cold boot).
    #[cfg(target_os = "windows")]
    fn generate_snapshot(
        exe_dir: &Path,
        snapshot_home: &Path,
        nanvixd: &Path,
        ramfs: &Path,
        initrd: &Path,
    ) -> Result<(), NanVixError> {
        std::fs::create_dir_all(snapshot_home).map_err(|e| {
            NanVixError::Preflight(format!("failed to create snapshot home: {}", e))
        })?;

        eprintln!("nanvix: no snapshot found — generating via cold boot (one-time cost)...");

        let start = Instant::now();
        crate::nanvix_common::generate_snapshot(
            snapshot_home,
            nanvixd,
            &exe_dir.join(BIN_DIR),
            ramfs,
            initrd,
        )
        .map_err(NanVixError::Preflight)?;

        eprintln!(
            "nanvix: snapshot generated in {:.0?} — subsequent runs will use warm start",
            start.elapsed()
        );
        Ok(())
    }

    /// Compute total timeout: boot grace + staging overhead + script timeout.
    /// When `script_timeout == 0` the caller intends "no limit", so the watchdog
    /// is disabled entirely (returns `u64::MAX`). Boot and staging time are
    /// unbounded in this case — this is by design for interactive/exploratory use.
    fn total_timeout_ms(script_timeout: u32, staging_overhead_ms: u64) -> u64 {
        if script_timeout == 0 {
            u64::MAX
        } else {
            BOOT_TIMEOUT_MS
                .saturating_add(staging_overhead_ms)
                .saturating_add(script_timeout as u64)
        }
    }

    fn resolve_networking_mode(request: &ExecutionRequest) -> Result<bool, NanVixError> {
        let policy = &request.policy;
        if policy.network_egress.is_none() && policy.network_ingress.is_none() {
            return Ok(policy.default_network_policy == NetworkPolicy::Allow
                || !policy.allowed_hosts.is_empty());
        }
        if !policy.allowed_hosts.is_empty()
            || !policy.blocked_hosts.is_empty()
            || policy
                .network_egress
                .as_ref()
                .is_some_and(|egress| !egress.allow.is_empty() || !egress.deny.is_empty())
        {
            return Err(NanVixError::Preflight(ERR_DIRECTIONAL_FILTERS.to_string()));
        }
        let egress = policy
            .network_egress
            .as_ref()
            .map(|egress| egress.default)
            .unwrap_or(NetworkAction::Deny);
        let ingress = policy
            .network_ingress
            .as_ref()
            .map(|ingress| ingress.default)
            .unwrap_or(NetworkAction::Deny);
        let host_loopback = policy
            .network_ingress
            .as_ref()
            .map(|ingress| ingress.host_loopback)
            .unwrap_or(NetworkAction::Deny);
        if egress != ingress || ingress != host_loopback {
            return Err(NanVixError::Preflight(ERR_DIRECTIONAL_NETWORK.to_string()));
        }
        Ok(egress == NetworkAction::Allow)
    }

    /// Resolves a host entry list into IPv4/CIDR literals for nanvixd's
    /// `-allow-host`/`-block-host` flags, alongside the entries that resolved
    /// to nothing.
    ///
    /// - `a.b.c.d` and `a.b.c.d/n` literals pass through unchanged.
    /// - Hostnames resolve to their IPv4 (A-record) addresses; AAAA results are
    ///   dropped because the guest filter is IPv4-only.
    /// - Entries that fail to parse or resolve to any IPv4 address contribute
    ///   nothing to the resolved list and are collected into the second return
    ///   value so callers can warn (allowlist) or reject (blocklist).
    ///
    /// Mirrors `lxc::network_iptables::resolve_host` for the hostname-to-IPv4
    /// mapping; unlike that helper this also preserves IPv4/CIDR literals.
    ///
    /// Returns `(resolved_ips, unresolved_entries)`. Empty/whitespace entries
    /// are ignored entirely and appear in neither list.
    fn resolve_hosts_detailed(hosts: &[String]) -> (Vec<String>, Vec<String>) {
        let mut out: Vec<String> = Vec::new();
        let mut unresolved: Vec<String> = Vec::new();
        for host in hosts {
            let entry = host.trim();
            if entry.is_empty() {
                continue;
            }
            let before = out.len();
            // CIDR literal: pass through only when the address is IPv4 and the
            // prefix is in range. nanvixd parses CIDR directly.
            if let Some((addr, prefix)) = entry.split_once('/') {
                let addr_ok = addr.trim().parse::<std::net::Ipv4Addr>().is_ok();
                let prefix_ok = prefix
                    .trim()
                    .parse::<u8>()
                    .map(|p| p <= 32)
                    .unwrap_or(false);
                if addr_ok && prefix_ok {
                    out.push(entry.to_string());
                }
            } else if let Ok(addr) = entry.parse::<std::net::IpAddr>() {
                // Bare IP literal: keep IPv4, drop IPv6.
                if addr.is_ipv4() {
                    out.push(entry.to_string());
                }
            } else if let Ok(addrs) = format!("{}:0", entry).to_socket_addrs() {
                // Hostname: resolve to IPv4 A records.
                for ip in addrs.map(|a| a.ip()).filter(|ip| ip.is_ipv4()) {
                    out.push(ip.to_string());
                }
            }
            if out.len() == before {
                unresolved.push(entry.to_string());
            }
        }
        (out, unresolved)
    }

    /// Resolves the request's allow/block host lists, failing closed.
    ///
    /// Returns the resolved allow/block IPv4 lists plus human-readable warnings
    /// for any allowlist entries that were dropped. Shared validation rejects
    /// invalid default/list combinations before execution, and NanVix rejects
    /// simultaneous lists because its guest filter is allow-XOR-block.
    ///
    /// Fail-closed semantics differ by list direction:
    /// - **Allowlist** (deny-by-default): a fully unresolvable allowlist is an
    ///   error, because emitting `-allow-host-networking` with no filter would
    ///   fail open (nanvixd treats no list as allow-all). Partially dropped
    ///   entries only narrow access, so they are reported as warnings and the
    ///   run continues.
    /// - **Blocklist** (allow-by-default): *any* unresolvable entry is an
    ///   error. Silently dropping a blocked host would let traffic the policy
    ///   explicitly blocks flow freely (fail-open), and the static preflight
    ///   filter cannot enforce a name that does not resolve.
    fn resolve_host_lists(request: &ExecutionRequest) -> Result<ResolvedHostLists, NanVixError> {
        let (allow, allow_unresolved) = Self::resolve_hosts_detailed(&request.policy.allowed_hosts);
        if !request.policy.allowed_hosts.is_empty() && allow.is_empty() {
            return Err(NanVixError::Preflight(ERR_HOSTS_UNRESOLVED.to_string()));
        }

        let (block, block_unresolved) = Self::resolve_hosts_detailed(&request.policy.blocked_hosts);
        if let Some(first) = block_unresolved.first() {
            return Err(NanVixError::Preflight(format!(
                "{} (entry: '{}')",
                ERR_BLOCKED_HOST_UNRESOLVED, first
            )));
        }

        let warnings = allow_unresolved
            .iter()
            .map(|h| {
                format!(
                    "Warning: could not resolve allowedHosts entry '{}' to an IPv4 address; skipping",
                    h
                )
            })
            .collect();

        Ok(ResolvedHostLists {
            allow,
            block,
            warnings,
        })
    }

    fn validate_policies(request: &ExecutionRequest) -> Result<(), NanVixError> {
        // denied_paths is explicitly rejected — microvm has no host visibility.
        if !request.policy.denied_paths.is_empty() {
            return Err(NanVixError::Preflight(ERR_DENIED_PATHS.to_string()));
        }
        // NanVix's guest egress filter is allow-XOR-block and cannot represent
        // simultaneous allow and block lists, even though the shared policy model can.
        if request.policy.default_network_policy == NetworkPolicy::Block
            && !request.policy.allowed_hosts.is_empty()
            && !request.policy.blocked_hosts.is_empty()
        {
            return Err(NanVixError::Preflight(ERR_NETWORK_HOSTS.to_string()));
        }
        if request.policy.network_proxy.is_enabled() {
            return Err(NanVixError::Preflight(ERR_PROXY_POLICY.to_string()));
        }
        if !request.working_directory.is_empty() {
            return Err(NanVixError::Preflight(ERR_WORKDIR.to_string()));
        }
        Self::resolve_networking_mode(request)?;

        Ok(())
    }

    fn nanvixd_command(
        paths: &ResolvedPaths,
        staging_dir: &Path,
        request: &ExecutionRequest,
        allow_hosts: &[String],
        block_hosts: &[String],
    ) -> Result<Command, NanVixError> {
        let host_networking = Self::resolve_networking_mode(request)?;
        let trace = nanvix_trace_enabled();
        // Default: silence nanvixd and inherit stderr so kernel traces (if
        // any) stream straight to the parent terminal without a per-run
        // host-side drain. Diagnostic mode pipes stderr so the runner can
        // attach it to the wxc-exec log on failure.
        let stderr = if trace {
            Stdio::piped()
        } else {
            Stdio::inherit()
        };

        let mut cmd = Command::new(&paths.nanvixd);

        // Host networking is opt-in. When enabled, attach the host network
        // backend; nanvixd parses this flag regardless of argument order, so
        // it is added up front for both the Windows (snapshot) and Linux
        // (cold-boot) invocations below. Verified to work on warm-start
        // snapshot restore as well as cold boot.
        if host_networking {
            cmd.arg("-allow-host-networking");
        }

        // Per-host egress filtering. The supplied lists have already been
        // reduced to the one that refines the shared legacy default. NanVix
        // rejects simultaneous lists during validation, so at most one loop
        // emits flags. The guest daemon auto-exempts the DNS port in allowlist
        // mode, so no resolver IPs are added here.
        for host in allow_hosts {
            cmd.arg("-allow-host").arg(host);
        }
        for host in block_hosts {
            cmd.arg("-block-host").arg(host);
        }

        #[cfg(target_os = "windows")]
        {
            // nanvixd loads kernel.vmem from <cwd>/snapshots/ so cwd must be
            // the snapshot home. All other paths are passed as absolute.
            //   nanvixd.exe [-allow-host-networking] -snapshot snapshots/kernel.whp.cbor
            //              -bin-dir <exe>/bin -ramfs <img> -mount <staging> -- python3.initrd
            let snapshot_rel = Path::new(SNAPSHOTS_DIR).join(SNAPSHOT_CBOR);
            cmd.current_dir(&paths.snapshot_home)
                .arg("-snapshot")
                .arg(&snapshot_rel)
                .arg("-bin-dir")
                .arg(paths.exe_dir.join(BIN_DIR))
                .arg("-ramfs")
                .arg(&paths.ramfs)
                .arg("-mount")
                .arg(staging_dir)
                .arg("--")
                .arg(&paths.initrd);
        }

        #[cfg(target_os = "linux")]
        {
            // Linux invocation (cold boot via KVM):
            //   nanvixd.elf [-allow-host-networking] -ramfs <rootfs.img> -mount <staging_dir> -- python3.initrd
            cmd.current_dir(&paths.exe_dir)
                .arg("-ramfs")
                .arg(&paths.ramfs)
                .arg("-mount")
                .arg(staging_dir)
                .arg("--")
                .arg(&paths.initrd);
        }

        cmd.stdin(Stdio::null())
            .stdout(Stdio::inherit())
            .stderr(stderr);
        if !trace {
            // Suppress nanvixd's env_logger output and per-run log file.
            cmd.env("RUST_LOG", "off");
        }
        Ok(cmd)
    }

    fn spawn_nanvixd(
        paths: &ResolvedPaths,
        staging_dir: &Path,
        request: &ExecutionRequest,
        allow_hosts: &[String],
        block_hosts: &[String],
    ) -> Result<std::process::Child, NanVixError> {
        Self::nanvixd_command(paths, staging_dir, request, allow_hosts, block_hosts)?
            .spawn()
            .map_err(|e| {
                NanVixError::Platform(format!("failed to spawn {}: {}", NANVIXD_BINARY, e))
            })
    }

    fn start_watchdog(
        child: &std::process::Child,
        timeout_ms: u64,
        cancel_pair: Arc<(Mutex<bool>, Condvar)>,
        timed_out: Arc<AtomicBool>,
    ) -> Option<thread::JoinHandle<()>> {
        if timeout_ms == u64::MAX {
            return None;
        }

        let duration = Duration::from_millis(timeout_ms);

        #[cfg(target_os = "windows")]
        {
            // Duplicate the process handle at spawn time (safe against PID reuse).
            use std::os::windows::io::AsRawHandle;
            use windows::Win32::Foundation::{DuplicateHandle, DUPLICATE_SAME_ACCESS, HANDLE};
            use windows::Win32::System::Threading::GetCurrentProcess;

            let raw = child.as_raw_handle();
            let mut dup_handle = HANDLE::default();
            let dup_ok = unsafe {
                // SAFETY: `raw` is the live process HANDLE from `std::process::Child`.
                // We duplicate it into the current process with same access rights so
                // the watchdog thread can safely terminate/close it independently.
                DuplicateHandle(
                    GetCurrentProcess(),
                    HANDLE(raw),
                    GetCurrentProcess(),
                    &mut dup_handle,
                    0,
                    false,
                    DUPLICATE_SAME_ACCESS,
                )
            };
            if dup_ok.is_err() {
                return None;
            }
            let process_id_or_handle = dup_handle.0 as usize;

            Some(thread::spawn(move || {
                watchdog_thread_fn(process_id_or_handle, duration, cancel_pair, timed_out);
            }))
        }

        #[cfg(target_os = "linux")]
        {
            // On Linux, use the child PID directly for kill-based termination.
            let pid = child.id() as usize;

            Some(thread::spawn(move || {
                watchdog_thread_fn(pid, duration, cancel_pair, timed_out);
            }))
        }
    }

    fn setup_watchdog(
        child: &mut std::process::Child,
        timeout_ms: u64,
        logger: &mut Logger,
    ) -> Result<WatchdogState, ScriptResponse> {
        let timed_out = Arc::new(AtomicBool::new(false));
        let cancel_pair = Arc::new((Mutex::new(false), Condvar::new()));

        let watchdog = if timeout_ms < u64::MAX {
            match Self::start_watchdog(
                child,
                timeout_ms,
                Arc::clone(&cancel_pair),
                Arc::clone(&timed_out),
            ) {
                Some(handle) => Some(handle),
                None => {
                    let err = NanVixError::Platform(format!(
                        "failed to duplicate {} process handle",
                        NANVIXD_BINARY
                    ));
                    let _ = writeln!(logger, "{}", err);
                    if let Err(e) = child.kill() {
                        let _ = writeln!(
                            logger,
                            "NanVix: failed to kill child after handle dup failure: {}",
                            e
                        );
                    }
                    if let Err(e) = child.wait() {
                        let _ = writeln!(
                            logger,
                            "NanVix: failed to wait for child after handle dup failure: {}",
                            e
                        );
                    }
                    return Err(err.to_response());
                }
            }
        } else {
            None
        };

        Ok((watchdog, cancel_pair, timed_out))
    }

    fn log_resolved_paths(logger: &mut Logger, paths: &ResolvedPaths) {
        let _ = writeln!(logger, "NanVix: nanvixd={:?}", paths.nanvixd);
        let _ = writeln!(logger, "NanVix: ramfs={:?}", paths.ramfs);
        let _ = writeln!(logger, "NanVix: initrd={:?}", paths.initrd);
        let _ = writeln!(logger, "NanVix: snapshot_home={:?}", paths.snapshot_home);
    }

    fn wait_and_respond(
        child: &mut Child,
        watchdog: Option<JoinHandle<()>>,
        cancel_pair: &Arc<(Mutex<bool>, Condvar)>,
        timed_out: &AtomicBool,
        timeout_ms: u64,
        script_timeout: u32,
        logger: &mut Logger,
    ) -> ScriptResponse {
        // Drain stderr concurrently with `wait()` so a verbose child cannot
        // block on a full pipe buffer. We retain only the last
        // [`crate::nanvix_common::STDERR_TAIL_BYTES`] bytes so an untrusted guest
        // emitting unbounded stderr cannot cause host memory growth
        // (availability / DoS hardening). In the default (non-trace) mode
        // stderr is inherited and `child.stderr` is `None`, so the join
        // returns the empty string immediately.
        let stderr_handle = child
            .stderr
            .take()
            .map(|s| thread::spawn(move || crate::nanvix_common::drain_stderr_tail(s)));

        let exit_status = child.wait();

        let stderr_output = stderr_handle
            .and_then(|h| h.join().ok())
            .map(|(bytes, truncated)| crate::nanvix_common::format_stderr_tail(&bytes, truncated))
            .unwrap_or_default();

        {
            let (lock, cvar) = &**cancel_pair;
            let mut cancelled = lock.lock().unwrap_or_else(|e| e.into_inner());
            *cancelled = true;
            cvar.notify_one();
        }

        if let Some(handle) = watchdog {
            let _ = handle.join();
        }

        if timed_out.load(Ordering::SeqCst) {
            let _ = child.kill();
            let err = NanVixError::Timeout {
                script_timeout_ms: script_timeout,
                total_ms: timeout_ms,
            };
            let _ = writeln!(logger, "{}", err);
            return err.to_response();
        }

        match exit_status {
            Ok(status) => {
                let exit_code = exit_code_from_status(&status);
                let _ = writeln!(logger, "NanVix: process exited with code {}", exit_code);
                if exit_code != 0 && !stderr_output.is_empty() {
                    let _ = writeln!(logger, "NanVix stderr:\n{}", stderr_output);
                }
                ScriptResponse {
                    exit_code,
                    ..Default::default()
                }
            }
            Err(e) => {
                if !stderr_output.is_empty() {
                    let _ = writeln!(logger, "NanVix stderr:\n{}", stderr_output);
                }
                let err =
                    NanVixError::Runtime(format!("failed to wait for {}: {}", NANVIXD_BINARY, e));
                let _ = writeln!(logger, "{}", err);
                err.to_response()
            }
        }
    }
    /// Returns `true` when filesystem copyback should run.
    /// Copyback runs on any normal process exit (including non-zero exit codes).
    /// It is skipped for preflight, spawn, runtime, and timeout errors, and for
    /// OS crashes (negative exit codes from NTSTATUS values).
    fn should_copy_back(response: &ScriptResponse) -> bool {
        response.error_message.is_empty() && response.exit_code >= 0
    }
}

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

    fn execute(&mut self, request: &ExecutionRequest, logger: &mut Logger) -> ScriptResponse {
        let host_networking = match Self::resolve_networking_mode(request) {
            Ok(enabled) => enabled,
            Err(error) => return error.to_response(),
        };
        let paths = match self.resolve_paths() {
            Ok(p) => p,
            Err(e) => return e.to_response(),
        };

        // Build staging directory with script and filesystem policy paths.
        let staging_root = std::env::temp_dir().join("mxc-microvm");
        // Sweep orphaned staging dirs from previous crashed runs (older than 1 hour).
        crate::mxc_common::microvm_staging::sweep_orphaned_staging_dirs(
            &staging_root,
            std::time::Duration::from_secs(ORPHAN_SWEEP_MAX_AGE_SECS),
        );
        let mut staging = match crate::mxc_common::microvm_staging::StagingDir::new(
            staging_root,
            &request.script_code,
            &request.policy.readwrite_paths,
            &request.policy.readonly_paths,
        ) {
            Ok(s) => s,
            Err(e) => {
                let err = NanVixError::Preflight(e.to_string());
                let _ = writeln!(logger, "{}", err);
                return err.to_response();
            }
        };

        Self::log_resolved_paths(logger, &paths);
        let _ = writeln!(logger, "NanVix: staging_dir={:?}", staging.path());

        if host_networking {
            let _ = writeln!(logger, "NanVix: host networking enabled");
        }
        let (allow_hosts, block_hosts) = match Self::resolve_host_lists(request) {
            Ok(resolved) => {
                for warning in &resolved.warnings {
                    let _ = writeln!(logger, "NanVix: {}", warning);
                }
                (resolved.allow, resolved.block)
            }
            Err(e) => {
                let _ = writeln!(logger, "{}", e);
                return e.to_response();
            }
        };
        if !allow_hosts.is_empty() {
            let _ = writeln!(logger, "NanVix: egress allowlist={:?}", allow_hosts);
        }
        if !block_hosts.is_empty() {
            let _ = writeln!(logger, "NanVix: egress blocklist={:?}", block_hosts);
        }
        let mut child = match Self::spawn_nanvixd(
            &paths,
            staging.path(),
            request,
            &allow_hosts,
            &block_hosts,
        ) {
            Ok(c) => c,
            Err(e) => {
                let _ = writeln!(logger, "{}", e);
                return e.to_response();
            }
        };

        let staging_overhead = staging.staging_overhead_ms();
        let timeout_ms = Self::total_timeout_ms(request.script_timeout, staging_overhead);
        let (watchdog, cancel_pair, timed_out) =
            match Self::setup_watchdog(&mut child, timeout_ms, logger) {
                Ok(v) => v,
                Err(resp) => return resp,
            };

        let response = Self::wait_and_respond(
            &mut child,
            watchdog,
            &cancel_pair,
            timed_out.as_ref(),
            timeout_ms,
            request.script_timeout,
            logger,
        );

        // Copy back RW filesystem changes on normal process exit.
        if Self::should_copy_back(&response) {
            if let Err(e) = staging.copy_back_to_host() {
                let preserved = staging
                    .preserved_path()
                    .map(|p| p.display().to_string())
                    .unwrap_or_default();
                let err = NanVixError::Runtime(format!(
                    "failed to copy back microvm filesystem changes: {}. \
                     Staged files preserved at: {}",
                    e, preserved
                ));
                let _ = writeln!(logger, "{}", err);
                return err.to_response();
            }
        }

        response
        // staging is dropped here → cleanup
    }
}

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

    #[test]
    fn total_timeout_adds_boot_staging_and_script() {
        // script_timeout=0 => infinite script timeout sentinel.
        assert_eq!(NanVixScriptRunner::total_timeout_ms(0, 0), u64::MAX);
        // script_timeout=30000, staging_overhead=500 -> 30s + 500ms + 60s boot = 90.5s
        assert_eq!(NanVixScriptRunner::total_timeout_ms(30_000, 500), 90_500);
        // script_timeout=30000, no staging -> 30s + 60s boot = 90s
        assert_eq!(NanVixScriptRunner::total_timeout_ms(30_000, 0), 90_000);
    }

    #[test]
    fn resolve_paths_fails_when_exe_dir_has_no_binaries() {
        let runner = NanVixScriptRunner::new();
        let err = runner.resolve_paths().unwrap_err();
        assert!(err.to_string().contains("not found"), "got: {}", err);
    }

    // -- Policy validation tests -------------------------------------------------

    fn directional_request(
        egress: NetworkAction,
        ingress: NetworkAction,
        host_loopback: NetworkAction,
    ) -> ExecutionRequest {
        ExecutionRequest {
            policy: ContainerPolicy {
                network_egress: Some(crate::mxc_common::models::NetworkEgressPolicy {
                    default: egress,
                    allow: Vec::new(),
                    deny: Vec::new(),
                }),
                network_ingress: Some(crate::mxc_common::models::NetworkIngressPolicy {
                    default: ingress,
                    host_loopback,
                }),
                network_specified: true,
                network_mode_specified: true,
                ..Default::default()
            },
            ..Default::default()
        }
    }

    fn command_arguments(
        request: &ExecutionRequest,
        allow_hosts: &[String],
        block_hosts: &[String],
    ) -> Result<Vec<String>, NanVixError> {
        let root = PathBuf::from("nanvix-command-test");
        let paths = ResolvedPaths {
            nanvixd: root.join(NANVIXD_BINARY),
            ramfs: root.join("rootfs.img"),
            initrd: root.join("python3.initrd"),
            exe_dir: root.clone(),
            snapshot_home: root,
        };
        let command = NanVixScriptRunner::nanvixd_command(
            &paths,
            Path::new("staging"),
            request,
            allow_hosts,
            block_hosts,
        )?;
        Ok(command
            .get_args()
            .map(|argument| argument.to_string_lossy().into_owned())
            .collect())
    }

    #[test]
    fn directional_networking_requires_a_coherent_explicit_posture() {
        let runner = NanVixScriptRunner::new();
        for egress in [NetworkAction::Deny, NetworkAction::Allow] {
            for ingress in [NetworkAction::Deny, NetworkAction::Allow] {
                for host_loopback in [NetworkAction::Deny, NetworkAction::Allow] {
                    let request = directional_request(egress, ingress, host_loopback);
                    if egress == ingress && ingress == host_loopback {
                        runner.validate_runner(&request).unwrap();
                        assert_eq!(
                            NanVixScriptRunner::resolve_networking_mode(&request).unwrap(),
                            egress == NetworkAction::Allow
                        );
                        let arguments = command_arguments(&request, &[], &[]).unwrap();
                        assert_eq!(
                            arguments
                                .iter()
                                .filter(|arg| *arg == "-allow-host-networking")
                                .count(),
                            usize::from(egress == NetworkAction::Allow)
                        );
                    } else {
                        let error = runner.validate_runner(&request).unwrap_err();
                        assert!(error.error_message.contains(ERR_DIRECTIONAL_NETWORK));
                        assert!(command_arguments(&request, &[], &[]).is_err());
                    }
                }
            }
        }
    }

    #[test]
    fn directional_egress_allow_does_not_implicitly_allow_ingress() {
        let mut request = directional_request(
            NetworkAction::Allow,
            NetworkAction::Allow,
            NetworkAction::Allow,
        );
        request.policy.network_ingress = None;
        assert!(NanVixScriptRunner::resolve_networking_mode(&request).is_err());
    }

    #[test]
    fn directional_filter_requests_are_rejected_before_execution() {
        for rules in ["allow", "deny"] {
            let source = format!(
                r#"{{"version":"1.1.0-alpha","containment":"microvm",
                    "process":{{"commandLine":"print(1)"}},
                    "network":{{"egress":{{"default":"allow","{rules}":[{{"to":[{{"cidr":"203.0.113.0/24"}}]}}]}},
                               "ingress":{{"default":"allow","hostLoopback":"allow"}}}}}}"#
            );
            let mut logger = Logger::new(Mode::Buffer);
            let parsed =
                crate::mxc_common::config_parser::load_mxc_request_from_json(&source, &mut logger)
                    .unwrap();
            let crate::mxc_common::state_aware_request::MxcRequest::OneShot(request) = parsed
            else {
                panic!("expected one-shot");
            };
            let error = NanVixScriptRunner::new()
                .validate_runner(&request)
                .unwrap_err();
            assert!(
                error.error_message.contains(ERR_DIRECTIONAL_FILTERS),
                "unexpected validation error: {}",
                error.error_message
            );
            assert!(command_arguments(&request, &[], &[]).is_err());
        }
    }

    #[test]
    fn public_directional_fixtures_enable_host_networking() {
        for source in [
            include_str!("../../../../../../tests/configs/microvm_network.json"),
            include_str!("../../../../../../tests/configs/microvm_network_linux.json"),
        ] {
            let mut logger = Logger::new(Mode::Buffer);
            let parsed =
                crate::mxc_common::config_parser::load_mxc_request_from_json(source, &mut logger)
                    .unwrap();
            let crate::mxc_common::state_aware_request::MxcRequest::OneShot(request) = parsed
            else {
                panic!("expected one-shot");
            };
            NanVixScriptRunner::new().validate_runner(&request).unwrap();
            assert!(NanVixScriptRunner::resolve_networking_mode(&request).unwrap());
            let arguments = command_arguments(&request, &[], &[]).unwrap();
            assert_eq!(
                arguments.first().map(String::as_str),
                Some("-allow-host-networking")
            );
            assert!(!arguments
                .iter()
                .any(|arg| arg == "-allow-host" || arg == "-block-host"));
        }
    }

    #[test]
    fn command_arguments_preserve_network_defaults_and_host_filters() {
        for (default, allow, block, expected_prefix) in [
            (NetworkPolicy::Block, vec![], vec![], vec![]),
            (
                NetworkPolicy::Allow,
                vec![],
                vec![],
                vec!["-allow-host-networking"],
            ),
            (
                NetworkPolicy::Block,
                vec!["192.0.2.1"],
                vec![],
                vec!["-allow-host-networking", "-allow-host", "192.0.2.1"],
            ),
            (
                NetworkPolicy::Allow,
                vec![],
                vec!["192.0.2.0/24"],
                vec!["-allow-host-networking", "-block-host", "192.0.2.0/24"],
            ),
        ] {
            let request = ExecutionRequest {
                policy: ContainerPolicy {
                    default_network_policy: default,
                    allowed_hosts: allow.into_iter().map(str::to_owned).collect(),
                    blocked_hosts: block.into_iter().map(str::to_owned).collect(),
                    ..Default::default()
                },
                ..Default::default()
            };
            let resolved = NanVixScriptRunner::resolve_host_lists(&request).unwrap();
            let arguments = command_arguments(&request, &resolved.allow, &resolved.block).unwrap();
            let expected: Vec<String> = expected_prefix.into_iter().map(str::to_owned).collect();
            assert!(arguments.starts_with(&expected), "{arguments:?}");
            assert_eq!(
                arguments.iter().any(|arg| arg == "-allow-host-networking"),
                !expected.is_empty(),
                "{arguments:?}"
            );
        }
    }

    #[test]
    fn policy_accepts_readwrite_paths() {
        // Validation passes; the runner fails later on path resolution.
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                readwrite_paths: vec!["/tmp".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let result = NanVixScriptRunner::validate_policies(&request);
        assert!(result.is_ok(), "readwrite_paths accepted");
    }

    #[test]
    fn policy_accepts_readonly_paths() {
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                readonly_paths: vec!["/data".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let result = NanVixScriptRunner::validate_policies(&request);
        assert!(result.is_ok(), "readonly_paths accepted");
    }

    #[test]
    fn policy_rejects_denied_paths() {
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                denied_paths: vec!["/secret".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let result = NanVixScriptRunner::validate_policies(&request);
        assert!(result.is_err(), "denied_paths should be rejected");
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains(ERR_DENIED_PATHS),
            "expected denied_paths error, got: {}",
            err
        );
    }

    #[test]
    fn policy_accepts_allowlist_only() {
        // A bare allowlist is now supported (forwarded as -allow-host).
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                allowed_hosts: vec!["93.184.216.34".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(
            NanVixScriptRunner::validate_policies(&request).is_ok(),
            "a bare allowlist should pass validation"
        );
    }

    #[test]
    fn policy_rejects_blocklist_without_allowlist_under_block_default() {
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                blocked_hosts: vec!["93.184.216.34".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let error = NanVixScriptRunner::new()
            .validate_runner(&request)
            .unwrap_err();
        assert_eq!(
            error.error_message,
            "blockedHosts requires allowedHosts when network.defaultPolicy='block'"
        );
    }

    #[test]
    fn policy_rejects_both_host_lists() {
        // allow + block are mutually exclusive (the guest filter is allow-XOR-block).
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                allowed_hosts: vec!["10.0.0.1".to_string()],
                blocked_hosts: vec!["10.0.0.2".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = NanVixScriptRunner::validate_policies(&request).unwrap_err();
        assert!(
            err.to_string().contains(ERR_NETWORK_HOSTS),
            "both lists should be rejected, got: {}",
            err
        );
    }

    // -- Host resolution / decision-matrix tests --------------------------------

    #[test]
    fn resolve_hosts_passes_ipv4_and_cidr_literals() {
        let hosts = vec![
            "1.2.3.4".to_string(),
            "10.0.0.0/8".to_string(),
            "192.168.1.1/32".to_string(),
        ];
        let (resolved, unresolved) = NanVixScriptRunner::resolve_hosts_detailed(&hosts);
        assert_eq!(resolved, vec!["1.2.3.4", "10.0.0.0/8", "192.168.1.1/32"]);
        assert!(unresolved.is_empty());
    }

    #[test]
    fn resolve_hosts_drops_ipv6_and_bad_entries() {
        let hosts = vec![
            "::1".to_string(),           // IPv6 literal -> dropped
            "2001:db8::/32".to_string(), // IPv6 CIDR -> dropped (addr not IPv4)
            "1.2.3.4/33".to_string(),    // out-of-range prefix -> dropped
            "  ".to_string(),            // blank -> skipped
            "5.6.7.8".to_string(),       // valid -> kept
        ];
        let (resolved, _) = NanVixScriptRunner::resolve_hosts_detailed(&hosts);
        assert_eq!(resolved, vec!["5.6.7.8"]);
    }

    #[test]
    fn resolve_host_lists_returns_resolved_allow() {
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                allowed_hosts: vec!["1.1.1.1".to_string(), "8.8.8.8/32".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let resolved = NanVixScriptRunner::resolve_host_lists(&request).unwrap();
        assert_eq!(resolved.allow, vec!["1.1.1.1", "8.8.8.8/32"]);
        assert!(resolved.block.is_empty());
        assert!(resolved.warnings.is_empty());
    }

    #[test]
    fn resolve_host_lists_fails_closed_when_allowlist_unresolvable() {
        // A non-empty allowlist that resolves to nothing must error rather than
        // silently fall through to allow-all.
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                // IPv6-only literal resolves to no IPv4 entry.
                allowed_hosts: vec!["::1".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = NanVixScriptRunner::resolve_host_lists(&request).unwrap_err();
        assert!(
            err.to_string().contains(ERR_HOSTS_UNRESOLVED),
            "unresolvable allowlist should fail closed, got: {}",
            err
        );
    }

    #[test]
    fn resolve_hosts_detailed_reports_unresolved_entries() {
        // IPv4/CIDR pass through; IPv6 + malformed entries are reported as
        // unresolved; blanks are ignored entirely.
        let hosts = vec![
            "5.6.7.8".to_string(),            // valid -> kept
            "::1".to_string(),                // IPv6 literal -> unresolved
            "2001:db8::/32".to_string(),      // IPv6 CIDR -> unresolved
            "1.2.3.4/33".to_string(),         // out-of-range prefix -> unresolved
            "not_a_host.invalid".to_string(), // no A record -> unresolved
            "  ".to_string(),                 // blank -> ignored (neither list)
        ];
        let (resolved, unresolved) = NanVixScriptRunner::resolve_hosts_detailed(&hosts);
        assert_eq!(resolved, vec!["5.6.7.8"]);
        assert_eq!(
            unresolved,
            vec!["::1", "2001:db8::/32", "1.2.3.4/33", "not_a_host.invalid"]
        );
    }

    #[test]
    fn resolve_host_lists_warns_on_dropped_allowlist_entries() {
        // A partially-resolvable allowlist narrows access (fail-safe): the run
        // continues and each dropped entry produces a warning.
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                allowed_hosts: vec![
                    "9.9.9.9".to_string(),
                    "::1".to_string(),
                    "dropme.invalid".to_string(),
                ],
                ..Default::default()
            },
            ..Default::default()
        };
        let resolved = NanVixScriptRunner::resolve_host_lists(&request).unwrap();
        assert_eq!(resolved.allow, vec!["9.9.9.9"]);
        assert!(resolved.block.is_empty());
        assert_eq!(resolved.warnings.len(), 2, "two entries were dropped");
        assert!(resolved.warnings.iter().any(|w| w.contains("::1")));
        assert!(resolved
            .warnings
            .iter()
            .any(|w| w.contains("dropme.invalid")));
    }

    #[test]
    fn resolve_host_lists_fails_closed_on_unresolvable_blocklist_entry() {
        // A blocklist (allow-by-default) must fail closed if ANY entry cannot
        // be resolved -- silently dropping it would let blocked traffic flow.
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                default_network_policy: NetworkPolicy::Allow,
                blocked_hosts: vec!["10.0.0.1".to_string(), "::1".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let err = NanVixScriptRunner::resolve_host_lists(&request).unwrap_err();
        assert!(
            err.to_string().contains(ERR_BLOCKED_HOST_UNRESOLVED),
            "unresolvable blocklist entry should fail closed, got: {}",
            err
        );
        assert!(
            err.to_string().contains("::1"),
            "error should name the offending entry, got: {}",
            err
        );
    }

    #[test]
    fn resolve_host_lists_accepts_fully_resolved_blocklist() {
        let request = ExecutionRequest {
            policy: ContainerPolicy {
                default_network_policy: NetworkPolicy::Allow,
                blocked_hosts: vec!["10.0.0.1".to_string(), "192.168.0.0/16".to_string()],
                ..Default::default()
            },
            ..Default::default()
        };
        let resolved = NanVixScriptRunner::resolve_host_lists(&request).unwrap();
        assert!(resolved.allow.is_empty());
        assert_eq!(resolved.block, vec!["10.0.0.1", "192.168.0.0/16"]);
        assert!(resolved.warnings.is_empty());
    }

    #[test]
    fn default_block_no_lists_disables_host_networking() {
        // The default posture (block, no lists) keeps networking off.
        let request = ExecutionRequest::default();
        assert!(!NanVixScriptRunner::resolve_networking_mode(&request).unwrap());
        let resolved = NanVixScriptRunner::resolve_host_lists(&request).unwrap();
        assert!(resolved.allow.is_empty() && resolved.block.is_empty());
        assert!(resolved.warnings.is_empty());
    }

    #[test]
    fn allow_policy_enables_host_networking() {
        // `network.defaultPolicy = "allow"` maps to host networking and must
        // pass validation (the run later fails on missing nanvixd binaries,
        // not on policy). Per-host filtering is absent, so it is accepted.
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                default_network_policy: NetworkPolicy::Allow,
                ..Default::default()
            },
            ..Default::default()
        };
        assert!(NanVixScriptRunner::resolve_networking_mode(&request).unwrap());
        assert!(
            NanVixScriptRunner::validate_policies(&request).is_ok(),
            "allow posture without per-host filtering should pass validation"
        );

        let mut runner = NanVixScriptRunner::new();
        let mut logger = Logger::new(Mode::Buffer);
        let resp = runner.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert!(
            !resp.error_message.contains(ERR_NETWORK_HOSTS),
            "allow posture must not trigger a network policy rejection, got: {}",
            resp.error_message
        );
    }

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

    #[test]
    fn policy_allows_defaults() {
        // NanVix accepts a default (deny-by-default) policy. With no host
        // networking requested, the run later fails on missing nanvixd
        // binaries, not on policy.
        let mut runner = NanVixScriptRunner::new();
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            ..Default::default()
        };
        assert!(!NanVixScriptRunner::resolve_networking_mode(&request).unwrap());
        let mut logger = Logger::new(Mode::Buffer);
        let resp = runner.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert!(
            !resp.error_message.contains(ERR_NETWORK_HOSTS),
            "default request should not trigger network policy rejection"
        );
        assert!(
            !resp.error_message.contains(ERR_WORKDIR),
            "default request should not trigger workingDirectory rejection"
        );
    }

    #[test]
    fn policy_rejects_network_proxy() {
        let mut runner = NanVixScriptRunner::new();
        let request = ExecutionRequest {
            script_code: "echo test".to_string(),
            policy: ContainerPolicy {
                network_proxy: crate::mxc_common::models::ProxyConfig {
                    address: Some(crate::mxc_common::models::ProxyAddress::new(
                        "127.0.0.1".to_string(),
                        8080,
                    )),
                    builtin_test_server: false,
                },
                ..Default::default()
            },
            ..Default::default()
        };
        let mut logger = Logger::new(Mode::Buffer);
        let resp = runner.run(&request, &mut logger);
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert!(resp.error_message.contains(ERR_PROXY_POLICY));
    }

    #[test]
    fn resolve_paths_checks_for_snapshot() {
        let runner = NanVixScriptRunner::new();
        let err = runner.resolve_paths().unwrap_err();
        // Should fail on missing binaries (not on snapshot specifically,
        // since nanvixd.exe is checked first).
        assert!(err.to_string().contains("not found"), "got: {}", err);
    }

    // -- Copyback decision tests ------------------------------------------------

    #[test]
    fn copyback_allowed_for_zero_exit() {
        let response = ScriptResponse {
            exit_code: 0,
            ..Default::default()
        };
        assert!(NanVixScriptRunner::should_copy_back(&response));
    }

    #[test]
    fn copyback_allowed_for_nonzero_normal_exit() {
        let response = ScriptResponse {
            exit_code: 42,
            ..Default::default()
        };
        assert!(NanVixScriptRunner::should_copy_back(&response));
    }

    #[test]
    fn copyback_skipped_for_runner_error() {
        let response = ScriptResponse {
            exit_code: ERROR_EXIT_CODE,
            error_message: "NanVix execution timed out after 90000ms".to_string(),
            ..Default::default()
        };
        assert!(!NanVixScriptRunner::should_copy_back(&response));
    }

    #[test]
    fn copyback_skipped_for_os_crash() {
        // STATUS_ACCESS_VIOLATION = 0xC0000005 → interpreted as i32 = -1073741819.
        // This is a nanvixd OS crash — copyback must be suppressed.
        let response = ScriptResponse {
            exit_code: -1073741819_i32,
            error_message: String::new(),
            ..Default::default()
        };
        assert!(
            !NanVixScriptRunner::should_copy_back(&response),
            "copyback must be skipped for NTSTATUS crash exit codes"
        );
    }

    #[test]
    fn copyback_skipped_for_signal_killed() {
        // On Linux, SIGKILL results in exit code -9 (negative signal number).
        let response = ScriptResponse {
            exit_code: -9,
            error_message: String::new(),
            ..Default::default()
        };
        assert!(
            !NanVixScriptRunner::should_copy_back(&response),
            "copyback must be skipped for signal-killed processes"
        );
    }

    // -- Platform-specific constant tests ---------------------------------------

    #[test]
    fn nanvixd_binary_matches_platform() {
        #[cfg(target_os = "linux")]
        assert_eq!(NANVIXD_BINARY, "nanvixd.elf");
        #[cfg(target_os = "windows")]
        assert_eq!(NANVIXD_BINARY, "nanvixd.exe");
    }

    #[test]
    fn total_timeout_infinite_when_zero() {
        assert_eq!(NanVixScriptRunner::total_timeout_ms(0, 0), u64::MAX);
        assert_eq!(NanVixScriptRunner::total_timeout_ms(0, 500), u64::MAX);
    }

    #[test]
    fn total_timeout_saturates_on_overflow() {
        // With values that would cause u64 overflow, should saturate at u64::MAX.
        let result = NanVixScriptRunner::total_timeout_ms(u32::MAX, u64::MAX - 1);
        assert_eq!(result, u64::MAX);
    }

    // -- Watchdog timeout state tests ------------------------------------------

    #[test]
    fn watchdog_state_no_thread_when_infinite_timeout() {
        // When timeout is u64::MAX, start_watchdog should return None.
        // We can't test this directly without a real child process, but we can
        // verify the total_timeout_ms sentinel logic.
        let timeout = NanVixScriptRunner::total_timeout_ms(0, 0);
        assert_eq!(
            timeout,
            u64::MAX,
            "zero script_timeout should yield infinite"
        );
    }

    // -- NanVixError display tests ---------------------------------------------

    #[test]
    fn error_display_preflight() {
        let err = NanVixError::Preflight("missing binary".to_string());
        assert!(err.to_string().contains("preflight"));
        assert!(err.to_string().contains("missing binary"));
    }

    #[test]
    fn error_display_platform() {
        let err = NanVixError::Platform("spawn failed".to_string());
        assert!(err.to_string().contains("platform"));
        assert!(err.to_string().contains("spawn failed"));
    }

    #[test]
    fn error_display_runtime() {
        let err = NanVixError::Runtime("VM crashed".to_string());
        assert!(err.to_string().contains("runtime"));
        assert!(err.to_string().contains("VM crashed"));
    }

    #[test]
    fn error_display_timeout() {
        let err = NanVixError::Timeout {
            script_timeout_ms: 5000,
            total_ms: 65000,
        };
        let msg = err.to_string();
        assert!(msg.contains("timed out"));
        assert!(msg.contains("65000"));
        assert!(msg.contains("5000"));
    }

    #[test]
    fn error_to_response_has_error_exit_code() {
        let err = NanVixError::Preflight("test".to_string());
        let resp = err.to_response();
        assert_eq!(resp.exit_code, ERROR_EXIT_CODE);
        assert!(!resp.error_message.is_empty());
    }
}