orch-cli 0.105.13

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
//! How orch commits. A repository that uses shipcheck commits through `shipcheck commit`, which
//! commits only a tree its checks passed, any other repository through git

use super::shipcheck::Shipcheck;
use std::path::Path;
use std::process::{Output, Stdio};

use tokio::io::AsyncWriteExt;
use tokio::process::Command;

use crate::config;
use crate::sys::cmd::CommandErrorContext;

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Tool {
    Git,
    Shipcheck,
}

impl Tool {
    /// The same rule the agent prompt follows: shipcheck when the repository opts in and the
    /// installed shipcheck has `commit`, git otherwise
    pub async fn detect(dir: &Path) -> Self {
        // Without the file there is nothing to ask, and asking runs `shipcheck --help`
        if !dir.join("shipcheck.toml").exists() {
            return Tool::Git;
        }

        match Shipcheck::detect(dir).await {
            Shipcheck::Available => Tool::Shipcheck,
            Shipcheck::Absent | Shipcheck::NotInstalled | Shipcheck::Outdated => Tool::Git,
        }
    }
}

/// Whether a commit may skip shipcheck's gate
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum When {
    /// Only a tree shipcheck already passed, for steps during a session
    Tested,
    /// Commit anyway, for the end of a session, so the agent's work is never left uncommitted.
    /// shipcheck's hooks run the checks when the branch is pushed
    Always,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Outcome {
    Committed {
        /// Staged blobs left out because they are over GitHub's 100 MiB limit
        skipped_oversized: Vec<String>,
    },
    Nothing {
        skipped_oversized: Vec<String>,
    },
    /// The commit did not happen, and the tree is as it was. shipcheck refuses a tree without a passing run
    Refused {
        by: Tool,
        reason: String,
    },
}

/// GitHub refuses a push that holds a blob over 100 MiB (GH001)
pub(crate) const MAX_BLOB_BYTES: u64 = 100 * 1024 * 1024;

/// Last-error text when `commit_all` leaves blobs over GitHub's size limit unstaged
pub(crate) fn oversized_commit_note(paths: &[String]) -> String {
    format!(
        "left files over GitHub's size limit out of the commit: {}",
        paths.join(", ")
    )
}

fn identity(agent: &str) -> (String, String) {
    let name = config::get("git.name").unwrap_or_else(|_| format!("{agent}[bot]"));
    let email = config::get("git.email")
        .unwrap_or_else(|_| format!("{agent}[bot]@users.noreply.github.com"));
    (name, email)
}

/// The git commit behind every orch commit: the agent's identity, and never the operator's signing agent
pub async fn git_commit(dir: &Path, message: &str, agent: &str) -> anyhow::Result<Output> {
    let (name, email) = identity(agent);
    Command::new("git")
        .args(["-c", "commit.gpgsign=false", "commit", "-m", message])
        .env("GIT_AUTHOR_NAME", &name)
        .env("GIT_COMMITTER_NAME", &name)
        .env("GIT_AUTHOR_EMAIL", &email)
        .env("GIT_COMMITTER_EMAIL", &email)
        .current_dir(dir)
        .output_with_context()
        .await
}

async fn shipcheck_commit(
    dir: &Path,
    bin: &Path,
    message: &str,
    agent: &str,
) -> anyhow::Result<Outcome> {
    let (name, email) = identity(agent);
    let out = Command::new(bin)
        .args(["commit", "-m", message])
        .env("GIT_AUTHOR_NAME", &name)
        .env("GIT_COMMITTER_NAME", &name)
        .env("GIT_AUTHOR_EMAIL", &email)
        .env("GIT_COMMITTER_EMAIL", &email)
        .current_dir(dir)
        .output_with_context()
        .await?;
    if out.status.success() {
        return Ok(Outcome::Committed {
            skipped_oversized: Vec::new(),
        });
    }

    let why = String::from_utf8_lossy(&out.stderr).trim().to_string();
    Ok(Outcome::Refused {
        by: Tool::Shipcheck,
        reason: format!("shipcheck commit refused, run `shipcheck run` first: {why}"),
    })
}

/// Commit every change in `dir` with the tool the repository uses
pub async fn commit_all(
    dir: &Path,
    message: &str,
    agent: &str,
    when: When,
) -> anyhow::Result<Outcome> {
    let tool = Tool::detect(dir).await;
    let bin = which::which("shipcheck").unwrap_or_else(|_| "shipcheck".into());
    commit_with(dir, tool, &bin, message, agent, when).await
}

async fn commit_with(
    dir: &Path,
    tool: Tool,
    shipcheck: &Path,
    message: &str,
    agent: &str,
    when: When,
) -> anyhow::Result<Outcome> {
    if !has_changes(dir).await {
        return Ok(Outcome::Nothing {
            skipped_oversized: Vec::new(),
        });
    }

    if tool == Tool::Shipcheck {
        let outcome = shipcheck_commit(dir, shipcheck, message, agent).await?;
        let Outcome::Refused { reason, .. } = &outcome else {
            return Ok(outcome);
        };
        if when == When::Tested {
            return Ok(outcome);
        }

        tracing::info!(reason = %reason, "committing untested work through git at the end of the session");
    }

    let add = Command::new("git")
        .args(["add", "-A"])
        .current_dir(dir)
        .output_with_context()
        .await?;
    if !add.status.success() {
        tracing::warn!("git add -A failed");
        return Ok(Outcome::Refused {
            by: Tool::Git,
            reason: String::from_utf8_lossy(&add.stderr).trim().to_string(),
        });
    }

    let skipped_oversized = unstage_oversized(dir, MAX_BLOB_BYTES).await?;
    if !skipped_oversized.is_empty() {
        tracing::warn!(
            files = ?skipped_oversized,
            "left files over GitHub's size limit out of the commit"
        );
        if !has_staged(dir).await {
            return Ok(Outcome::Nothing { skipped_oversized });
        }
    }

    let out = git_commit(dir, message, agent).await?;
    if out.status.success() {
        return Ok(Outcome::Committed { skipped_oversized });
    }

    let reason = String::from_utf8_lossy(&out.stderr).trim().to_string();
    unstage(dir, &reason).await?;
    Ok(Outcome::Refused {
        by: Tool::Git,
        reason,
    })
}

/// Unstage every staged blob larger than `limit` and return its path. The staged size is what
/// gets pushed, so an LFS pointer stays staged however large the file on disk is
async fn unstage_oversized(dir: &Path, limit: u64) -> anyhow::Result<Vec<String>> {
    let raw = Command::new("git")
        .args([
            "diff",
            "--cached",
            "--raw",
            "--full-index",
            "--no-renames",
            "-z",
            "--diff-filter=AMT",
        ])
        .current_dir(dir)
        .output_with_context()
        .await?;
    if !raw.status.success() {
        return Ok(Vec::new());
    }

    let entries = parse_raw_diff(&String::from_utf8_lossy(&raw.stdout));
    if entries.is_empty() {
        return Ok(Vec::new());
    }

    let mut child = Command::new("git")
        .args(["cat-file", "--batch-check=%(objectsize)"])
        .current_dir(dir)
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .kill_on_drop(true)
        .spawn()?;
    let mut input = entries
        .iter()
        .map(|(sha, _)| sha.as_str())
        .collect::<Vec<_>>()
        .join("\n");
    input.push('\n');
    {
        let mut stdin = child
            .stdin
            .take()
            .ok_or_else(|| anyhow::anyhow!("git cat-file stdin closed"))?;
        stdin.write_all(input.as_bytes()).await?;
    }

    let sizes = child.wait_with_output().await?;
    if !sizes.status.success() {
        anyhow::bail!(
            "git cat-file failed: {}",
            String::from_utf8_lossy(&sizes.stderr).trim()
        );
    }

    let oversized: Vec<String> = String::from_utf8_lossy(&sizes.stdout)
        .lines()
        .zip(&entries)
        .filter(|(size, _)| size.trim().parse::<u64>().is_ok_and(|n| n > limit))
        .map(|(_, (_, path))| path.clone())
        .collect();
    if oversized.is_empty() {
        return Ok(oversized);
    }

    let restore = Command::new("git")
        .args(["--literal-pathspecs", "restore", "--staged", "--"])
        .args(&oversized)
        .current_dir(dir)
        .output_with_context()
        .await?;
    if !restore.status.success() {
        anyhow::bail!(
            "failed to unstage files over GitHub's size limit: {}",
            String::from_utf8_lossy(&restore.stderr).trim()
        );
    }

    Ok(oversized)
}

/// The new blob sha and path of each entry in `git diff --raw -z`, gitlinks left out
fn parse_raw_diff(out: &str) -> Vec<(String, String)> {
    let mut fields = out.split('\0');
    let mut entries = Vec::new();
    while let (Some(meta), Some(path)) = (fields.next(), fields.next()) {
        let parts: Vec<&str> = meta.trim_start_matches(':').split(' ').collect();
        if let [_, mode, _, sha, _] = parts[..]
            && mode != "160000"
        {
            entries.push((sha.to_string(), path.to_string()));
        }
    }
    entries
}

async fn has_staged(dir: &Path) -> bool {
    Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .current_dir(dir)
        .status()
        .await
        .is_ok_and(|s| !s.success())
}

/// Leave a failed commit's files unstaged, so the next check sees them and can retry cleanly
async fn unstage(dir: &Path, commit_err: &str) -> anyhow::Result<()> {
    let restore = Command::new("git")
        .args(["restore", "--staged", "."])
        .current_dir(dir)
        .output_with_context()
        .await;
    let restore_err = match restore {
        Ok(o) if o.status.success() => return Ok(()),
        Ok(o) => String::from_utf8_lossy(&o.stderr).trim().to_string(),
        Err(e) => e.to_string(),
    };
    tracing::warn!(err = %restore_err, "git restore --staged failed, falling back to git reset HEAD -- .");
    let reset = Command::new("git")
        .args(["reset", "HEAD", "--", "."])
        .current_dir(dir)
        .output_with_context()
        .await?;
    if !reset.status.success() {
        anyhow::bail!(
            "git commit failed and cleanup failed (git restore --staged + git reset HEAD -- .): commit stderr: {commit_err}; restore: {restore_err}; reset stderr: {}",
            String::from_utf8_lossy(&reset.stderr).trim()
        );
    }

    Ok(())
}

/// Check if there are uncommitted changes in the working directory.
pub async fn has_changes(dir: &Path) -> bool {
    // Check for staged, unstaged, and untracked files
    let diff = Command::new("git")
        .args(["diff", "--quiet"])
        .current_dir(dir)
        .status()
        .await;

    let cached = Command::new("git")
        .args(["diff", "--cached", "--quiet"])
        .current_dir(dir)
        .status()
        .await;

    let untracked = Command::new("git")
        .args(["ls-files", "--others", "--exclude-standard"])
        .current_dir(dir)
        .output_with_context()
        .await;

    let has_diff = diff.is_ok_and(|s| !s.success());
    let has_cached = cached.is_ok_and(|s| !s.success());
    let has_untracked =
        untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());

    has_diff || has_cached || has_untracked
}

#[cfg(test)]
mod tests {
    use std::fs;
    use std::fs::Permissions;
    use std::os::unix::fs::PermissionsExt;
    use std::path::PathBuf;
    use std::process;

    use super::*;

    fn git(dir: &Path, args: &[&str]) -> String {
        let out = process::Command::new("git")
            .args([
                "-c",
                "user.name=T",
                "-c",
                "user.email=t@t",
                "-c",
                "commit.gpgsign=false",
            ])
            .args(args)
            .current_dir(dir)
            .output()
            .unwrap();
        assert!(
            out.status.success(),
            "git {args:?}: {}",
            String::from_utf8_lossy(&out.stderr)
        );
        String::from_utf8_lossy(&out.stdout).to_string()
    }

    fn repo() -> tempfile::TempDir {
        let dir = tempfile::tempdir().unwrap();
        git(dir.path(), &["init", "-b", "main"]);
        fs::write(dir.path().join("base.txt"), "base").unwrap();
        git(dir.path(), &["add", "base.txt"]);
        git(dir.path(), &["commit", "-m", "base"]);
        dir
    }

    /// A stand-in for shipcheck: `ok` commits like `shipcheck commit`, anything else refuses
    fn fake_shipcheck(dir: &Path, ok: bool) -> PathBuf {
        let bin = dir.join("shipcheck");
        let body = if ok {
            "#!/bin/sh\ngit add -A && git -c commit.gpgsign=false commit -q -m \"$3\"\n"
        } else {
            "#!/bin/sh\necho 'no passing result for this tree' >&2\nexit 1\n"
        };
        fs::write(&bin, body).unwrap();
        fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
        bin
    }

    #[tokio::test]
    async fn git_commits_every_change_and_reports_nothing_on_a_clean_tree() {
        let dir = repo();
        let missing = Path::new("/nonexistent/shipcheck");
        fs::write(dir.path().join("a.txt"), "a").unwrap();
        let out = commit_with(
            dir.path(),
            Tool::Git,
            missing,
            "step",
            "claude",
            When::Tested,
        )
        .await
        .unwrap();
        assert_eq!(
            out,
            Outcome::Committed {
                skipped_oversized: vec![]
            }
        );
        let (name, _) = identity("claude");
        assert_eq!(
            git(dir.path(), &["log", "-1", "--format=%s%n%an"]).trim(),
            format!("step\n{name}")
        );
        let out = commit_with(
            dir.path(),
            Tool::Git,
            missing,
            "again",
            "claude",
            When::Tested,
        )
        .await
        .unwrap();
        assert_eq!(
            out,
            Outcome::Nothing {
                skipped_oversized: vec![]
            }
        );
    }

    #[tokio::test]
    async fn oversized_blobs_are_unstaged_and_the_rest_stays_staged() {
        let dir = repo();
        fs::write(dir.path().join("big file.db"), vec![0u8; 64]).unwrap();
        fs::write(dir.path().join("small.txt"), "s").unwrap();
        fs::write(dir.path().join("base.txt"), vec![1u8; 64]).unwrap();
        git(dir.path(), &["add", "-A"]);
        let skipped = unstage_oversized(dir.path(), 32).await.unwrap();
        assert_eq!(
            skipped,
            vec!["base.txt".to_string(), "big file.db".to_string()]
        );
        assert_eq!(
            git(dir.path(), &["diff", "--cached", "--name-only"]),
            "small.txt\n"
        );
        assert!(has_staged(dir.path()).await);
        assert!(unstage_oversized(dir.path(), 32).await.unwrap().is_empty());
    }

    #[tokio::test]
    async fn a_tree_with_only_oversized_blobs_stages_nothing() {
        let dir = repo();
        fs::write(dir.path().join("big.db"), vec![0u8; 64]).unwrap();
        git(dir.path(), &["add", "-A"]);
        unstage_oversized(dir.path(), 32).await.unwrap();
        assert!(!has_staged(dir.path()).await);
        assert_eq!(git(dir.path(), &["status", "--porcelain"]), "?? big.db\n");
    }

    #[tokio::test]
    async fn a_shipcheck_refusal_commits_nothing_and_leaves_the_tree() {
        let dir = repo();
        let bins = tempfile::tempdir().unwrap();
        let bin = fake_shipcheck(bins.path(), false);
        let head = git(dir.path(), &["rev-parse", "HEAD"]);
        fs::write(dir.path().join("untested.txt"), "x").unwrap();
        let out = commit_with(
            dir.path(),
            Tool::Shipcheck,
            &bin,
            "step",
            "claude",
            When::Tested,
        )
        .await
        .unwrap();
        match out {
            Outcome::Refused { by, reason } => {
                assert_eq!(by, Tool::Shipcheck);
                assert!(reason.contains("shipcheck run"), "{reason}");
            }
            other => panic!("expected a refusal, got {other:?}"),
        }
        assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), head);
        assert_eq!(
            git(dir.path(), &["status", "--porcelain"]),
            "?? untested.txt\n"
        );
    }

    #[tokio::test]
    async fn an_accepting_shipcheck_commits() {
        let dir = repo();
        let bins = tempfile::tempdir().unwrap();
        let bin = fake_shipcheck(bins.path(), true);
        fs::write(dir.path().join("tested.txt"), "x").unwrap();
        let out = commit_with(
            dir.path(),
            Tool::Shipcheck,
            &bin,
            "tested step",
            "claude",
            When::Tested,
        )
        .await
        .unwrap();
        assert_eq!(
            out,
            Outcome::Committed {
                skipped_oversized: vec![]
            }
        );
        assert_eq!(
            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
            "tested step"
        );
    }

    #[tokio::test]
    async fn the_end_of_a_session_commits_untested_work_through_git() {
        let dir = repo();
        let bins = tempfile::tempdir().unwrap();
        let bin = fake_shipcheck(bins.path(), false);
        fs::write(dir.path().join("untested.txt"), "x").unwrap();
        let out = commit_with(
            dir.path(),
            Tool::Shipcheck,
            &bin,
            "final",
            "claude",
            When::Always,
        )
        .await
        .unwrap();
        assert_eq!(
            out,
            Outcome::Committed {
                skipped_oversized: vec![]
            }
        );
        assert_eq!(git(dir.path(), &["status", "--porcelain"]), "");
        assert_eq!(
            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
            "final"
        );
    }

    #[test]
    fn oversized_commit_note_lists_the_paths() {
        assert_eq!(
            oversized_commit_note(&["data/x.sqlite".to_string(), "a.bin".to_string()]),
            "left files over GitHub's size limit out of the commit: data/x.sqlite, a.bin"
        );
    }

    #[test]
    fn parse_raw_diff_reads_blob_paths_and_skips_gitlinks() {
        let out = ":100644 100644 oldsha newsha M\0src/a.rs\0\
:000000 100644 0000000 blobsha A\0big file.db\0\
:100644 160000 oldsha subsha T\0vendor/lib\0";
        assert_eq!(
            parse_raw_diff(out),
            vec![
                ("newsha".to_string(), "src/a.rs".to_string()),
                ("blobsha".to_string(), "big file.db".to_string()),
            ]
        );
    }
}