runtimo-core 0.2.0

Agent-centric capability runtime with telemetry, process tracking, and crash recovery for persistent machines
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
//! ShellExec capability — execute shell commands with full telemetry and audit trail.
//!
//! Executes shell commands with:
//! - Timeout enforcement (default 30s, configurable)
//! - Output capture (stdout/stderr, bounded to 10MB)
//! - PID tracking (child + grandchildren via /proc/{pid}/children)
//! - Process group isolation (kills all descendants on timeout)
//! - Telemetry before/after execution
//! - WAL logging for audit trail (includes spawned_pids array)
//! - Resource guard checks before execution
//! - Dangerous command detection (blocks rm -rf /, dd, mkfs, etc.)
//! - PATH hijack protection (resolves program names to absolute paths)
//! - Stdin pipe support
//!
//! # Security
//!
//! **CRITICAL:** This capability executes arbitrary commands. It enforces:
//! - Dangerous command blocklist (rm -rf /, dd, mkfs, fdisk, shutdown, etc.)
//! - PATH hijack protection (resolves bare names to absolute paths)
//! - Process group isolation (setpgid for clean descendant cleanup)
//! - Output size limits (10MB max to prevent OOM)
//! - Timeout enforcement with process group kill
//! - All commands logged to WAL for audit
//!
//! # Limitations
//!
//! **ShellExec has no undo support.** Unlike FileWrite which creates backups for undo,
//! shell commands are arbitrary and have ill-defined "before" states. There is no safe
//! way to reverse arbitrary shell commands like `rm -rf /tmp/*` or `apt-get upgrade`.
//!
//! # Example
//!
//! ```rust,ignore
//! use runtimo_core::capabilities::ShellExec;
//! use runtimo_core::capability::{Capability, Context};
//! use serde_json::json;
//!
//! let cap = ShellExec;
//! let result = cap.execute(
//! &json!({"cmd": "uptime", "timeout_secs": 10}),
//! &Context { dry_run: false, job_id: "test".into(), ..Default::default() }
//! ).unwrap();
//!
//! assert!(result.success);
//! assert!(result.data["stdout"].as_str().unwrap().contains("up"));
//! assert!(result.data["pid"].as_u64().is_some());
//! ```

use crate::capability::{Capability, Context, Output};
use crate::validation::path::{validate_path, PathContext};
use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::fs;
use std::io::{Read, Write};
use std::os::unix::process::CommandExt;
use std::process::{Child, Command, ExitStatus};
use std::thread;
use std::time::{Duration, Instant};

/// Default timeout for shell command execution (seconds).
const DEFAULT_TIMEOUT_SECS: u64 = 30;

/// Maximum output size per stream (stdout/stderr) — 10MB.
const MAX_OUTPUT_BYTES: usize = 10 * 1024 * 1024;

/// Maximum stdin input size — 1MB.
const MAX_STDIN_BYTES: usize = 1024 * 1024;

/// Arguments for the [`ShellExec`] capability.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShellExecArgs {
    /// Command or program to execute (e.g., "uptime" or "/bin/ls").
    /// When `args` is also provided, this is treated as the program name only.
    /// When `args` is absent, the first whitespace-separated token is the program.
    pub cmd: String,
    /// Explicit arguments passed directly to the program (no shell interpretation).
    /// When provided, `cmd` is the program and these are its arguments — shell
    /// metacharacters like `;`, `|`, `&` are treated as literal characters.
    pub args: Option<Vec<String>>,
    /// Timeout in seconds (default: 30).
    pub timeout_secs: Option<u64>,
    /// Working directory for command execution.
    pub cwd: Option<String>,
    /// Content to pipe to the child process's stdin.
    pub stdin: Option<String>,
}

/// Resolves a program name to an absolute path, preventing PATH hijack attacks.
///
/// - Absolute paths are used directly.
/// - Relative paths (containing `/` but not starting with `/`) are rejected.
/// - Bare names are resolved by searching `$PATH`.
/// - If not found in `$PATH`, falls back to the bare name (for compatibility).
fn resolve_program(program: &str) -> Result<String> {
    if program.starts_with('/') {
        return Ok(program.to_string());
    }
    if program.contains('/') {
        return Err(Error::ExecutionFailed(format!(
            "relative paths are not allowed: '{}'", program
        )));
    }
    if let Ok(path_env) = std::env::var("PATH") {
        for dir in path_env.split(':') {
            let candidate = std::path::PathBuf::from(dir).join(program);
            if candidate.exists() {
                return Ok(candidate.to_string_lossy().to_string());
            }
        }
    }
    Ok(program.to_string())
}

/// Checks if a command is dangerous and should be blocked.
///
/// Returns `Some(reason)` if the command is dangerous, `None` otherwise.
fn is_dangerous_command(program: &str, args: &[String]) -> Option<&'static str> {
    let program_lower = program.to_lowercase();

    match program_lower.as_str() {
        "mkfs" | "mkfs.ext2" | "mkfs.ext3" | "mkfs.ext4" | "mkfs.xfs"
        | "mkfs.vfat" | "mkfs.btrfs" | "mkswap" => {
            return Some("filesystem creation commands are blocked");
        }
        "fdisk" | "parted" | "sfdisk" | "cfdisk" => {
            return Some("disk partitioning commands are blocked");
        }
        "dd" => {
            return Some("dd (disk destroyer) is blocked");
        }
        "shutdown" | "reboot" | "halt" | "poweroff" => {
            return Some("system power commands are blocked");
        }
        _ => {}
    }

    if program_lower == "rm" {
        let has_recursive = args.iter().any(|a| a.starts_with('-') && a.contains('r'));
        let has_force = args.iter().any(|a| a.starts_with('-') && a.contains('f'));
        let targets_dangerous = args.iter().any(|a| {
            a == "/" || a == "/*" || a.starts_with("/dev/") || a.starts_with("/boot")
        });
        if has_recursive && has_force && targets_dangerous {
            return Some("rm -rf on root, devices, or boot is blocked");
        }
    }

    if program_lower == "chmod" && args.iter().any(|a| a == "/")
        && args.iter().any(|a| a == "777" || a == "0777") {
            return Some("chmod 777 / is blocked");
        }

    None
}

/// Waits for a child process with timeout, bounded output, and process group cleanup.
///
/// Features:
/// - Concurrent pipe draining via threads (prevents pipe buffer deadlock)
/// - Bounded output reading via `Read::take()` (prevents OOM)
/// - Process group kill on timeout via `libc::kill(-pgid, SIGKILL)` (kills all descendants)
/// - Zombie reaping via `child.wait()` after kill
/// - Descendant PID collection before reaping
fn wait_with_timeout(
    child: &mut Child,
    pgid: u32,
    timeout_secs: u64,
) -> Result<(ExitStatus, Vec<u8>, Vec<u8>, Vec<u32>)> {
    let start = Instant::now();
    let timeout = Duration::from_secs(timeout_secs);
    let child_pid = child.id();

    // Spawn reader threads for concurrent pipe draining — prevents deadlock when
    // one pipe fills up while the other is empty (pipe buffer is typically 64KB).
    let stdout_thread = child.stdout.take().map(|stdout| {
        thread::spawn(move || {
            let mut data = Vec::new();
            let _ = stdout.take(MAX_OUTPUT_BYTES as u64).read_to_end(&mut data);
            data
        })
    });

    let stderr_thread = child.stderr.take().map(|stderr| {
        thread::spawn(move || {
            let mut data = Vec::new();
            let _ = stderr.take(MAX_OUTPUT_BYTES as u64).read_to_end(&mut data);
            data
        })
    });

    #[allow(unused_assignments)]
    let mut last_descendants = Vec::new();

    loop {
        if start.elapsed() > timeout {
            // Kill entire process group — SIGKILL to negative PID kills all members
            unsafe {
                let _ = libc::kill(-(pgid as libc::pid_t), libc::SIGKILL);
            }
            // Collect descendants before final cleanup
            last_descendants = get_all_descendants(child_pid);
            // Reap zombie process (prevents zombie leak)
            let _status = child.wait().map_err(|e| {
                Error::ExecutionFailed(format!("failed to reap after kill: {}", e))
            })?;
            // Drain pipe threads — they complete when all process group fds close
            let _stdout_data = stdout_thread
                .map(|h| h.join().unwrap_or_default())
                .unwrap_or_default();
            let _stderr_data = stderr_thread
                .map(|h| h.join().unwrap_or_default())
                .unwrap_or_default();
            return Err(Error::ExecutionFailed(format!(
                "command timed out after {}s ({} descendants found)",
                timeout_secs,
                last_descendants.len()
            )));
        }

        // Collect descendants while child is still alive
        last_descendants = get_all_descendants(child_pid);

        match child.try_wait() {
            Ok(Some(status)) => {
                let stdout_data = stdout_thread
                    .map(|h| h.join().unwrap_or_default())
                    .unwrap_or_default();
                let stderr_data = stderr_thread
                    .map(|h| h.join().unwrap_or_default())
                    .unwrap_or_default();
                return Ok((status, stdout_data, stderr_data, last_descendants));
            }
            Ok(None) => {
                std::thread::sleep(Duration::from_millis(50));
            }
            Err(e) => {
                return Err(Error::ExecutionFailed(format!("error waiting: {}", e)));
            }
        }
    }
}

/// Reads /proc/{pid}/children to find direct child processes.
///
/// Linux-specific: returns list of direct child PIDs.
fn get_direct_children(pid: u32) -> Vec<u32> {
    let children_path = format!("/proc/{}/children", pid);
    if let Ok(content) = fs::read_to_string(&children_path) {
        content
            .split_whitespace()
            .filter_map(|s| s.parse::<u32>().ok())
            .collect()
    } else {
        Vec::new()
    }
}

/// Recursively collects all descendant PIDs of a given process.
///
/// Traverses /proc/{pid}/children recursively to find grandchildren and beyond.
/// Falls back to `pgrep -P {pid}` for older kernels where /proc/PID/children
/// is unavailable (FINDING #6).
fn get_all_descendants(pid: u32) -> Vec<u32> {
    let mut descendants = Vec::new();
    let mut stack = vec![pid];
    let mut visited = std::collections::HashSet::new();

    while let Some(current) = stack.pop() {
        if visited.contains(&current) {
            continue;
        }
        visited.insert(current);

        let children = get_direct_children(current);
        if children.is_empty() {
            // Fallback: try pgrep -P for older kernels (FINDING #6)
            if let Ok(output) = std::process::Command::new("pgrep")
                .arg("-P")
                .arg(current.to_string())
                .output()
            {
                if output.status.success() {
                    let pgrep_children = String::from_utf8_lossy(&output.stdout)
                        .lines()
                        .filter_map(|s| s.trim().parse::<u32>().ok())
                        .collect::<Vec<_>>();
                    for child in pgrep_children {
                        if !visited.contains(&child) {
                            descendants.push(child);
                            stack.push(child);
                        }
                    }
                    continue;
                }
            }
        }

        for child in children {
            if !visited.contains(&child) {
                descendants.push(child);
                stack.push(child);
            }
        }
    }

    descendants
}

/// Capability that executes commands with full telemetry and audit.
///
/// # Security
///
/// Commands are executed via `Command::new(program)` with explicit argument
/// separation — no shell interpretation. Shell metacharacters (`;`, `|`, `&`,
/// `>`, `<`, `$()`, backticks) are treated as literal characters, preventing
/// shell injection attacks (FINDING #5).
///
/// Every command is logged to the WAL for audit purposes.
pub struct ShellExec;

impl Capability for ShellExec {
    fn name(&self) -> &'static str {
        "ShellExec"
    }

    fn description(&self) -> &'static str {
        "Execute a shell command with timeout, output capture, process group isolation, and audit logging. Dangerous commands are blocked."
    }

    /// Returns the JSON Schema for ShellExec arguments.
    ///
    /// Schema requires `"cmd"` string; `"args"`, `"timeout_secs"`, `"cwd"`, and `"stdin"` are optional.
    fn schema(&self) -> Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "cmd": { "type": "string" },
                "args": { "type": "array", "items": { "type": "string" } },
                "timeout_secs": { "type": "integer", "minimum": 1, "maximum": 300 },
                "cwd": { "type": "string" },
                "stdin": { "type": "string" }
            },
            "required": ["cmd"]
        })
    }

    fn validate(&self, args: &Value) -> Result<()> {
        let args: ShellExecArgs = serde_json::from_value(args.clone())
            .map_err(|e| Error::SchemaValidationFailed(e.to_string()))?;

        if args.cmd.is_empty() {
            return Err(Error::SchemaValidationFailed("cmd is empty".into()));
        }

        Ok(())
    }

    fn execute(&self, args: &Value, ctx: &Context) -> Result<Output> {
        // Respect dry_run — skip execution entirely
        if ctx.dry_run {
            return Ok(Output {
                success: true,
                data: serde_json::json!({
                    "cmd": args.get("cmd").and_then(|v| v.as_str()).unwrap_or(""),
                    "dry_run": true,
                }),
                message: Some("DRY RUN: would execute shell command".to_string()),
            });
        }

        let args: ShellExecArgs = serde_json::from_value(args.clone())
            .map_err(|e| Error::ExecutionFailed(e.to_string()))?;

        let timeout = args.timeout_secs.unwrap_or(DEFAULT_TIMEOUT_SECS);

        // Determine program and arguments (explicit args vs legacy whitespace split)
        let (program, program_args): (String, Vec<String>) =
            if let Some(ref explicit_args) = args.args {
                (args.cmd.clone(), explicit_args.clone())
            } else {
                let mut parts = args.cmd.split_whitespace();
                let program = parts
                    .next()
                    .ok_or_else(|| Error::ExecutionFailed("cmd is empty after split".into()))?
                    .to_string();
                (program, parts.map(String::from).collect())
            };

        // Check for dangerous commands (P1: command allowlist/blocklist)
        if let Some(reason) = is_dangerous_command(&program, &program_args) {
            return Err(Error::ExecutionFailed(format!(
                "dangerous command blocked: {}", reason
            )));
        }

        // Resolve program to absolute path (P1: PATH hijack protection)
        let resolved_program = resolve_program(&program)?;

        // Build command
        let mut cmd = Command::new(&resolved_program);
        cmd.args(&program_args);

        // Set working directory if specified
        if let Some(cwd) = &args.cwd {
            let path_ctx = PathContext {
                require_exists: true,
                require_file: false,
                ..Default::default()
            };
            let cwd_path = validate_path(cwd, &path_ctx)
                .map_err(|e| Error::ExecutionFailed(format!("invalid cwd: {}", e)))?;
            cmd.current_dir(cwd_path);
        }

        // Create process group for clean descendant cleanup (P0: kill all descendants)
        let mut child = cmd
            .process_group(0)
            .stdout(std::process::Stdio::piped())
            .stderr(std::process::Stdio::piped())
            .stdin(if args.stdin.is_some() {
                std::process::Stdio::piped()
            } else {
                std::process::Stdio::null()
            })
            .spawn()
            .map_err(|e| Error::ExecutionFailed(format!("failed to spawn: {}", e)))?;

        let child_pid = child.id();
        let pgid = child_pid; // Child is the process group leader

        // Write stdin if provided (P2: stdin handling)
        if let Some(ref stdin_content) = args.stdin {
            if stdin_content.len() > MAX_STDIN_BYTES {
                return Err(Error::ExecutionFailed(format!(
                    "stdin exceeds maximum size ({} > {} bytes)",
                    stdin_content.len(),
                    MAX_STDIN_BYTES
                )));
            }
            if let Some(mut stdin_pipe) = child.stdin.take() {
                stdin_pipe
                    .write_all(stdin_content.as_bytes())
                    .map_err(|e| Error::ExecutionFailed(format!("failed to write stdin: {}", e)))?;
                // Drop stdin_pipe to signal EOF to child
            }
        }

        // Wait with timeout — handles process group kill, bounded output, zombie reaping
        let (exit_status, stdout, stderr, descendants) =
            wait_with_timeout(&mut child, pgid, timeout)?;

        let mut spawned_pids = vec![child_pid];
        spawned_pids.extend(descendants);

        let stdout_str = String::from_utf8_lossy(&stdout).to_string();
        let stderr_str = String::from_utf8_lossy(&stderr).to_string();
        let success = exit_status.success();

        Ok(Output {
            success,
            data: serde_json::json!({
                "cmd": args.cmd,
                "stdout": stdout_str,
                "stderr": stderr_str,
                "exit_code": exit_status.code().unwrap_or(-1),
                "pid": child_pid,
                "spawned_pids": spawned_pids,
                "timeout_secs": timeout,
                "timed_out": exit_status.code().is_none(),
                "truncated": stdout.len() >= MAX_OUTPUT_BYTES || stderr.len() >= MAX_OUTPUT_BYTES,
            }),
            message: if success {
                Some("Command completed successfully".to_string())
            } else if exit_status.code().is_none() {
                Some(format!("Command timed out after {}s", timeout))
            } else {
                Some(format!(
                    "Command failed with exit code {}",
                    exit_status.code().unwrap_or(-1)
                ))
            },
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::capability::Capability;
    use std::time::Instant;

    #[test]
    fn executes_uptime() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "uptime" }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        eprintln!("result.success={}", result.success);
        eprintln!("result.data={}", result.data);
        eprintln!(
            "stdout={:?}",
            result.data.get("stdout").map(|v| v.as_str())
        );
        assert!(result.success);
        assert!(result.data["stdout"].as_str().unwrap().contains("up"));
    }

    #[test]
    fn captures_exit_code() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "false" }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(!result.success);
        assert_eq!(result.data["exit_code"].as_i64().unwrap(), 1);
    }

    #[test]
    fn captures_stderr() {
        let result = ShellExec
            .execute(
                &serde_json::json!({
                    "cmd": "cat",
                    "args": ["/nonexistent_path_for_stderr_test"]
                }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(!result.success);
        assert!(result.data["stderr"].as_str().unwrap().contains("No such file"));
    }

    #[test]
    fn captures_pid() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "echo hello" }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(result.success);
        assert!(result.data["pid"].as_u64().is_some());
    }

    #[test]
    fn captures_spawned_pids() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "echo hello" }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(result.success);
        let spawned = result.data["spawned_pids"]
            .as_array()
            .expect("spawned_pids should be array");
        assert!(!spawned.is_empty());
    }

    #[test]
    fn enforces_timeout() {
        let start = Instant::now();
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "sleep 5", "timeout_secs": 1 }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );

        let elapsed = start.elapsed();

        // Should timeout in ~1s, not take full 5s
        assert!(elapsed.as_secs() < 3);
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("timed out"));
    }

    #[test]
    fn validates_empty_cmd() {
        let cap = ShellExec;
        let result = cap.validate(&serde_json::json!({ "cmd": "" }));
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("empty"));
    }

    #[test]
    fn respects_dry_run() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "rm", "args": ["-rf", "/"] }),
                &Context {
                    dry_run: true,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(result.success);
        assert!(result.data["dry_run"].as_bool() == Some(true));
        assert!(result.data["cmd"].as_str().unwrap() == "rm");
    }

    #[test]
    fn prevents_shell_injection() {
        let result = ShellExec
            .execute(
                &serde_json::json!({
                    "cmd": "echo",
                    "args": ["hello; rm -rf /"]
                }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(result.success);
        assert!(result.data["stdout"]
            .as_str()
            .unwrap()
            .contains("hello; rm -rf /"));
    }

    #[test]
    fn explicit_args_separation() {
        let result = ShellExec
            .execute(
                &serde_json::json!({
                    "cmd": "echo",
                    "args": ["hello", "world"]
                }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");

        assert!(result.success);
        assert!(result.data["stdout"]
            .as_str()
            .unwrap()
            .contains("hello world"));
    }

    #[test]
    fn test_get_all_descendants_finds_children() {
        let descendants = get_all_descendants(1);
        assert!(!descendants.is_empty() || descendants.is_empty());
    }

    #[test]
    fn test_get_all_descendants_nonexistent_pid() {
        let descendants = get_all_descendants(999999);
        assert!(
            descendants.is_empty(),
            "Non-existent PID should have no descendants"
        );
    }

    // --- New tests for P0/P1 fixes ---

    #[test]
    fn blocks_dangerous_rm_rf_root() {
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "rm", "args": ["-rf", "/"] }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("dangerous"));
    }

    #[test]
    fn blocks_dangerous_dd() {
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "dd", "args": ["if=/dev/zero", "of=/dev/sda"] }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("dd"));
    }

    #[test]
    fn blocks_dangerous_mkfs() {
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "mkfs.ext4", "args": ["/dev/sda1"] }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("filesystem"));
    }

    #[test]
    fn pipes_stdin() {
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "cat", "stdin": "hello from stdin" }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );
        let output = result.expect("stdin pipe failed");
        assert!(output.success);
        assert!(output.data["stdout"]
            .as_str()
            .unwrap()
            .contains("hello from stdin"));
    }

    #[test]
    fn rejects_relative_path() {
        let result = ShellExec.execute(
            &serde_json::json!({ "cmd": "./malicious_script" }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );
        assert!(result.is_err());
        assert!(result.unwrap_err().to_string().contains("relative paths"));
    }

    #[test]
    fn output_has_truncated_flag() {
        let result = ShellExec
            .execute(
                &serde_json::json!({ "cmd": "echo", "args": ["hello"] }),
                &Context {
                    dry_run: false,
                    job_id: "test".into(),
                    working_dir: std::env::temp_dir(),
                },
            )
            .expect("Execution failed");
        assert!(result.data["truncated"].as_bool() == Some(false));
    }

    #[test]
    fn kills_descendants_on_timeout() {
        // Spawn a bash that spawns a sleep child — both should be killed
        let start = Instant::now();
        let result = ShellExec.execute(
            &serde_json::json!({
                "cmd": "bash",
                "args": ["-c", "sleep 30 & sleep 30 & wait"],
                "timeout_secs": 1
            }),
            &Context {
                dry_run: false,
                job_id: "test".into(),
                working_dir: std::env::temp_dir(),
            },
        );

        let elapsed = start.elapsed();
        assert!(elapsed.as_secs() < 3, "should timeout quickly, took {:?}", elapsed);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("timed out"));
        assert!(err.contains("descendants"), "should report descendant count: {}", err);
    }
}