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

use serde::{Deserialize, Serialize};
use std::net::IpAddr;

use crate::mxc_common::error::WxcError;
use crate::mxc_common::mxc_error::MxcErrorCode;

/// Selects which containment backend to use for script execution.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ContainmentBackend {
    #[default]
    /// Windows process-level containment using native PSEC. The schema version
    /// does not influence native contract selection.
    /// Selected on the wire as `"processcontainer"`.
    ProcessContainer,
    /// Linux container via WSL Container SDK (WSLC SDK).
    Wslc,
    /// LXC — Linux container isolation.
    Lxc,
    /// VM-based isolation.
    Vm,
    /// MicroVM isolation via Windows Hypervisor Platform (internally powered by NanVix).
    #[serde(rename = "microvm")]
    MicroVm,
    /// MicroVM isolation via Hyperlight + Unikraft, using an embedded
    /// warmed-up CPython snapshot. ~100 ms cold start per invocation,
    /// hermetic via snapshot restore. Experimental — requires
    /// --experimental. Cross-platform (Linux KVM, Windows WHP).
    Hyperlight,
    /// Windows Sandbox — full VM isolation (experimental, requires --experimental flag).
    WindowsSandbox,
    /// Isolation Session — process isolation via the IsolationSession API.
    #[serde(rename = "isolation_session")]
    IsolationSession,
    /// macOS Seatbelt sandbox backend.
    /// Implemented on top of the OS-bundled sandbox facility (Apple's
    /// internal codename for the App Sandbox / `sandbox_init` machinery
    /// is "Seatbelt"); selected on the wire as `"seatbelt"`.
    Seatbelt,
    /// Bubblewrap — unprivileged Linux sandboxing via user namespaces.
    /// Uses `bwrap` to create namespace-isolated processes without root
    /// privileges. Selected on the wire as `"bubblewrap"`.
    Bubblewrap,
    /// Experimental remote Windows 365 checkout lifecycle.
    #[serde(rename = "w365_agents")]
    W365Agents,
}

impl ContainmentBackend {
    /// Canonical wire string matching the JSON schema `containment` enum.
    pub fn wire_name(&self) -> &'static str {
        match self {
            ContainmentBackend::ProcessContainer => "processcontainer",
            ContainmentBackend::Wslc => "wslc",
            ContainmentBackend::Lxc => "lxc",
            ContainmentBackend::Vm => "vm",
            ContainmentBackend::MicroVm => "microvm",
            ContainmentBackend::Hyperlight => "hyperlight",
            ContainmentBackend::WindowsSandbox => "windows_sandbox",
            ContainmentBackend::IsolationSession => "isolation_session",
            ContainmentBackend::Seatbelt => "seatbelt",
            ContainmentBackend::Bubblewrap => "bubblewrap",
            ContainmentBackend::W365Agents => "w365_agents",
        }
    }

    /// JSON path of this backend's per-backend config section, if any.
    /// Backends without a section return `None` and reject any backend
    /// section paired with them.
    pub fn section_path(&self) -> Option<&'static str> {
        match self {
            ContainmentBackend::ProcessContainer => Some("processContainer"),
            ContainmentBackend::Lxc => Some("lxc"),
            ContainmentBackend::WindowsSandbox => Some("windowsSandbox"),
            ContainmentBackend::Wslc => Some("wslc"),
            ContainmentBackend::Seatbelt => Some("seatbelt"),
            ContainmentBackend::IsolationSession => Some("isolationSession"),
            ContainmentBackend::Hyperlight => Some("hyperlight"),
            ContainmentBackend::W365Agents => Some("w365Agents"),
            ContainmentBackend::Bubblewrap
            | ContainmentBackend::MicroVm
            | ContainmentBackend::Vm => None,
        }
    }
}

impl From<crate::mxc_common::wire::Containment> for ContainmentBackend {
    /// Resolve a `containment` wire value to a concrete domain backend.
    ///
    /// The abstract intents resolve per host: `process` → the OS-native process
    /// sandbox, `vm` → the host's VM-class backend. Concrete backends map
    /// verbatim. Deprecated spellings (`appcontainer`, `macos_sandbox`) are
    /// normalized before this conversion, either by exact-contract
    /// deserialization or by explicit internal string classification through
    /// `wire::Containment::parse_wire_name`.
    fn from(c: crate::mxc_common::wire::Containment) -> Self {
        use crate::mxc_common::wire::Containment as W;
        match c {
            W::Process => {
                #[cfg(target_os = "linux")]
                {
                    Self::Bubblewrap
                }
                #[cfg(target_os = "macos")]
                {
                    Self::Seatbelt
                }
                #[cfg(not(any(target_os = "linux", target_os = "macos")))]
                {
                    Self::ProcessContainer
                }
            }
            W::ProcessContainer => Self::ProcessContainer,
            W::Vm => {
                #[cfg(target_os = "windows")]
                {
                    Self::WindowsSandbox
                }
                #[cfg(not(target_os = "windows"))]
                {
                    Self::Vm
                }
            }
            W::WindowsSandbox => Self::WindowsSandbox,
            W::Lxc => Self::Lxc,
            W::Microvm => Self::MicroVm,
            W::Hyperlight => Self::Hyperlight,
            W::Wslc => Self::Wslc,
            W::Seatbelt => Self::Seatbelt,
            W::IsolationSession => Self::IsolationSession,
            W::Bubblewrap => Self::Bubblewrap,
            W::W365Agents => Self::W365Agents,
        }
    }
}

/// Configuration specific to the Seatbelt backend.
/// Used under the top-level `seatbelt` key when `containment == Seatbelt`.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SeatbeltConfig {
    /// Optional override of the generated TinyScheme profile.
    #[serde(rename = "profileOverride", skip_serializing_if = "Option::is_none")]
    pub profile_override: Option<String>,

    /// Allow the Mach IPC services that GUI applications need to draw
    /// windows, composite frames, resolve fonts, and register with the Dock.
    /// When `false` (default), these services are blocked and GUI apps will
    /// be killed by the system on launch.
    #[serde(rename = "guiAccess", default)]
    pub gui_access: bool,

    /// Allow the inner process to allocate its own pseudo-terminals via
    /// `posix_openpt`. Defaults to `true` because most agent-style
    /// workloads spawn shells (tests, `git`, `gh`, REPLs) that fail
    /// without this. Adds `(allow pseudo-tty)`, `(allow iokit-open)`, and
    /// read/write/ioctl on `/dev/ptmx`. Set to `false` for the tightest
    /// possible sandbox when the inner command does not need to allocate
    /// new ttys.
    #[serde(rename = "nestedPty", default = "default_nested_pty")]
    pub nested_pty: bool,

    /// Allow Mach IPC + filesystem access required for `keytar` /
    /// `Security.framework` to actually use the macOS Keychain
    /// end-to-end (Mach: securityd, SecurityServer, cfprefsd.daemon,
    /// xpcd, lsd.*; FS read: `/Library/Keychains`, `/private/var/db/mds`;
    /// FS read+write: `~/Library/Keychains`, `/private/var/folders`;
    /// plus `iokit-open` for crypto accelerators). Defaults to `false`;
    /// opt in only when the inner workload genuinely needs Keychain
    /// access.
    #[serde(rename = "keychainAccess", default)]
    pub keychain_access: bool,

    /// Additional Mach service global-names to allow `mach-lookup` for.
    /// Escape hatch for callers that need to talk to a system service
    /// the baseline doesn't cover (e.g. opt-in agent integrations).
    /// Each entry is rendered verbatim as a `(global-name "...")`
    /// inside a single `(allow mach-lookup ...)` form.
    #[serde(
        rename = "extraMachLookups",
        default,
        skip_serializing_if = "Vec::is_empty"
    )]
    pub extra_mach_lookups: Vec<String>,

    /// Records sandbox denials through the unified log while the workload
    /// runs. On macOS, `retain_etl` keeps the raw log as `.seatbelt.log`.
    #[serde(rename = "captureDenials", skip_serializing_if = "Option::is_none")]
    pub capture_denials: Option<CaptureDenialsConfig>,
}

fn default_nested_pty() -> bool {
    true
}

impl Default for SeatbeltConfig {
    fn default() -> Self {
        Self {
            profile_override: None,
            gui_access: false,
            nested_pty: true,
            keychain_access: false,
            extra_mach_lookups: Vec::new(),
            capture_denials: None,
        }
    }
}

/// Configuration specific to the Windows Sandbox backend.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WindowsSandboxConfig {
    /// Legacy daemon idle timeout. Parsed for compatibility and ignored by the
    /// one-shot backend.
    pub idle_timeout_ms: u32,
    /// Legacy daemon endpoint name. Parsed for compatibility and ignored by the
    /// one-shot backend.
    pub daemon_pipe_name: String,
}

impl Default for WindowsSandboxConfig {
    fn default() -> Self {
        Self {
            idle_timeout_ms: 300_000,
            daemon_pipe_name: "wxc-windows-sandbox".to_string(),
        }
    }
}

/// State-aware provision-phase config for the Isolation Session backend.
/// Nested under `isolationSession.provision`. The one-shot
/// surface takes no backend configuration.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct IsolationSessionProvisionConfig {
    /// Optional identifier for the calling application, associating the
    /// provisioned agent user with its owning app.
    ///
    /// **A packaged app must pass its Package Family Name in the form
    /// `PFN:<packageFamilyName>`** (e.g. `PFN:Contoso.App_8wekyb3d8bbwe`) — the
    /// literal `PFN:` prefix followed by the PFN. A non-empty value is used
    /// verbatim, so a bare PFN without the prefix will **not** be treated as
    /// PFN-scoped. An unpackaged app may pass any string. Carried verbatim
    /// inside the returned `SandboxId` so later lifecycle phases can recover it
    /// without the caller re-supplying it.
    ///
    /// On an unpackaged host an explicitly-supplied empty string is a
    /// **distinct** value from an absent one and round-trips as such. The exact
    /// JSON contract rejects `null`.
    pub app_id: Option<String>,
}

/// Image and guest memory settings shared by MicroVM creation paths.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MicroVmProvisionConfig {
    /// Registry image fixed at creation.
    pub image: String,
    /// Guest memory in MiB. The backend chooses its default when absent.
    pub memory_mib: Option<u32>,
}

impl MicroVmProvisionConfig {
    pub(crate) fn validate_memory_mib(
        memory_mib: Option<u32>,
    ) -> Result<(), crate::mxc_common::error::WxcError> {
        if memory_mib == Some(0) {
            return Err(crate::mxc_common::error::WxcError::ConfigParse(
                "microvm.provision.memoryMib must be greater than zero".to_owned(),
            ));
        }
        Ok(())
    }
}

/// Passive W365 provision inputs; defaults and enforcement belong to the backend.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct W365AgentsProvisionConfig {
    pub pool_id: String,
    pub user_type: Option<String>,
    pub user_object_id: Option<String>,
}

/// Runtime-owned state-aware provision config for the WSLc backend.
///
/// Image selection and defaulting remain backend responsibilities. Conversion
/// preserves absent fields and explicitly supplied empty strings unchanged.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct WslcProvisionConfig {
    /// Container image reference. The backend selects its default when absent.
    pub image: Option<String>,

    /// Local image tarball to import instead of pulling an image.
    pub image_tar_path: Option<String>,

    /// Join this session, or the shared default session when absent.
    pub session_id: Option<String>,

    /// Host-to-container TCP forwards applied to the sandbox's own container.
    pub port_mappings: Option<Vec<PortMapping>>,
}

/// Runtime-owned state-aware session provision config for the WSLc backend.
///
/// Sizing belongs to the session, so these values describe the utility VM the
/// session runs in rather than a per-sandbox quota. Defaulting remains a
/// backend responsibility, so an absent field stays absent here.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WslcProvisionSessionConfig {
    pub cpu_count: Option<u32>,

    pub memory_mb: Option<u64>,

    /// Whether GPU passthrough is enabled.
    pub gpu: Option<bool>,
}

/// Configuration specific to the LXC container backend.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LxcConfig {
    /// Linux distribution for the container rootfs (e.g., "alpine", "ubuntu"). Required.
    pub distribution: String,
    /// Distribution release version (e.g., "3.20", "24.04"). Required.
    pub release: String,
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NetworkAction {
    Allow,
    #[default]
    Deny,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum NetworkProtocol {
    Tcp,
    Udp,
    Icmp,
    Any,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkCidr {
    pub address: IpAddr,
    pub prefix_length: u8,
}

impl std::str::FromStr for NetworkCidr {
    type Err = cidr::errors::NetworkParseError;

    fn from_str(value: &str) -> Result<Self, Self::Err> {
        let network = value.parse::<cidr::IpCidr>()?;

        Ok(Self {
            address: network.first_address(),
            prefix_length: network.network_length(),
        })
    }
}

impl NetworkCidr {
    pub fn contains_cidr(&self, other: &Self) -> bool {
        let Ok(parent) = cidr::IpCidr::new(self.address, self.prefix_length) else {
            return false;
        };
        let Ok(child) = cidr::IpCidr::new(other.address, other.prefix_length) else {
            return false;
        };
        parent.network_length() <= child.network_length() && parent.contains(&child.first_address())
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkPeer {
    pub cidr: NetworkCidr,
    pub except: Vec<NetworkCidr>,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkPort {
    pub protocol: NetworkProtocol,
    pub port: Option<u16>,
    pub end_port: Option<u16>,
}

#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkRule {
    pub to: Vec<NetworkPeer>,
    pub ports: Vec<NetworkPort>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkEgressPolicy {
    pub default: NetworkAction,
    pub allow: Vec<NetworkRule>,
    pub deny: Vec<NetworkRule>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NetworkIngressPolicy {
    pub default: NetworkAction,
    pub host_loopback: NetworkAction,
}

/// A hostname-to-IP mapping that makes a sandbox resolve the proxy to exactly
/// the address the firewall authorized.
///
/// This exists instead of rewriting the proxy URL's host to the resolved IP.
/// Rewriting the host breaks TLS for an `https://`-scheme proxy: the client
/// then contacts an IP literal, so SNI and certificate validation fail unless
/// the proxy certificate carries an IP SAN. Pinning the name resolution
/// instead keeps the hostname in the URL, so TLS identity is preserved, while
/// still guaranteeing the sandbox and the firewall agree on one endpoint.
///
/// Without a pin the sandbox re-resolves the hostname itself, and under
/// round-robin or split-horizon DNS it can select an address the firewall
/// never allowed.
///
/// The fields are private and the address is an [`IpAddr`], so a pin that does
/// not denote exactly one mapping cannot be constructed. This matters because
/// [`Self::hosts_line`] is written to a hosts file: a newline or space in
/// either field would inject additional entries, letting an attacker redirect
/// names the policy never mentioned. Construct one with
/// [`ProxyAddress::host_pin`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ProxyHostPin {
    hostname: String,
    ip: IpAddr,
}

impl ProxyHostPin {
    /// The proxy hostname as it appears in the URL handed to the sandbox.
    pub fn hostname(&self) -> &str {
        &self.hostname
    }

    /// The address the hostname is pinned to, and the only address the
    /// firewall authorizes for it.
    pub fn ip(&self) -> IpAddr {
        self.ip
    }

    /// Render this pin as a `/etc/hosts` line.
    ///
    /// The address is written bare. A hosts file takes an unbracketed IPv6
    /// literal where a URL host component requires brackets, so this rendering
    /// and [`ProxyAddress::to_url`] differ on the same address by design.
    pub fn hosts_line(&self) -> String {
        format!("{} {}", self.ip, self.hostname)
    }
}

#[derive(Debug, Clone)]
pub struct ProxyAddress {
    pub address: String,
    pub port: u16,
    /// Original URL string if provided via `{ "url": "..." }`.
    pub original_url: Option<String>,
}

impl ProxyAddress {
    pub fn new(address: String, port: u16) -> Self {
        Self {
            address,
            port,
            original_url: None,
        }
    }

    /// Create a ProxyAddress from a parsed URL, preserving the original string.
    pub fn from_url(url: &str, host: String, port: u16) -> Self {
        Self {
            address: host,
            port,
            original_url: Some(url.to_string()),
        }
    }

    pub fn host(&self) -> &str {
        &self.address
    }

    pub fn port(&self) -> u16 {
        self.port
    }

    /// Returns the proxy URL. Uses the original URL if one was provided,
    /// otherwise constructs one from this address and port.
    ///
    /// The address is never assumed to be loopback. The URL the sandbox is
    /// given and the endpoint the firewall authorized have to name the same
    /// proxy, so a fixed `127.0.0.1` would be wrong for a proxy not bound
    /// there.
    pub fn to_url(&self) -> String {
        if let Some(url) = &self.original_url {
            return url.clone();
        }
        format!(
            "http://{}:{}",
            Self::bracket_if_ipv6(&self.address),
            self.port
        )
    }

    /// Returns the pin required for a sandbox to resolve this proxy's hostname
    /// to `ip`.
    ///
    /// `Ok(None)` means no pin is needed, because the address is already an IP
    /// literal: there is nothing to resolve, and so nothing a sandbox could
    /// resolve differently.
    ///
    /// `Err` means a pin is needed and cannot be produced -- the address is
    /// empty, or holds characters a hostname cannot. That is an error rather
    /// than `None` because `None` reads as "no hosts entry required", which
    /// would let a malformed address silently skip the pin and leave the
    /// sandbox free to re-resolve the name. A proxy whose endpoint cannot be
    /// pinned must not run.
    ///
    /// The [`IpAddr`] parameter puts resolution on the caller and leaves an
    /// unparseable address unrepresentable here.
    ///
    /// The URL keeps its hostname; [`ProxyHostPin`] carries the reason.
    pub fn host_pin(&self, ip: IpAddr) -> Result<Option<ProxyHostPin>, WxcError> {
        let hostname = unbracket_host(&self.address);

        // An IP literal needs no pin. Unbracket first so a bracketed IPv6
        // literal is recognized as a literal rather than mistaken for a
        // hostname: `IpAddr::from_str` rejects brackets, so `[::1]` would
        // otherwise be pinned as though it were a name.
        if hostname.parse::<IpAddr>().is_ok() {
            return Ok(None);
        }

        if !Self::is_pinnable_hostname(hostname) {
            return Err(WxcError::NetworkProxy(format!(
                "proxy address {:?} cannot be pinned to {}: not a valid hostname",
                self.address, ip
            )));
        }

        Ok(Some(ProxyHostPin {
            hostname: hostname.to_string(),
            ip,
        }))
    }

    /// Whether `host` is safe to write as the name column of a hosts file
    /// entry.
    ///
    /// What matters about the allowed set is what it leaves out: a space or a
    /// newline would end the record, so a hostname carrying one would write
    /// further mappings for names the policy never authorized.
    fn is_pinnable_hostname(host: &str) -> bool {
        !host.is_empty()
            && host
                .chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.')
    }

    /// Wraps `host` in `[` `]` when it is a bare IPv6 literal, so it is valid
    /// as a URL host component.
    ///
    /// Double bracketing needs no guard: `IpAddr::from_str` rejects brackets,
    /// so an already-bracketed literal fails to parse and passes through
    /// unchanged.
    fn bracket_if_ipv6(host: &str) -> std::borrow::Cow<'_, str> {
        match host.parse::<IpAddr>() {
            Ok(IpAddr::V6(_)) => std::borrow::Cow::Owned(format!("[{host}]")),
            _ => std::borrow::Cow::Borrowed(host),
        }
    }
}

/// Strips one pair of surrounding `[` `]` from a bracketed IPv6 literal.
///
/// A URL host component keeps the brackets, but `IpAddr::from_str`, hosts
/// files, and iptables all reject them.
pub fn unbracket_host(host: &str) -> &str {
    host.strip_prefix('[')
        .and_then(|rest| rest.strip_suffix(']'))
        .unwrap_or(host)
}

/// Normalized runtime proxy configuration.
#[derive(Debug, Default, Clone)]
pub struct ProxyConfig {
    pub address: Option<ProxyAddress>,
}

impl ProxyConfig {
    pub fn is_enabled(&self) -> bool {
        self.address.is_some()
    }
}

/// Clipboard access policy for UI restrictions.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ClipboardPolicy {
    #[default]
    None,
    Read,
    Write,
    #[serde(rename = "all")]
    All,
}

impl From<crate::mxc_common::wire::ClipboardPolicy> for ClipboardPolicy {
    fn from(c: crate::mxc_common::wire::ClipboardPolicy) -> Self {
        match c {
            crate::mxc_common::wire::ClipboardPolicy::None => Self::None,
            crate::mxc_common::wire::ClipboardPolicy::Read => Self::Read,
            crate::mxc_common::wire::ClipboardPolicy::Write => Self::Write,
            crate::mxc_common::wire::ClipboardPolicy::All => Self::All,
        }
    }
}

/// Cross-platform UI policy parsed from the `ui` JSON section.
/// Default-deny: UI is disabled, no clipboard, no injection.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct UiPolicy {
    /// When true, the sandbox cannot create visible windows (disables Win32k).
    pub disable: bool,
    /// Clipboard access level.
    pub clipboard: ClipboardPolicy,
    /// Whether input injection (keyboard/mouse) is allowed.
    pub injection: bool,
}

impl Default for UiPolicy {
    fn default() -> Self {
        Self {
            disable: true,
            clipboard: ClipboardPolicy::None,
            injection: false,
        }
    }
}

/// BaseProcessContainer-specific UI configuration (Windows only).
/// Parsed from `processContainer.ui` in the JSON config.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct BaseProcessUiConfig {
    /// UI isolation level for the desktop.
    pub isolation: String,
    /// Whether desktop system control is allowed.
    #[serde(rename = "desktopSystemControl")]
    pub desktop_system_control: bool,
    /// System settings access level.
    #[serde(rename = "systemSettings")]
    pub system_settings: String,
    /// Whether IME (Input Method Editor) is allowed.
    pub ime: bool,
}

impl Default for BaseProcessUiConfig {
    fn default() -> Self {
        Self {
            isolation: "container".to_string(),
            desktop_system_control: false,
            system_settings: "none".to_string(),
            ime: false,
        }
    }
}

/// Reserved ProcessContainer access-check modes, shared by diagnostics and telemetry.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum LearningModeCapability {
    /// Record denied accesses without allowing them.
    Learning,
    /// Allow and record accesses instead of enforcing deny-by-default.
    Permissive,
}

impl LearningModeCapability {
    /// Windows derives capability SIDs case-insensitively.
    pub(crate) fn from_capability_name(name: &str) -> Option<Self> {
        if name.eq_ignore_ascii_case("learningModeLogging") {
            Some(Self::Learning)
        } else if name.eq_ignore_ascii_case("permissiveLearningMode") {
            Some(Self::Permissive)
        } else {
            None
        }
    }
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ContainerPolicy {
    pub least_privilege_mode: bool,
    pub capabilities: Vec<String>,
    pub readwrite_paths: Vec<String>,
    pub readonly_paths: Vec<String>,
    pub enumerate_paths: Vec<String>,
    pub denied_paths: Vec<String>,
    /// Outbound CIDR, protocol, and port policy.
    pub network_egress: Option<NetworkEgressPolicy>,
    /// Inbound and host-loopback policy.
    pub network_ingress: Option<NetworkIngressPolicy>,
    /// ProcessContainer proxy peer identity.
    pub allowed_proxy_peer: Option<String>,
    #[serde(skip)]
    pub network_proxy: ProxyConfig,
    /// Whether the caller supplied a `network` block on the wire (any field
    /// present), captured at parse time. Distinguishes an absent network policy
    /// from an explicit one whose values equal the defaults. Used by backends
    /// (e.g. IsolationSession) that must reject a network
    /// policy supplied on a phase where the posture is immutable. Parse-derived,
    /// never on the wire.
    #[serde(skip)]
    pub network_specified: bool,
    /// Whether the caller supplied directional network posture fields:
    /// `egress` or `ingress`.
    /// Runtime proxy data is excluded. This lets state-aware backends reject a
    /// post-provision posture change by presence while still accepting a
    /// proxy-only exec request. Parse-derived, never on the wire.
    #[serde(skip)]
    pub network_mode_specified: bool,
    /// Whether `runtimeConfig.networkProxy` was supplied, even if the network
    /// posture itself was omitted.
    #[serde(skip)]
    pub runtime_network_proxy_specified: bool,
    /// Cross-platform UI policy.
    pub ui: UiPolicy,
    /// Whether the caller supplied a `ui` block on the wire (any field
    /// present), captured at parse time. The twin of `network_specified`, and
    /// necessary for the same reason: `UiPolicy::default()` is full lockdown,
    /// so an absent `ui` and an explicitly-supplied lockdown `ui` are
    /// indistinguishable from the other fields here. Parse-derived, never on
    /// the wire.
    ///
    /// Consumed only by IsolationSession today, which has no UI-restriction
    /// primitive and refuses a supplied UI policy rather than accepting and
    /// dropping it. The other backends that do not enforce `policy.ui` — LXC
    /// and Bubblewrap on Linux, Seatbelt on macOS, Windows Sandbox — still
    /// accept and ignore it, so this flag being set does not mean a UI policy
    /// was honored anywhere; it means only that the caller supplied one.
    #[serde(skip)]
    pub ui_specified: bool,
    /// BaseProcessContainer-specific UI config (Windows only, from processContainer.ui).
    pub base_process_ui: BaseProcessUiConfig,
    /// Windows denial capture (from `processContainer.captureDenials`). When
    /// `Some`, the runner records the sandboxed process's ungranted access
    /// attempts to a learning-mode ETL trace. `None` disables capture.
    pub capture_denials: Option<CaptureDenialsConfig>,
}

/// Windows denial-capture settings (from `processContainer.captureDenials`).
/// The presence of this struct on [`ContainerPolicy::capture_denials`] enables
/// capture; the runner records the sandboxed process's ungranted access
/// attempts to a learning-mode ETL trace. [`CaptureDenialsConfig::mode`]
/// decides whether each recorded access is blocked (default) or allowed.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct CaptureDenialsConfig {
    /// How each ungranted access check is handled while it is recorded.
    /// Defaults to [`CaptureDenialsMode::Block`].
    pub mode: CaptureDenialsMode,
    /// Absolute path where the JSON denials output file is written. This is the
    /// application-facing deliverable, not the runner-managed intermediate ETL.
    /// The runner inserts a per-run identifier into the file stem (`denials.json` ->
    /// `denials.<run-id>.json`) so concurrent and sequential captures don't
    /// collide, and reports the actual path on stderr. When `None`, the runner
    /// falls back to a managed per-run temporary file and prints its path on
    /// stderr.
    pub output_path: Option<String>,
    /// Whether to preserve the sealed ETL trace (on macOS, the raw
    /// `.seatbelt.log`) after analysis. Defaults to `false`, which deletes the
    /// internal trace. Retention is honored only by
    /// a terminal wait that leaves structured output observable; abandoning the
    /// process handle deletes the trace.
    pub retain_etl: bool,
}

/// How `captureDenials` handles each ungranted access check while recording it.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum CaptureDenialsMode {
    /// The access stays denied and the denial is recorded; deny-by-default
    /// containment is preserved. Safe default.
    #[default]
    Block,
    /// The access is allowed and recorded (audit mode); deny-by-default is
    /// relaxed for the run. Security-sensitive — the runner warns.
    Allow,
}

/// Port mapping for host↔container port forwarding.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct PortMapping {
    /// Port on the Windows host.
    pub windows_port: u16,
    /// Port inside the Linux container.
    pub container_port: u16,
    /// Protocol: "tcp" or "udp". Default: "tcp".
    pub protocol: String,
}

/// Configuration for the WSL Container (WSLC SDK) backend.
/// Used when containment == Wslc.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct WslcConfig {
    /// Target OS for the container. Currently only "linux" is supported.
    pub target_os: String,
    /// Container image name (e.g., "alpine:latest", "python:3.12").
    pub image: String,
    /// Path to a local tar file to import as the container image.
    /// When set, the image is imported from this file instead of pulling from a registry.
    pub image_tar_path: Option<String>,
    /// Number of CPUs allocated to the session. None = host-determined.
    pub cpu_count: Option<u32>,
    /// Memory in MB allocated to the session. None = host-determined.
    pub memory_mb: Option<u64>,
    /// Enable GPU passthrough via WSLC_CONTAINER_FLAG_ENABLE_GPU.
    pub gpu: bool,
    /// Storage path for WSLC session image store. None = SDK default.
    pub storage_path: Option<String>,
    /// Host↔container port mappings.
    pub port_mappings: Vec<PortMapping>,
}

impl Default for WslcConfig {
    fn default() -> Self {
        Self {
            target_os: "linux".to_string(),
            image: "alpine:latest".to_string(),
            image_tar_path: None,
            cpu_count: None,
            memory_mb: None,
            gpu: false,
            storage_path: None,
            port_mappings: Vec::new(),
        }
    }
}

/// Container lifecycle settings shared across all backends.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LifecycleConfig {
    /// Destroy the container after execution completes. Default: true.
    pub destroy_on_exit: bool,
    /// If true, retain filesystem and network policies after execution. Default: false.
    pub preserve_policy: bool,
}

impl Default for LifecycleConfig {
    fn default() -> Self {
        Self {
            destroy_on_exit: true,
            preserve_policy: false,
        }
    }
}

/// Placeholder experimental feature for testing the experimental infrastructure.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TestFeatureConfig {
    /// Message to log when the feature is applied.
    pub message: String,
}

impl TestFeatureConfig {
    pub fn from_raw(message: Option<String>) -> Self {
        Self {
            message: message.unwrap_or_default(),
        }
    }
}

/// Telemetry configuration parsed from the top-level JSON config `telemetry` section.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct TelemetryConfig {
    /// Compatibility preference ignored by supported-contract Required collection.
    /// Unattributed requests require `Some(true)`, consent, and permitting policy.
    pub enabled: Option<bool>,
}

/// Guest runtime for the Hyperlight backend: what `process.commandLine`
/// is source for.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum HyperlightRuntime {
    /// CPython with the data-science stack preloaded.
    #[default]
    Agent,
    /// CPython.
    Python,
    /// CPython with a BusyBox shell.
    #[serde(rename = "python-shell")]
    PythonShell,
    /// Node.js.
    Node,
    /// Bash with BusyBox.
    Bash,
    /// .NET with the JIT.
    #[serde(rename = "dotnet-jit")]
    DotnetJit,
}

impl HyperlightRuntime {
    /// Every runtime the backend can install and run.
    pub const ALL: [HyperlightRuntime; 6] = [
        HyperlightRuntime::Agent,
        HyperlightRuntime::Python,
        HyperlightRuntime::PythonShell,
        HyperlightRuntime::Node,
        HyperlightRuntime::Bash,
        HyperlightRuntime::DotnetJit,
    ];

    /// The wire spelling: the upstream image's name, also the runtime's
    /// directory in an image home.
    pub fn name(self) -> &'static str {
        match self {
            HyperlightRuntime::Agent => "agent",
            HyperlightRuntime::Python => "python",
            HyperlightRuntime::PythonShell => "python-shell",
            HyperlightRuntime::Node => "node",
            HyperlightRuntime::Bash => "bash",
            HyperlightRuntime::DotnetJit => "dotnet-jit",
        }
    }
}

impl std::str::FromStr for HyperlightRuntime {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        HyperlightRuntime::ALL
            .into_iter()
            .find(|runtime| runtime.name() == s)
            .ok_or_else(|| {
                let known: Vec<&str> = HyperlightRuntime::ALL.iter().map(|r| r.name()).collect();
                format!(
                    "unknown hyperlight runtime {s:?}; expected one of {}",
                    known.join(", ")
                )
            })
    }
}

/// Hyperlight backend configuration (`hyperlight`).
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(default)]
pub struct HyperlightConfig {
    /// Guest runtime for the run.
    pub runtime: HyperlightRuntime,
}

#[derive(Debug, Clone, Default, Serialize)]
pub struct ExecutionRequest {
    /// Contract that produced this request, including typed SDK compatibility input.
    ///
    /// Direct internal construction may omit contract attribution.
    #[serde(serialize_with = "serialize_source_contract")]
    pub source_contract: Option<crate::mxc_contract::ContractVersion>,
    /// Caller-requested containment kind, independent of telemetry preferences.
    #[serde(skip)]
    pub requested_sandbox_kind: Option<&'static str>,
    /// Externally assigned container identifier.
    pub container_id: String,
    /// Environment variables as "KEY=VALUE" strings (from `process.env`).
    ///
    /// Three states, deliberately distinct:
    ///
    /// * `None` — the caller supplied no environment. Backends provide a
    ///   default: on Windows, the user's profile block; on LXC, Bubblewrap, and
    ///   Seatbelt, `PATH` + `TERM`, plus `HOME` naming the directory the child
    ///   is started in. Those three omit `HOME` when no working directory
    ///   resolves, having no private directory to point it at. On WSLc it is
    ///   the container image's own `ENV`.
    /// * `Some(vec![])` — the caller asked for an *empty* environment, unless
    ///   [`ExecutionRequest::inherit_default_env`] layers it over the default
    ///   and so asks for the default itself. This is not the same as `None`,
    ///   and on the Windows process container an empty block is rejected before
    ///   launch, because the OS requires certain names to be present (see
    ///   `REQUIRED_CHILD_ENV_VARS`).
    /// * `Some(entries)` — the caller's environment, used verbatim. MXC does
    ///   not add to it; callers that want the default block or the calling
    ///   process's variables must merge them in themselves, or set
    ///   [`ExecutionRequest::inherit_default_env`].
    ///
    /// IsolationSession starts every process from the agent user's default
    /// environment, so it rejects `Some` without
    /// [`ExecutionRequest::inherit_default_env`].
    pub env: Option<Vec<String>>,

    /// Layer [`ExecutionRequest::env`] on top of the backend's default
    /// environment instead of replacing it (from `process.inheritDefaultEnv`).
    ///
    /// Only meaningful when `env` is `Some`: with `None` the child already gets
    /// the default.
    pub inherit_default_env: bool,
    pub script_code: String,
    pub working_directory: String,
    pub script_timeout: u32,
    /// Which containment backend to use. Default: ProcessContainer.
    pub containment: ContainmentBackend,
    /// Shared lifecycle settings.
    pub lifecycle: LifecycleConfig,
    /// ProcessContainer-specific policy (used when containment == ProcessContainer).
    pub policy: ContainerPolicy,
    /// LXC-specific configuration (used when containment == Lxc).
    pub lxc_config: LxcConfig,
    /// WSLC-specific configuration (used when containment == Wslc).
    pub wslc: Option<WslcConfig>,
    /// Seatbelt (macOS) backend configuration (used when containment == Seatbelt).
    pub seatbelt: Option<SeatbeltConfig>,
    /// Per-invocation telemetry configuration.
    pub telemetry: Option<TelemetryConfig>,
    /// Placeholder feature for testing experimental infrastructure.
    pub test_feature: Option<TestFeatureConfig>,
    /// Windows Sandbox backend configuration.
    pub windows_sandbox: Option<WindowsSandboxConfig>,
    /// Hyperlight backend configuration (used when containment == Hyperlight).
    pub hyperlight: Option<HyperlightConfig>,
    /// Registry image for MicroVM creation; never supplied for existing-container execution.
    pub microvm_image: Option<String>,
    /// Explicit MicroVM creation memory; absent leaves the backend default unchanged.
    pub microvm_memory_mib: Option<u32>,
    /// Whether the --experimental flag was passed.
    pub experimental_enabled: bool,
    /// Dry-run mode: validate config and runner setup then return success
    /// without executing the sandboxed process.
    pub dry_run: bool,
}

fn serialize_source_contract<S>(
    value: &Option<crate::mxc_contract::ContractVersion>,
    serializer: S,
) -> Result<S::Ok, S::Error>
where
    S: serde::Serializer,
{
    value
        .map(crate::mxc_contract::ContractVersion::as_str)
        .serialize(serializer)
}

/// Where a [`ResolvedWorkingDirectory`] came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WorkingDirectorySource {
    /// The caller's explicit `process.cwd`.
    Explicit,
    /// Derived from the filesystem policy because `process.cwd` was omitted.
    Policy,
}

/// The working directory a backend should launch the sandboxed child in,
/// together with where it came from (for logging and error context).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ResolvedWorkingDirectory<'a> {
    /// The selected directory. Never empty.
    pub path: &'a str,
    /// Whether `path` is the caller's `process.cwd` or a policy fallback.
    pub source: WorkingDirectorySource,
}

/// Normalize `path` to an absolute, lexically clean path inside a sandbox whose
/// root is `/`.
///
/// Backends that start the child with a `chdir` relative to the guest root use
/// this so the directory the child lands in and the `HOME` naming it cannot
/// disagree. `.` segments are dropped and `..` pops the previous segment
/// without escaping the root. Purely lexical: no symlink resolution, and the
/// path is not probed.
pub fn sandbox_absolute_path(path: &str) -> String {
    let mut segments: Vec<&str> = Vec::new();
    for segment in path.split('/') {
        match segment {
            "" | "." => {}
            ".." => {
                segments.pop();
            }
            other => segments.push(other),
        }
    }
    format!("/{}", segments.join("/"))
}

impl ExecutionRequest {
    /// Exact external contract spelling for diagnostics and telemetry.
    ///
    /// Direct typed SDK requests return an empty string because they have no
    /// external JSON contract attribution.
    pub fn source_contract_version(&self) -> &'static str {
        self.source_contract
            .map(crate::mxc_contract::ContractVersion::as_str)
            .unwrap_or_default()
    }

    /// The caller's environment entries, with "not supplied" and "supplied but
    /// empty" flattened to the same empty slice.
    ///
    /// Backends with an enumerable default must match on
    /// [`ExecutionRequest::env`] directly, since `None` means "give the child
    /// the default" and `Some(vec![])` means "give the child nothing". A
    /// backend whose default MXC cannot enumerate takes the state from `env`
    /// and the entries from here: WSLc, whose default is the
    /// container image's `ENV`, and IsolationSession, which starts every
    /// process from the agent user's default environment.
    pub fn env_entries(&self) -> &[String] {
        self.env.as_deref().unwrap_or(&[])
    }

    /// Resolve the working directory for the sandboxed child: an explicit
    /// `working_directory`, else the first filesystem-policy grant that is an
    /// existing directory (`readwrite` paths before `readonly` ones), else
    /// `None`.
    ///
    /// Backends that must not let the child inherit the host process's cwd use
    /// this to fall back to a policy-granted path. It matters most on Windows:
    /// a `NULL` current directory makes `CreateProcessW` inherit the parent's
    /// cwd, and when the AppContainer token can't open it the kernel silently
    /// resets the child to the drive root (`C:\`) instead of failing the launch.
    ///
    /// Policy grants may name individual *files* or directories that do not
    /// exist yet, neither of which a process can be launched in, so only
    /// existing directories are considered. An explicit `working_directory` is
    /// returned unchecked — the caller asked for it, so a bad one must fail the
    /// launch loudly rather than be silently replaced.
    ///
    /// Callers whose policy paths need normalizing before they can be probed
    /// (e.g. Seatbelt's `~` expansion) should use
    /// [`ExecutionRequest::resolved_working_directory_with`].
    pub fn resolved_working_directory(&self) -> Option<ResolvedWorkingDirectory<'_>> {
        self.resolved_working_directory_with(|path| std::path::Path::new(path).is_dir())
    }

    /// [`ExecutionRequest::resolved_working_directory`] with an injectable
    /// "is this an existing directory?" probe, so backends can normalize a
    /// policy path before testing it and unit tests can run without touching
    /// the filesystem. The returned path is always the *unnormalized* policy
    /// entry; normalize it again if `is_dir` did.
    pub fn resolved_working_directory_with(
        &self,
        is_dir: impl Fn(&str) -> bool,
    ) -> Option<ResolvedWorkingDirectory<'_>> {
        if !self.working_directory.trim().is_empty() {
            return Some(ResolvedWorkingDirectory {
                path: self.working_directory.as_str(),
                source: WorkingDirectorySource::Explicit,
            });
        }
        self.policy
            .readwrite_paths
            .iter()
            .chain(self.policy.readonly_paths.iter())
            .map(String::as_str)
            .filter(|path| !path.trim().is_empty())
            .find(|path| is_dir(path))
            .map(|path| ResolvedWorkingDirectory {
                path,
                source: WorkingDirectorySource::Policy,
            })
    }
}

/// Distinguishes whether an error occurred during process creation (launch)
/// or after the process started but exited with a failure code.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum FailurePhase {
    /// No failure (process exited successfully, or has not been evaluated yet).
    #[default]
    None,
    /// The launch attempt failed: the CreateProcess (or equivalent) API call,
    /// the VM/sandbox bring-up, or a transient resource contention (e.g. a
    /// single-instance backend already running). Generally worth retrying.
    LaunchFailed,
    /// The request itself is refusable: the policy asks for something the
    /// selected backend cannot enforce. Only a changed request can succeed.
    Rejected,
    /// The launch command succeeded but the guest/sandbox infrastructure failed
    /// before or while running user code (agent rendezvous, channel connect, or
    /// the execution relay) — i.e. the process never ran to a clean exit.
    PostLaunchFailed,
    /// The process was created and ran, but exited with a non-zero code.
    ProcessExited,
    /// The process was force-terminated because it exceeded `scriptTimeout`.
    /// Distinct from [`FailurePhase::ProcessExited`] (it did not exit on its own) so callers
    /// can detect a timeout uniformly across backends rather than inferring it
    /// from `exit_code == -1` (which collides with other failures).
    Timeout,
    /// The host cannot provide the selected containment backend at all: the API
    /// is missing, the runtime is not installed, or an OS feature it depends on
    /// is disabled. No change to the request can satisfy it — the host has to
    /// be provisioned, or a different backend selected. Distinct from
    /// [`FailurePhase::LaunchFailed`], which is a backend that is present and failed.
    BackendUnavailable,
}

impl FailurePhase {
    /// The wire error code a failure in this phase is reported as.
    ///
    /// Two phases earn a code of their own because they tell the caller which
    /// side is at fault: [`Rejected`](FailurePhase::Rejected) blames the
    /// request, and [`BackendUnavailable`](FailurePhase::BackendUnavailable)
    /// blames the host. Every other failure is a runtime fault the caller
    /// cannot distinguish usefully and stays `backend_error`.
    pub fn error_code(&self) -> MxcErrorCode {
        match self {
            FailurePhase::Rejected => MxcErrorCode::PolicyValidation,
            FailurePhase::BackendUnavailable => MxcErrorCode::BackendUnavailable,
            _ => MxcErrorCode::BackendError,
        }
    }

    /// The process exit status a failure in this phase terminates with.
    ///
    /// Derived from [`error_code`](FailurePhase::error_code) so a response and
    /// an entry-point failure carrying the same code always exit alike: a
    /// refusal exits 1, and a host or runtime fault exits -1.
    pub fn failure_exit_code(&self) -> i32 {
        self.error_code().exit_code()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ScriptResponse {
    pub exit_code: i32,
    pub standard_out: String,
    pub standard_err: String,
    pub error_message: String,
    /// Raw system/API error detail intended for developers and diagnostics
    /// (e.g. "CreateProcessSecurityEnvironment failed: HRESULT(...)").
    /// Kept separate from `error_message` which holds user-friendly text.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub extended_error: String,
    /// Indicates at what phase the failure occurred.
    #[serde(default)]
    pub failure_phase: FailurePhase,
    /// Non-fatal diagnostics raised while building or running the sandbox,
    /// carried on the response so a programmatic caller can filter them
    /// instead of scraping stderr.
    ///
    /// Boxed, like `output_metadata`, to keep `ScriptResponse` small enough to
    /// serve as a `Result` error type. Reach for it through
    /// [`warnings`](ScriptResponse::warnings) and
    /// [`extend_warnings`](ScriptResponse::extend_warnings) rather than the
    /// field, so the "absent" and "empty" spellings cannot drift apart.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub warnings: Option<Box<Vec<String>>>,
    /// Structured metadata produced after the sandboxed process exits.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub output_metadata: Option<Box<SandboxOutputMetadata>>,
}

impl Default for ScriptResponse {
    fn default() -> Self {
        Self {
            exit_code: -1,
            standard_out: String::new(),
            standard_err: String::new(),
            error_message: String::new(),
            extended_error: String::new(),
            failure_phase: FailurePhase::None,
            warnings: None,
            output_metadata: None,
        }
    }
}

/// Structured outputs produced by optional sandbox features.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SandboxOutputMetadata {
    /// Location and summary of a captureDenials output document.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_denials: Option<CaptureDenialsOutput>,
    /// Failure details and retained ETL location when capture finalization fails.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capture_denials_error: Option<CaptureDenialsErrorOutput>,
}

/// Structured diagnostics for a failed captureDenials finalization.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureDenialsErrorOutput {
    /// Human-readable finalization failure.
    pub message: String,
    /// Absolute path to the retained ETL trace.
    pub etl_path: String,
}

/// Location and summary of a captureDenials output document.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CaptureDenialsOutput {
    /// Discriminator used by line-oriented CLI consumers.
    #[serde(rename = "type")]
    pub kind: String,
    /// Absolute path to the JSON denials output file.
    pub output_path: String,
    /// Exit code of the sandboxed child.
    pub exit_code: i32,
    /// Count of unique denials written.
    pub total_denials: usize,
    /// Whether the emitted denial set was truncated.
    pub denied_resources_truncated: bool,
    /// Absolute path to the retained ETL trace (on macOS, the `.seatbelt.log`),
    /// when retention was requested.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub etl_path: Option<String>,
}

impl CaptureDenialsOutput {
    /// The fixed `type` discriminator value.
    pub const KIND: &'static str = "captureDenials";
}

impl From<crate::learning_mode_core::DenialsOutputPointer> for CaptureDenialsOutput {
    fn from(pointer: crate::learning_mode_core::DenialsOutputPointer) -> Self {
        Self {
            kind: pointer.kind,
            output_path: pointer.output_path,
            exit_code: pointer.exit_code,
            total_denials: pointer.total_denials,
            denied_resources_truncated: pointer.denied_resources_truncated,
            etl_path: None,
        }
    }
}

impl ScriptResponse {
    /// Create an error response with the given message and exit code -1.
    pub fn error(msg: &str) -> Self {
        ScriptResponse {
            exit_code: -1,
            standard_err: msg.to_string(),
            error_message: msg.to_string(),
            ..Default::default()
        }
    }

    /// Create a response for a request the backend refuses.
    ///
    /// Exits 1 and reports `policy_validation`, matching a parser-side
    /// rejection, so a caller can tell a refused policy from a crash, a launch
    /// failure, or a timeout — all of which exit -1.
    ///
    /// Unlike [`ScriptResponse::error`] the message is not also copied into
    /// `standard_err`: nothing ran, so there is no workload output to relay, and
    /// copying it would print the message bare and then again inside the JSON
    /// envelope.
    pub fn rejected(msg: &str) -> Self {
        Self::failed(FailurePhase::Rejected, msg)
    }

    /// Create a response for a backend this host cannot provide.
    ///
    /// Reports `backend_unavailable`, which tells the caller the host is at
    /// fault: no change to the request will satisfy it. Like
    /// [`ScriptResponse::rejected`] nothing ran, so the message is left to the
    /// envelope rather than copied into `standard_err`.
    pub fn unavailable(msg: &str) -> Self {
        Self::failed(FailurePhase::BackendUnavailable, msg)
    }

    /// Create a response for a failure attributed to `phase`.
    ///
    /// The exit code follows the phase, and the message is left to the error
    /// envelope rather than copied into `standard_err`.
    pub fn failed(phase: FailurePhase, msg: &str) -> Self {
        ScriptResponse {
            exit_code: phase.failure_exit_code(),
            error_message: msg.to_string(),
            failure_phase: phase,
            ..Default::default()
        }
    }

    /// The non-fatal diagnostics this run recorded.
    pub fn warnings(&self) -> &[String] {
        self.warnings.as_deref().map_or(&[], Vec::as_slice)
    }

    /// Append diagnostics, allocating only once there is something to record.
    pub fn extend_warnings(&mut self, warnings: impl IntoIterator<Item = String>) {
        let mut incoming = warnings.into_iter().peekable();
        if incoming.peek().is_none() {
            return;
        }
        self.warnings
            .get_or_insert_with(Box::default)
            .extend(incoming);
    }
}

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

    #[test]
    fn each_caller_actionable_phase_earns_its_own_error_code() {
        assert_eq!(
            FailurePhase::Rejected.error_code(),
            MxcErrorCode::PolicyValidation
        );
        assert_eq!(
            FailurePhase::BackendUnavailable.error_code(),
            MxcErrorCode::BackendUnavailable
        );
        for phase in [
            FailurePhase::None,
            FailurePhase::LaunchFailed,
            FailurePhase::PostLaunchFailed,
            FailurePhase::ProcessExited,
            FailurePhase::Timeout,
        ] {
            assert_eq!(
                phase.error_code(),
                MxcErrorCode::BackendError,
                "phase {phase:?}"
            );
        }
    }

    #[test]
    fn only_a_refusal_exits_one() {
        assert_eq!(FailurePhase::Rejected.failure_exit_code(), 1);
        for phase in [
            FailurePhase::None,
            FailurePhase::LaunchFailed,
            FailurePhase::PostLaunchFailed,
            FailurePhase::ProcessExited,
            FailurePhase::Timeout,
            FailurePhase::BackendUnavailable,
        ] {
            assert_eq!(phase.failure_exit_code(), -1, "phase {phase:?}");
        }
    }

    #[test]
    fn an_unavailable_host_is_told_apart_from_a_refusal_and_a_crash() {
        let unavailable = ScriptResponse::unavailable("WSL is not installed");

        assert_eq!(unavailable.exit_code, -1);
        assert_eq!(
            unavailable.failure_phase.error_code(),
            MxcErrorCode::BackendUnavailable
        );
        assert!(unavailable.standard_err.is_empty());
    }

    #[test]
    fn warnings_are_omitted_from_the_wire_when_there_are_none() {
        let quiet = serde_json::to_string(&ScriptResponse::default()).unwrap();
        assert!(!quiet.contains("warnings"), "{quiet}");

        let mut noisy = ScriptResponse::default();
        noisy.extend_warnings(["dacl augmentation fell back".to_string()]);
        let noisy = serde_json::to_string(&noisy).unwrap();
        assert!(noisy.contains("dacl augmentation fell back"), "{noisy}");
    }

    #[test]
    fn recording_nothing_allocates_nothing() {
        let mut response = ScriptResponse::default();
        response.extend_warnings(Vec::new());
        assert!(response.warnings.is_none());
        assert!(response.warnings().is_empty());
    }

    // `ScriptResponse` is used as a `Result` error type, so it has to stay
    // under clippy's `result_large_err` threshold.
    #[test]
    fn the_response_stays_small_enough_to_be_an_error_type() {
        assert!(
            std::mem::size_of::<ScriptResponse>() <= 128,
            "{} bytes",
            std::mem::size_of::<ScriptResponse>()
        );
    }

    #[test]
    fn rejection_exits_one_and_leaves_stderr_to_the_envelope() {
        let rejected = ScriptResponse::rejected("policy not supported");

        assert_eq!(rejected.exit_code, 1);
        assert_eq!(rejected.failure_phase, FailurePhase::Rejected);
        assert_eq!(rejected.error_message, "policy not supported");
        // The envelope carries the message; duplicating it into standard_err
        // would print it twice, unseparated, ahead of the JSON.
        assert!(rejected.standard_err.is_empty());
    }

    #[test]
    fn a_phased_failure_takes_its_exit_code_from_the_phase() {
        let launch = ScriptResponse::failed(FailurePhase::LaunchFailed, "spawn failed");

        assert_eq!(launch.exit_code, -1);
        assert_eq!(launch.failure_phase, FailurePhase::LaunchFailed);
        assert_eq!(launch.error_message, "spawn failed");
        assert!(launch.standard_err.is_empty());
    }

    #[test]
    fn sandbox_paths_normalize_against_the_root() {
        for (input, expected) in [
            ("/workspace", "/workspace"),
            ("work", "/work"),
            ("./work", "/work"),
            ("a/../b", "/b"),
            ("/x/../y/./z", "/y/z"),
            ("/a//b/", "/a/b"),
            ("../../etc", "/etc"),
            ("", "/"),
            ("/", "/"),
        ] {
            assert_eq!(sandbox_absolute_path(input), expected, "input {input:?}");
        }
    }

    #[test]
    fn directional_network_defaults_deny() {
        assert_eq!(NetworkAction::default(), NetworkAction::Deny);

        let egress = NetworkEgressPolicy::default();
        assert_eq!(egress.default, NetworkAction::Deny);
        assert!(egress.allow.is_empty());
        assert!(egress.deny.is_empty());

        let ingress = NetworkIngressPolicy::default();
        assert_eq!(ingress.default, NetworkAction::Deny);
        assert_eq!(ingress.host_loopback, NetworkAction::Deny);
    }

    fn request_with_paths(readwrite: &[&str], readonly: &[&str]) -> ExecutionRequest {
        ExecutionRequest {
            policy: ContainerPolicy {
                readwrite_paths: readwrite.iter().map(|s| s.to_string()).collect(),
                readonly_paths: readonly.iter().map(|s| s.to_string()).collect(),
                ..Default::default()
            },
            ..Default::default()
        }
    }

    /// Resolve against a fake filesystem: every path in `dirs` is an existing
    /// directory, everything else is not (a file, or nonexistent).
    fn resolve<'a>(
        req: &'a ExecutionRequest,
        dirs: &'a [&'a str],
    ) -> Option<ResolvedWorkingDirectory<'a>> {
        req.resolved_working_directory_with(|path| dirs.contains(&path))
    }

    #[test]
    fn resolved_working_directory_prefers_explicit_value() {
        let mut req = request_with_paths(&["C:\\rw"], &["C:\\ro"]);
        req.working_directory = "C:\\explicit".to_string();
        let resolved = resolve(&req, &["C:\\rw", "C:\\ro"]).expect("explicit cwd");
        assert_eq!(resolved.path, "C:\\explicit");
        assert_eq!(resolved.source, WorkingDirectorySource::Explicit);
    }

    /// An explicit cwd is the caller's own choice, so it is returned unchecked
    /// rather than silently swapped for a policy path when it does not exist.
    #[test]
    fn resolved_working_directory_returns_explicit_value_unchecked() {
        let mut req = request_with_paths(&["C:\\rw"], &[]);
        req.working_directory = "C:\\does-not-exist".to_string();
        let resolved = resolve(&req, &["C:\\rw"]).expect("explicit cwd");
        assert_eq!(resolved.path, "C:\\does-not-exist");
        assert_eq!(resolved.source, WorkingDirectorySource::Explicit);
    }

    #[test]
    fn resolved_working_directory_falls_back_to_first_readwrite() {
        let req = request_with_paths(&["C:\\rw1", "C:\\rw2"], &["C:\\ro"]);
        let resolved = resolve(&req, &["C:\\rw1", "C:\\rw2", "C:\\ro"]).expect("policy path");
        assert_eq!(resolved.path, "C:\\rw1");
        assert_eq!(resolved.source, WorkingDirectorySource::Policy);
    }

    #[test]
    fn resolved_working_directory_falls_back_to_first_readonly() {
        let req = request_with_paths(&[], &["C:\\ro1", "C:\\ro2"]);
        let resolved = resolve(&req, &["C:\\ro1", "C:\\ro2"]).expect("policy path");
        assert_eq!(resolved.path, "C:\\ro1");
        assert_eq!(resolved.source, WorkingDirectorySource::Policy);
    }

    #[test]
    fn resolved_working_directory_none_when_no_dir_and_no_paths() {
        let req = request_with_paths(&[], &[]);
        assert_eq!(resolve(&req, &[]), None);
    }

    /// Policy grants may name individual files; `CreateProcessW` fails with
    /// `ERROR_DIRECTORY` on one, so files must be skipped.
    #[test]
    fn resolved_working_directory_skips_policy_files() {
        let req = request_with_paths(&["C:\\inputs\\config.json", "C:\\workspace"], &[]);
        let resolved = resolve(&req, &["C:\\workspace"]).expect("policy path");
        assert_eq!(resolved.path, "C:\\workspace");
    }

    /// A grant for a directory the caller intends to create later must not be
    /// used as the cwd — the launch would fail before it could be created.
    #[test]
    fn resolved_working_directory_skips_nonexistent_policy_paths() {
        let req = request_with_paths(&["C:\\not-yet"], &["C:\\ro"]);
        let resolved = resolve(&req, &["C:\\ro"]).expect("policy path");
        assert_eq!(resolved.path, "C:\\ro");
    }

    #[test]
    fn resolved_working_directory_skips_blank_entries() {
        let req = request_with_paths(&["", "   "], &[]);
        assert_eq!(resolve(&req, &["", "   "]), None);
    }

    /// A whitespace-only `process.cwd` is not a caller choice; fall through to
    /// the policy rather than treating it as an explicit directory.
    #[test]
    fn resolved_working_directory_ignores_blank_explicit_value() {
        let mut req = request_with_paths(&["C:\\rw"], &[]);
        req.working_directory = "   ".to_string();
        let resolved = resolve(&req, &["C:\\rw"]).expect("policy path");
        assert_eq!(resolved.path, "C:\\rw");
        assert_eq!(resolved.source, WorkingDirectorySource::Policy);
    }

    #[test]
    fn resolved_working_directory_none_when_no_policy_path_is_a_directory() {
        let req = request_with_paths(&["C:\\a.txt"], &["C:\\b.txt"]);
        assert_eq!(resolve(&req, &[]), None);
    }

    /// Covers the real (non-injected) filesystem probe used in production.
    #[test]
    fn resolved_working_directory_probes_the_real_filesystem() {
        let temp_dir = std::env::temp_dir().to_string_lossy().into_owned();
        let missing = std::env::temp_dir()
            .join("mxc-resolver-nonexistent-4f1c9a")
            .to_string_lossy()
            .into_owned();
        let req = request_with_paths(&[&missing], &[&temp_dir]);
        let resolved = req.resolved_working_directory().expect("policy path");
        assert_eq!(resolved.path, temp_dir);
        assert_eq!(resolved.source, WorkingDirectorySource::Policy);
    }

    #[test]
    fn script_response_backend_unavailable_round_trips() {
        let r = ScriptResponse {
            failure_phase: FailurePhase::BackendUnavailable,
            ..Default::default()
        };
        let json = serde_json::to_string(&r).unwrap();
        let back: ScriptResponse = serde_json::from_str(&json).unwrap();
        assert_eq!(back.failure_phase, FailurePhase::BackendUnavailable);
        // An omitted failure_phase still defaults to None.
        let defaulted: ScriptResponse = serde_json::from_str("{}").unwrap();
        assert_eq!(defaulted.failure_phase, FailurePhase::None);
    }

    #[test]
    fn failure_phase_serde_round_trips_all_variants() {
        let cases = [
            (FailurePhase::None, "\"None\""),
            (FailurePhase::LaunchFailed, "\"LaunchFailed\""),
            (FailurePhase::Rejected, "\"Rejected\""),
            (FailurePhase::PostLaunchFailed, "\"PostLaunchFailed\""),
            (FailurePhase::ProcessExited, "\"ProcessExited\""),
            (FailurePhase::Timeout, "\"Timeout\""),
            (FailurePhase::BackendUnavailable, "\"BackendUnavailable\""),
        ];
        for (variant, wire) in cases {
            let s = serde_json::to_string(&variant).unwrap();
            assert_eq!(s, wire, "serialize {variant:?}");
            let back: FailurePhase = serde_json::from_str(wire).unwrap();
            assert_eq!(back, variant, "round-trip {wire}");
        }
    }
    #[test]
    fn capture_denials_output_omits_unretained_etl_path() {
        let output = CaptureDenialsOutput {
            kind: CaptureDenialsOutput::KIND.to_string(),
            output_path: "denials.json".to_string(),
            exit_code: 0,
            total_denials: 1,
            denied_resources_truncated: false,
            etl_path: None,
        };

        let value = serde_json::to_value(output).unwrap();
        assert!(value.get("etlPath").is_none());
    }

    #[test]
    fn capture_denials_output_serializes_retained_etl_path() {
        let output = CaptureDenialsOutput {
            kind: CaptureDenialsOutput::KIND.to_string(),
            output_path: "denials.json".to_string(),
            exit_code: 0,
            total_denials: 1,
            denied_resources_truncated: false,
            etl_path: Some("capture.etl".to_string()),
        };

        let value = serde_json::to_value(output).unwrap();
        assert_eq!(value["etlPath"], "capture.etl");
    }

    #[test]
    fn capture_denials_error_serializes_retained_etl_path() {
        let metadata = SandboxOutputMetadata {
            capture_denials: None,
            capture_denials_error: Some(CaptureDenialsErrorOutput {
                message: "decode failed".to_string(),
                etl_path: "capture.etl".to_string(),
            }),
        };

        let value = serde_json::to_value(metadata).expect("serialize metadata");
        assert_eq!(value["captureDenialsError"]["message"], "decode failed");
        assert_eq!(value["captureDenialsError"]["etlPath"], "capture.etl");
    }
}