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