Skip to main content

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