Skip to main content

orch/engine/runner/
git_ops.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
10use crate::cmd::CommandErrorContext;
11use crate::github::http;
12use crate::github::http::GhHttp;
13use crate::github::token;
14use crate::plan;
15use crate::security;
16use regex::Regex;
17use std::ffi::OsStr;
18use std::fmt::Write as _;
19use std::io;
20use std::path::Path;
21use std::process::Output;
22use std::sync::LazyLock;
23use std::sync::atomic::{AtomicU64, Ordering};
24use std::time::Duration;
25
26use tokio::process::Command;
27use tokio::time;
28
29/// Format a task ID for display in PR/issue footers.
30///
31/// GitHub task IDs are displayed as `#123` (creates a GH issue hyperlink).
32/// Internal task IDs (`internal:13`) are displayed as `internal-13` (no `#`
33/// to avoid creating a false issue link).
34pub(crate) fn format_task_ref(task_id: &str) -> String {
35    if task_id.starts_with("internal:") {
36        task_id.replace(':', "-")
37    } else {
38        format!("#{task_id}")
39    }
40}
41
42/// Errors that can occur during PR creation.
43#[derive(Debug, thiserror::Error)]
44pub enum PrCreateError {
45    #[error("GitHub API error: {0}")]
46    ApiError(#[from] anyhow::Error),
47}
48
49/// Result type for PR creation operations.
50pub type PrCreateResult<T> = Result<T, PrCreateError>;
51
52/// Check if the current branch has any commits ahead of the default branch.
53pub async fn has_commits_ahead(dir: &Path, default_branch: &str) -> bool {
54    let output = Command::new("git")
55        .args([
56            "rev-list",
57            "--count",
58            &format!("origin/{default_branch}..HEAD"),
59        ])
60        .current_dir(dir)
61        .output()
62        .await;
63    match output {
64        Ok(o) if o.status.success() => {
65            let count: u32 = String::from_utf8_lossy(&o.stdout)
66                .trim()
67                .parse()
68                .unwrap_or(0);
69            count > 0
70        }
71        _ => {
72            tracing::debug!(
73                default_branch,
74                "git rev-list failed for compare ref, assuming commits ahead"
75            );
76            // If we can't determine, assume there ARE commits ahead so we
77            // attempt a push (better to try and fail loudly than silently
78            // skip push and lose the PR creation path).
79            true
80        }
81    }
82}
83
84/// Check if there are uncommitted changes in the working directory.
85pub async fn has_changes(dir: &Path) -> bool {
86    // Check for staged, unstaged, and untracked files
87    let diff = Command::new("git")
88        .args(["diff", "--quiet"])
89        .current_dir(dir)
90        .status()
91        .await;
92
93    let cached = Command::new("git")
94        .args(["diff", "--cached", "--quiet"])
95        .current_dir(dir)
96        .status()
97        .await;
98
99    let untracked = Command::new("git")
100        .args(["ls-files", "--others", "--exclude-standard"])
101        .current_dir(dir)
102        .output_with_context()
103        .await;
104
105    let has_diff = diff.is_ok_and(|s| !s.success());
106    let has_cached = cached.is_ok_and(|s| !s.success());
107    let has_untracked =
108        untracked.is_ok_and(|o| !String::from_utf8_lossy(&o.stdout).trim().is_empty());
109
110    has_diff || has_cached || has_untracked
111}
112
113pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
114    stash_list.lines().find_map(|line| {
115        let mut parts = line.split_whitespace();
116        match (parts.next(), parts.next()) {
117            (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
118            _ => None,
119        }
120    })
121}
122
123/// Options for [`stash_rebase_restore`].
124pub(crate) struct StashRebaseOpts {
125    /// Abort the rebase (via `git rebase --abort`) and restore the stash when the
126    /// rebase fails.  Set to `false` when the caller intentionally leaves the working
127    /// tree in the in-progress-rebase state so an agent can resolve conflicts.
128    pub abort_on_failure: bool,
129}
130
131impl Default for StashRebaseOpts {
132    fn default() -> Self {
133        Self {
134            abort_on_failure: true,
135        }
136    }
137}
138
139/// Outcome returned by [`stash_rebase_restore`].
140#[derive(Debug)]
141pub(crate) enum RebaseOutcome {
142    /// Rebase completed successfully.
143    Succeeded,
144    /// Rebase failed.  When `abort_on_failure` is true the rebase was aborted and any
145    /// stash was restored; when false the working tree is left in the in-progress-rebase
146    /// state.
147    Failed(String),
148    /// A stash operation failed (push failed, or OID could not be captured); the
149    /// rebase was skipped to preserve the dirty working tree.
150    Skipped(String),
151}
152
153/// Stash uncommitted changes, rebase onto `target_ref`, then restore the stash.
154///
155/// This is the single canonical implementation of the stash → rebase → restore
156/// pattern used in multiple call sites.  Callers are responsible for any
157/// `git fetch` that should precede the rebase.
158///
159/// # Concurrency safety
160/// Git stashes are repo-global; multiple worktrees share the same stash stack.
161/// This function captures the stash OID immediately after pushing and applies by
162/// that exact ref — never via `stash pop` — to avoid restoring a stash that
163/// belongs to a different concurrently-running worktree.
164///
165/// # Stash failure handling
166/// If the stash push fails, or the OID cannot be captured after a successful push,
167/// the rebase is **skipped** and [`RebaseOutcome::Skipped`] is returned.  This
168/// preserves the dirty working tree intact rather than risking data loss.
169pub(crate) async fn stash_rebase_restore(
170    dir: &Path,
171    target_ref: &str,
172    opts: StashRebaseOpts,
173) -> anyhow::Result<RebaseOutcome> {
174    let stash_ref: Option<String> = if has_changes(dir).await {
175        let stash_out = Command::new("git")
176            .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
177            .current_dir(dir)
178            .output_with_context()
179            .await;
180
181        match stash_out {
182            Ok(o) if o.status.success() => {
183                let stdout_preview = String::from_utf8_lossy(&o.stdout)
184                    .lines()
185                    .next()
186                    .unwrap_or("")
187                    .to_string();
188                tracing::debug!(
189                    dir = %dir.display(),
190                    stdout = %stdout_preview,
191                    "git stash push succeeded before rebase"
192                );
193
194                // Capture the OID of the stash object just created so we can
195                // apply it back by that exact ref, regardless of any stashes
196                // that other worktrees may push between now and then.
197                let ref_out = Command::new("git")
198                    .args(["rev-parse", "refs/stash@{0}"])
199                    .current_dir(dir)
200                    .output_with_context()
201                    .await;
202                let stash_hash = ref_out
203                    .ok()
204                    .filter(|o| o.status.success())
205                    .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
206                    .filter(|s| !s.is_empty());
207
208                if stash_hash.is_none() {
209                    // Stash was created but we can't track its ref.
210                    // Pop immediately to avoid orphaning the changes, then skip.
211                    tracing::warn!(
212                        dir = %dir.display(),
213                        "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
214                    );
215                    let _ = Command::new("git")
216                        .args(["stash", "pop"])
217                        .current_dir(dir)
218                        .output_with_context()
219                        .await;
220                    return Ok(RebaseOutcome::Skipped(
221                        "stash OID capture failed".to_string(),
222                    ));
223                }
224                stash_hash
225            }
226            Ok(o) => {
227                let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
228                tracing::warn!(
229                    dir = %dir.display(),
230                    code = ?o.status.code(),
231                    stderr = %stderr,
232                    "git stash push failed — skipping rebase to preserve dirty state"
233                );
234                return Ok(RebaseOutcome::Skipped(format!(
235                    "stash push failed: {stderr}"
236                )));
237            }
238            Err(e) => {
239                tracing::warn!(
240                    dir = %dir.display(),
241                    error = %e,
242                    "failed to run git stash push — skipping rebase to preserve dirty state"
243                );
244                return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
245            }
246        }
247    } else {
248        None
249    };
250
251    let output = git()
252        .await
253        .args(["rebase", target_ref])
254        .current_dir(dir)
255        .output_with_context()
256        .await;
257
258    match output {
259        Ok(o) if o.status.success() => {
260            tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
261            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
262            Ok(RebaseOutcome::Succeeded)
263        }
264        Ok(o) => {
265            let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
266            tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
267            if opts.abort_on_failure {
268                let abort = Command::new("git")
269                    .args(["rebase", "--abort"])
270                    .current_dir(dir)
271                    .output_with_context()
272                    .await;
273                match abort {
274                    Err(e) => {
275                        tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
276                    }
277                    Ok(o) if !o.status.success() => {
278                        let stderr = String::from_utf8_lossy(&o.stderr);
279                        tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
280                    }
281                    _ => {}
282                }
283            }
284            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
285            Ok(RebaseOutcome::Failed(stderr))
286        }
287        Err(e) => {
288            if opts.abort_on_failure {
289                let abort = Command::new("git")
290                    .args(["rebase", "--abort"])
291                    .current_dir(dir)
292                    .output_with_context()
293                    .await;
294                match abort {
295                    Err(e) => {
296                        tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
297                    }
298                    Ok(o) if !o.status.success() => {
299                        let stderr = String::from_utf8_lossy(&o.stderr);
300                        tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
301                    }
302                    _ => {}
303                }
304            }
305            restore_stash_by_hash(dir, stash_ref.as_deref()).await;
306            Err(e)
307        }
308    }
309}
310
311/// Apply a stash entry by its OID and drop it from the stack on success.
312///
313/// On failure the entry is preserved so it can be recovered manually.
314async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
315    let Some(stash_hash) = stash_hash else {
316        return;
317    };
318
319    let apply = Command::new("git")
320        .args(["stash", "apply", stash_hash])
321        .current_dir(dir)
322        .output_with_context()
323        .await;
324    if apply.is_ok_and(|o| o.status.success()) {
325        let list = Command::new("git")
326            .args(["stash", "list", "--format=%H %gd"])
327            .current_dir(dir)
328            .output_with_context()
329            .await;
330        if let Ok(list_out) = list
331            && list_out.status.success()
332        {
333            let list_str = String::from_utf8_lossy(&list_out.stdout);
334            if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
335                match Command::new("git")
336                    .args(["stash", "drop", &stash_ref])
337                    .current_dir(dir)
338                    .output_with_context()
339                    .await
340                {
341                    Ok(drop_out) if !drop_out.status.success() => {
342                        let stderr = String::from_utf8_lossy(&drop_out.stderr);
343                        tracing::warn!(
344                            dir = %dir.display(),
345                            stash_ref = %stash_ref,
346                            err = %stderr,
347                            "stash drop failed after apply — entry may remain on stack"
348                        );
349                    }
350                    Err(e) => {
351                        tracing::warn!(
352                            dir = %dir.display(),
353                            stash_ref = %stash_ref,
354                            error = %e,
355                            "stash drop command failed after apply — entry may remain on stack"
356                        );
357                    }
358                    _ => {}
359                }
360            } else {
361                tracing::warn!(
362                    dir = %dir.display(),
363                    stash = %stash_hash,
364                    "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
365                );
366            }
367        }
368    } else {
369        tracing::warn!(
370            dir = %dir.display(),
371            stash = %stash_hash,
372            "stash apply failed after rebase — stash preserved for manual recovery"
373        );
374    }
375}
376
377/// Commit what the agent left, with the tool the repository uses (see `commit`).
378pub async fn auto_commit(
379    dir: &Path,
380    task_id: &str,
381    title: &str,
382    agent: &str,
383    attempt: u32,
384    when: super::commit::When,
385) -> anyhow::Result<bool> {
386    if !has_changes(dir).await {
387        return Ok(false);
388    }
389
390    tracing::info!(task_id, "auto-committing uncommitted changes");
391    let task_ref = format_task_ref(task_id);
392    let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
393    match super::commit::commit_all(dir, &message, agent, when).await? {
394        super::commit::Outcome::Committed => {
395            tracing::info!(task_id, "auto-commit succeeded");
396            Ok(true)
397        }
398        super::commit::Outcome::Nothing => Ok(false),
399        super::commit::Outcome::Refused {
400            by: super::commit::Tool::Git,
401            reason,
402        } => {
403            tracing::warn!(task_id, err = %reason, "git commit failed");
404            Ok(false)
405        }
406        super::commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
407    }
408}
409
410/// Maximum number of commits to replay during a rebase.
411///
412/// If a branch has diverged so far from the default branch that it would
413/// require replaying more than this many commits, we skip the rebase entirely.
414/// This prevents degenerate cases (e.g. a branch forked from the very first
415/// commit that now sits 300+ commits behind main) from producing hundreds of
416/// add/add conflicts that block the agent and leave the worktree unusable.
417const MAX_REBASE_COMMITS: usize = 50;
418
419/// Rebase the current branch on top of `origin/{branch}`.
420///
421/// Used for push-failure recovery: when another agent has pushed to the same
422/// branch, we fetch the latest remote state and rebase local commits on top.
423/// Returns `Ok(true)` if rebase succeeded, `Ok(false)` if there was nothing to
424/// rebase, and `Err` if rebase failed (conflicts).
425///
426/// Similar to `rebase_on_default` but targets the feature branch instead of
427/// the default branch, and is used after push failures rather than at startup.
428pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
429    let origin_branch = format!("origin/{branch}");
430
431    // Fetch the remote branch to get latest state.
432    // 2-minute timeout mirrors the push timeout to prevent indefinite stalls.
433    let fetch = time::timeout(
434        Duration::from_secs(120),
435        git()
436            .await
437            .args(["fetch", "origin", branch])
438            .kill_on_drop(true)
439            .current_dir(dir)
440            .output(),
441    )
442    .await
443    .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
444    .and_then(|r| r.map_err(Into::into));
445
446    match fetch {
447        Ok(o) if o.status.success() => {}
448        Ok(o) => {
449            let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
450            anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
451        }
452        Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
453    }
454
455    // Check if there are local commits to rebase.
456    let count_output = Command::new("git")
457        .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
458        .current_dir(dir)
459        .output_with_context()
460        .await;
461
462    let commit_count: usize = match count_output {
463        Ok(o) if o.status.success() => {
464            let raw = String::from_utf8_lossy(&o.stdout);
465            raw.trim().parse().map_err(|e| {
466                anyhow::anyhow!(
467                    "failed to parse commit count from git rev-list output {:?}: {e}",
468                    raw.trim()
469                )
470            })?
471        }
472        Ok(o) => {
473            let stderr = String::from_utf8_lossy(&o.stderr);
474            anyhow::bail!("git rev-list --count failed: {stderr}");
475        }
476        Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
477    };
478
479    if commit_count == 0 {
480        // No local commits to rebase — nothing to do.
481        return Ok(false);
482    }
483
484    if commit_count > MAX_REBASE_COMMITS {
485        anyhow::bail!(
486            "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
487        );
488    }
489
490    tracing::info!(
491        branch = branch,
492        commit_count,
493        "rebasing local commits on origin/{branch}"
494    );
495
496    match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
497        RebaseOutcome::Succeeded => Ok(true),
498        RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
499        RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
500    }
501}
502
503/// Rebase the current branch on the default branch.
504///
505/// Run before the agent starts to ensure the worktree has the latest code.
506/// Fetches both the default branch and the current branch so agents never
507/// need to run `git fetch` themselves (important for sandboxed agents like
508/// codex whose workspace-write sandbox blocks writes outside the worktree).
509/// Non-fatal: if rebase fails (conflicts), the agent may still be able to work.
510pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
511    // auto_merge leaves a conflicted rebase in place for the agent, aborting it here would undo that
512    if rebase_in_progress(dir).await {
513        tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
514        return;
515    }
516
517    // A later force push leases this tip, so fetching someone else's commits cannot permit replacing them
518    let branch = get_current_branch(dir).await;
519    record_push_lease(dir, &branch, default_branch).await;
520
521    // Fetch current branch (for retries with existing remote commits)
522    // and default branch (for rebase) in one call.
523    let _ = git()
524        .await
525        .args(["fetch", "origin"])
526        .current_dir(dir)
527        .output_with_context()
528        .await;
529
530    // Count commits that would be replayed.  If the branch diverged too far
531    // back we skip the rebase: replaying hundreds of historical commits produces
532    // massive add/add conflicts (the branch adds files that main already has)
533    // and leaves the worktree stuck.
534    let commit_count = Command::new("git")
535        .args([
536            "rev-list",
537            "--count",
538            &format!("origin/{default_branch}..HEAD"),
539        ])
540        .current_dir(dir)
541        .output_with_context()
542        .await
543        .ok()
544        .and_then(|o| {
545            String::from_utf8_lossy(&o.stdout)
546                .trim()
547                .parse::<usize>()
548                .ok()
549        })
550        .unwrap_or(0);
551
552    if commit_count > MAX_REBASE_COMMITS {
553        tracing::warn!(
554            default_branch,
555            commit_count,
556            max = MAX_REBASE_COMMITS,
557            "skipping rebase: branch has too many commits to replay safely"
558        );
559        return;
560    }
561
562    match stash_rebase_restore(
563        dir,
564        &format!("origin/{default_branch}"),
565        StashRebaseOpts::default(),
566    )
567    .await
568    {
569        Ok(RebaseOutcome::Succeeded) => {
570            tracing::debug!(default_branch, "rebased worktree on default branch");
571        }
572        Ok(RebaseOutcome::Failed(e)) => {
573            tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
574        }
575        Ok(RebaseOutcome::Skipped(reason)) => {
576            tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
577        }
578        Err(e) => tracing::warn!(err = %e, "rebase error"),
579    }
580}
581
582pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
583    for name in ["rebase-merge", "rebase-apply"] {
584        let out = Command::new("git")
585            .args(["rev-parse", "--git-path", name])
586            .current_dir(dir)
587            .output_with_context()
588            .await;
589        if let Ok(o) = out {
590            let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
591            if !p.is_empty() && dir.join(p).exists() {
592                return true;
593            }
594        }
595    }
596    false
597}
598
599/// Tool patterns no agent may run: a worktree shares `.git/config` with the operator's checkout,
600/// so a rewritten remote or URL rule would change the main repository
601pub(crate) fn remote_change_tools() -> Vec<String> {
602    [
603        "Bash(git remote set-url*)",
604        "Bash(git remote add*)",
605        "Bash(git remote remove*)",
606        "Bash(git remote rm*)",
607        "Bash(git remote rename*)",
608        "Bash(git config*remote.*)",
609        "Bash(git config*url.*)",
610    ]
611    .map(String::from)
612    .to_vec()
613}
614
615/// Credentialed git command whose stdout and stderr are sanitized when read
616pub(crate) struct GitCommand {
617    inner: Command,
618}
619
620impl GitCommand {
621    pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
622        self.inner.arg(arg);
623        self
624    }
625
626    pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
627    where
628        I: IntoIterator<Item = S>,
629        S: AsRef<OsStr>,
630    {
631        self.inner.args(args);
632        self
633    }
634
635    pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
636        self.inner.current_dir(dir);
637        self
638    }
639
640    pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
641    where
642        K: AsRef<OsStr>,
643        V: AsRef<OsStr>,
644    {
645        self.inner.env(key, val);
646        self
647    }
648
649    pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
650        self.inner.kill_on_drop(kill);
651        self
652    }
653
654    pub(crate) async fn output(&mut self) -> io::Result<Output> {
655        self.inner.output().await.map(sanitize_git_output)
656    }
657
658    pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
659        self.inner
660            .output_with_context()
661            .await
662            .map(sanitize_git_output)
663    }
664}
665
666/// A `git` command for every call orch makes: GitHub over HTTPS with the gh token, never SSH,
667/// and no commit or tag signing, whatever the owner's git config says
668pub(crate) async fn git() -> GitCommand {
669    let mut cmd = Command::new("git");
670    cmd.envs(build_git_auth_env().await).kill_on_drop(true);
671    GitCommand { inner: cmd }
672}
673
674/// Build git config environment variables that inject GitHub token credentials.
675///
676/// This handles two scenarios:
677/// - **SSH remotes** (`git@github.com:user/repo.git`): rewritten to
678///   `https://x-access-token:TOKEN@github.com/…` via `insteadOf`.
679/// - **HTTPS remotes** (`https://github.com/user/repo.git`): rewritten to
680///   `https://x-access-token:TOKEN@github.com/…` via a second `insteadOf`.
681///
682/// When no token is available, falls back to the legacy SSH→HTTPS conversion
683/// without credentials (works for repos that use credential helpers or SSH keys).
684///
685/// Returns a `Vec<(String, String)>` of environment variable key-value pairs.
686/// These are NOT visible in the process list (`ps`), unlike `-c` args.
687///
688/// Git environment variables:
689/// - `GIT_CONFIG_COUNT` — number of config entries
690/// - `GIT_CONFIG_KEY_N` — config key for entry N
691/// - `GIT_CONFIG_VALUE_N` — config value for entry N
692///
693/// Signing is switched off too, `commit.gpgsign=false` and `tag.gpgsign=false`
694pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
695    let token = token::shared().get_token().await.ok().flatten();
696    build_git_auth_env_for_token(token)
697}
698
699fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
700    let mut config: Vec<(String, String)> = match token {
701        Some(t) if !t.is_empty() => {
702            let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
703            vec![
704                (authed.clone(), "https://github.com/".into()),
705                (authed, "git@github.com:".into()),
706            ]
707        }
708        _ => vec![(
709            "url.https://github.com/.insteadOf".into(),
710            "git@github.com:".into(),
711        )],
712    };
713    // orch's git never signs, a signing key would ask the owner for a passphrase or a touch
714    config.push(("commit.gpgsign".into(), "false".into()));
715    config.push(("tag.gpgsign".into(), "false".into()));
716
717    let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
718    for (n, (key, value)) in config.into_iter().enumerate() {
719        env.push((format!("GIT_CONFIG_KEY_{n}"), key));
720        env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
721    }
722    env
723}
724
725/// Returns `true` if the push error indicates that the GitHub token lacks the
726/// `workflow` OAuth scope, which is required to push changes to
727/// `.github/workflows/` files.
728///
729/// GitHub rejects pushes with: "refusing to allow an OAuth App to create or
730/// update workflow `…` without `workflow` scope"
731pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
732    stderr.contains("without `workflow` scope")
733        || stderr.contains("without 'workflow' scope")
734        || (stderr.contains("refusing to allow")
735            && stderr.contains("workflow")
736            && stderr.contains("scope"))
737}
738
739/// Remove `.github/workflows/` files from committed changes and amend the
740/// commits so the branch can be pushed without the `workflow` OAuth scope.
741///
742/// Strategy: find all commits ahead of `origin/{default_branch}`, identify
743/// which ones touch `.github/workflows/`, and rewrite them to exclude those
744/// files. Uses `git filter-branch`-style approach via interactive rebase
745/// with `exec` steps.
746///
747/// Returns `Ok(true)` if workflow files were removed and commits rewritten,
748/// `Ok(false)` if no workflow files were found in the commits.
749async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
750    // Find workflow files in commits ahead of the default branch
751    let output = Command::new("git")
752        .args([
753            "diff",
754            "--name-only",
755            &format!("origin/{default_branch}...HEAD"),
756            "--",
757            ".github/workflows/",
758        ])
759        .current_dir(dir)
760        .output_with_context()
761        .await?;
762
763    let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
764        .lines()
765        .filter(|l| !l.is_empty())
766        .map(ToString::to_string)
767        .collect();
768
769    if workflow_files.is_empty() {
770        return Ok(false);
771    }
772
773    tracing::info!(
774        files = ?workflow_files,
775        "stripping workflow files from commits to bypass missing workflow scope"
776    );
777
778    // Remove workflow files from the index and amend each commit.
779    // We use a soft reset → remove files → re-commit approach for simplicity.
780    //
781    // Count commits ahead of default branch
782    let count_output = Command::new("git")
783        .args([
784            "rev-list",
785            "--count",
786            &format!("origin/{default_branch}..HEAD"),
787        ])
788        .current_dir(dir)
789        .output_with_context()
790        .await?;
791
792    let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
793        .trim()
794        .parse()
795        .unwrap_or(0);
796
797    if commit_count == 0 {
798        return Ok(false);
799    }
800
801    // Save the commit messages before resetting.
802    // Use a null byte as the record prefix — null bytes cannot appear in git commit
803    // messages, so this separator is unambiguous (unlike a string like ---COMMIT_SEP---
804    // which an agent could write into a commit body, corrupting the parse).
805    let log_output = Command::new("git")
806        .args([
807            "log",
808            "--format=%x00%H%n%B",
809            &format!("origin/{default_branch}..HEAD"),
810        ])
811        .current_dir(dir)
812        .output_with_context()
813        .await?;
814    let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
815
816    // Parse commits in reverse order (oldest first).
817    // Each record starts with \0 (from %x00 in the format), so split on \0 and
818    // discard any leading empty fragment before the first record.
819    let commits: Vec<(String, String)> = log_text
820        .split('\0')
821        .filter(|s| !s.trim().is_empty())
822        .map(|block| {
823            let block = block.trim();
824            let first_nl = block.find('\n').unwrap_or(block.len());
825            let hash = block[..first_nl].to_string();
826            let msg = block[first_nl..].trim().to_string();
827            (hash, msg)
828        })
829        .collect::<Vec<_>>()
830        .into_iter()
831        .rev()
832        .collect();
833
834    if commits.is_empty() {
835        return Ok(false);
836    }
837
838    // Soft reset to the base (origin/default_branch)
839    let reset = Command::new("git")
840        .args(["reset", "--soft", &format!("origin/{default_branch}")])
841        .current_dir(dir)
842        .output_with_context()
843        .await?;
844
845    if !reset.status.success() {
846        let stderr = String::from_utf8_lossy(&reset.stderr);
847        anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
848    }
849
850    // Remove workflow files from the index
851    let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
852    let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
853    rm_args.extend(file_refs);
854
855    let rm = Command::new("git")
856        .args(&rm_args)
857        .current_dir(dir)
858        .output_with_context()
859        .await?;
860
861    if !rm.status.success() {
862        let stderr = String::from_utf8_lossy(&rm.stderr);
863        tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
864    }
865
866    // Re-commit all remaining changes as a single commit preserving the first message.
867    // This squashes multiple commits but preserves the work minus workflow files.
868    let has_staged = Command::new("git")
869        .args(["diff", "--cached", "--quiet"])
870        .current_dir(dir)
871        .status()
872        .await
873        .is_ok_and(|s| !s.success());
874
875    if !has_staged {
876        tracing::warn!(
877            "after removing workflow files, no staged changes remain — \
878             the only changes were workflow files"
879        );
880        // Reset back to where we were — nothing to push
881        // Use the original HEAD from the first (newest) commit
882        if let Some((hash, _)) = commits.last() {
883            let _ = Command::new("git")
884                .args(["reset", "--soft", hash])
885                .current_dir(dir)
886                .output_with_context()
887                .await;
888        }
889        return Ok(false);
890    }
891
892    // Use the first commit's message (oldest commit)
893    let commit_msg = if commits.len() == 1 {
894        commits[0].1.clone()
895    } else {
896        // Combine messages when squashing
897        let mut combined = String::new();
898        for (i, (_, msg)) in commits.iter().enumerate() {
899            if i > 0 {
900                combined.push_str("\n\n");
901            }
902            combined.push_str(msg);
903        }
904        combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
905        combined
906    };
907
908    // A repair of commits already made, so it lands through git even where shipcheck commits
909    let commit = super::commit::git_commit(dir, &commit_msg, "orchestrator").await?;
910
911    if !commit.status.success() {
912        let stderr = String::from_utf8_lossy(&commit.stderr);
913        // Recovery: restore the original commits so the worktree isn't stuck
914        if let Some((original_head, _)) = commits.last() {
915            let _ = Command::new("git")
916                .args(["reset", "--hard", original_head])
917                .current_dir(dir)
918                .output_with_context()
919                .await;
920        }
921        anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
922    }
923
924    tracing::info!(
925        stripped_files = ?workflow_files,
926        original_commits = commit_count,
927        "successfully stripped workflow files from commits"
928    );
929
930    Ok(true)
931}
932
933const LEASE_ABSENT: &str = "absent";
934
935/// Force pushes that found no recorded lease and fell back to the fetched tip
936static LEASE_FALLBACKS: AtomicU64 = AtomicU64::new(0);
937
938async fn git_stdout(dir: &Path, args: &[&str]) -> Option<String> {
939    let out = Command::new("git")
940        .args(args)
941        .current_dir(dir)
942        .output_with_context()
943        .await
944        .ok()?;
945    if !out.status.success() {
946        return None;
947    }
948
949    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
950}
951
952fn lease_key(branch: &str) -> String {
953    format!("branch.{branch}.orchPushLease")
954}
955
956async fn read_push_lease(dir: &Path, branch: &str) -> Option<String> {
957    git_stdout(dir, &["config", "--get", &lease_key(branch)]).await
958}
959
960async fn write_push_lease(dir: &Path, branch: &str, value: &str) {
961    if git_stdout(dir, &["config", &lease_key(branch), value])
962        .await
963        .is_none()
964    {
965        tracing::warn!(branch, "failed to record push lease");
966    }
967}
968
969async fn remote_tracking_sha(dir: &Path, branch: &str) -> Option<String> {
970    let rev = format!("refs/remotes/origin/{branch}");
971    git_stdout(dir, &["rev-parse", "--verify", "--quiet", &rev])
972        .await
973        .filter(|sha| http::is_full_commit_sha(sha))
974}
975
976async fn is_ancestor(dir: &Path, ancestor: &str, descendant: &str) -> bool {
977    git_stdout(dir, &["merge-base", "--is-ancestor", ancestor, descendant])
978        .await
979        .is_some()
980}
981
982/// Record the remote tip this worktree may replace, before a fetch moves `origin/<branch>`. The lease
983/// moves only to a tip HEAD contains, such as the agent's own push, never to one only fetched
984pub(crate) async fn record_push_lease(dir: &Path, branch: &str, default_branch: &str) {
985    if branch.is_empty() || branch == default_branch {
986        return;
987    }
988
989    let tip = remote_tracking_sha(dir, branch).await;
990    match (read_push_lease(dir, branch).await, tip) {
991        (Some(lease), Some(tip)) if lease != tip && is_ancestor(dir, &tip, "HEAD").await => {
992            write_push_lease(dir, branch, &tip).await;
993        }
994        (Some(_), _) => {}
995        (None, tip) => {
996            let expect = tip.unwrap_or_else(|| LEASE_ABSENT.to_string());
997            write_push_lease(dir, branch, &expect).await;
998        }
999    }
1000}
1001
1002/// Drop the lease of a branch whose remote was deleted, so the next dispatch records one for the recreated branch
1003pub(crate) async fn clear_push_lease(dir: &Path, branch: &str) {
1004    let _ = git_stdout(dir, &["config", "--unset", &lease_key(branch)]).await;
1005}
1006
1007async fn note_pushed_head(dir: &Path, branch: &str) {
1008    let spec = format!("refs/heads/{branch}");
1009    if let Some(sha) = git_stdout(dir, &["rev-parse", "--verify", &spec]).await {
1010        write_push_lease(dir, branch, &sha).await;
1011    }
1012}
1013
1014/// True when `tip` is GitHub's "Update branch" of `lease`: a merge with first parent `lease` and
1015/// second parent on the default branch, or a rebase whose commits all have a twin in `lease`
1016async fn is_github_branch_update(dir: &Path, tip: &str, lease: &str, default_branch: &str) -> bool {
1017    let base = format!("origin/{default_branch}");
1018    let Some(line) = git_stdout(dir, &["rev-list", "--parents", "-n", "1", tip]).await else {
1019        return false;
1020    };
1021    let parents: Vec<&str> = line.split_whitespace().skip(1).collect();
1022    if let [first, second] = parents[..] {
1023        return first == lease && is_ancestor(dir, second, &base).await;
1024    }
1025
1026    // `git cherry` marks each commit in base..tip with `-` when `lease` holds the same patch
1027    let Some(cherry) = git_stdout(dir, &["cherry", lease, tip, &base]).await else {
1028        return false;
1029    };
1030    is_ancestor(dir, &base, tip).await
1031        && !cherry.is_empty()
1032        && cherry.lines().all(|l| l.starts_with('-'))
1033}
1034
1035async fn expected_force_sha(
1036    dir: &Path,
1037    branch: &str,
1038    default_branch: &str,
1039) -> anyhow::Result<String> {
1040    let tip = remote_tracking_sha(dir, branch).await;
1041    let base = format!("origin/{default_branch}");
1042    if let Some(tip) = &tip {
1043        // A tip the default branch already holds has no commits of its own, so a force push loses nothing
1044        if is_ancestor(dir, tip, &base).await {
1045            tracing::info!(branch, %tip, "remote tip is contained in the default branch, leasing it");
1046            return Ok(tip.clone());
1047        }
1048    }
1049
1050    match read_push_lease(dir, branch).await {
1051        Some(lease) if lease == LEASE_ABSENT => anyhow::bail!(
1052            "force push rejected: remote branch {branch} was absent when the lease was recorded"
1053        ),
1054        Some(lease) => match tip {
1055            Some(tip)
1056                if tip != lease
1057                    && is_github_branch_update(dir, &tip, &lease, default_branch).await =>
1058            {
1059                tracing::info!(branch, %lease, %tip, "remote tip is GitHub's update of the leased branch, leasing it");
1060                Ok(tip)
1061            }
1062            _ => Ok(lease),
1063        },
1064        None => {
1065            let Some(tip) = tip else {
1066                anyhow::bail!("force push rejected: no remote sha recorded for {branch}");
1067            };
1068            let fallbacks = LEASE_FALLBACKS.fetch_add(1, Ordering::Relaxed) + 1;
1069            tracing::warn!(
1070                branch,
1071                fallbacks,
1072                "no push lease recorded, using the fetched origin tip"
1073            );
1074            Ok(tip)
1075        }
1076    }
1077}
1078
1079/// Force-push `branch` only if the remote still holds the leased sha
1080pub(crate) async fn force_push_leased(
1081    dir: &Path,
1082    branch: &str,
1083    default_branch: &str,
1084) -> anyhow::Result<()> {
1085    let expected = expected_force_sha(dir, branch, default_branch).await?;
1086    let lease = format!("--force-with-lease={branch}:{expected}");
1087    tracing::info!(branch, expected_sha = %expected, "force-pushing with an expected remote sha");
1088    let output = git()
1089        .await
1090        .args([
1091            "-c",
1092            "lfs.locksverify=false",
1093            "push",
1094            &lease,
1095            "-u",
1096            "origin",
1097            branch,
1098        ])
1099        .current_dir(dir)
1100        .kill_on_drop(true)
1101        .output_with_context()
1102        .await?;
1103    if output.status.success() {
1104        note_pushed_head(dir, branch).await;
1105        return Ok(());
1106    }
1107
1108    let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
1109    anyhow::bail!("{stderr}")
1110}
1111
1112/// True for a branch orch must never push: the repo default, plus `main` and `master`
1113fn is_protected_push_branch(name: &str, default_branch: &str) -> bool {
1114    !name.is_empty() && (name == default_branch || name == "main" || name == "master")
1115}
1116
1117/// Pick the ref to push. A protected checkout falls back to the task branch when that name is safe
1118fn resolve_push_branch<'a>(
1119    current: &'a str,
1120    branch: &'a str,
1121    default_branch: &str,
1122) -> anyhow::Result<&'a str> {
1123    let chosen = if !current.is_empty() && !is_protected_push_branch(current, default_branch) {
1124        current
1125    } else if !branch.is_empty() && !is_protected_push_branch(branch, default_branch) {
1126        branch
1127    } else {
1128        let name = if current.is_empty() { branch } else { current };
1129        if name.is_empty() {
1130            anyhow::bail!("cannot push: branch name is empty");
1131        }
1132        anyhow::bail!("push refused: '{name}' is a default branch");
1133    };
1134    Ok(chosen)
1135}
1136
1137/// Push the branch to origin.
1138///
1139/// Returns `Ok(true)` when the branch is on the remote, `Ok(false)` when the push was skipped,
1140/// and `Err` when the push was refused (default branch) or failed
1141pub async fn push_branch(dir: &Path, branch: &str, default_branch: &str) -> anyhow::Result<bool> {
1142    let current = get_current_branch(dir).await;
1143    let branch_to_push = resolve_push_branch(&current, branch, default_branch)?;
1144
1145    // Check if there are commits to push and whether the remote branch exists
1146    let (remote_exists, has_unpushed) =
1147        check_push_needed(dir, branch_to_push, default_branch).await;
1148    if remote_exists && !has_unpushed {
1149        // Remote already has this branch and it's up to date — nothing to push.
1150        // Return true so callers know the branch IS on the remote and PR creation
1151        // is safe to attempt (e.g. a PR may already exist or can be created).
1152        tracing::debug!(
1153            branch = branch_to_push,
1154            "remote branch exists and is up to date, skipping push"
1155        );
1156        note_pushed_head(dir, branch_to_push).await;
1157        return Ok(true);
1158    }
1159    if !remote_exists && !has_unpushed {
1160        // Branch doesn't exist on the remote and has no commits ahead of the
1161        // default branch — push it anyway so the branch is created on the remote.
1162        // PR creation will then fail with "No commits between …" (422) which is
1163        // handled downstream, rather than with "head invalid" (422) which is
1164        // harder to distinguish from a real error.
1165        tracing::debug!(
1166            branch = branch_to_push,
1167            "remote branch missing with no new commits — pushing to create it on remote"
1168        );
1169    }
1170
1171    tracing::info!(branch = branch_to_push, "pushing branch");
1172
1173    // First attempt: normal push (no force).
1174    // lfs.locksverify=false skips the auxiliary LFS locks/verify roundtrip in
1175    // the pre-push hook; agents never hold LFS locks, and a transient timeout
1176    // on that endpoint must not fail the whole push.
1177    // A 2-minute timeout prevents an indefinitely-stalled push from blocking
1178    // post-processing and triggering a stuck-task re-dispatch race.
1179    let output = time::timeout(
1180        Duration::from_secs(120),
1181        git()
1182            .await
1183            .args([
1184                "-c",
1185                "lfs.locksverify=false",
1186                "push",
1187                "-u",
1188                "origin",
1189                branch_to_push,
1190            ])
1191            .kill_on_drop(true)
1192            .current_dir(dir)
1193            .output(),
1194    )
1195    .await
1196    .map_err(|_| anyhow::anyhow!("git push timed out after 120s"))??;
1197
1198    if output.status.success() {
1199        tracing::info!(branch = branch_to_push, "push succeeded");
1200        note_pushed_head(dir, branch_to_push).await;
1201        return Ok(true);
1202    }
1203
1204    let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
1205
1206    // Transient network blip (timeout, reset) rather than a ref rejection —
1207    // retry the identical push once before classifying the run as failed.
1208    if is_transient_network_error(&stderr) {
1209        tracing::warn!(
1210            branch = branch_to_push,
1211            stderr = %stderr,
1212            "push failed with transient network error — retrying once"
1213        );
1214        let retry_output = time::timeout(
1215            Duration::from_secs(120),
1216            git()
1217                .await
1218                .args([
1219                    "-c",
1220                    "lfs.locksverify=false",
1221                    "push",
1222                    "-u",
1223                    "origin",
1224                    branch_to_push,
1225                ])
1226                .kill_on_drop(true)
1227                .current_dir(dir)
1228                .output(),
1229        )
1230        .await
1231        .map_err(|_| anyhow::anyhow!("git push (network retry) timed out after 120s"))??;
1232
1233        if retry_output.status.success() {
1234            tracing::info!(branch = branch_to_push, "push succeeded on network retry");
1235            note_pushed_head(dir, branch_to_push).await;
1236            return Ok(true);
1237        }
1238
1239        let retry_stderr =
1240            sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
1241        tracing::warn!(
1242            branch = branch_to_push,
1243            stderr = %retry_stderr,
1244            "push retry also failed"
1245        );
1246        anyhow::bail!("push failed: {retry_stderr}");
1247    }
1248
1249    // Handle workflow scope error: the token lacks the `workflow` OAuth scope
1250    // required to push changes to `.github/workflows/`. Strip workflow files
1251    // from commits and retry the push.
1252    if is_workflow_scope_error(&stderr) {
1253        tracing::warn!(
1254            branch = branch_to_push,
1255            "push rejected: token lacks `workflow` scope — stripping workflow files and retrying"
1256        );
1257
1258        match strip_workflow_files(dir, default_branch).await {
1259            Ok(true) => {
1260                // Workflow files stripped, retry push
1261                let retry_output = time::timeout(
1262                    Duration::from_secs(120),
1263                    git()
1264                        .await
1265                        .args([
1266                            "-c",
1267                            "lfs.locksverify=false",
1268                            "push",
1269                            "-u",
1270                            "origin",
1271                            branch_to_push,
1272                        ])
1273                        .kill_on_drop(true)
1274                        .current_dir(dir)
1275                        .output(),
1276                )
1277                .await
1278                .map_err(|_| anyhow::anyhow!("git push (retry) timed out after 120s"))??;
1279
1280                if retry_output.status.success() {
1281                    tracing::info!(
1282                        branch = branch_to_push,
1283                        "push succeeded after stripping workflow files"
1284                    );
1285                    note_pushed_head(dir, branch_to_push).await;
1286                    return Ok(true);
1287                }
1288
1289                let retry_stderr =
1290                    sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
1291
1292                // If still failing with workflow scope, bail with clear message
1293                if is_workflow_scope_error(&retry_stderr) {
1294                    anyhow::bail!(
1295                        "push failed: token lacks `workflow` OAuth scope and workflow files \
1296                         could not be fully stripped — add `workflow` scope to your GitHub \
1297                         token or use a GitHub App for authentication"
1298                    );
1299                }
1300
1301                anyhow::bail!("push failed after stripping workflow files: {retry_stderr}");
1302            }
1303            Ok(false) => {
1304                // No workflow files found to strip (shouldn't happen if error was detected)
1305                anyhow::bail!(
1306                    "push failed: token lacks `workflow` OAuth scope — add `workflow` scope \
1307                     to your GitHub token or use a GitHub App for authentication. \
1308                     Error: {stderr}"
1309                );
1310            }
1311            Err(e) => {
1312                tracing::error!(error = %e, "failed to strip workflow files from commits");
1313                anyhow::bail!(
1314                    "push failed: token lacks `workflow` OAuth scope and automatic \
1315                     recovery failed ({e}) — add `workflow` scope to your GitHub token \
1316                     or use a GitHub App for authentication"
1317                );
1318            }
1319        }
1320    }
1321
1322    // Non-fast-forward after `rebase_on_default`. The lease was recorded before that fetch,
1323    // so this replaces only a tip this worktree already built on
1324    if push_needs_rebase(&stderr) && remote_exists {
1325        tracing::info!(
1326            branch = branch_to_push,
1327            "push rejected (non-fast-forward), force-pushing with lease"
1328        );
1329        let stderr = match force_push_leased(dir, branch_to_push, default_branch).await {
1330            Ok(()) => {
1331                tracing::info!(branch = branch_to_push, "force push succeeded");
1332                return Ok(true);
1333            }
1334            Err(e) => e.to_string(),
1335        };
1336
1337        // Check if force push also hit the workflow scope error
1338        if is_workflow_scope_error(&stderr) {
1339            tracing::warn!(
1340                branch = branch_to_push,
1341                "force push also rejected due to workflow scope — stripping and retrying"
1342            );
1343            match strip_workflow_files(dir, default_branch).await {
1344                Ok(true) => {
1345                    if let Err(e) = force_push_leased(dir, branch_to_push, default_branch).await {
1346                        anyhow::bail!("force push failed after stripping workflow files: {e}");
1347                    }
1348
1349                    tracing::info!(
1350                        branch = branch_to_push,
1351                        "force push succeeded after stripping workflow files"
1352                    );
1353                    return Ok(true);
1354                }
1355                Ok(false) => {
1356                    anyhow::bail!(
1357                        "force push failed: token lacks `workflow` OAuth scope — \
1358                         add `workflow` scope to your GitHub token or use a GitHub App. \
1359                         Error: {stderr}"
1360                    );
1361                }
1362                Err(e) => {
1363                    anyhow::bail!(
1364                        "force push failed: token lacks `workflow` scope and recovery \
1365                         failed ({e})"
1366                    );
1367                }
1368            }
1369        }
1370
1371        // The remote branch moved since the last fetch (GitHub's "Update branch", another
1372        // clone), so the lease no longer matches. Replay local commits on the new tip once
1373        if is_stale_lease_error(&stderr) && rebase_on_branch(dir, branch_to_push).await? {
1374            let output = git()
1375                .await
1376                .args([
1377                    "-c",
1378                    "lfs.locksverify=false",
1379                    "push",
1380                    "-u",
1381                    "origin",
1382                    branch_to_push,
1383                ])
1384                .current_dir(dir)
1385                .output_with_context()
1386                .await?;
1387            if output.status.success() {
1388                tracing::info!(
1389                    branch = branch_to_push,
1390                    "push succeeded after rebasing on the moved remote branch"
1391                );
1392                note_pushed_head(dir, branch_to_push).await;
1393                return Ok(true);
1394            }
1395
1396            let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
1397            anyhow::bail!("push failed after rebasing on the moved remote branch: {stderr}");
1398        }
1399
1400        if is_stale_lease_error(&stderr) {
1401            tracing::info!(
1402                branch = branch_to_push,
1403                "remote branch already holds every local commit, nothing to push"
1404            );
1405            return Ok(true);
1406        }
1407
1408        anyhow::bail!("force push failed: {stderr}");
1409    }
1410
1411    anyhow::bail!("push failed: {stderr}")
1412}
1413
1414pub fn is_missing_remote_ref_error(err: &anyhow::Error) -> bool {
1415    err.to_string().contains("couldn't find remote ref")
1416}
1417
1418fn push_needs_rebase(stderr: &str) -> bool {
1419    let lower = stderr.to_ascii_lowercase();
1420    lower.contains("non-fast-forward")
1421        || lower.contains("rejected")
1422        || lower.contains("fetch first")
1423        || lower.contains("behind")
1424}
1425
1426/// True when `--force-with-lease` refused because the remote ref is not the one last fetched
1427fn is_stale_lease_error(stderr: &str) -> bool {
1428    let lower = stderr.to_ascii_lowercase();
1429    lower.contains("stale info") || lower.contains("remote ref updated since checkout")
1430}
1431
1432/// True when a push failure looks like a transient network error (dial
1433/// timeout, i/o timeout, connection reset) rather than a ref rejection.
1434/// A refused ref must not be retried, but a blipped endpoint deserves one
1435/// immediate retry before the run is classified as `push_failed`.
1436pub fn is_transient_network_error(stderr: &str) -> bool {
1437    let lower = stderr.to_ascii_lowercase();
1438    lower.contains("i/o timeout")
1439        || lower.contains("dial tcp")
1440        || lower.contains("connection reset")
1441        || lower.contains("connection refused")
1442        || lower.contains("no route to host")
1443        || lower.contains("temporary failure in name resolution")
1444        || lower.contains("eof")
1445        || lower.contains("fatal error in commit_refs")
1446        || (lower.contains("[remote rejected]") && lower.contains("(failure)"))
1447}
1448
1449/// Strip URL userinfo (`https://x-access-token:TOKEN@…`) and leak-pattern secrets
1450/// from credentialed git stdout and stderr before it is logged or stored
1451pub(crate) fn sanitize_push_error(stderr: &str) -> String {
1452    static URL_USERINFO: LazyLock<Regex> =
1453        LazyLock::new(|| Regex::new(r"://[^/@\s]+@").expect("valid url userinfo regex"));
1454    let no_userinfo = URL_USERINFO.replace_all(stderr, "://***@");
1455    security::redact(&no_userinfo)
1456}
1457
1458/// Sanitize both streams of a credentialed git `Output` so callers cannot log the raw bytes
1459pub(crate) fn sanitize_git_output(mut output: Output) -> Output {
1460    output.stdout = sanitize_push_error(&String::from_utf8_lossy(&output.stdout)).into_bytes();
1461    output.stderr = sanitize_push_error(&String::from_utf8_lossy(&output.stderr)).into_bytes();
1462    output
1463}
1464
1465/// Drop sentences and list items about pushing or opening the PR
1466/// Agents report they could not push, orch already pushed, so those lines read as false on GitHub
1467fn strip_push_and_pr_creation(text: &str) -> String {
1468    let mut kept_lines: Vec<String> = Vec::new();
1469    for line in text.lines() {
1470        if line.trim().is_empty() {
1471            if kept_lines.last().is_some_and(|l| !l.is_empty()) {
1472                kept_lines.push(String::new());
1473            }
1474            continue;
1475        }
1476
1477        let indent_len = line.len() - line.trim_start().len();
1478        let indent = &line[..indent_len];
1479        let trimmed = line.trim();
1480        let (marker, rest) = match list_marker(trimmed) {
1481            Some((m, r)) => (m, r),
1482            None => ("", trimmed),
1483        };
1484
1485        let kept: Vec<&str> = split_statements(rest)
1486            .into_iter()
1487            .filter(|s| !is_push_or_pr_creation_statement(s))
1488            .collect();
1489        if kept.is_empty() {
1490            continue;
1491        }
1492        kept_lines.push(format!("{indent}{marker}{}", kept.join(" ")));
1493    }
1494    while kept_lines.last().is_some_and(String::is_empty) {
1495        kept_lines.pop();
1496    }
1497    kept_lines.join("\n")
1498}
1499
1500fn split_statements(text: &str) -> Vec<&str> {
1501    static SEP: LazyLock<Regex> =
1502        LazyLock::new(|| Regex::new(r"(\.{2,}|(?:[.!?]))\s+").expect("valid statement separator"));
1503    let mut statements = Vec::new();
1504    let mut last = 0;
1505    for cap in SEP.captures_iter(text) {
1506        let full = cap.get(0).expect("full separator match");
1507        let punct = cap.get(1).expect("punctuation capture");
1508        let ellipsis = punct.as_str().len() >= 2 && punct.as_str().bytes().all(|b| b == b'.');
1509        let end = if ellipsis { punct.start() } else { punct.end() };
1510        let stmt = text[last..end].trim();
1511        if !stmt.is_empty() {
1512            statements.push(stmt);
1513        }
1514        last = full.end();
1515    }
1516    let rest = text[last..].trim();
1517    if !rest.is_empty() {
1518        statements.push(rest);
1519    }
1520    statements
1521}
1522
1523fn list_marker(line: &str) -> Option<(&str, &str)> {
1524    for prefix in ["- ", "* ", "+ "] {
1525        if let Some(rest) = line.strip_prefix(prefix) {
1526            return Some((prefix, rest));
1527        }
1528    }
1529    let dot = line.find(". ")?;
1530    if !line[..dot].is_empty() && line[..dot].bytes().all(|b| b.is_ascii_digit()) {
1531        Some((&line[..dot + 2], &line[dot + 2..]))
1532    } else {
1533        None
1534    }
1535}
1536
1537fn is_push_or_pr_creation_statement(text: &str) -> bool {
1538    static PAT: LazyLock<Regex> = LazyLock::new(|| {
1539        Regex::new(concat!(
1540            r"(?i)",
1541            r"\bgit\s+push\b",
1542            r"|\bgh\s+pr\s+create\b",
1543            r"|\bgh\s+pr\s+open\b",
1544            r"|\bpush\s+(was\s+)?(denied|blocked|rejected)\b",
1545            r"|\bpush\s+permission\b",
1546            r"|\bcouldn['’]?t\s+push\b",
1547            r"|\bcould\s+not\s+push\b",
1548            r"|\bcan['’]?t\s+push\b",
1549            r"|\bcannot\s+push\b",
1550            r"|\bdidn['’]?t\s+push\b",
1551            r"|\bdid\s+not\s+push\b",
1552            r"|\bnothing\s+is\s+on\s+the\s+remote\b",
1553            r"|\bnot\s+on\s+the\s+remote\b",
1554            r"|\bopen(?:ing)?\s+(?:the|a)\s+pr\b",
1555            r"|\bcreat(?:e|ing)\s+(?:the|a)\s+pr\b",
1556            r"|\bopen(?:ing)?\s+(?:the|a)\s+pull\s+request\b",
1557            r"|\bcreat(?:e|ing)\s+(?:the|a)\s+pull\s+request\b",
1558        ))
1559        .expect("valid push/pr-creation regex")
1560    });
1561    PAT.is_match(text)
1562}
1563
1564fn cleaned_pr_items(items: &[String]) -> Vec<String> {
1565    items
1566        .iter()
1567        .filter_map(|item| {
1568            let cleaned = strip_push_and_pr_creation(item);
1569            (!cleaned.is_empty()).then_some(cleaned)
1570        })
1571        .collect()
1572}
1573
1574/// Format the GitHub PR description from the agent summary, stripping push and PR-creation statements
1575#[expect(
1576    clippy::too_many_arguments,
1577    reason = "each argument is one section of the PR body"
1578)]
1579fn build_pr_body(
1580    title: &str,
1581    summary: &str,
1582    accomplished: &[String],
1583    remaining: &[String],
1584    files: &[String],
1585    task_id: &str,
1586    agent: &str,
1587    model: Option<&str>,
1588) -> String {
1589    let cleaned_summary = strip_push_and_pr_creation(summary);
1590    let summary_text = if cleaned_summary.is_empty() {
1591        title
1592    } else {
1593        cleaned_summary.as_str()
1594    };
1595    let accomplished = cleaned_pr_items(accomplished);
1596    let remaining = cleaned_pr_items(remaining);
1597
1598    let mut body = format!("## Summary\n\n{summary_text}");
1599
1600    if !accomplished.is_empty() {
1601        body.push_str("\n\n### What was done\n\n");
1602        for item in &accomplished {
1603            let _ = writeln!(body, "- {item}");
1604        }
1605    }
1606
1607    if !remaining.is_empty() {
1608        body.push_str("\n\n### Remaining\n\n");
1609        for item in &remaining {
1610            let _ = writeln!(body, "- {item}");
1611        }
1612    }
1613
1614    if !files.is_empty() {
1615        body.push_str("\n\n### Files changed\n\n");
1616        for file in files {
1617            let _ = writeln!(body, "- `{file}`");
1618        }
1619    }
1620
1621    // CI-01 must stay open after merge until the default-branch ruleset exists
1622    let bootstrap = plan::is_ci_bootstrap_id(title.split_whitespace().next().unwrap_or(title));
1623    if !bootstrap
1624        && !task_id.starts_with("internal:")
1625        && let Ok(issue_num) = task_id.parse::<u64>()
1626    {
1627        let _ = write!(body, "\n\nCloses #{issue_num}");
1628    }
1629
1630    let model_str = model.map(|m| format!(" using `{m}`")).unwrap_or_default();
1631    let task_ref = format_task_ref(task_id);
1632    let _ = write!(
1633        body,
1634        "\n\n---\n*Task {task_ref} · Created by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch){model_str}*"
1635    );
1636    body
1637}
1638
1639/// Create a PR if one doesn't already exist.
1640///
1641/// Uses [`GhHttp`] exclusively for GitHub API operations. No `gh` CLI
1642/// fallback is used, ensuring consistent behavior across environments.
1643///
1644/// # Returns
1645/// - `Ok(url)` - PR URL (newly created or already existed)
1646/// - `Err(PrCreateError)` - API error or other failure
1647#[expect(
1648    clippy::too_many_arguments,
1649    reason = "the PR needs its branch, body sections, attribution and target together"
1650)]
1651pub async fn create_pr_if_needed(
1652    dir: &Path,
1653    branch: &str,
1654    title: &str,
1655    summary: &str,
1656    accomplished: &[String],
1657    remaining: &[String],
1658    files: &[String],
1659    task_id: &str,
1660    agent: &str,
1661    model: Option<&str>,
1662    repo: &str,
1663    base_branch: &str,
1664) -> PrCreateResult<String> {
1665    // Retries for transient 5xx errors on PR creation below
1666    const MAX_RETRIES: u32 = 3;
1667    let gh = GhHttp::new()?;
1668
1669    // Check if PR already exists using GhHttp API
1670    match gh.get_pr_number(repo, branch).await {
1671        Ok(Some(pr_number)) => {
1672            tracing::info!(task_id, pr = pr_number, "PR already exists");
1673            // Append attribution footer if the agent created the PR without one.
1674            append_pr_footer_if_missing(&gh, repo, pr_number, task_id, agent, model).await;
1675            // Fetch the existing PR to get its URL so the caller can store pr_number.
1676            let pr = match gh.get_pr(repo, pr_number).await {
1677                Ok(pr) => pr,
1678                Err(e) => {
1679                    tracing::warn!(task_id, error = %e, "get_pr API call failed after detecting existing PR");
1680                    return Err(PrCreateError::ApiError(e));
1681                }
1682            };
1683            return Ok(pr.html_url);
1684        }
1685        Ok(None) => {
1686            // No PR exists, proceed to create one
1687        }
1688        Err(e) => {
1689            tracing::warn!(task_id, error = %e, "get_pr_number API call failed");
1690            return Err(PrCreateError::ApiError(e));
1691        }
1692    }
1693
1694    // When the agent didn't self-report files, derive them from git.
1695    let git_files: Vec<String>;
1696    let effective_files: &[String] = if files.is_empty() {
1697        match Command::new("git")
1698            .args([
1699                "diff",
1700                &format!("origin/{base_branch}...HEAD"),
1701                "--name-only",
1702            ])
1703            .current_dir(dir)
1704            .output()
1705            .await
1706        {
1707            Ok(output) if output.status.success() => {
1708                git_files = String::from_utf8_lossy(&output.stdout)
1709                    .lines()
1710                    .filter(|l| !l.is_empty())
1711                    .map(ToString::to_string)
1712                    .collect();
1713                &git_files
1714            }
1715            _ => files,
1716        }
1717    } else {
1718        files
1719    };
1720
1721    let body = build_pr_body(
1722        title,
1723        summary,
1724        accomplished,
1725        remaining,
1726        effective_files,
1727        task_id,
1728        agent,
1729        model,
1730    );
1731
1732    // Always use the short task title for the PR title (summary goes in body)
1733    let pr_title = title;
1734
1735    // Create PR using GhHttp API with exponential backoff retry for transient 5xx errors.
1736    let mut last_error: Option<anyhow::Error> = None;
1737    let mut created_url: Option<String> = None;
1738    let mut had_transient_error = false;
1739    let mut effective_base = base_branch.to_string();
1740    let mut tried_api_fallback = false;
1741
1742    for attempt in 1..=MAX_RETRIES {
1743        match gh
1744            .create_pr(repo, pr_title, &body, branch, &effective_base)
1745            .await
1746        {
1747            Ok(u) => {
1748                created_url = Some(u);
1749                break;
1750            }
1751            Err(e) => {
1752                let err_str = format!("{e}");
1753                if is_transient_github_error(&err_str) {
1754                    had_transient_error = true;
1755                    if attempt < MAX_RETRIES {
1756                        let delay = Duration::from_secs(2u64.pow(attempt));
1757                        tracing::warn!(
1758                            task_id,
1759                            attempt,
1760                            delay_secs = delay.as_secs(),
1761                            error = %e,
1762                            "transient GitHub API error during PR creation — retrying"
1763                        );
1764                        time::sleep(delay).await;
1765                    }
1766                } else if is_invalid_base_error(&err_str) && !tried_api_fallback {
1767                    // Local base branch detection was wrong (e.g. "remotes/origin/main").
1768                    // Query GitHub API for the canonical default branch and retry once.
1769                    tried_api_fallback = true;
1770                    tracing::warn!(
1771                        task_id,
1772                        base_branch = %effective_base,
1773                        error = %e,
1774                        "PR creation failed with invalid base — fetching default branch from GitHub API"
1775                    );
1776                    match gh.get_default_branch(repo).await {
1777                        Ok(api_default) if api_default != effective_base => {
1778                            tracing::info!(
1779                                task_id,
1780                                old_base = %effective_base,
1781                                new_base = %api_default,
1782                                "retrying PR creation with GitHub API default branch"
1783                            );
1784                            effective_base = api_default;
1785                            continue;
1786                        }
1787                        Ok(api_default) => {
1788                            tracing::warn!(
1789                                task_id,
1790                                base_branch = %api_default,
1791                                "GitHub API default branch matches local — no fallback possible"
1792                            );
1793                        }
1794                        Err(api_err) => {
1795                            tracing::warn!(
1796                                task_id,
1797                                error = %api_err,
1798                                "failed to fetch default branch from GitHub API"
1799                            );
1800                        }
1801                    }
1802                }
1803                last_error = Some(e);
1804            }
1805        }
1806    }
1807
1808    let url = if let Some(u) = created_url {
1809        u
1810    } else {
1811        let e = last_error.unwrap_or_else(|| {
1812            anyhow::anyhow!("PR creation failed after retries (no error captured)")
1813        });
1814        let err_str = format!("{e}");
1815        // For transient 5xx errors, GitHub may have created the PR despite returning
1816        // an error (e.g. 502 after the write succeeded). Re-check for an existing PR
1817        // before propagating the failure so we don't orphan the PR from the task.
1818        // Also check when the final error is non-transient but a prior attempt had a
1819        // transient error — the PR may have been created on that earlier attempt (e.g.
1820        // attempt 1 returns 502, attempt 2 returns 422 "already exists").
1821        if is_transient_github_error(&err_str) || had_transient_error {
1822            tracing::warn!(
1823                task_id,
1824                error = %e,
1825                "transient GitHub API error after all retries — checking if PR was actually created"
1826            );
1827            match gh.get_pr_number(repo, branch).await {
1828                Ok(Some(pr_number)) => {
1829                    tracing::info!(
1830                        task_id,
1831                        pr = pr_number,
1832                        "PR was created despite transient errors — recovering"
1833                    );
1834                    append_pr_footer_if_missing(&gh, repo, pr_number, task_id, agent, model).await;
1835                    match gh.get_pr(repo, pr_number).await {
1836                        Ok(pr) => pr.html_url,
1837                        Err(get_err) => {
1838                            tracing::warn!(
1839                                task_id,
1840                                error = %get_err,
1841                                "failed to fetch PR URL after transient-error recovery"
1842                            );
1843                            return Err(PrCreateError::ApiError(e));
1844                        }
1845                    }
1846                }
1847                Ok(None) => {
1848                    tracing::warn!(
1849                        task_id,
1850                        "PR was not created after all retries — propagating original error"
1851                    );
1852                    return Err(PrCreateError::ApiError(e));
1853                }
1854                Err(check_err) => {
1855                    tracing::warn!(
1856                        task_id,
1857                        error = %check_err,
1858                        "failed to verify PR existence after transient error retries — propagating original error"
1859                    );
1860                    return Err(PrCreateError::ApiError(e));
1861                }
1862            }
1863        } else {
1864            return Err(PrCreateError::ApiError(e));
1865        }
1866    };
1867
1868    tracing::info!(task_id, pr_url = %url, "created PR via GhHttp API");
1869
1870    Ok(url)
1871}
1872
1873/// Returns true if the error string indicates a transient GitHub API failure
1874/// (HTTP 5xx, network errors, DNS failures, TLS issues, rate limits), where
1875/// the operation may succeed on retry.
1876pub(crate) fn is_transient_github_error(err_str: &str) -> bool {
1877    // Treat transport/send failures and explicit GhHttp server-error messages
1878    // as transient. Older callers relied on parsing the "failed (NNN)" pattern
1879    // to detect 5xx — keep that, but also recognize the newer wrappers.
1880    if err_str.contains("HTTP send failed") {
1881        return true;
1882    }
1883    if err_str.contains("GitHub API server error") {
1884        return true;
1885    }
1886
1887    // Check for HTTP 5xx status codes
1888    if extract_github_http_status(err_str).is_some_and(|s| (500..600).contains(&s)) {
1889        return true;
1890    }
1891
1892    // Check for common network-level transient errors
1893    let lower = err_str.to_lowercase();
1894
1895    // Connection and transport errors
1896    if lower.contains("connection reset")
1897        || lower.contains("broken pipe")
1898        || lower.contains("connection refused")
1899        || lower.contains("connection closed")
1900        || lower.contains("transport error")
1901        || lower.contains("failed to connect")
1902        || lower.contains("failed to connect to github.com port")
1903        || lower.contains("curl: (7) failed to connect")
1904        || lower.contains("couldn't connect to server")
1905        || lower.contains("could not connect to server")
1906    {
1907        return true;
1908    }
1909
1910    // Timeout errors
1911    if lower.contains("timeout") {
1912        return true;
1913    }
1914
1915    // DNS resolution errors
1916    if lower.contains("dns error")
1917        || lower.contains("resolve")
1918        || lower.contains("name resolution")
1919        || lower.contains("no such host")
1920    {
1921        return true;
1922    }
1923
1924    // TLS/SSL errors
1925    if lower.contains("tls handshake")
1926        || lower.contains("certificate")
1927        || lower.contains("ssl error")
1928    {
1929        return true;
1930    }
1931
1932    // Network unreachable errors
1933    if lower.contains("network is unreachable")
1934        || lower.contains("host unreachable")
1935        || lower.contains("temporary failure")
1936    {
1937        return true;
1938    }
1939
1940    // EOF errors (connection dropped mid-request)
1941    if lower.contains("unexpected eof") || lower.contains("unexpected end of file") {
1942        return true;
1943    }
1944
1945    // Internal circuit-breaker state (orch's own GitHub 5xx protection)
1946    if lower.contains("circuit-breaker") || lower.contains("circuit breaker") {
1947        return true;
1948    }
1949
1950    // Rate limit errors (transient with cooldown/retry)
1951    if lower.contains("rate limit") || lower.contains("too many requests") {
1952        return true;
1953    }
1954
1955    false
1956}
1957
1958/// Returns true when the error indicates the PR base branch is invalid.
1959///
1960/// GitHub returns HTTP 422 with `PullRequest.base invalid` when the base
1961/// branch name is not a valid ref in the repository. This is a terminal
1962/// configuration error — retrying with the same base will never succeed.
1963pub(crate) fn is_invalid_base_error(err_str: &str) -> bool {
1964    let lower = err_str.to_lowercase();
1965    lower.contains("422") && lower.contains("base") && lower.contains("invalid")
1966}
1967
1968/// Returns true when an error looks like a transient *GitHub API/CLI* failure.
1969///
1970/// This is stricter than [`is_transient_github_error`]: in addition to matching
1971/// a transient transport pattern, it requires GitHub-specific context in the
1972/// message. This prevents generic agent/runtime transport failures (for
1973/// example "broken pipe" from a model stream disconnect) from being treated as
1974/// GitHub retry signals in review reroute logic.
1975pub(crate) fn is_transient_github_api_error(err_str: &str) -> bool {
1976    if !is_transient_github_error(err_str) {
1977        return false;
1978    }
1979
1980    if extract_github_http_status(err_str).is_some() {
1981        return true;
1982    }
1983
1984    let lower = err_str.to_lowercase();
1985    lower.contains("github")
1986        || lower.contains("api.github.com")
1987        || lower.contains("gh api")
1988        || lower.contains("gh pr")
1989        || lower.contains("gh error")
1990        // `circuit-breaker` is orch's internal GitHub 5xx protection, set
1991        // exclusively by GhHttp.  It can never originate from agent/runtime
1992        // failures, so treating it as a GitHub-context marker is safe even
1993        // when upstream wrapping strips the "GitHub API" prefix.
1994        || lower.contains("circuit-breaker")
1995        || lower.contains("circuit breaker")
1996}
1997
1998/// Extract the HTTP status code from a GhHttp error string.
1999///
2000/// GhHttp formats errors as: `"GitHub API POST https://... failed (NNN): body"`
2001/// This parses the numeric status code from that format.
2002fn extract_github_http_status(err_str: &str) -> Option<u16> {
2003    let marker = "failed (";
2004    let start = err_str.find(marker)? + marker.len();
2005    let rest = &err_str[start..];
2006    let end = rest.find(')')?;
2007    rest[..end].parse().ok()
2008}
2009
2010/// Append the Orch attribution footer to an existing PR body if not already present.
2011///
2012/// Called when the agent created the PR directly (bypassing orch's
2013/// `create_pr_if_needed`), so the footer was never added by `build_pr_body`.
2014async fn append_pr_footer_if_missing(
2015    gh: &GhHttp,
2016    repo: &str,
2017    pr_number: u64,
2018    task_id: &str,
2019    agent: &str,
2020    model: Option<&str>,
2021) {
2022    let pr = match gh.get_pr(repo, pr_number).await {
2023        Ok(pr) => pr,
2024        Err(e) => {
2025            tracing::debug!(task_id, error = %e, "failed to fetch PR for footer check");
2026            return;
2027        }
2028    };
2029
2030    let body = pr.body.unwrap_or_default();
2031    if body.contains("via [Orch]") {
2032        return; // Footer already present
2033    }
2034
2035    let model_str = model.map(|m| format!(" using `{m}`")).unwrap_or_default();
2036    let task_ref = format_task_ref(task_id);
2037    let footer = format!(
2038        "\n\n---\n*Task {task_ref} · Created by {agent}[bot] via [Orch](https://github.com/gabrielkoerich/orch){model_str}*"
2039    );
2040    let new_body = format!("{body}{footer}");
2041
2042    match gh.update_pr_body(repo, pr_number, &new_body).await {
2043        Err(e) => {
2044            tracing::warn!(task_id, error = %e, "failed to append footer to PR (non-fatal)");
2045        }
2046        _ => {
2047            tracing::info!(
2048                task_id,
2049                pr = pr_number,
2050                "appended attribution footer to agent-created PR"
2051            );
2052        }
2053    }
2054}
2055
2056/// Get the current branch name.
2057pub(crate) async fn get_current_branch(dir: &Path) -> String {
2058    let output = Command::new("git")
2059        .args(["branch", "--show-current"])
2060        .current_dir(dir)
2061        .output_with_context()
2062        .await;
2063
2064    match output {
2065        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
2066        _ => String::new(),
2067    }
2068}
2069
2070/// Count the number of changed files in the working directory.
2071pub async fn count_changed_files(dir: &Path) -> anyhow::Result<usize> {
2072    // Count modified and new files (excluding deleted)
2073    let output = Command::new("git")
2074        .args(["status", "--porcelain"])
2075        .current_dir(dir)
2076        .output_with_context()
2077        .await?;
2078
2079    let status_output = String::from_utf8_lossy(&output.stdout);
2080    let count = status_output
2081        .lines()
2082        .filter(|line| {
2083            let prefix = line.get(0..2).unwrap_or("");
2084            // Count modified (M), added (A), renamed (R), copied (C), untracked (??)
2085            prefix.starts_with('M')
2086                || prefix.starts_with('A')
2087                || prefix.starts_with('R')
2088                || prefix.starts_with('C')
2089                || prefix.starts_with('?')
2090        })
2091        .count();
2092
2093    Ok(count)
2094}
2095
2096/// Check if there are unpushed commits.
2097/// Returns `(remote_exists, has_unpushed_commits)`.
2098///
2099/// - `remote_exists` — whether `origin/<branch>` is known to the local repo.
2100/// - `has_unpushed_commits` — whether there are local commits not yet on the
2101///   remote.  When the remote branch doesn't exist the comparison is against
2102///   `origin/<default_branch>` so we can still detect new work.
2103async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
2104    // Check if remote tracking branch exists
2105    let remote_exists = Command::new("git")
2106        .args(["rev-parse", &format!("origin/{branch}")])
2107        .current_dir(dir)
2108        .output_with_context()
2109        .await
2110        .is_ok_and(|o| o.status.success());
2111
2112    let compare_ref = if remote_exists {
2113        format!("origin/{branch}..{branch}")
2114    } else {
2115        // Compare the named branch, not HEAD: a protected checkout still pushes the task branch
2116        format!("origin/{default_branch}..{branch}")
2117    };
2118
2119    tracing::debug!(
2120        branch,
2121        compare_ref,
2122        remote_exists,
2123        "checking unpushed commits"
2124    );
2125
2126    let output = Command::new("git")
2127        .args(["log", &compare_ref, "--oneline"])
2128        .current_dir(dir)
2129        .output_with_context()
2130        .await;
2131
2132    let has_unpushed = match output {
2133        Ok(o) if o.status.success() => {
2134            let out = String::from_utf8_lossy(&o.stdout);
2135            let has = !out.trim().is_empty();
2136            tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
2137            has
2138        }
2139        _ => {
2140            tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
2141            // If we can't determine, assume there ARE commits to push
2142            // (better to attempt push and let it fail than silently skip)
2143            true
2144        }
2145    };
2146
2147    (remote_exists, has_unpushed)
2148}
2149
2150#[cfg(test)]
2151mod tests {
2152    use std::env;
2153    use std::fs;
2154    #[cfg(unix)]
2155    use std::os::unix::fs::PermissionsExt;
2156    #[cfg(unix)]
2157    use std::os::unix::process::ExitStatusExt;
2158    use std::path::PathBuf;
2159    use std::process;
2160
2161    use super::*;
2162
2163    #[test]
2164    fn pr_create_error_display() {
2165        let err = PrCreateError::ApiError(anyhow::anyhow!("test error"));
2166        assert_eq!(format!("{err}"), "GitHub API error: test error");
2167    }
2168
2169    #[test]
2170    fn pr_create_error_from_anyhow() {
2171        let anyhow_err = anyhow::anyhow!("source error");
2172        let pr_err: PrCreateError = anyhow_err.into();
2173        assert!(matches!(pr_err, PrCreateError::ApiError(_)));
2174    }
2175
2176    #[test]
2177    fn git_env_never_signs_with_or_without_a_token() {
2178        for env in [
2179            build_git_auth_env_for_token(None),
2180            build_git_auth_env_for_token(Some("ghp_testtoken1234".into())),
2181        ] {
2182            let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
2183            let count: usize = get("GIT_CONFIG_COUNT").unwrap().parse().unwrap();
2184            let config: Vec<(String, String)> = (0..count)
2185                .map(|n| {
2186                    (
2187                        get(&format!("GIT_CONFIG_KEY_{n}")).unwrap(),
2188                        get(&format!("GIT_CONFIG_VALUE_{n}")).unwrap(),
2189                    )
2190                })
2191                .collect();
2192            assert!(config.contains(&("commit.gpgsign".into(), "false".into())));
2193            assert!(config.contains(&("tag.gpgsign".into(), "false".into())));
2194        }
2195    }
2196
2197    #[test]
2198    fn build_git_auth_env_without_token_falls_back_to_ssh_https_conversion() {
2199        // Pass None directly to test the no-token path without relying on env vars
2200        // or the gh CLI, keeping the test deterministic regardless of local auth state.
2201        let env = build_git_auth_env_for_token(None);
2202
2203        // When no token is available the fallback must include the SSH insteadOf rule.
2204        // The SSH→HTTPS conversion sets the target URL (the rewrite destination) to git@github.com:.
2205        let has_ssh_rule = env
2206            .iter()
2207            .any(|(k, v)| k == "GIT_CONFIG_VALUE_0" && v == "git@github.com:");
2208        assert!(
2209            has_ssh_rule,
2210            "expected SSH insteadOf fallback (value is git@github.com:), got: {env:?}"
2211        );
2212    }
2213
2214    #[test]
2215    fn build_git_auth_env_with_token_covers_both_ssh_and_https() {
2216        // Pass a pre-built token directly to test the token path without touching env vars.
2217        let env = build_git_auth_env_for_token(Some("ghp_testtoken1234".into()));
2218
2219        // Must contain the token in the auth URL (the token is in the value of GIT_CONFIG_KEY_N).
2220        let has_token = env
2221            .iter()
2222            .any(|(_, v)| v.contains("x-access-token:ghp_testtoken1234@github.com"));
2223        assert!(has_token, "expected token in auth URL, got: {env:?}");
2224        // Must cover HTTPS origins (GIT_CONFIG_VALUE_0 is the HTTPS source URL).
2225        let has_https_rule = env
2226            .iter()
2227            .any(|(k, v)| k == "GIT_CONFIG_VALUE_0" && v == "https://github.com/");
2228        assert!(
2229            has_https_rule,
2230            "expected HTTPS insteadOf rule, got: {env:?}"
2231        );
2232        // Must cover SSH origins (GIT_CONFIG_VALUE_1 is the SSH source URL).
2233        let has_ssh_rule = env
2234            .iter()
2235            .any(|(k, v)| k == "GIT_CONFIG_VALUE_1" && v == "git@github.com:");
2236        assert!(has_ssh_rule, "expected SSH insteadOf rule, got: {env:?}");
2237    }
2238
2239    #[test]
2240    fn find_stash_ref_by_hash_returns_matching_reference() {
2241        let stash_list = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa stash@{1}\nbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb stash@{0}";
2242
2243        assert_eq!(
2244            find_stash_ref_by_hash(stash_list, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"),
2245            Some("stash@{1}".to_string())
2246        );
2247        assert_eq!(
2248            find_stash_ref_by_hash(stash_list, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"),
2249            Some("stash@{0}".to_string())
2250        );
2251    }
2252
2253    #[test]
2254    fn find_stash_ref_by_hash_returns_none_when_missing_or_malformed() {
2255        let stash_list = "malformed-line\naaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa stash@{2}";
2256
2257        assert_eq!(
2258            find_stash_ref_by_hash(stash_list, "cccccccccccccccccccccccccccccccccccccccc"),
2259            None
2260        );
2261        assert_eq!(find_stash_ref_by_hash("", "anything"), None);
2262    }
2263
2264    #[test]
2265    fn push_needs_rebase_detects_common_rejections() {
2266        assert!(push_needs_rebase(
2267            "! [rejected] branch -> branch (fetch first)"
2268        ));
2269        assert!(push_needs_rebase("non-fast-forward update was rejected"));
2270        assert!(push_needs_rebase(
2271            "push rejected because the remote contains work"
2272        ));
2273    }
2274
2275    #[test]
2276    fn is_transient_network_error_detects_lfs_locks_timeout() {
2277        let lfs_err = "Post \"https://x-access-token:***@github.com/o/r.git/info/lfs/locks/verify\": dial tcp 140.82.112.4:443: i/o timeout";
2278        assert!(is_transient_network_error(lfs_err));
2279        assert!(is_transient_network_error(
2280            "dial tcp 140.82.112.4:443: connect: connection refused"
2281        ));
2282        assert!(is_transient_network_error(
2283            "read tcp 10.0.0.1:51234->140.82.112.4:443: read: connection reset by peer"
2284        ));
2285    }
2286
2287    #[test]
2288    fn is_transient_network_error_rejects_ref_rejections() {
2289        assert!(!is_transient_network_error(
2290            "! [rejected] branch -> branch (fetch first)"
2291        ));
2292        assert!(!is_transient_network_error(
2293            "remote: error: GH006: Protected branch update failed"
2294        ));
2295    }
2296
2297    #[test]
2298    fn is_transient_network_error_detects_github_remote_failure() {
2299        assert!(is_transient_network_error(
2300            "remote: fatal error in commit_refs\n ! [remote rejected] b -> b (failure)"
2301        ));
2302        assert!(is_transient_network_error(
2303            "! [remote rejected] b -> b (failure)"
2304        ));
2305    }
2306
2307    #[test]
2308    fn missing_remote_ref_error_is_detected() {
2309        let err = anyhow::anyhow!("failed to fetch origin/b: fatal: couldn't find remote ref b");
2310        assert!(is_missing_remote_ref_error(&err));
2311        assert!(!is_missing_remote_ref_error(&anyhow::anyhow!("conflict")));
2312    }
2313
2314    #[test]
2315    fn sanitize_push_error_strips_url_credentials() {
2316        // Shape must not look like a real GitHub PAT so gitleaks stays clean
2317        let raw = "Post \"https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git/info/lfs/locks/verify\": dial tcp 140.82.112.4:443: i/o timeout";
2318        let sanitized = sanitize_push_error(raw);
2319        assert!(!sanitized.contains("test-secret-1234567890abcdef"));
2320        assert!(sanitized.contains("://***@github.com"));
2321        assert!(sanitized.contains("i/o timeout"));
2322    }
2323
2324    #[test]
2325    fn sanitize_push_error_strips_fetch_url_credentials() {
2326        let raw = "fatal: unable to access 'https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git/': The requested URL returned error: 403";
2327        let sanitized = sanitize_push_error(raw);
2328        assert!(!sanitized.contains("test-secret-1234567890abcdef"));
2329        assert!(sanitized.contains("://***@github.com"));
2330        assert!(sanitized.contains("403"));
2331        assert_eq!(sanitized, sanitize_push_error(&sanitized));
2332    }
2333
2334    #[cfg(unix)]
2335    #[test]
2336    fn sanitize_git_output_strips_url_credentials_from_both_streams() {
2337        let output = process::Output {
2338            status: process::ExitStatus::from_raw(0),
2339            stdout: b"To https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git\n"
2340                .to_vec(),
2341            stderr: b"fatal: unable to access 'https://x-access-token:test-secret-1234567890abcdef@github.com/o/r.git/'\n"
2342                .to_vec(),
2343        };
2344        let sanitized = sanitize_git_output(output);
2345        let stdout = String::from_utf8_lossy(&sanitized.stdout);
2346        let stderr = String::from_utf8_lossy(&sanitized.stderr);
2347        assert!(!stdout.contains("test-secret-1234567890abcdef"));
2348        assert!(!stderr.contains("test-secret-1234567890abcdef"));
2349        assert!(stdout.contains("://***@github.com"));
2350        assert!(stderr.contains("://***@github.com"));
2351    }
2352
2353    #[test]
2354    fn extract_github_http_status_parses_ghhttp_error_format() {
2355        let err =
2356            "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (502): Bad Gateway";
2357        assert_eq!(extract_github_http_status(err), Some(502));
2358
2359        let err500 = "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (500): Internal Server Error";
2360        assert_eq!(extract_github_http_status(err500), Some(500));
2361
2362        let err422 = "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (422): Unprocessable Entity";
2363        assert_eq!(extract_github_http_status(err422), Some(422));
2364
2365        let not_github = "some other error";
2366        assert_eq!(extract_github_http_status(not_github), None);
2367    }
2368
2369    #[test]
2370    fn is_transient_github_error_matches_5xx_only() {
2371        let err502 =
2372            "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (502): Bad Gateway";
2373        assert!(is_transient_github_error(err502));
2374
2375        let err503 = "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (503): Service Unavailable";
2376        assert!(is_transient_github_error(err503));
2377
2378        let err422 = "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (422): Unprocessable Entity";
2379        assert!(!is_transient_github_error(err422));
2380
2381        let err404 =
2382            "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (404): Not Found";
2383        assert!(!is_transient_github_error(err404));
2384    }
2385
2386    #[test]
2387    fn is_transient_github_error_matches_connection_errors() {
2388        // Connection-related transient errors
2389        assert!(is_transient_github_error("connection refused"));
2390        assert!(is_transient_github_error("Connection reset by peer"));
2391        assert!(is_transient_github_error("broken pipe"));
2392        assert!(is_transient_github_error("connection closed unexpectedly"));
2393        assert!(is_transient_github_error(
2394            "transport error: connection lost"
2395        ));
2396
2397        // Git/Curl connect-failure patterns (review push failures)
2398        assert!(is_transient_github_error(
2399            "fatal: unable to access 'https://github.com/owner/repo.git/': Failed to connect to github.com port 443 after 20990 ms: Couldn't connect to server"
2400        ));
2401        assert!(is_transient_github_error(
2402            "Failed to connect to github.com port 443: Connection timed out"
2403        ));
2404        assert!(is_transient_github_error(
2405            "Failed to connect to github.com port 443: Connection refused"
2406        ));
2407        assert!(is_transient_github_error(
2408            "curl: (7) Failed to connect to github.com port 443: Couldn't connect to server"
2409        ));
2410        assert!(is_transient_github_error(
2411            "fatal: unable to access 'https://github.com/owner/repo.git/': Couldn't connect to server"
2412        ));
2413    }
2414
2415    #[test]
2416    fn is_transient_github_error_matches_dns_errors() {
2417        // DNS resolution failures
2418        assert!(is_transient_github_error("dns error: failed to lookup"));
2419        assert!(is_transient_github_error("failed to resolve hostname"));
2420        assert!(is_transient_github_error("name resolution failed"));
2421        assert!(is_transient_github_error("no such host: api.github.com"));
2422    }
2423
2424    #[test]
2425    fn is_transient_github_error_matches_tls_errors() {
2426        // TLS/SSL handshake failures
2427        assert!(is_transient_github_error("tls handshake failed"));
2428        assert!(is_transient_github_error("certificate verification failed"));
2429        assert!(is_transient_github_error("ssl error: unknown ca"));
2430    }
2431
2432    #[test]
2433    fn is_transient_github_error_matches_network_unreachable() {
2434        // Network unreachable errors
2435        assert!(is_transient_github_error("network is unreachable"));
2436        assert!(is_transient_github_error("host unreachable"));
2437        assert!(is_transient_github_error(
2438            "temporary failure in name resolution"
2439        ));
2440    }
2441
2442    #[test]
2443    fn is_transient_github_error_matches_eof_errors() {
2444        // EOF/connection dropped errors
2445        assert!(is_transient_github_error("unexpected eof while reading"));
2446        assert!(is_transient_github_error("unexpected end of file"));
2447    }
2448
2449    #[test]
2450    fn is_transient_github_error_matches_rate_limit() {
2451        // Rate limit errors (transient with cooldown)
2452        assert!(is_transient_github_error("rate limit exceeded"));
2453        assert!(is_transient_github_error("429 Too Many Requests"));
2454        assert!(is_transient_github_error("too many requests, retry later"));
2455    }
2456
2457    #[test]
2458    fn is_transient_github_error_matches_timeout() {
2459        // Timeout errors
2460        assert!(is_transient_github_error("operation timeout"));
2461        assert!(is_transient_github_error("request timeout"));
2462    }
2463
2464    #[test]
2465    fn is_transient_github_error_rejects_non_transient() {
2466        // Non-transient errors should not match
2467        assert!(!is_transient_github_error("permission denied"));
2468        assert!(!is_transient_github_error("file not found"));
2469        assert!(!is_transient_github_error("invalid argument"));
2470        assert!(!is_transient_github_error("authentication failed"));
2471        assert!(!is_transient_github_error("bad credentials"));
2472    }
2473
2474    #[test]
2475    fn is_transient_github_api_error_requires_github_context() {
2476        assert!(is_transient_github_api_error(
2477            "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (502): Bad Gateway"
2478        ));
2479        assert!(is_transient_github_api_error(
2480            "gh error: transport error: connection reset by peer"
2481        ));
2482        assert!(is_transient_github_api_error(
2483            "push failed: fatal: unable to access 'https://github.com/owner/repo.git/': Failed to connect to github.com port 443 after 20990 ms: Couldn't connect to server"
2484        ));
2485        assert!(!is_transient_github_api_error(
2486            "codex failed: Reconnecting... (stream disconnected before completion: Broken pipe)"
2487        ));
2488        assert!(!is_transient_github_api_error(
2489            "agent stream failed: failed to connect to local relay"
2490        ));
2491    }
2492
2493    #[test]
2494    fn is_transient_github_api_error_matches_circuit_breaker() {
2495        // Full message from GhHttp
2496        assert!(is_transient_github_api_error(
2497            "GitHub API transient 5xx circuit-breaker active for 240s"
2498        ));
2499        // Wrapped through PrCreateError + response_handler
2500        assert!(is_transient_github_api_error(
2501            "create PR failed: GitHub API error: GitHub API transient 5xx circuit-breaker active"
2502        ));
2503        // Shortened form where upstream wrapping stripped the "GitHub API" prefix —
2504        // circuit-breaker alone must still be recognized as a GitHub signal.
2505        assert!(is_transient_github_api_error(
2506            "create PR failed: circuit-breaker"
2507        ));
2508        // Spaced variant
2509        assert!(is_transient_github_api_error(
2510            "create PR failed: circuit breaker tripped"
2511        ));
2512    }
2513
2514    #[tokio::test]
2515    async fn auto_commit_unstages_files_on_commit_failure() {
2516        // Create a temp git repo with one initial commit
2517        let dir = env::temp_dir().join(format!("orch_test_auto_commit_{}", process::id()));
2518        let _ = fs::remove_dir_all(&dir);
2519        fs::create_dir_all(&dir).unwrap();
2520
2521        // Init repo
2522        let _ = Command::new("git")
2523            .args(["init"])
2524            .current_dir(&dir)
2525            .output()
2526            .await;
2527        let _ = Command::new("git")
2528            .args(["config", "user.email", "test@test.com"])
2529            .current_dir(&dir)
2530            .output()
2531            .await;
2532        let _ = Command::new("git")
2533            .args(["config", "user.name", "Test"])
2534            .current_dir(&dir)
2535            .output()
2536            .await;
2537        // Create initial file and commit
2538        fs::write(dir.join("init.txt"), "init").unwrap();
2539        let _ = Command::new("git")
2540            .args(["add", "init.txt"])
2541            .current_dir(&dir)
2542            .output()
2543            .await;
2544        let _ = Command::new("git")
2545            .args(["-c", "commit.gpgsign=false", "commit", "-m", "init"])
2546            .current_dir(&dir)
2547            .output()
2548            .await;
2549
2550        // Create a new file (unstaged)
2551        fs::write(dir.join("new_file.txt"), "content").unwrap();
2552
2553        // Verify has_changes sees it
2554        assert!(has_changes(&dir).await);
2555
2556        // auto_commit should return false (no git user.email configured for this
2557        // test repo would cause commit to fail if we hadn't set it, but we did —
2558        // so this test verifies the happy path too).
2559        // For this test, the commit should succeed since we set user.email/name.
2560        let result = auto_commit(
2561            &dir,
2562            "1",
2563            "Test title",
2564            "test",
2565            1,
2566            super::super::commit::When::Always,
2567        )
2568        .await;
2569        assert!(result.unwrap());
2570
2571        // Verify no changes remain
2572        assert!(!has_changes(&dir).await);
2573
2574        // Cleanup
2575        let _ = fs::remove_dir_all(&dir);
2576    }
2577
2578    #[tokio::test]
2579    async fn auto_commit_ignores_repo_signing_config() {
2580        // Repo demands signing via a signer that always fails — auto_commit
2581        // must still commit (it passes -c commit.gpgsign=false)
2582        let dir = env::temp_dir().join(format!("orch_test_auto_commit_gpg_{}", process::id()));
2583        let _ = fs::remove_dir_all(&dir);
2584        fs::create_dir_all(&dir).unwrap();
2585
2586        for args in [
2587            vec!["init"],
2588            vec!["config", "user.email", "test@test.com"],
2589            vec!["config", "user.name", "Test"],
2590            vec!["config", "commit.gpgsign", "true"],
2591            vec!["config", "gpg.program", "/usr/bin/false"],
2592        ] {
2593            let _ = Command::new("git")
2594                .args(&args)
2595                .current_dir(&dir)
2596                .output()
2597                .await;
2598        }
2599        fs::write(dir.join("init.txt"), "init").unwrap();
2600        let _ = Command::new("git")
2601            .args(["add", "init.txt"])
2602            .current_dir(&dir)
2603            .output()
2604            .await;
2605        let _ = Command::new("git")
2606            .args(["-c", "commit.gpgsign=false", "commit", "-m", "init"])
2607            .current_dir(&dir)
2608            .output()
2609            .await;
2610
2611        fs::write(dir.join("signed_off.txt"), "content").unwrap();
2612        assert!(has_changes(&dir).await);
2613
2614        let result = auto_commit(
2615            &dir,
2616            "3",
2617            "Test title",
2618            "test",
2619            1,
2620            super::super::commit::When::Always,
2621        )
2622        .await;
2623        assert!(result.unwrap());
2624        assert!(!has_changes(&dir).await);
2625
2626        let _ = fs::remove_dir_all(&dir);
2627    }
2628
2629    #[tokio::test]
2630    async fn auto_commit_unstages_on_pre_commit_hook_failure() {
2631        // Create a temp git repo where commit always fails (via pre-commit hook)
2632        let dir = env::temp_dir().join(format!("orch_test_auto_commit_hook_{}", process::id()));
2633        let _ = fs::remove_dir_all(&dir);
2634        fs::create_dir_all(&dir).unwrap();
2635
2636        // Init repo
2637        let _ = Command::new("git")
2638            .args(["init"])
2639            .current_dir(&dir)
2640            .output()
2641            .await;
2642        let _ = Command::new("git")
2643            .args(["config", "user.email", "test@test.com"])
2644            .current_dir(&dir)
2645            .output()
2646            .await;
2647        let _ = Command::new("git")
2648            .args(["config", "user.name", "Test"])
2649            .current_dir(&dir)
2650            .output()
2651            .await;
2652        // Create initial commit
2653        fs::write(dir.join("init.txt"), "init").unwrap();
2654        let _ = Command::new("git")
2655            .args(["add", "init.txt"])
2656            .current_dir(&dir)
2657            .output()
2658            .await;
2659        let _ = Command::new("git")
2660            .args(["-c", "commit.gpgsign=false", "commit", "-m", "init"])
2661            .current_dir(&dir)
2662            .output()
2663            .await;
2664
2665        // Install a pre-commit hook that always fails
2666        let hooks_dir = dir.join(".git/hooks");
2667        fs::create_dir_all(&hooks_dir).unwrap();
2668        fs::write(hooks_dir.join("pre-commit"), "#!/bin/sh\nexit 1\n").unwrap();
2669        #[cfg(unix)]
2670        {
2671            let mut perms = fs::metadata(hooks_dir.join("pre-commit"))
2672                .unwrap()
2673                .permissions();
2674            perms.set_mode(0o755);
2675            fs::set_permissions(hooks_dir.join("pre-commit"), perms).unwrap();
2676        }
2677
2678        // Create a new file
2679        fs::write(dir.join("staged_file.txt"), "content").unwrap();
2680
2681        // Verify has_changes sees it
2682        assert!(has_changes(&dir).await);
2683
2684        // auto_commit should return false (pre-commit hook blocks it)
2685        let result = auto_commit(
2686            &dir,
2687            "2",
2688            "Test title",
2689            "test",
2690            1,
2691            super::super::commit::When::Always,
2692        )
2693        .await;
2694        assert!(!result.unwrap());
2695
2696        // After commit failure, files should be unstaged — has_changes should
2697        // still return true because the unstaged file is still there.
2698        assert!(has_changes(&dir).await);
2699
2700        // Verify the file is NOT staged (git diff --cached --quiet should succeed)
2701        let cached = Command::new("git")
2702            .args(["diff", "--cached", "--quiet"])
2703            .current_dir(&dir)
2704            .status()
2705            .await;
2706        assert!(
2707            cached.is_ok_and(|s| s.success()),
2708            "files should be unstaged after commit failure"
2709        );
2710
2711        // Cleanup
2712        let _ = fs::remove_dir_all(&dir);
2713    }
2714
2715    #[test]
2716    fn is_workflow_scope_error_detects_backtick_format() {
2717        let err = "! [remote rejected] branch -> branch (refusing to allow an OAuth App to create or update workflow `.github/workflows/ci.yml` without `workflow` scope)";
2718        assert!(is_workflow_scope_error(err));
2719    }
2720
2721    #[test]
2722    fn is_workflow_scope_error_detects_single_quote_format() {
2723        let err = "refusing to allow an OAuth App to create or update workflow '.github/workflows/ci.yml' without 'workflow' scope";
2724        assert!(is_workflow_scope_error(err));
2725    }
2726
2727    #[test]
2728    fn is_workflow_scope_error_detects_refusing_to_allow_variant() {
2729        let err = "remote: refusing to allow a Personal Access Token to create or update workflow `.github/workflows/scan.yml` without `workflow` scope";
2730        assert!(is_workflow_scope_error(err));
2731    }
2732
2733    #[test]
2734    fn is_workflow_scope_error_rejects_unrelated_errors() {
2735        assert!(!is_workflow_scope_error("non-fast-forward"));
2736        assert!(!is_workflow_scope_error("permission denied"));
2737        assert!(!is_workflow_scope_error("authentication failed"));
2738        assert!(!is_workflow_scope_error("rejected"));
2739    }
2740
2741    #[tokio::test]
2742    async fn strip_workflow_files_removes_workflow_from_commits() {
2743        // Create a temp git repo simulating the scenario
2744        let dir = env::temp_dir().join(format!("orch_test_strip_wf_{}", process::id()));
2745        let _ = fs::remove_dir_all(&dir);
2746        fs::create_dir_all(&dir).unwrap();
2747
2748        // Init repo with initial commit
2749        let _ = Command::new("git")
2750            .args(["init"])
2751            .current_dir(&dir)
2752            .output()
2753            .await;
2754        let _ = Command::new("git")
2755            .args(["config", "user.email", "test@test.com"])
2756            .current_dir(&dir)
2757            .output()
2758            .await;
2759        let _ = Command::new("git")
2760            .args(["config", "user.name", "Test"])
2761            .current_dir(&dir)
2762            .output()
2763            .await;
2764        fs::write(dir.join("init.txt"), "init").unwrap();
2765        let _ = Command::new("git")
2766            .args(["add", "."])
2767            .current_dir(&dir)
2768            .output()
2769            .await;
2770        let _ = Command::new("git")
2771            .args(["-c", "commit.gpgsign=false", "commit", "-m", "init"])
2772            .current_dir(&dir)
2773            .output()
2774            .await;
2775
2776        // Create a "remote" by adding the repo as its own origin (for rev-list)
2777        let _ = Command::new("git")
2778            .args(["remote", "add", "origin", dir.to_str().unwrap()])
2779            .current_dir(&dir)
2780            .output()
2781            .await;
2782        let _ = Command::new("git")
2783            .args(["fetch", "origin"])
2784            .current_dir(&dir)
2785            .output()
2786            .await;
2787
2788        // Create a branch off main
2789        let _ = Command::new("git")
2790            .args(["checkout", "-b", "feature"])
2791            .current_dir(&dir)
2792            .output()
2793            .await;
2794
2795        // Add both a normal file and a workflow file
2796        fs::write(dir.join("feature.txt"), "feature work").unwrap();
2797        let wf_dir = dir.join(".github/workflows");
2798        fs::create_dir_all(&wf_dir).unwrap();
2799        fs::write(wf_dir.join("ci.yml"), "name: CI\non: push").unwrap();
2800        let _ = Command::new("git")
2801            .args(["add", "."])
2802            .current_dir(&dir)
2803            .output()
2804            .await;
2805        let _ = Command::new("git")
2806            .args([
2807                "-c",
2808                "commit.gpgsign=false",
2809                "commit",
2810                "-m",
2811                "add feature and workflow",
2812            ])
2813            .current_dir(&dir)
2814            .output()
2815            .await;
2816
2817        // Get the default branch name
2818        let branch_out = Command::new("git")
2819            .args(["rev-parse", "--abbrev-ref", "origin/HEAD"])
2820            .current_dir(&dir)
2821            .output()
2822            .await;
2823        // Fallback to "main" if origin/HEAD is not set
2824        let default_branch = branch_out.ok().filter(|o| o.status.success()).map_or_else(
2825            || "main".to_string(),
2826            |o| {
2827                String::from_utf8_lossy(&o.stdout)
2828                    .trim()
2829                    .strip_prefix("origin/")
2830                    .unwrap_or("main")
2831                    .to_string()
2832            },
2833        );
2834
2835        // Strip workflow files
2836        let stripped = strip_workflow_files(&dir, &default_branch).await.unwrap();
2837        assert!(stripped, "should have stripped workflow files");
2838
2839        // Verify workflow file is no longer in the committed tree
2840        let ls_output = Command::new("git")
2841            .args(["ls-tree", "-r", "--name-only", "HEAD"])
2842            .current_dir(&dir)
2843            .output()
2844            .await
2845            .unwrap();
2846        let files = String::from_utf8_lossy(&ls_output.stdout);
2847        assert!(
2848            !files.contains(".github/workflows/ci.yml"),
2849            "workflow file should be removed from commits"
2850        );
2851        assert!(
2852            files.contains("feature.txt"),
2853            "non-workflow files should be preserved"
2854        );
2855
2856        // Cleanup
2857        let _ = fs::remove_dir_all(&dir);
2858    }
2859
2860    #[tokio::test]
2861    async fn strip_workflow_files_returns_false_when_no_workflows() {
2862        let dir = env::temp_dir().join(format!("orch_test_strip_wf_none_{}", process::id()));
2863        let _ = fs::remove_dir_all(&dir);
2864        fs::create_dir_all(&dir).unwrap();
2865
2866        // Init repo
2867        let _ = Command::new("git")
2868            .args(["init"])
2869            .current_dir(&dir)
2870            .output()
2871            .await;
2872        let _ = Command::new("git")
2873            .args(["config", "user.email", "test@test.com"])
2874            .current_dir(&dir)
2875            .output()
2876            .await;
2877        let _ = Command::new("git")
2878            .args(["config", "user.name", "Test"])
2879            .current_dir(&dir)
2880            .output()
2881            .await;
2882        fs::write(dir.join("init.txt"), "init").unwrap();
2883        let _ = Command::new("git")
2884            .args(["add", "."])
2885            .current_dir(&dir)
2886            .output()
2887            .await;
2888        let _ = Command::new("git")
2889            .args(["-c", "commit.gpgsign=false", "commit", "-m", "init"])
2890            .current_dir(&dir)
2891            .output()
2892            .await;
2893
2894        let _ = Command::new("git")
2895            .args(["remote", "add", "origin", dir.to_str().unwrap()])
2896            .current_dir(&dir)
2897            .output()
2898            .await;
2899        let _ = Command::new("git")
2900            .args(["fetch", "origin"])
2901            .current_dir(&dir)
2902            .output()
2903            .await;
2904
2905        let _ = Command::new("git")
2906            .args(["checkout", "-b", "feature2"])
2907            .current_dir(&dir)
2908            .output()
2909            .await;
2910
2911        // Only non-workflow files
2912        fs::write(dir.join("feature.txt"), "feature").unwrap();
2913        let _ = Command::new("git")
2914            .args(["add", "."])
2915            .current_dir(&dir)
2916            .output()
2917            .await;
2918        let _ = Command::new("git")
2919            .args([
2920                "-c",
2921                "commit.gpgsign=false",
2922                "commit",
2923                "-m",
2924                "add feature only",
2925            ])
2926            .current_dir(&dir)
2927            .output()
2928            .await;
2929
2930        let stripped = strip_workflow_files(&dir, "main").await.unwrap();
2931        assert!(!stripped, "should not strip when no workflow files exist");
2932
2933        // Cleanup
2934        let _ = fs::remove_dir_all(&dir);
2935    }
2936
2937    #[test]
2938    fn is_invalid_base_error_detects_base_invalid() {
2939        assert!(is_invalid_base_error(
2940            "GitHub API POST https://api.github.com/repos/foo/bar/pulls failed (422): {\"errors\":[{\"resource\":\"PullRequest\",\"field\":\"base\",\"code\":\"invalid\"}]}"
2941        ));
2942        assert!(is_invalid_base_error(
2943            "GitHub API POST .../pulls failed (422): Base field is invalid"
2944        ));
2945    }
2946
2947    #[test]
2948    fn is_invalid_base_error_rejects_non_base_errors() {
2949        // No-commits error should NOT match
2950        assert!(!is_invalid_base_error(
2951            "GitHub API POST .../pulls failed (422): No commits between main and branch"
2952        ));
2953        // Head invalid should NOT match
2954        assert!(!is_invalid_base_error(
2955            "GitHub API POST .../pulls failed (422): head is not a valid ref"
2956        ));
2957        // Transient 5xx should NOT match
2958        assert!(!is_invalid_base_error(
2959            "GitHub API POST .../pulls failed (502): Bad Gateway"
2960        ));
2961        // 404 should NOT match
2962        assert!(!is_invalid_base_error(
2963            "GitHub API POST .../pulls failed (404): Not Found"
2964        ));
2965    }
2966
2967    fn pr_summary(body: &str) -> &str {
2968        let rest = body
2969            .strip_prefix("## Summary\n\n")
2970            .expect("PR body starts with ## Summary");
2971        rest.split("\n\n").next().unwrap()
2972    }
2973
2974    fn assert_no_push_or_pr_creation(body: &str) {
2975        let lower = body.to_ascii_lowercase();
2976        for needle in [
2977            "git push",
2978            "gh pr create",
2979            "did not push",
2980            "couldn't push",
2981            "could not push",
2982            "push was denied",
2983            "push was blocked",
2984            "push permission",
2985            "nothing is on the remote",
2986            "open the pr",
2987        ] {
2988            assert!(
2989                !lower.contains(needle),
2990                "PR body still contains {needle:?}:\n{body}"
2991            );
2992        }
2993    }
2994
2995    #[test]
2996    fn build_pr_body_strips_push_and_pr_creation_statements() {
2997        let examples = [
2998            (
2999                concat!(
3000                    "Added the lesson list page. ",
3001                    "I did not push or open the PR, because the push was blocked on a permission prompt. ",
3002                    "Run `git push -u origin HEAD`, then `gh pr create`.",
3003                ),
3004                "Added the lesson list page.",
3005            ),
3006            (
3007                "It is committed locally ... The push was denied, so nothing is on the remote yet.",
3008                "It is committed locally",
3009            ),
3010            (
3011                concat!(
3012                    "Fixed the quiz scoring. ",
3013                    "I couldn't push it because the push permission was denied.",
3014                ),
3015                "Fixed the quiz scoring.",
3016            ),
3017        ];
3018        for (summary, work) in examples {
3019            let body = build_pr_body(
3020                "Fix the widget",
3021                summary,
3022                &[
3023                    "Wrote the lesson list".into(),
3024                    "Could not push because the push permission was denied".into(),
3025                ],
3026                &["Run `git push -u origin HEAD`".into()],
3027                &[],
3028                "16",
3029                "claude",
3030                None,
3031            );
3032            assert_eq!(pr_summary(&body), work);
3033            assert!(body.contains("Wrote the lesson list"));
3034            assert!(!body.contains("### Remaining"));
3035            assert_no_push_or_pr_creation(&body);
3036        }
3037    }
3038
3039    #[test]
3040    fn build_pr_body_keeps_summary_without_push_text() {
3041        let summary = "Added retry logic for GitHub 5xx errors.";
3042        let accomplished = vec!["Extracted the PR body builder".into()];
3043        let remaining = vec!["Watch CI after merge".into()];
3044        let body = build_pr_body(
3045            "Fix the widget",
3046            summary,
3047            &accomplished,
3048            &remaining,
3049            &["src/engine/runner/git_ops.rs".into()],
3050            "16",
3051            "claude",
3052            Some("sonnet"),
3053        );
3054        assert_eq!(pr_summary(&body), summary);
3055        assert!(body.contains("### What was done\n\n- Extracted the PR body builder\n"));
3056        assert!(body.contains("### Remaining\n\n- Watch CI after merge\n"));
3057        assert!(body.contains("- `src/engine/runner/git_ops.rs`"));
3058        assert!(body.contains(" using `sonnet`"));
3059        assert!(body.contains("Closes #16"));
3060    }
3061
3062    #[test]
3063    fn build_pr_body_keeps_a_ci_bootstrap_issue_open() {
3064        let body = build_pr_body(
3065            "CI-01 Set up CI and tests",
3066            "Added the workflow.",
3067            &[],
3068            &[],
3069            &[],
3070            "16",
3071            "claude",
3072            None,
3073        );
3074        assert!(!body.contains("Closes #"));
3075        assert!(!body.contains("Resolves #"));
3076    }
3077
3078    fn sh_git(dir: &Path, args: &[&str]) {
3079        let out = process::Command::new("git")
3080            .args([
3081                "-c",
3082                "commit.gpgsign=false",
3083                "-c",
3084                "user.name=T",
3085                "-c",
3086                "user.email=t@t",
3087            ])
3088            .args(args)
3089            .current_dir(dir)
3090            .output()
3091            .unwrap();
3092        assert!(
3093            out.status.success(),
3094            "git {args:?}: {}",
3095            String::from_utf8_lossy(&out.stderr)
3096        );
3097    }
3098
3099    fn commit_file(dir: &Path, name: &str) {
3100        fs::write(dir.join(name), name).unwrap();
3101        sh_git(dir, &["add", name]);
3102        sh_git(dir, &["commit", "-m", name]);
3103    }
3104
3105    /**
3106     * The review rebases its branch on main and force-pushes with lease. When GitHub's
3107     * "Update branch" moved the remote branch after the last fetch, the lease is stale and
3108     * the push was rejected, which blocked approved work (#3783)
3109     **/
3110    #[tokio::test]
3111    async fn push_branch_recovers_from_stale_lease_after_remote_moved() {
3112        let temp = tempfile::TempDir::new().unwrap();
3113        let bare = temp.path().join("origin.git");
3114        let a = temp.path().join("a");
3115        let b = temp.path().join("b");
3116        fs::create_dir_all(&bare).unwrap();
3117        sh_git(&bare, &["init", "--bare", "-b", "main"]);
3118        sh_git(temp.path(), &["clone", bare.to_str().unwrap(), "a"]);
3119        // push_branch's own rebase commits, and CI runners have no global identity
3120        sh_git(&a, &["config", "user.name", "T"]);
3121        sh_git(&a, &["config", "user.email", "t@t"]);
3122        commit_file(&a, "base.txt");
3123        sh_git(&a, &["push", "origin", "main"]);
3124        sh_git(&a, &["checkout", "-b", "feat"]);
3125        commit_file(&a, "feature.txt");
3126        sh_git(&a, &["push", "-u", "origin", "feat"]);
3127
3128        sh_git(temp.path(), &["clone", bare.to_str().unwrap(), "b"]);
3129        commit_file(&b, "main-change.txt");
3130        sh_git(&b, &["push", "origin", "main"]);
3131        sh_git(&b, &["checkout", "feat"]);
3132        commit_file(&b, "update-branch.txt");
3133        sh_git(&b, &["push", "origin", "feat"]);
3134
3135        // A only fetches main, so its view of origin/feat is stale when it rewrites feat
3136        sh_git(&a, &["fetch", "origin", "main"]);
3137        sh_git(&a, &["rebase", "origin/main"]);
3138
3139        assert!(push_branch(&a, "feat", "main").await.unwrap());
3140
3141        sh_git(&b, &["fetch", "origin", "feat"]);
3142        sh_git(&b, &["checkout", "origin/feat"]);
3143        for name in [
3144            "base.txt",
3145            "feature.txt",
3146            "main-change.txt",
3147            "update-branch.txt",
3148        ] {
3149            assert!(b.join(name).exists(), "remote feat lost {name}");
3150        }
3151    }
3152
3153    #[test]
3154    fn stale_lease_error_matches_git_messages() {
3155        assert!(is_stale_lease_error(
3156            "! [rejected] feat -> feat (stale info)"
3157        ));
3158        assert!(is_stale_lease_error(
3159            "! [rejected] feat -> feat (remote ref updated since checkout)"
3160        ));
3161        assert!(!is_stale_lease_error(
3162            "! [rejected] feat -> feat (fetch first)"
3163        ));
3164    }
3165
3166    fn git_ok(dir: &Path, args: &[&str]) {
3167        let out = process::Command::new("git")
3168            .args(args)
3169            .current_dir(dir)
3170            .output()
3171            .unwrap();
3172        assert!(
3173            out.status.success(),
3174            "git {} failed: {}",
3175            args.join(" "),
3176            String::from_utf8_lossy(&out.stderr)
3177        );
3178    }
3179
3180    fn git_sha(dir: &Path, rev: &str) -> String {
3181        let out = process::Command::new("git")
3182            .args(["rev-parse", rev])
3183            .current_dir(dir)
3184            .output()
3185            .unwrap();
3186        assert!(out.status.success(), "git rev-parse {rev} failed");
3187        String::from_utf8_lossy(&out.stdout).trim().to_string()
3188    }
3189
3190    fn init_identity(dir: &Path) {
3191        git_ok(dir, &["config", "user.email", "test@example.com"]);
3192        git_ok(dir, &["config", "user.name", "Test"]);
3193        git_ok(dir, &["config", "commit.gpgsign", "false"]);
3194    }
3195
3196    fn write_commit(dir: &Path, file: &str, body: &str, msg: &str) {
3197        fs::write(dir.join(file), body).unwrap();
3198        git_ok(dir, &["add", file]);
3199        git_ok(dir, &["commit", "-m", msg]);
3200    }
3201
3202    /// A bare origin with `main` and a pushed `feature`, and a clone `a` on `feature`
3203    fn publish_feature(root: &Path) -> (PathBuf, PathBuf) {
3204        let (bare, a) = publish_default(root, "main");
3205        git_ok(&a, &["checkout", "-b", "feature"]);
3206        write_commit(&a, "feature.txt", "feature\n", "feature");
3207        git_ok(&a, &["push", "-u", "origin", "feature"]);
3208        (bare, a)
3209    }
3210
3211    fn publish_default(root: &Path, default_branch: &str) -> (PathBuf, PathBuf) {
3212        let bare = root.join("bare.git");
3213        let a = root.join("a");
3214        git_ok(root, &["init", "-b", default_branch, a.to_str().unwrap()]);
3215        init_identity(&a);
3216        write_commit(&a, "README.md", "base\n", "base");
3217        git_ok(
3218            root,
3219            &[
3220                "init",
3221                "--bare",
3222                "-b",
3223                default_branch,
3224                bare.to_str().unwrap(),
3225            ],
3226        );
3227        git_ok(&a, &["remote", "add", "origin", bare.to_str().unwrap()]);
3228        git_ok(&a, &["push", "-u", "origin", default_branch]);
3229        (bare, a)
3230    }
3231
3232    fn clone_on(root: &Path, bare: &Path, name: &str, branch: &str) -> PathBuf {
3233        let dir = root.join(name);
3234        git_ok(
3235            root,
3236            &["clone", bare.to_str().unwrap(), dir.to_str().unwrap()],
3237        );
3238        init_identity(&dir);
3239        if branch != "main" {
3240            git_ok(
3241                &dir,
3242                &["checkout", "-b", branch, &format!("origin/{branch}")],
3243            );
3244        }
3245
3246        dir
3247    }
3248
3249    #[tokio::test]
3250    async fn leased_force_push_does_not_replace_a_newer_remote_tip() {
3251        let root = tempfile::tempdir().unwrap();
3252        let (bare, a) = publish_feature(root.path());
3253        let b = clone_on(root.path(), &bare, "b", "feature");
3254        record_push_lease(&b, "feature", "main").await;
3255        let leased = git_sha(&b, "refs/remotes/origin/feature");
3256
3257        write_commit(&a, "feature.txt", "from a\n", "from a");
3258        git_ok(&a, &["push", "origin", "feature"]);
3259        let newer = git_sha(&a, "HEAD");
3260
3261        git_ok(&b, &["fetch", "origin"]);
3262        write_commit(&b, "feature.txt", "from b\n", "from b");
3263        let pushed = push_branch(&b, "feature", "main").await;
3264        assert!(
3265            pushed.is_err(),
3266            "force push should be rejected, got {pushed:?}"
3267        );
3268        assert_eq!(git_sha(&bare, "refs/heads/feature"), newer);
3269
3270        // A retry sees the fetched tip, which HEAD does not contain, so the lease stays
3271        record_push_lease(&b, "feature", "main").await;
3272        assert_eq!(read_push_lease(&b, "feature").await, Some(leased));
3273        let again = push_branch(&b, "feature", "main").await;
3274        assert!(
3275            again.is_err(),
3276            "second force push should stay rejected, got {again:?}"
3277        );
3278        assert_eq!(git_sha(&bare, "refs/heads/feature"), newer);
3279    }
3280
3281    #[tokio::test]
3282    async fn leased_force_push_allows_rewrite_of_the_recorded_tip() {
3283        let root = tempfile::tempdir().unwrap();
3284        let (bare, a) = publish_feature(root.path());
3285        record_push_lease(&a, "feature", "main").await;
3286        fs::write(a.join("feature.txt"), "rewritten\n").unwrap();
3287        git_ok(&a, &["commit", "-am", "--amend", "-m", "feature rewritten"]);
3288
3289        let pushed = push_branch(&a, "feature", "main").await;
3290        assert!(
3291            pushed.is_ok(),
3292            "rewrite of the leased tip should push, got {pushed:?}"
3293        );
3294        assert_eq!(git_sha(&bare, "refs/heads/feature"), git_sha(&a, "HEAD"));
3295        assert_eq!(
3296            read_push_lease(&a, "feature").await,
3297            Some(git_sha(&a, "HEAD"))
3298        );
3299    }
3300
3301    #[tokio::test]
3302    async fn push_after_update_branch_merge_force_pushes_the_rebased_branch() {
3303        let root = tempfile::tempdir().unwrap();
3304        let (bare, a) = publish_feature(root.path());
3305        record_push_lease(&a, "feature", "main").await;
3306
3307        // GitHub's "Update branch": main moves, then main is merged into feature on the remote
3308        let c = clone_on(root.path(), &bare, "c", "main");
3309        write_commit(&c, "main.txt", "main\n", "main moves");
3310        git_ok(&c, &["push", "origin", "main"]);
3311        git_ok(&c, &["checkout", "-b", "feature", "origin/feature"]);
3312        git_ok(
3313            &c,
3314            &[
3315                "merge",
3316                "--no-ff",
3317                "-m",
3318                "Merge main into feature",
3319                "origin/main",
3320            ],
3321        );
3322        git_ok(&c, &["push", "origin", "feature"]);
3323
3324        rebase_on_default(&a, "main").await;
3325        write_commit(&a, "feature.txt", "review fix\n", "review fix");
3326        let pushed = push_branch(&a, "feature", "main").await;
3327        assert!(
3328            pushed.is_ok(),
3329            "push after update-branch should succeed, got {pushed:?}"
3330        );
3331        assert_eq!(git_sha(&bare, "refs/heads/feature"), git_sha(&a, "HEAD"));
3332    }
3333
3334    #[tokio::test]
3335    async fn agent_push_moves_the_lease_to_a_tip_head_contains() {
3336        let root = tempfile::tempdir().unwrap();
3337        let (_bare, a) = publish_feature(root.path());
3338        record_push_lease(&a, "feature", "main").await;
3339
3340        write_commit(&a, "feature.txt", "agent step\n", "agent step");
3341        git_ok(&a, &["push", "origin", "feature"]);
3342        record_push_lease(&a, "feature", "main").await;
3343        assert_eq!(
3344            read_push_lease(&a, "feature").await,
3345            Some(git_sha(&a, "HEAD"))
3346        );
3347    }
3348
3349    #[tokio::test]
3350    async fn record_push_lease_skips_the_default_branch() {
3351        let root = tempfile::tempdir().unwrap();
3352        let (_bare, a) = publish_feature(root.path());
3353        git_ok(&a, &["checkout", "main"]);
3354        record_push_lease(&a, "main", "main").await;
3355        assert_eq!(read_push_lease(&a, "main").await, None);
3356    }
3357
3358    /// GitHub's "Update branch" by merge: main moves, then main is merged into feature
3359    fn github_update_by_merge(root: &Path, bare: &Path, name: &str) {
3360        let c = clone_on(root, bare, name, "main");
3361        write_commit(&c, "main.txt", "main\n", "main moves");
3362        git_ok(&c, &["push", "origin", "main"]);
3363        git_ok(&c, &["checkout", "-b", "feature", "origin/feature"]);
3364        git_ok(
3365            &c,
3366            &[
3367                "merge",
3368                "--no-ff",
3369                "-m",
3370                "Merge main into feature",
3371                "origin/main",
3372            ],
3373        );
3374        git_ok(&c, &["push", "origin", "feature"]);
3375    }
3376
3377    /// GitHub's "Update branch" by rebase: main moves, then feature is replayed on it
3378    fn github_update_by_rebase(root: &Path, bare: &Path, name: &str) -> PathBuf {
3379        let c = clone_on(root, bare, name, "main");
3380        write_commit(&c, "main.txt", "main\n", "main moves");
3381        git_ok(&c, &["push", "origin", "main"]);
3382        git_ok(&c, &["checkout", "-b", "feature", "origin/feature"]);
3383        git_ok(&c, &["rebase", "origin/main"]);
3384        git_ok(&c, &["push", "--force", "origin", "feature"]);
3385        c
3386    }
3387
3388    fn remote_has(root: &Path, bare: &Path, file: &str) -> bool {
3389        let check = root.join("check");
3390        if !check.exists() {
3391            git_ok(
3392                root,
3393                &["clone", bare.to_str().unwrap(), check.to_str().unwrap()],
3394            );
3395        }
3396
3397        git_ok(&check, &["fetch", "origin"]);
3398        git_ok(&check, &["checkout", "--detach", "origin/feature"]);
3399        check.join(file).exists()
3400    }
3401
3402    #[tokio::test]
3403    async fn push_after_update_branch_rebase_force_pushes_the_rebased_branch() {
3404        let root = tempfile::tempdir().unwrap();
3405        let (bare, a) = publish_feature(root.path());
3406        record_push_lease(&a, "feature", "main").await;
3407        github_update_by_rebase(root.path(), &bare, "c");
3408
3409        rebase_on_default(&a, "main").await;
3410        write_commit(&a, "fix.txt", "review fix\n", "review fix");
3411        let pushed = push_branch(&a, "feature", "main").await;
3412        assert!(
3413            pushed.is_ok(),
3414            "push after a rebase update should succeed, got {pushed:?}"
3415        );
3416        assert_eq!(git_sha(&bare, "refs/heads/feature"), git_sha(&a, "HEAD"));
3417    }
3418
3419    #[tokio::test]
3420    async fn rebase_update_with_a_foreign_commit_keeps_the_foreign_commit() {
3421        let root = tempfile::tempdir().unwrap();
3422        let (bare, a) = publish_feature(root.path());
3423        record_push_lease(&a, "feature", "main").await;
3424        let c = github_update_by_rebase(root.path(), &bare, "c");
3425        write_commit(&c, "other.txt", "other machine\n", "other machine");
3426        git_ok(&c, &["push", "origin", "feature"]);
3427
3428        rebase_on_default(&a, "main").await;
3429        write_commit(&a, "fix.txt", "review fix\n", "review fix");
3430        let _ = push_branch(&a, "feature", "main").await;
3431        assert!(
3432            remote_has(root.path(), &bare, "other.txt"),
3433            "the other machine's commit was dropped"
3434        );
3435    }
3436
3437    #[tokio::test]
3438    async fn merge_of_a_non_default_branch_is_not_a_github_update() {
3439        let root = tempfile::tempdir().unwrap();
3440        let (bare, a) = publish_feature(root.path());
3441        record_push_lease(&a, "feature", "main").await;
3442        let c = clone_on(root.path(), &bare, "c", "feature");
3443        git_ok(&c, &["checkout", "-b", "side", "origin/main"]);
3444        write_commit(&c, "side.txt", "side\n", "side work");
3445        git_ok(&c, &["checkout", "feature"]);
3446        git_ok(&c, &["merge", "--no-ff", "-m", "Merge side", "side"]);
3447        git_ok(&c, &["push", "origin", "feature"]);
3448
3449        rebase_on_default(&a, "main").await;
3450        write_commit(&a, "fix.txt", "review fix\n", "review fix");
3451        let _ = push_branch(&a, "feature", "main").await;
3452        assert!(
3453            remote_has(root.path(), &bare, "side.txt"),
3454            "the merged side branch was dropped"
3455        );
3456    }
3457
3458    #[tokio::test]
3459    async fn update_merge_on_top_of_a_foreign_push_keeps_the_foreign_commit() {
3460        let root = tempfile::tempdir().unwrap();
3461        let (bare, a) = publish_feature(root.path());
3462        record_push_lease(&a, "feature", "main").await;
3463        let c = clone_on(root.path(), &bare, "c", "feature");
3464        write_commit(&c, "other.txt", "other machine\n", "other machine");
3465        git_ok(&c, &["push", "origin", "feature"]);
3466        github_update_by_merge(root.path(), &bare, "d");
3467
3468        rebase_on_default(&a, "main").await;
3469        write_commit(&a, "fix.txt", "review fix\n", "review fix");
3470        let _ = push_branch(&a, "feature", "main").await;
3471        assert!(
3472            remote_has(root.path(), &bare, "other.txt"),
3473            "the other machine's commit was dropped"
3474        );
3475    }
3476
3477    #[tokio::test]
3478    async fn force_push_leased_accepts_github_updates() {
3479        for by_rebase in [false, true] {
3480            let root = tempfile::tempdir().unwrap();
3481            let (bare, a) = publish_feature(root.path());
3482            record_push_lease(&a, "feature", "main").await;
3483            if by_rebase {
3484                github_update_by_rebase(root.path(), &bare, "c");
3485            } else {
3486                github_update_by_merge(root.path(), &bare, "c");
3487            }
3488
3489            git_ok(&a, &["fetch", "origin"]);
3490            git_ok(&a, &["rebase", "origin/main"]);
3491            let pushed = force_push_leased(&a, "feature", "main").await;
3492            assert!(pushed.is_ok(), "by_rebase={by_rebase}: {pushed:?}");
3493            assert_eq!(git_sha(&bare, "refs/heads/feature"), git_sha(&a, "HEAD"));
3494        }
3495    }
3496
3497    #[tokio::test]
3498    async fn force_push_leased_accepts_a_branch_recreated_at_the_default_head() {
3499        let root = tempfile::tempdir().unwrap();
3500        let (bare, a) = publish_feature(root.path());
3501        record_push_lease(&a, "feature", "main").await;
3502        let c = clone_on(root.path(), &bare, "c", "main");
3503        write_commit(&c, "feature.txt", "main version\n", "main moves");
3504        git_ok(&c, &["push", "origin", "main"]);
3505        git_ok(
3506            &c,
3507            &["push", "origin", "main:refs/heads/feature", "--force"],
3508        );
3509
3510        git_ok(&a, &["fetch", "origin"]);
3511        record_push_lease(&a, "feature", "main").await;
3512        fs::write(a.join("feature.txt"), "feature rewritten\n").unwrap();
3513        git_ok(&a, &["commit", "-am", "rewrite"]);
3514        let pushed = force_push_leased(&a, "feature", "main").await;
3515        assert!(pushed.is_ok(), "{pushed:?}");
3516        assert_eq!(git_sha(&bare, "refs/heads/feature"), git_sha(&a, "HEAD"));
3517    }
3518
3519    #[tokio::test]
3520    async fn clear_push_lease_drops_the_recorded_lease() {
3521        let root = tempfile::tempdir().unwrap();
3522        let (_bare, a) = publish_feature(root.path());
3523        record_push_lease(&a, "feature", "main").await;
3524        assert!(read_push_lease(&a, "feature").await.is_some());
3525        clear_push_lease(&a, "feature").await;
3526        assert_eq!(read_push_lease(&a, "feature").await, None);
3527    }
3528
3529    #[tokio::test]
3530    async fn force_push_leased_refuses_a_foreign_push() {
3531        let root = tempfile::tempdir().unwrap();
3532        let (bare, a) = publish_feature(root.path());
3533        record_push_lease(&a, "feature", "main").await;
3534        let c = clone_on(root.path(), &bare, "c", "feature");
3535        write_commit(&c, "other.txt", "other machine\n", "other machine");
3536        git_ok(&c, &["push", "origin", "feature"]);
3537        let foreign = git_sha(&c, "HEAD");
3538
3539        git_ok(&a, &["fetch", "origin"]);
3540        record_push_lease(&a, "feature", "main").await;
3541        fs::write(a.join("feature.txt"), "rewritten\n").unwrap();
3542        git_ok(&a, &["commit", "-am", "--amend", "-m", "rewritten"]);
3543        assert!(force_push_leased(&a, "feature", "main").await.is_err());
3544        assert_eq!(git_sha(&bare, "refs/heads/feature"), foreign);
3545    }
3546
3547    #[tokio::test]
3548    async fn force_push_leased_refuses_a_branch_created_after_an_absent_lease() {
3549        let root = tempfile::tempdir().unwrap();
3550        let (bare, a) = publish_feature(root.path());
3551        git_ok(&a, &["checkout", "-b", "fresh", "main"]);
3552        record_push_lease(&a, "fresh", "main").await;
3553        assert_eq!(
3554            read_push_lease(&a, "fresh").await.as_deref(),
3555            Some(LEASE_ABSENT)
3556        );
3557
3558        let c = clone_on(root.path(), &bare, "c", "main");
3559        git_ok(&c, &["checkout", "-b", "fresh"]);
3560        write_commit(&c, "other.txt", "other machine\n", "other machine");
3561        git_ok(&c, &["push", "origin", "fresh"]);
3562        let foreign = git_sha(&c, "HEAD");
3563
3564        git_ok(&a, &["fetch", "origin"]);
3565        write_commit(&a, "mine.txt", "mine\n", "mine");
3566        assert!(force_push_leased(&a, "fresh", "main").await.is_err());
3567        assert_eq!(git_sha(&bare, "refs/heads/fresh"), foreign);
3568    }
3569
3570    #[tokio::test]
3571    async fn first_push_records_the_pushed_head_as_the_lease() {
3572        let root = tempfile::tempdir().unwrap();
3573        let (_bare, a) = publish_feature(root.path());
3574        git_ok(&a, &["checkout", "-b", "fresh", "main"]);
3575        write_commit(&a, "mine.txt", "mine\n", "mine");
3576        assert!(push_branch(&a, "fresh", "main").await.unwrap());
3577        assert_eq!(
3578            read_push_lease(&a, "fresh").await,
3579            Some(git_sha(&a, "HEAD"))
3580        );
3581    }
3582
3583    #[tokio::test]
3584    async fn missing_lease_falls_back_to_the_fetched_tip_and_counts_it() {
3585        let root = tempfile::tempdir().unwrap();
3586        let (_bare, a) = publish_feature(root.path());
3587        let before = LEASE_FALLBACKS.load(Ordering::Relaxed);
3588        let expected = expected_force_sha(&a, "feature", "main").await.unwrap();
3589        assert_eq!(expected, git_sha(&a, "refs/remotes/origin/feature"));
3590        assert!(LEASE_FALLBACKS.load(Ordering::Relaxed) > before);
3591    }
3592
3593    #[tokio::test]
3594    async fn agent_push_then_foreign_push_keeps_the_agent_tip_as_lease() {
3595        let root = tempfile::tempdir().unwrap();
3596        let (bare, a) = publish_feature(root.path());
3597        record_push_lease(&a, "feature", "main").await;
3598        write_commit(&a, "step.txt", "agent step\n", "agent step");
3599        git_ok(&a, &["push", "origin", "feature"]);
3600        let agent_tip = git_sha(&a, "HEAD");
3601
3602        let c = clone_on(root.path(), &bare, "c", "feature");
3603        write_commit(&c, "other.txt", "other machine\n", "other machine");
3604        git_ok(&c, &["push", "origin", "feature"]);
3605
3606        // Callers record before they fetch, so the lease moves to the agent's push and no further
3607        record_push_lease(&a, "feature", "main").await;
3608        git_ok(&a, &["fetch", "origin"]);
3609        record_push_lease(&a, "feature", "main").await;
3610        assert_eq!(read_push_lease(&a, "feature").await, Some(agent_tip));
3611        let foreign = git_sha(&bare, "refs/heads/feature");
3612        git_ok(&a, &["commit", "--amend", "-m", "agent step rewritten"]);
3613        assert!(force_push_leased(&a, "feature", "main").await.is_err());
3614        assert_eq!(git_sha(&bare, "refs/heads/feature"), foreign);
3615    }
3616
3617    #[tokio::test]
3618    async fn branch_without_remote_and_head_without_twins_are_not_github_updates() {
3619        let root = tempfile::tempdir().unwrap();
3620        let (_bare, a) = publish_feature(root.path());
3621        let lease = git_sha(&a, "HEAD");
3622        let main = git_sha(&a, "origin/main");
3623        // A tip equal to main has nothing in base..tip, which must not count as a rebase update
3624        assert!(!is_github_branch_update(&a, &main, &lease, "main").await);
3625        assert!(
3626            !is_github_branch_update(
3627                &a,
3628                "0000000000000000000000000000000000000000",
3629                &lease,
3630                "main"
3631            )
3632            .await
3633        );
3634    }
3635
3636    #[test]
3637    fn resolve_push_branch_picks_the_task_branch_when_checkout_is_main() {
3638        assert_eq!(
3639            resolve_push_branch("main", "feature", "main").unwrap(),
3640            "feature"
3641        );
3642        assert_eq!(
3643            resolve_push_branch("main", "feature", "develop").unwrap(),
3644            "feature"
3645        );
3646    }
3647
3648    #[test]
3649    fn resolve_push_branch_refuses_a_develop_default_checkout() {
3650        let err = resolve_push_branch("develop", "develop", "develop")
3651            .unwrap_err()
3652            .to_string();
3653        assert!(err.contains("push refused"), "{err}");
3654        assert!(err.contains("develop"), "{err}");
3655    }
3656
3657    #[test]
3658    fn resolve_push_branch_picks_the_task_branch_when_checkout_is_default_develop() {
3659        assert_eq!(
3660            resolve_push_branch("develop", "feature", "develop").unwrap(),
3661            "feature"
3662        );
3663    }
3664
3665    #[tokio::test]
3666    async fn push_branch_refuses_when_checkout_is_default_develop() {
3667        let root = tempfile::tempdir().unwrap();
3668        let (bare, a) = publish_default(root.path(), "develop");
3669        write_commit(&a, "secret.txt", "must not land on develop\n", "local");
3670        let before = git_sha(&bare, "refs/heads/develop");
3671
3672        let err = push_branch(&a, "develop", "develop")
3673            .await
3674            .unwrap_err()
3675            .to_string();
3676        assert!(err.contains("push refused"), "{err}");
3677        assert_eq!(git_sha(&bare, "refs/heads/develop"), before);
3678    }
3679
3680    #[tokio::test]
3681    async fn push_branch_pushes_the_task_branch_when_checkout_is_main() {
3682        let root = tempfile::tempdir().unwrap();
3683        let (bare, a) = publish_feature(root.path());
3684        write_commit(&a, "more.txt", "more\n", "more");
3685        let feature_sha = git_sha(&a, "feature");
3686        git_ok(&a, &["checkout", "main"]);
3687
3688        assert!(push_branch(&a, "feature", "main").await.unwrap());
3689        assert_eq!(git_sha(&bare, "refs/heads/feature"), feature_sha);
3690        assert_ne!(git_sha(&bare, "refs/heads/main"), feature_sha);
3691        assert_eq!(
3692            read_push_lease(&a, "feature").await.as_deref(),
3693            Some(feature_sha.as_str())
3694        );
3695    }
3696
3697    #[tokio::test]
3698    async fn push_branch_pushes_the_task_branch_when_checkout_is_default_develop() {
3699        let root = tempfile::tempdir().unwrap();
3700        let (bare, a) = publish_default(root.path(), "develop");
3701        git_ok(&a, &["checkout", "-b", "feature"]);
3702        write_commit(&a, "feature.txt", "feature\n", "feature");
3703        let feature_sha = git_sha(&a, "feature");
3704        git_ok(&a, &["checkout", "develop"]);
3705
3706        assert!(push_branch(&a, "feature", "develop").await.unwrap());
3707        assert_eq!(git_sha(&bare, "refs/heads/feature"), feature_sha);
3708        assert_ne!(git_sha(&bare, "refs/heads/develop"), feature_sha);
3709    }
3710}