vtcode-core 0.103.3

Core library for VT Code - a Rust-based terminal coding agent
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
//! Sandbox policy definitions
//!
//! Defines the isolation levels for command execution, following the Codex model.
//! Implements the "three-question model" from the AI sandbox field guide:
//! - **Boundary**: What is shared between code and host (kernel-enforced via Seatbelt/Landlock)
//! - **Policy**: What can code touch (files, network, devices, syscalls)
//! - **Lifecycle**: What survives between runs (session-scoped approvals)

use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

/// A root directory that may be written to under the sandbox policy.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct WritableRoot {
    /// Absolute path to the writable directory.
    pub root: PathBuf,
}

impl WritableRoot {
    /// Create a new writable root from a path.
    pub fn new(path: impl Into<PathBuf>) -> Self {
        Self { root: path.into() }
    }
}

/// Network allowlist entry for domain-based egress control.
///
/// Following the field guide's recommendation: "Default-deny outbound network, then allowlist."
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct NetworkAllowlistEntry {
    /// Domain pattern (e.g., "api.github.com", "*.npmjs.org")
    pub domain: String,
    /// Optional port (defaults to 443 for HTTPS)
    #[serde(default = "default_https_port")]
    pub port: u16,
    /// Protocol (tcp or udp, defaults to tcp)
    #[serde(default = "default_protocol")]
    pub protocol: String,
}

fn default_https_port() -> u16 {
    443
}

fn default_protocol() -> String {
    "tcp".to_string()
}

impl NetworkAllowlistEntry {
    /// Create a new allowlist entry for HTTPS access to a domain.
    pub fn https(domain: impl Into<String>) -> Self {
        Self {
            domain: domain.into(),
            port: 443,
            protocol: "tcp".to_string(),
        }
    }

    /// Create a new allowlist entry with custom port.
    pub fn with_port(domain: impl Into<String>, port: u16) -> Self {
        Self {
            domain: domain.into(),
            port,
            protocol: "tcp".to_string(),
        }
    }

    /// Check if a domain matches this entry (supports wildcard prefix).
    pub fn matches(&self, domain: &str, port: u16) -> bool {
        if self.port != port {
            return false;
        }
        if self.domain.starts_with("*.") {
            let suffix = &self.domain[1..]; // Keep the dot
            domain.ends_with(suffix) || domain == &self.domain[2..]
        } else {
            domain == self.domain
        }
    }
}

/// Default sensitive paths that should be blocked from sandboxed processes.
///
/// Following the field guide's warning about "policy leakage":
/// "If your sandbox can read ~/.ssh or mount host volumes, it can leak credentials."
pub const DEFAULT_SENSITIVE_PATHS: &[&str] = &[
    // SSH keys and configuration
    "~/.ssh",
    // AWS credentials
    "~/.aws",
    // Google Cloud credentials
    "~/.config/gcloud",
    // Azure credentials
    "~/.azure",
    // Kubernetes config (contains cluster credentials)
    "~/.kube",
    // Docker config (may contain registry auth)
    "~/.docker",
    // NPM tokens
    "~/.npmrc",
    // PyPI tokens
    "~/.pypirc",
    // GitHub CLI tokens
    "~/.config/gh",
    // Generic secrets directory
    "~/.secrets",
    // Gnupg keys
    "~/.gnupg",
    // 1Password CLI
    "~/.config/op",
    // Vault tokens
    "~/.vault-token",
    // Terraform credentials
    "~/.terraform.d/credentials.tfrc.json",
    // Cargo registry tokens
    "~/.cargo/credentials.toml",
    // Git credentials
    "~/.git-credentials",
    // Netrc (may contain passwords)
    "~/.netrc",
];

#[cfg(windows)]
const USERPROFILE_READ_ROOT_EXCLUSIONS: &[&str] = &[
    ".ssh",
    ".gnupg",
    ".aws",
    ".azure",
    ".kube",
    ".docker",
    ".config",
    ".npm",
    ".pki",
    ".terraform.d",
];

/// Sensitive path entry for blocking access to credential locations.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct SensitivePath {
    /// Path pattern (supports ~ for home directory)
    pub path: String,
    /// Whether to block read access (true by default)
    #[serde(default = "default_true")]
    pub block_read: bool,
    /// Whether to block write access (true by default)
    #[serde(default = "default_true")]
    pub block_write: bool,
}

fn default_true() -> bool {
    true
}

impl SensitivePath {
    /// Create a new sensitive path entry that blocks both read and write.
    pub fn new(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            block_read: true,
            block_write: true,
        }
    }

    /// Create a sensitive path entry that only blocks write access.
    pub fn write_only(path: impl Into<String>) -> Self {
        Self {
            path: path.into(),
            block_read: false,
            block_write: true,
        }
    }

    /// Expand ~ to the user's home directory.
    pub fn expand_path(&self) -> PathBuf {
        if self.path.starts_with("~/")
            && let Some(home) = dirs::home_dir()
        {
            return home.join(&self.path[2..]);
        } else if self.path == "~"
            && let Some(home) = dirs::home_dir()
        {
            return home;
        }
        PathBuf::from(&self.path)
    }

    /// Check if a given path matches this sensitive path pattern.
    pub fn matches(&self, path: &Path) -> bool {
        let expanded = self.expand_path();
        #[cfg(windows)]
        {
            let path_norm = normalize_windows_path(path);
            let expanded_norm = normalize_windows_path(&expanded);
            let mut expanded_prefix = expanded_norm.clone();
            if !expanded_prefix.ends_with('/') {
                expanded_prefix.push('/');
            }
            return path_norm == expanded_norm || path_norm.starts_with(&expanded_prefix);
        }
        path.starts_with(&expanded)
    }
}

#[cfg(windows)]
fn normalize_windows_path(path: &Path) -> String {
    path.to_string_lossy()
        .replace('\\', "/")
        .to_ascii_lowercase()
}

/// Get the default sensitive paths as SensitivePath entries.
pub fn default_sensitive_paths() -> Vec<SensitivePath> {
    let paths: Vec<SensitivePath> = DEFAULT_SENSITIVE_PATHS
        .iter()
        .map(|p| SensitivePath::new(*p))
        .collect();

    #[cfg(windows)]
    {
        let mut paths = paths;
        for entry in USERPROFILE_READ_ROOT_EXCLUSIONS {
            let path = format!("~/{}", entry);
            if !paths.iter().any(|existing| existing.path == path) {
                paths.push(SensitivePath::new(path));
            }
        }
        paths
    }

    #[cfg(not(windows))]
    paths
}

const PROTECTED_WRITABLE_ROOT_DIR_NAMES: &[&str] = &[".git", ".vtcode", ".codex", ".agents"];

fn protected_writable_root_sensitive_paths(writable_roots: &[WritableRoot]) -> Vec<SensitivePath> {
    let mut paths = Vec::new();

    for root in writable_roots {
        for dir_name in PROTECTED_WRITABLE_ROOT_DIR_NAMES {
            let protected_path = root.root.join(dir_name).display().to_string();
            if !paths.iter().any(|existing: &SensitivePath| {
                existing.path == protected_path && !existing.block_read && existing.block_write
            }) {
                paths.push(SensitivePath::write_only(protected_path));
            }
        }
    }

    paths
}

/// Resource limits for sandboxed execution.
///
/// Following the field guide's recommendation for resource accounting:
/// "CPU, memory, disk, timeouts, and PIDs."
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResourceLimits {
    /// Maximum memory usage in megabytes (0 = unlimited).
    #[serde(default)]
    pub max_memory_mb: u64,

    /// Maximum number of processes/threads (0 = unlimited).
    /// Prevents fork bombs.
    #[serde(default)]
    pub max_pids: u32,

    /// Maximum disk write in megabytes (0 = unlimited).
    #[serde(default)]
    pub max_disk_mb: u64,

    /// CPU time limit in seconds (0 = unlimited).
    #[serde(default)]
    pub cpu_time_secs: u64,

    /// Wall clock timeout in seconds (0 = use default).
    #[serde(default)]
    pub timeout_secs: u64,
}

impl Default for ResourceLimits {
    fn default() -> Self {
        Self {
            max_memory_mb: 0,  // Unlimited by default
            max_pids: 0,       // Unlimited by default
            max_disk_mb: 0,    // Unlimited by default
            cpu_time_secs: 0,  // Unlimited by default
            timeout_secs: 300, // 5 minute wall clock default
        }
    }
}

impl ResourceLimits {
    /// Create new resource limits with all values unlimited.
    pub fn unlimited() -> Self {
        Self {
            max_memory_mb: 0,
            max_pids: 0,
            max_disk_mb: 0,
            cpu_time_secs: 0,
            timeout_secs: 0,
        }
    }

    /// Create conservative limits suitable for untrusted code.
    /// Following field guide: "Resource limits: CPU, memory, disk, timeouts, and PIDs."
    pub fn conservative() -> Self {
        Self {
            max_memory_mb: 512, // 512MB memory
            max_pids: 64,       // 64 processes (prevents fork bombs)
            max_disk_mb: 1024,  // 1GB disk writes
            cpu_time_secs: 60,  // 1 minute CPU time
            timeout_secs: 120,  // 2 minute wall clock
        }
    }

    /// Create moderate limits for semi-trusted code.
    pub fn moderate() -> Self {
        Self {
            max_memory_mb: 2048, // 2GB memory
            max_pids: 256,       // 256 processes
            max_disk_mb: 4096,   // 4GB disk writes
            cpu_time_secs: 300,  // 5 minutes CPU time
            timeout_secs: 600,   // 10 minute wall clock
        }
    }

    /// Create generous limits for trusted internal code.
    pub fn generous() -> Self {
        Self {
            max_memory_mb: 8192, // 8GB memory
            max_pids: 1024,      // 1024 processes
            max_disk_mb: 16384,  // 16GB disk writes
            cpu_time_secs: 0,    // Unlimited CPU time
            timeout_secs: 3600,  // 1 hour wall clock
        }
    }

    /// Builder: set memory limit.
    pub fn with_memory_mb(mut self, mb: u64) -> Self {
        self.max_memory_mb = mb;
        self
    }

    /// Builder: set PID limit.
    pub fn with_max_pids(mut self, pids: u32) -> Self {
        self.max_pids = pids;
        self
    }

    /// Builder: set disk limit.
    pub fn with_disk_mb(mut self, mb: u64) -> Self {
        self.max_disk_mb = mb;
        self
    }

    /// Builder: set CPU time limit.
    pub fn with_cpu_time_secs(mut self, secs: u64) -> Self {
        self.cpu_time_secs = secs;
        self
    }

    /// Builder: set timeout.
    pub fn with_timeout_secs(mut self, secs: u64) -> Self {
        self.timeout_secs = secs;
        self
    }

    /// Check if any limits are set.
    pub fn has_limits(&self) -> bool {
        self.max_memory_mb > 0
            || self.max_pids > 0
            || self.max_disk_mb > 0
            || self.cpu_time_secs > 0
    }

    /// Get the effective timeout in seconds.
    pub fn effective_timeout_secs(&self) -> u64 {
        if self.timeout_secs > 0 {
            self.timeout_secs
        } else {
            300 // Default 5 minutes
        }
    }
}

/// Syscalls that should be blocked in seccomp-bpf profiles.
///
/// Following the field guide: "A tight seccomp profile blocks syscalls that expand
/// kernel attack surface or enable escalation."
pub const BLOCKED_SYSCALLS: &[&str] = &[
    // Debugging/tracing - can be used to escape sandboxes
    "ptrace",
    // Mounting - can change filesystem namespace
    "mount",
    "umount",
    "umount2",
    // Kernel module loading
    "init_module",
    "finit_module",
    "delete_module",
    // Kernel replacement
    "kexec_load",
    "kexec_file_load",
    // BPF - can be used for sandbox escape
    "bpf",
    // Performance events - information leakage risk
    "perf_event_open",
    // Userfaultfd - can be used for race conditions
    "userfaultfd",
    // Process VM operations
    "process_vm_readv",
    "process_vm_writev",
    // Reboot/power
    "reboot",
    // Swap manipulation
    "swapon",
    "swapoff",
    // System time manipulation
    "settimeofday",
    "clock_settime",
    "adjtimex",
    // Keyring manipulation
    "add_key",
    "request_key",
    "keyctl",
    // IO permission
    "ioperm",
    "iopl",
    // Raw I/O port access
    "iopl",
    // Acct - process accounting manipulation
    "acct",
    // Quota manipulation
    "quotactl",
    // Namespace creation (can bypass restrictions)
    "unshare",
    "setns",
    // Personality - can enable legacy modes
    "personality",
];

/// Syscalls that require argument filtering (not fully blocked).
pub const FILTERED_SYSCALLS: &[&str] = &[
    // clone/clone3: filter to prevent new namespaces
    "clone", "clone3", // ioctl: filter to block dangerous device ioctls
    "ioctl",  // prctl: filter to block dangerous operations
    "prctl",  // socket: filter to enforce network policy
    "socket",
];

/// Seccomp profile configuration for Linux sandboxing.
///
/// Used alongside Landlock for defense-in-depth.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct SeccompProfile {
    /// Syscalls to block entirely.
    #[serde(default = "default_blocked_syscalls")]
    pub blocked_syscalls: Vec<String>,

    /// Whether to allow new namespace creation (usually false for sandboxes).
    #[serde(default)]
    pub allow_namespaces: bool,

    /// Whether to allow network socket creation (controlled separately).
    #[serde(default)]
    pub allow_network_sockets: bool,

    /// Whether to log blocked syscalls instead of killing the process.
    #[serde(default)]
    pub log_only: bool,
}

fn default_blocked_syscalls() -> Vec<String> {
    BLOCKED_SYSCALLS.iter().map(|s| s.to_string()).collect()
}

impl Default for SeccompProfile {
    fn default() -> Self {
        Self {
            blocked_syscalls: default_blocked_syscalls(),
            allow_namespaces: false,
            allow_network_sockets: false,
            log_only: false,
        }
    }
}

impl SeccompProfile {
    /// Create a strict profile blocking all dangerous syscalls.
    pub fn strict() -> Self {
        Self {
            blocked_syscalls: default_blocked_syscalls(),
            allow_namespaces: false,
            allow_network_sockets: false,
            log_only: false,
        }
    }

    /// Create a permissive profile for semi-trusted code.
    pub fn permissive() -> Self {
        Self {
            blocked_syscalls: vec![
                "ptrace".to_string(),
                "kexec_load".to_string(),
                "kexec_file_load".to_string(),
                "reboot".to_string(),
            ],
            allow_namespaces: false,
            allow_network_sockets: true,
            log_only: false,
        }
    }

    /// Create a logging-only profile for debugging.
    pub fn logging() -> Self {
        Self {
            blocked_syscalls: default_blocked_syscalls(),
            allow_namespaces: false,
            allow_network_sockets: false,
            log_only: true,
        }
    }

    /// Builder: add a syscall to block.
    pub fn block_syscall(mut self, syscall: impl Into<String>) -> Self {
        let syscall = syscall.into();
        if !self.blocked_syscalls.contains(&syscall) {
            self.blocked_syscalls.push(syscall);
        }
        self
    }

    /// Builder: allow network sockets.
    pub fn with_network(mut self) -> Self {
        self.allow_network_sockets = true;
        self
    }

    /// Builder: enable log-only mode.
    pub fn with_logging(mut self) -> Self {
        self.log_only = true;
        self
    }

    /// Check if a syscall is blocked by this profile.
    pub fn is_blocked(&self, syscall: &str) -> bool {
        self.blocked_syscalls.iter().any(|s| s == syscall)
    }

    /// Generate a JSON representation for the sandbox helper.
    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string(self)
    }
}

/// Sandbox policy determining what operations are permitted during execution.
///
/// This follows the Codex sandboxing model with three main variants:
/// - **ReadOnly**: Only read operations allowed (safe for viewing files)
/// - **WorkspaceWrite**: Can write within specified directories
/// - **DangerFullAccess**: No restrictions (dangerous, requires explicit approval)
///
/// The field guide's three-question model:
/// 1. What is shared between this code and the host? (boundary)
/// 2. What can the code touch? (policy - this enum)
/// 3. What survives between runs? (lifecycle)
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum SandboxPolicy {
    /// No write access to the filesystem; network access may be restricted or allowlisted.
    ReadOnly {
        /// Whether network access is enabled when no allowlist is set.
        #[serde(default)]
        network_access: bool,

        /// Domain-based network egress allowlist.
        #[serde(default)]
        network_allowlist: Vec<NetworkAllowlistEntry>,
    },

    /// Write access limited to the specified roots; network controlled by allowlist.
    WorkspaceWrite {
        /// Directories where write access is permitted.
        writable_roots: Vec<WritableRoot>,

        /// Whether network access is allowed (legacy boolean, use network_allowlist for fine-grained control).
        #[serde(default)]
        network_access: bool,

        /// Domain-based network egress allowlist.
        /// When non-empty, only connections to these destinations are permitted.
        /// Following field guide: "Default-deny outbound network, then allowlist."
        #[serde(default)]
        network_allowlist: Vec<NetworkAllowlistEntry>,

        /// Sensitive paths to block (credentials, SSH keys, cloud configs).
        /// Following field guide: prevents "policy leakage" of credentials.
        /// Defaults to DEFAULT_SENSITIVE_PATHS if None.
        #[serde(default)]
        sensitive_paths: Option<Vec<SensitivePath>>,

        /// Resource limits (memory, PIDs, disk, CPU).
        /// Following field guide: prevents fork bombs, memory exhaustion.
        #[serde(default)]
        resource_limits: ResourceLimits,

        /// Seccomp-BPF profile for Linux syscall filtering.
        /// Following field guide: "Landlock + seccomp is the recommended Linux pattern."
        #[serde(default)]
        seccomp_profile: SeccompProfile,

        /// Exclude the TMPDIR environment variable from writable roots.
        #[serde(default)]
        exclude_tmpdir_env_var: bool,

        /// Exclude /tmp from writable roots.
        #[serde(default)]
        exclude_slash_tmp: bool,
    },

    /// Full access - no sandbox restrictions applied.
    /// Use with extreme caution.
    DangerFullAccess,

    /// External sandbox - the caller is responsible for sandbox setup.
    ExternalSandbox {
        /// Description of the external sandbox mechanism.
        description: String,
    },
}

impl SandboxPolicy {
    /// Create a read-only policy.
    pub fn read_only() -> Self {
        Self::ReadOnly {
            network_access: false,
            network_allowlist: Vec::new(),
        }
    }

    /// Create a new read-only policy (alias for backwards compatibility).
    pub fn new_read_only_policy() -> Self {
        Self::read_only()
    }

    /// Create a read-only policy with a network allowlist.
    pub fn read_only_with_network(network_allowlist: Vec<NetworkAllowlistEntry>) -> Self {
        Self::ReadOnly {
            network_access: !network_allowlist.is_empty(),
            network_allowlist,
        }
    }

    /// Create a read-only policy with full network access.
    pub fn read_only_with_full_network() -> Self {
        Self::ReadOnly {
            network_access: true,
            network_allowlist: Vec::new(),
        }
    }

    /// Create a workspace-write policy with specified roots.
    /// Uses default sensitive path blocking and strict seccomp profile.
    pub fn workspace_write(writable_roots: Vec<PathBuf>) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: false,
            network_allowlist: Vec::new(),
            sensitive_paths: None, // Uses defaults
            resource_limits: ResourceLimits::default(),
            seccomp_profile: SeccompProfile::strict(),
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a workspace-write policy with network allowlist.
    pub fn workspace_write_with_network(
        writable_roots: Vec<PathBuf>,
        network_allowlist: Vec<NetworkAllowlistEntry>,
    ) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: !network_allowlist.is_empty(),
            network_allowlist,
            sensitive_paths: None, // Uses defaults
            resource_limits: ResourceLimits::default(),
            seccomp_profile: SeccompProfile::strict().with_network(),
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a workspace-write policy with custom sensitive path settings.
    pub fn workspace_write_with_sensitive_paths(
        writable_roots: Vec<PathBuf>,
        sensitive_paths: Vec<SensitivePath>,
    ) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: false,
            network_allowlist: Vec::new(),
            sensitive_paths: Some(sensitive_paths),
            resource_limits: ResourceLimits::default(),
            seccomp_profile: SeccompProfile::strict(),
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a workspace-write policy without sensitive path blocking (dangerous).
    pub fn workspace_write_no_sensitive_blocking(writable_roots: Vec<PathBuf>) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: false,
            network_allowlist: Vec::new(),
            sensitive_paths: Some(Vec::new()), // Explicitly empty
            resource_limits: ResourceLimits::default(),
            seccomp_profile: SeccompProfile::strict(),
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a workspace-write policy with resource limits.
    /// Useful for untrusted code that needs containment.
    pub fn workspace_write_with_limits(
        writable_roots: Vec<PathBuf>,
        resource_limits: ResourceLimits,
    ) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: false,
            network_allowlist: Vec::new(),
            sensitive_paths: None,
            resource_limits,
            seccomp_profile: SeccompProfile::strict(),
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a fully-configured workspace-write policy.
    pub fn workspace_write_full(
        writable_roots: Vec<PathBuf>,
        network_allowlist: Vec<NetworkAllowlistEntry>,
        sensitive_paths: Option<Vec<SensitivePath>>,
        resource_limits: ResourceLimits,
        seccomp_profile: SeccompProfile,
    ) -> Self {
        Self::WorkspaceWrite {
            writable_roots: writable_roots.into_iter().map(WritableRoot::new).collect(),
            network_access: !network_allowlist.is_empty(),
            network_allowlist,
            sensitive_paths,
            resource_limits,
            seccomp_profile,
            exclude_tmpdir_env_var: true,
            exclude_slash_tmp: true,
        }
    }

    /// Create a full-access policy (dangerous).
    pub fn full_access() -> Self {
        Self::DangerFullAccess
    }

    /// Check if the policy allows full network access (unrestricted).
    pub fn has_full_network_access(&self) -> bool {
        match self {
            Self::ReadOnly {
                network_access,
                network_allowlist,
            }
            | Self::WorkspaceWrite {
                network_access,
                network_allowlist,
                ..
            } => *network_access && network_allowlist.is_empty(),
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
        }
    }

    /// Check if the policy has a network allowlist (domain-restricted access).
    pub fn has_network_allowlist(&self) -> bool {
        match self {
            Self::ReadOnly {
                network_allowlist, ..
            }
            | Self::WorkspaceWrite {
                network_allowlist, ..
            } => !network_allowlist.is_empty(),
            _ => false,
        }
    }

    /// Get the network allowlist entries, if any.
    pub fn network_allowlist(&self) -> &[NetworkAllowlistEntry] {
        match self {
            Self::ReadOnly {
                network_allowlist, ..
            }
            | Self::WorkspaceWrite {
                network_allowlist, ..
            } => network_allowlist,
            _ => &[],
        }
    }

    /// Check if network access to a specific domain:port is allowed.
    pub fn is_network_allowed(&self, domain: &str, port: u16) -> bool {
        match self {
            Self::ReadOnly {
                network_access,
                network_allowlist,
            }
            | Self::WorkspaceWrite {
                network_access,
                network_allowlist,
                ..
            } => {
                if network_allowlist.is_empty() {
                    // Legacy behavior: binary network_access flag
                    *network_access
                } else {
                    // Allowlist-based access control
                    network_allowlist
                        .iter()
                        .any(|entry| entry.matches(domain, port))
                }
            }
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
        }
    }

    /// Get the effective sensitive paths to block.
    /// Returns default paths if not explicitly configured.
    pub fn sensitive_paths(&self) -> Vec<SensitivePath> {
        match self {
            Self::ReadOnly { .. } => default_sensitive_paths(),
            Self::WorkspaceWrite {
                sensitive_paths, ..
            } => sensitive_paths
                .clone()
                .unwrap_or_else(default_sensitive_paths),
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => Vec::new(),
        }
    }

    /// Get sensitive paths including write-only protected directories for writable roots.
    pub fn sensitive_paths_for_execution(&self, cwd: &Path) -> Vec<SensitivePath> {
        match self {
            Self::WorkspaceWrite { .. } => {
                let mut sensitive_paths = self.sensitive_paths();
                sensitive_paths.extend(protected_writable_root_sensitive_paths(
                    &self.get_writable_roots_with_cwd(cwd),
                ));
                sensitive_paths
            }
            _ => self.sensitive_paths(),
        }
    }

    /// Check if a path is a sensitive location that should be blocked.
    pub fn is_sensitive_path(&self, path: &Path) -> bool {
        self.sensitive_paths()
            .iter()
            .any(|sp| sp.matches(path) && sp.block_read)
    }

    /// Check if write access to a path is blocked under this policy.
    pub fn is_path_write_blocked(&self, path: &Path, cwd: &Path) -> bool {
        match self {
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => false,
            _ => self
                .sensitive_paths_for_execution(cwd)
                .iter()
                .any(|sp| sp.matches(path) && sp.block_write),
        }
    }

    /// Check if read access to a path is allowed under this policy.
    /// Returns false if the path is in the sensitive paths list.
    pub fn is_path_readable(&self, path: &Path) -> bool {
        match self {
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
            _ => !self.is_sensitive_path(path),
        }
    }

    /// Get the resource limits for this policy.
    pub fn resource_limits(&self) -> ResourceLimits {
        match self {
            Self::ReadOnly { .. } => ResourceLimits::conservative(),
            Self::WorkspaceWrite {
                resource_limits, ..
            } => resource_limits.clone(),
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => ResourceLimits::unlimited(),
        }
    }

    /// Get the seccomp profile for this policy (Linux only).
    pub fn seccomp_profile(&self) -> SeccompProfile {
        match self {
            Self::ReadOnly {
                network_access,
                network_allowlist,
            } => {
                let mut profile = SeccompProfile::strict();
                if *network_access || !network_allowlist.is_empty() {
                    profile = profile.with_network();
                }
                profile
            }
            Self::WorkspaceWrite {
                seccomp_profile, ..
            } => seccomp_profile.clone(),
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => SeccompProfile::permissive(),
        }
    }

    /// Check if the policy allows full disk write access.
    pub fn has_full_disk_write_access(&self) -> bool {
        matches!(self, Self::DangerFullAccess | Self::ExternalSandbox { .. })
    }

    /// Check if the policy allows full disk read access.
    pub fn has_full_disk_read_access(&self) -> bool {
        // All policies allow read access
        true
    }

    /// Get the list of writable roots including the current working directory.
    pub fn get_writable_roots_with_cwd(&self, cwd: &Path) -> Vec<WritableRoot> {
        match self {
            Self::ReadOnly { .. } => vec![],
            Self::WorkspaceWrite { writable_roots, .. } => {
                let mut roots = writable_roots.clone();
                // Add cwd if not already included
                let cwd_root = WritableRoot::new(cwd);
                if !roots.contains(&cwd_root) {
                    roots.push(cwd_root);
                }
                roots
            }
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => {
                // Full access - return cwd as a formality
                vec![WritableRoot::new(cwd)]
            }
        }
    }

    /// Check if a path is writable under this policy.
    pub fn is_path_writable(&self, path: &Path, cwd: &Path) -> bool {
        match self {
            Self::ReadOnly { .. } => false,
            Self::WorkspaceWrite { .. } => {
                let writable = self.get_writable_roots_with_cwd(cwd);
                writable.iter().any(|root| path.starts_with(&root.root))
                    && !self.is_path_write_blocked(path, cwd)
            }
            Self::DangerFullAccess | Self::ExternalSandbox { .. } => true,
        }
    }

    /// Validate that another policy can be set from this one.
    /// Used to enforce policy escalation restrictions.
    pub fn can_set(&self, new_policy: &SandboxPolicy) -> anyhow::Result<()> {
        use SandboxPolicy::*;

        match (self, new_policy) {
            // Can always downgrade
            (DangerFullAccess, _) => Ok(()),
            // Cannot escalate from ReadOnly to write-capable
            (ReadOnly { .. }, WorkspaceWrite { .. } | DangerFullAccess) => Err(anyhow::anyhow!(
                "cannot escalate from read-only to write-capable policy"
            )),
            // Other transitions are allowed
            _ => Ok(()),
        }
    }

    /// Get a human-readable description of the policy.
    pub fn description(&self) -> &'static str {
        match self {
            Self::ReadOnly { .. } => "read-only access",
            Self::WorkspaceWrite { .. } => "workspace write access",
            Self::DangerFullAccess => "full access (dangerous)",
            Self::ExternalSandbox { .. } => "external sandbox",
        }
    }
}

impl Default for SandboxPolicy {
    fn default() -> Self {
        Self::read_only()
    }
}

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

    #[test]
    fn test_read_only_policy() {
        let policy = SandboxPolicy::read_only();
        assert!(!policy.has_full_network_access());
        assert!(!policy.has_network_allowlist());
        assert!(!policy.has_full_disk_write_access());
        assert!(policy.has_full_disk_read_access());
    }

    #[test]
    fn test_read_only_with_network_allowlist() {
        let policy = SandboxPolicy::read_only_with_network(vec![
            NetworkAllowlistEntry::https("api.github.com"),
            NetworkAllowlistEntry::with_port("registry.npmjs.org", 443),
        ]);

        assert!(!policy.has_full_network_access());
        assert!(policy.has_network_allowlist());
        assert!(policy.is_network_allowed("api.github.com", 443));
        assert!(policy.is_network_allowed("registry.npmjs.org", 443));
        assert!(!policy.is_network_allowed("example.com", 443));
    }

    #[test]
    fn test_read_only_with_full_network_access() {
        let policy = SandboxPolicy::read_only_with_full_network();

        assert!(policy.has_full_network_access());
        assert!(policy.is_network_allowed("example.com", 443));
        assert!(policy.seccomp_profile().allow_network_sockets);
    }

    #[test]
    fn test_read_only_deserializes_legacy_shape() {
        let policy: SandboxPolicy =
            serde_json::from_str(r#"{"type":"read_only"}"#).expect("legacy read-only policy");

        assert_eq!(policy, SandboxPolicy::read_only());
    }

    #[test]
    fn test_workspace_write_policy() {
        let policy = SandboxPolicy::workspace_write(vec![PathBuf::from("/tmp/workspace")]);
        assert!(!policy.has_full_network_access());
        assert!(!policy.has_full_disk_write_access());

        let cwd = PathBuf::from("/tmp/workspace");
        assert!(policy.is_path_writable(&cwd, &cwd));
        assert!(!policy.is_path_writable(&PathBuf::from("/etc"), &cwd));
    }

    #[test]
    fn test_workspace_write_protects_internal_metadata_dirs() {
        let cwd = PathBuf::from("/tmp/workspace");
        let policy = SandboxPolicy::workspace_write(vec![cwd.clone()]);

        assert!(!policy.is_path_writable(&cwd.join(".git/config"), &cwd));
        assert!(!policy.is_path_writable(&cwd.join(".vtcode/cache"), &cwd));
        assert!(!policy.is_path_writable(&cwd.join(".codex/state"), &cwd));
        assert!(!policy.is_path_writable(&cwd.join(".agents/skills"), &cwd));
        assert!(policy.is_path_writable(&cwd.join("src/main.rs"), &cwd));
    }

    #[test]
    fn test_full_access_policy() {
        let policy = SandboxPolicy::full_access();
        assert!(policy.has_full_network_access());
        assert!(policy.has_full_disk_write_access());
    }

    #[test]
    fn test_policy_escalation() {
        let read_only = SandboxPolicy::read_only();
        let full = SandboxPolicy::full_access();

        // Cannot escalate from read-only
        assert!(read_only.can_set(&full).is_err());

        // Can downgrade from full
        assert!(full.can_set(&read_only).is_ok());
    }

    #[test]
    fn test_network_allowlist_entry_matching() {
        let entry = NetworkAllowlistEntry::https("api.github.com");
        assert!(entry.matches("api.github.com", 443));
        assert!(!entry.matches("api.github.com", 80));
        assert!(!entry.matches("github.com", 443));
    }

    #[test]
    fn test_network_allowlist_wildcard() {
        let entry = NetworkAllowlistEntry::https("*.npmjs.org");
        assert!(entry.matches("registry.npmjs.org", 443));
        assert!(entry.matches("npmjs.org", 443));
        assert!(!entry.matches("npmjs.org.evil.com", 443));
    }

    #[test]
    fn test_workspace_with_network_allowlist() {
        let allowlist = vec![
            NetworkAllowlistEntry::https("api.github.com"),
            NetworkAllowlistEntry::https("*.npmjs.org"),
        ];
        let policy = SandboxPolicy::workspace_write_with_network(
            vec![PathBuf::from("/tmp/workspace")],
            allowlist,
        );

        // Has allowlist, not full access
        assert!(!policy.has_full_network_access());
        assert!(policy.has_network_allowlist());

        // Domain checks
        assert!(policy.is_network_allowed("api.github.com", 443));
        assert!(policy.is_network_allowed("registry.npmjs.org", 443));
        assert!(!policy.is_network_allowed("evil.com", 443));
        assert!(!policy.is_network_allowed("api.github.com", 80));
    }

    #[test]
    fn test_workspace_no_network() {
        let policy = SandboxPolicy::workspace_write(vec![PathBuf::from("/tmp/workspace")]);

        assert!(!policy.has_full_network_access());
        assert!(!policy.has_network_allowlist());
        assert!(!policy.is_network_allowed("api.github.com", 443));
    }

    #[test]
    fn test_sensitive_path_expansion() {
        let sp = SensitivePath::new("~/.ssh");
        let expanded = sp.expand_path();
        // Should expand to home directory
        assert!(expanded.to_string_lossy().contains(".ssh"));
        assert!(!expanded.to_string_lossy().starts_with('~'));
    }

    #[test]
    fn test_sensitive_path_matching() {
        let sp = SensitivePath::new("~/.ssh");
        let expanded = sp.expand_path();
        let ssh_key = expanded.join("id_rsa");
        assert!(sp.matches(&ssh_key));
        assert!(sp.matches(&expanded));
    }

    #[test]
    fn test_default_sensitive_paths() {
        let paths = default_sensitive_paths();
        assert!(!paths.is_empty());
        // Should include common credential locations
        let path_strings: Vec<&str> = paths.iter().map(|p| p.path.as_str()).collect();
        assert!(path_strings.contains(&"~/.ssh"));
        assert!(path_strings.contains(&"~/.aws"));
        assert!(path_strings.contains(&"~/.kube"));
    }

    #[cfg(windows)]
    #[test]
    fn test_windows_userprofile_root_exclusions_are_in_defaults() {
        let paths = default_sensitive_paths();
        let path_strings: Vec<&str> = paths.iter().map(|p| p.path.as_str()).collect();

        for entry in USERPROFILE_READ_ROOT_EXCLUSIONS {
            let expected = format!("~/{}", entry);
            assert!(
                path_strings.contains(&expected.as_str()),
                "missing expected default sensitive path: {expected}"
            );
        }
    }

    #[cfg(windows)]
    #[test]
    fn test_sensitive_path_matching_is_case_insensitive_on_windows() {
        let sp = SensitivePath::new("~/.aws");
        let home = dirs::home_dir().expect("home dir");
        let mixed_case_candidate = home.join(".AWS").join("credentials");

        assert!(sp.matches(&mixed_case_candidate));
    }

    #[test]
    fn test_workspace_blocks_sensitive_by_default() {
        let policy = SandboxPolicy::workspace_write(vec![PathBuf::from("/tmp/workspace")]);
        let sensitive = policy.sensitive_paths();
        assert!(!sensitive.is_empty());

        // Check that SSH keys are blocked
        if let Some(home) = dirs::home_dir() {
            let ssh_path = home.join(".ssh").join("id_rsa");
            assert!(policy.is_sensitive_path(&ssh_path));
            assert!(!policy.is_path_readable(&ssh_path));
        }
    }

    #[test]
    fn test_workspace_no_sensitive_blocking() {
        let policy =
            SandboxPolicy::workspace_write_no_sensitive_blocking(vec![PathBuf::from("/tmp")]);
        let sensitive = policy.sensitive_paths();
        assert!(sensitive.is_empty());

        // Nothing should be blocked
        if let Some(home) = dirs::home_dir() {
            let ssh_path = home.join(".ssh").join("id_rsa");
            assert!(!policy.is_sensitive_path(&ssh_path));
            assert!(policy.is_path_readable(&ssh_path));
        }
    }

    #[test]
    fn test_full_access_no_sensitive_blocking() {
        let policy = SandboxPolicy::full_access();
        let sensitive = policy.sensitive_paths();
        assert!(sensitive.is_empty());

        // Full access should allow everything
        if let Some(home) = dirs::home_dir() {
            let ssh_path = home.join(".ssh").join("id_rsa");
            assert!(policy.is_path_readable(&ssh_path));
        }
    }

    #[test]
    fn test_resource_limits_default() {
        let limits = ResourceLimits::default();
        assert_eq!(limits.max_memory_mb, 0);
        assert_eq!(limits.max_pids, 0);
        assert_eq!(limits.timeout_secs, 300);
        assert!(!limits.has_limits());
    }

    #[test]
    fn test_resource_limits_conservative() {
        let limits = ResourceLimits::conservative();
        assert_eq!(limits.max_memory_mb, 512);
        assert_eq!(limits.max_pids, 64);
        assert_eq!(limits.cpu_time_secs, 60);
        assert!(limits.has_limits());
    }

    #[test]
    fn test_resource_limits_builder() {
        let limits = ResourceLimits::default()
            .with_memory_mb(1024)
            .with_max_pids(128)
            .with_timeout_secs(60);
        assert_eq!(limits.max_memory_mb, 1024);
        assert_eq!(limits.max_pids, 128);
        assert_eq!(limits.effective_timeout_secs(), 60);
    }

    #[test]
    fn test_workspace_with_limits() {
        let limits = ResourceLimits::conservative();
        let policy = SandboxPolicy::workspace_write_with_limits(
            vec![PathBuf::from("/tmp/workspace")],
            limits.clone(),
        );

        let policy_limits = policy.resource_limits();
        assert_eq!(policy_limits.max_memory_mb, limits.max_memory_mb);
        assert_eq!(policy_limits.max_pids, limits.max_pids);
    }

    #[test]
    fn test_read_only_conservative_limits() {
        let policy = SandboxPolicy::read_only();
        let limits = policy.resource_limits();
        // ReadOnly should get conservative limits
        assert!(limits.has_limits());
        assert_eq!(limits.max_memory_mb, 512);
    }

    #[test]
    fn test_full_access_unlimited() {
        let policy = SandboxPolicy::full_access();
        let limits = policy.resource_limits();
        // Full access should have no limits
        assert!(!limits.has_limits());
    }

    #[test]
    fn test_seccomp_profile_strict() {
        let profile = SeccompProfile::strict();
        assert!(profile.is_blocked("ptrace"));
        assert!(profile.is_blocked("mount"));
        assert!(profile.is_blocked("kexec_load"));
        assert!(profile.is_blocked("bpf"));
        assert!(!profile.allow_network_sockets);
        assert!(!profile.allow_namespaces);
    }

    #[test]
    fn test_seccomp_profile_permissive() {
        let profile = SeccompProfile::permissive();
        // Still blocks the most dangerous syscalls
        assert!(profile.is_blocked("ptrace"));
        assert!(profile.is_blocked("kexec_load"));
        // But allows network
        assert!(profile.allow_network_sockets);
    }

    #[test]
    fn test_seccomp_profile_builder() {
        let profile = SeccompProfile::strict()
            .with_network()
            .block_syscall("custom_syscall");
        assert!(profile.allow_network_sockets);
        assert!(profile.is_blocked("custom_syscall"));
    }

    #[test]
    fn test_workspace_seccomp_profile() {
        let policy = SandboxPolicy::workspace_write(vec![PathBuf::from("/tmp")]);
        let profile = policy.seccomp_profile();
        // Should get strict profile by default
        assert!(profile.is_blocked("ptrace"));
        assert!(profile.is_blocked("mount"));
    }

    #[test]
    fn test_workspace_with_network_seccomp() {
        let policy = SandboxPolicy::workspace_write_with_network(
            vec![PathBuf::from("/tmp")],
            vec![NetworkAllowlistEntry::https("api.github.com")],
        );
        let profile = policy.seccomp_profile();
        // Should allow network sockets when network is enabled
        assert!(profile.allow_network_sockets);
    }

    #[test]
    fn test_seccomp_profile_json() {
        let profile = SeccompProfile::strict();
        let json = profile.to_json().unwrap();
        assert!(json.contains("ptrace"));
        assert!(json.contains("blocked_syscalls"));
    }

    #[test]
    fn test_blocked_syscalls_constant() {
        // Verify key dangerous syscalls are in the list
        assert!(BLOCKED_SYSCALLS.contains(&"ptrace"));
        assert!(BLOCKED_SYSCALLS.contains(&"mount"));
        assert!(BLOCKED_SYSCALLS.contains(&"kexec_load"));
        assert!(BLOCKED_SYSCALLS.contains(&"bpf"));
        assert!(BLOCKED_SYSCALLS.contains(&"perf_event_open"));
    }
}