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