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