mod pr;
mod push;
use super::commit;
use crate::github::token;
use crate::sys::cmd::CommandErrorContext;
use std::ffi::OsStr;
use std::io;
use std::path::Path;
use std::process::Output;
use std::time::Duration;
pub use pr::create_pr_if_needed;
pub(crate) use pr::{
is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
};
pub(crate) use push::{
clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
sanitize_push_error,
};
pub use push::{is_missing_remote_ref_error, is_transient_network_error, push_branch};
use tokio::process::Command;
use tokio::time;
pub(crate) fn format_task_ref(task_id: &str) -> String {
if task_id.starts_with("internal:") {
task_id.replace(':', "-")
} else {
format!("#{task_id}")
}
}
#[derive(Debug, thiserror::Error)]
pub enum PrCreateError {
#[error("GitHub API error: {0}")]
ApiError(#[from] anyhow::Error),
}
pub type PrCreateResult<T> = Result<T, PrCreateError>;
pub async fn has_commits_ahead(dir: &Path, default_branch: &str) -> bool {
let output = Command::new("git")
.args([
"rev-list",
"--count",
&format!("origin/{default_branch}..HEAD"),
])
.current_dir(dir)
.output()
.await;
match output {
Ok(o) if o.status.success() => {
let count: u32 = String::from_utf8_lossy(&o.stdout)
.trim()
.parse()
.unwrap_or(0);
count > 0
}
_ => {
tracing::debug!(
default_branch,
"git rev-list failed for compare ref, assuming commits ahead"
);
true
}
}
}
pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
stash_list.lines().find_map(|line| {
let mut parts = line.split_whitespace();
match (parts.next(), parts.next()) {
(Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
_ => None,
}
})
}
pub(crate) struct StashRebaseOpts {
pub abort_on_failure: bool,
}
impl Default for StashRebaseOpts {
fn default() -> Self {
Self {
abort_on_failure: true,
}
}
}
#[derive(Debug)]
pub(crate) enum RebaseOutcome {
Succeeded,
Failed(String),
Skipped(String),
}
pub(crate) async fn stash_rebase_restore(
dir: &Path,
target_ref: &str,
opts: StashRebaseOpts,
) -> anyhow::Result<RebaseOutcome> {
let stash_ref: Option<String> = if commit::has_changes(dir).await {
let stash_out = Command::new("git")
.args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
.current_dir(dir)
.output_with_context()
.await;
match stash_out {
Ok(o) if o.status.success() => {
let stdout_preview = String::from_utf8_lossy(&o.stdout)
.lines()
.next()
.unwrap_or("")
.to_string();
tracing::debug!(
dir = %dir.display(),
stdout = %stdout_preview,
"git stash push succeeded before rebase"
);
let ref_out = Command::new("git")
.args(["rev-parse", "refs/stash@{0}"])
.current_dir(dir)
.output_with_context()
.await;
let stash_hash = ref_out
.ok()
.filter(|o| o.status.success())
.map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
.filter(|s| !s.is_empty());
if stash_hash.is_none() {
tracing::warn!(
dir = %dir.display(),
"git stash succeeded but rev-parse failed — popping stash and skipping rebase"
);
let _ = Command::new("git")
.args(["stash", "pop"])
.current_dir(dir)
.output_with_context()
.await;
return Ok(RebaseOutcome::Skipped(
"stash OID capture failed".to_string(),
));
}
stash_hash
}
Ok(o) => {
let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
tracing::warn!(
dir = %dir.display(),
code = ?o.status.code(),
stderr = %stderr,
"git stash push failed — skipping rebase to preserve dirty state"
);
return Ok(RebaseOutcome::Skipped(format!(
"stash push failed: {stderr}"
)));
}
Err(e) => {
tracing::warn!(
dir = %dir.display(),
error = %e,
"failed to run git stash push — skipping rebase to preserve dirty state"
);
return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
}
}
} else {
None
};
let output = git()
.await
.args(["rebase", target_ref])
.current_dir(dir)
.output_with_context()
.await;
match output {
Ok(o) if o.status.success() => {
tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
restore_stash_by_hash(dir, stash_ref.as_deref()).await;
Ok(RebaseOutcome::Succeeded)
}
Ok(o) => {
let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
if opts.abort_on_failure {
let abort = Command::new("git")
.args(["rebase", "--abort"])
.current_dir(dir)
.output_with_context()
.await;
match abort {
Err(e) => {
tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
}
Ok(o) if !o.status.success() => {
let stderr = String::from_utf8_lossy(&o.stderr);
tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
}
_ => {}
}
}
restore_stash_by_hash(dir, stash_ref.as_deref()).await;
Ok(RebaseOutcome::Failed(stderr))
}
Err(e) => {
if opts.abort_on_failure {
let abort = Command::new("git")
.args(["rebase", "--abort"])
.current_dir(dir)
.output_with_context()
.await;
match abort {
Err(e) => {
tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
}
Ok(o) if !o.status.success() => {
let stderr = String::from_utf8_lossy(&o.stderr);
tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
}
_ => {}
}
}
restore_stash_by_hash(dir, stash_ref.as_deref()).await;
Err(e)
}
}
}
async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
let Some(stash_hash) = stash_hash else {
return;
};
let apply = Command::new("git")
.args(["stash", "apply", stash_hash])
.current_dir(dir)
.output_with_context()
.await;
if apply.is_ok_and(|o| o.status.success()) {
let list = Command::new("git")
.args(["stash", "list", "--format=%H %gd"])
.current_dir(dir)
.output_with_context()
.await;
if let Ok(list_out) = list
&& list_out.status.success()
{
let list_str = String::from_utf8_lossy(&list_out.stdout);
if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
match Command::new("git")
.args(["stash", "drop", &stash_ref])
.current_dir(dir)
.output_with_context()
.await
{
Ok(drop_out) if !drop_out.status.success() => {
let stderr = String::from_utf8_lossy(&drop_out.stderr);
tracing::warn!(
dir = %dir.display(),
stash_ref = %stash_ref,
err = %stderr,
"stash drop failed after apply — entry may remain on stack"
);
}
Err(e) => {
tracing::warn!(
dir = %dir.display(),
stash_ref = %stash_ref,
error = %e,
"stash drop command failed after apply — entry may remain on stack"
);
}
_ => {}
}
} else {
tracing::warn!(
dir = %dir.display(),
stash = %stash_hash,
"stash applied but could not find ref by hash — stash entry may be orphaned on stack"
);
}
}
} else {
tracing::warn!(
dir = %dir.display(),
stash = %stash_hash,
"stash apply failed after rebase — stash preserved for manual recovery"
);
}
}
pub async fn auto_commit(
dir: &Path,
task_id: &str,
title: &str,
agent: &str,
attempt: u32,
when: commit::When,
) -> anyhow::Result<bool> {
if !commit::has_changes(dir).await {
return Ok(false);
}
tracing::info!(task_id, "auto-committing uncommitted changes");
let task_ref = format_task_ref(task_id);
let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
match commit::commit_all(dir, &message, agent, when).await? {
commit::Outcome::Committed => {
tracing::info!(task_id, "auto-commit succeeded");
Ok(true)
}
commit::Outcome::Nothing => Ok(false),
commit::Outcome::Refused {
by: commit::Tool::Git,
reason,
} => {
tracing::warn!(task_id, err = %reason, "git commit failed");
Ok(false)
}
commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
}
}
const MAX_REBASE_COMMITS: usize = 50;
pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
let origin_branch = format!("origin/{branch}");
let fetch = time::timeout(
Duration::from_secs(120),
git()
.await
.args(["fetch", "origin", branch])
.kill_on_drop(true)
.current_dir(dir)
.output(),
)
.await
.map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
.and_then(|r| r.map_err(Into::into));
match fetch {
Ok(o) if o.status.success() => {}
Ok(o) => {
let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
}
Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
}
let count_output = Command::new("git")
.args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
.current_dir(dir)
.output_with_context()
.await;
let commit_count: usize = match count_output {
Ok(o) if o.status.success() => {
let raw = String::from_utf8_lossy(&o.stdout);
raw.trim().parse().map_err(|e| {
anyhow::anyhow!(
"failed to parse commit count from git rev-list output {:?}: {e}",
raw.trim()
)
})?
}
Ok(o) => {
let stderr = String::from_utf8_lossy(&o.stderr);
anyhow::bail!("git rev-list --count failed: {stderr}");
}
Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
};
if commit_count == 0 {
return Ok(false);
}
if commit_count > MAX_REBASE_COMMITS {
anyhow::bail!(
"refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
);
}
tracing::info!(
branch = branch,
commit_count,
"rebasing local commits on origin/{branch}"
);
match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
RebaseOutcome::Succeeded => Ok(true),
RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
}
}
pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
if rebase_in_progress(dir).await {
tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
return;
}
let branch = get_current_branch(dir).await;
record_push_lease(dir, &branch, default_branch).await;
let _ = git()
.await
.args(["fetch", "origin"])
.current_dir(dir)
.output_with_context()
.await;
let commit_count = Command::new("git")
.args([
"rev-list",
"--count",
&format!("origin/{default_branch}..HEAD"),
])
.current_dir(dir)
.output_with_context()
.await
.ok()
.and_then(|o| {
String::from_utf8_lossy(&o.stdout)
.trim()
.parse::<usize>()
.ok()
})
.unwrap_or(0);
if commit_count > MAX_REBASE_COMMITS {
tracing::warn!(
default_branch,
commit_count,
max = MAX_REBASE_COMMITS,
"skipping rebase: branch has too many commits to replay safely"
);
return;
}
match stash_rebase_restore(
dir,
&format!("origin/{default_branch}"),
StashRebaseOpts::default(),
)
.await
{
Ok(RebaseOutcome::Succeeded) => {
tracing::debug!(default_branch, "rebased worktree on default branch");
}
Ok(RebaseOutcome::Failed(e)) => {
tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
}
Ok(RebaseOutcome::Skipped(reason)) => {
tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
}
Err(e) => tracing::warn!(err = %e, "rebase error"),
}
}
pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
for name in ["rebase-merge", "rebase-apply"] {
let out = Command::new("git")
.args(["rev-parse", "--git-path", name])
.current_dir(dir)
.output_with_context()
.await;
if let Ok(o) = out {
let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
if !p.is_empty() && dir.join(p).exists() {
return true;
}
}
}
false
}
pub(crate) fn remote_change_tools() -> Vec<String> {
[
"Bash(git remote set-url*)",
"Bash(git remote add*)",
"Bash(git remote remove*)",
"Bash(git remote rm*)",
"Bash(git remote rename*)",
"Bash(git config*remote.*)",
"Bash(git config*url.*)",
]
.map(String::from)
.to_vec()
}
pub(crate) struct GitCommand {
inner: Command,
}
impl GitCommand {
pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
self.inner.arg(arg);
self
}
pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
where
I: IntoIterator<Item = S>,
S: AsRef<OsStr>,
{
self.inner.args(args);
self
}
pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
self.inner.current_dir(dir);
self
}
pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.inner.env(key, val);
self
}
pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
self.inner.kill_on_drop(kill);
self
}
pub(crate) async fn output(&mut self) -> io::Result<Output> {
self.inner.output().await.map(sanitize_git_output)
}
pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
self.inner
.output_with_context()
.await
.map(sanitize_git_output)
}
}
pub(crate) async fn git() -> GitCommand {
let mut cmd = Command::new("git");
cmd.envs(build_git_auth_env().await).kill_on_drop(true);
GitCommand { inner: cmd }
}
pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
let token = token::shared().get_token().await.ok().flatten();
build_git_auth_env_for_token(token)
}
fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
let mut config: Vec<(String, String)> = match token {
Some(t) if !t.is_empty() => {
let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
vec![
(authed.clone(), "https://github.com/".into()),
(authed, "git@github.com:".into()),
]
}
_ => vec![(
"url.https://github.com/.insteadOf".into(),
"git@github.com:".into(),
)],
};
config.push(("commit.gpgsign".into(), "false".into()));
config.push(("tag.gpgsign".into(), "false".into()));
let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
for (n, (key, value)) in config.into_iter().enumerate() {
env.push((format!("GIT_CONFIG_KEY_{n}"), key));
env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
}
env
}
pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
stderr.contains("without `workflow` scope")
|| stderr.contains("without 'workflow' scope")
|| (stderr.contains("refusing to allow")
&& stderr.contains("workflow")
&& stderr.contains("scope"))
}
async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
let output = Command::new("git")
.args([
"diff",
"--name-only",
&format!("origin/{default_branch}...HEAD"),
"--",
".github/workflows/",
])
.current_dir(dir)
.output_with_context()
.await?;
let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
.lines()
.filter(|l| !l.is_empty())
.map(ToString::to_string)
.collect();
if workflow_files.is_empty() {
return Ok(false);
}
tracing::info!(
files = ?workflow_files,
"stripping workflow files from commits to bypass missing workflow scope"
);
let count_output = Command::new("git")
.args([
"rev-list",
"--count",
&format!("origin/{default_branch}..HEAD"),
])
.current_dir(dir)
.output_with_context()
.await?;
let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
.trim()
.parse()
.unwrap_or(0);
if commit_count == 0 {
return Ok(false);
}
let log_output = Command::new("git")
.args([
"log",
"--format=%x00%H%n%B",
&format!("origin/{default_branch}..HEAD"),
])
.current_dir(dir)
.output_with_context()
.await?;
let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
let commits: Vec<(String, String)> = log_text
.split('\0')
.filter(|s| !s.trim().is_empty())
.map(|block| {
let block = block.trim();
let first_nl = block.find('\n').unwrap_or(block.len());
let hash = block[..first_nl].to_string();
let msg = block[first_nl..].trim().to_string();
(hash, msg)
})
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
if commits.is_empty() {
return Ok(false);
}
let reset = Command::new("git")
.args(["reset", "--soft", &format!("origin/{default_branch}")])
.current_dir(dir)
.output_with_context()
.await?;
if !reset.status.success() {
let stderr = String::from_utf8_lossy(&reset.stderr);
anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
}
let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
rm_args.extend(file_refs);
let rm = Command::new("git")
.args(&rm_args)
.current_dir(dir)
.output_with_context()
.await?;
if !rm.status.success() {
let stderr = String::from_utf8_lossy(&rm.stderr);
tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
}
let has_staged = Command::new("git")
.args(["diff", "--cached", "--quiet"])
.current_dir(dir)
.status()
.await
.is_ok_and(|s| !s.success());
if !has_staged {
tracing::warn!(
"after removing workflow files, no staged changes remain — \
the only changes were workflow files"
);
if let Some((hash, _)) = commits.last() {
let _ = Command::new("git")
.args(["reset", "--soft", hash])
.current_dir(dir)
.output_with_context()
.await;
}
return Ok(false);
}
let commit_msg = if commits.len() == 1 {
commits[0].1.clone()
} else {
let mut combined = String::new();
for (i, (_, msg)) in commits.iter().enumerate() {
if i > 0 {
combined.push_str("\n\n");
}
combined.push_str(msg);
}
combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
combined
};
let commit = commit::git_commit(dir, &commit_msg, "orchestrator").await?;
if !commit.status.success() {
let stderr = String::from_utf8_lossy(&commit.stderr);
if let Some((original_head, _)) = commits.last() {
let _ = Command::new("git")
.args(["reset", "--hard", original_head])
.current_dir(dir)
.output_with_context()
.await;
}
anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
}
tracing::info!(
stripped_files = ?workflow_files,
original_commits = commit_count,
"successfully stripped workflow files from commits"
);
Ok(true)
}
pub(crate) async fn get_current_branch(dir: &Path) -> String {
let output = Command::new("git")
.args(["branch", "--show-current"])
.current_dir(dir)
.output_with_context()
.await;
match output {
Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
_ => String::new(),
}
}
pub async fn count_changed_files(dir: &Path) -> anyhow::Result<usize> {
let output = Command::new("git")
.args(["status", "--porcelain"])
.current_dir(dir)
.output_with_context()
.await?;
let status_output = String::from_utf8_lossy(&output.stdout);
let count = status_output
.lines()
.filter(|line| {
let prefix = line.get(0..2).unwrap_or("");
prefix.starts_with('M')
|| prefix.starts_with('A')
|| prefix.starts_with('R')
|| prefix.starts_with('C')
|| prefix.starts_with('?')
})
.count();
Ok(count)
}
async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
let remote_exists = Command::new("git")
.args(["rev-parse", &format!("origin/{branch}")])
.current_dir(dir)
.output_with_context()
.await
.is_ok_and(|o| o.status.success());
let compare_ref = if remote_exists {
format!("origin/{branch}..{branch}")
} else {
format!("origin/{default_branch}..{branch}")
};
tracing::debug!(
branch,
compare_ref,
remote_exists,
"checking unpushed commits"
);
let output = Command::new("git")
.args(["log", &compare_ref, "--oneline"])
.current_dir(dir)
.output_with_context()
.await;
let has_unpushed = match output {
Ok(o) if o.status.success() => {
let out = String::from_utf8_lossy(&o.stdout);
let has = !out.trim().is_empty();
tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
has
}
_ => {
tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
true
}
};
(remote_exists, has_unpushed)
}
#[cfg(test)]
mod tests;