Skip to main content

orch/engine/git/
commit.rs

1//! How orch commits. A repository that uses shipcheck commits through `shipcheck commit`, which
2//! commits only a tree its checks passed, any other repository through git
3
4use super::shipcheck::Shipcheck;
5use std::path::Path;
6use std::process::{Output, Stdio};
7
8use tokio::io::AsyncWriteExt;
9use tokio::process::Command;
10
11use crate::config;
12use crate::sys::cmd::CommandErrorContext;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum Tool {
16    Git,
17    Shipcheck,
18}
19
20impl Tool {
21    /// The same rule the agent prompt follows: shipcheck when the repository opts in and the
22    /// installed shipcheck has `commit`, git otherwise
23    pub async fn detect(dir: &Path) -> Self {
24        // Without the file there is nothing to ask, and asking runs `shipcheck --help`
25        if !dir.join("shipcheck.toml").exists() {
26            return Tool::Git;
27        }
28
29        match Shipcheck::detect(dir).await {
30            Shipcheck::Available => Tool::Shipcheck,
31            Shipcheck::Absent | Shipcheck::NotInstalled | Shipcheck::Outdated => Tool::Git,
32        }
33    }
34}
35
36/// Whether a commit may skip shipcheck's gate
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum When {
39    /// Only a tree shipcheck already passed, for steps during a session
40    Tested,
41    /// Commit anyway, for the end of a session, so the agent's work is never left uncommitted.
42    /// shipcheck's hooks run the checks when the branch is pushed
43    Always,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub enum Outcome {
48    Committed {
49        /// Staged blobs left out because they are over GitHub's 100 MiB limit
50        skipped_oversized: Vec<String>,
51    },
52    Nothing {
53        skipped_oversized: Vec<String>,
54    },
55    /// The commit did not happen, and the tree is as it was. shipcheck refuses a tree without a passing run
56    Refused {
57        by: Tool,
58        reason: String,
59    },
60}
61
62/// GitHub refuses a push that holds a blob over 100 MiB (GH001)
63pub(crate) const MAX_BLOB_BYTES: u64 = 100 * 1024 * 1024;
64
65/// Last-error text when `commit_all` leaves blobs over GitHub's size limit unstaged
66pub(crate) fn oversized_commit_note(paths: &[String]) -> String {
67    format!(
68        "left files over GitHub's size limit out of the commit: {}",
69        paths.join(", ")
70    )
71}
72
73fn identity(agent: &str) -> (String, String) {
74    let name = config::get("git.name").unwrap_or_else(|_| format!("{agent}[bot]"));
75    let email = config::get("git.email")
76        .unwrap_or_else(|_| format!("{agent}[bot]@users.noreply.github.com"));
77    (name, email)
78}
79
80/// The git commit behind every orch commit: the agent's identity, and never the operator's signing agent
81pub async fn git_commit(dir: &Path, message: &str, agent: &str) -> anyhow::Result<Output> {
82    let (name, email) = identity(agent);
83    Command::new("git")
84        .args(["-c", "commit.gpgsign=false", "commit", "-m", message])
85        .env("GIT_AUTHOR_NAME", &name)
86        .env("GIT_COMMITTER_NAME", &name)
87        .env("GIT_AUTHOR_EMAIL", &email)
88        .env("GIT_COMMITTER_EMAIL", &email)
89        .current_dir(dir)
90        .output_with_context()
91        .await
92}
93
94async fn shipcheck_commit(
95    dir: &Path,
96    bin: &Path,
97    message: &str,
98    agent: &str,
99) -> anyhow::Result<Outcome> {
100    let (name, email) = identity(agent);
101    let out = Command::new(bin)
102        .args(["commit", "-m", message])
103        .env("GIT_AUTHOR_NAME", &name)
104        .env("GIT_COMMITTER_NAME", &name)
105        .env("GIT_AUTHOR_EMAIL", &email)
106        .env("GIT_COMMITTER_EMAIL", &email)
107        .current_dir(dir)
108        .output_with_context()
109        .await?;
110    if out.status.success() {
111        return Ok(Outcome::Committed {
112            skipped_oversized: Vec::new(),
113        });
114    }
115
116    let why = String::from_utf8_lossy(&out.stderr).trim().to_string();
117    Ok(Outcome::Refused {
118        by: Tool::Shipcheck,
119        reason: format!("shipcheck commit refused, run `shipcheck run` first: {why}"),
120    })
121}
122
123/// Commit every change in `dir` with the tool the repository uses
124pub async fn commit_all(
125    dir: &Path,
126    message: &str,
127    agent: &str,
128    when: When,
129) -> anyhow::Result<Outcome> {
130    let tool = Tool::detect(dir).await;
131    let bin = which::which("shipcheck").unwrap_or_else(|_| "shipcheck".into());
132    commit_with(dir, tool, &bin, message, agent, when).await
133}
134
135async fn commit_with(
136    dir: &Path,
137    tool: Tool,
138    shipcheck: &Path,
139    message: &str,
140    agent: &str,
141    when: When,
142) -> anyhow::Result<Outcome> {
143    if !has_changes(dir).await {
144        return Ok(Outcome::Nothing {
145            skipped_oversized: Vec::new(),
146        });
147    }
148
149    if tool == Tool::Shipcheck {
150        let outcome = shipcheck_commit(dir, shipcheck, message, agent).await?;
151        let Outcome::Refused { reason, .. } = &outcome else {
152            return Ok(outcome);
153        };
154        if when == When::Tested {
155            return Ok(outcome);
156        }
157
158        tracing::info!(reason = %reason, "committing untested work through git at the end of the session");
159    }
160
161    let add = Command::new("git")
162        .args(["add", "-A"])
163        .current_dir(dir)
164        .output_with_context()
165        .await?;
166    if !add.status.success() {
167        tracing::warn!("git add -A failed");
168        return Ok(Outcome::Refused {
169            by: Tool::Git,
170            reason: String::from_utf8_lossy(&add.stderr).trim().to_string(),
171        });
172    }
173
174    let skipped_oversized = unstage_oversized(dir, MAX_BLOB_BYTES).await?;
175    if !skipped_oversized.is_empty() {
176        tracing::warn!(
177            files = ?skipped_oversized,
178            "left files over GitHub's size limit out of the commit"
179        );
180        if !has_staged(dir).await {
181            return Ok(Outcome::Nothing { skipped_oversized });
182        }
183    }
184
185    let out = git_commit(dir, message, agent).await?;
186    if out.status.success() {
187        return Ok(Outcome::Committed { skipped_oversized });
188    }
189
190    let reason = String::from_utf8_lossy(&out.stderr).trim().to_string();
191    unstage(dir, &reason).await?;
192    Ok(Outcome::Refused {
193        by: Tool::Git,
194        reason,
195    })
196}
197
198/// Unstage every staged blob larger than `limit` and return its path. The staged size is what
199/// gets pushed, so an LFS pointer stays staged however large the file on disk is
200async fn unstage_oversized(dir: &Path, limit: u64) -> anyhow::Result<Vec<String>> {
201    let raw = Command::new("git")
202        .args([
203            "diff",
204            "--cached",
205            "--raw",
206            "--full-index",
207            "--no-renames",
208            "-z",
209            "--diff-filter=AMT",
210        ])
211        .current_dir(dir)
212        .output_with_context()
213        .await?;
214    if !raw.status.success() {
215        return Ok(Vec::new());
216    }
217
218    let entries = parse_raw_diff(&String::from_utf8_lossy(&raw.stdout));
219    if entries.is_empty() {
220        return Ok(Vec::new());
221    }
222
223    let mut child = Command::new("git")
224        .args(["cat-file", "--batch-check=%(objectsize)"])
225        .current_dir(dir)
226        .stdin(Stdio::piped())
227        .stdout(Stdio::piped())
228        .stderr(Stdio::piped())
229        .kill_on_drop(true)
230        .spawn()?;
231    let mut input = entries
232        .iter()
233        .map(|(sha, _)| sha.as_str())
234        .collect::<Vec<_>>()
235        .join("\n");
236    input.push('\n');
237    {
238        let mut stdin = child
239            .stdin
240            .take()
241            .ok_or_else(|| anyhow::anyhow!("git cat-file stdin closed"))?;
242        stdin.write_all(input.as_bytes()).await?;
243    }
244
245    let sizes = child.wait_with_output().await?;
246    if !sizes.status.success() {
247        anyhow::bail!(
248            "git cat-file failed: {}",
249            String::from_utf8_lossy(&sizes.stderr).trim()
250        );
251    }
252
253    let oversized: Vec<String> = String::from_utf8_lossy(&sizes.stdout)
254        .lines()
255        .zip(&entries)
256        .filter(|(size, _)| size.trim().parse::<u64>().is_ok_and(|n| n > limit))
257        .map(|(_, (_, path))| path.clone())
258        .collect();
259    if oversized.is_empty() {
260        return Ok(oversized);
261    }
262
263    let restore = Command::new("git")
264        .args(["--literal-pathspecs", "restore", "--staged", "--"])
265        .args(&oversized)
266        .current_dir(dir)
267        .output_with_context()
268        .await?;
269    if !restore.status.success() {
270        anyhow::bail!(
271            "failed to unstage files over GitHub's size limit: {}",
272            String::from_utf8_lossy(&restore.stderr).trim()
273        );
274    }
275
276    Ok(oversized)
277}
278
279/// The new blob sha and path of each entry in `git diff --raw -z`, gitlinks left out
280fn parse_raw_diff(out: &str) -> Vec<(String, String)> {
281    let mut fields = out.split('\0');
282    let mut entries = Vec::new();
283    while let (Some(meta), Some(path)) = (fields.next(), fields.next()) {
284        let parts: Vec<&str> = meta.trim_start_matches(':').split(' ').collect();
285        if let [_, mode, _, sha, _] = parts[..]
286            && mode != "160000"
287        {
288            entries.push((sha.to_string(), path.to_string()));
289        }
290    }
291    entries
292}
293
294async fn has_staged(dir: &Path) -> bool {
295    Command::new("git")
296        .args(["diff", "--cached", "--quiet"])
297        .current_dir(dir)
298        .status()
299        .await
300        .is_ok_and(|s| !s.success())
301}
302
303/// Leave a failed commit's files unstaged, so the next check sees them and can retry cleanly
304async fn unstage(dir: &Path, commit_err: &str) -> anyhow::Result<()> {
305    let restore = Command::new("git")
306        .args(["restore", "--staged", "."])
307        .current_dir(dir)
308        .output_with_context()
309        .await;
310    let restore_err = match restore {
311        Ok(o) if o.status.success() => return Ok(()),
312        Ok(o) => String::from_utf8_lossy(&o.stderr).trim().to_string(),
313        Err(e) => e.to_string(),
314    };
315    tracing::warn!(err = %restore_err, "git restore --staged failed, falling back to git reset HEAD -- .");
316    let reset = Command::new("git")
317        .args(["reset", "HEAD", "--", "."])
318        .current_dir(dir)
319        .output_with_context()
320        .await?;
321    if !reset.status.success() {
322        anyhow::bail!(
323            "git commit failed and cleanup failed (git restore --staged + git reset HEAD -- .): commit stderr: {commit_err}; restore: {restore_err}; reset stderr: {}",
324            String::from_utf8_lossy(&reset.stderr).trim()
325        );
326    }
327
328    Ok(())
329}
330
331/// Check if there are uncommitted changes in the working directory.
332pub async fn has_changes(dir: &Path) -> bool {
333    // Check for staged, unstaged, and untracked files
334    let diff = Command::new("git")
335        .args(["diff", "--quiet"])
336        .current_dir(dir)
337        .status()
338        .await;
339
340    let cached = Command::new("git")
341        .args(["diff", "--cached", "--quiet"])
342        .current_dir(dir)
343        .status()
344        .await;
345
346    let untracked = Command::new("git")
347        .args(["ls-files", "--others", "--exclude-standard"])
348        .current_dir(dir)
349        .output_with_context()
350        .await;
351
352    let has_diff = diff.is_ok_and(|s| !s.success());
353    let has_cached = cached.is_ok_and(|s| !s.success());
354    let has_untracked =
355        untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
356
357    has_diff || has_cached || has_untracked
358}
359
360#[cfg(test)]
361mod tests {
362    use std::fs;
363    use std::fs::Permissions;
364    use std::os::unix::fs::PermissionsExt;
365    use std::path::PathBuf;
366    use std::process;
367
368    use super::*;
369
370    fn git(dir: &Path, args: &[&str]) -> String {
371        let out = process::Command::new("git")
372            .args([
373                "-c",
374                "user.name=T",
375                "-c",
376                "user.email=t@t",
377                "-c",
378                "commit.gpgsign=false",
379            ])
380            .args(args)
381            .current_dir(dir)
382            .output()
383            .unwrap();
384        assert!(
385            out.status.success(),
386            "git {args:?}: {}",
387            String::from_utf8_lossy(&out.stderr)
388        );
389        String::from_utf8_lossy(&out.stdout).to_string()
390    }
391
392    fn repo() -> tempfile::TempDir {
393        let dir = tempfile::tempdir().unwrap();
394        git(dir.path(), &["init", "-b", "main"]);
395        fs::write(dir.path().join("base.txt"), "base").unwrap();
396        git(dir.path(), &["add", "base.txt"]);
397        git(dir.path(), &["commit", "-m", "base"]);
398        dir
399    }
400
401    /// A stand-in for shipcheck: `ok` commits like `shipcheck commit`, anything else refuses
402    fn fake_shipcheck(dir: &Path, ok: bool) -> PathBuf {
403        let bin = dir.join("shipcheck");
404        let body = if ok {
405            "#!/bin/sh\ngit add -A && git -c commit.gpgsign=false commit -q -m \"$3\"\n"
406        } else {
407            "#!/bin/sh\necho 'no passing result for this tree' >&2\nexit 1\n"
408        };
409        fs::write(&bin, body).unwrap();
410        fs::set_permissions(&bin, Permissions::from_mode(0o755)).unwrap();
411        bin
412    }
413
414    #[tokio::test]
415    async fn git_commits_every_change_and_reports_nothing_on_a_clean_tree() {
416        let dir = repo();
417        let missing = Path::new("/nonexistent/shipcheck");
418        fs::write(dir.path().join("a.txt"), "a").unwrap();
419        let out = commit_with(
420            dir.path(),
421            Tool::Git,
422            missing,
423            "step",
424            "claude",
425            When::Tested,
426        )
427        .await
428        .unwrap();
429        assert_eq!(
430            out,
431            Outcome::Committed {
432                skipped_oversized: vec![]
433            }
434        );
435        let (name, _) = identity("claude");
436        assert_eq!(
437            git(dir.path(), &["log", "-1", "--format=%s%n%an"]).trim(),
438            format!("step\n{name}")
439        );
440        let out = commit_with(
441            dir.path(),
442            Tool::Git,
443            missing,
444            "again",
445            "claude",
446            When::Tested,
447        )
448        .await
449        .unwrap();
450        assert_eq!(
451            out,
452            Outcome::Nothing {
453                skipped_oversized: vec![]
454            }
455        );
456    }
457
458    #[tokio::test]
459    async fn oversized_blobs_are_unstaged_and_the_rest_stays_staged() {
460        let dir = repo();
461        fs::write(dir.path().join("big file.db"), vec![0u8; 64]).unwrap();
462        fs::write(dir.path().join("small.txt"), "s").unwrap();
463        fs::write(dir.path().join("base.txt"), vec![1u8; 64]).unwrap();
464        git(dir.path(), &["add", "-A"]);
465        let skipped = unstage_oversized(dir.path(), 32).await.unwrap();
466        assert_eq!(
467            skipped,
468            vec!["base.txt".to_string(), "big file.db".to_string()]
469        );
470        assert_eq!(
471            git(dir.path(), &["diff", "--cached", "--name-only"]),
472            "small.txt\n"
473        );
474        assert!(has_staged(dir.path()).await);
475        assert!(unstage_oversized(dir.path(), 32).await.unwrap().is_empty());
476    }
477
478    #[tokio::test]
479    async fn a_tree_with_only_oversized_blobs_stages_nothing() {
480        let dir = repo();
481        fs::write(dir.path().join("big.db"), vec![0u8; 64]).unwrap();
482        git(dir.path(), &["add", "-A"]);
483        unstage_oversized(dir.path(), 32).await.unwrap();
484        assert!(!has_staged(dir.path()).await);
485        assert_eq!(git(dir.path(), &["status", "--porcelain"]), "?? big.db\n");
486    }
487
488    #[tokio::test]
489    async fn a_shipcheck_refusal_commits_nothing_and_leaves_the_tree() {
490        let dir = repo();
491        let bins = tempfile::tempdir().unwrap();
492        let bin = fake_shipcheck(bins.path(), false);
493        let head = git(dir.path(), &["rev-parse", "HEAD"]);
494        fs::write(dir.path().join("untested.txt"), "x").unwrap();
495        let out = commit_with(
496            dir.path(),
497            Tool::Shipcheck,
498            &bin,
499            "step",
500            "claude",
501            When::Tested,
502        )
503        .await
504        .unwrap();
505        match out {
506            Outcome::Refused { by, reason } => {
507                assert_eq!(by, Tool::Shipcheck);
508                assert!(reason.contains("shipcheck run"), "{reason}");
509            }
510            other => panic!("expected a refusal, got {other:?}"),
511        }
512        assert_eq!(git(dir.path(), &["rev-parse", "HEAD"]), head);
513        assert_eq!(
514            git(dir.path(), &["status", "--porcelain"]),
515            "?? untested.txt\n"
516        );
517    }
518
519    #[tokio::test]
520    async fn an_accepting_shipcheck_commits() {
521        let dir = repo();
522        let bins = tempfile::tempdir().unwrap();
523        let bin = fake_shipcheck(bins.path(), true);
524        fs::write(dir.path().join("tested.txt"), "x").unwrap();
525        let out = commit_with(
526            dir.path(),
527            Tool::Shipcheck,
528            &bin,
529            "tested step",
530            "claude",
531            When::Tested,
532        )
533        .await
534        .unwrap();
535        assert_eq!(
536            out,
537            Outcome::Committed {
538                skipped_oversized: vec![]
539            }
540        );
541        assert_eq!(
542            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
543            "tested step"
544        );
545    }
546
547    #[tokio::test]
548    async fn the_end_of_a_session_commits_untested_work_through_git() {
549        let dir = repo();
550        let bins = tempfile::tempdir().unwrap();
551        let bin = fake_shipcheck(bins.path(), false);
552        fs::write(dir.path().join("untested.txt"), "x").unwrap();
553        let out = commit_with(
554            dir.path(),
555            Tool::Shipcheck,
556            &bin,
557            "final",
558            "claude",
559            When::Always,
560        )
561        .await
562        .unwrap();
563        assert_eq!(
564            out,
565            Outcome::Committed {
566                skipped_oversized: vec![]
567            }
568        );
569        assert_eq!(git(dir.path(), &["status", "--porcelain"]), "");
570        assert_eq!(
571            git(dir.path(), &["log", "-1", "--format=%s"]).trim(),
572            "final"
573        );
574    }
575
576    #[test]
577    fn oversized_commit_note_lists_the_paths() {
578        assert_eq!(
579            oversized_commit_note(&["data/x.sqlite".to_string(), "a.bin".to_string()]),
580            "left files over GitHub's size limit out of the commit: data/x.sqlite, a.bin"
581        );
582    }
583
584    #[test]
585    fn parse_raw_diff_reads_blob_paths_and_skips_gitlinks() {
586        let out = ":100644 100644 oldsha newsha M\0src/a.rs\0\
587:000000 100644 0000000 blobsha A\0big file.db\0\
588:100644 160000 oldsha subsha T\0vendor/lib\0";
589        assert_eq!(
590            parse_raw_diff(out),
591            vec![
592                ("newsha".to_string(), "src/a.rs".to_string()),
593                ("blobsha".to_string(), "big file.db".to_string()),
594            ]
595        );
596    }
597}