orch-cli 0.112.0

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
//! Copy-on-write task worktrees cloned from a per-project template by the git-cow crate, see docs/content/docs/cow-worktrees.md

use crate::sys::home;
use std::env;
use std::path::{Path, PathBuf};

use git_cow::cleanup::{self, Action, Done, Options};
use tokio::task;

fn template_dir(project: &str) -> anyhow::Result<PathBuf> {
    Ok(home::state_dir()?.join("templates").join(project))
}

// Called after a task PR merges and before its worktree is removed.
// Projects with a working checkout are warmed from that checkout instead
pub async fn warm_from_merged(repo_root: &Path, project: &str, wt_dir: &Path) {
    let (repo, wt) = (repo_root.to_path_buf(), wt_dir.to_path_buf());
    let Ok(template) = template_dir(project) else {
        return;
    };
    let res = task::spawn_blocking(move || {
        let bare =
            git_cow::git(&repo, &["rev-parse", "--is-bare-repository"]).is_ok_and(|v| v == "true");
        let wt_parent = wt.parent().unwrap_or(&wt);
        let templates = template.parent().unwrap_or(&template);
        if !bare || !template.join(".git").exists() || !git_cow::can_clone(templates, wt_parent) {
            return Ok(());
        }
        git_cow::warm(&wt, &template)
    })
    .await;
    if let Ok(Err(e)) = res {
        tracing::debug!(error = %e, "template warm-up from merged task failed");
    }
}

// The step after a merge: git-cow removes the worktree and its local branch when the work is in
// `base`, merged or squash-merged. False when the worktree stays, so the caller removes it
pub async fn remove_landed(repo_root: &Path, wt_dir: &Path, base: Option<&str>) -> bool {
    let (repo, wt) = (repo_root.to_path_buf(), wt_dir.to_path_buf());
    let opts = Options {
        base: base.map(String::from),
        ..Options::default()
    };
    let res = task::spawn_blocking(move || {
        let plan = cleanup::plan_worktree(&repo, &wt, &opts)?;
        for item in plan.items() {
            if let Action::Keep(why) = item.action() {
                tracing::debug!(worktree = %wt.display(), state = item.state().label(), %why, "git-cow keeps the worktree");
            }
        }
        let mut removed = false;
        for done in cleanup::execute(&plan) {
            match done {
                Done::Removed(path) => {
                    removed = true;
                    tracing::info!(worktree = %path.display(), "landed worktree removed");
                }
                Done::Deleted { branch, backup, .. } => {
                    tracing::info!(%branch, %backup, "landed local branch deleted");
                }
                Done::Failed { what, why } => {
                    tracing::warn!(%what, %why, "git-cow cleanup left an item");
                }
                _ => {}
            }
        }
        anyhow::Ok(removed)
    })
    .await;
    match res {
        Ok(Ok(removed)) => removed,
        Ok(Err(e)) => {
            tracing::debug!(error = %e, "git-cow cleanup plan failed");
            false
        }
        Err(e) => {
            tracing::warn!(error = %e, "git-cow cleanup task failed");
            false
        }
    }
}

// Create `wt_dir` as a worktree of `branch` by cloning the project template checked out at `start`.
// On error nothing is left behind and the caller falls back to `git worktree add`
pub async fn create_worktree(
    main_dir: &Path,
    project: &str,
    wt_dir: &Path,
    branch: &str,
    start: &str,
) -> anyhow::Result<()> {
    if env::var("ORCH_COW_WORKTREES").is_ok_and(|v| v == "0") {
        anyhow::bail!("disabled by ORCH_COW_WORKTREES=0");
    }
    let template = template_dir(project)?;
    let (repo, wt, branch, start) = (
        main_dir.to_path_buf(),
        wt_dir.to_path_buf(),
        branch.to_string(),
        start.to_string(),
    );
    task::spawn_blocking(move || git_cow::add(&repo, &template, &start, &wt, None, Some(&branch)))
        .await??;
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::process::Command;

    use super::*;

    fn sh(dir: &Path, args: &[&str]) {
        let mut cmd = Command::new("git");
        cmd.current_dir(dir);
        // Global commit.gpgsign calls the operator's signer (1Password)
        if args.first() == Some(&"commit") {
            cmd.args(["-c", "commit.gpgsign=false"]);
        }
        let st = cmd.args(args).status().unwrap();
        assert!(st.success(), "git {args:?}");
    }

    // CI jobs on a clone-capable volume set this so a failed probe fails the test
    fn expect_clone() -> bool {
        env::var("ORCH_COW_EXPECT_CLONE").is_ok_and(|v| v == "1")
    }

    fn repo_with_origin() -> (tempfile::TempDir, tempfile::TempDir, tempfile::TempDir) {
        let remote = tempfile::tempdir().unwrap();
        sh(remote.path(), &["init", "--bare", "-b", "main"]);
        let project = tempfile::tempdir().unwrap();
        sh(
            project.path(),
            &["clone", remote.path().to_str().unwrap(), "."],
        );
        sh(project.path(), &["config", "user.email", "t@t.com"]);
        sh(project.path(), &["config", "user.name", "T"]);
        fs::write(project.path().join("a.txt"), "a\n").unwrap();
        fs::write(project.path().join("d.txt"), "d\n").unwrap();
        sh(project.path(), &["add", "."]);
        sh(project.path(), &["commit", "-m", "init"]);
        sh(project.path(), &["push", "origin", "HEAD:main"]);
        sh(project.path(), &["fetch", "origin"]);
        let home = tempfile::tempdir().unwrap();
        (remote, project, home)
    }

    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn clone_gives_clean_worktree_or_falls_back() {
        let (_remote, project, home) = repo_with_origin();
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        let templates = home.path().join("state/templates");
        fs::create_dir_all(&templates).unwrap();
        let wt_dir = home.path().join("worktrees/p/task-1");
        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
        sh(project.path(), &["branch", "task-1", "origin/main"]);

        // Volumes without clone support (ext4, HFS+) take the else branch
        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
        if expect_clone() {
            assert!(
                supported,
                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
            );
        }
        let res = create_worktree(project.path(), "p", &wt_dir, "task-1", "main").await;
        if supported {
            res.expect("clone path should succeed");
            assert_eq!(fs::read_to_string(wt_dir.join("a.txt")).unwrap(), "a\n");
            let status = Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&wt_dir)
                .output()
                .unwrap();
            assert!(status.stdout.is_empty(), "clone must have a clean index");
            assert!(super::super::worktree::validate_worktree_gitdir(&wt_dir).await);
        } else {
            assert!(res.is_err());
            assert!(!wt_dir.exists(), "failed clone must leave no directory");
        }
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
    }

    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn branch_differing_from_template_gets_its_own_files() {
        let (_remote, project, home) = repo_with_origin();
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        let templates = home.path().join("state/templates");
        fs::create_dir_all(&templates).unwrap();
        let wt_dir = home.path().join("worktrees/p/task-3");
        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();

        // Task branch: a.txt changed, b.txt added, d.txt deleted
        sh(
            project.path(),
            &["checkout", "-q", "-b", "task-3", "origin/main"],
        );
        fs::write(project.path().join("a.txt"), "changed\n").unwrap();
        fs::write(project.path().join("b.txt"), "b\n").unwrap();
        fs::remove_file(project.path().join("d.txt")).unwrap();
        sh(project.path(), &["add", "-A"]);
        sh(project.path(), &["commit", "-m", "task"]);
        sh(project.path(), &["checkout", "-q", "--detach"]);

        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
        if expect_clone() {
            assert!(
                supported,
                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
            );
        }
        if supported {
            create_worktree(project.path(), "p", &wt_dir, "task-3", "main")
                .await
                .expect("clone path should succeed");
            assert_eq!(
                fs::read_to_string(wt_dir.join("a.txt")).unwrap(),
                "changed\n"
            );
            assert_eq!(fs::read_to_string(wt_dir.join("b.txt")).unwrap(), "b\n");
            assert!(!wt_dir.join("d.txt").exists());
            let status = Command::new("git")
                .args(["status", "--porcelain"])
                .current_dir(&wt_dir)
                .output()
                .unwrap();
            assert!(status.stdout.is_empty(), "clone must have a clean index");
        }
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
    }

    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn checkout_ignored_dirs_reach_template_and_clone() {
        let (_remote, project, home) = repo_with_origin();
        fs::write(
            project.path().join(".gitignore"),
            "out/\n.env\n.local/\nnode/\n",
        )
        .unwrap();
        sh(project.path(), &["add", "."]);
        sh(project.path(), &["commit", "-m", "ignore"]);
        sh(project.path(), &["push", "origin", "HEAD:main"]);
        sh(project.path(), &["fetch", "origin"]);
        fs::create_dir_all(project.path().join("out/sub")).unwrap();
        fs::write(project.path().join("out/sub/dep.bin"), "dep\n").unwrap();
        fs::create_dir_all(project.path().join(".local")).unwrap();
        fs::write(project.path().join(".local/settings"), "x\n").unwrap();
        fs::create_dir_all(project.path().join("pkg/a/node")).unwrap();
        fs::write(project.path().join("pkg/a/node/dep.bin"), "nested\n").unwrap();
        fs::create_dir_all(project.path().join("pkg/a/.hidden/node")).unwrap();
        fs::write(project.path().join("pkg/a/.hidden/node/x"), "x\n").unwrap();
        fs::write(project.path().join("pkg/a/keep.txt"), "k\n").unwrap();
        fs::write(project.path().join(".env"), "secret\n").unwrap();

        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        let templates = home.path().join("state/templates");
        fs::create_dir_all(&templates).unwrap();
        let wt_dir = home.path().join("worktrees/p/task-4");
        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();
        sh(project.path(), &["branch", "task-4", "origin/main"]);

        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
        if expect_clone() {
            assert!(
                supported,
                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
            );
        }
        if supported {
            create_worktree(project.path(), "p", &wt_dir, "task-4", "main")
                .await
                .expect("clone path should succeed");
            let tpl = templates.join("p");
            for root in [&tpl, &wt_dir] {
                assert_eq!(
                    fs::read_to_string(root.join("out/sub/dep.bin")).unwrap(),
                    "dep\n"
                );
                assert!(!root.join(".env").exists(), "loose ignored file was copied");
                assert!(!root.join(".local").exists(), "hidden dir was copied");
                assert!(
                    !root.join("pkg/a/.hidden").exists(),
                    "nested hidden dir was copied"
                );
                assert_eq!(
                    fs::read_to_string(root.join("pkg/a/node/dep.bin")).unwrap(),
                    "nested\n"
                );
            }
            // The worktree keeps its own gitdir
            assert!(wt_dir.join(".git").is_file());
            assert_ne!(
                fs::read_to_string(wt_dir.join(".git")).unwrap(),
                fs::read_to_string(tpl.join(".git")).unwrap()
            );
            // git-cow warms the template from the checkout at most once an hour, so a second task
            // right after the first keeps the build output the template already has
            fs::remove_file(project.path().join("out/sub/dep.bin")).unwrap();
            fs::write(project.path().join("out/new.bin"), "new\n").unwrap();
            let wt2 = home.path().join("worktrees/p/task-5");
            sh(project.path(), &["branch", "task-5", "origin/main"]);
            create_worktree(project.path(), "p", &wt2, "task-5", "main")
                .await
                .unwrap();
            assert!(wt2.join("out/sub/dep.bin").exists());
            assert!(!wt2.join("out/new.bin").exists());
        }
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
    }

    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn merged_task_ignored_dirs_reach_template_of_bare_project() {
        let (remote, project, home) = repo_with_origin();
        fs::write(project.path().join(".gitignore"), "out/\n").unwrap();
        sh(project.path(), &["add", "."]);
        sh(project.path(), &["commit", "-m", "ignore"]);
        sh(project.path(), &["push", "origin", "HEAD:main"]);
        let bare = home.path().join("bare.git");
        sh(
            home.path(),
            &[
                "clone",
                "--bare",
                remote.path().to_str().unwrap(),
                "bare.git",
            ],
        );
        sh(&bare, &["branch", "task-6", "main"]);

        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        let templates = home.path().join("state/templates");
        fs::create_dir_all(&templates).unwrap();
        let wt_dir = home.path().join("worktrees/pb/task-6");
        fs::create_dir_all(wt_dir.parent().unwrap()).unwrap();

        let supported = git_cow::can_clone(&templates, wt_dir.parent().unwrap());
        if expect_clone() {
            assert!(
                supported,
                "ORCH_COW_EXPECT_CLONE is set but the volume cannot clone"
            );
        }
        if supported {
            create_worktree(&bare, "pb", &wt_dir, "task-6", "main")
                .await
                .expect("clone path should succeed");
            let tpl = templates.join("pb");
            assert!(!tpl.join("out").exists());

            fs::create_dir_all(wt_dir.join("out")).unwrap();
            fs::write(wt_dir.join("out/dep.bin"), "dep\n").unwrap();
            fs::write(wt_dir.join("loose.log"), "x\n").unwrap();

            // A project with a working checkout is not warmed from tasks
            warm_from_merged(project.path(), "pb", &wt_dir).await;
            assert!(!tpl.join("out").exists());

            warm_from_merged(&bare, "pb", &wt_dir).await;
            assert_eq!(
                fs::read_to_string(tpl.join("out/dep.bin")).unwrap(),
                "dep\n"
            );
            assert!(!tpl.join("loose.log").exists());
            assert!(tpl.join(".git").is_file());
        }
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
    }

    // A task worktree on `branch` with one commit, pushed, as a task leaves it before the merge
    fn task_worktree(project: &Path, home: &Path, branch: &str) -> PathBuf {
        let wt = home.join("worktrees/p").join(branch);
        fs::create_dir_all(wt.parent().unwrap()).unwrap();
        let wt_str = wt.to_str().unwrap();
        sh(
            project,
            &["worktree", "add", "-b", branch, wt_str, "origin/main"],
        );
        fs::write(wt.join("task.txt"), "work\n").unwrap();
        sh(&wt, &["add", "."]);
        sh(&wt, &["commit", "-m", "task work"]);
        sh(&wt, &["push", "origin", branch]);
        wt
    }

    fn squash_merge(project: &Path, branch: &str) {
        sh(project, &["merge", "--squash", branch]);
        sh(project, &["commit", "-m", "task work (#1)"]);
        sh(project, &["push", "origin", "HEAD:main"]);
    }

    fn ref_exists(project: &Path, name: &str) -> bool {
        let out = Command::new("git")
            .current_dir(project)
            .args(["for-each-ref", name])
            .output()
            .unwrap();
        !out.stdout.is_empty()
    }

    #[tokio::test]
    async fn remove_landed_removes_a_squash_merged_worktree_and_keeps_a_backup() {
        if !cleanup::squash_check_works() {
            return;
        }
        let (_remote, project, home) = repo_with_origin();
        let wt = task_worktree(project.path(), home.path(), "task-7");
        squash_merge(project.path(), "task-7");

        assert!(remove_landed(project.path(), &wt, None).await);
        assert!(!wt.exists());
        assert!(!ref_exists(project.path(), "refs/heads/task-7"));
        assert!(ref_exists(project.path(), "refs/git-cow/deleted/"));
    }

    #[tokio::test]
    async fn remove_landed_keeps_a_worktree_whose_work_is_not_in_the_base() {
        let (_remote, project, home) = repo_with_origin();
        let wt = task_worktree(project.path(), home.path(), "task-8");

        assert!(!remove_landed(project.path(), &wt, None).await);
        assert!(wt.join("task.txt").exists());
        assert!(ref_exists(project.path(), "refs/heads/task-8"));
    }

    #[tokio::test]
    async fn remove_landed_keeps_a_merged_worktree_with_an_untracked_file() {
        if !cleanup::squash_check_works() {
            return;
        }
        let (_remote, project, home) = repo_with_origin();
        let wt = task_worktree(project.path(), home.path(), "task-9");
        squash_merge(project.path(), "task-9");
        // Without the file git-cow removes this worktree, as the squash-merged test shows
        fs::write(wt.join("notes.txt"), "not committed\n").unwrap();

        assert!(!remove_landed(project.path(), &wt, None).await);
        assert!(wt.join("notes.txt").exists());
        assert!(ref_exists(project.path(), "refs/heads/task-9"));
    }

    #[tokio::test]
    #[serial_test::serial(orch_home)]
    async fn env_switch_disables_clone_path() {
        let (_remote, project, home) = repo_with_origin();
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_HOME", home.path()) };
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::set_var("ORCH_COW_WORKTREES", "0") };
        let wt_dir = home.path().join("worktrees/p/task-2");
        let res = create_worktree(project.path(), "p", &wt_dir, "task-2", "main").await;
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_COW_WORKTREES") };
        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
        unsafe { env::remove_var("ORCH_HOME") };
        assert!(res.is_err());
        assert!(!wt_dir.exists());
    }
}