Skip to main content

orch/engine/git/git_ops/
mod.rs

1//! Git operations — auto-commit, push, PR creation.
2//!
3//! These run after the agent completes to ensure all changes
4//! are committed, pushed, and a PR is created.
5//!
6//! All GitHub API operations use [`GhHttp`] exclusively. The `gh` CLI
7//! is not used as a fallback to ensure consistent behavior across
8//! environments and simplify testing.
9
10mod pr;
11mod push;
12
13use super::commit;
14use crate::github::token;
15use crate::sys::cmd::CommandErrorContext;
16use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19use std::process::Output;
20use std::time::Duration;
21
22pub use pr::create_pr_if_needed;
23pub(crate) use pr::{
24    is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
25};
26pub(crate) use push::{
27    clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
28    sanitize_push_error,
29};
30pub use push::{is_missing_remote_ref_error, is_transient_network_error, push_branch};
31use tokio::process::Command;
32use tokio::time;
33
34/// Format a task ID for display in PR/issue footers.
35///
36/// GitHub task IDs are displayed as `#123` (creates a GH issue hyperlink).
37/// Internal task IDs (`internal:13`) are displayed as `internal-13` (no `#`
38/// to avoid creating a false issue link).
39pub(crate) fn format_task_ref(task_id: &str) -> String {
40    if task_id.starts_with("internal:") {
41        task_id.replace(':', "-")
42    } else {
43        format!("#{task_id}")
44    }
45}
46
47/// Errors that can occur during PR creation.
48#[derive(Debug, thiserror::Error)]
49pub enum PrCreateError {
50    #[error("GitHub API error: {0}")]
51    ApiError(#[from] anyhow::Error),
52}
53
54/// Result type for PR creation operations.
55pub type PrCreateResult<T> = Result<T, PrCreateError>;
56
57pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
58    stash_list.lines().find_map(|line| {
59        let mut parts = line.split_whitespace();
60        match (parts.next(), parts.next()) {
61            (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
62            _ => None,
63        }
64    })
65}
66
67/// Options for [`stash_rebase_restore`].
68pub(crate) struct StashRebaseOpts {
69    /// Abort the rebase (via `git rebase --abort`) and restore the stash when the
70    /// rebase fails.  Set to `false` when the caller intentionally leaves the working
71    /// tree in the in-progress-rebase state so an agent can resolve conflicts.
72    pub abort_on_failure: bool,
73}
74
75impl Default for StashRebaseOpts {
76    fn default() -> Self {
77        Self {
78            abort_on_failure: true,
79        }
80    }
81}
82
83/// Outcome returned by [`stash_rebase_restore`].
84#[derive(Debug)]
85pub(crate) enum RebaseOutcome {
86    /// Rebase completed successfully.
87    Succeeded,
88    /// Rebase failed.  When `abort_on_failure` is true the rebase was aborted and any
89    /// stash was restored; when false the working tree is left in the in-progress-rebase
90    /// state.
91    Failed(String),
92    /// A stash operation failed (push failed, or OID could not be captured); the
93    /// rebase was skipped to preserve the dirty working tree.
94    Skipped(String),
95}
96
97/// Stash uncommitted changes, rebase onto `target_ref`, then restore the stash.
98///
99/// This is the single canonical implementation of the stash → rebase → restore
100/// pattern used in multiple call sites.  Callers are responsible for any
101/// `git fetch` that should precede the rebase.
102///
103/// # Concurrency safety
104/// Git stashes are repo-global; multiple worktrees share the same stash stack.
105/// This function captures the stash OID immediately after pushing and applies by
106/// that exact ref — never via `stash pop` — to avoid restoring a stash that
107/// belongs to a different concurrently-running worktree.
108///
109/// # Stash failure handling
110/// If the stash push fails, or the OID cannot be captured after a successful push,
111/// the rebase is **skipped** and [`RebaseOutcome::Skipped`] is returned.  This
112/// preserves the dirty working tree intact rather than risking data loss.
113pub(crate) async fn stash_rebase_restore(
114    dir: &Path,
115    target_ref: &str,
116    opts: StashRebaseOpts,
117) -> anyhow::Result<RebaseOutcome> {
118    let stash_ref: Option<String> = if commit::has_changes(dir).await {
119        let stash_out = Command::new("git")
120            .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
121            .current_dir(dir)
122            .output_with_context()
123            .await;
124
125        match stash_out {
126            Ok(o) if o.status.success() => {
127                let stdout_preview = String::from_utf8_lossy(&o.stdout)
128                    .lines()
129                    .next()
130                    .unwrap_or("")
131                    .to_string();
132                tracing::debug!(
133                    dir = %dir.display(),
134                    stdout = %stdout_preview,
135                    "git stash push succeeded before rebase"
136                );
137
138                // Capture the OID of the stash object just created so we can
139                // apply it back by that exact ref, regardless of any stashes
140                // that other worktrees may push between now and then.
141                let ref_out = Command::new("git")
142                    .args(["rev-parse", "refs/stash@{0}"])
143                    .current_dir(dir)
144                    .output_with_context()
145                    .await;
146                let stash_hash = ref_out
147                    .ok()
148                    .filter(|o| o.status.success())
149                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
150                    .filter(|s| !s.is_empty());
151
152                if stash_hash.is_none() {
153                    // Stash was created but we can't track its ref.
154                    // Pop immediately to avoid orphaning the changes, then skip.
155                    tracing::warn!(
156                        dir = %dir.display(),
157                        "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
158                    );
159                    let _ = Command::new("git")
160                        .args(["stash", "pop"])
161                        .current_dir(dir)
162                        .output_with_context()
163                        .await;
164                    return Ok(RebaseOutcome::Skipped(
165                        "stash OID capture failed".to_string(),
166                    ));
167                }
168                stash_hash
169            }
170            Ok(o) => {
171                let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
172                tracing::warn!(
173                    dir = %dir.display(),
174                    code = ?o.status.code(),
175                    stderr = %stderr,
176                    "git stash push failed — skipping rebase to preserve dirty state"
177                );
178                return Ok(RebaseOutcome::Skipped(format!(
179                    "stash push failed: {stderr}"
180                )));
181            }
182            Err(e) => {
183                tracing::warn!(
184                    dir = %dir.display(),
185                    error = %e,
186                    "failed to run git stash push — skipping rebase to preserve dirty state"
187                );
188                return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
189            }
190        }
191    } else {
192        None
193    };
194
195    let output = git()
196        .await
197        .args(["rebase", target_ref])
198        .current_dir(dir)
199        .output_with_context()
200        .await;
201
202    match output {
203        Ok(o) if o.status.success() => {
204            tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
205            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
206            Ok(RebaseOutcome::Succeeded)
207        }
208        Ok(o) => {
209            let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
210            tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
211            if opts.abort_on_failure {
212                let abort = Command::new("git")
213                    .args(["rebase", "--abort"])
214                    .current_dir(dir)
215                    .output_with_context()
216                    .await;
217                match abort {
218                    Err(e) => {
219                        tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
220                    }
221                    Ok(o) if !o.status.success() => {
222                        let stderr = String::from_utf8_lossy(&o.stderr);
223                        tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
224                    }
225                    _ => {}
226                }
227            }
228            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
229            Ok(RebaseOutcome::Failed(stderr))
230        }
231        Err(e) => {
232            if opts.abort_on_failure {
233                let abort = Command::new("git")
234                    .args(["rebase", "--abort"])
235                    .current_dir(dir)
236                    .output_with_context()
237                    .await;
238                match abort {
239                    Err(e) => {
240                        tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
241                    }
242                    Ok(o) if !o.status.success() => {
243                        let stderr = String::from_utf8_lossy(&o.stderr);
244                        tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
245                    }
246                    _ => {}
247                }
248            }
249            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
250            Err(e)
251        }
252    }
253}
254
255/// Apply a stash entry by its OID and drop it from the stack on success.
256///
257/// On failure the entry is preserved so it can be recovered manually.
258async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
259    let Some(stash_hash) = stash_hash else {
260        return;
261    };
262
263    let apply = Command::new("git")
264        .args(["stash", "apply", stash_hash])
265        .current_dir(dir)
266        .output_with_context()
267        .await;
268    if apply.is_ok_and(|o| o.status.success()) {
269        let list = Command::new("git")
270            .args(["stash", "list", "--format=%H %gd"])
271            .current_dir(dir)
272            .output_with_context()
273            .await;
274        if let Ok(list_out) = list
275            && list_out.status.success()
276        {
277            let list_str = String::from_utf8_lossy(&list_out.stdout);
278            if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
279                match Command::new("git")
280                    .args(["stash", "drop", &stash_ref])
281                    .current_dir(dir)
282                    .output_with_context()
283                    .await
284                {
285                    Ok(drop_out) if !drop_out.status.success() => {
286                        let stderr = String::from_utf8_lossy(&drop_out.stderr);
287                        tracing::warn!(
288                            dir = %dir.display(),
289                            stash_ref = %stash_ref,
290                            err = %stderr,
291                            "stash drop failed after apply — entry may remain on stack"
292                        );
293                    }
294                    Err(e) => {
295                        tracing::warn!(
296                            dir = %dir.display(),
297                            stash_ref = %stash_ref,
298                            error = %e,
299                            "stash drop command failed after apply — entry may remain on stack"
300                        );
301                    }
302                    _ => {}
303                }
304            } else {
305                tracing::warn!(
306                    dir = %dir.display(),
307                    stash = %stash_hash,
308                    "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
309                );
310            }
311        }
312    } else {
313        tracing::warn!(
314            dir = %dir.display(),
315            stash = %stash_hash,
316            "stash apply failed after rebase — stash preserved for manual recovery"
317        );
318    }
319}
320
321/// Commit what the agent left, with the tool the repository uses (see `commit`).
322pub async fn auto_commit(
323    dir: &Path,
324    task_id: &str,
325    title: &str,
326    agent: &str,
327    attempt: u32,
328    when: commit::When,
329) -> anyhow::Result<bool> {
330    if !commit::has_changes(dir).await {
331        return Ok(false);
332    }
333
334    tracing::info!(task_id, "auto-committing uncommitted changes");
335    let task_ref = format_task_ref(task_id);
336    let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
337    match commit::commit_all(dir, &message, agent, when).await? {
338        commit::Outcome::Committed => {
339            tracing::info!(task_id, "auto-commit succeeded");
340            Ok(true)
341        }
342        commit::Outcome::Nothing => Ok(false),
343        commit::Outcome::Refused {
344            by: commit::Tool::Git,
345            reason,
346        } => {
347            tracing::warn!(task_id, err = %reason, "git commit failed");
348            Ok(false)
349        }
350        commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
351    }
352}
353
354/// Maximum number of commits to replay during a rebase.
355///
356/// If a branch has diverged so far from the default branch that it would
357/// require replaying more than this many commits, we skip the rebase entirely.
358/// This prevents degenerate cases (e.g. a branch forked from the very first
359/// commit that now sits 300+ commits behind main) from producing hundreds of
360/// add/add conflicts that block the agent and leave the worktree unusable.
361const MAX_REBASE_COMMITS: usize = 50;
362
363/// Rebase the current branch on top of `origin/{branch}`.
364///
365/// Used for push-failure recovery: when another agent has pushed to the same
366/// branch, we fetch the latest remote state and rebase local commits on top.
367/// Returns `Ok(true)` if rebase succeeded, `Ok(false)` if there was nothing to
368/// rebase, and `Err` if rebase failed (conflicts).
369///
370/// Similar to `rebase_on_default` but targets the feature branch instead of
371/// the default branch, and is used after push failures rather than at startup.
372pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
373    let origin_branch = format!("origin/{branch}");
374
375    // Fetch the remote branch to get latest state.
376    // 2-minute timeout mirrors the push timeout to prevent indefinite stalls.
377    let fetch = time::timeout(
378        Duration::from_secs(120),
379        git()
380            .await
381            .args(["fetch", "origin", branch])
382            .kill_on_drop(true)
383            .current_dir(dir)
384            .output(),
385    )
386    .await
387    .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
388    .and_then(|r| r.map_err(Into::into));
389
390    match fetch {
391        Ok(o) if o.status.success() => {}
392        Ok(o) => {
393            let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
394            anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
395        }
396        Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
397    }
398
399    // Check if there are local commits to rebase.
400    let count_output = Command::new("git")
401        .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
402        .current_dir(dir)
403        .output_with_context()
404        .await;
405
406    let commit_count: usize = match count_output {
407        Ok(o) if o.status.success() => {
408            let raw = String::from_utf8_lossy(&o.stdout);
409            raw.trim().parse().map_err(|e| {
410                anyhow::anyhow!(
411                    "failed to parse commit count from git rev-list output {:?}: {e}",
412                    raw.trim()
413                )
414            })?
415        }
416        Ok(o) => {
417            let stderr = String::from_utf8_lossy(&o.stderr);
418            anyhow::bail!("git rev-list --count failed: {stderr}");
419        }
420        Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
421    };
422
423    if commit_count == 0 {
424        // No local commits to rebase — nothing to do.
425        return Ok(false);
426    }
427
428    if commit_count > MAX_REBASE_COMMITS {
429        anyhow::bail!(
430            "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
431        );
432    }
433
434    tracing::info!(
435        branch = branch,
436        commit_count,
437        "rebasing local commits on origin/{branch}"
438    );
439
440    match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
441        RebaseOutcome::Succeeded => Ok(true),
442        RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
443        RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
444    }
445}
446
447/// Rebase the current branch on the default branch.
448///
449/// Run before the agent starts to ensure the worktree has the latest code.
450/// Fetches both the default branch and the current branch so agents never
451/// need to run `git fetch` themselves (important for sandboxed agents like
452/// codex whose workspace-write sandbox blocks writes outside the worktree).
453/// Non-fatal: if rebase fails (conflicts), the agent may still be able to work.
454pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
455    // auto_merge leaves a conflicted rebase in place for the agent, aborting it here would undo that
456    if rebase_in_progress(dir).await {
457        tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
458        return;
459    }
460
461    // A later force push leases this tip, so fetching someone else's commits cannot permit replacing them
462    let branch = get_current_branch(dir).await;
463    record_push_lease(dir, &branch, default_branch).await;
464
465    // Fetch current branch (for retries with existing remote commits)
466    // and default branch (for rebase) in one call.
467    let _ = git()
468        .await
469        .args(["fetch", "origin"])
470        .current_dir(dir)
471        .output_with_context()
472        .await;
473
474    // Count commits that would be replayed.  If the branch diverged too far
475    // back we skip the rebase: replaying hundreds of historical commits produces
476    // massive add/add conflicts (the branch adds files that main already has)
477    // and leaves the worktree stuck.
478    let commit_count = Command::new("git")
479        .args([
480            "rev-list",
481            "--count",
482            &format!("origin/{default_branch}..HEAD"),
483        ])
484        .current_dir(dir)
485        .output_with_context()
486        .await
487        .ok()
488        .and_then(|o| {
489            String::from_utf8_lossy(&o.stdout)
490                .trim()
491                .parse::<usize>()
492                .ok()
493        })
494        .unwrap_or(0);
495
496    if commit_count > MAX_REBASE_COMMITS {
497        tracing::warn!(
498            default_branch,
499            commit_count,
500            max = MAX_REBASE_COMMITS,
501            "skipping rebase: branch has too many commits to replay safely"
502        );
503        return;
504    }
505
506    match stash_rebase_restore(
507        dir,
508        &format!("origin/{default_branch}"),
509        StashRebaseOpts::default(),
510    )
511    .await
512    {
513        Ok(RebaseOutcome::Succeeded) => {
514            tracing::debug!(default_branch, "rebased worktree on default branch");
515        }
516        Ok(RebaseOutcome::Failed(e)) => {
517            tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
518        }
519        Ok(RebaseOutcome::Skipped(reason)) => {
520            tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
521        }
522        Err(e) => tracing::warn!(err = %e, "rebase error"),
523    }
524}
525
526pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
527    for name in ["rebase-merge", "rebase-apply"] {
528        let out = Command::new("git")
529            .args(["rev-parse", "--git-path", name])
530            .current_dir(dir)
531            .output_with_context()
532            .await;
533        if let Ok(o) = out {
534            let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
535            if !p.is_empty() && dir.join(p).exists() {
536                return true;
537            }
538        }
539    }
540    false
541}
542
543/// Credentialed git command whose stdout and stderr are sanitized when read
544pub(crate) struct GitCommand {
545    inner: Command,
546}
547
548impl GitCommand {
549    pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
550        self.inner.arg(arg);
551        self
552    }
553
554    pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
555    where
556        I: IntoIterator<Item = S>,
557        S: AsRef<OsStr>,
558    {
559        self.inner.args(args);
560        self
561    }
562
563    pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
564        self.inner.current_dir(dir);
565        self
566    }
567
568    pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
569    where
570        K: AsRef<OsStr>,
571        V: AsRef<OsStr>,
572    {
573        self.inner.env(key, val);
574        self
575    }
576
577    pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
578        self.inner.kill_on_drop(kill);
579        self
580    }
581
582    pub(crate) async fn output(&mut self) -> io::Result<Output> {
583        self.inner.output().await.map(sanitize_git_output)
584    }
585
586    pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
587        self.inner
588            .output_with_context()
589            .await
590            .map(sanitize_git_output)
591    }
592}
593
594/// A `git` command for every call orch makes: GitHub over HTTPS with the gh token, never SSH,
595/// and no commit or tag signing, whatever the owner's git config says
596pub(crate) async fn git() -> GitCommand {
597    let mut cmd = Command::new("git");
598    cmd.envs(build_git_auth_env().await).kill_on_drop(true);
599    GitCommand { inner: cmd }
600}
601
602/// Build git config environment variables that inject GitHub token credentials.
603///
604/// This handles two scenarios:
605/// - **SSH remotes** (`git@github.com:user/repo.git`): rewritten to
606///   `https://x-access-token:TOKEN@github.com/…` via `insteadOf`.
607/// - **HTTPS remotes** (`https://github.com/user/repo.git`): rewritten to
608///   `https://x-access-token:TOKEN@github.com/…` via a second `insteadOf`.
609///
610/// When no token is available, falls back to the legacy SSH→HTTPS conversion
611/// without credentials (works for repos that use credential helpers or SSH keys).
612///
613/// Returns a `Vec<(String, String)>` of environment variable key-value pairs.
614/// These are NOT visible in the process list (`ps`), unlike `-c` args.
615///
616/// Git environment variables:
617/// - `GIT_CONFIG_COUNT` — number of config entries
618/// - `GIT_CONFIG_KEY_N` — config key for entry N
619/// - `GIT_CONFIG_VALUE_N` — config value for entry N
620///
621/// Signing is switched off too, `commit.gpgsign=false` and `tag.gpgsign=false`
622pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
623    let token = token::shared().get_token().await.ok().flatten();
624    build_git_auth_env_for_token(token)
625}
626
627fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
628    let mut config: Vec<(String, String)> = match token {
629        Some(t) if !t.is_empty() => {
630            let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
631            vec![
632                (authed.clone(), "https://github.com/".into()),
633                (authed, "git@github.com:".into()),
634            ]
635        }
636        _ => vec![(
637            "url.https://github.com/.insteadOf".into(),
638            "git@github.com:".into(),
639        )],
640    };
641    // orch's git never signs, a signing key would ask the owner for a passphrase or a touch
642    config.push(("commit.gpgsign".into(), "false".into()));
643    config.push(("tag.gpgsign".into(), "false".into()));
644
645    let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
646    for (n, (key, value)) in config.into_iter().enumerate() {
647        env.push((format!("GIT_CONFIG_KEY_{n}"), key));
648        env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
649    }
650    env
651}
652
653/// Returns `true` if the push error indicates that the GitHub token lacks the
654/// `workflow` OAuth scope, which is required to push changes to
655/// `.github/workflows/` files.
656///
657/// GitHub rejects pushes with: "refusing to allow an OAuth App to create or
658/// update workflow `…` without `workflow` scope"
659pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
660    stderr.contains("without `workflow` scope")
661        || stderr.contains("without 'workflow' scope")
662        || (stderr.contains("refusing to allow")
663            && stderr.contains("workflow")
664            && stderr.contains("scope"))
665}
666
667/// Remove `.github/workflows/` files from committed changes and amend the
668/// commits so the branch can be pushed without the `workflow` OAuth scope.
669///
670/// Strategy: find all commits ahead of `origin/{default_branch}`, identify
671/// which ones touch `.github/workflows/`, and rewrite them to exclude those
672/// files. Uses `git filter-branch`-style approach via interactive rebase
673/// with `exec` steps.
674///
675/// Returns `Ok(true)` if workflow files were removed and commits rewritten,
676/// `Ok(false)` if no workflow files were found in the commits.
677async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
678    // Find workflow files in commits ahead of the default branch
679    let output = Command::new("git")
680        .args([
681            "diff",
682            "--name-only",
683            &format!("origin/{default_branch}...HEAD"),
684            "--",
685            ".github/workflows/",
686        ])
687        .current_dir(dir)
688        .output_with_context()
689        .await?;
690
691    let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
692        .lines()
693        .filter(|l| !l.is_empty())
694        .map(ToString::to_string)
695        .collect();
696
697    if workflow_files.is_empty() {
698        return Ok(false);
699    }
700
701    tracing::info!(
702        files = ?workflow_files,
703        "stripping workflow files from commits to bypass missing workflow scope"
704    );
705
706    // Remove workflow files from the index and amend each commit.
707    // We use a soft reset → remove files → re-commit approach for simplicity.
708    //
709    // Count commits ahead of default branch
710    let count_output = Command::new("git")
711        .args([
712            "rev-list",
713            "--count",
714            &format!("origin/{default_branch}..HEAD"),
715        ])
716        .current_dir(dir)
717        .output_with_context()
718        .await?;
719
720    let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
721        .trim()
722        .parse()
723        .unwrap_or(0);
724
725    if commit_count == 0 {
726        return Ok(false);
727    }
728
729    // Save the commit messages before resetting.
730    // Use a null byte as the record prefix — null bytes cannot appear in git commit
731    // messages, so this separator is unambiguous (unlike a string like ---COMMIT_SEP---
732    // which an agent could write into a commit body, corrupting the parse).
733    let log_output = Command::new("git")
734        .args([
735            "log",
736            "--format=%x00%H%n%B",
737            &format!("origin/{default_branch}..HEAD"),
738        ])
739        .current_dir(dir)
740        .output_with_context()
741        .await?;
742    let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
743
744    // Parse commits in reverse order (oldest first).
745    // Each record starts with \0 (from %x00 in the format), so split on \0 and
746    // discard any leading empty fragment before the first record.
747    let commits: Vec<(String, String)> = log_text
748        .split('\0')
749        .filter(|s| !s.trim().is_empty())
750        .map(|block| {
751            let block = block.trim();
752            let first_nl = block.find('\n').unwrap_or(block.len());
753            let hash = block[..first_nl].to_string();
754            let msg = block[first_nl..].trim().to_string();
755            (hash, msg)
756        })
757        .collect::<Vec<_>>()
758        .into_iter()
759        .rev()
760        .collect();
761
762    if commits.is_empty() {
763        return Ok(false);
764    }
765
766    // Soft reset to the base (origin/default_branch)
767    let reset = Command::new("git")
768        .args(["reset", "--soft", &format!("origin/{default_branch}")])
769        .current_dir(dir)
770        .output_with_context()
771        .await?;
772
773    if !reset.status.success() {
774        let stderr = String::from_utf8_lossy(&reset.stderr);
775        anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
776    }
777
778    // Remove workflow files from the index
779    let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
780    let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
781    rm_args.extend(file_refs);
782
783    let rm = Command::new("git")
784        .args(&rm_args)
785        .current_dir(dir)
786        .output_with_context()
787        .await?;
788
789    if !rm.status.success() {
790        let stderr = String::from_utf8_lossy(&rm.stderr);
791        tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
792    }
793
794    // Re-commit all remaining changes as a single commit preserving the first message.
795    // This squashes multiple commits but preserves the work minus workflow files.
796    let has_staged = Command::new("git")
797        .args(["diff", "--cached", "--quiet"])
798        .current_dir(dir)
799        .status()
800        .await
801        .is_ok_and(|s| !s.success());
802
803    if !has_staged {
804        tracing::warn!(
805            "after removing workflow files, no staged changes remain — \
806             the only changes were workflow files"
807        );
808        // Reset back to where we were — nothing to push
809        // Use the original HEAD from the first (newest) commit
810        if let Some((hash, _)) = commits.last() {
811            let _ = Command::new("git")
812                .args(["reset", "--soft", hash])
813                .current_dir(dir)
814                .output_with_context()
815                .await;
816        }
817        return Ok(false);
818    }
819
820    // Use the first commit's message (oldest commit)
821    let commit_msg = if commits.len() == 1 {
822        commits[0].1.clone()
823    } else {
824        // Combine messages when squashing
825        let mut combined = String::new();
826        for (i, (_, msg)) in commits.iter().enumerate() {
827            if i > 0 {
828                combined.push_str("\n\n");
829            }
830            combined.push_str(msg);
831        }
832        combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
833        combined
834    };
835
836    // A repair of commits already made, so it lands through git even where shipcheck commits
837    let commit = commit::git_commit(dir, &commit_msg, "orchestrator").await?;
838
839    if !commit.status.success() {
840        let stderr = String::from_utf8_lossy(&commit.stderr);
841        // Recovery: restore the original commits so the worktree isn't stuck
842        if let Some((original_head, _)) = commits.last() {
843            let _ = Command::new("git")
844                .args(["reset", "--hard", original_head])
845                .current_dir(dir)
846                .output_with_context()
847                .await;
848        }
849        anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
850    }
851
852    tracing::info!(
853        stripped_files = ?workflow_files,
854        original_commits = commit_count,
855        "successfully stripped workflow files from commits"
856    );
857
858    Ok(true)
859}
860
861/// Get the current branch name.
862pub(crate) async fn get_current_branch(dir: &Path) -> String {
863    let output = Command::new("git")
864        .args(["branch", "--show-current"])
865        .current_dir(dir)
866        .output_with_context()
867        .await;
868
869    match output {
870        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
871        _ => String::new(),
872    }
873}
874
875/// Check if there are unpushed commits.
876/// Returns `(remote_exists, has_unpushed_commits)`.
877///
878/// - `remote_exists` — whether `origin/<branch>` is known to the local repo.
879/// - `has_unpushed_commits` — whether there are local commits not yet on the
880///   remote.  When the remote branch doesn't exist the comparison is against
881///   `origin/<default_branch>` so we can still detect new work.
882async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
883    // Check if remote tracking branch exists
884    let remote_exists = Command::new("git")
885        .args(["rev-parse", &format!("origin/{branch}")])
886        .current_dir(dir)
887        .output_with_context()
888        .await
889        .is_ok_and(|o| o.status.success());
890
891    let compare_ref = if remote_exists {
892        format!("origin/{branch}..{branch}")
893    } else {
894        // Compare the named branch, not HEAD: a protected checkout still pushes the task branch
895        format!("origin/{default_branch}..{branch}")
896    };
897
898    tracing::debug!(
899        branch,
900        compare_ref,
901        remote_exists,
902        "checking unpushed commits"
903    );
904
905    let output = Command::new("git")
906        .args(["log", &compare_ref, "--oneline"])
907        .current_dir(dir)
908        .output_with_context()
909        .await;
910
911    let has_unpushed = match output {
912        Ok(o) if o.status.success() => {
913            let out = String::from_utf8_lossy(&o.stdout);
914            let has = !out.trim().is_empty();
915            tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
916            has
917        }
918        _ => {
919            tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
920            // If we can't determine, assume there ARE commits to push
921            // (better to attempt push and let it fail than silently skip)
922            true
923        }
924    };
925
926    (remote_exists, has_unpushed)
927}
928
929#[cfg(test)]
930mod tests;