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