vtcode-safety 0.181.2

Command safety detection, execution policies, and sandboxing for VT Code
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
//! Context-aware approval checks for recursive `rm` commands.

use std::fs;
use std::path::{Path, PathBuf};
#[cfg(any(
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly"
))]
use std::process::Command;

use super::dangerous_commands::{unwrap_command_prefix, unwrap_command_prefix_with_context};

/// One recursive-`rm` operand and the directory it resolves against.
///
/// `base` is `None` when the directory context is unknown. An unknown base
/// keeps the operand unresolved, so it stays reviewable instead of silently
/// resolving against the wrong directory.
#[derive(Debug, PartialEq, Eq)]
struct RmTarget {
    operand: String,
    base: Option<PathBuf>,
}

/// Returns whether a recursive `rm` command requires approval based on its
/// target and the command working directory.
///
/// Relative targets are resolved from `working_directory`. A mounted root,
/// its immediate children, and known mount-layout roots require approval. If
/// mount data or target resolution is unavailable, the function fails closed.
/// Shell or wrapper directory changes make relative target resolution uncertain and
/// therefore require approval for recursive deletes.
///
/// `command` is the requested argv. `script` is the shell script the command
/// executes: a compound command such as `cd /Volumes/Backup && rm --recursive
/// Photos` keeps its structure only in the script text, so both views are
/// analyzed and a non-`rm` first token cannot hide a recursive delete.
pub fn recursive_rm_targets_require_approval_in_directory(
    command: &[String],
    script: Option<&str>,
    working_directory: &Path,
) -> bool {
    let targets = recursive_rm_targets(command, script, Some(working_directory));
    if targets.is_empty() {
        return false;
    }
    let Some(mount_points) = mounted_filesystem_mount_points() else {
        // Without a mount table, recursive deletes cannot be proven to avoid
        // mounted filesystems. Keep the decision on the approval path.
        return true;
    };

    rm_targets_are_sensitive(&targets, &normalized_mount_points(&mount_points))
}

/// Collect every recursive-`rm` operand in a command and in the shell script
/// the command executes.
fn recursive_rm_targets(command: &[String], script: Option<&str>, base: Option<&Path>) -> Vec<RmTarget> {
    let mut targets = Vec::new();
    collect_argv_rm_targets(command, base, &mut targets);
    if let Some(script) = script
        && script_mentions_rm(script)
    {
        collect_script_rm_targets(script, base, &mut targets);
    }
    targets
}

/// Cheap pre-filter: a script without the `rm` token cannot delete through
/// `rm`, so it never needs the grammar pass.
fn script_mentions_rm(script: &str) -> bool {
    script.contains("rm")
}

/// Collect recursive-`rm` operands from one argv vector.
fn collect_argv_rm_targets(command: &[String], base: Option<&Path>, targets: &mut Vec<RmTarget>) {
    let Some(unwrapped) = unwrap_command_prefix_with_context(command) else {
        return;
    };
    // A wrapper that changes the directory invalidates the relative base.
    let base = base.filter(|_| !unwrapped.changes_directory);
    let command = unwrapped.command;

    if let Some(script) = shell_script_argument(command) {
        collect_script_rm_targets(script, base, targets);
        return;
    }

    let Some(executable) = command.first() else {
        return;
    };
    let executable = Path::new(executable)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(executable);
    if executable != "rm" {
        return;
    }

    let Some(arguments) = command.get(1..) else {
        return;
    };
    let parsed = parse_rm_arguments(arguments);
    if !parsed.recursive {
        return;
    }
    for operand in parsed.targets {
        targets.push(RmTarget {
            operand: operand.to_owned(),
            base: base.map(Path::to_path_buf),
        });
    }
}

/// Extract the script argument of an explicit shell invocation.
fn shell_script_argument(command: &[String]) -> Option<&str> {
    let executable = command.first()?;
    let executable = Path::new(executable)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(executable);
    if !matches!(executable, "bash" | "sh" | "zsh") {
        return None;
    }
    let flag = command.get(1)?;
    if !matches!(flag.as_str(), "-c" | "-lc" | "-ilc") {
        return None;
    }
    command.get(2).map(String::as_str)
}

/// Collect recursive-`rm` operands from a shell script.
fn collect_script_rm_targets(script: &str, base: Option<&Path>, targets: &mut Vec<RmTarget>) {
    let Some(commands) = parse_rm_shell_commands(script) else {
        // A malformed script cannot be proven to delete only ordinary paths.
        // Keep the delete reviewable instead of failing open.
        targets.push(RmTarget { operand: String::new(), base: None });
        return;
    };
    // Flattened commands do not retain control flow or subshell scope, so a
    // directory change anywhere in the script invalidates the shared base.
    let base = base.filter(|_| !commands.iter().any(|nested| changes_shell_directory(nested)));
    for nested in &commands {
        collect_argv_rm_targets(nested, base, targets);
    }
}

/// Whether any collected operand can reach a mounted filesystem.
fn rm_targets_are_sensitive(targets: &[RmTarget], mount_points: &[PathBuf]) -> bool {
    targets.iter().any(|target| rm_target_is_sensitive(target, mount_points))
}

fn rm_target_is_sensitive(target: &RmTarget, mount_points: &[PathBuf]) -> bool {
    let Some(resolved) = resolve_target_path(&target.operand, target.base.as_deref()) else {
        // A shell expansion or inaccessible working directory can hide a
        // mounted target, so unresolved recursive targets require review.
        return true;
    };

    is_known_mount_layout_target(&resolved)
        || mount_points
            .iter()
            .any(|mount_point| is_mount_root_or_top_level_target(&resolved, mount_point))
}

/// Canonicalize mount points so target comparison ignores symlinked paths.
fn normalized_mount_points(mount_points: &[PathBuf]) -> Vec<PathBuf> {
    mount_points
        .iter()
        .map(|mount_point| {
            vtcode_commons::paths::canonicalize(mount_point)
                .unwrap_or_else(|_| vtcode_commons::paths::normalize_path(mount_point))
        })
        .collect()
}

#[derive(Debug, Default, PartialEq, Eq)]
struct RmArguments<'a> {
    recursive: bool,
    targets: Vec<&'a str>,
}

fn parse_rm_arguments(arguments: &[String]) -> RmArguments<'_> {
    let mut parsed = RmArguments::default();
    let mut end_of_options = false;

    for argument in arguments {
        if end_of_options {
            parsed.targets.push(argument);
            continue;
        }

        // Treat `--` as the end of option parsing, matching Codex's pinned
        // `rm_args_include_force_option` convention in
        // `codex-rs/shell-command/src/command_safety/is_dangerous_command.rs`
        // (commit `f29d55ff0697a88226e8a9811b3c007e5f719cba`).
        if argument == "--" {
            end_of_options = true;
        } else if argument == "--recursive" {
            parsed.recursive = true;
        } else if argument.starts_with("--") {
            // `rm` has no long option that consumes a separate argument.
        } else if let Some(flags) = argument
            .strip_prefix('-')
            .filter(|flags| !flags.is_empty() && !flags.starts_with('-'))
        {
            parsed.recursive |= flags.chars().any(|flag| matches!(flag, 'r' | 'R'));
        } else {
            parsed.targets.push(argument);
        }
    }

    parsed
}

fn parse_rm_shell_commands(script: &str) -> Option<Vec<Vec<String>>> {
    // AST extraction preserves source quotes. Decode each word once at this
    // boundary so nested shell scripts and quoted options retain argv semantics.
    super::shell_parser::parse_shell_commands_tree_sitter(script)
        .ok()?
        .into_iter()
        .map(|command| {
            command
                .into_iter()
                .map(|word| {
                    // shell_words does not interpret Bash ANSI-C quoting.
                    if word.contains("$'") {
                        return None;
                    }
                    let mut words = shell_words::split(&word).ok()?;
                    if words.len() == 1 { words.pop() } else { None }
                })
                .collect()
        })
        .collect()
}

/// Whether a command changes the shell's working directory.
///
/// The shared prefix unwrapping already resolves runner and builtin prefixes,
/// so the executable that decides the directory change is the first word.
fn changes_shell_directory(command: &[String]) -> bool {
    let Some(command) = unwrap_command_prefix(command) else {
        return false;
    };
    matches!(command.first().map(String::as_str), Some("cd" | "pushd" | "popd"))
}

fn resolve_target_path(target: &str, working_directory: Option<&Path>) -> Option<PathBuf> {
    if target
        .chars()
        .any(|character| matches!(character, '$' | '`' | '*' | '?' | '[' | ']' | '{' | '}' | '~'))
    {
        return None;
    }

    let target_path = Path::new(target);
    let candidate = if target_path.is_absolute() {
        target_path.to_path_buf()
    } else {
        let working_directory = working_directory?;
        let working_directory = if working_directory.is_absolute() {
            working_directory.to_path_buf()
        } else {
            std::env::current_dir().ok()?.join(working_directory)
        };
        working_directory.join(target_path)
    };

    canonicalize_allowing_missing(&candidate)
}

fn canonicalize_allowing_missing(path: &Path) -> Option<PathBuf> {
    let mut ancestor = path;
    let mut missing_components = Vec::new();

    loop {
        match vtcode_commons::paths::canonicalize(ancestor) {
            Ok(mut resolved) => {
                for component in missing_components.iter().rev() {
                    resolved.push(component);
                }
                return Some(vtcode_commons::paths::normalize_path(&resolved));
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                missing_components.push(ancestor.file_name()?.to_os_string());
                ancestor = ancestor.parent()?;
            }
            Err(_) => return None,
        }
    }
}

fn is_known_mount_layout_target(target: &Path) -> bool {
    path_is_within_depth(target, Path::new("/Volumes"), 2)
        || path_is_within_depth(target, Path::new("/media"), 3)
        || is_wsl_drive_layout_target(target)
}

fn path_is_within_depth(target: &Path, root: &Path, max_relative_depth: usize) -> bool {
    target
        .strip_prefix(root)
        .is_ok_and(|relative| relative.components().count() <= max_relative_depth)
}

fn is_wsl_drive_layout_target(target: &Path) -> bool {
    let root = Path::new("/mnt");
    if target == root {
        return true;
    }

    let Ok(relative) = target.strip_prefix(root) else {
        return false;
    };
    let mut components = relative.components();
    let Some(std::path::Component::Normal(drive)) = components.next() else {
        return false;
    };
    let Some(drive) = drive.to_str() else {
        return false;
    };
    drive.len() == 1 && drive.bytes().next().is_some_and(|byte| byte.is_ascii_alphabetic()) && components.count() <= 1
}

fn is_mount_root_or_top_level_target(target: &Path, mount_point: &Path) -> bool {
    target == mount_point
        || target.parent() == Some(mount_point)
        // Removing an ancestor recursively would traverse into the mount.
        || mount_point.starts_with(target)
}

#[cfg(target_os = "linux")]
fn mounted_filesystem_mount_points() -> Option<Vec<PathBuf>> {
    parse_linux_mount_info(&fs::read_to_string("/proc/self/mountinfo").ok()?)
}

#[cfg(any(
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly"
))]
fn mounted_filesystem_mount_points() -> Option<Vec<PathBuf>> {
    let output = Command::new("/sbin/mount").output().ok()?;
    if !output.status.success() {
        return None;
    }
    parse_bsd_mount_output(&String::from_utf8(output.stdout).ok()?)
}

#[cfg(not(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly"
)))]
fn mounted_filesystem_mount_points() -> Option<Vec<PathBuf>> {
    None
}

#[cfg(any(target_os = "linux", test))]
fn parse_linux_mount_info(contents: &str) -> Option<Vec<PathBuf>> {
    parse_mount_points(contents.lines().map(|line| line.split_whitespace().nth(4)))
}

#[cfg(any(
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    test
))]
fn parse_bsd_mount_output(contents: &str) -> Option<Vec<PathBuf>> {
    parse_mount_points(contents.lines().map(|line| {
        let (_, mount_description) = line.split_once(" on ")?;
        let (mount_point, _) = mount_description.rsplit_once(" (")?;
        Some(mount_point)
    }))
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    test
))]
fn parse_mount_points<'a>(fields: impl Iterator<Item = Option<&'a str>>) -> Option<Vec<PathBuf>> {
    let mount_points: Option<Vec<PathBuf>> = fields
        .map(|field| {
            let decoded = decode_mount_path(field?)?;
            let path = PathBuf::from(decoded);
            path.is_absolute().then_some(path)
        })
        .collect();
    let mount_points = mount_points?;
    (!mount_points.is_empty()).then_some(mount_points)
}

#[cfg(any(
    target_os = "linux",
    target_os = "macos",
    target_os = "freebsd",
    target_os = "openbsd",
    target_os = "netbsd",
    target_os = "dragonfly",
    test
))]
fn decode_mount_path(encoded: &str) -> Option<String> {
    let decoded = encoded
        .replace("\\040", " ")
        .replace("\\011", "\t")
        .replace("\\012", "\n")
        .replace("\\134", "\\");
    if decoded.is_empty() {
        return None;
    }
    Some(decoded)
}

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

    fn command(args: &[&str]) -> Vec<String> {
        args.iter().map(|argument| (*argument).to_owned()).collect()
    }

    /// Approval decision with injected mount points, mirroring the production
    /// path without touching the host mount table.
    fn approval_with_mount_points(
        command: &[String],
        script: Option<&str>,
        working_directory: &Path,
        mount_points: Option<&[PathBuf]>,
    ) -> bool {
        let targets = recursive_rm_targets(command, script, Some(working_directory));
        if targets.is_empty() {
            return false;
        }
        let Some(mount_points) = mount_points else {
            return true;
        };
        rm_targets_are_sensitive(&targets, &normalized_mount_points(mount_points))
    }

    /// Sensitivity of a command's recursive-`rm` targets against injected
    /// mount points.
    fn recursive_rm_targets_are_sensitive(
        command: &[String],
        working_directory: &Path,
        mount_points: &[PathBuf],
    ) -> bool {
        let targets = recursive_rm_targets(command, None, Some(working_directory));
        rm_targets_are_sensitive(&targets, &normalized_mount_points(mount_points))
    }

    #[test]
    fn rm_parser_reads_recursive_options_and_end_of_options_targets() {
        for args in [
            command(&["-r", "/mnt/c"]),
            command(&["-rf", "/mnt/c"]),
            command(&["-fiR", "/mnt/c"]),
            command(&["--recursive", "/mnt/c"]),
        ] {
            let parsed = parse_rm_arguments(&args);
            assert!(parsed.recursive, "expected recursive option: {args:?}");
            assert_eq!(parsed.targets, ["/mnt/c"]);
        }

        let args = command(&["--", "-r", "/mnt/c"]);
        let after_separator = parse_rm_arguments(&args);
        assert!(!after_separator.recursive);
        assert_eq!(after_separator.targets, ["-r", "/mnt/c"]);

        let args = command(&["-fiR", "--", "-target", "/mnt/c"]);
        let parsed = parse_rm_arguments(&args);
        assert!(parsed.recursive);
        assert_eq!(parsed.targets, ["-target", "/mnt/c"]);
    }

    #[test]
    fn recursive_rm_prompts_for_mount_roots_and_immediate_children() {
        let mounts = [PathBuf::from("/"), PathBuf::from("/custom/archive")];
        for target in [
            "/Applications",
            "/Volumes",
            "/Volumes/Backup",
            "/Volumes/Backup/Photos",
            "/media",
            "/media/user/USB/Photos",
            "/mnt/c",
            "/mnt/c/Users",
            "/custom/archive",
            "/custom/archive/Photos",
        ] {
            assert!(
                recursive_rm_targets_are_sensitive(
                    &command(&["rm", "--recursive", target]),
                    Path::new("/tmp"),
                    &mounts
                ),
                "expected prompt for {target}"
            );
        }

        for invocation in [
            command(&["rm", "-r", "/Volumes"]),
            command(&["rm", "-rf", "/Volumes/Backup"]),
            command(&["rm", "-fiR", "/media/user/USB/Photos"]),
            command(&["rm", "--recursive", "/mnt/c/Users"]),
            command(&["rm", "-r", "--", "/custom/archive/Photos"]),
            command(&["bash", "-lc", "rm --recursive /custom/archive/Photos"]),
        ] {
            assert!(
                recursive_rm_targets_are_sensitive(&invocation, Path::new("/tmp"), &mounts),
                "expected prompt for {invocation:?}"
            );
        }

        for target in [
            "/Volumes/Backup/Photos/2026",
            "/custom/archive/Photos/2026",
            "/tmp/project/target",
        ] {
            assert!(
                !recursive_rm_targets_are_sensitive(&command(&["rm", "-r", target]), Path::new("/tmp"), &mounts),
                "ordinary nested target should not be newly classified: {target}"
            );
        }
    }

    #[test]
    fn recursive_rm_resolves_relative_targets_from_working_directory() {
        let temp_dir = tempfile::tempdir().expect("temporary directory");
        let mount_point = temp_dir.path().join("drive");
        fs::create_dir_all(mount_point.join("Projects")).expect("create mount fixture");
        let mounts = [mount_point.clone()];

        assert!(recursive_rm_targets_are_sensitive(&command(&["rm", "-rf", "Projects"]), &mount_point, &mounts));
        assert!(recursive_rm_targets_are_sensitive(&command(&["rm", "-r", "--", "Projects"]), &mount_point, &mounts));
        assert!(!recursive_rm_targets_are_sensitive(
            &command(&["rm", "--", "-r", "Projects"]),
            &mount_point,
            &mounts
        ));
    }

    #[test]
    fn recursive_rm_after_shell_directory_changes_requires_approval() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup")];

        for script in [
            "cd /Volumes/Backup && rm --recursive Photos",
            "cd /Volumes/Backup && rm --recursive Photos &&",
            "'cd' /Volumes/Backup && 'rm' '--recursive' 'Photos'",
            "$'cd' /Volumes/Backup && rm --recursive Photos",
            "builtin cd /Volumes/Backup; rm -r Photos",
            "command -- cd /Volumes/Backup && rm -R Photos",
            "pushd /Volumes/Backup && rm --recursive Photos",
            "popd; rm --recursive Photos",
            "if cd /Volumes/Backup; then rm --recursive Photos; fi",
            "(cd /Volumes/Backup && rm --recursive Photos)",
            "cd /Volumes/Backup && sh -c 'rm --recursive Photos'",
            "sh -c 'cd /Volumes/Backup && rm --recursive Photos'",
            // Flattening cannot establish directory scope or ordering safely.
            "rm --recursive Photos; cd /Volumes/Backup",
        ] {
            assert!(
                approval_with_mount_points(&command(&["bash", "-lc", script]), None, project.path(), Some(&mounts),),
                "relative recursive target needs approval with uncertain directory: {script}"
            );
        }

        let absolute_cleanup =
            format!("cd /Volumes/Backup && rm --recursive '{}'", project.path().join("build/cache").display());
        for script in [
            "rm --recursive Photos",
            "echo cd /Volumes/Backup && rm --recursive Photos",
            "cd /Volumes/Backup && rm -- Photos",
            absolute_cleanup.as_str(),
        ] {
            assert!(
                !approval_with_mount_points(&command(&["bash", "-lc", script]), None, project.path(), Some(&mounts),),
                "known ordinary targets or nonrecursive deletes should retain their classification: {script}"
            );
        }
    }

    #[test]
    fn recursive_rm_preserves_directory_uncertainty_from_command_wrappers() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup")];
        for invocation in [
            command(&["sudo", "--chdir", "/Volumes/Backup", "rm", "--recursive", "Photos"]),
            command(&["sudo", "--chdir=/Volumes/Backup", "rm", "--recursive", "Photos"]),
            command(&[
                "env",
                "MODE=test",
                "sudo",
                "--chdir=/Volumes/Backup",
                "rm",
                "--recursive",
                "Photos",
            ]),
            command(&["sudo", "--chdir=/Volumes/Backup", "sh", "-c", "rm --recursive Photos"]),
        ] {
            assert!(!super::super::command_might_be_dangerous(&invocation));
            assert!(
                approval_with_mount_points(&invocation, None, project.path(), Some(&mounts)),
                "a directory-changing wrapper must invalidate relative target context: {invocation:?}"
            );
        }

        let absolute_cleanup = project.path().join("build/cache");
        for invocation in [
            command(&["sudo", "-u", "root", "rm", "--recursive", "Photos"]),
            command(&["sudo", "-C", "3", "rm", "--recursive", "Photos"]),
            command(&[
                "sudo",
                "--chdir=/Volumes/Backup",
                "rm",
                "--recursive",
                absolute_cleanup.to_str().unwrap(),
            ]),
        ] {
            assert!(
                !approval_with_mount_points(&invocation, None, project.path(), Some(&mounts)),
                "ordinary wrappers and absolute project targets retain their classification: {invocation:?}"
            );
        }
    }

    #[test]
    fn recursive_rm_with_unresolved_targets_fails_closed() {
        let command = command(&["rm", "--recursive", "$TARGET"]);
        assert!(recursive_rm_targets_are_sensitive(&command, Path::new("/tmp"), &[]));
        assert!(approval_with_mount_points(&command, None, Path::new("/tmp"), Some(&[])));
    }

    #[test]
    fn ordinary_recursive_project_cleanup_stays_unchanged_with_mount_data() {
        let temp_dir = tempfile::tempdir().expect("temporary directory");
        let target = temp_dir.path().join("build/cache");
        fs::create_dir_all(&target).expect("create project fixture");
        let command = command(&["rm", "--recursive", "build/cache"]);
        let mount_points = [PathBuf::from("/"), PathBuf::from("/custom/archive")];

        assert!(!approval_with_mount_points(&command, None, temp_dir.path(), Some(&mount_points)));
    }

    #[test]
    fn recursive_rm_requires_approval_when_mount_data_is_unavailable() {
        let command = command(&["rm", "--recursive", "build/cache"]);
        assert!(approval_with_mount_points(&command, None, Path::new("/tmp/project"), None));
    }

    #[test]
    fn mount_tables_decode_paths_and_reject_incomplete_data() {
        let linux =
            parse_linux_mount_info("36 25 0:32 / /mnt/My\\040Drive rw - ext4 /dev/sda1 rw\n").expect("valid mountinfo");
        assert_eq!(linux, [PathBuf::from("/mnt/My Drive")]);
        assert!(parse_bsd_mount_output("/dev/disk3 on /Volumes/My\\040Drive (apfs, local)\n").is_some());
        assert!(parse_linux_mount_info("malformed\n").is_none());
        assert!(parse_bsd_mount_output("malformed\n").is_none());
    }

    /// A compound command string is tokenized before it reaches the safety
    /// layer, so the shell structure only survives in the script text. The
    /// script view must still find the recursive delete behind a non-`rm`
    /// first token.
    #[test]
    fn compound_command_scripts_cannot_hide_a_recursive_delete() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup")];
        let compound = command(&["cd", "/Volumes/Backup", "&&", "rm", "--recursive", "Photos"]);

        // The tokenized argv alone carries no shell structure.
        assert!(
            !approval_with_mount_points(&compound, None, project.path(), Some(&mounts)),
            "the argv view alone cannot classify a compound command"
        );
        // The script view recovers the delete and keeps it reviewable.
        assert!(
            approval_with_mount_points(
                &compound,
                Some("cd /Volumes/Backup && rm --recursive Photos"),
                project.path(),
                Some(&mounts)
            ),
            "a compound command must not hide a mounted recursive delete"
        );

        // Asymmetric boundary: the same compound shape without a recursive
        // delete stays unclassified, and a relative delete in an ordinary
        // project directory stays unclassified.
        assert!(!approval_with_mount_points(
            &command(&["cd", "/Volumes/Backup", "&&", "rm", "Photos"]),
            Some("cd /Volumes/Backup && rm Photos"),
            project.path(),
            Some(&mounts)
        ));
        assert!(!approval_with_mount_points(
            &command(&["rm", "--recursive", "build"]),
            Some("rm --recursive build"),
            project.path(),
            Some(&mounts)
        ));
    }

    /// A shell builtin that runs the next word must not hide the delete.
    #[test]
    fn builtin_prefix_cannot_hide_a_recursive_delete() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup")];
        for invocation in [
            command(&["command", "rm", "--recursive", "/Volumes/Backup/Photos"]),
            command(&["builtin", "rm", "--recursive", "/Volumes/Backup/Photos"]),
            command(&["command", "--", "rm", "--recursive", "/Volumes/Backup/Photos"]),
        ] {
            assert!(
                approval_with_mount_points(&invocation, None, project.path(), Some(&mounts)),
                "a builtin prefix must not hide a mounted recursive delete: {invocation:?}"
            );
        }

        // A lookup is not a delete.
        assert!(!approval_with_mount_points(&command(&["command", "-v", "rm"]), None, project.path(), Some(&mounts)));
    }

    /// The script view must not turn ordinary commands into approvals.
    #[test]
    fn script_view_keeps_ordinary_commands_unclassified() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup"), PathBuf::from("/")];

        for script in [
            "ls -la",
            "cargo fmt --all",
            "echo 'rm -rf /'",
            "grep -r rm src",
            "rm build/cache",
            "rm -f build/cache",
        ] {
            assert!(
                !approval_with_mount_points(
                    &command(&["sh", "-c", script]),
                    Some(script),
                    project.path(),
                    Some(&mounts),
                ),
                "ordinary command must not require approval: {script}"
            );
        }
    }

    /// A malformed script cannot be proven to delete only ordinary paths, so
    /// it stays on the approval path instead of failing open.
    #[test]
    fn malformed_recursive_script_fails_closed() {
        let project = tempfile::tempdir().expect("project directory");
        let mounts = [PathBuf::from("/Volumes/Backup")];
        let malformed = "rm --recursive 'unterminated";

        assert!(approval_with_mount_points(
            &command(&["sh", "-c", malformed]),
            Some(malformed),
            project.path(),
            Some(&mounts),
        ));
    }
}