Skip to main content

orch/engine/runner/git_ops/
push.rs

1//! Pushing branches with leases and classifying push errors
2
3use super::{
4    check_push_needed, get_current_branch, git, is_workflow_scope_error, rebase_on_branch,
5    strip_workflow_files,
6};
7use crate::cmd::CommandErrorContext;
8use crate::github::http;
9use crate::security;
10use regex::Regex;
11use std::path::Path;
12use std::process::Output;
13use std::sync::LazyLock;
14use std::sync::atomic::{AtomicU64, Ordering};
15use std::time::Duration;
16use tokio::process::Command;
17use tokio::time;
18
19pub(super) const LEASE_ABSENT: &str = "absent";
20
21/// Force pushes that found no recorded lease and fell back to the fetched tip
22pub(super) static LEASE_FALLBACKS: AtomicU64 = AtomicU64::new(0);
23
24async fn git_stdout(dir: &Path, args: &[&str]) -> Option<String> {
25    let out = Command::new("git")
26        .args(args)
27        .current_dir(dir)
28        .output_with_context()
29        .await
30        .ok()?;
31    if !out.status.success() {
32        return None;
33    }
34
35    Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
36}
37
38fn lease_key(branch: &str) -> String {
39    format!("branch.{branch}.orchPushLease")
40}
41
42pub(super) async fn read_push_lease(dir: &Path, branch: &str) -> Option<String> {
43    git_stdout(dir, &["config", "--get", &lease_key(branch)]).await
44}
45
46async fn write_push_lease(dir: &Path, branch: &str, value: &str) {
47    if git_stdout(dir, &["config", &lease_key(branch), value])
48        .await
49        .is_none()
50    {
51        tracing::warn!(branch, "failed to record push lease");
52    }
53}
54
55async fn remote_tracking_sha(dir: &Path, branch: &str) -> Option<String> {
56    let rev = format!("refs/remotes/origin/{branch}");
57    git_stdout(dir, &["rev-parse", "--verify", "--quiet", &rev])
58        .await
59        .filter(|sha| http::is_full_commit_sha(sha))
60}
61
62async fn is_ancestor(dir: &Path, ancestor: &str, descendant: &str) -> bool {
63    git_stdout(dir, &["merge-base", "--is-ancestor", ancestor, descendant])
64        .await
65        .is_some()
66}
67
68/// Record the remote tip this worktree may replace, before a fetch moves `origin/<branch>`. The lease
69/// moves only to a tip HEAD contains, such as the agent's own push, never to one only fetched
70pub(crate) async fn record_push_lease(dir: &Path, branch: &str, default_branch: &str) {
71    if branch.is_empty() || branch == default_branch {
72        return;
73    }
74
75    let tip = remote_tracking_sha(dir, branch).await;
76    match (read_push_lease(dir, branch).await, tip) {
77        (Some(lease), Some(tip)) if lease != tip && is_ancestor(dir, &tip, "HEAD").await => {
78            write_push_lease(dir, branch, &tip).await;
79        }
80        (Some(_), _) => {}
81        (None, tip) => {
82            let expect = tip.unwrap_or_else(|| LEASE_ABSENT.to_string());
83            write_push_lease(dir, branch, &expect).await;
84        }
85    }
86}
87
88/// Drop the lease of a branch whose remote was deleted, so the next dispatch records one for the recreated branch
89pub(crate) async fn clear_push_lease(dir: &Path, branch: &str) {
90    let _ = git_stdout(dir, &["config", "--unset", &lease_key(branch)]).await;
91}
92
93async fn note_pushed_head(dir: &Path, branch: &str) {
94    let spec = format!("refs/heads/{branch}");
95    if let Some(sha) = git_stdout(dir, &["rev-parse", "--verify", &spec]).await {
96        write_push_lease(dir, branch, &sha).await;
97    }
98}
99
100/// True when `tip` is GitHub's "Update branch" of `lease`: a merge with first parent `lease` and
101/// second parent on the default branch, or a rebase whose commits all have a twin in `lease`
102pub(super) async fn is_github_branch_update(
103    dir: &Path,
104    tip: &str,
105    lease: &str,
106    default_branch: &str,
107) -> bool {
108    let base = format!("origin/{default_branch}");
109    let Some(line) = git_stdout(dir, &["rev-list", "--parents", "-n", "1", tip]).await else {
110        return false;
111    };
112    let parents: Vec<&str> = line.split_whitespace().skip(1).collect();
113    if let [first, second] = parents[..] {
114        return first == lease && is_ancestor(dir, second, &base).await;
115    }
116
117    // `git cherry` marks each commit in base..tip with `-` when `lease` holds the same patch
118    let Some(cherry) = git_stdout(dir, &["cherry", lease, tip, &base]).await else {
119        return false;
120    };
121    is_ancestor(dir, &base, tip).await
122        && !cherry.is_empty()
123        && cherry.lines().all(|l| l.starts_with('-'))
124}
125
126pub(super) async fn expected_force_sha(
127    dir: &Path,
128    branch: &str,
129    default_branch: &str,
130) -> anyhow::Result<String> {
131    let tip = remote_tracking_sha(dir, branch).await;
132    let base = format!("origin/{default_branch}");
133    if let Some(tip) = &tip {
134        // A tip the default branch already holds has no commits of its own, so a force push loses nothing
135        if is_ancestor(dir, tip, &base).await {
136            tracing::info!(branch, %tip, "remote tip is contained in the default branch, leasing it");
137            return Ok(tip.clone());
138        }
139    }
140
141    match read_push_lease(dir, branch).await {
142        Some(lease) if lease == LEASE_ABSENT => anyhow::bail!(
143            "force push rejected: remote branch {branch} was absent when the lease was recorded"
144        ),
145        Some(lease) => match tip {
146            Some(tip)
147                if tip != lease
148                    && is_github_branch_update(dir, &tip, &lease, default_branch).await =>
149            {
150                tracing::info!(branch, %lease, %tip, "remote tip is GitHub's update of the leased branch, leasing it");
151                Ok(tip)
152            }
153            _ => Ok(lease),
154        },
155        None => {
156            let Some(tip) = tip else {
157                anyhow::bail!("force push rejected: no remote sha recorded for {branch}");
158            };
159            let fallbacks = LEASE_FALLBACKS.fetch_add(1, Ordering::Relaxed) + 1;
160            tracing::warn!(
161                branch,
162                fallbacks,
163                "no push lease recorded, using the fetched origin tip"
164            );
165            Ok(tip)
166        }
167    }
168}
169
170/// Force-push `branch` only if the remote still holds the leased sha
171pub(crate) async fn force_push_leased(
172    dir: &Path,
173    branch: &str,
174    default_branch: &str,
175) -> anyhow::Result<()> {
176    let expected = expected_force_sha(dir, branch, default_branch).await?;
177    let lease = format!("--force-with-lease={branch}:{expected}");
178    tracing::info!(branch, expected_sha = %expected, "force-pushing with an expected remote sha");
179    let output = git()
180        .await
181        .args([
182            "-c",
183            "lfs.locksverify=false",
184            "push",
185            &lease,
186            "-u",
187            "origin",
188            branch,
189        ])
190        .current_dir(dir)
191        .kill_on_drop(true)
192        .output_with_context()
193        .await?;
194    if output.status.success() {
195        note_pushed_head(dir, branch).await;
196        return Ok(());
197    }
198
199    let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
200    anyhow::bail!("{stderr}")
201}
202
203/// True for a branch orch must never push: the repo default, plus `main` and `master`
204fn is_protected_push_branch(name: &str, default_branch: &str) -> bool {
205    !name.is_empty() && (name == default_branch || name == "main" || name == "master")
206}
207
208/// Pick the ref to push. A protected checkout falls back to the task branch when that name is safe
209pub(super) fn resolve_push_branch<'a>(
210    current: &'a str,
211    branch: &'a str,
212    default_branch: &str,
213) -> anyhow::Result<&'a str> {
214    let chosen = if !current.is_empty() && !is_protected_push_branch(current, default_branch) {
215        current
216    } else if !branch.is_empty() && !is_protected_push_branch(branch, default_branch) {
217        branch
218    } else {
219        let name = if current.is_empty() { branch } else { current };
220        if name.is_empty() {
221            anyhow::bail!("cannot push: branch name is empty");
222        }
223        anyhow::bail!("push refused: '{name}' is a default branch");
224    };
225    Ok(chosen)
226}
227
228/// Push the branch to origin.
229///
230/// Returns `Ok(true)` when the branch is on the remote, `Ok(false)` when the push was skipped,
231/// and `Err` when the push was refused (default branch) or failed
232pub async fn push_branch(dir: &Path, branch: &str, default_branch: &str) -> anyhow::Result<bool> {
233    let current = get_current_branch(dir).await;
234    let branch_to_push = resolve_push_branch(&current, branch, default_branch)?;
235
236    // Check if there are commits to push and whether the remote branch exists
237    let (remote_exists, has_unpushed) =
238        check_push_needed(dir, branch_to_push, default_branch).await;
239    if remote_exists && !has_unpushed {
240        // Remote already has this branch and it's up to date — nothing to push.
241        // Return true so callers know the branch IS on the remote and PR creation
242        // is safe to attempt (e.g. a PR may already exist or can be created).
243        tracing::debug!(
244            branch = branch_to_push,
245            "remote branch exists and is up to date, skipping push"
246        );
247        note_pushed_head(dir, branch_to_push).await;
248        return Ok(true);
249    }
250    if !remote_exists && !has_unpushed {
251        // Branch doesn't exist on the remote and has no commits ahead of the
252        // default branch — push it anyway so the branch is created on the remote.
253        // PR creation will then fail with "No commits between …" (422) which is
254        // handled downstream, rather than with "head invalid" (422) which is
255        // harder to distinguish from a real error.
256        tracing::debug!(
257            branch = branch_to_push,
258            "remote branch missing with no new commits — pushing to create it on remote"
259        );
260    }
261
262    tracing::info!(branch = branch_to_push, "pushing branch");
263
264    // First attempt: normal push (no force).
265    // lfs.locksverify=false skips the auxiliary LFS locks/verify roundtrip in
266    // the pre-push hook; agents never hold LFS locks, and a transient timeout
267    // on that endpoint must not fail the whole push.
268    // A 2-minute timeout prevents an indefinitely-stalled push from blocking
269    // post-processing and triggering a stuck-task re-dispatch race.
270    let output = time::timeout(
271        Duration::from_secs(120),
272        git()
273            .await
274            .args([
275                "-c",
276                "lfs.locksverify=false",
277                "push",
278                "-u",
279                "origin",
280                branch_to_push,
281            ])
282            .kill_on_drop(true)
283            .current_dir(dir)
284            .output(),
285    )
286    .await
287    .map_err(|_| anyhow::anyhow!("git push timed out after 120s"))??;
288
289    if output.status.success() {
290        tracing::info!(branch = branch_to_push, "push succeeded");
291        note_pushed_head(dir, branch_to_push).await;
292        return Ok(true);
293    }
294
295    let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
296
297    // Transient network blip (timeout, reset) rather than a ref rejection —
298    // retry the identical push once before classifying the run as failed.
299    if is_transient_network_error(&stderr) {
300        tracing::warn!(
301            branch = branch_to_push,
302            stderr = %stderr,
303            "push failed with transient network error — retrying once"
304        );
305        let retry_output = time::timeout(
306            Duration::from_secs(120),
307            git()
308                .await
309                .args([
310                    "-c",
311                    "lfs.locksverify=false",
312                    "push",
313                    "-u",
314                    "origin",
315                    branch_to_push,
316                ])
317                .kill_on_drop(true)
318                .current_dir(dir)
319                .output(),
320        )
321        .await
322        .map_err(|_| anyhow::anyhow!("git push (network retry) timed out after 120s"))??;
323
324        if retry_output.status.success() {
325            tracing::info!(branch = branch_to_push, "push succeeded on network retry");
326            note_pushed_head(dir, branch_to_push).await;
327            return Ok(true);
328        }
329
330        let retry_stderr =
331            sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
332        tracing::warn!(
333            branch = branch_to_push,
334            stderr = %retry_stderr,
335            "push retry also failed"
336        );
337        anyhow::bail!("push failed: {retry_stderr}");
338    }
339
340    // Handle workflow scope error: the token lacks the `workflow` OAuth scope
341    // required to push changes to `.github/workflows/`. Strip workflow files
342    // from commits and retry the push.
343    if is_workflow_scope_error(&stderr) {
344        tracing::warn!(
345            branch = branch_to_push,
346            "push rejected: token lacks `workflow` scope — stripping workflow files and retrying"
347        );
348
349        match strip_workflow_files(dir, default_branch).await {
350            Ok(true) => {
351                // Workflow files stripped, retry push
352                let retry_output = time::timeout(
353                    Duration::from_secs(120),
354                    git()
355                        .await
356                        .args([
357                            "-c",
358                            "lfs.locksverify=false",
359                            "push",
360                            "-u",
361                            "origin",
362                            branch_to_push,
363                        ])
364                        .kill_on_drop(true)
365                        .current_dir(dir)
366                        .output(),
367                )
368                .await
369                .map_err(|_| anyhow::anyhow!("git push (retry) timed out after 120s"))??;
370
371                if retry_output.status.success() {
372                    tracing::info!(
373                        branch = branch_to_push,
374                        "push succeeded after stripping workflow files"
375                    );
376                    note_pushed_head(dir, branch_to_push).await;
377                    return Ok(true);
378                }
379
380                let retry_stderr =
381                    sanitize_push_error(String::from_utf8_lossy(&retry_output.stderr).trim());
382
383                // If still failing with workflow scope, bail with clear message
384                if is_workflow_scope_error(&retry_stderr) {
385                    anyhow::bail!(
386                        "push failed: token lacks `workflow` OAuth scope and workflow files \
387                         could not be fully stripped — add `workflow` scope to your GitHub \
388                         token or use a GitHub App for authentication"
389                    );
390                }
391
392                anyhow::bail!("push failed after stripping workflow files: {retry_stderr}");
393            }
394            Ok(false) => {
395                // No workflow files found to strip (shouldn't happen if error was detected)
396                anyhow::bail!(
397                    "push failed: token lacks `workflow` OAuth scope — add `workflow` scope \
398                     to your GitHub token or use a GitHub App for authentication. \
399                     Error: {stderr}"
400                );
401            }
402            Err(e) => {
403                tracing::error!(error = %e, "failed to strip workflow files from commits");
404                anyhow::bail!(
405                    "push failed: token lacks `workflow` OAuth scope and automatic \
406                     recovery failed ({e}) — add `workflow` scope to your GitHub token \
407                     or use a GitHub App for authentication"
408                );
409            }
410        }
411    }
412
413    // Non-fast-forward after `rebase_on_default`. The lease was recorded before that fetch,
414    // so this replaces only a tip this worktree already built on
415    if push_needs_rebase(&stderr) && remote_exists {
416        tracing::info!(
417            branch = branch_to_push,
418            "push rejected (non-fast-forward), force-pushing with lease"
419        );
420        let stderr = match force_push_leased(dir, branch_to_push, default_branch).await {
421            Ok(()) => {
422                tracing::info!(branch = branch_to_push, "force push succeeded");
423                return Ok(true);
424            }
425            Err(e) => e.to_string(),
426        };
427
428        // Check if force push also hit the workflow scope error
429        if is_workflow_scope_error(&stderr) {
430            tracing::warn!(
431                branch = branch_to_push,
432                "force push also rejected due to workflow scope — stripping and retrying"
433            );
434            match strip_workflow_files(dir, default_branch).await {
435                Ok(true) => {
436                    if let Err(e) = force_push_leased(dir, branch_to_push, default_branch).await {
437                        anyhow::bail!("force push failed after stripping workflow files: {e}");
438                    }
439
440                    tracing::info!(
441                        branch = branch_to_push,
442                        "force push succeeded after stripping workflow files"
443                    );
444                    return Ok(true);
445                }
446                Ok(false) => {
447                    anyhow::bail!(
448                        "force push failed: token lacks `workflow` OAuth scope — \
449                         add `workflow` scope to your GitHub token or use a GitHub App. \
450                         Error: {stderr}"
451                    );
452                }
453                Err(e) => {
454                    anyhow::bail!(
455                        "force push failed: token lacks `workflow` scope and recovery \
456                         failed ({e})"
457                    );
458                }
459            }
460        }
461
462        // The remote branch moved since the last fetch (GitHub's "Update branch", another
463        // clone), so the lease no longer matches. Replay local commits on the new tip once
464        if is_stale_lease_error(&stderr) && rebase_on_branch(dir, branch_to_push).await? {
465            let output = git()
466                .await
467                .args([
468                    "-c",
469                    "lfs.locksverify=false",
470                    "push",
471                    "-u",
472                    "origin",
473                    branch_to_push,
474                ])
475                .current_dir(dir)
476                .output_with_context()
477                .await?;
478            if output.status.success() {
479                tracing::info!(
480                    branch = branch_to_push,
481                    "push succeeded after rebasing on the moved remote branch"
482                );
483                note_pushed_head(dir, branch_to_push).await;
484                return Ok(true);
485            }
486
487            let stderr = sanitize_push_error(String::from_utf8_lossy(&output.stderr).trim());
488            anyhow::bail!("push failed after rebasing on the moved remote branch: {stderr}");
489        }
490
491        if is_stale_lease_error(&stderr) {
492            tracing::info!(
493                branch = branch_to_push,
494                "remote branch already holds every local commit, nothing to push"
495            );
496            return Ok(true);
497        }
498
499        anyhow::bail!("force push failed: {stderr}");
500    }
501
502    anyhow::bail!("push failed: {stderr}")
503}
504
505pub fn is_missing_remote_ref_error(err: &anyhow::Error) -> bool {
506    err.to_string().contains("couldn't find remote ref")
507}
508
509pub(super) fn push_needs_rebase(stderr: &str) -> bool {
510    let lower = stderr.to_ascii_lowercase();
511    lower.contains("non-fast-forward")
512        || lower.contains("rejected")
513        || lower.contains("fetch first")
514        || lower.contains("behind")
515}
516
517/// True when `--force-with-lease` refused because the remote ref is not the one last fetched
518pub(super) fn is_stale_lease_error(stderr: &str) -> bool {
519    let lower = stderr.to_ascii_lowercase();
520    lower.contains("stale info") || lower.contains("remote ref updated since checkout")
521}
522
523/// True when a push failure looks like a transient network error (dial
524/// timeout, i/o timeout, connection reset) rather than a ref rejection.
525/// A refused ref must not be retried, but a blipped endpoint deserves one
526/// immediate retry before the run is classified as `push_failed`.
527pub fn is_transient_network_error(stderr: &str) -> bool {
528    let lower = stderr.to_ascii_lowercase();
529    lower.contains("i/o timeout")
530        || lower.contains("dial tcp")
531        || lower.contains("connection reset")
532        || lower.contains("connection refused")
533        || lower.contains("no route to host")
534        || lower.contains("temporary failure in name resolution")
535        || lower.contains("eof")
536        || lower.contains("fatal error in commit_refs")
537        || (lower.contains("[remote rejected]") && lower.contains("(failure)"))
538}
539
540/// Strip URL userinfo (`https://x-access-token:TOKEN@…`) and leak-pattern secrets
541/// from credentialed git stdout and stderr before it is logged or stored
542pub(crate) fn sanitize_push_error(stderr: &str) -> String {
543    static URL_USERINFO: LazyLock<Regex> =
544        LazyLock::new(|| Regex::new(r"://[^/@\s]+@").expect("valid url userinfo regex"));
545    let no_userinfo = URL_USERINFO.replace_all(stderr, "://***@");
546    security::redact(&no_userinfo)
547}
548
549/// Sanitize both streams of a credentialed git `Output` so callers cannot log the raw bytes
550pub(crate) fn sanitize_git_output(mut output: Output) -> Output {
551    output.stdout = sanitize_push_error(&String::from_utf8_lossy(&output.stdout)).into_bytes();
552    output.stderr = sanitize_push_error(&String::from_utf8_lossy(&output.stderr)).into_bytes();
553    output
554}