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