agentkernel 0.18.1

Run AI coding agents in secure, isolated microVMs
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
//! Unified backend abstraction for sandbox execution.
//!
//! This module provides a common interface for all sandbox backends:
//! - Docker/Podman containers
//! - Firecracker microVMs
//! - Apple Containers (macOS 26+)
//! - Hyperlight WebAssembly (Linux with KVM)

// Allow dead code temporarily - this module provides the new unified interface
// that will be integrated into vmm.rs and main.rs incrementally
#![allow(dead_code)]

#[cfg(target_os = "macos")]
pub mod apple;
pub mod docker;
pub mod firecracker;
pub mod hyperlight;
#[cfg(feature = "kubernetes")]
pub mod kubernetes;
#[cfg(feature = "kubernetes")]
pub mod kubernetes_operator;
#[cfg(feature = "kubernetes")]
pub mod kubernetes_pool;
#[cfg(feature = "nomad")]
pub mod nomad;
#[cfg(feature = "nomad")]
pub mod nomad_pool;

use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::fmt;

use crate::ssh::SshConfig;

#[cfg(target_os = "macos")]
pub use apple::AppleSandbox;
pub use docker::{ContainerRuntime, DockerSandbox};
pub use firecracker::FirecrackerSandbox;
pub use hyperlight::HyperlightSandbox;
#[cfg(feature = "kubernetes")]
pub use kubernetes::KubernetesSandbox;
#[cfg(feature = "nomad")]
pub use nomad::NomadSandbox;

/// Backend type identifier
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum BackendType {
    /// Docker or Podman container
    Docker,
    /// Podman container (explicit)
    Podman,
    /// Firecracker microVM
    Firecracker,
    /// Apple Containers (macOS 26+)
    Apple,
    /// Hyperlight WebAssembly
    Hyperlight,
    /// Kubernetes pods (requires --features kubernetes)
    Kubernetes,
    /// HashiCorp Nomad jobs (requires --features nomad)
    Nomad,
}

impl fmt::Display for BackendType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            BackendType::Docker => write!(f, "docker"),
            BackendType::Podman => write!(f, "podman"),
            BackendType::Firecracker => write!(f, "firecracker"),
            BackendType::Apple => write!(f, "apple"),
            BackendType::Hyperlight => write!(f, "hyperlight"),
            BackendType::Kubernetes => write!(f, "kubernetes"),
            BackendType::Nomad => write!(f, "nomad"),
        }
    }
}

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

    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "docker" => Ok(BackendType::Docker),
            "podman" => Ok(BackendType::Podman),
            "firecracker" => Ok(BackendType::Firecracker),
            "apple" => Ok(BackendType::Apple),
            "hyperlight" => Ok(BackendType::Hyperlight),
            "kubernetes" | "k8s" => Ok(BackendType::Kubernetes),
            "nomad" => Ok(BackendType::Nomad),
            _ => Err(format!(
                "Unknown backend '{}'. Valid options: docker, podman, firecracker, apple, hyperlight, kubernetes, nomad",
                s
            )),
        }
    }
}

/// Protocol for port mappings
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PortProtocol {
    #[default]
    Tcp,
    Udp,
}

impl fmt::Display for PortProtocol {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PortProtocol::Tcp => write!(f, "tcp"),
            PortProtocol::Udp => write!(f, "udp"),
        }
    }
}

/// A port mapping from host to container
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PortMapping {
    /// Host port (None = auto-assign)
    pub host_port: Option<u16>,
    /// Container port (required)
    pub container_port: u16,
    /// Protocol (default: tcp)
    #[serde(default)]
    pub protocol: PortProtocol,
}

impl PortMapping {
    /// Parse a Docker-style port string: "host:container", "container", "host:container/udp"
    pub fn parse(s: &str) -> anyhow::Result<Self> {
        let (port_part, protocol) = if let Some(stripped) = s.strip_suffix("/udp") {
            (stripped, PortProtocol::Udp)
        } else if let Some(stripped) = s.strip_suffix("/tcp") {
            (stripped, PortProtocol::Tcp)
        } else {
            (s, PortProtocol::Tcp)
        };

        if let Some((host, container)) = port_part.split_once(':') {
            let host_port: u16 = host
                .parse()
                .map_err(|_| anyhow::anyhow!("Invalid host port '{}' in '{}'", host, s))?;
            let container_port: u16 = container.parse().map_err(|_| {
                anyhow::anyhow!("Invalid container port '{}' in '{}'", container, s)
            })?;
            Ok(PortMapping {
                host_port: Some(host_port),
                container_port,
                protocol,
            })
        } else {
            let container_port: u16 = port_part
                .parse()
                .map_err(|_| anyhow::anyhow!("Invalid port '{}' in '{}'", port_part, s))?;
            Ok(PortMapping {
                host_port: None,
                container_port,
                protocol,
            })
        }
    }
}

impl fmt::Display for PortMapping {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.host_port {
            Some(hp) => write!(f, "{}:{}", hp, self.container_port)?,
            None => write!(f, "{}", self.container_port)?,
        }
        if self.protocol == PortProtocol::Udp {
            write!(f, "/udp")?;
        }
        Ok(())
    }
}

/// File to inject into sandbox at startup
#[derive(Debug, Clone)]
pub struct FileInjection {
    /// Content to write
    pub content: Vec<u8>,
    /// Destination path inside the sandbox (absolute)
    pub dest: String,
}

/// Configuration for starting a sandbox
#[derive(Debug, Clone)]
pub struct SandboxConfig {
    /// Container/VM image to use (e.g., "python:3.12-alpine")
    pub image: String,
    /// Number of vCPUs (for VM backends)
    pub vcpus: u32,
    /// Memory in MB (for VM backends)
    pub memory_mb: u64,
    /// Whether to mount the current working directory
    pub mount_cwd: bool,
    /// Path to mount as working directory
    pub work_dir: Option<String>,
    /// Environment variables to set
    pub env: Vec<(String, String)>,
    /// Network access enabled
    pub network: bool,
    /// Make root filesystem read-only
    pub read_only: bool,
    /// Mount home directory (read-only)
    pub mount_home: bool,
    /// Files to inject after sandbox starts
    pub files: Vec<FileInjection>,
    /// Port mappings (host:container)
    pub ports: Vec<PortMapping>,
    /// SSH configuration (None = SSH disabled)
    pub ssh: Option<SshConfig>,
    /// Volume mounts (slug:/path or slug:/path:ro)
    pub volumes: Vec<String>,
}

impl Default for SandboxConfig {
    fn default() -> Self {
        Self {
            image: "alpine:3.20".to_string(),
            vcpus: 1,
            memory_mb: 512,
            mount_cwd: false,
            work_dir: None,
            env: Vec::new(),
            network: true,
            read_only: false,
            mount_home: false,
            files: Vec::new(),
            ports: Vec::new(),
            ssh: None,
            volumes: Vec::new(),
        }
    }
}

impl SandboxConfig {
    /// Create a new config with the given image
    pub fn with_image(image: &str) -> Self {
        Self {
            image: image.to_string(),
            ..Default::default()
        }
    }

    /// Set resource limits
    pub fn with_resources(mut self, vcpus: u32, memory_mb: u64) -> Self {
        self.vcpus = vcpus;
        self.memory_mb = memory_mb;
        self
    }

    /// Enable/disable network
    pub fn with_network(mut self, network: bool) -> Self {
        self.network = network;
        self
    }

    /// Mount current working directory
    pub fn with_mount_cwd(mut self, mount: bool, work_dir: Option<String>) -> Self {
        self.mount_cwd = mount;
        self.work_dir = work_dir;
        self
    }

    /// Set environment variables
    pub fn with_env(mut self, env: Vec<(String, String)>) -> Self {
        self.env = env;
        self
    }

    /// Add files to inject after sandbox starts
    pub fn with_files(mut self, files: Vec<FileInjection>) -> Self {
        self.files = files;
        self
    }

    /// Set port mappings
    pub fn with_ports(mut self, ports: Vec<PortMapping>) -> Self {
        self.ports = ports;
        self
    }

    /// Set SSH configuration
    pub fn with_ssh(mut self, ssh: Option<SshConfig>) -> Self {
        self.ssh = ssh;
        self
    }
}

/// Result of executing a command in a sandbox
#[derive(Debug, Clone)]
pub struct ExecResult {
    /// Exit code (0 = success)
    pub exit_code: i32,
    /// Standard output
    pub stdout: String,
    /// Standard error
    pub stderr: String,
}

impl ExecResult {
    /// Create a successful result
    pub fn success(stdout: String) -> Self {
        Self {
            exit_code: 0,
            stdout,
            stderr: String::new(),
        }
    }

    /// Create a failed result
    pub fn failure(exit_code: i32, stderr: String) -> Self {
        Self {
            exit_code,
            stdout: String::new(),
            stderr,
        }
    }

    /// Check if the command succeeded
    pub fn is_success(&self) -> bool {
        self.exit_code == 0
    }

    /// Get combined output (stdout + stderr)
    pub fn output(&self) -> String {
        if self.stderr.is_empty() {
            self.stdout.clone()
        } else if self.stdout.is_empty() {
            self.stderr.clone()
        } else {
            format!("{}\n{}", self.stdout, self.stderr)
        }
    }
}

/// Options for executing a command in a sandbox
#[derive(Debug, Default, Clone)]
pub struct ExecOptions {
    /// Environment variables as KEY=VALUE pairs
    pub env: Vec<String>,
    /// Working directory inside the sandbox
    pub workdir: Option<String>,
    /// User to run the command as (e.g., "root")
    pub user: Option<String>,
}

/// Unified sandbox interface for all backends
///
/// Each backend implements this trait to provide a consistent API for:
/// - Starting sandboxes with configuration
/// - Executing commands
/// - File operations (read/write)
/// - Stopping and cleaning up
#[async_trait]
pub trait Sandbox: Send + Sync {
    /// Start the sandbox with the given configuration
    async fn start(&mut self, config: &SandboxConfig) -> Result<()>;

    /// Execute a command in the sandbox
    async fn exec(&mut self, cmd: &[&str]) -> Result<ExecResult>;

    /// Execute a command with environment variables
    async fn exec_with_env(&mut self, cmd: &[&str], env: &[String]) -> Result<ExecResult> {
        if !env.is_empty() {
            eprintln!(
                "Warning: This backend doesn't support environment variables, ignoring {} var(s)",
                env.len()
            );
        }
        self.exec(cmd).await
    }

    /// Execute a command with full options (env, workdir, user)
    async fn exec_with_options(&mut self, cmd: &[&str], opts: &ExecOptions) -> Result<ExecResult> {
        if opts.workdir.is_some() || opts.user.is_some() {
            eprintln!("Warning: This backend doesn't support workdir/user options, ignoring");
        }
        self.exec_with_env(cmd, &opts.env).await
    }

    /// Stop the sandbox and clean up resources
    async fn stop(&mut self) -> Result<()>;

    /// Attempt to resize sandbox resources in-place.
    ///
    /// Returns:
    /// - `Ok(true)` when resize succeeded in-place
    /// - `Ok(false)` when backend does not support in-place resize
    async fn resize(&mut self, _vcpus: u32, _memory_mb: u64) -> Result<bool> {
        Ok(false)
    }

    /// Get the sandbox name/identifier
    fn name(&self) -> &str;

    /// Get the backend type
    fn backend_type(&self) -> BackendType;

    /// Check if the sandbox is running
    fn is_running(&self) -> bool;

    // --- File Operations ---

    /// Write a file to the sandbox filesystem
    ///
    /// # Arguments
    /// * `path` - Absolute path inside the sandbox (must start with '/')
    /// * `content` - File content as bytes
    ///
    /// # Security
    /// Path is validated to prevent traversal attacks and writes to system paths
    async fn write_file(&mut self, path: &str, content: &[u8]) -> Result<()> {
        validate_sandbox_path(path)?;
        self.write_file_unchecked(path, content).await
    }

    /// Internal write implementation (no validation, called by write_file)
    async fn write_file_unchecked(&mut self, path: &str, content: &[u8]) -> Result<()>;

    /// Read a file from the sandbox filesystem
    ///
    /// # Arguments
    /// * `path` - Absolute path inside the sandbox (must start with '/')
    ///
    /// # Returns
    /// File content as bytes
    async fn read_file(&mut self, path: &str) -> Result<Vec<u8>> {
        validate_sandbox_path(path)?;
        self.read_file_unchecked(path).await
    }

    /// Internal read implementation (no validation, called by read_file)
    async fn read_file_unchecked(&mut self, path: &str) -> Result<Vec<u8>>;

    /// Remove a file from the sandbox filesystem
    async fn remove_file(&mut self, path: &str) -> Result<()> {
        validate_sandbox_path(path)?;
        self.remove_file_unchecked(path).await
    }

    /// Internal remove implementation
    async fn remove_file_unchecked(&mut self, path: &str) -> Result<()>;

    /// Create a directory in the sandbox filesystem
    async fn mkdir(&mut self, path: &str, recursive: bool) -> Result<()> {
        validate_sandbox_path(path)?;
        self.mkdir_unchecked(path, recursive).await
    }

    /// Internal mkdir implementation
    async fn mkdir_unchecked(&mut self, path: &str, recursive: bool) -> Result<()>;

    /// Inject files from config into the sandbox
    ///
    /// Called automatically after start() when files are specified in config.
    /// Creates parent directories as needed.
    async fn inject_files(&mut self, files: &[FileInjection]) -> Result<()> {
        for file in files {
            // Create parent directory if needed
            if let Some(parent) = std::path::Path::new(&file.dest).parent() {
                let parent_str = parent.to_string_lossy();
                if parent_str != "/" {
                    self.mkdir(&parent_str, true).await?;
                }
            }
            // Write the file
            self.write_file(&file.dest, &file.content).await?;
        }
        Ok(())
    }

    // --- Interactive Shell/PTY Operations ---

    /// Attach an interactive shell to the sandbox
    ///
    /// This opens a PTY session in the guest and bridges it to the host terminal.
    /// The shell runs until the user exits (Ctrl+D or exit command).
    ///
    /// # Arguments
    /// * `shell` - Shell to run (e.g., "/bin/sh", "/bin/bash"). If None, uses /bin/sh.
    ///
    /// # Returns
    /// The exit code of the shell process.
    async fn attach(&mut self, shell: Option<&str>) -> Result<i32> {
        // Default implementation returns an error since not all backends support PTY
        let _ = shell;
        anyhow::bail!("Interactive shell not supported by this backend")
    }

    /// Attach to the sandbox with an interactive shell and environment variables
    ///
    /// # Arguments
    /// * `shell` - Shell to run (e.g., "/bin/sh", "/bin/bash"). If None, uses /bin/sh.
    /// * `env` - Environment variables as KEY=VALUE pairs
    ///
    /// # Returns
    /// The exit code of the shell process.
    async fn attach_with_env(&mut self, shell: Option<&str>, env: &[String]) -> Result<i32> {
        // Default implementation ignores env vars
        if !env.is_empty() {
            eprintln!(
                "Warning: This backend doesn't support environment variables, ignoring {} var(s)",
                env.len()
            );
        }
        self.attach(shell).await
    }
}

/// Validate a path for sandbox file operations
///
/// Ensures paths are:
/// - Absolute (start with '/')
/// - No path traversal (..)
/// - Not targeting sensitive system paths
pub fn validate_sandbox_path(path: &str) -> Result<()> {
    use anyhow::bail;

    // Must be absolute path
    if !path.starts_with('/') {
        bail!("Sandbox path must be absolute, got: {}", path);
    }

    // No path traversal
    if path.contains("..") {
        bail!("Path traversal not allowed: {}", path);
    }

    // Block sensitive system paths
    const BLOCKED_PATHS: &[&str] = &[
        "/proc",
        "/sys",
        "/dev",
        "/etc/passwd",
        "/etc/shadow",
        "/etc/sudoers",
        "/root/.ssh",
    ];

    for blocked in BLOCKED_PATHS {
        if path.starts_with(blocked) {
            bail!("Cannot access system path: {}", path);
        }
    }

    Ok(())
}

/// Detect the best available backend for the current platform
pub fn detect_best_backend() -> Option<BackendType> {
    // On Linux, prefer Firecracker if KVM is available
    #[cfg(target_os = "linux")]
    {
        if std::path::Path::new("/dev/kvm").exists() {
            // Check if firecracker is available
            if firecracker::firecracker_available() {
                return Some(BackendType::Firecracker);
            }
        }
    }

    // On macOS 26+, check for Apple Containers
    #[cfg(target_os = "macos")]
    {
        if apple::apple_containers_available() {
            return Some(BackendType::Apple);
        }
    }

    // Fall back to containers (prefer Podman over Docker)
    if docker::podman_available() {
        return Some(BackendType::Podman);
    }
    if docker::docker_available() {
        return Some(BackendType::Docker);
    }

    None
}

/// Check if a specific backend is available
pub fn backend_available(backend: BackendType) -> bool {
    match backend {
        BackendType::Docker => docker::docker_available(),
        BackendType::Podman => docker::podman_available(),
        BackendType::Firecracker => firecracker::firecracker_available(),
        #[cfg(target_os = "macos")]
        BackendType::Apple => apple::apple_containers_available(),
        #[cfg(not(target_os = "macos"))]
        BackendType::Apple => false,
        BackendType::Hyperlight => hyperlight::hyperlight_available(),
        // Kubernetes and Nomad are always "available" when compiled with the feature;
        // actual connectivity is checked at start() time.
        #[cfg(feature = "kubernetes")]
        BackendType::Kubernetes => true,
        #[cfg(not(feature = "kubernetes"))]
        BackendType::Kubernetes => false,
        #[cfg(feature = "nomad")]
        BackendType::Nomad => true,
        #[cfg(not(feature = "nomad"))]
        BackendType::Nomad => false,
    }
}

/// Create a sandbox for the specified backend
///
/// For Docker/Podman, creates persistent sandboxes that survive CLI exit.
/// This is needed because the Sandbox trait workflow (create/start/stop/attach)
/// expects containers to persist between CLI invocations.
pub fn create_sandbox(backend: BackendType, name: &str) -> Result<Box<dyn Sandbox>> {
    create_sandbox_with_config(backend, name, &crate::config::OrchestratorConfig::default())
}

/// Create a sandbox with orchestrator configuration
///
/// Used by Kubernetes/Nomad backends to pass namespace, runtime class, etc.
pub fn create_sandbox_with_config(
    backend: BackendType,
    name: &str,
    #[allow(unused_variables)] orch_config: &crate::config::OrchestratorConfig,
) -> Result<Box<dyn Sandbox>> {
    match backend {
        // Use new_persistent for Docker/Podman so containers survive CLI exit
        BackendType::Docker => Ok(Box::new(DockerSandbox::new_persistent(
            name,
            ContainerRuntime::Docker,
        ))),
        BackendType::Podman => Ok(Box::new(DockerSandbox::new_persistent(
            name,
            ContainerRuntime::Podman,
        ))),
        BackendType::Firecracker => Ok(Box::new(FirecrackerSandbox::new(name)?)),
        #[cfg(target_os = "macos")]
        BackendType::Apple => Ok(Box::new(AppleSandbox::new_persistent(name))),
        #[cfg(not(target_os = "macos"))]
        BackendType::Apple => anyhow::bail!("Apple Containers only available on macOS"),
        BackendType::Hyperlight => Ok(Box::new(HyperlightSandbox::new(name))),
        #[cfg(feature = "kubernetes")]
        BackendType::Kubernetes => Ok(Box::new(KubernetesSandbox::new(name, orch_config))),
        #[cfg(not(feature = "kubernetes"))]
        BackendType::Kubernetes => {
            anyhow::bail!("Kubernetes backend not compiled. Rebuild with --features kubernetes")
        }
        #[cfg(feature = "nomad")]
        BackendType::Nomad => Ok(Box::new(NomadSandbox::new(name, orch_config))),
        #[cfg(not(feature = "nomad"))]
        BackendType::Nomad => {
            anyhow::bail!("Nomad backend not compiled. Rebuild with --features nomad")
        }
    }
}

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

    // === BackendType tests ===

    #[test]
    fn test_backend_type_display() {
        assert_eq!(format!("{}", BackendType::Docker), "docker");
        assert_eq!(format!("{}", BackendType::Podman), "podman");
        assert_eq!(format!("{}", BackendType::Firecracker), "firecracker");
        assert_eq!(format!("{}", BackendType::Apple), "apple");
        assert_eq!(format!("{}", BackendType::Hyperlight), "hyperlight");
        assert_eq!(format!("{}", BackendType::Kubernetes), "kubernetes");
        assert_eq!(format!("{}", BackendType::Nomad), "nomad");
    }

    #[test]
    fn test_backend_type_from_str() {
        assert_eq!(
            "docker".parse::<BackendType>().unwrap(),
            BackendType::Docker
        );
        assert_eq!(
            "podman".parse::<BackendType>().unwrap(),
            BackendType::Podman
        );
        assert_eq!(
            "firecracker".parse::<BackendType>().unwrap(),
            BackendType::Firecracker
        );
        assert_eq!("apple".parse::<BackendType>().unwrap(), BackendType::Apple);
        assert_eq!(
            "hyperlight".parse::<BackendType>().unwrap(),
            BackendType::Hyperlight
        );
        assert_eq!(
            "kubernetes".parse::<BackendType>().unwrap(),
            BackendType::Kubernetes
        );
        assert_eq!(
            "k8s".parse::<BackendType>().unwrap(),
            BackendType::Kubernetes
        );
        assert_eq!("nomad".parse::<BackendType>().unwrap(), BackendType::Nomad);
    }

    #[test]
    fn test_backend_type_from_str_case_insensitive() {
        assert_eq!(
            "DOCKER".parse::<BackendType>().unwrap(),
            BackendType::Docker
        );
        assert_eq!(
            "Docker".parse::<BackendType>().unwrap(),
            BackendType::Docker
        );
        assert_eq!(
            "PODMAN".parse::<BackendType>().unwrap(),
            BackendType::Podman
        );
    }

    #[test]
    fn test_backend_type_from_str_invalid() {
        assert!("invalid".parse::<BackendType>().is_err());
        assert!("".parse::<BackendType>().is_err());
        assert!("dock".parse::<BackendType>().is_err());
    }

    #[test]
    fn test_backend_type_serialize() {
        let backend = BackendType::Docker;
        let json = serde_json::to_string(&backend).unwrap();
        assert_eq!(json, "\"Docker\"");
    }

    #[test]
    fn test_backend_type_deserialize() {
        let backend: BackendType = serde_json::from_str("\"Podman\"").unwrap();
        assert_eq!(backend, BackendType::Podman);
    }

    // === SandboxConfig tests ===

    #[test]
    fn test_sandbox_config_default() {
        let config = SandboxConfig::default();
        assert_eq!(config.image, "alpine:3.20");
        assert_eq!(config.vcpus, 1);
        assert_eq!(config.memory_mb, 512);
        assert!(!config.mount_cwd);
        assert!(config.work_dir.is_none());
        assert!(config.env.is_empty());
        assert!(config.network);
        assert!(!config.read_only);
        assert!(!config.mount_home);
        assert!(config.files.is_empty());
        assert!(config.ports.is_empty());
        assert!(config.ssh.is_none());
    }

    #[test]
    fn test_sandbox_config_with_image() {
        let config = SandboxConfig::with_image("python:3.12-alpine");
        assert_eq!(config.image, "python:3.12-alpine");
        // Other fields should be default
        assert_eq!(config.vcpus, 1);
        assert_eq!(config.memory_mb, 512);
    }

    #[test]
    fn test_sandbox_config_builder() {
        let config = SandboxConfig::with_image("node:20")
            .with_resources(4, 2048)
            .with_network(false)
            .with_mount_cwd(true, Some("/workspace".to_string()))
            .with_env(vec![("NODE_ENV".to_string(), "production".to_string())]);

        assert_eq!(config.image, "node:20");
        assert_eq!(config.vcpus, 4);
        assert_eq!(config.memory_mb, 2048);
        assert!(!config.network);
        assert!(config.mount_cwd);
        assert_eq!(config.work_dir, Some("/workspace".to_string()));
        assert_eq!(config.env.len(), 1);
        assert_eq!(
            config.env[0],
            ("NODE_ENV".to_string(), "production".to_string())
        );
    }

    // === ExecResult tests ===

    #[test]
    fn test_exec_result_success() {
        let result = ExecResult::success("hello world".to_string());
        assert!(result.is_success());
        assert_eq!(result.exit_code, 0);
        assert_eq!(result.stdout, "hello world");
        assert!(result.stderr.is_empty());
    }

    #[test]
    fn test_exec_result_failure() {
        let result = ExecResult::failure(1, "error message".to_string());
        assert!(!result.is_success());
        assert_eq!(result.exit_code, 1);
        assert!(result.stdout.is_empty());
        assert_eq!(result.stderr, "error message");
    }

    #[test]
    fn test_exec_result_output_stdout_only() {
        let result = ExecResult {
            exit_code: 0,
            stdout: "stdout output".to_string(),
            stderr: String::new(),
        };
        assert_eq!(result.output(), "stdout output");
    }

    #[test]
    fn test_exec_result_output_stderr_only() {
        let result = ExecResult {
            exit_code: 1,
            stdout: String::new(),
            stderr: "stderr output".to_string(),
        };
        assert_eq!(result.output(), "stderr output");
    }

    #[test]
    fn test_exec_result_output_combined() {
        let result = ExecResult {
            exit_code: 0,
            stdout: "stdout".to_string(),
            stderr: "stderr".to_string(),
        };
        assert_eq!(result.output(), "stdout\nstderr");
    }

    // === Path validation tests ===

    #[test]
    fn test_validate_sandbox_path_valid() {
        assert!(validate_sandbox_path("/home/user/file.txt").is_ok());
        assert!(validate_sandbox_path("/workspace/project/src/main.rs").is_ok());
        assert!(validate_sandbox_path("/tmp/test").is_ok());
        assert!(validate_sandbox_path("/app/data.json").is_ok());
    }

    #[test]
    fn test_validate_sandbox_path_relative() {
        assert!(validate_sandbox_path("relative/path").is_err());
        assert!(validate_sandbox_path("./file.txt").is_err());
        assert!(validate_sandbox_path("file.txt").is_err());
    }

    #[test]
    fn test_validate_sandbox_path_traversal() {
        assert!(validate_sandbox_path("/home/../etc/passwd").is_err());
        assert!(validate_sandbox_path("/workspace/..").is_err());
        assert!(validate_sandbox_path("/../root").is_err());
    }

    #[test]
    fn test_validate_sandbox_path_blocked_paths() {
        assert!(validate_sandbox_path("/proc/1/cmdline").is_err());
        assert!(validate_sandbox_path("/sys/kernel").is_err());
        assert!(validate_sandbox_path("/dev/null").is_err());
        assert!(validate_sandbox_path("/etc/passwd").is_err());
        assert!(validate_sandbox_path("/etc/shadow").is_err());
        assert!(validate_sandbox_path("/etc/sudoers").is_err());
        assert!(validate_sandbox_path("/root/.ssh/id_rsa").is_err());
    }

    #[test]
    fn test_validate_sandbox_path_similar_but_allowed() {
        // These look similar to blocked paths but should be allowed
        assert!(validate_sandbox_path("/etc/hosts").is_ok());
        assert!(validate_sandbox_path("/home/root/.ssh").is_ok());
        assert!(validate_sandbox_path("/myproc/data").is_ok());
    }

    // === FileInjection tests ===

    #[test]
    fn test_file_injection_creation() {
        let injection = FileInjection {
            content: b"hello world".to_vec(),
            dest: "/app/config.txt".to_string(),
        };
        assert_eq!(injection.content, b"hello world");
        assert_eq!(injection.dest, "/app/config.txt");
    }

    #[test]
    fn test_sandbox_config_with_files() {
        let files = vec![
            FileInjection {
                content: b"content1".to_vec(),
                dest: "/app/file1.txt".to_string(),
            },
            FileInjection {
                content: b"content2".to_vec(),
                dest: "/app/file2.txt".to_string(),
            },
        ];

        let config = SandboxConfig::default().with_files(files);
        assert_eq!(config.files.len(), 2);
    }

    // === PortMapping tests ===

    #[test]
    fn test_port_mapping_parse_host_container() {
        let pm = PortMapping::parse("8080:80").unwrap();
        assert_eq!(pm.host_port, Some(8080));
        assert_eq!(pm.container_port, 80);
        assert_eq!(pm.protocol, PortProtocol::Tcp);
    }

    #[test]
    fn test_port_mapping_parse_container_only() {
        let pm = PortMapping::parse("3000").unwrap();
        assert_eq!(pm.host_port, None);
        assert_eq!(pm.container_port, 3000);
        assert_eq!(pm.protocol, PortProtocol::Tcp);
    }

    #[test]
    fn test_port_mapping_parse_udp() {
        let pm = PortMapping::parse("5353:53/udp").unwrap();
        assert_eq!(pm.host_port, Some(5353));
        assert_eq!(pm.container_port, 53);
        assert_eq!(pm.protocol, PortProtocol::Udp);
    }

    #[test]
    fn test_port_mapping_parse_explicit_tcp() {
        let pm = PortMapping::parse("8080:80/tcp").unwrap();
        assert_eq!(pm.host_port, Some(8080));
        assert_eq!(pm.container_port, 80);
        assert_eq!(pm.protocol, PortProtocol::Tcp);
    }

    #[test]
    fn test_port_mapping_parse_invalid_host() {
        assert!(PortMapping::parse("abc:80").is_err());
    }

    #[test]
    fn test_port_mapping_parse_invalid_container() {
        assert!(PortMapping::parse("8080:abc").is_err());
    }

    #[test]
    fn test_port_mapping_parse_invalid_single() {
        assert!(PortMapping::parse("not-a-port").is_err());
    }

    #[test]
    fn test_port_mapping_display() {
        assert_eq!(
            format!(
                "{}",
                PortMapping {
                    host_port: Some(8080),
                    container_port: 80,
                    protocol: PortProtocol::Tcp
                }
            ),
            "8080:80"
        );
        assert_eq!(
            format!(
                "{}",
                PortMapping {
                    host_port: None,
                    container_port: 3000,
                    protocol: PortProtocol::Tcp
                }
            ),
            "3000"
        );
        assert_eq!(
            format!(
                "{}",
                PortMapping {
                    host_port: Some(5353),
                    container_port: 53,
                    protocol: PortProtocol::Udp
                }
            ),
            "5353:53/udp"
        );
    }

    #[test]
    fn test_port_mapping_serialize_roundtrip() {
        let pm = PortMapping::parse("8080:80").unwrap();
        let json = serde_json::to_string(&pm).unwrap();
        let pm2: PortMapping = serde_json::from_str(&json).unwrap();
        assert_eq!(pm, pm2);
    }

    #[test]
    fn test_sandbox_config_with_ports() {
        let ports = vec![
            PortMapping::parse("8080:80").unwrap(),
            PortMapping::parse("3000").unwrap(),
        ];
        let config = SandboxConfig::default().with_ports(ports);
        assert_eq!(config.ports.len(), 2);
        assert_eq!(config.ports[0].container_port, 80);
        assert_eq!(config.ports[1].container_port, 3000);
    }
}