1mod pr;
11mod push;
12
13use super::commit;
14use crate::github::token;
15use crate::sys::cmd::CommandErrorContext;
16use std::ffi::OsStr;
17use std::io;
18use std::path::Path;
19use std::process::Output;
20use std::time::Duration;
21
22pub use pr::create_pr_if_needed;
23pub(crate) use pr::{
24 is_invalid_base_error, is_transient_github_api_error, is_transient_github_error,
25};
26pub(crate) use push::{
27 clear_push_lease, force_push_leased, record_push_lease, sanitize_git_output,
28 sanitize_push_error,
29};
30pub use push::{is_missing_remote_ref_error, is_transient_network_error, push_branch};
31use tokio::process::Command;
32use tokio::time;
33
34pub(crate) fn format_task_ref(task_id: &str) -> String {
40 if task_id.starts_with("internal:") {
41 task_id.replace(':', "-")
42 } else {
43 format!("#{task_id}")
44 }
45}
46
47#[derive(Debug, thiserror::Error)]
49pub enum PrCreateError {
50 #[error("GitHub API error: {0}")]
51 ApiError(#[from] anyhow::Error),
52}
53
54pub type PrCreateResult<T> = Result<T, PrCreateError>;
56
57pub(crate) fn find_stash_ref_by_hash(stash_list: &str, stash_hash: &str) -> Option<String> {
58 stash_list.lines().find_map(|line| {
59 let mut parts = line.split_whitespace();
60 match (parts.next(), parts.next()) {
61 (Some(hash), Some(reference)) if hash == stash_hash => Some(reference.to_string()),
62 _ => None,
63 }
64 })
65}
66
67pub(crate) struct StashRebaseOpts {
69 pub abort_on_failure: bool,
73}
74
75impl Default for StashRebaseOpts {
76 fn default() -> Self {
77 Self {
78 abort_on_failure: true,
79 }
80 }
81}
82
83#[derive(Debug)]
85pub(crate) enum RebaseOutcome {
86 Succeeded,
88 Failed(String),
92 Skipped(String),
95}
96
97pub(crate) async fn stash_rebase_restore(
114 dir: &Path,
115 target_ref: &str,
116 opts: StashRebaseOpts,
117) -> anyhow::Result<RebaseOutcome> {
118 let stash_ref: Option<String> = if commit::has_changes(dir).await {
119 let stash_out = Command::new("git")
120 .args(["stash", "push", "--include-untracked", "-m", "orch-rebase"])
121 .current_dir(dir)
122 .output_with_context()
123 .await;
124
125 match stash_out {
126 Ok(o) if o.status.success() => {
127 let stdout_preview = String::from_utf8_lossy(&o.stdout)
128 .lines()
129 .next()
130 .unwrap_or("")
131 .to_string();
132 tracing::debug!(
133 dir = %dir.display(),
134 stdout = %stdout_preview,
135 "git stash push succeeded before rebase"
136 );
137
138 let ref_out = Command::new("git")
142 .args(["rev-parse", "refs/stash@{0}"])
143 .current_dir(dir)
144 .output_with_context()
145 .await;
146 let stash_hash = ref_out
147 .ok()
148 .filter(|o| o.status.success())
149 .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
150 .filter(|s| !s.is_empty());
151
152 if stash_hash.is_none() {
153 tracing::warn!(
156 dir = %dir.display(),
157 "git stash succeeded but rev-parse failed — popping stash and skipping rebase"
158 );
159 let _ = Command::new("git")
160 .args(["stash", "pop"])
161 .current_dir(dir)
162 .output_with_context()
163 .await;
164 return Ok(RebaseOutcome::Skipped(
165 "stash OID capture failed".to_string(),
166 ));
167 }
168 stash_hash
169 }
170 Ok(o) => {
171 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
172 tracing::warn!(
173 dir = %dir.display(),
174 code = ?o.status.code(),
175 stderr = %stderr,
176 "git stash push failed — skipping rebase to preserve dirty state"
177 );
178 return Ok(RebaseOutcome::Skipped(format!(
179 "stash push failed: {stderr}"
180 )));
181 }
182 Err(e) => {
183 tracing::warn!(
184 dir = %dir.display(),
185 error = %e,
186 "failed to run git stash push — skipping rebase to preserve dirty state"
187 );
188 return Ok(RebaseOutcome::Skipped(format!("stash push error: {e}")));
189 }
190 }
191 } else {
192 None
193 };
194
195 let output = git()
196 .await
197 .args(["rebase", target_ref])
198 .current_dir(dir)
199 .output_with_context()
200 .await;
201
202 match output {
203 Ok(o) if o.status.success() => {
204 tracing::debug!(dir = %dir.display(), target_ref, "rebase succeeded");
205 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
206 Ok(RebaseOutcome::Succeeded)
207 }
208 Ok(o) => {
209 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
210 tracing::warn!(dir = %dir.display(), target_ref, err = %stderr, "rebase failed");
211 if opts.abort_on_failure {
212 let abort = Command::new("git")
213 .args(["rebase", "--abort"])
214 .current_dir(dir)
215 .output_with_context()
216 .await;
217 match abort {
218 Err(e) => {
219 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
220 }
221 Ok(o) if !o.status.success() => {
222 let stderr = String::from_utf8_lossy(&o.stderr);
223 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
224 }
225 _ => {}
226 }
227 }
228 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
229 Ok(RebaseOutcome::Failed(stderr))
230 }
231 Err(e) => {
232 if opts.abort_on_failure {
233 let abort = Command::new("git")
234 .args(["rebase", "--abort"])
235 .current_dir(dir)
236 .output_with_context()
237 .await;
238 match abort {
239 Err(e) => {
240 tracing::warn!(dir = %dir.display(), error = %e, "git rebase --abort failed — worktree may be in inconsistent state");
241 }
242 Ok(o) if !o.status.success() => {
243 let stderr = String::from_utf8_lossy(&o.stderr);
244 tracing::warn!(dir = %dir.display(), stderr = %stderr, "git rebase --abort returned non-zero — worktree may be in inconsistent state");
245 }
246 _ => {}
247 }
248 }
249 restore_stash_by_hash(dir, stash_ref.as_deref()).await;
250 Err(e)
251 }
252 }
253}
254
255async fn restore_stash_by_hash(dir: &Path, stash_hash: Option<&str>) {
259 let Some(stash_hash) = stash_hash else {
260 return;
261 };
262
263 let apply = Command::new("git")
264 .args(["stash", "apply", stash_hash])
265 .current_dir(dir)
266 .output_with_context()
267 .await;
268 if apply.is_ok_and(|o| o.status.success()) {
269 let list = Command::new("git")
270 .args(["stash", "list", "--format=%H %gd"])
271 .current_dir(dir)
272 .output_with_context()
273 .await;
274 if let Ok(list_out) = list
275 && list_out.status.success()
276 {
277 let list_str = String::from_utf8_lossy(&list_out.stdout);
278 if let Some(stash_ref) = find_stash_ref_by_hash(&list_str, stash_hash) {
279 match Command::new("git")
280 .args(["stash", "drop", &stash_ref])
281 .current_dir(dir)
282 .output_with_context()
283 .await
284 {
285 Ok(drop_out) if !drop_out.status.success() => {
286 let stderr = String::from_utf8_lossy(&drop_out.stderr);
287 tracing::warn!(
288 dir = %dir.display(),
289 stash_ref = %stash_ref,
290 err = %stderr,
291 "stash drop failed after apply — entry may remain on stack"
292 );
293 }
294 Err(e) => {
295 tracing::warn!(
296 dir = %dir.display(),
297 stash_ref = %stash_ref,
298 error = %e,
299 "stash drop command failed after apply — entry may remain on stack"
300 );
301 }
302 _ => {}
303 }
304 } else {
305 tracing::warn!(
306 dir = %dir.display(),
307 stash = %stash_hash,
308 "stash applied but could not find ref by hash — stash entry may be orphaned on stack"
309 );
310 }
311 }
312 } else {
313 tracing::warn!(
314 dir = %dir.display(),
315 stash = %stash_hash,
316 "stash apply failed after rebase — stash preserved for manual recovery"
317 );
318 }
319}
320
321pub async fn auto_commit(
323 dir: &Path,
324 task_id: &str,
325 title: &str,
326 agent: &str,
327 attempt: u32,
328 when: commit::When,
329) -> anyhow::Result<bool> {
330 if !commit::has_changes(dir).await {
331 return Ok(false);
332 }
333
334 tracing::info!(task_id, "auto-committing uncommitted changes");
335 let task_ref = format_task_ref(task_id);
336 let message = format!("{title}\n\nTask {task_ref}\nAgent: {agent}\nAttempt: {attempt}");
337 match commit::commit_all(dir, &message, agent, when).await? {
338 commit::Outcome::Committed => {
339 tracing::info!(task_id, "auto-commit succeeded");
340 Ok(true)
341 }
342 commit::Outcome::Nothing => Ok(false),
343 commit::Outcome::Refused {
344 by: commit::Tool::Git,
345 reason,
346 } => {
347 tracing::warn!(task_id, err = %reason, "git commit failed");
348 Ok(false)
349 }
350 commit::Outcome::Refused { reason, .. } => anyhow::bail!(reason),
351 }
352}
353
354const MAX_REBASE_COMMITS: usize = 50;
362
363pub async fn rebase_on_branch(dir: &Path, branch: &str) -> anyhow::Result<bool> {
373 let origin_branch = format!("origin/{branch}");
374
375 let fetch = time::timeout(
378 Duration::from_secs(120),
379 git()
380 .await
381 .args(["fetch", "origin", branch])
382 .kill_on_drop(true)
383 .current_dir(dir)
384 .output(),
385 )
386 .await
387 .map_err(|_| anyhow::anyhow!("git fetch timed out after 120s"))
388 .and_then(|r| r.map_err(Into::into));
389
390 match fetch {
391 Ok(o) if o.status.success() => {}
392 Ok(o) => {
393 let stderr = sanitize_push_error(&String::from_utf8_lossy(&o.stderr));
394 anyhow::bail!("failed to fetch origin/{branch}: {stderr}");
395 }
396 Err(e) => anyhow::bail!("failed to fetch origin/{branch}: {e}"),
397 }
398
399 let count_output = Command::new("git")
401 .args(["rev-list", "--count", &format!("{origin_branch}..HEAD")])
402 .current_dir(dir)
403 .output_with_context()
404 .await;
405
406 let commit_count: usize = match count_output {
407 Ok(o) if o.status.success() => {
408 let raw = String::from_utf8_lossy(&o.stdout);
409 raw.trim().parse().map_err(|e| {
410 anyhow::anyhow!(
411 "failed to parse commit count from git rev-list output {:?}: {e}",
412 raw.trim()
413 )
414 })?
415 }
416 Ok(o) => {
417 let stderr = String::from_utf8_lossy(&o.stderr);
418 anyhow::bail!("git rev-list --count failed: {stderr}");
419 }
420 Err(e) => anyhow::bail!("failed to run git rev-list --count: {e}"),
421 };
422
423 if commit_count == 0 {
424 return Ok(false);
426 }
427
428 if commit_count > MAX_REBASE_COMMITS {
429 anyhow::bail!(
430 "refusing to rebase {commit_count} commits on origin/{branch} (max {MAX_REBASE_COMMITS})"
431 );
432 }
433
434 tracing::info!(
435 branch = branch,
436 commit_count,
437 "rebasing local commits on origin/{branch}"
438 );
439
440 match stash_rebase_restore(dir, &origin_branch, StashRebaseOpts::default()).await? {
441 RebaseOutcome::Succeeded => Ok(true),
442 RebaseOutcome::Failed(e) => anyhow::bail!("rebase failed: {e}"),
443 RebaseOutcome::Skipped(reason) => anyhow::bail!("rebase skipped: {reason}"),
444 }
445}
446
447pub async fn rebase_on_default(dir: &Path, default_branch: &str) {
455 if rebase_in_progress(dir).await {
457 tracing::info!("rebase already in progress, skipping pre-dispatch rebase");
458 return;
459 }
460
461 let branch = get_current_branch(dir).await;
463 record_push_lease(dir, &branch, default_branch).await;
464
465 let _ = git()
468 .await
469 .args(["fetch", "origin"])
470 .current_dir(dir)
471 .output_with_context()
472 .await;
473
474 let commit_count = Command::new("git")
479 .args([
480 "rev-list",
481 "--count",
482 &format!("origin/{default_branch}..HEAD"),
483 ])
484 .current_dir(dir)
485 .output_with_context()
486 .await
487 .ok()
488 .and_then(|o| {
489 String::from_utf8_lossy(&o.stdout)
490 .trim()
491 .parse::<usize>()
492 .ok()
493 })
494 .unwrap_or(0);
495
496 if commit_count > MAX_REBASE_COMMITS {
497 tracing::warn!(
498 default_branch,
499 commit_count,
500 max = MAX_REBASE_COMMITS,
501 "skipping rebase: branch has too many commits to replay safely"
502 );
503 return;
504 }
505
506 match stash_rebase_restore(
507 dir,
508 &format!("origin/{default_branch}"),
509 StashRebaseOpts::default(),
510 )
511 .await
512 {
513 Ok(RebaseOutcome::Succeeded) => {
514 tracing::debug!(default_branch, "rebased worktree on default branch");
515 }
516 Ok(RebaseOutcome::Failed(e)) => {
517 tracing::warn!(default_branch, err = %e, "rebase failed, continuing with current state");
518 }
519 Ok(RebaseOutcome::Skipped(reason)) => {
520 tracing::warn!(default_branch, %reason, "stash failed before rebase, continuing with current state");
521 }
522 Err(e) => tracing::warn!(err = %e, "rebase error"),
523 }
524}
525
526pub(crate) async fn rebase_in_progress(dir: &Path) -> bool {
527 for name in ["rebase-merge", "rebase-apply"] {
528 let out = Command::new("git")
529 .args(["rev-parse", "--git-path", name])
530 .current_dir(dir)
531 .output_with_context()
532 .await;
533 if let Ok(o) = out {
534 let p = String::from_utf8_lossy(&o.stdout).trim().to_string();
535 if !p.is_empty() && dir.join(p).exists() {
536 return true;
537 }
538 }
539 }
540 false
541}
542
543pub(crate) struct GitCommand {
545 inner: Command,
546}
547
548impl GitCommand {
549 pub(crate) fn arg<S: AsRef<OsStr>>(&mut self, arg: S) -> &mut Self {
550 self.inner.arg(arg);
551 self
552 }
553
554 pub(crate) fn args<I, S>(&mut self, args: I) -> &mut Self
555 where
556 I: IntoIterator<Item = S>,
557 S: AsRef<OsStr>,
558 {
559 self.inner.args(args);
560 self
561 }
562
563 pub(crate) fn current_dir<P: AsRef<Path>>(&mut self, dir: P) -> &mut Self {
564 self.inner.current_dir(dir);
565 self
566 }
567
568 pub(crate) fn env<K, V>(&mut self, key: K, val: V) -> &mut Self
569 where
570 K: AsRef<OsStr>,
571 V: AsRef<OsStr>,
572 {
573 self.inner.env(key, val);
574 self
575 }
576
577 pub(crate) fn kill_on_drop(&mut self, kill: bool) -> &mut Self {
578 self.inner.kill_on_drop(kill);
579 self
580 }
581
582 pub(crate) async fn output(&mut self) -> io::Result<Output> {
583 self.inner.output().await.map(sanitize_git_output)
584 }
585
586 pub(crate) async fn output_with_context(&mut self) -> anyhow::Result<Output> {
587 self.inner
588 .output_with_context()
589 .await
590 .map(sanitize_git_output)
591 }
592}
593
594pub(crate) async fn git() -> GitCommand {
597 let mut cmd = Command::new("git");
598 cmd.envs(build_git_auth_env().await).kill_on_drop(true);
599 GitCommand { inner: cmd }
600}
601
602pub(crate) async fn build_git_auth_env() -> Vec<(String, String)> {
623 let token = token::shared().get_token().await.ok().flatten();
624 build_git_auth_env_for_token(token)
625}
626
627fn build_git_auth_env_for_token(token: Option<String>) -> Vec<(String, String)> {
628 let mut config: Vec<(String, String)> = match token {
629 Some(t) if !t.is_empty() => {
630 let authed = format!("url.https://x-access-token:{t}@github.com/.insteadOf");
631 vec![
632 (authed.clone(), "https://github.com/".into()),
633 (authed, "git@github.com:".into()),
634 ]
635 }
636 _ => vec![(
637 "url.https://github.com/.insteadOf".into(),
638 "git@github.com:".into(),
639 )],
640 };
641 config.push(("commit.gpgsign".into(), "false".into()));
643 config.push(("tag.gpgsign".into(), "false".into()));
644
645 let mut env = vec![("GIT_CONFIG_COUNT".to_string(), config.len().to_string())];
646 for (n, (key, value)) in config.into_iter().enumerate() {
647 env.push((format!("GIT_CONFIG_KEY_{n}"), key));
648 env.push((format!("GIT_CONFIG_VALUE_{n}"), value));
649 }
650 env
651}
652
653pub(crate) fn is_workflow_scope_error(stderr: &str) -> bool {
660 stderr.contains("without `workflow` scope")
661 || stderr.contains("without 'workflow' scope")
662 || (stderr.contains("refusing to allow")
663 && stderr.contains("workflow")
664 && stderr.contains("scope"))
665}
666
667async fn strip_workflow_files(dir: &Path, default_branch: &str) -> anyhow::Result<bool> {
678 let output = Command::new("git")
680 .args([
681 "diff",
682 "--name-only",
683 &format!("origin/{default_branch}...HEAD"),
684 "--",
685 ".github/workflows/",
686 ])
687 .current_dir(dir)
688 .output_with_context()
689 .await?;
690
691 let workflow_files: Vec<String> = String::from_utf8_lossy(&output.stdout)
692 .lines()
693 .filter(|l| !l.is_empty())
694 .map(ToString::to_string)
695 .collect();
696
697 if workflow_files.is_empty() {
698 return Ok(false);
699 }
700
701 tracing::info!(
702 files = ?workflow_files,
703 "stripping workflow files from commits to bypass missing workflow scope"
704 );
705
706 let count_output = Command::new("git")
711 .args([
712 "rev-list",
713 "--count",
714 &format!("origin/{default_branch}..HEAD"),
715 ])
716 .current_dir(dir)
717 .output_with_context()
718 .await?;
719
720 let commit_count: usize = String::from_utf8_lossy(&count_output.stdout)
721 .trim()
722 .parse()
723 .unwrap_or(0);
724
725 if commit_count == 0 {
726 return Ok(false);
727 }
728
729 let log_output = Command::new("git")
734 .args([
735 "log",
736 "--format=%x00%H%n%B",
737 &format!("origin/{default_branch}..HEAD"),
738 ])
739 .current_dir(dir)
740 .output_with_context()
741 .await?;
742 let log_text = String::from_utf8_lossy(&log_output.stdout).to_string();
743
744 let commits: Vec<(String, String)> = log_text
748 .split('\0')
749 .filter(|s| !s.trim().is_empty())
750 .map(|block| {
751 let block = block.trim();
752 let first_nl = block.find('\n').unwrap_or(block.len());
753 let hash = block[..first_nl].to_string();
754 let msg = block[first_nl..].trim().to_string();
755 (hash, msg)
756 })
757 .collect::<Vec<_>>()
758 .into_iter()
759 .rev()
760 .collect();
761
762 if commits.is_empty() {
763 return Ok(false);
764 }
765
766 let reset = Command::new("git")
768 .args(["reset", "--soft", &format!("origin/{default_branch}")])
769 .current_dir(dir)
770 .output_with_context()
771 .await?;
772
773 if !reset.status.success() {
774 let stderr = String::from_utf8_lossy(&reset.stderr);
775 anyhow::bail!("git reset --soft failed during workflow file stripping: {stderr}");
776 }
777
778 let mut rm_args = vec!["rm", "--cached", "--ignore-unmatch", "--"];
780 let file_refs: Vec<&str> = workflow_files.iter().map(String::as_str).collect();
781 rm_args.extend(file_refs);
782
783 let rm = Command::new("git")
784 .args(&rm_args)
785 .current_dir(dir)
786 .output_with_context()
787 .await?;
788
789 if !rm.status.success() {
790 let stderr = String::from_utf8_lossy(&rm.stderr);
791 tracing::warn!("git rm --cached for workflow files failed (non-fatal): {stderr}");
792 }
793
794 let has_staged = Command::new("git")
797 .args(["diff", "--cached", "--quiet"])
798 .current_dir(dir)
799 .status()
800 .await
801 .is_ok_and(|s| !s.success());
802
803 if !has_staged {
804 tracing::warn!(
805 "after removing workflow files, no staged changes remain — \
806 the only changes were workflow files"
807 );
808 if let Some((hash, _)) = commits.last() {
811 let _ = Command::new("git")
812 .args(["reset", "--soft", hash])
813 .current_dir(dir)
814 .output_with_context()
815 .await;
816 }
817 return Ok(false);
818 }
819
820 let commit_msg = if commits.len() == 1 {
822 commits[0].1.clone()
823 } else {
824 let mut combined = String::new();
826 for (i, (_, msg)) in commits.iter().enumerate() {
827 if i > 0 {
828 combined.push_str("\n\n");
829 }
830 combined.push_str(msg);
831 }
832 combined.push_str("\n\n[workflow files stripped: token lacks `workflow` scope]");
833 combined
834 };
835
836 let commit = commit::git_commit(dir, &commit_msg, "orchestrator").await?;
838
839 if !commit.status.success() {
840 let stderr = String::from_utf8_lossy(&commit.stderr);
841 if let Some((original_head, _)) = commits.last() {
843 let _ = Command::new("git")
844 .args(["reset", "--hard", original_head])
845 .current_dir(dir)
846 .output_with_context()
847 .await;
848 }
849 anyhow::bail!("git commit failed during workflow file stripping: {stderr}");
850 }
851
852 tracing::info!(
853 stripped_files = ?workflow_files,
854 original_commits = commit_count,
855 "successfully stripped workflow files from commits"
856 );
857
858 Ok(true)
859}
860
861pub(crate) async fn get_current_branch(dir: &Path) -> String {
863 let output = Command::new("git")
864 .args(["branch", "--show-current"])
865 .current_dir(dir)
866 .output_with_context()
867 .await;
868
869 match output {
870 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
871 _ => String::new(),
872 }
873}
874
875async fn check_push_needed(dir: &Path, branch: &str, default_branch: &str) -> (bool, bool) {
883 let remote_exists = Command::new("git")
885 .args(["rev-parse", &format!("origin/{branch}")])
886 .current_dir(dir)
887 .output_with_context()
888 .await
889 .is_ok_and(|o| o.status.success());
890
891 let compare_ref = if remote_exists {
892 format!("origin/{branch}..{branch}")
893 } else {
894 format!("origin/{default_branch}..{branch}")
896 };
897
898 tracing::debug!(
899 branch,
900 compare_ref,
901 remote_exists,
902 "checking unpushed commits"
903 );
904
905 let output = Command::new("git")
906 .args(["log", &compare_ref, "--oneline"])
907 .current_dir(dir)
908 .output_with_context()
909 .await;
910
911 let has_unpushed = match output {
912 Ok(o) if o.status.success() => {
913 let out = String::from_utf8_lossy(&o.stdout);
914 let has = !out.trim().is_empty();
915 tracing::debug!(branch, has_unpushed = has, "unpushed commits check result");
916 has
917 }
918 _ => {
919 tracing::debug!(branch, "git log failed for compare ref, assuming unpushed");
920 true
923 }
924 };
925
926 (remote_exists, has_unpushed)
927}
928
929#[cfg(test)]
930mod tests;