agengo 0.5.1

Orchestrate AI coding agents (Claude Code) to build, verify, review and integrate tasks in isolated Git worktrees
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
//! What agengo does to confine the agents it starts (`sandbox` in
//! `.agengo/config.yaml`, or `--sandbox`): which agents have an OS sandbox
//! agengo can switch on and check, and which environment variables an agent
//! is given. This narrows the damage a mistaken or manipulated agent can do;
//! it is not complete isolation (see docs/guide.md, "Security limits").

use crate::adapter::API_KEY_VARIABLES;
use crate::config::{Config, Sandbox};
use anyhow::{bail, Result};
use std::{ffi::OsStr, path::Path, process::Command};

/// What agengo can say about an agent's sandbox before starting it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Support {
    /// agengo switches the sandbox on and has checked it can start.
    Enforced,
    /// The agent has a sandbox of its own that agengo asks for but cannot
    /// check.
    Unchecked(String),
    /// agengo cannot sandbox this agent here.
    Unavailable(String),
}

impl Support {
    pub fn is_enforced(&self) -> bool {
        matches!(self, Self::Enforced)
    }

    fn reason(&self) -> &str {
        match self {
            Self::Enforced => "",
            Self::Unchecked(reason) | Self::Unavailable(reason) => reason,
        }
    }
}

/// Whether Claude Code's sandbox can run here. It needs bubblewrap and socat
/// on Linux and WSL2, uses Seatbelt on macOS, and does not exist on native
/// Windows.
pub fn claude_support(cwd: &Path) -> Support {
    let has = |program: &str| crate::process::resolve(OsStr::new(program), cwd).is_some();
    claude_support_for(std::env::consts::OS, has("bwrap"), has("socat"))
}

/// Whether Codex's sandbox can run here. It is built in on macOS and Windows;
/// on Linux and WSL2 it uses bubblewrap, and without `bwrap` on PATH it falls
/// back to a bundled helper that needs unprivileged user namespaces, which
/// agengo cannot check.
pub fn codex_support(cwd: &Path) -> Support {
    let bubblewrap = crate::process::resolve(OsStr::new("bwrap"), cwd).is_some();
    codex_support_for(std::env::consts::OS, bubblewrap)
}

fn codex_support_for(os: &str, bubblewrap: bool) -> Support {
    match os {
        "macos" | "windows" => Support::Enforced,
        "linux" if bubblewrap => Support::Enforced,
        "linux" => Support::Unchecked(
            "Codex's sandbox on Linux uses bubblewrap (`sudo apt-get install bubblewrap`); without it Codex falls back to a helper that needs user namespaces, which agengo cannot check".into(),
        ),
        other => Support::Unchecked(format!("agengo does not know whether Codex's sandbox works on {other}")),
    }
}

fn claude_support_for(os: &str, bubblewrap: bool, socat: bool) -> Support {
    match os {
        "macos" => Support::Enforced,
        "linux" if bubblewrap && socat => Support::Enforced,
        "linux" => {
            let missing: Vec<&str> = [(bubblewrap, "bubblewrap (bwrap)"), (socat, "socat")]
                .iter()
                .filter(|(found, _)| !found)
                .map(|(_, name)| *name)
                .collect();
            Support::Unavailable(format!(
                "Claude Code's sandbox needs {} on PATH (for example `sudo apt-get install bubblewrap socat`)",
                missing.join(" and ")
            ))
        }
        "windows" => Support::Unavailable(
            "Claude Code has no sandbox on native Windows; use WSL2, or run agengo in a container or VM".into(),
        ),
        other => Support::Unavailable(format!("Claude Code's sandbox is not supported on {other}")),
    }
}

/// Apply the sandbox mode to an agent: refuse in `strict` mode when the
/// sandbox cannot be enforced, say so once in `auto` mode.
pub fn check(mode: Sandbox, agent: &str, support: &Support) -> Result<()> {
    if mode == Sandbox::Off || support.is_enforced() {
        return Ok(());
    }
    if mode == Sandbox::Strict {
        bail!(
            "--sandbox strict needs an agent whose sandbox agengo can enforce, and {agent} is not one here: {}. Fix that, run agengo in a container or VM and use --sandbox auto, or use --sandbox off.",
            support.reason()
        );
    }
    note_once(agent, support.reason());
    Ok(())
}

fn note_once(agent: &str, reason: &str) {
    use std::sync::Mutex;
    static SAID: Mutex<Vec<String>> = Mutex::new(Vec::new());
    if let Ok(mut said) = SAID.lock() {
        if !said.iter().any(|name| name == agent) {
            said.push(agent.to_owned());
            eprintln!("agengo: note: {agent} runs without an OS sandbox from agengo ({reason})");
        }
    }
}

/// Variables every agent and the tools it runs usually need. Anything else
/// (`GITHUB_TOKEN`, `AWS_*`, `NPM_TOKEN`, ...) stays out unless the user lists
/// it under `sandbox_env`.
const KEPT: &[&str] = &[
    "PATH",
    "HOME",
    "USER",
    "LOGNAME",
    "SHELL",
    "LANG",
    "LANGUAGE",
    "TERM",
    "COLORTERM",
    "NO_COLOR",
    "TMPDIR",
    "TMP",
    "TEMP",
    "TZ",
    "PWD",
    "SSL_CERT_FILE",
    "SSL_CERT_DIR",
    "REQUESTS_CA_BUNDLE",
    "CURL_CA_BUNDLE",
    "HTTP_PROXY",
    "HTTPS_PROXY",
    "NO_PROXY",
    "ALL_PROXY",
    "CARGO_HOME",
    "RUSTUP_HOME",
    "GOPATH",
    "GOROOT",
    "JAVA_HOME",
    "VIRTUAL_ENV",
    "NVM_DIR",
    "SYSTEMROOT",
    "COMSPEC",
    "PATHEXT",
    "USERPROFILE",
    "APPDATA",
    "LOCALAPPDATA",
    "PROGRAMFILES",
    "WINDIR",
    "DISPLAY",
    "WAYLAND_DISPLAY",
];

/// Prefixes of variables that belong to the agents themselves or to the
/// system: their settings, login tokens and locale.
const KEPT_PREFIXES: &[&str] = &[
    "LC_",
    "XDG_",
    "CLAUDE",
    "CODEX",
    "ANTIGRAVITY",
    "AGY_",
    "ANTHROPIC_",
    "OPENAI_",
    "GEMINI_",
    "AGENGO_",
];

/// The variables to pass on, from `vars`. Names compare without regard to
/// case, because Windows does not tell them apart.
fn kept(
    vars: impl Iterator<Item = (String, String)>,
    extra: &[String],
    api_keys: bool,
) -> Vec<(String, String)> {
    vars.filter(|(name, _)| {
        let upper = name.to_ascii_uppercase();
        if extra.iter().any(|wanted| wanted.eq_ignore_ascii_case(name)) {
            return true;
        }
        if API_KEY_VARIABLES.contains(&upper.as_str()) {
            return api_keys;
        }
        KEPT.contains(&upper.as_str())
            || KEPT_PREFIXES.iter().any(|prefix| upper.starts_with(prefix))
    })
    .collect()
}

/// Give an agent's `command` only the variables in `kept`. With `--auth
/// subscription` the caller removes the API key variables afterwards, as
/// before.
pub fn filter_env(command: &mut Command, extra: &[String]) {
    command
        .env_clear()
        .envs(kept(std::env::vars(), extra, true));
}

/// Which kind of plan command is being started: `setup` installs what the
/// task needs and so may use the network; everything else only checks.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Phase {
    Setup,
    Check,
}

/// Home folders and files that hold credentials. They are hidden from plan
/// commands in the sandbox.
const SECRET_PATHS: &[&str] = &[
    ".ssh",
    ".aws",
    ".gnupg",
    ".kube",
    ".docker",
    ".azure",
    ".config/gh",
    ".config/gcloud",
    ".netrc",
    ".git-credentials",
];

/// Folders under home that build tools write to; they stay writable if they
/// exist.
const CACHE_PATHS: &[&str] = &[".cargo", ".npm", ".cache"];

/// Whether commands from the plan can be put in a sandbox here: Linux with
/// bubblewrap. (macOS and Windows have no wrapper yet.)
fn plan_sandbox_unavailable(cwd: &Path) -> Option<String> {
    let has_bwrap = crate::process::resolve(OsStr::new("bwrap"), cwd).is_some();
    plan_sandbox_unavailable_for(std::env::consts::OS, has_bwrap)
}

fn plan_sandbox_unavailable_for(os: &str, bubblewrap: bool) -> Option<String> {
    match (os, bubblewrap) {
        ("linux", true) => None,
        ("linux", false) => Some(
            "plan commands need bubblewrap to be sandboxed (`sudo apt-get install bubblewrap`)"
                .into(),
        ),
        (other, _) => Some(format!(
            "plan commands cannot be sandboxed on {other} yet; run agengo on Linux or WSL2, or in a container"
        )),
    }
}

/// The `bwrap` arguments that confine a plan command: the whole file system
/// read-only except the worktree (and the Git folder of that worktree), a
/// scratch `/tmp`, the package caches and what the user lists; credential
/// folders hidden; and no network unless `network` is set.
fn bwrap_args(
    worktree: &Path,
    git_dir: Option<&Path>,
    git_common_dir: Option<&Path>,
    home: Option<&Path>,
    exists: &dyn Fn(&Path) -> bool,
    network: bool,
    extra_write: &[String],
) -> Vec<String> {
    let text = |path: &Path| path.to_string_lossy().into_owned();
    let mut args: Vec<String> = [
        "--ro-bind",
        "/",
        "/",
        "--dev",
        "/dev",
        "--proc",
        "/proc",
        "--tmpfs",
        "/tmp",
        "--die-with-parent",
        "--new-session",
    ]
    .iter()
    .map(|part| (*part).to_owned())
    .collect();
    // The scratch `/tmp` hides a repository that lives there, so its shared
    // Git folder comes back read-only before the writable parts.
    if let Some(common) = git_common_dir.filter(|common| common.starts_with("/tmp")) {
        args.extend(["--ro-bind".into(), text(common), text(common)]);
    }
    let mut bind = |path: &Path| {
        args.extend(["--bind".into(), text(path), text(path)]);
    };
    bind(worktree);
    if let Some(git_dir) = git_dir {
        bind(git_dir);
    }
    if let Some(home) = home {
        for name in CACHE_PATHS {
            let path = home.join(name);
            if exists(&path) {
                bind(&path);
            }
        }
    }
    for wanted in extra_write {
        let path = match (wanted.strip_prefix("~/"), home) {
            (Some(rest), Some(home)) => home.join(rest),
            _ => Path::new(wanted).to_path_buf(),
        };
        if exists(&path) {
            bind(&path);
        }
    }
    if let Some(home) = home {
        for name in SECRET_PATHS {
            let path = home.join(name);
            if !exists(&path) {
                continue;
            }
            if path.is_dir() {
                args.extend(["--tmpfs".into(), text(&path)]);
            } else {
                args.extend(["--ro-bind".into(), "/dev/null".into(), text(&path)]);
            }
        }
    }
    if !network {
        args.push("--unshare-net".into());
    }
    args.extend(["--chdir".into(), text(worktree), "--".into()]);
    args
}

/// A `setup`, `verify` or other command from the plan. With `sandbox` not
/// `off` it gets the same short environment as an agent, minus the API keys:
/// a build or test command has no use for the key that pays for the agent.
/// On Linux with bubblewrap it also runs confined: it can write only in the
/// worktree, its Git folder, a scratch `/tmp` and the package caches, cannot
/// see credential folders, and has no network unless it is a `setup` command
/// or `sandbox_check_network` is set. Where that is not possible `auto` says so
/// once and runs it as before, and `strict` refuses.
pub fn plan_command(
    command: &[String],
    cwd: &Path,
    config: &Config,
    phase: Phase,
) -> Result<Command> {
    let unavailable = if config.sandbox == Sandbox::Off {
        None
    } else {
        plan_sandbox_unavailable(cwd)
    };
    plan_command_with(command, cwd, config, phase, unavailable)
}

fn plan_command_with(
    command: &[String],
    cwd: &Path,
    config: &Config,
    phase: Phase,
    unavailable: Option<String>,
) -> Result<Command> {
    let mut result = crate::process::argv(command, cwd)?;
    if config.sandbox == Sandbox::Off {
        return Ok(result);
    }
    let vars = kept(std::env::vars(), &config.sandbox_env, false);
    if let Some(reason) = unavailable {
        if config.sandbox == Sandbox::Strict {
            bail!("--sandbox strict cannot confine a plan command here: {reason}");
        }
        note_once("plan commands", &reason);
        result.env_clear().envs(vars);
        return Ok(result);
    }
    let git_dir = crate::process::run(
        Command::new("git")
            .current_dir(cwd)
            .args(["rev-parse", "--absolute-git-dir"]),
        None,
        Some(10),
    )
    .ok()
    .filter(|output| output.status.success())
    .map(|output| std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()));
    let git_common_dir = crate::process::run(
        Command::new("git").current_dir(cwd).args([
            "rev-parse",
            "--path-format=absolute",
            "--git-common-dir",
        ]),
        None,
        Some(10),
    )
    .ok()
    .filter(|output| output.status.success())
    .map(|output| std::path::PathBuf::from(String::from_utf8_lossy(&output.stdout).trim()));
    let home = std::env::var_os("HOME").map(std::path::PathBuf::from);
    let network = phase == Phase::Setup || config.sandbox_check_network;
    let worktree = cwd.canonicalize().unwrap_or_else(|_| cwd.to_path_buf());
    let mut wrapped = Command::new("bwrap");
    wrapped
        .args(bwrap_args(
            &worktree,
            git_dir.as_deref(),
            git_common_dir.as_deref(),
            home.as_deref(),
            &|path| path.exists(),
            network,
            &config.sandbox_write,
        ))
        .arg(result.get_program())
        .args(result.get_args())
        .current_dir(cwd)
        .env_clear()
        .envs(vars);
    Ok(wrapped)
}

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

    fn vars(names: &[&str]) -> Vec<(String, String)> {
        names
            .iter()
            .map(|n| ((*n).to_owned(), "x".to_owned()))
            .collect()
    }

    #[test]
    fn secrets_stay_out_unless_listed() {
        let all = vars(&[
            "PATH",
            "HOME",
            "GITHUB_TOKEN",
            "AWS_SECRET_ACCESS_KEY",
            "NPM_TOKEN",
            "LC_ALL",
            "CLAUDE_CODE_OAUTH_TOKEN",
            "CODEX_HOME",
            "OPENAI_API_KEY",
            "Path",
        ]);
        let names = |extra: &[String]| -> Vec<String> {
            kept(all.clone().into_iter(), extra, true)
                .into_iter()
                .map(|(name, _)| name)
                .collect()
        };
        let plain = names(&[]);
        for wanted in [
            "PATH",
            "HOME",
            "LC_ALL",
            "CLAUDE_CODE_OAUTH_TOKEN",
            "CODEX_HOME",
            "Path",
        ] {
            assert!(plain.contains(&wanted.to_owned()), "{wanted} is dropped");
        }
        for secret in ["GITHUB_TOKEN", "AWS_SECRET_ACCESS_KEY", "NPM_TOKEN"] {
            assert!(!plain.contains(&secret.to_owned()), "{secret} is passed");
        }
        // API keys pass here so `--auth api` still works; `--auth
        // subscription` removes them afterwards.
        assert!(plain.contains(&"OPENAI_API_KEY".to_owned()));
        assert!(names(&["github_token".to_owned()]).contains(&"GITHUB_TOKEN".to_owned()));
        // Plan commands never get the API keys.
        let no_keys: Vec<String> = kept(all.clone().into_iter(), &[], false)
            .into_iter()
            .map(|(name, _)| name)
            .collect();
        assert!(!no_keys.contains(&"OPENAI_API_KEY".to_owned()));
        assert!(no_keys.contains(&"PATH".to_owned()));
    }

    #[test]
    fn claude_sandbox_support_by_platform() {
        assert!(claude_support_for("macos", false, false).is_enforced());
        assert!(claude_support_for("linux", true, true).is_enforced());
        let missing = claude_support_for("linux", true, false);
        assert!(missing.reason().contains("socat"), "{missing:?}");
        assert!(missing.reason().contains("needs socat on PATH"));
        assert!(claude_support_for("windows", true, true)
            .reason()
            .contains("WSL2"));
    }

    #[test]
    fn codex_sandbox_support_by_platform() {
        assert!(codex_support_for("windows", false).is_enforced());
        assert!(codex_support_for("macos", false).is_enforced());
        assert!(codex_support_for("linux", true).is_enforced());
        assert!(!codex_support_for("linux", false).is_enforced());
        assert!(codex_support_for("linux", false)
            .reason()
            .contains("bubblewrap"));
    }

    #[test]
    fn strict_refuses_what_cannot_be_enforced_and_auto_does_not() {
        let cannot = Support::Unavailable("no sandbox here".into());
        assert!(check(Sandbox::Off, "agy", &cannot).is_ok());
        assert!(check(Sandbox::Auto, "agy", &cannot).is_ok());
        assert!(check(Sandbox::Strict, "claude", &Support::Enforced).is_ok());
        let error = check(Sandbox::Strict, "agy", &cannot)
            .unwrap_err()
            .to_string();
        assert!(
            error.contains("agy") && error.contains("no sandbox here"),
            "{error}"
        );
    }

    #[cfg(unix)]
    #[test]
    fn plan_commands_get_the_short_environment_only_when_asked() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let run = |sandbox| -> Result<String> {
            let config = Config {
                sandbox,
                ..Config::default()
            };
            let mut command = plan_command_with(
                &["env".to_owned()],
                dir.path(),
                &config,
                Phase::Check,
                Some("no wrapper in this test".into()),
            )?;
            Ok(String::from_utf8(command.output()?.stdout)?)
        };
        // Cargo fills the test's environment with its own variables.
        assert!(run(Sandbox::Off)?.contains("CARGO_MANIFEST_DIR="));
        let env = run(Sandbox::Auto)?;
        assert!(env.contains("PATH="));
        assert!(!env.contains("CARGO_MANIFEST_DIR="), "{env}");
        Ok(())
    }

    #[test]
    #[cfg(unix)]
    fn bwrap_confines_writes_hides_secrets_and_closes_the_network() {
        let exists = |path: &Path| {
            matches!(
                path.to_str(),
                Some("/home/u/.cargo" | "/home/u/.ssh" | "/home/u/.netrc" | "/home/u/data")
            )
        };
        let args = bwrap_args(
            Path::new("/work/wt"),
            Some(Path::new("/repo/.git/worktrees/wt")),
            Some(Path::new("/tmp/r/.git")),
            Some(Path::new("/home/u")),
            &exists,
            false,
            &["~/data".to_owned(), "~/missing".to_owned()],
        );
        let joined = args.join(" ");
        assert!(joined.starts_with("--ro-bind / / --dev /dev --proc /proc --tmpfs /tmp"));
        for wanted in [
            "--tmpfs /tmp --die-with-parent --new-session --ro-bind /tmp/r/.git /tmp/r/.git --bind /work/wt /work/wt",
            "--bind /repo/.git/worktrees/wt /repo/.git/worktrees/wt",
            "--bind /home/u/.cargo /home/u/.cargo",
            "--bind /home/u/data /home/u/data",
            "--ro-bind /dev/null /home/u/.netrc",
            "--unshare-net",
            "--chdir /work/wt --",
        ] {
            assert!(joined.contains(wanted), "{wanted} missing from {joined}");
        }
        assert!(!joined.contains("/home/u/missing"));
        assert!(
            !joined.contains("--bind /home/u/.ssh"),
            "secrets are hidden, not bound"
        );
        assert_eq!(args.last().map(String::as_str), Some("--"));
        // With the network allowed, nothing unshares it.
        let open = bwrap_args(Path::new("/work/wt"), None, None, None, &exists, true, &[]);
        assert!(!open.contains(&"--unshare-net".to_owned()));
    }

    #[test]
    #[cfg(unix)]
    fn plan_commands_run_through_bwrap_and_strict_refuses_without_it() -> Result<()> {
        let dir = tempfile::tempdir()?;
        let config = |sandbox| Config {
            sandbox,
            ..Config::default()
        };
        let command = ["make".to_owned(), "test".to_owned()];
        let wrapped = plan_command_with(
            &command,
            dir.path(),
            &config(Sandbox::Auto),
            Phase::Check,
            None,
        )?;
        assert_eq!(wrapped.get_program(), "bwrap");
        let args: Vec<_> = wrapped
            .get_args()
            .map(|a| a.to_string_lossy().into_owned())
            .collect();
        assert!(
            args.contains(&"--unshare-net".to_owned()),
            "checks have no network"
        );
        assert_eq!(&args[args.len() - 3..], ["--", "make", "test"]);
        let setup = plan_command_with(
            &command,
            dir.path(),
            &config(Sandbox::Auto),
            Phase::Setup,
            None,
        )?;
        assert!(
            !setup.get_args().any(|a| a == "--unshare-net"),
            "setup keeps the network"
        );
        // Off leaves the command alone; strict refuses what it cannot confine.
        let plain = plan_command_with(
            &command,
            dir.path(),
            &config(Sandbox::Off),
            Phase::Check,
            None,
        )?;
        assert_eq!(plain.get_program(), "make");
        let error = plan_command_with(
            &command,
            dir.path(),
            &config(Sandbox::Strict),
            Phase::Check,
            Some("no bwrap".into()),
        )
        .unwrap_err()
        .to_string();
        assert!(error.contains("no bwrap"), "{error}");
        assert!(plan_sandbox_unavailable_for("linux", true).is_none());
        assert!(plan_sandbox_unavailable_for("linux", false)
            .unwrap()
            .contains("bubblewrap"));
        assert!(plan_sandbox_unavailable_for("windows", true)
            .unwrap()
            .contains("windows"));
        Ok(())
    }

    /// Runs real commands through bubblewrap, so it needs `bwrap` and is run
    /// by hand: `cargo test real_bwrap -- --ignored`.
    #[cfg(target_os = "linux")]
    #[test]
    #[ignore = "needs bubblewrap"]
    fn real_bwrap_confines_a_plan_command() -> Result<()> {
        let git = |dir: &Path, args: &[&str]| -> Result<()> {
            let status = Command::new("git")
                .current_dir(dir)
                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
                .args(args)
                .status()?;
            anyhow::ensure!(status.success(), "git {args:?} failed");
            Ok(())
        };
        let dir = tempfile::tempdir()?;
        let repo = dir.path().join("repo");
        let worktree = dir.path().join("wt");
        std::fs::create_dir(&repo)?;
        git(&repo, &["init", "-q"])?;
        git(&repo, &["commit", "-q", "--allow-empty", "-m", "first"])?;
        git(
            &repo,
            &[
                "worktree",
                "add",
                "-q",
                worktree.to_str().unwrap(),
                "-b",
                "t1",
            ],
        )?;
        let outside =
            std::path::PathBuf::from(std::env::var("HOME")?).join("agengo-bwrap-outside.txt");
        let script = format!(
            "echo in > inside.txt; echo inside=$?; \
             echo out > '{outside}' 2>/dev/null; echo outside=$?; \
             curl -s -m 3 -o /dev/null https://example.com; echo net=$?; \
             git status --short >/dev/null; echo gitstatus=$?",
            outside = outside.display()
        );
        let command = ["sh".to_owned(), "-c".to_owned(), script];
        let run = |phase| -> Result<String> {
            let config = Config {
                sandbox: Sandbox::Auto,
                ..Config::default()
            };
            let mut wrapped = plan_command(&command, &worktree, &config, phase)?;
            Ok(String::from_utf8(wrapped.output()?.stdout)?)
        };
        let check = run(Phase::Check)?;
        assert!(check.contains("inside=0"), "{check}");
        assert!(
            !check.contains("outside=0"),
            "wrote outside the worktree: {check}"
        );
        assert!(!check.contains("net=0"), "reached the network: {check}");
        assert!(check.contains("gitstatus=0"), "{check}");
        assert!(worktree.join("inside.txt").exists());
        assert!(!outside.exists());
        Ok(())
    }
}