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