Skip to main content

orch/engine/runner/
sandbox.rs

1//! The OS sandbox around a task or review agent, on unless `workflow.sandbox` is `false`. The policy and
2//! why it is shaped this way are in docs/plans/2026-10-28-agent-sandboxes.md
3
4use crate::config;
5use crate::sys::home;
6use sandbox_jail::{Access, Backend, Policy, Sandbox, known};
7use std::env;
8use std::error;
9use std::ffi::OsString;
10use std::fmt;
11use std::fmt::Display;
12use std::fmt::Formatter;
13use std::fs;
14use std::path::{Component, Path, PathBuf};
15use std::sync::{Mutex, PoisonError};
16use std::time::{Duration, Instant};
17use tokio::fs as async_fs;
18use tokio::process::Command;
19use tokio::task;
20
21/// Top-level dirs of the home that stay read-only: what loads or runs later as the operator, the
22/// agents' own settings and keys. Everything at the top of the home that is not a dir is read-only too
23const HOME_READ_ONLY: &[&str] = &[
24    ".config", ".claude", ".ssh", ".gnupg", "bin", "Library", ".local", ".passbox",
25];
26
27/// Writable parts of the read-only dirs above, for caches and agent state
28const HOME_WRITABLE: &[&str] = &[
29    "Library/Caches",
30    "Library/Logs",
31    ".local/share",
32    ".local/state",
33];
34
35/// Codex's settings and instructions, which sit beside the state it rewrites
36const AGENT_CONFIG: &[&str] = &[".codex/config.toml", ".codex/AGENTS.md", ".codex/rules"];
37
38/// Config inside writable home dirs that runs code on the operator's next build or shell, read-only
39/// even when missing. Cargo's `rustc-wrapper` and `runner`, gradle's init scripts, shell frameworks
40const HOME_EXEC_CONFIG: &[&str] = &[
41    ".cargo/config",
42    ".cargo/config.toml",
43    ".gradle/init.d",
44    ".gradle/init.gradle",
45    ".gradle/gradle.properties",
46    ".m2/settings.xml",
47    ".oh-my-zsh",
48    ".zprezto",
49];
50
51/// The one socket in the home an agent may connect to: passbox's broker, which asks the operator
52/// before it hands out a secret. Its ssh-agent socket beside it stays out of reach
53const HOME_SOCKETS: &[&str] = &[".passbox/broker.sock"];
54
55/// State other tools trust, inside the writable `.local/state`, read-only even when missing:
56/// shipcheck posts a PR's required checks from its cache and runs what its `trusted` file names
57const HOME_TRUSTED_STATE: &[&str] = &[".local/state/shipcheck"];
58
59/// The address and password of opencode's background service, which runs tools outside the sandbox
60const OPENCODE_SERVICE: &[&str] = &[
61    ".local/state/opencode/service.json",
62    ".config/opencode/service.json",
63];
64
65/// The tmux, ssh-agent and Docker sockets that would let an agent start a process outside
66const SCRATCH: &[&str] = &["/tmp", "/run", "/var/tmp"];
67
68/// macOS services an agent may look up: the basics, and securityd for its keychain login. Not
69/// LaunchServices, which `open` uses to start an app outside the sandbox
70const KEYCHAIN: &str = "com.apple.SecurityServer";
71
72/// More services a task agent may look up: certificate trust, which `curl` needs for chains the
73/// system file lacks, and the read-only LaunchServices database, which `xcodebuild` needs to tell
74/// a project from a folder. Neither starts a process
75const TASK_MACH_SERVICES: &[&str] = &["com.apple.TrustEvaluationAgent", "com.apple.lsd.mapdb"];
76
77const CLANG_MODULE_CACHE: &str = "Library/Caches/orch/clang-module-cache";
78
79/// The calendar, which scheduled jobs read. A GitHub-issue task has no use for it
80const JOB_MACH_SERVICES: &[&str] = &["com.apple.CalendarAgent"];
81
82/// The run's own temp dir, so no socket of the operator's apps in the shared one is in reach
83pub fn run_temp_dir(attempt_dir: &Path) -> PathBuf {
84    attempt_dir.join("tmp")
85}
86
87/// The empty config dir `gh` gets in the sandbox, inside the run's temp dir
88pub fn gh_config_dir(temp: &Path) -> PathBuf {
89    temp.join("gh")
90}
91
92/// Whether the project runs its agents in the sandbox. It is on unless `workflow.sandbox` is
93/// `false` in the project's `.orch.yml` or the global config
94pub fn enabled(project_dir: &Path) -> bool {
95    is_on(config::get_for_project(project_dir, "workflow.sandbox").ok())
96}
97
98/// Like [`enabled`] from the global config alone, for a run whose project is unknown
99pub fn enabled_globally() -> bool {
100    is_on(config::get_global("workflow.sandbox").ok())
101}
102
103// Only an explicit `false` turns it off, so a typo in the value cannot run an agent unsandboxed
104fn is_on(setting: Option<String>) -> bool {
105    setting.is_none_or(|v| v.trim() != "false")
106}
107
108/**
109 * The program and arguments that go before the agent command, or why the sandbox cannot start.
110 * The worktree's `.git` file is the agent's to write, so the common dir comes from the main
111 * checkout and the branch from orch's records, and a git dir outside them refuses the run
112 **/
113pub async fn argv(inv: &Scope<'_>, temp: &Path) -> anyhow::Result<Vec<OsString>> {
114    build(inv, temp)
115        .await
116        .map_err(|e| anyhow::Error::new(SandboxFailed(format!("{e:#}"))))
117}
118
119/// The parts of an agent run the sandbox policy depends on
120#[derive(Debug)]
121pub struct Scope<'a> {
122    pub work_dir: &'a Path,
123    pub main_project_dir: &'a Path,
124    pub branch: &'a str,
125    pub task_id: &'a str,
126}
127
128/// The sandbox cannot start. It is the operator's setup, so it blocks the task and counts against no agent
129#[derive(Debug)]
130pub struct SandboxFailed(pub String);
131
132impl Display for SandboxFailed {
133    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
134        write!(f, "the OS sandbox cannot start: {}", self.0)
135    }
136}
137
138impl error::Error for SandboxFailed {}
139
140async fn build(inv: &Scope<'_>, temp: &Path) -> anyhow::Result<Vec<OsString>> {
141    let backend = Backend::detect()?;
142    let common_dir = resolve_git_dir_arg(inv.main_project_dir, "--git-common-dir").await?;
143    let git_dir = resolve_git_dir_arg(inv.work_dir, "--git-dir").await?;
144
145    check_git_dirs(
146        inv.work_dir,
147        inv.main_project_dir,
148        git_dir.as_deref(),
149        common_dir.as_deref(),
150    )?;
151
152    let home = env::var_os("HOME")
153        .map(PathBuf::from)
154        .ok_or_else(|| anyhow::anyhow!("HOME is not set, so the sandbox cannot hide its keys"))?;
155    let mut projects: Vec<PathBuf> = config::get_projects_with_paths()
156        .unwrap_or_default()
157        .into_iter()
158        .map(|(_, dir)| dir)
159        // A config with `gh.repo` and no `projects:` names the project `.`, a path no policy holds
160        .filter(|dir| dir.is_absolute())
161        .collect();
162    projects.push(inv.main_project_dir.to_path_buf());
163    let path_dirs = env::var_os("PATH")
164        .map(|p| env::split_paths(&p).collect())
165        .unwrap_or_default();
166
167    let extra = Extra::from_config(inv.main_project_dir, &home);
168    let run = Run {
169        work_dir: inv.work_dir.to_path_buf(),
170        git_dir,
171        common_dir,
172        own_ref: (!inv.branch.is_empty()).then(|| format!("refs/heads/{}", inv.branch)),
173        home,
174        orch_home: home::orch_home()?,
175        projects,
176        path_dirs,
177        temp: temp.to_path_buf(),
178        extra,
179        internal: inv.task_id.starts_with("internal:"),
180        seatbelt: backend == Backend::Seatbelt,
181    };
182    // The policy reads many dirs, so it stays off the async workers
183    task::spawn_blocking(move || {
184        // bwrap binds only a path that exists, and the preflight's temp dir is new
185        fs::create_dir_all(&run.temp)?;
186        let sandbox = Sandbox::new(backend, policy(&run))?;
187        Ok(sandbox.argv().to_vec())
188    })
189    .await?
190}
191
192/**
193 * Refuses a worktree whose git dir the agent could have pointed elsewhere. Only the main checkout
194 * has the common dir as its git dir. A linked worktree's git dir is in `<common>/worktrees`, and
195 * its `gitdir` file, which the agent cannot write, points back at this worktree
196 **/
197fn check_git_dirs(
198    work_dir: &Path,
199    main_project_dir: &Path,
200    git_dir: Option<&Path>,
201    common_dir: Option<&Path>,
202) -> anyhow::Result<()> {
203    let real = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());
204
205    match (git_dir, common_dir) {
206        (Some(git), Some(common)) if git == common => anyhow::ensure!(
207            real(work_dir) == real(main_project_dir),
208            "the worktree {} uses the repository's own git dir {}",
209            work_dir.display(),
210            common.display()
211        ),
212        (Some(git), Some(common)) => {
213            anyhow::ensure!(
214                git.starts_with(common.join("worktrees")),
215                "the worktree's git dir {} is outside its repository {}",
216                git.display(),
217                common.display()
218            );
219            let back = fs::read_to_string(git.join("gitdir")).unwrap_or_default();
220            anyhow::ensure!(
221                real(Path::new(back.trim())) == real(&work_dir.join(".git")),
222                "the git dir {} belongs to another worktree",
223                git.display()
224            );
225        }
226        (None, Some(common)) => anyhow::bail!(
227            "the worktree {} has no git dir in {}",
228            work_dir.display(),
229            common.display()
230        ),
231        _ => {}
232    }
233
234    Ok(())
235}
236
237/**
238 * Paths added to the policy. `sandbox.write` adds a writable path, from the main checkout's
239 * `.orch.yml` and the global config. `sandbox.read`, which shows a hidden credential path, and
240 * `sandbox.sockets`, a unix socket or a dir of them, come from the global config alone: a merged
241 * change to `.orch.yml` must not hand later tasks a credential or Docker's socket. No entry lifts
242 * a read-only rule, which wins over a writable one
243 **/
244#[derive(Default)]
245struct Extra {
246    write: Vec<PathBuf>,
247    read: Vec<PathBuf>,
248    sockets: Vec<PathBuf>,
249}
250
251impl Extra {
252    fn from_config(project_dir: &Path, home: &Path) -> Self {
253        let paths = |list: Vec<String>| -> Vec<PathBuf> {
254            list.iter().filter_map(|text| expand(text, home)).collect()
255        };
256        let mut write = paths(config::get_list_for_project(project_dir, "sandbox.write"));
257        write.retain(|path| {
258            let allowed = may_write(path, home);
259
260            if !allowed {
261                tracing::warn!(path = %path.display(), "sandbox.write entry refused, it is too wide or holds keys or startup files");
262            }
263
264            allowed
265        });
266        Self {
267            write,
268            read: paths(config::get_global_list("sandbox.read")),
269            sockets: paths(config::get_global_list("sandbox.sockets")),
270        }
271    }
272}
273
274/// Parts of the home no config entry makes writable: keys, the agents' and orch's own files, and
275/// what runs at login or from `PATH`
276const NEVER_WRITABLE: &[&str] = &[
277    ".ssh",
278    ".gnupg",
279    ".passbox",
280    ".claude",
281    ".orch",
282    ".config/git",
283    "bin",
284    ".local/bin",
285    "library/launchagents",
286    "library/keychains",
287];
288
289/**
290 * Whether a `sandbox.write` entry is narrow enough: not the home, a parent of it or an entry at
291 * its top, where the shell's startup files are, and not inside [`NEVER_WRITABLE`], whatever its
292 * case, since macOS file systems ignore it. A guard against a mistake: `.orch.yml` is trusted as
293 * a whole, its `bash` jobs already run as the operator
294 **/
295fn may_write(path: &Path, home: &Path) -> bool {
296    if home.starts_with(path) || path.components().any(|c| c == Component::ParentDir) {
297        return false;
298    }
299
300    let Ok(inside) = path.strip_prefix(home) else {
301        return true;
302    };
303    let lower = PathBuf::from(inside.to_string_lossy().to_lowercase());
304    inside.components().count() > 1 && !NEVER_WRITABLE.iter().any(|dir| lower.starts_with(dir))
305}
306
307/// An absolute path, with `~/` as the home. A relative one names nothing a policy can hold
308fn expand(text: &str, home: &Path) -> Option<PathBuf> {
309    let path = match text.strip_prefix("~/") {
310        Some(rest) => home.join(rest),
311        None => PathBuf::from(text),
312    };
313    path.is_absolute().then_some(path)
314}
315
316/// Package manager settings in the home, hidden since they can hold a registry token: the file,
317/// the variable that points its tool at another one, and whether it holds one setting a line
318const PACKAGE_CONFIG: &[(&str, &str, bool)] = &[
319    (".npmrc", "NPM_CONFIG_USERCONFIG", true),
320    (".config/uv/uv.toml", "UV_CONFIG_FILE", false),
321    (".config/pip/pip.conf", "PIP_CONFIG_FILE", false),
322];
323
324/// What marks a line of package manager config as a credential
325const SECRET_WORDS: &[&str] = &["_auth", "password", "token", "secret", "key", "cert"];
326
327fn holds_secret(line: &str) -> bool {
328    let lower = line.to_lowercase();
329    // A URL with a user in it, as in https://user:pass@host
330    let user_in_url = lower.split("://").skip(1).any(|rest| {
331        rest.split(['/', ' ', '"', '\''])
332            .next()
333            .is_some_and(|host| host.contains('@'))
334    });
335    user_in_url || SECRET_WORDS.iter().any(|word| lower.contains(word))
336}
337
338/**
339 * Copies of the operator's package manager settings without their credentials, written under
340 * `temp`, as `(variable, file)` for the agent's environment, so an install inside the sandbox
341 * follows the operator's rules, such as a minimum package age. `.npmrc` holds one setting a line
342 * and loses its credential lines. A TOML or INI file that holds a credential is not copied at
343 * all, since a dropped line can break it
344 **/
345pub fn package_config(home: &Path, temp: &Path) -> Vec<(&'static str, PathBuf)> {
346    let dir = temp.join("config");
347    let mut found = Vec::new();
348
349    for (file, variable, by_line) in PACKAGE_CONFIG {
350        let Ok(text) = fs::read_to_string(home.join(file)) else {
351            continue;
352        };
353        if !by_line && text.lines().any(holds_secret) {
354            continue;
355        }
356
357        let kept: String = text
358            .lines()
359            .filter(|line| !holds_secret(line))
360            .flat_map(|line| [line, "\n"])
361            .collect();
362        let copy = dir.join(file.rsplit('/').next().unwrap_or(file));
363
364        if fs::create_dir_all(&dir).is_ok() && fs::write(&copy, kept).is_ok() {
365            found.push((*variable, copy));
366        }
367    }
368
369    found
370}
371
372/**
373 * Compiler caches moved out of the per-user cache dir under `/var/folders`, which the sandbox does
374 * not let an agent write. clang and swiftc put their module cache there on macOS, so a Swift build
375 * fails. The new one sits under `~/Library/Caches`, kept between runs and apart from the operator's
376 * own builds, which never load a module an agent compiled
377 **/
378pub fn cache_env(home: &Path) -> Vec<(&'static str, PathBuf)> {
379    if cfg!(target_os = "macos") {
380        vec![("CLANG_MODULE_CACHE_PATH", home.join(CLANG_MODULE_CACHE))]
381    } else {
382        Vec::new()
383    }
384}
385
386/// What the policy of one run depends on
387struct Run {
388    work_dir: PathBuf,
389    git_dir: Option<PathBuf>,
390    common_dir: Option<PathBuf>,
391    /// The task's branch, `refs/heads/<branch>`, from orch's records
392    own_ref: Option<String>,
393    home: PathBuf,
394    orch_home: PathBuf,
395    projects: Vec<PathBuf>,
396    path_dirs: Vec<PathBuf>,
397    /// The run's own temp dir, where the agent may also connect to a socket
398    temp: PathBuf,
399    /// Paths the operator's config adds to the policy
400    extra: Extra,
401    internal: bool,
402    seatbelt: bool,
403}
404
405impl Run {
406    fn git_dirs(&self) -> impl Iterator<Item = &PathBuf> {
407        self.git_dir.iter().chain(&self.common_dir)
408    }
409}
410
411fn policy(run: &Run) -> Policy {
412    let mut p = Policy::default();
413    p.writable.push(run.work_dir.clone());
414    p.writable.extend(run.git_dirs().cloned());
415    p.writable.extend(home_writable(&run.home));
416    p.writable.push(run.temp.clone());
417    p.writable
418        .extend(claude_project_dir(&run.home, &run.work_dir));
419
420    // bwrap binds only a path that exists, Seatbelt lets the agent create a missing one
421    p.writable.extend(
422        run.extra
423            .write
424            .iter()
425            .filter(|path| run.seatbelt || path.exists())
426            .cloned(),
427    );
428
429    if run.seatbelt {
430        p.writable.push("/private/tmp".into());
431        let jobs: &[&str] = if run.internal { JOB_MACH_SERVICES } else { &[] };
432        p.mach_services = Access::Only(
433            known::BASIC_MACH_SERVICES
434                .iter()
435                .chain(&[KEYCHAIN])
436                .chain(TASK_MACH_SERVICES)
437                .chain(jobs)
438                .map(ToString::to_string)
439                .collect(),
440        );
441    } else {
442        // bwrap has no socket filter, so the dirs that hold sockets start empty instead
443        p.scratch = SCRATCH
444            .iter()
445            .map(PathBuf::from)
446            .filter(|d| d.is_dir())
447            .collect();
448    }
449
450    // The tmux server runs outside the sandbox, so its socket in /tmp must stay out of reach
451    let mut sockets = vec![run.work_dir.clone(), run.temp.clone()];
452    sockets.extend(
453        HOME_SOCKETS
454            .iter()
455            .map(|s| run.home.join(s))
456            .filter(|s| s.exists()),
457    );
458    sockets.extend(run.extra.sockets.iter().cloned());
459    p.unix_sockets = Access::Only(sockets);
460
461    if let Some(common) = &run.common_dir {
462        git_rules(
463            common,
464            run.git_dir.as_ref(),
465            run.own_ref.as_deref(),
466            &mut p.read_only,
467        );
468
469        if run.git_dir.as_ref().is_some_and(|g| g != common) {
470            p.read_only.push(run.work_dir.join(".git"));
471        }
472    }
473
474    p.read_only.extend(home_git_dirs(&run.home));
475
476    // /private/tmp stays writable, but the agent must not delete or replace these sockets.
477    // bwrap hides those in a scratch dir, and binding one back would expose it
478    let hidden = p.scratch.clone();
479    p.read_only.extend(
480        socket_dirs(&run.temp)
481            .into_iter()
482            .filter(|d| !hidden.iter().any(|s| d.starts_with(s))),
483    );
484
485    p.read_only.push(run.work_dir.join(".orch.yml"));
486    p.read_only.extend(
487        AGENT_CONFIG
488            .iter()
489            .chain(HOME_EXEC_CONFIG)
490            .chain(HOME_TRUSTED_STATE)
491            .map(|path| run.home.join(path)),
492    );
493    // A tool on PATH inside the home, such as ~/.cargo/bin, runs later as the operator
494    p.read_only.extend(
495        run.path_dirs
496            .iter()
497            .filter(|d| d.starts_with(&run.home))
498            .cloned(),
499    );
500
501    let mut keep: Vec<PathBuf> = vec![run.work_dir.clone(), run.temp.clone()];
502    keep.extend(run.git_dirs().cloned());
503
504    guard_orch_home(run, &keep, &mut p);
505
506    if run.internal {
507        p.writable
508            .extend(["orch.db", "orch.db-wal", "orch.db-shm"].map(|f| run.orch_home.join(f)));
509    }
510    // The daemon's loopback write endpoint takes this token, so reading it is a write to the store
511    let write_token = run.orch_home.join("state/cluster.port");
512
513    for project in &run.projects {
514        read_only_around(project, &keep, &mut p.read_only);
515    }
516
517    // The crate's list hides cargo's config too, which holds build settings agents need
518    p.hidden = known::credentials(&run.home)
519        .into_iter()
520        .filter(|path| {
521            ![".cargo/config", ".cargo/config.toml"]
522                .map(|c| run.home.join(c))
523                .contains(path)
524        })
525        .filter(|path| !run.extra.read.iter().any(|open| path.starts_with(open)))
526        .collect();
527    p.hidden.push(run.home.join(".gnupg"));
528    p.hidden
529        .extend(OPENCODE_SERVICE.iter().map(|f| run.home.join(f)));
530
531    // The web UI's token drives the daemon's API, config edits and plan imports among it
532    p.hidden.push(run.orch_home.join(UI_TOKEN));
533
534    if !run.internal {
535        p.hidden.push(write_token);
536    }
537
538    p.own_signals = true;
539
540    // launchctl and setuid binaries start processes outside the sandbox
541    if run.seatbelt {
542        p.apple_events = false;
543        p.no_exec.push(known::LAUNCHCTL.into());
544        p.no_exec.extend(known::setuid_binaries().iter().cloned());
545    }
546
547    p
548}
549
550/// The web UI's port and token. No agent may read it, it would drive the daemon through the UI's API
551const UI_TOKEN: &str = "state/ui.port";
552
553/// The agent's own login and settings, which it reads to start. The Security framework reads the
554/// login keychain in the calling process, and its access rules still give the agent only its own item
555const CHAT_AGENT_HOME: &[&str] = &[".claude", ".claude.json", "Library/Keychains"];
556
557/// Where agents keep sessions and caches, which the control chat writes to resume a conversation
558const AGENT_STATE: &[&str] = &[
559    ".claude/projects",
560    ".claude/todos",
561    ".claude/shell-snapshots",
562    ".claude/statsig",
563    ".codex",
564    ".local/share/opencode",
565    ".local/state/opencode",
566];
567
568/// Other agents' settings, read at start
569const AGENT_CONFIG_READ: &[&str] = &[".codex", ".config/opencode", ".grok"];
570
571/// What a chat agent may touch, as opposed to a task agent's [`policy`]
572struct ChatRun {
573    home: PathBuf,
574    orch_home: PathBuf,
575    /// The project a project chat reads, none for the control chat
576    project: Option<PathBuf>,
577    temp: PathBuf,
578    path_dirs: Vec<PathBuf>,
579    seatbelt: bool,
580    /// The control chat keeps agent sessions and acts through orch, so it writes session dirs and
581    /// reads the daemon's write token. A project chat does neither
582    control: bool,
583}
584
585/// The sandbox prefix for a project chat agent. It reads the project and orch's store and config,
586/// writes only its temp dir, and cannot read the rest of the home or any credential
587pub fn chat_argv(project: &Path, temp: &Path) -> anyhow::Result<Vec<OsString>> {
588    chat_sandbox(Some(project), temp, false)
589}
590
591/**
592 * The sandbox prefix for the control chat, which Telegram and the other channels reach. It reads
593 * orch's home and acts through orch, and cannot read the rest of the home or any credential.
594 * Inside another Seatbelt sandbox, which cannot nest, it runs in that one
595 **/
596pub fn control_argv(temp: &Path) -> anyhow::Result<Vec<OsString>> {
597    match chat_sandbox(None, temp, true) {
598        Err(e)
599            if e.downcast_ref::<sandbox_jail::Error>()
600                .is_some_and(|e| matches!(e, sandbox_jail::Error::Nested)) =>
601        {
602            tracing::info!("already inside a sandbox, the control chat runs in it");
603            Ok(Vec::new())
604        }
605        other => other,
606    }
607}
608
609fn chat_sandbox(
610    project: Option<&Path>,
611    temp: &Path,
612    control: bool,
613) -> anyhow::Result<Vec<OsString>> {
614    let backend = Backend::detect()?;
615    let home = env::var_os("HOME")
616        .map(PathBuf::from)
617        .ok_or_else(|| anyhow::anyhow!("HOME is not set"))?;
618    let run = ChatRun {
619        home,
620        orch_home: home::orch_home()?,
621        project: project.map(Path::to_path_buf),
622        temp: temp.to_path_buf(),
623        path_dirs: env::var_os("PATH")
624            .map(|p| env::split_paths(&p).collect())
625            .unwrap_or_default(),
626        seatbelt: matches!(backend, Backend::Seatbelt),
627        control,
628    };
629    Ok(Sandbox::new(backend, chat_policy(&run))?.argv().to_vec())
630}
631
632fn chat_policy(run: &ChatRun) -> Policy {
633    let mut p = Policy::default();
634    p.writable.push(run.temp.clone());
635    // `orch task list` opens the store, and SQLite writes its -wal and -shm files even to read
636    p.writable.extend(
637        ["orch.db", "orch.db-wal", "orch.db-shm"]
638            .map(|f| run.orch_home.join(f))
639            .into_iter()
640            .filter(|f| f.exists()),
641    );
642
643    if run.seatbelt {
644        p.writable.push("/private/tmp".into());
645        p.mach_services = Access::Only(
646            known::BASIC_MACH_SERVICES
647                .iter()
648                .chain(&[KEYCHAIN])
649                .map(ToString::to_string)
650                .collect(),
651        );
652    } else {
653        p.scratch = SCRATCH
654            .iter()
655            .map(PathBuf::from)
656            .filter(|d| d.is_dir())
657            .collect();
658    }
659
660    p.unix_sockets = Access::Only(vec![run.temp.clone()]);
661
662    if run.control {
663        p.writable.extend(
664            AGENT_STATE
665                .iter()
666                .map(|d| run.home.join(d))
667                .filter(|d| d.is_dir()),
668        );
669        // Codex writes its state beside its settings, which stay as the owner wrote them
670        p.read_only
671            .extend(AGENT_CONFIG.iter().map(|path| run.home.join(path)));
672    }
673
674    // The tmux server and launchd's sockets sit in the writable /private/tmp, and an agent that
675    // deleted or replaced one would end every session or stand in for the ssh agent
676    p.read_only.extend(socket_dirs(&run.temp));
677
678    p.unreadable.push(run.home.clone());
679    p.readable.extend(run.project.iter().cloned());
680    p.readable.push(run.orch_home.clone());
681    p.readable
682        .extend(AGENT_CONFIG_READ.iter().map(|f| run.home.join(f)));
683    p.readable
684        .extend(CHAT_AGENT_HOME.iter().map(|f| run.home.join(f)));
685    p.readable.extend(
686        run.path_dirs
687            .iter()
688            .filter(|d| d.starts_with(&run.home))
689            .cloned(),
690    );
691
692    p.hidden = known::credentials(&run.home);
693    p.hidden.push(run.home.join(".gnupg"));
694    p.hidden.push(run.orch_home.join(UI_TOKEN));
695    // The daemon's loopback write endpoint takes this token, and a project chat only reads
696    if !run.control {
697        p.hidden.push(run.orch_home.join("state/cluster.port"));
698    }
699
700    p.own_signals = true;
701    if run.seatbelt {
702        p.apple_events = false;
703        p.no_exec.push(known::LAUNCHCTL.into());
704        p.no_exec.extend(known::setuid_binaries().iter().cloned());
705    }
706
707    p
708}
709
710/// How many levels below a writable home dir are searched for repositories
711const GIT_SCAN_DEPTH: usize = 4;
712
713/// How long a scan of the home for repositories is reused. It takes seconds and every run needs it
714/// twice in a row. Kept short, since a repository cloned after the scan is not in it
715const GIT_SCAN_TTL: Duration = Duration::from_secs(60);
716
717static GIT_SCAN: Mutex<Option<(Instant, PathBuf, Vec<PathBuf>)>> = Mutex::new(None);
718
719/// The hooks and config of every repository under the home's writable dirs, from a recent scan
720fn home_git_dirs(home: &Path) -> Vec<PathBuf> {
721    let mut last = GIT_SCAN.lock().unwrap_or_else(PoisonError::into_inner);
722
723    if let Some((at, of, found)) = last.as_ref()
724        && of == home
725        && at.elapsed() < GIT_SCAN_TTL
726    {
727        return found.clone();
728    }
729
730    let mut found = Vec::new();
731
732    for dir in home_writable(home) {
733        find_git_dirs(&dir, GIT_SCAN_DEPTH, &mut found);
734    }
735
736    *last = Some((Instant::now(), home.to_path_buf(), found.clone()));
737    found
738}
739
740// Hooks and config of a repository orch does not know run as the operator on its next git command
741fn find_git_dirs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
742    let git = dir.join(".git");
743
744    if git.is_dir() {
745        out.extend(["hooks", "config", "info", "modules"].map(|f| git.join(f)));
746    }
747
748    if depth == 0 {
749        return;
750    }
751
752    for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
753        let name = entry.file_name();
754
755        if entry.file_type().is_ok_and(|t| t.is_dir()) && name != ".git" && name != "node_modules" {
756            find_git_dirs(&entry.path(), depth - 1, out);
757        }
758    }
759}
760
761/// The tmux and launchd socket dirs in the shared temp dirs, which the tmux server and the
762/// ssh-agent keep running outside the sandbox
763fn socket_dirs(temp: &Path) -> Vec<PathBuf> {
764    let mut roots = vec![PathBuf::from("/private/tmp"), PathBuf::from("/tmp")];
765    roots.extend(env::var_os("TMUX_TMPDIR").map(PathBuf::from));
766    roots.push(temp.to_path_buf());
767
768    roots
769        .iter()
770        .filter_map(|r| fs::read_dir(r).ok())
771        .flatten()
772        .flatten()
773        .filter(|e| {
774            let name = e.file_name();
775            let name = name.to_string_lossy();
776            name.starts_with("tmux-") || name.starts_with("com.apple.launchd.")
777        })
778        .map(|e| e.path())
779        .collect()
780}
781
782/**
783 * Where Claude Code keeps the session of a run in this worktree: its transcript, and the tool
784 * output too long for the context. Without it a long command output is cut off with no notice.
785 * The dir is named after the cwd with every character but letters and digits as `-`
786 **/
787fn claude_project_dir(home: &Path, work_dir: &Path) -> Option<PathBuf> {
788    let projects = home.join(".claude/projects");
789    let name: String = work_dir
790        .to_string_lossy()
791        .chars()
792        .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
793        .collect();
794    let dir = projects.join(name);
795
796    // bwrap binds only a path that exists
797    (projects.is_dir() && fs::create_dir_all(&dir).is_ok()).then_some(dir)
798}
799
800/// The home's writable parts: its top-level dirs but [`HOME_READ_ONLY`], and [`HOME_WRITABLE`]
801/// inside those. The home itself stays read-only, so no new dotfile appears at its top
802fn home_writable(home: &Path) -> Vec<PathBuf> {
803    let mut dirs: Vec<PathBuf> = fs::read_dir(home)
804        .into_iter()
805        .flatten()
806        .flatten()
807        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
808        .filter(|e| !HOME_READ_ONLY.contains(&e.file_name().to_string_lossy().as_ref()))
809        .map(|e| e.path())
810        .collect();
811    dirs.extend(
812        HOME_WRITABLE
813            .iter()
814            .map(|d| home.join(d))
815            .filter(|d| d.is_dir()),
816    );
817    dirs
818}
819
820/**
821 * The git common dir is writable for objects, the task's branch, remote refs and the task's own
822 * worktree dir, and read-only around those: hooks and config run the next time the operator runs
823 * git, and another branch is the operator's work. Paths git would pick up when they appear are
824 * read-only even when missing, and so is a loose ref for a branch only `packed-refs` holds, since
825 * it would win over the packed one
826 **/
827fn git_rules(
828    common: &Path,
829    git_dir: Option<&PathBuf>,
830    own_ref: Option<&str>,
831    out: &mut Vec<PathBuf>,
832) {
833    out.extend(
834        [
835            "hooks",
836            "config",
837            "info",
838            "modules",
839            "packed-refs",
840            "refs/tags",
841            "commondir",
842            "gitdir",
843            "config.worktree",
844        ]
845        .map(|d| common.join(d)),
846    );
847    let own: Vec<PathBuf> = own_ref
848        .map(|r| vec![common.join(r), common.join("logs").join(r)])
849        .unwrap_or_default();
850
851    match git_dir {
852        Some(dir) if dir != common => {
853            let mut keep = vec![
854                common.join("objects"),
855                common.join("refs/remotes"),
856                common.join("logs/refs/remotes"),
857                dir.clone(),
858            ];
859            keep.extend(own.iter().cloned());
860            read_only_around(common, &keep, out);
861            // HEAD stays writable, a rebase detaches it. Other branches stay read-only whatever it
862            // names, and orch pushes the task's branch by name
863            out.extend(["commondir", "gitdir", "config.worktree"].map(|f| dir.join(f)));
864        }
865        // The worktree is the main checkout, so its index and HEAD live in the common dir
866        _ => read_only_around(&common.join("refs/heads"), &own, out),
867    }
868
869    let packed = fs::read_to_string(common.join("packed-refs")).unwrap_or_default();
870    for name in packed
871        .lines()
872        .filter_map(|l| l.split_once(' ').map(|(_, r)| r))
873    {
874        let path = common.join(name);
875
876        if name.starts_with("refs/heads/") && !own.contains(&path) && !path.exists() {
877            out.push(path);
878        }
879    }
880}
881
882/**
883 * Every entry of `dir` read-only but the paths in `keep`. An entry that holds a kept path is
884 * walked instead, so `~/.orch` stays read-only around the task's own worktree, and a main checkout
885 * around its `.git`. A missing `dir` adds nothing
886 **/
887/**
888 * orch's home is never writable but for its task worktree and temp dir, which are writable on their
889 * own. A writable dir in the home that holds it gives way to its other entries, so the rules do not
890 * grow with the tasks orch holds: a rule per task overflowed Seatbelt's compiler at a few thousand.
891 * A writable dir outside the home, such as /private/tmp, keeps its new entries writable, so there
892 * orch's home gets read-only rules around the paths the run keeps
893 **/
894fn guard_orch_home(run: &Run, keep: &[PathBuf], p: &mut Policy) {
895    let home = &run.orch_home;
896    let holders: Vec<PathBuf> = p
897        .writable
898        .iter()
899        .filter(|w| home.starts_with(w))
900        .cloned()
901        .collect();
902    let mut walked = false;
903
904    for dir in holders {
905        if dir.starts_with(&run.home) {
906            p.writable.retain(|w| w != &dir);
907
908            if &dir != home {
909                writable_around(&dir, home, &mut p.writable);
910            }
911        } else if !walked {
912            read_only_around(home, keep, &mut p.read_only);
913            walked = true;
914        }
915    }
916}
917
918fn writable_around(dir: &Path, skip: &Path, out: &mut Vec<PathBuf>) {
919    let Ok(entries) = fs::read_dir(dir) else {
920        return;
921    };
922
923    for entry in entries.flatten() {
924        let path = entry.path();
925
926        if path == skip {
927            continue;
928        }
929
930        if skip.starts_with(&path) && entry.file_type().is_ok_and(|t| t.is_dir()) {
931            writable_around(&path, skip, out);
932        } else {
933            out.push(path);
934        }
935    }
936}
937
938fn read_only_around(dir: &Path, keep: &[PathBuf], out: &mut Vec<PathBuf>) {
939    let Ok(entries) = fs::read_dir(dir) else {
940        return;
941    };
942
943    for entry in entries.flatten() {
944        let path = entry.path();
945
946        if keep.iter().any(|k| path.starts_with(k)) {
947            continue;
948        }
949
950        let holds_kept = keep.iter().any(|k| k.starts_with(&path));
951        let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());
952
953        if holds_kept && is_dir {
954            read_only_around(&path, keep, out);
955        } else if !holds_kept {
956            out.push(path);
957        }
958    }
959}
960
961/// Run `git rev-parse <arg>` from `work_dir` and canonicalize the
962/// result. Returns `Ok(None)` when git is not available or the command fails.
963pub(crate) async fn resolve_git_dir_arg(
964    work_dir: &Path,
965    arg: &str,
966) -> anyhow::Result<Option<PathBuf>> {
967    let output = Command::new("git")
968        .args(["rev-parse", arg])
969        .current_dir(work_dir)
970        .output()
971        .await?;
972
973    if !output.status.success() {
974        return Ok(None);
975    }
976
977    let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
978    if raw.is_empty() {
979        return Ok(None);
980    }
981
982    // The path may be relative to work_dir; canonicalize to absolute.
983    let candidate = if Path::new(&raw).is_absolute() {
984        PathBuf::from(&raw)
985    } else {
986        work_dir.join(&raw)
987    };
988
989    let canonical = async_fs::canonicalize(&candidate)
990        .await
991        .unwrap_or(candidate);
992    Ok(Some(canonical))
993}
994
995#[cfg(test)]
996mod tests {
997    use super::*;
998    #[cfg(any(target_os = "macos", target_os = "linux"))]
999    use serial_test::serial;
1000    use std::fs;
1001    #[cfg(target_os = "macos")]
1002    use std::os::unix::net::UnixListener;
1003    #[cfg(any(target_os = "macos", target_os = "linux"))]
1004    use std::process::Command;
1005    #[cfg(target_os = "macos")]
1006    use std::thread;
1007
1008    #[test]
1009    fn only_an_explicit_false_turns_the_sandbox_off() {
1010        assert!(is_on(None));
1011        assert!(is_on(Some("os".into())));
1012        assert!(is_on(Some("flase".into())));
1013        assert!(!is_on(Some("false".into())));
1014        assert!(!is_on(Some(" false\n".into())));
1015    }
1016
1017    #[tokio::test]
1018    async fn argv_error_is_tagged_so_spawn_blocks_the_task() {
1019        let inv = Scope {
1020            work_dir: Path::new("/nonexistent/work"),
1021            main_project_dir: Path::new("/nonexistent/main"),
1022            branch: "",
1023            task_id: "t",
1024        };
1025        let err = argv(&inv, Path::new("/tmp/orch-test-run"))
1026            .await
1027            .expect_err("no checkout, so no sandbox");
1028        assert!(err.downcast_ref::<SandboxFailed>().is_some());
1029        assert!(err.to_string().starts_with("the OS sandbox cannot start: "));
1030    }
1031
1032    // The preflight passes a temp dir no one made yet, which bwrap refuses to bind
1033    #[cfg(any(target_os = "macos", target_os = "linux"))]
1034    #[tokio::test]
1035    #[serial(orch_home)]
1036    async fn argv_makes_the_run_temp_dir_before_the_policy_binds_it() {
1037        if Backend::detect().is_err() {
1038            eprintln!("skipped: no OS sandbox starts here");
1039            return;
1040        }
1041        let root = tempfile::tempdir().unwrap();
1042        let r = root.path().canonicalize().unwrap();
1043        let (home, main) = (r.join("home"), r.join("home/proj"));
1044        let work = home.join(".orch/worktrees/proj/feat");
1045        fs::create_dir_all(&main).unwrap();
1046        let git = |dir: &Path, args: &[&str]| {
1047            let out = Command::new("git")
1048                .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1049                .args(args)
1050                .current_dir(dir)
1051                .output()
1052                .unwrap();
1053            assert!(
1054                out.status.success(),
1055                "{}",
1056                String::from_utf8_lossy(&out.stderr)
1057            );
1058        };
1059        git(&main, &["init", "-q", "-b", "main"]);
1060        git(&main, &["commit", "-q", "--allow-empty", "-m", "init"]);
1061        git(
1062            &main,
1063            &[
1064                "worktree",
1065                "add",
1066                "-q",
1067                "-b",
1068                "feat",
1069                work.to_str().unwrap(),
1070            ],
1071        );
1072        let previous = (env::var_os("HOME"), env::var_os("ORCH_HOME"));
1073        // SAFETY: nextest runs each test in its own process, and serial(orch_home) orders the rest
1074        unsafe { env::set_var("HOME", &home) };
1075        // SAFETY: as above
1076        unsafe { env::set_var("ORCH_HOME", home.join(".orch")) };
1077        config::clear_test_cache();
1078        let inv = Scope {
1079            work_dir: &work,
1080            main_project_dir: &main,
1081            branch: "feat",
1082            task_id: "t",
1083        };
1084        let temp = r.join("preflight");
1085        let built = argv(&inv, &temp).await;
1086        for (key, value) in [("HOME", previous.0), ("ORCH_HOME", previous.1)] {
1087            match value {
1088                // SAFETY: as above
1089                Some(v) => unsafe { env::set_var(key, v) },
1090                // SAFETY: as above
1091                None => unsafe { env::remove_var(key) },
1092            }
1093        }
1094        config::clear_test_cache();
1095        assert!(!built.unwrap().is_empty());
1096        assert!(temp.is_dir());
1097    }
1098
1099    /// A home with an orch home inside, two worktrees and a main checkout, and the run of one task
1100    fn fixture(internal: bool) -> (tempfile::TempDir, Run) {
1101        let root = tempfile::tempdir().unwrap();
1102        let r = root.path().canonicalize().unwrap();
1103        let (home, orch) = (r.join("home"), r.join("home/.orch"));
1104        for dir in [
1105            "home/.orch/worktrees/proj/mine",
1106            "home/.orch/worktrees/proj/other",
1107            "home/.orch/state",
1108            "home/proj/.git/worktrees/mine",
1109            "home/proj/.git/refs/heads/feat",
1110            "home/proj/src",
1111            "home/proj/.git/objects",
1112            "home/proj/.git/worktrees/other",
1113            "home/.config/nvim",
1114            "home/.claude",
1115            "home/.cargo/bin",
1116            "home/Library/Caches",
1117            "home/Library/LaunchAgents",
1118            "tmp",
1119        ] {
1120            fs::create_dir_all(r.join(dir)).unwrap();
1121        }
1122        for file in [
1123            "home/.orch/config.yml",
1124            "home/.orch/orch.db",
1125            "home/proj/README.md",
1126            "home/proj/.git/refs/heads/main",
1127            "home/proj/.git/refs/heads/feat/mine",
1128            "home/proj/.git/worktrees/mine/HEAD",
1129            "home/proj/.git/worktrees/mine/gitdir",
1130            "home/.zshrc",
1131            "home/.claude.json",
1132        ] {
1133            fs::write(r.join(file), "").unwrap();
1134        }
1135        fs::write(
1136            r.join("home/proj/.git/packed-refs"),
1137            "# pack-refs with: peeled\nabc refs/heads/release\n",
1138        )
1139        .unwrap();
1140
1141        let run = Run {
1142            work_dir: orch.join("worktrees/proj/mine"),
1143            git_dir: Some(home.join("proj/.git/worktrees/mine")),
1144            common_dir: Some(home.join("proj/.git")),
1145            own_ref: Some("refs/heads/feat/mine".into()),
1146            home: home.clone(),
1147            orch_home: orch,
1148            projects: vec![home.join("proj")],
1149            path_dirs: vec![home.join(".cargo/bin"), "/usr/bin".into()],
1150            temp: r.join("tmp"),
1151            extra: Extra::default(),
1152            internal,
1153            seatbelt: false,
1154        };
1155        (root, run)
1156    }
1157
1158    fn chat_fixture() -> ChatRun {
1159        ChatRun {
1160            home: PathBuf::from("/home/u"),
1161            orch_home: PathBuf::from("/home/u/.orch"),
1162            project: Some(PathBuf::from("/home/u/code/app")),
1163            temp: PathBuf::from("/tmp/chat"),
1164            path_dirs: vec![
1165                PathBuf::from("/home/u/.cargo/bin"),
1166                PathBuf::from("/usr/bin"),
1167            ],
1168            seatbelt: true,
1169            control: false,
1170        }
1171    }
1172
1173    #[test]
1174    fn no_task_can_read_the_web_ui_token() {
1175        for internal in [false, true] {
1176            let (_root, run) = fixture(internal);
1177            let token = run.orch_home.join("state/ui.port");
1178            assert!(policy(&run).hidden.contains(&token), "internal: {internal}");
1179        }
1180    }
1181
1182    #[test]
1183    fn no_chat_can_read_the_web_ui_token() {
1184        let token = PathBuf::from("/home/u/.orch/state/ui.port");
1185        let mut run = chat_fixture();
1186        assert!(
1187            chat_policy(&run).hidden.contains(&token),
1188            "the project chat"
1189        );
1190        run.project = None;
1191        run.control = true;
1192        assert!(
1193            chat_policy(&run).hidden.contains(&token),
1194            "the control chat"
1195        );
1196    }
1197
1198    #[test]
1199    fn the_control_chat_reads_no_project_and_may_act_through_orch() {
1200        let mut run = chat_fixture();
1201        run.project = None;
1202        run.control = true;
1203        let p = chat_policy(&run);
1204        assert!(
1205            !p.readable.iter().any(|r| r.starts_with("/home/u/code")),
1206            "no project folder"
1207        );
1208        assert!(
1209            !p.hidden
1210                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
1211            "it acts through the daemon"
1212        );
1213        assert!(
1214            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
1215            "credentials stay hidden"
1216        );
1217        assert!(
1218            p.unreadable.contains(&PathBuf::from("/home/u")),
1219            "the home stays closed"
1220        );
1221    }
1222
1223    #[test]
1224    fn a_chat_writes_only_its_temp_dir() {
1225        let p = chat_policy(&chat_fixture());
1226        assert!(
1227            p.writable.contains(&PathBuf::from("/tmp/chat")),
1228            "its temp dir"
1229        );
1230        assert!(
1231            !p.writable.iter().any(|w| w.starts_with("/home/u/code")),
1232            "never the project"
1233        );
1234    }
1235
1236    #[test]
1237    fn a_chat_reads_the_project_but_not_the_rest_of_the_home() {
1238        let p = chat_policy(&chat_fixture());
1239        assert!(
1240            p.unreadable.contains(&PathBuf::from("/home/u")),
1241            "the home is closed"
1242        );
1243        assert!(
1244            p.readable.contains(&PathBuf::from("/home/u/code/app")),
1245            "the project is open"
1246        );
1247        assert!(
1248            p.readable.contains(&PathBuf::from("/home/u/.claude")),
1249            "the agent can log in"
1250        );
1251        assert!(
1252            p.readable.contains(&PathBuf::from("/home/u/.cargo/bin")),
1253            "tools on PATH"
1254        );
1255    }
1256
1257    #[test]
1258    fn a_chat_cannot_see_credentials_or_the_write_token() {
1259        let p = chat_policy(&chat_fixture());
1260        assert!(
1261            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
1262            "ssh keys"
1263        );
1264        assert!(
1265            p.hidden.contains(&PathBuf::from("/home/u/.config/gh")),
1266            "the gh token"
1267        );
1268        assert!(
1269            p.hidden
1270                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
1271            "the daemon's write token"
1272        );
1273    }
1274
1275    #[test]
1276    fn orch_home_is_read_only_but_the_task_worktree_and_temp_dir() {
1277        let (_root, run) = fixture(false);
1278        let p = policy(&run);
1279        let o = &run.orch_home;
1280        let h = &run.home;
1281        assert!(
1282            !p.writable
1283                .iter()
1284                .any(|w| w.starts_with(h) && o.starts_with(w))
1285        );
1286        assert!(!p.writable.contains(&o.join("orch.db")));
1287        assert!(p.writable.contains(&run.work_dir));
1288        assert!(p.writable.contains(&run.temp));
1289        let other = o.join("worktrees/proj/other");
1290        assert!(!p.read_only.contains(&other));
1291        assert!(
1292            !p.writable
1293                .iter()
1294                .any(|w| other.starts_with(w) && w.starts_with(h))
1295        );
1296    }
1297
1298    #[test]
1299    fn other_tasks_add_no_rules() {
1300        let (_root, mut run) = fixture(false);
1301        let tasks = run.orch_home.join("state/owner/proj/tasks");
1302        for n in 0..50 {
1303            fs::create_dir_all(tasks.join(n.to_string()).join("attempts/1")).unwrap();
1304        }
1305        run.temp = tasks.join("7/attempts/1/tmp");
1306        fs::create_dir_all(&run.temp).unwrap();
1307        let p = policy(&run);
1308        assert!(!p.read_only.iter().any(|r| r.starts_with(&tasks)));
1309        assert!(p.writable.contains(&run.temp));
1310    }
1311
1312    #[test]
1313    fn a_relocated_orch_home_stays_read_only() {
1314        let (_root, mut run) = fixture(false);
1315        let data = run.home.join("data");
1316        let orch = data.join("orch");
1317        fs::create_dir_all(orch.join("worktrees/proj/mine")).unwrap();
1318        fs::create_dir_all(data.join("notes")).unwrap();
1319        fs::write(orch.join("config.yml"), "").unwrap();
1320        run.orch_home = orch.clone();
1321        run.work_dir = orch.join("worktrees/proj/mine");
1322        let p = policy(&run);
1323        let h = &run.home;
1324        let config = orch.join("config.yml");
1325        assert!(
1326            !p.writable
1327                .iter()
1328                .any(|w| config.starts_with(w) && w.starts_with(h))
1329        );
1330        assert!(p.writable.contains(&run.work_dir));
1331        assert!(p.writable.contains(&data.join("notes")));
1332        assert!(!p.writable.contains(&data));
1333    }
1334
1335    #[test]
1336    fn an_orch_home_in_a_writable_dir_outside_the_home_gets_read_only_rules() {
1337        let (root, mut run) = fixture(false);
1338        let outside = root.path().join("shared");
1339        let orch = outside.join("orch");
1340        fs::create_dir_all(orch.join("worktrees/proj/mine")).unwrap();
1341        fs::write(orch.join("config.yml"), "").unwrap();
1342        run.orch_home = orch.clone();
1343        run.work_dir = orch.join("worktrees/proj/mine");
1344        run.extra.write = vec![outside];
1345        let p = policy(&run);
1346        assert!(p.read_only.contains(&orch.join("config.yml")));
1347        assert!(!p.read_only.contains(&run.work_dir));
1348    }
1349
1350    #[test]
1351    fn the_clang_module_cache_is_writable_on_macos() {
1352        let (_root, run) = fixture(false);
1353        fs::create_dir_all(run.home.join("Library/Caches")).unwrap();
1354        let p = policy(&run);
1355        for (_, path) in cache_env(&run.home) {
1356            assert!(
1357                p.writable.iter().any(|w| path.starts_with(w)),
1358                "{} not writable",
1359                path.display()
1360            );
1361        }
1362    }
1363
1364    #[test]
1365    fn an_internal_task_writes_the_store() {
1366        let (_root, mut run) = fixture(false);
1367        run.internal = true;
1368        let p = policy(&run);
1369        for f in ["orch.db", "orch.db-wal", "orch.db-shm"] {
1370            assert!(
1371                p.writable.contains(&run.orch_home.join(f)),
1372                "{f} not writable"
1373            );
1374        }
1375    }
1376
1377    #[test]
1378    fn the_main_checkout_is_read_only_but_its_git_dir() {
1379        let (_root, run) = fixture(false);
1380        let p = policy(&run);
1381        let proj = run.home.join("proj");
1382        assert!(p.read_only.contains(&proj.join("src")));
1383        assert!(p.read_only.contains(&proj.join("README.md")));
1384        assert!(!p.read_only.contains(&proj.join(".git")));
1385        assert!(p.read_only.contains(&proj.join(".git/hooks")));
1386        assert!(p.read_only.contains(&proj.join(".git/config")));
1387    }
1388
1389    #[test]
1390    fn only_the_task_branch_is_writable_in_the_git_dir() {
1391        let (_root, run) = fixture(false);
1392        let p = policy(&run);
1393        let git = run.home.join("proj/.git");
1394        for path in [
1395            "refs/heads/main",
1396            "refs/heads/release",
1397            "packed-refs",
1398            "hooks",
1399            "config",
1400            "commondir",
1401            "gitdir",
1402            "config.worktree",
1403        ] {
1404            assert!(
1405                p.read_only.contains(&git.join(path)),
1406                "{path} not read-only"
1407            );
1408        }
1409        assert!(!p.read_only.contains(&git.join("refs/heads/feat/mine")));
1410        assert!(!p.read_only.contains(&git.join("refs/heads/feat")));
1411        assert!(!p.read_only.contains(&git.join("objects")));
1412        assert!(p.read_only.contains(&git.join("worktrees/other")));
1413        assert!(p.read_only.contains(&git.join("worktrees/mine/gitdir")));
1414        assert!(!p.read_only.contains(&git.join("worktrees/mine/HEAD")));
1415        assert!(p.read_only.contains(&run.work_dir.join(".git")));
1416        assert!(p.writable.contains(&git));
1417    }
1418
1419    #[test]
1420    fn hooks_and_config_of_an_unknown_repository_are_read_only() {
1421        let (_root, run) = fixture(false);
1422        let git = run.home.join("code/deep/other/.git");
1423        fs::create_dir_all(&git).unwrap();
1424        let p = policy(&run);
1425        assert!(p.read_only.contains(&git.join("hooks")));
1426        assert!(p.read_only.contains(&git.join("config")));
1427        assert!(!p.read_only.contains(&git));
1428    }
1429
1430    #[test]
1431    fn only_the_home_s_cache_dirs_are_writable() {
1432        let (_root, run) = fixture(false);
1433        let p = policy(&run);
1434        let h = &run.home;
1435        for path in [".cargo", "Library/Caches"] {
1436            assert!(p.writable.contains(&h.join(path)), "{path} not writable");
1437        }
1438        for path in ["", ".config", ".claude", ".orch", "Library"] {
1439            assert!(!p.writable.contains(&h.join(path)), "{path:?} writable");
1440        }
1441        assert!(p.read_only.contains(&h.join(".cargo/bin")));
1442        assert!(!p.read_only.contains(&PathBuf::from("/usr/bin")));
1443    }
1444
1445    #[test]
1446    fn no_socket_outside_the_worktree_and_no_launch_services() {
1447        let (root, mut run) = fixture(false);
1448        run.seatbelt = true;
1449        let p = policy(&run);
1450        let Access::Only(sockets) = &p.unix_sockets else {
1451            panic!("every unix socket is reachable");
1452        };
1453        assert_eq!(sockets, &vec![run.work_dir.clone(), run.temp.clone()]);
1454
1455        // Only the broker's socket, and the store beside it is not the agent's to write
1456        fs::create_dir_all(run.home.join(".passbox")).unwrap();
1457        fs::write(run.home.join(".passbox/broker.sock"), "").unwrap();
1458        fs::write(run.home.join(".passbox/ssh-agent.sock"), "").unwrap();
1459        let p = policy(&run);
1460        let Access::Only(sockets) = &p.unix_sockets else {
1461            panic!("every unix socket is reachable");
1462        };
1463        assert!(sockets.contains(&run.home.join(".passbox/broker.sock")));
1464        assert!(!sockets.contains(&run.home.join(".passbox/ssh-agent.sock")));
1465        assert!(!p.writable.contains(&run.home.join(".passbox")));
1466        // The fixture sits under /tmp when TMPDIR does
1467        let fixture_dir = root.path().canonicalize().unwrap();
1468        assert!(!sockets.iter().any(|s| {
1469            !s.starts_with(&fixture_dir) && (s.starts_with("/tmp") || s.starts_with("/private/tmp"))
1470        }));
1471        let Access::Only(mach) = &p.mach_services else {
1472            panic!("every Mach service is reachable");
1473        };
1474        assert!(mach.iter().any(|s| s == KEYCHAIN));
1475        assert!(!mach.iter().any(|s| s.contains("launchservices")));
1476        assert!(!mach.iter().any(|s| s.contains("CalendarAgent")));
1477
1478        let (_root, mut job) = fixture(true);
1479        job.seatbelt = true;
1480        let Access::Only(mach) = policy(&job).mach_services else {
1481            panic!("every Mach service is reachable");
1482        };
1483        assert!(mach.iter().any(|s| s == "com.apple.CalendarAgent"));
1484    }
1485
1486    #[test]
1487    fn code_running_config_in_a_writable_home_dir_is_read_only() {
1488        let (_root, run) = fixture(false);
1489        let p = policy(&run);
1490        assert!(p.writable.contains(&run.home.join(".cargo")));
1491        assert!(p.read_only.contains(&run.home.join(".cargo/config.toml")));
1492    }
1493
1494    #[test]
1495    fn a_git_dir_the_agent_could_have_pointed_elsewhere_is_refused() {
1496        let (_root, run) = fixture(false);
1497        let (work, main) = (&run.work_dir, run.home.join("proj"));
1498        let (git, common) = (
1499            run.git_dir.clone().unwrap(),
1500            run.common_dir.clone().unwrap(),
1501        );
1502
1503        fs::write(
1504            git.join("gitdir"),
1505            format!("{}\n", work.join(".git").display()),
1506        )
1507        .unwrap();
1508        assert!(check_git_dirs(work, &main, Some(&git), Some(&common)).is_ok());
1509
1510        // Pointed at the common dir, which only the main checkout uses
1511        assert!(check_git_dirs(work, &main, Some(&common), Some(&common)).is_err());
1512        assert!(check_git_dirs(&main, &main, Some(&common), Some(&common)).is_ok());
1513        // Another worktree's git dir, or none at all
1514        let other = common.join("worktrees/other");
1515        fs::write(other.join("gitdir"), "/elsewhere/.git\n").unwrap();
1516        assert!(check_git_dirs(work, &main, Some(&other), Some(&common)).is_err());
1517        assert!(check_git_dirs(work, &main, Some(&run.home), Some(&common)).is_err());
1518        assert!(check_git_dirs(work, &main, None, Some(&common)).is_err());
1519    }
1520
1521    #[test]
1522    fn the_config_adds_paths_and_lifts_no_read_only_rule() {
1523        let (_root, mut run) = fixture(false);
1524        let h = run.home.clone();
1525        fs::create_dir_all(h.join(".config/solana/install")).unwrap();
1526        run.extra = Extra {
1527            write: vec![h.join(".config/solana/install")],
1528            read: vec![h.join(".aws")],
1529            sockets: vec![h.join(".docker/run")],
1530        };
1531        let p = policy(&run);
1532        assert!(p.writable.contains(&h.join(".config/solana/install")));
1533        assert!(!p.hidden.contains(&h.join(".aws")));
1534        assert!(p.hidden.contains(&h.join(".ssh")));
1535        let Access::Only(sockets) = &p.unix_sockets else {
1536            panic!("every unix socket is reachable");
1537        };
1538        assert!(sockets.contains(&h.join(".docker/run")));
1539        assert!(p.read_only.contains(&h.join(".cargo/bin")));
1540    }
1541
1542    #[test]
1543    fn a_wide_write_entry_and_one_on_keys_or_startup_files_is_refused() {
1544        let home = Path::new("/home/u");
1545        for allowed in [
1546            "/home/u/.config/solana/install",
1547            "/home/u/Library/Developer/Xcode",
1548            "/opt/tool/cache",
1549        ] {
1550            assert!(may_write(Path::new(allowed), home), "{allowed}");
1551        }
1552        for refused in [
1553            "/",
1554            "/home",
1555            "/home/u",
1556            "/home/u/.zshrc",
1557            "/home/u/.config",
1558            "/home/u/.ssh/authorized_keys",
1559            "/home/u/.claude/settings.json",
1560            "/home/u/.local/bin/tool",
1561            "/home/u/Library/LaunchAgents/x.plist",
1562            "/home/u/.orch/config.yml",
1563            "/home/u/.config/../.ssh/x",
1564            "/home/u/.SSH/authorized_keys",
1565            "/home/u/.config/git/config",
1566        ] {
1567            assert!(!may_write(Path::new(refused), home), "{refused}");
1568        }
1569    }
1570
1571    #[test]
1572    fn a_config_path_is_absolute_or_under_the_home() {
1573        let home = Path::new("/home/u");
1574        assert_eq!(expand("~/.pypirc", home), Some("/home/u/.pypirc".into()));
1575        assert_eq!(expand("/opt/tool", home), Some("/opt/tool".into()));
1576        assert_eq!(expand("relative/path", home), None);
1577        assert_eq!(expand("~other/x", home), None);
1578    }
1579
1580    #[test]
1581    fn package_settings_reach_the_agent_without_their_credentials() {
1582        let (root, run) = fixture(false);
1583        let h = &run.home;
1584        fs::write(
1585            h.join(".npmrc"),
1586            "min-release-age=7\n//registry.npmjs.org/:_authToken=npm_abc\nregistry=https://user:pw@r.example/\nsave-exact=true\n",
1587        )
1588        .unwrap();
1589        fs::create_dir_all(h.join(".config/uv")).unwrap();
1590        fs::write(h.join(".config/uv/uv.toml"), "exclude-newer = \"7 days\"\n").unwrap();
1591        fs::create_dir_all(h.join(".config/pip")).unwrap();
1592        fs::write(
1593            h.join(".config/pip/pip.conf"),
1594            "[global]\nindex-url = https://u:p@pypi.example/simple\n",
1595        )
1596        .unwrap();
1597
1598        let temp = root.path().join("run-tmp");
1599        let found = package_config(h, &temp);
1600        let names: Vec<&str> = found.iter().map(|(name, _)| *name).collect();
1601        assert_eq!(names, ["NPM_CONFIG_USERCONFIG", "UV_CONFIG_FILE"]);
1602        let npmrc = fs::read_to_string(&found[0].1).unwrap();
1603        assert_eq!(npmrc, "min-release-age=7\nsave-exact=true\n");
1604        let uv = fs::read_to_string(&found[1].1).unwrap();
1605        assert_eq!(uv, "exclude-newer = \"7 days\"\n");
1606        assert!(found.iter().all(|(_, file)| file.starts_with(&temp)));
1607
1608        // The files themselves stay hidden
1609        let p = policy(&run);
1610        assert!(p.hidden.contains(&h.join(".npmrc")));
1611        assert!(p.hidden.contains(&h.join(".config/uv")));
1612    }
1613
1614    #[test]
1615    fn claude_s_session_dir_of_the_worktree_is_writable() {
1616        let (_root, run) = fixture(false);
1617        assert!(claude_project_dir(&run.home, &run.work_dir).is_none());
1618        fs::create_dir_all(run.home.join(".claude/projects/-other")).unwrap();
1619        let p = policy(&run);
1620        let name = run.work_dir.to_string_lossy().replace(['/', '.'], "-");
1621        let dir = run.home.join(".claude/projects").join(name);
1622        assert!(dir.is_dir());
1623        assert!(p.writable.contains(&dir));
1624        assert!(!p.writable.contains(&run.home.join(".claude/projects")));
1625        assert!(!p.writable.contains(&run.home.join(".claude")));
1626    }
1627
1628    #[test]
1629    fn shipcheck_s_state_is_read_only_and_opencode_s_service_hidden() {
1630        let (_root, run) = fixture(false);
1631        let p = policy(&run);
1632        let h = &run.home;
1633        assert!(p.read_only.contains(&h.join(".local/state/shipcheck")));
1634        assert!(
1635            p.hidden
1636                .contains(&h.join(".local/state/opencode/service.json"))
1637        );
1638        assert!(p.hidden.contains(&h.join(".config/opencode/service.json")));
1639    }
1640
1641    #[test]
1642    fn a_job_task_may_write_the_store() {
1643        let (_root, run) = fixture(true);
1644        assert!(
1645            !policy(&run)
1646                .read_only
1647                .contains(&run.orch_home.join("orch.db"))
1648        );
1649    }
1650
1651    #[test]
1652    fn only_a_job_task_sees_the_write_endpoint_token() {
1653        let (_root, run) = fixture(false);
1654        let token = run.orch_home.join("state/cluster.port");
1655        assert!(policy(&run).hidden.contains(&token));
1656        let (_root, run) = fixture(true);
1657        assert!(!policy(&run).hidden.contains(&token));
1658    }
1659
1660    #[test]
1661    fn keys_are_hidden_and_startup_files_read_only() {
1662        let (_root, run) = fixture(false);
1663        let p = policy(&run);
1664        assert!(p.hidden.contains(&run.home.join(".ssh")));
1665        assert!(p.hidden.contains(&run.home.join(".gnupg")));
1666        assert!(!p.hidden.iter().any(|h| h.ends_with(".cargo/config.toml")));
1667        assert!(p.read_only.contains(&run.work_dir.join(".orch.yml")));
1668    }
1669
1670    // A real Seatbelt run of the policy, skipped where no sandbox starts, such as inside another one.
1671    // Not on Linux: bwrap binds only existing paths, so a missing read-only path such as `.orch.yml` stays writable
1672    #[cfg(target_os = "macos")]
1673    #[test]
1674    fn the_kernel_enforces_the_policy() {
1675        let Ok(backend) = Backend::detect() else {
1676            eprintln!("skipped: no OS sandbox starts here");
1677            return;
1678        };
1679        let (_root, mut run) = fixture(false);
1680        run.seatbelt = backend == Backend::Seatbelt;
1681        let other = run.orch_home.join("worktrees/proj/other");
1682        fs::create_dir_all(run.home.join(".ssh")).unwrap();
1683        fs::write(run.home.join(".ssh/key"), "k").unwrap();
1684        let script = format!(
1685            "echo ok > {w}/f && ! echo x > {o}/config.yml && ! echo x > {other}/f \
1686             && ! echo x > {w}/.orch.yml && ! echo x >> {h}/.zshrc && ! cat {h}/.ssh/key \
1687             && ! echo x > {h}/.new-dotfile && ! echo x > {h}/.claude.json \
1688             && echo cache > {h}/.cargo/probe",
1689            w = run.work_dir.display(),
1690            o = run.orch_home.display(),
1691            other = other.display(),
1692            h = run.home.display(),
1693        );
1694        let out = Sandbox::new(backend, policy(&run))
1695            .unwrap()
1696            .command("/bin/sh")
1697            .args(["-c", &script])
1698            .output()
1699            .unwrap();
1700        assert!(
1701            out.status.success(),
1702            "{}",
1703            String::from_utf8_lossy(&out.stderr)
1704        );
1705        assert!(run.work_dir.join("f").exists());
1706        assert!(!other.join("f").exists());
1707    }
1708
1709    // A socket outside the worktree, such as tmux's, is out of reach, and another branch's ref too
1710    // Not on Linux: bwrap has no socket filter, so a socket in the home stays reachable
1711    #[cfg(target_os = "macos")]
1712    #[test]
1713    fn the_kernel_keeps_sockets_and_other_branches_out_of_reach() {
1714        let Ok(backend) = Backend::detect() else {
1715            eprintln!("skipped: no OS sandbox starts here");
1716            return;
1717        };
1718        let (_root, mut run) = fixture(false);
1719        run.seatbelt = backend == Backend::Seatbelt;
1720        for dir in [&run.work_dir, &run.home] {
1721            let listener = UnixListener::bind(dir.join("s")).unwrap();
1722            thread::spawn(move || listener.incoming().for_each(drop));
1723        }
1724        let git = run.home.join("proj/.git");
1725        let script = format!(
1726            "/usr/bin/nc -U {w}/s </dev/null && ! /usr/bin/nc -U {h}/s </dev/null \
1727             && echo sha > {g}/refs/heads/feat/mine && ! echo sha > {g}/refs/heads/main \
1728             && echo sha > {g}/worktrees/mine/HEAD && ! echo x > {g}/worktrees/mine/gitdir",
1729            w = run.work_dir.display(),
1730            h = run.home.display(),
1731            g = git.display(),
1732        );
1733        let out = Sandbox::new(backend, policy(&run))
1734            .unwrap()
1735            .command("/bin/sh")
1736            .args(["-c", &script])
1737            .output()
1738            .unwrap();
1739        assert!(
1740            out.status.success(),
1741            "{}",
1742            String::from_utf8_lossy(&out.stderr)
1743        );
1744        assert_eq!(fs::read_to_string(git.join("refs/heads/main")).unwrap(), "");
1745    }
1746
1747    // A missing commondir in the common dir would redirect git to a dir the agent controls
1748    // Not on Linux: bwrap binds only existing paths, so a missing `commondir` stays writable
1749    #[cfg(target_os = "macos")]
1750    #[test]
1751    fn the_kernel_refuses_a_new_commondir_in_the_common_dir() {
1752        let Ok(backend) = Backend::detect() else {
1753            eprintln!("skipped: no OS sandbox starts here");
1754            return;
1755        };
1756        let (_root, mut run) = fixture(false);
1757        run.seatbelt = backend == Backend::Seatbelt;
1758        let git = run.home.join("proj/.git");
1759        assert!(!git.join("commondir").exists());
1760        let script = format!(
1761            "! echo {w} > {g}/commondir",
1762            w = run.work_dir.display(),
1763            g = git.display()
1764        );
1765        let out = Sandbox::new(backend, policy(&run))
1766            .unwrap()
1767            .command("/bin/sh")
1768            .args(["-c", &script])
1769            .output()
1770            .unwrap();
1771        assert!(
1772            out.status.success(),
1773            "{}",
1774            String::from_utf8_lossy(&out.stderr)
1775        );
1776        assert!(!git.join("commondir").exists());
1777    }
1778
1779    // Removing or replacing tmux's socket file is refused
1780    #[cfg(any(target_os = "macos", target_os = "linux"))]
1781    #[test]
1782    fn the_kernel_keeps_the_tmux_socket_in_the_temp_dir_in_place() {
1783        let Ok(backend) = Backend::detect() else {
1784            eprintln!("skipped: no OS sandbox starts here");
1785            return;
1786        };
1787        let (_root, mut run) = fixture(false);
1788        run.seatbelt = backend == Backend::Seatbelt;
1789        let dir = tempfile::Builder::new()
1790            .prefix("tmux-")
1791            .tempdir_in(&run.home)
1792            .unwrap();
1793        run.temp = run.home.clone();
1794        let sock = dir.path().join("default");
1795        fs::write(&sock, "").unwrap();
1796        let script = format!(
1797            "! rm {s} && ! mv {s} {s}2 && ! echo x > {d}/new",
1798            s = sock.display(),
1799            d = dir.path().display(),
1800        );
1801        let out = Sandbox::new(backend, policy(&run))
1802            .unwrap()
1803            .command("/bin/sh")
1804            .args(["-c", &script])
1805            .output()
1806            .unwrap();
1807        assert!(
1808            out.status.success(),
1809            "{}",
1810            String::from_utf8_lossy(&out.stderr)
1811        );
1812        assert!(sock.exists());
1813    }
1814
1815    // The run's temp dir, the package settings copy and the `sandbox:` paths, under the kernel
1816    #[cfg(any(target_os = "macos", target_os = "linux"))]
1817    #[test]
1818    fn the_kernel_honors_the_run_temp_dir_package_copies_and_config_paths() {
1819        let Ok(backend) = Backend::detect() else {
1820            eprintln!("skipped: no OS sandbox starts here");
1821            return;
1822        };
1823        let (root, mut run) = fixture(false);
1824        run.seatbelt = backend == Backend::Seatbelt;
1825        let (h, r) = (run.home.clone(), root.path().canonicalize().unwrap());
1826        fs::create_dir_all(&run.temp).unwrap();
1827        fs::write(
1828            h.join(".npmrc"),
1829            "min-release-age=3\n//registry.example/:_authToken=npm-secret\n",
1830        )
1831        .unwrap();
1832        fs::create_dir_all(h.join(".aws")).unwrap();
1833        fs::write(h.join(".aws/config"), "aws").unwrap();
1834        let (outside, shared) = (r.join("outside"), r.parent().unwrap().to_path_buf());
1835        fs::create_dir_all(&outside).unwrap();
1836        let found = package_config(&h, &run.temp);
1837        let npmrc = &found
1838            .iter()
1839            .find(|(v, _)| *v == "NPM_CONFIG_USERCONFIG")
1840            .unwrap()
1841            .1;
1842        let probe = |run: &Run, script: &str| {
1843            let out = Sandbox::new(backend, policy(run))
1844                .unwrap()
1845                .command("/bin/sh")
1846                .args(["-c", script])
1847                .env("TMPDIR", &run.temp)
1848                .output()
1849                .unwrap();
1850            assert!(
1851                out.status.success(),
1852                "{script}\n{}",
1853                String::from_utf8_lossy(&out.stderr)
1854            );
1855        };
1856        let name = format!("{}-probe", r.file_name().unwrap().to_string_lossy());
1857        probe(
1858            &run,
1859            &format!(
1860                "f=$(mktemp \"$TMPDIR/x.XXXXXX\") && echo ok > \"$f\" \
1861                 && ! echo x > {s}/{name} \
1862                 && grep -q min-release-age {n} && ! grep -q npm-secret {n} \
1863                 && ! cat {h}/.npmrc && ! cat {h}/.aws/config && ! echo x > {o}/f",
1864                s = shared.display(),
1865                n = npmrc.display(),
1866                h = h.display(),
1867                o = outside.display(),
1868            ),
1869        );
1870        assert!(!shared.join(&name).exists());
1871
1872        run.extra = Extra {
1873            write: vec![outside.clone(), h.join("proj/src")],
1874            read: vec![h.join(".aws")],
1875            sockets: vec![],
1876        };
1877        probe(
1878            &run,
1879            &format!(
1880                "echo ok > {o}/f && cat {h}/.aws/config && ! cat {h}/.npmrc \
1881                 && ! echo x > {h}/proj/src/f",
1882                o = outside.display(),
1883                h = h.display(),
1884            ),
1885        );
1886        assert!(outside.join("f").exists());
1887        assert!(!h.join("proj/src/f").exists());
1888    }
1889
1890    // A logged-in claude answers under the policy with the real home: `--run-ignored only claude`
1891    #[cfg(target_os = "macos")]
1892    #[test]
1893    #[ignore = "needs a logged-in claude on the host"]
1894    fn claude_answers_inside_the_sandbox_with_the_real_home() {
1895        let root = tempfile::tempdir().unwrap();
1896        let work = root.path().canonicalize().unwrap();
1897        let home = PathBuf::from(env::var_os("HOME").unwrap());
1898        let run = Run {
1899            work_dir: work.clone(),
1900            git_dir: None,
1901            common_dir: None,
1902            own_ref: None,
1903            home: home.clone(),
1904            orch_home: home.join(".orch"),
1905            projects: vec![],
1906            path_dirs: env::split_paths(&env::var_os("PATH").unwrap()).collect(),
1907            temp: env::temp_dir(),
1908            extra: Extra::default(),
1909            internal: false,
1910            seatbelt: true,
1911        };
1912        let out = Sandbox::new(Backend::Seatbelt, policy(&run))
1913            .unwrap()
1914            .command("/bin/sh")
1915            .args(["-c", "claude -p --model haiku 'Reply with the word ok'"])
1916            .current_dir(&work)
1917            .output()
1918            .unwrap();
1919        let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
1920        assert!(
1921            text.contains("ok"),
1922            "{text}{}",
1923            String::from_utf8_lossy(&out.stderr)
1924        );
1925    }
1926
1927    #[test]
1928    fn bwrap_drops_a_missing_write_path_and_seatbelt_keeps_it() {
1929        let (_root, mut run) = fixture(false);
1930        let (missing, present) = (run.home.join("data/new"), run.home.join(".config/nvim"));
1931        run.extra.write = vec![missing.clone(), present.clone()];
1932        let p = policy(&run);
1933        assert!(!p.writable.contains(&missing));
1934        assert!(p.writable.contains(&present));
1935        run.seatbelt = true;
1936        assert!(policy(&run).writable.contains(&missing));
1937    }
1938
1939    #[test]
1940    fn a_worktree_that_is_the_main_checkout_stays_writable() {
1941        let (_root, mut run) = fixture(false);
1942        run.work_dir = run.home.join("proj");
1943        let p = policy(&run);
1944        assert!(!p.read_only.contains(&run.work_dir));
1945        assert!(!p.read_only.contains(&run.work_dir.join("src")));
1946    }
1947}