orch-cli 0.103.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
//! The OS sandbox around a task or review agent, when `workflow.sandbox` is `os`. The policy and
//! why it is shaped this way are in docs/plans/2026-10-28-agent-sandboxes.md

use super::agent::AgentInvocation;
use crate::config;
use crate::home;
use sandbox_jail::{Access, Backend, Policy, Sandbox, known};
use std::env;
use std::error;
use std::ffi::OsString;
use std::fmt;
use std::fmt::Display;
use std::fmt::Formatter;
use std::fs;
use std::path::{Path, PathBuf};

/// Top-level dirs of the home that stay read-only: what loads or runs later as the operator, the
/// agents' own settings, and keys. Everything at the top of the home that is not a dir is read-only too
const HOME_READ_ONLY: &[&str] = &[
    ".config", ".claude", ".ssh", ".gnupg", "bin", "Library", ".local",
];

/// Writable parts of the read-only dirs above, for caches and agent state
const HOME_WRITABLE: &[&str] = &[
    "Library/Caches",
    "Library/Logs",
    ".local/share",
    ".local/state",
];

/// Codex's settings and instructions, which sit beside the state it rewrites
const AGENT_CONFIG: &[&str] = &[".codex/config.toml", ".codex/AGENTS.md", ".codex/rules"];

/// Config inside writable home dirs that runs code on the operator's next build or shell, read-only
/// even when missing. Cargo's `rustc-wrapper` and `runner`, gradle's init scripts, shell frameworks
const HOME_EXEC_CONFIG: &[&str] = &[
    ".cargo/config",
    ".cargo/config.toml",
    ".gradle/init.d",
    ".gradle/init.gradle",
    ".gradle/gradle.properties",
    ".m2/settings.xml",
    ".oh-my-zsh",
    ".zprezto",
];

/// The tmux, ssh-agent and Docker sockets that would let an agent start a process outside
const SCRATCH: &[&str] = &["/tmp", "/run", "/var/tmp"];

/// macOS services an agent may look up: the basics, and securityd for its keychain login. Not
/// LaunchServices, which `open` uses to start an app outside the sandbox
const KEYCHAIN: &str = "com.apple.SecurityServer";

/// The run's own temp dir, so no socket of the operator's apps in the shared one is in reach
pub fn run_temp_dir(attempt_dir: &Path) -> PathBuf {
    attempt_dir.join("tmp")
}

/// Whether the project runs its agents in the sandbox: `workflow.sandbox: os` in its `.orch.yml`
/// or the global config. `false` or no setting leaves it off
pub fn enabled(project_dir: &Path) -> bool {
    config::get_for_project(project_dir, "workflow.sandbox").is_ok_and(|v| v.trim() == "os")
}

/// Like [`enabled`] from the global config alone, for a run whose project is unknown
pub fn enabled_globally() -> bool {
    config::get_global("workflow.sandbox").is_ok_and(|v| v.trim() == "os")
}

/**
 * The program and arguments that go before the agent command, or why the sandbox cannot start.
 * The worktree's `.git` file is the agent's to write, so the common dir comes from the main
 * checkout and the branch from orch's records, and a git dir outside them refuses the run
 **/
pub async fn argv(inv: &AgentInvocation, temp: &Path) -> anyhow::Result<Vec<OsString>> {
    build(inv, temp)
        .await
        .map_err(|e| anyhow::Error::new(SandboxFailed(format!("{e:#}"))))
}

/// The sandbox cannot start. It is the operator's setup, so it blocks the task and counts against no agent
#[derive(Debug)]
pub struct SandboxFailed(pub String);

impl Display for SandboxFailed {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        write!(f, "the OS sandbox cannot start: {}", self.0)
    }
}

impl error::Error for SandboxFailed {}

async fn build(inv: &AgentInvocation, temp: &Path) -> anyhow::Result<Vec<OsString>> {
    let backend = Backend::detect()?;
    let common_dir =
        super::agent::resolve_git_dir_arg(&inv.main_project_dir, "--git-common-dir").await?;
    let git_dir = super::agent::resolve_git_dir_arg(&inv.work_dir, "--git-dir").await?;

    check_git_dirs(
        &inv.work_dir,
        &inv.main_project_dir,
        git_dir.as_deref(),
        common_dir.as_deref(),
    )?;

    let home = env::var_os("HOME")
        .map(PathBuf::from)
        .ok_or_else(|| anyhow::anyhow!("HOME is not set, so the sandbox cannot hide its keys"))?;
    let mut projects: Vec<PathBuf> = config::get_projects_with_paths()
        .unwrap_or_default()
        .into_iter()
        .map(|(_, dir)| dir)
        .collect();
    projects.push(inv.main_project_dir.clone());
    let path_dirs = env::var_os("PATH")
        .map(|p| env::split_paths(&p).collect())
        .unwrap_or_default();

    let run = Run {
        work_dir: inv.work_dir.clone(),
        git_dir,
        common_dir,
        own_ref: (!inv.branch.is_empty()).then(|| format!("refs/heads/{}", inv.branch)),
        home,
        orch_home: home::orch_home()?,
        projects,
        path_dirs,
        temp: temp.to_path_buf(),
        internal: inv.task_id.starts_with("internal:"),
        seatbelt: backend == Backend::Seatbelt,
    };
    let sandbox = Sandbox::new(backend, policy(&run))?;
    Ok(sandbox.argv().to_vec())
}

/**
 * Refuses a worktree whose git dir the agent could have pointed elsewhere. Only the main checkout
 * has the common dir as its git dir. A linked worktree's git dir is in `<common>/worktrees`, and
 * its `gitdir` file, which the agent cannot write, points back at this worktree
 **/
fn check_git_dirs(
    work_dir: &Path,
    main_project_dir: &Path,
    git_dir: Option<&Path>,
    common_dir: Option<&Path>,
) -> anyhow::Result<()> {
    let real = |p: &Path| p.canonicalize().unwrap_or_else(|_| p.to_path_buf());

    match (git_dir, common_dir) {
        (Some(git), Some(common)) if git == common => anyhow::ensure!(
            real(work_dir) == real(main_project_dir),
            "the worktree {} uses the repository's own git dir {}",
            work_dir.display(),
            common.display()
        ),
        (Some(git), Some(common)) => {
            anyhow::ensure!(
                git.starts_with(common.join("worktrees")),
                "the worktree's git dir {} is outside its repository {}",
                git.display(),
                common.display()
            );
            let back = fs::read_to_string(git.join("gitdir")).unwrap_or_default();
            anyhow::ensure!(
                real(Path::new(back.trim())) == real(&work_dir.join(".git")),
                "the git dir {} belongs to another worktree",
                git.display()
            );
        }
        (None, Some(common)) => anyhow::bail!(
            "the worktree {} has no git dir in {}",
            work_dir.display(),
            common.display()
        ),
        _ => {}
    }

    Ok(())
}

/// What the policy of one run depends on
struct Run {
    work_dir: PathBuf,
    git_dir: Option<PathBuf>,
    common_dir: Option<PathBuf>,
    /// The task's branch, `refs/heads/<branch>`, from orch's records
    own_ref: Option<String>,
    home: PathBuf,
    orch_home: PathBuf,
    projects: Vec<PathBuf>,
    path_dirs: Vec<PathBuf>,
    /// The run's own temp dir, where the agent may also connect to a socket
    temp: PathBuf,
    internal: bool,
    seatbelt: bool,
}

impl Run {
    fn git_dirs(&self) -> impl Iterator<Item = &PathBuf> {
        self.git_dir.iter().chain(&self.common_dir)
    }
}

fn policy(run: &Run) -> Policy {
    let mut p = Policy::default();
    p.writable.push(run.work_dir.clone());
    p.writable.extend(run.git_dirs().cloned());
    p.writable.extend(home_writable(&run.home));
    p.writable.push(run.temp.clone());

    if run.seatbelt {
        p.writable.push("/private/tmp".into());
        p.mach_services = Access::Only(
            known::BASIC_MACH_SERVICES
                .iter()
                .chain(&[KEYCHAIN])
                .map(ToString::to_string)
                .collect(),
        );
    } else {
        // bwrap has no socket filter, so the dirs that hold sockets start empty instead
        p.scratch = SCRATCH
            .iter()
            .map(PathBuf::from)
            .filter(|d| d.is_dir())
            .collect();
    }

    // The tmux server runs outside the sandbox, so its socket in /tmp must stay out of reach
    p.unix_sockets = Access::Only(vec![run.work_dir.clone(), run.temp.clone()]);

    if let Some(common) = &run.common_dir {
        git_rules(
            common,
            run.git_dir.as_ref(),
            run.own_ref.as_deref(),
            &mut p.read_only,
        );

        if run.git_dir.as_ref().is_some_and(|g| g != common) {
            p.read_only.push(run.work_dir.join(".git"));
        }
    }

    for dir in home_writable(&run.home) {
        find_git_dirs(&dir, GIT_SCAN_DEPTH, &mut p.read_only);
    }

    // /private/tmp stays writable, but the agent must not delete or replace these sockets.
    // bwrap hides those in a scratch dir, and binding one back would expose it
    let hidden = p.scratch.clone();
    p.read_only.extend(
        socket_dirs(&run.temp)
            .into_iter()
            .filter(|d| !hidden.iter().any(|s| d.starts_with(s))),
    );

    p.read_only.push(run.work_dir.join(".orch.yml"));
    p.read_only.extend(
        AGENT_CONFIG
            .iter()
            .chain(HOME_EXEC_CONFIG)
            .map(|path| run.home.join(path)),
    );
    // A tool on PATH inside the home, such as ~/.cargo/bin, runs later as the operator
    p.read_only.extend(
        run.path_dirs
            .iter()
            .filter(|d| d.starts_with(&run.home))
            .cloned(),
    );

    let mut keep: Vec<PathBuf> = vec![run.work_dir.clone(), run.temp.clone()];
    keep.extend(run.git_dirs().cloned());

    if run.internal {
        keep.extend(["orch.db", "orch.db-wal", "orch.db-shm"].map(|f| run.orch_home.join(f)));
    }
    // The daemon's loopback write endpoint takes this token, so reading it is a write to the store
    let write_token = run.orch_home.join("state/cluster.port");

    read_only_around(&run.orch_home, &keep, &mut p.read_only);

    for project in &run.projects {
        read_only_around(project, &keep, &mut p.read_only);
    }

    // The crate's list hides cargo's config too, which holds build settings agents need
    p.hidden = known::credentials(&run.home)
        .into_iter()
        .filter(|path| {
            ![".cargo/config", ".cargo/config.toml"]
                .map(|c| run.home.join(c))
                .contains(path)
        })
        .collect();
    p.hidden.push(run.home.join(".gnupg"));

    // The web UI's token drives the daemon's API, config edits and plan imports among it
    p.hidden.push(run.orch_home.join(UI_TOKEN));

    if !run.internal {
        p.hidden.push(write_token);
    }

    p.own_signals = true;

    // launchctl and setuid binaries start processes outside the sandbox
    if run.seatbelt {
        p.apple_events = false;
        p.no_exec.push(known::LAUNCHCTL.into());
        p.no_exec.extend(known::setuid_binaries().iter().cloned());
    }

    p
}

/// The web UI's port and token. No agent may read it, it would drive the daemon through the UI's API
const UI_TOKEN: &str = "state/ui.port";

/// The agent's own login and settings, which it reads to start. The Security framework reads the
/// login keychain in the calling process, and its access rules still give the agent only its own item
const CHAT_AGENT_HOME: &[&str] = &[".claude", ".claude.json", "Library/Keychains"];

/// Where agents keep sessions and caches, which the control chat writes to resume a conversation
const AGENT_STATE: &[&str] = &[
    ".claude/projects",
    ".claude/todos",
    ".claude/shell-snapshots",
    ".claude/statsig",
    ".codex",
    ".local/share/opencode",
    ".local/state/opencode",
];

/// Other agents' settings, read at start
const AGENT_CONFIG_READ: &[&str] = &[".codex", ".config/opencode", ".grok"];

/// What a chat agent may touch, as opposed to a task agent's [`policy`]
struct ChatRun {
    home: PathBuf,
    orch_home: PathBuf,
    /// The project a project chat reads, none for the control chat
    project: Option<PathBuf>,
    temp: PathBuf,
    path_dirs: Vec<PathBuf>,
    seatbelt: bool,
    /// The control chat keeps agent sessions and acts through orch, so it writes session dirs and
    /// reads the daemon's write token. A project chat does neither
    control: bool,
}

/// The sandbox prefix for a project chat agent. It reads the project and orch's store and config,
/// writes only its temp dir, and cannot read the rest of the home or any credential
pub fn chat_argv(project: &Path, temp: &Path) -> anyhow::Result<Vec<OsString>> {
    chat_sandbox(Some(project), temp, false)
}

/**
 * The sandbox prefix for the control chat, which Telegram and the other channels reach. It reads
 * orch's home and acts through orch, and cannot read the rest of the home or any credential.
 * Inside another Seatbelt sandbox, which cannot nest, it runs in that one
 **/
pub fn control_argv(temp: &Path) -> anyhow::Result<Vec<OsString>> {
    match chat_sandbox(None, temp, true) {
        Err(e)
            if e.downcast_ref::<sandbox_jail::Error>()
                .is_some_and(|e| matches!(e, sandbox_jail::Error::Nested)) =>
        {
            tracing::info!("already inside a sandbox, the control chat runs in it");
            Ok(Vec::new())
        }
        other => other,
    }
}

fn chat_sandbox(
    project: Option<&Path>,
    temp: &Path,
    control: bool,
) -> anyhow::Result<Vec<OsString>> {
    let backend = Backend::detect()?;
    let home = env::var_os("HOME")
        .map(PathBuf::from)
        .ok_or_else(|| anyhow::anyhow!("HOME is not set"))?;
    let run = ChatRun {
        home,
        orch_home: home::orch_home()?,
        project: project.map(Path::to_path_buf),
        temp: temp.to_path_buf(),
        path_dirs: env::var_os("PATH")
            .map(|p| env::split_paths(&p).collect())
            .unwrap_or_default(),
        seatbelt: matches!(backend, Backend::Seatbelt),
        control,
    };
    Ok(Sandbox::new(backend, chat_policy(&run))?.argv().to_vec())
}

fn chat_policy(run: &ChatRun) -> Policy {
    let mut p = Policy::default();
    p.writable.push(run.temp.clone());
    // `orch task list` opens the store, and SQLite writes its -wal and -shm files even to read
    p.writable.extend(
        ["orch.db", "orch.db-wal", "orch.db-shm"]
            .map(|f| run.orch_home.join(f))
            .into_iter()
            .filter(|f| f.exists()),
    );

    if run.seatbelt {
        p.writable.push("/private/tmp".into());
        p.mach_services = Access::Only(
            known::BASIC_MACH_SERVICES
                .iter()
                .chain(&[KEYCHAIN])
                .map(ToString::to_string)
                .collect(),
        );
    } else {
        p.scratch = SCRATCH
            .iter()
            .map(PathBuf::from)
            .filter(|d| d.is_dir())
            .collect();
    }

    p.unix_sockets = Access::Only(vec![run.temp.clone()]);

    if run.control {
        p.writable.extend(
            AGENT_STATE
                .iter()
                .map(|d| run.home.join(d))
                .filter(|d| d.is_dir()),
        );
        // Codex writes its state beside its settings, which stay as the owner wrote them
        p.read_only
            .extend(AGENT_CONFIG.iter().map(|path| run.home.join(path)));
    }

    // The tmux server and launchd's sockets sit in the writable /private/tmp, and an agent that
    // deleted or replaced one would end every session or stand in for the ssh agent
    p.read_only.extend(socket_dirs(&run.temp));

    p.unreadable.push(run.home.clone());
    p.readable.extend(run.project.iter().cloned());
    p.readable.push(run.orch_home.clone());
    p.readable
        .extend(AGENT_CONFIG_READ.iter().map(|f| run.home.join(f)));
    p.readable
        .extend(CHAT_AGENT_HOME.iter().map(|f| run.home.join(f)));
    p.readable.extend(
        run.path_dirs
            .iter()
            .filter(|d| d.starts_with(&run.home))
            .cloned(),
    );

    p.hidden = known::credentials(&run.home);
    p.hidden.push(run.home.join(".gnupg"));
    p.hidden.push(run.orch_home.join(UI_TOKEN));
    // The daemon's loopback write endpoint takes this token, and a project chat only reads
    if !run.control {
        p.hidden.push(run.orch_home.join("state/cluster.port"));
    }

    p.own_signals = true;
    if run.seatbelt {
        p.apple_events = false;
        p.no_exec.push(known::LAUNCHCTL.into());
        p.no_exec.extend(known::setuid_binaries().iter().cloned());
    }

    p
}

/// How many levels below a writable home dir are searched for repositories
const GIT_SCAN_DEPTH: usize = 4;

// Hooks and config of a repository orch does not know run as the operator on its next git command
fn find_git_dirs(dir: &Path, depth: usize, out: &mut Vec<PathBuf>) {
    let git = dir.join(".git");

    if git.is_dir() {
        out.extend(["hooks", "config", "info", "modules"].map(|f| git.join(f)));
    }

    if depth == 0 {
        return;
    }

    for entry in fs::read_dir(dir).into_iter().flatten().flatten() {
        let name = entry.file_name();

        if entry.file_type().is_ok_and(|t| t.is_dir()) && name != ".git" && name != "node_modules" {
            find_git_dirs(&entry.path(), depth - 1, out);
        }
    }
}

/// The tmux and launchd socket dirs in the shared temp dirs, which the tmux server and the
/// ssh-agent keep running outside the sandbox
fn socket_dirs(temp: &Path) -> Vec<PathBuf> {
    let mut roots = vec![PathBuf::from("/private/tmp"), PathBuf::from("/tmp")];
    roots.extend(env::var_os("TMUX_TMPDIR").map(PathBuf::from));
    roots.push(temp.to_path_buf());

    roots
        .iter()
        .filter_map(|r| fs::read_dir(r).ok())
        .flatten()
        .flatten()
        .filter(|e| {
            let name = e.file_name();
            let name = name.to_string_lossy();
            name.starts_with("tmux-") || name.starts_with("com.apple.launchd.")
        })
        .map(|e| e.path())
        .collect()
}

/// The home's writable parts: its top-level dirs but [`HOME_READ_ONLY`], and [`HOME_WRITABLE`]
/// inside those. The home itself stays read-only, so no new dotfile appears at its top
fn home_writable(home: &Path) -> Vec<PathBuf> {
    let mut dirs: Vec<PathBuf> = fs::read_dir(home)
        .into_iter()
        .flatten()
        .flatten()
        .filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
        .filter(|e| !HOME_READ_ONLY.contains(&e.file_name().to_string_lossy().as_ref()))
        .map(|e| e.path())
        .collect();
    dirs.extend(
        HOME_WRITABLE
            .iter()
            .map(|d| home.join(d))
            .filter(|d| d.is_dir()),
    );
    dirs
}

/**
 * The git common dir is writable for objects, the task's branch, remote refs and the task's own
 * worktree dir, and read-only around those: hooks and config run the next time the operator runs
 * git, and another branch is the operator's work. Paths git would pick up when they appear are
 * read-only even when missing, and so is a loose ref for a branch only `packed-refs` holds, since
 * it would win over the packed one
 **/
fn git_rules(
    common: &Path,
    git_dir: Option<&PathBuf>,
    own_ref: Option<&str>,
    out: &mut Vec<PathBuf>,
) {
    out.extend(
        [
            "hooks",
            "config",
            "info",
            "modules",
            "packed-refs",
            "refs/tags",
            "commondir",
            "gitdir",
            "config.worktree",
        ]
        .map(|d| common.join(d)),
    );
    let own: Vec<PathBuf> = own_ref
        .map(|r| vec![common.join(r), common.join("logs").join(r)])
        .unwrap_or_default();

    match git_dir {
        Some(dir) if dir != common => {
            let mut keep = vec![
                common.join("objects"),
                common.join("refs/remotes"),
                common.join("logs/refs/remotes"),
                dir.clone(),
            ];
            keep.extend(own.iter().cloned());
            read_only_around(common, &keep, out);
            out.extend(["HEAD", "commondir", "gitdir", "config.worktree"].map(|f| dir.join(f)));
        }
        // The worktree is the main checkout, so its index and HEAD live in the common dir
        _ => read_only_around(&common.join("refs/heads"), &own, out),
    }

    let packed = fs::read_to_string(common.join("packed-refs")).unwrap_or_default();
    for name in packed
        .lines()
        .filter_map(|l| l.split_once(' ').map(|(_, r)| r))
    {
        let path = common.join(name);

        if name.starts_with("refs/heads/") && !own.contains(&path) && !path.exists() {
            out.push(path);
        }
    }
}

/**
 * Every entry of `dir` read-only but the paths in `keep`. An entry that holds a kept path is
 * walked instead, so `~/.orch` stays read-only around the task's own worktree, and a main checkout
 * around its `.git`. A missing `dir` adds nothing
 **/
fn read_only_around(dir: &Path, keep: &[PathBuf], out: &mut Vec<PathBuf>) {
    let Ok(entries) = fs::read_dir(dir) else {
        return;
    };

    for entry in entries.flatten() {
        let path = entry.path();

        if keep.iter().any(|k| path.starts_with(k)) {
            continue;
        }

        let holds_kept = keep.iter().any(|k| k.starts_with(&path));
        let is_dir = entry.file_type().is_ok_and(|t| t.is_dir());

        if holds_kept && is_dir {
            read_only_around(&path, keep, out);
        } else if !holds_kept {
            out.push(path);
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    #[cfg(target_os = "macos")]
    use std::os::unix::net::UnixListener;
    #[cfg(target_os = "macos")]
    use std::thread;

    #[tokio::test]
    async fn argv_error_is_tagged_so_spawn_blocks_the_task() {
        let inv = AgentInvocation {
            agent: "claude".to_string(),
            model: None,
            work_dir: PathBuf::from("/nonexistent/work"),
            system_prompt: String::new(),
            agent_message: String::new(),
            task_id: "t".to_string(),
            disallowed_tools: vec![],
            git_author_name: String::new(),
            git_author_email: String::new(),
            output_file: PathBuf::from("/nonexistent/out.json"),
            timeout_seconds: 0,
            repo: "o/r".to_string(),
            attempt: 1,
            sandbox: true,
            main_project_dir: PathBuf::from("/nonexistent/main"),
            branch: String::new(),
        };
        let err = argv(&inv, Path::new("/tmp/orch-test-run"))
            .await
            .expect_err("no checkout, so no sandbox");
        assert!(err.downcast_ref::<SandboxFailed>().is_some());
        assert!(err.to_string().starts_with("the OS sandbox cannot start: "));
    }

    /// A home with an orch home inside, two worktrees and a main checkout, and the run of one task
    fn fixture(internal: bool) -> (tempfile::TempDir, Run) {
        let root = tempfile::tempdir().unwrap();
        let r = root.path().canonicalize().unwrap();
        let (home, orch) = (r.join("home"), r.join("home/.orch"));
        for dir in [
            "home/.orch/worktrees/proj/mine",
            "home/.orch/worktrees/proj/other",
            "home/.orch/state",
            "home/proj/.git/worktrees/mine",
            "home/proj/.git/refs/heads/feat",
            "home/proj/src",
            "home/proj/.git/objects",
            "home/proj/.git/worktrees/other",
            "home/.config/nvim",
            "home/.claude",
            "home/.cargo/bin",
            "home/Library/Caches",
            "home/Library/LaunchAgents",
        ] {
            fs::create_dir_all(r.join(dir)).unwrap();
        }
        for file in [
            "home/.orch/config.yml",
            "home/.orch/orch.db",
            "home/proj/README.md",
            "home/proj/.git/refs/heads/main",
            "home/proj/.git/refs/heads/feat/mine",
            "home/proj/.git/worktrees/mine/HEAD",
            "home/.zshrc",
            "home/.claude.json",
        ] {
            fs::write(r.join(file), "").unwrap();
        }
        fs::write(
            r.join("home/proj/.git/packed-refs"),
            "# pack-refs with: peeled\nabc refs/heads/release\n",
        )
        .unwrap();

        let run = Run {
            work_dir: orch.join("worktrees/proj/mine"),
            git_dir: Some(home.join("proj/.git/worktrees/mine")),
            common_dir: Some(home.join("proj/.git")),
            own_ref: Some("refs/heads/feat/mine".into()),
            home: home.clone(),
            orch_home: orch,
            projects: vec![home.join("proj")],
            path_dirs: vec![home.join(".cargo/bin"), "/usr/bin".into()],
            temp: r.join("tmp"),
            internal,
            seatbelt: false,
        };
        (root, run)
    }

    fn chat_fixture() -> ChatRun {
        ChatRun {
            home: PathBuf::from("/home/u"),
            orch_home: PathBuf::from("/home/u/.orch"),
            project: Some(PathBuf::from("/home/u/code/app")),
            temp: PathBuf::from("/tmp/chat"),
            path_dirs: vec![
                PathBuf::from("/home/u/.cargo/bin"),
                PathBuf::from("/usr/bin"),
            ],
            seatbelt: true,
            control: false,
        }
    }

    #[test]
    fn no_task_can_read_the_web_ui_token() {
        for internal in [false, true] {
            let (_root, run) = fixture(internal);
            let token = run.orch_home.join("state/ui.port");
            assert!(policy(&run).hidden.contains(&token), "internal: {internal}");
        }
    }

    #[test]
    fn no_chat_can_read_the_web_ui_token() {
        let token = PathBuf::from("/home/u/.orch/state/ui.port");
        let mut run = chat_fixture();
        assert!(
            chat_policy(&run).hidden.contains(&token),
            "the project chat"
        );
        run.project = None;
        run.control = true;
        assert!(
            chat_policy(&run).hidden.contains(&token),
            "the control chat"
        );
    }

    #[test]
    fn the_control_chat_reads_no_project_and_may_act_through_orch() {
        let mut run = chat_fixture();
        run.project = None;
        run.control = true;
        let p = chat_policy(&run);
        assert!(
            !p.readable.iter().any(|r| r.starts_with("/home/u/code")),
            "no project folder"
        );
        assert!(
            !p.hidden
                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
            "it acts through the daemon"
        );
        assert!(
            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
            "credentials stay hidden"
        );
        assert!(
            p.unreadable.contains(&PathBuf::from("/home/u")),
            "the home stays closed"
        );
    }

    #[test]
    fn a_chat_writes_only_its_temp_dir() {
        let p = chat_policy(&chat_fixture());
        assert!(
            p.writable.contains(&PathBuf::from("/tmp/chat")),
            "its temp dir"
        );
        assert!(
            !p.writable.iter().any(|w| w.starts_with("/home/u/code")),
            "never the project"
        );
    }

    #[test]
    fn a_chat_reads_the_project_but_not_the_rest_of_the_home() {
        let p = chat_policy(&chat_fixture());
        assert!(
            p.unreadable.contains(&PathBuf::from("/home/u")),
            "the home is closed"
        );
        assert!(
            p.readable.contains(&PathBuf::from("/home/u/code/app")),
            "the project is open"
        );
        assert!(
            p.readable.contains(&PathBuf::from("/home/u/.claude")),
            "the agent can log in"
        );
        assert!(
            p.readable.contains(&PathBuf::from("/home/u/.cargo/bin")),
            "tools on PATH"
        );
    }

    #[test]
    fn a_chat_cannot_see_credentials_or_the_write_token() {
        let p = chat_policy(&chat_fixture());
        assert!(
            p.hidden.contains(&PathBuf::from("/home/u/.ssh")),
            "ssh keys"
        );
        assert!(
            p.hidden.contains(&PathBuf::from("/home/u/.config/gh")),
            "the gh token"
        );
        assert!(
            p.hidden
                .contains(&PathBuf::from("/home/u/.orch/state/cluster.port")),
            "the daemon's write token"
        );
    }

    #[test]
    fn orch_home_is_read_only_around_the_task_worktree() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        let o = &run.orch_home;
        for path in [
            o.join("config.yml"),
            o.join("state"),
            o.join("orch.db"),
            o.join("worktrees/proj/other"),
        ] {
            assert!(
                p.read_only.contains(&path),
                "{} not read-only",
                path.display()
            );
        }
        for path in [
            o.join("worktrees"),
            o.join("worktrees/proj"),
            run.work_dir.clone(),
        ] {
            assert!(!p.read_only.contains(&path), "{} read-only", path.display());
        }
        assert!(p.writable.contains(&run.work_dir));
    }

    #[test]
    fn the_main_checkout_is_read_only_but_its_git_dir() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        let proj = run.home.join("proj");
        assert!(p.read_only.contains(&proj.join("src")));
        assert!(p.read_only.contains(&proj.join("README.md")));
        assert!(!p.read_only.contains(&proj.join(".git")));
        assert!(p.read_only.contains(&proj.join(".git/hooks")));
        assert!(p.read_only.contains(&proj.join(".git/config")));
    }

    #[test]
    fn only_the_task_branch_is_writable_in_the_git_dir() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        let git = run.home.join("proj/.git");
        for path in [
            "refs/heads/main",
            "refs/heads/release",
            "packed-refs",
            "hooks",
            "config",
            "commondir",
            "gitdir",
            "config.worktree",
        ] {
            assert!(
                p.read_only.contains(&git.join(path)),
                "{path} not read-only"
            );
        }
        assert!(!p.read_only.contains(&git.join("refs/heads/feat/mine")));
        assert!(!p.read_only.contains(&git.join("refs/heads/feat")));
        assert!(!p.read_only.contains(&git.join("objects")));
        assert!(p.read_only.contains(&git.join("worktrees/other")));
        assert!(p.read_only.contains(&git.join("worktrees/mine/HEAD")));
        assert!(p.read_only.contains(&run.work_dir.join(".git")));
        assert!(p.writable.contains(&git));
    }

    #[test]
    fn hooks_and_config_of_an_unknown_repository_are_read_only() {
        let (_root, run) = fixture(false);
        let git = run.home.join("code/deep/other/.git");
        fs::create_dir_all(&git).unwrap();
        let p = policy(&run);
        assert!(p.read_only.contains(&git.join("hooks")));
        assert!(p.read_only.contains(&git.join("config")));
        assert!(!p.read_only.contains(&git));
    }

    #[test]
    fn only_the_home_s_cache_dirs_are_writable() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        let h = &run.home;
        for path in [".cargo", ".orch", "Library/Caches"] {
            assert!(p.writable.contains(&h.join(path)), "{path} not writable");
        }
        for path in ["", ".config", ".claude", "Library"] {
            assert!(!p.writable.contains(&h.join(path)), "{path:?} writable");
        }
        assert!(p.read_only.contains(&h.join(".cargo/bin")));
        assert!(!p.read_only.contains(&PathBuf::from("/usr/bin")));
    }

    #[test]
    fn no_socket_outside_the_worktree_and_no_launch_services() {
        let (_root, mut run) = fixture(false);
        run.seatbelt = true;
        let p = policy(&run);
        let Access::Only(sockets) = &p.unix_sockets else {
            panic!("every unix socket is reachable");
        };
        assert_eq!(sockets, &vec![run.work_dir, run.temp]);
        assert!(
            !sockets
                .iter()
                .any(|s| s.starts_with("/tmp") || s.starts_with("/private/tmp"))
        );
        let Access::Only(mach) = &p.mach_services else {
            panic!("every Mach service is reachable");
        };
        assert!(mach.iter().any(|s| s == KEYCHAIN));
        assert!(!mach.iter().any(|s| s.contains("launchservices")));
    }

    #[test]
    fn code_running_config_in_a_writable_home_dir_is_read_only() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        assert!(p.writable.contains(&run.home.join(".cargo")));
        assert!(p.read_only.contains(&run.home.join(".cargo/config.toml")));
    }

    #[test]
    fn a_git_dir_the_agent_could_have_pointed_elsewhere_is_refused() {
        let (_root, run) = fixture(false);
        let (work, main) = (&run.work_dir, run.home.join("proj"));
        let (git, common) = (
            run.git_dir.clone().unwrap(),
            run.common_dir.clone().unwrap(),
        );

        fs::write(
            git.join("gitdir"),
            format!("{}\n", work.join(".git").display()),
        )
        .unwrap();
        assert!(check_git_dirs(work, &main, Some(&git), Some(&common)).is_ok());

        // Pointed at the common dir, which only the main checkout uses
        assert!(check_git_dirs(work, &main, Some(&common), Some(&common)).is_err());
        assert!(check_git_dirs(&main, &main, Some(&common), Some(&common)).is_ok());
        // Another worktree's git dir, or none at all
        let other = common.join("worktrees/other");
        fs::write(other.join("gitdir"), "/elsewhere/.git\n").unwrap();
        assert!(check_git_dirs(work, &main, Some(&other), Some(&common)).is_err());
        assert!(check_git_dirs(work, &main, Some(&run.home), Some(&common)).is_err());
        assert!(check_git_dirs(work, &main, None, Some(&common)).is_err());
    }

    #[test]
    fn a_job_task_may_write_the_store() {
        let (_root, run) = fixture(true);
        assert!(
            !policy(&run)
                .read_only
                .contains(&run.orch_home.join("orch.db"))
        );
    }

    #[test]
    fn only_a_job_task_sees_the_write_endpoint_token() {
        let (_root, run) = fixture(false);
        let token = run.orch_home.join("state/cluster.port");
        assert!(policy(&run).hidden.contains(&token));
        let (_root, run) = fixture(true);
        assert!(!policy(&run).hidden.contains(&token));
    }

    #[test]
    fn keys_are_hidden_and_startup_files_read_only() {
        let (_root, run) = fixture(false);
        let p = policy(&run);
        assert!(p.hidden.contains(&run.home.join(".ssh")));
        assert!(p.hidden.contains(&run.home.join(".gnupg")));
        assert!(!p.hidden.iter().any(|h| h.ends_with(".cargo/config.toml")));
        assert!(p.read_only.contains(&run.work_dir.join(".orch.yml")));
    }

    // A real Seatbelt run of the policy. Skipped where no sandbox starts, such as inside another one
    #[cfg(target_os = "macos")]
    #[test]
    fn the_kernel_enforces_the_policy() {
        let Ok(backend) = Backend::detect() else {
            eprintln!("skipped: no OS sandbox starts here");
            return;
        };
        let (_root, mut run) = fixture(false);
        run.seatbelt = backend == Backend::Seatbelt;
        let other = run.orch_home.join("worktrees/proj/other");
        fs::create_dir_all(run.home.join(".ssh")).unwrap();
        fs::write(run.home.join(".ssh/key"), "k").unwrap();
        let script = format!(
            "echo ok > {w}/f && ! echo x > {o}/config.yml && ! echo x > {other}/f \
             && ! echo x > {w}/.orch.yml && ! echo x >> {h}/.zshrc && ! cat {h}/.ssh/key \
             && ! echo x > {h}/.new-dotfile && ! echo x > {h}/.claude.json \
             && echo cache > {h}/.cargo/probe",
            w = run.work_dir.display(),
            o = run.orch_home.display(),
            other = other.display(),
            h = run.home.display(),
        );
        let out = Sandbox::new(backend, policy(&run))
            .unwrap()
            .command("/bin/sh")
            .args(["-c", &script])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(run.work_dir.join("f").exists());
        assert!(!other.join("f").exists());
    }

    // A socket outside the worktree, such as tmux's, is out of reach, and another branch's ref too
    #[cfg(target_os = "macos")]
    #[test]
    fn the_kernel_keeps_sockets_and_other_branches_out_of_reach() {
        let Ok(backend) = Backend::detect() else {
            eprintln!("skipped: no OS sandbox starts here");
            return;
        };
        let (_root, mut run) = fixture(false);
        run.seatbelt = backend == Backend::Seatbelt;
        for dir in [&run.work_dir, &run.home] {
            let listener = UnixListener::bind(dir.join("s")).unwrap();
            thread::spawn(move || listener.incoming().for_each(drop));
        }
        let git = run.home.join("proj/.git");
        let script = format!(
            "/usr/bin/nc -U {w}/s </dev/null && ! /usr/bin/nc -U {h}/s </dev/null \
             && echo sha > {g}/refs/heads/feat/mine && ! echo sha > {g}/refs/heads/main",
            w = run.work_dir.display(),
            h = run.home.display(),
            g = git.display(),
        );
        let out = Sandbox::new(backend, policy(&run))
            .unwrap()
            .command("/bin/sh")
            .args(["-c", &script])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert_eq!(fs::read_to_string(git.join("refs/heads/main")).unwrap(), "");
    }

    // A missing commondir in the common dir would redirect git to a dir the agent controls
    #[cfg(target_os = "macos")]
    #[test]
    fn the_kernel_refuses_a_new_commondir_in_the_common_dir() {
        let Ok(backend) = Backend::detect() else {
            eprintln!("skipped: no OS sandbox starts here");
            return;
        };
        let (_root, mut run) = fixture(false);
        run.seatbelt = backend == Backend::Seatbelt;
        let git = run.home.join("proj/.git");
        assert!(!git.join("commondir").exists());
        let script = format!(
            "! echo {w} > {g}/commondir",
            w = run.work_dir.display(),
            g = git.display()
        );
        let out = Sandbox::new(backend, policy(&run))
            .unwrap()
            .command("/bin/sh")
            .args(["-c", &script])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(!git.join("commondir").exists());
    }

    // Removing or replacing tmux's socket file is refused
    #[cfg(target_os = "macos")]
    #[test]
    fn the_kernel_keeps_the_tmux_socket_in_the_temp_dir_in_place() {
        let Ok(backend) = Backend::detect() else {
            eprintln!("skipped: no OS sandbox starts here");
            return;
        };
        let (_root, mut run) = fixture(false);
        run.seatbelt = backend == Backend::Seatbelt;
        let dir = tempfile::Builder::new()
            .prefix("tmux-")
            .tempdir_in(&run.home)
            .unwrap();
        run.temp = run.home.clone();
        let sock = dir.path().join("default");
        fs::write(&sock, "").unwrap();
        let script = format!(
            "! rm {s} && ! mv {s} {s}2 && ! echo x > {d}/new",
            s = sock.display(),
            d = dir.path().display(),
        );
        let out = Sandbox::new(backend, policy(&run))
            .unwrap()
            .command("/bin/sh")
            .args(["-c", &script])
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "{}",
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(sock.exists());
    }

    // A logged-in claude answers under the policy with the real home: `--run-ignored only claude`
    #[cfg(target_os = "macos")]
    #[test]
    #[ignore = "needs a logged-in claude on the host"]
    fn claude_answers_inside_the_sandbox_with_the_real_home() {
        let root = tempfile::tempdir().unwrap();
        let work = root.path().canonicalize().unwrap();
        let home = PathBuf::from(env::var_os("HOME").unwrap());
        let run = Run {
            work_dir: work.clone(),
            git_dir: None,
            common_dir: None,
            own_ref: None,
            home: home.clone(),
            orch_home: home.join(".orch"),
            projects: vec![],
            path_dirs: env::split_paths(&env::var_os("PATH").unwrap()).collect(),
            temp: env::temp_dir(),
            internal: false,
            seatbelt: true,
        };
        let out = Sandbox::new(Backend::Seatbelt, policy(&run))
            .unwrap()
            .command("/bin/sh")
            .args(["-c", "claude -p --model haiku 'Reply with the word ok'"])
            .current_dir(&work)
            .output()
            .unwrap();
        let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
        assert!(
            text.contains("ok"),
            "{text}{}",
            String::from_utf8_lossy(&out.stderr)
        );
    }

    #[test]
    fn a_worktree_that_is_the_main_checkout_stays_writable() {
        let (_root, mut run) = fixture(false);
        run.work_dir = run.home.join("proj");
        let p = policy(&run);
        assert!(!p.read_only.contains(&run.work_dir));
        assert!(!p.read_only.contains(&run.work_dir.join("src")));
    }
}