1use crate::cmd::CommandErrorContext;
7use crate::engine::git::git_ops;
8use crate::engine::git::git_ops::RebaseOutcome;
9use crate::engine::git::git_ops::StashRebaseOpts;
10use crate::github::http::GhHttp;
11use crate::home;
12use crate::store;
13use crate::store::TaskStore;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use tokio::fs;
17use tokio::process::Command;
18use tokio::task;
19
20#[derive(Debug)]
22pub struct WorktreeSetup {
23 pub work_dir: PathBuf,
25 pub branch: String,
27 pub default_branch: String,
29 pub main_project_dir: PathBuf,
31}
32
33pub fn project_name(project_dir: &Path) -> String {
35 project_dir
36 .file_name()
37 .map_or_else(
38 || "project".to_string(),
39 |s| s.to_string_lossy().to_string(),
40 )
41 .trim_end_matches(".git")
42 .to_string()
43}
44
45pub fn project_worktrees_dir(project_dir: &Path) -> PathBuf {
47 home::worktrees_dir()
48 .unwrap_or_default()
49 .join(project_name(project_dir))
50}
51
52pub async fn list_project_worktrees(project_dir: &Path) -> anyhow::Result<Vec<PathBuf>> {
54 let base = project_worktrees_dir(project_dir);
55 let mut worktrees = Vec::new();
56
57 if fs::metadata(&base).await.is_err() {
58 return Ok(worktrees);
59 }
60
61 let mut entries = fs::read_dir(&base).await?;
62 while let Some(entry) = entries.next_entry().await? {
63 if entry.metadata().await.is_ok_and(|m| m.is_dir()) {
64 worktrees.push(entry.path());
65 }
66 }
67
68 Ok(worktrees)
69}
70
71pub fn task_id_from_worktree_name(name: &str) -> Option<String> {
73 if let Some(rest) = name.strip_prefix("internal-") {
74 let num = rest.split('-').next()?;
75 return num.parse::<u64>().ok().map(|n| format!("internal:{n}"));
76 }
77
78 for prefix in ["gh-issue-", "gh-task-"] {
79 if let Some(rest) = name.strip_prefix(prefix) {
80 let task_part = rest.split('-').next()?;
81 if task_part == "internal" {
82 let num = rest.split('-').nth(1)?;
83 return num.parse::<u64>().ok().map(|n| format!("internal:{n}"));
84 }
85 return Some(task_part.to_string());
86 }
87 }
88
89 None
90}
91
92pub fn keep_conflicted_rebase(merge_conflict_retries: i32, pr_number: Option<i32>) -> bool {
94 merge_conflict_retries > 0 || pr_number.is_some()
95}
96
97pub async fn abort_worktree_rebase(worktree_dir: &Path) {
99 let _ = Command::new("git")
100 .args(["rebase", "--abort"])
101 .current_dir(worktree_dir)
102 .output_with_context()
103 .await;
104}
105
106pub async fn rebase_worktree_on_origin_main(
112 worktree_dir: &Path,
113 default_branch: &str,
114) -> anyhow::Result<()> {
115 let origin_branch = format!("origin/{default_branch}");
116
117 match git_ops::stash_rebase_restore(worktree_dir, &origin_branch, StashRebaseOpts::default())
118 .await?
119 {
120 RebaseOutcome::Succeeded | RebaseOutcome::Skipped(_) => Ok(()),
121 RebaseOutcome::Failed(e) => {
122 anyhow::bail!("git rebase {origin_branch} failed: {e}")
123 }
124 }
125}
126
127pub fn branch_name(task_id: &str, title: &str) -> String {
132 let (prefix, sanitized_id) = if let Some(num) = task_id.strip_prefix("internal:") {
133 ("internal", num.to_string())
134 } else {
135 ("gh-issue", sanitize_task_id(task_id))
136 };
137
138 let raw: String = title
139 .to_lowercase()
140 .chars()
141 .map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
142 .collect();
143
144 let mut slug = String::with_capacity(raw.len());
146 let mut prev_dash = false;
147 for c in raw.chars() {
148 if c == '-' {
149 if !prev_dash {
150 slug.push('-');
151 }
152 prev_dash = true;
153 } else {
154 slug.push(c);
155 prev_dash = false;
156 }
157 }
158 let slug = slug.trim_matches('-').to_string();
159
160 let slug = if slug.len() > 40 { &slug[..40] } else { &slug };
162 let slug = slug.trim_end_matches('-');
163
164 if slug.is_empty() {
165 format!("{prefix}-{sanitized_id}")
166 } else {
167 format!("{prefix}-{sanitized_id}-{slug}")
168 }
169}
170
171fn sanitize_task_id(task_id: &str) -> String {
173 task_id.replace(':', "-")
174}
175
176fn normalize_branch_name(raw: &str) -> Option<String> {
185 let branch = raw.trim();
186 if branch.is_empty() {
187 return None;
188 }
189
190 let cleaned = branch
192 .strip_prefix("refs/remotes/origin/")
193 .or_else(|| branch.strip_prefix("remotes/origin/"))
194 .or_else(|| branch.strip_prefix("refs/heads/"))
195 .or_else(|| branch.strip_prefix("origin/"))
196 .unwrap_or(branch);
197
198 if cleaned.is_empty() {
199 return None;
200 }
201 Some(cleaned.to_string())
202}
203
204pub async fn detect_default_branch(project_dir: &Path) -> String {
209 let symref = Command::new("git")
211 .args(["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
212 .current_dir(project_dir)
213 .output_with_context()
214 .await;
215
216 if let Ok(o) = &symref
217 && o.status.success()
218 {
219 let raw = String::from_utf8_lossy(&o.stdout);
220 if let Some(branch) = normalize_branch_name(&raw) {
221 return branch;
222 }
223 }
224
225 let revparse = Command::new("git")
227 .args(["rev-parse", "--abbrev-ref", "refs/remotes/origin/HEAD"])
228 .current_dir(project_dir)
229 .output_with_context()
230 .await;
231
232 if let Ok(o) = &revparse
233 && o.status.success()
234 {
235 let raw = String::from_utf8_lossy(&o.stdout);
236 if let Some(branch) = normalize_branch_name(&raw) {
237 return branch;
238 }
239 }
240
241 let remote_show = Command::new("git")
243 .args(["remote", "show", "origin"])
244 .current_dir(project_dir)
245 .output_with_context()
246 .await;
247
248 if let Ok(o) = &remote_show
249 && o.status.success()
250 {
251 let stdout = String::from_utf8_lossy(&o.stdout);
252 for line in stdout.lines() {
253 let trimmed = line.trim();
254 if trimmed.starts_with("HEAD branch:")
255 && let Some(branch) = trimmed.split(':').nth(1)
256 {
257 let branch = branch.trim();
258 if !branch.is_empty() && branch != "(unknown)" {
259 return branch.to_string();
260 }
261 }
262 }
263 }
264
265 tracing::warn!(
266 project_dir = %project_dir.display(),
267 "could not detect default branch from git, falling back to 'main'"
268 );
269 "main".to_string()
270}
271
272pub async fn resolve_main_repo(project_dir: &Path) -> PathBuf {
276 let output = Command::new("git")
277 .args(["worktree", "list", "--porcelain"])
278 .current_dir(project_dir)
279 .output_with_context()
280 .await;
281
282 if let Ok(o) = output
283 && o.status.success()
284 {
285 let stdout = String::from_utf8_lossy(&o.stdout);
286 if let Some(first_line) = stdout.lines().next()
287 && let Some(path) = first_line.strip_prefix("worktree ")
288 {
289 let main_path = PathBuf::from(path);
290 if main_path != project_dir {
291 tracing::info!(
292 worktree = %project_dir.display(),
293 main = %main_path.display(),
294 "resolved worktree to main repo"
295 );
296 return main_path;
297 }
298 }
299 }
300
301 project_dir.to_path_buf()
302}
303
304pub(super) async fn resolve_branch_start_point(
314 repo_root: &str,
315 branch: &str,
316 default_branch: &str,
317) -> String {
318 let verify = |reference: String| async move {
319 Command::new("git")
320 .args(["-C", repo_root, "rev-parse", "--verify", &reference])
321 .output_with_context()
322 .await
323 .is_ok_and(|o| o.status.success())
324 };
325
326 let origin_branch_ref = format!("origin/{branch}");
327 if verify(origin_branch_ref.clone()).await {
328 return origin_branch_ref;
329 }
330
331 let origin_default_ref = format!("origin/{default_branch}");
332 if verify(origin_default_ref.clone()).await {
333 return origin_default_ref;
334 }
335
336 default_branch.to_string()
337}
338
339pub async fn validate_worktree_gitdir(worktree_dir: &Path) -> bool {
345 let git_file = worktree_dir.join(".git");
346 if fs::metadata(&git_file).await.is_err() {
348 return false;
349 }
350 if fs::metadata(&git_file).await.is_ok_and(|m| m.is_dir()) {
352 return true;
353 }
354
355 let Ok(content) = fs::read_to_string(&git_file).await else {
356 return false;
357 };
358 if let Some(gitdir_path) = content
361 .lines()
362 .next()
363 .and_then(|l| l.strip_prefix("gitdir: "))
364 {
365 return fs::metadata(gitdir_path.trim())
367 .await
368 .is_ok_and(|m| m.is_dir());
369 }
370 false
371}
372
373#[expect(
379 clippy::ref_option,
380 reason = "the store helper it calls takes the store as &Option"
381)]
382async fn resolve_parent_branch(
383 store: &Option<Arc<TaskStore>>,
384 parent_id: Option<i64>,
385 worktrees_base: &Path,
386) -> Option<(String, PathBuf)> {
387 let parent_id = parent_id?;
388 let parent = store::opt_store_get_task_by_id(store, parent_id).await?;
389 if parent.branch.is_empty() {
390 return None;
391 }
392 let wt = if parent.worktree.is_empty() {
393 worktrees_base.join(&parent.branch)
394 } else {
395 let exists = fs::metadata(&parent.worktree)
397 .await
398 .is_ok_and(|m| m.is_dir());
399 if exists {
400 PathBuf::from(&parent.worktree)
401 } else {
402 worktrees_base.join(&parent.branch)
403 }
404 };
405 tracing::info!(
406 parent_id,
407 branch = %parent.branch,
408 worktree = %wt.display(),
409 "child task inheriting parent branch"
410 );
411 Some((parent.branch, wt))
412}
413
414pub async fn setup_worktree(
418 task_id: &str,
419 title: &str,
420 project_dir: &Path,
421 store: &Option<Arc<TaskStore>>,
422 repo: &str,
423) -> anyhow::Result<WorktreeSetup> {
424 let main_dir = resolve_main_repo(project_dir).await;
426 let default_branch = detect_default_branch(&main_dir).await;
427
428 let worktrees_base = project_worktrees_dir(&main_dir);
429 fs::create_dir_all(&worktrees_base).await?;
430
431 let task_record = store::opt_store_get_task(store, repo, task_id).await;
433 let (saved_branch, saved_worktree, parent_id) =
434 task_record.as_ref().map_or((None, None, None), |t| {
435 (
436 Some(t.branch.clone()),
437 Some(t.worktree.clone()),
438 t.parent_id,
439 )
440 });
441
442 let mut force_fresh = false;
443 if let (Some(store), Some(record)) = (store.as_ref(), task_record.as_ref()) {
444 let key = store::worktree_refresh_key(record.id);
445 if matches!(store.kv_get(&key).await, Ok(Some(_))) {
446 let _ = store.kv_delete(&key).await;
447 force_fresh = true;
448 tracing::info!(
449 task_id,
450 "dependency merged, discarding the old worktree so the next run starts at the default branch"
451 );
452 }
453 }
454
455 let (branch_name_str, worktree_dir) = if force_fresh {
456 if let Some(existing_dir) = find_existing_worktree(&worktrees_base, task_id).await {
457 discard_worktree(&main_dir, &existing_dir).await;
458 }
459 if let Some(saved) = saved_worktree.as_ref().filter(|path| !path.is_empty()) {
460 let saved_path = PathBuf::from(saved);
461 if fs::metadata(&saved_path).await.is_ok() {
462 discard_worktree(&main_dir, &saved_path).await;
463 }
464 }
465 let bn = branch_name(task_id, title);
466 (bn.clone(), worktrees_base.join(&bn))
467 } else if let Some(ref saved) = saved_branch {
468 if !saved.is_empty() {
469 let wt = match &saved_worktree {
471 Some(wt) if !wt.is_empty() => {
472 let wt_str = wt.clone();
473 let exists = task::spawn_blocking(move || Path::new(&wt_str).exists())
474 .await
475 .unwrap_or(false);
476 if exists {
477 PathBuf::from(wt)
478 } else {
479 worktrees_base.join(saved)
480 }
481 }
482 _ => worktrees_base.join(saved),
483 };
484 (saved.clone(), wt)
485 } else if let Some((parent_branch, parent_wt)) =
486 resolve_parent_branch(store, parent_id, &worktrees_base).await
487 {
488 (parent_branch, parent_wt)
491 } else {
492 let bn = branch_name(task_id, title);
493 (bn.clone(), worktrees_base.join(&bn))
494 }
495 } else {
496 if let Some((parent_branch, parent_wt)) =
498 resolve_parent_branch(store, parent_id, &worktrees_base).await
499 {
500 (parent_branch, parent_wt)
501 } else {
502 let existing = find_existing_worktree(&worktrees_base, task_id).await;
503 if let Some(existing_dir) = existing {
504 let bn = existing_dir
505 .file_name()
506 .filter(|n| !n.is_empty())
507 .map_or_else(
508 || branch_name(task_id, title),
509 |n| n.to_string_lossy().to_string(),
510 );
511 tracing::info!(task_id, worktree = %existing_dir.display(), "found existing worktree");
512 (bn, existing_dir)
513 } else {
514 let bn = branch_name(task_id, title);
515 (bn.clone(), worktrees_base.join(&bn))
516 }
517 }
518 };
519
520 if branch_name_str.is_empty() {
521 anyhow::bail!("empty branch name for task {task_id}");
522 }
523
524 if fs::metadata(&worktree_dir).await.is_ok() {
527 let keep_rebase = task_record
528 .as_ref()
529 .is_some_and(|t| keep_conflicted_rebase(t.merge_conflict_retries, t.pr_number))
530 && git_ops::rebase_in_progress(&worktree_dir).await;
531 if keep_rebase {
532 tracing::info!(
533 task_id,
534 "keeping the conflicted rebase auto_merge left for the agent"
535 );
536 } else {
537 let _ = Command::new("git")
538 .args(["rebase", "--abort"])
539 .current_dir(&worktree_dir)
540 .output_with_context()
541 .await;
542 }
543
544 let index_ok = Command::new("git")
550 .args(["status", "--porcelain"])
551 .current_dir(&worktree_dir)
552 .output_with_context()
553 .await
554 .is_ok_and(|o| o.status.success());
555
556 if !index_ok {
557 let stderr_hint = Command::new("git")
558 .args(["status", "--porcelain"])
559 .current_dir(&worktree_dir)
560 .output_with_context()
561 .await
562 .map(|o| String::from_utf8_lossy(&o.stderr).trim().to_string())
563 .unwrap_or_default();
564 tracing::warn!(
565 task_id,
566 worktree = %worktree_dir.display(),
567 stderr = %stderr_hint,
568 "corrupted worktree index detected — removing and recreating worktree"
569 );
570 let _ = Command::new("git")
572 .args([
573 "-C",
574 &main_dir.to_string_lossy(),
575 "worktree",
576 "remove",
577 "--force",
578 &worktree_dir.to_string_lossy(),
579 ])
580 .output_with_context()
581 .await;
582 if fs::metadata(&worktree_dir).await.is_ok() {
585 let _ = fs::remove_dir_all(&worktree_dir).await;
586 }
587 let _ = Command::new("git")
589 .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
590 .output_with_context()
591 .await;
592 }
593 }
594
595 if fs::metadata(&worktree_dir).await.is_err() {
597 tracing::info!(task_id, worktree = %worktree_dir.display(), "creating worktree");
598
599 let _ = git_ops::git()
605 .await
606 .args([
607 "-C",
608 &main_dir.to_string_lossy(),
609 "fetch",
610 "--prune",
611 "origin",
612 ])
613 .output_with_context()
614 .await;
615
616 let start_point = resolve_branch_start_point(
621 &main_dir.to_string_lossy(),
622 &branch_name_str,
623 &default_branch,
624 )
625 .await;
626 let _ = Command::new("git")
627 .args([
628 "-C",
629 &main_dir.to_string_lossy(),
630 "branch",
631 &branch_name_str,
632 &start_point,
633 ])
634 .output_with_context()
635 .await;
636
637 if let Some(parent) = worktree_dir.parent() {
639 fs::create_dir_all(parent).await?;
640 }
641
642 let template_start = resolve_branch_start_point(
643 &main_dir.to_string_lossy(),
644 &default_branch,
645 &default_branch,
646 )
647 .await;
648 let cloned = match super::cow::create_worktree(
649 &main_dir,
650 &project_name(&main_dir),
651 &worktree_dir,
652 &branch_name_str,
653 &template_start,
654 )
655 .await
656 {
657 Ok(()) => {
658 tracing::info!(task_id, "worktree cloned from project template");
659 true
660 }
661 Err(e) => {
662 tracing::debug!(task_id, error = %e, "copy-on-write worktree unavailable, using git worktree add");
663 false
664 }
665 };
666
667 if !cloned {
668 let output = Command::new("git")
669 .args([
670 "-C",
671 &main_dir.to_string_lossy(),
672 "worktree",
673 "add",
674 &worktree_dir.to_string_lossy(),
675 &branch_name_str,
676 ])
677 .output_with_context()
678 .await?;
679
680 if !output.status.success() && fs::metadata(&worktree_dir).await.is_err() {
681 let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
682 let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
683 tracing::warn!(
685 task_id,
686 stdout = %stdout,
687 stderr = %stderr,
688 "worktree creation failed, retrying after prune"
689 );
690
691 let _ = Command::new("git")
692 .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
693 .output_with_context()
694 .await;
695
696 let _ = Command::new("git")
697 .args([
698 "-C",
699 &main_dir.to_string_lossy(),
700 "branch",
701 "-D",
702 &branch_name_str,
703 ])
704 .output_with_context()
705 .await;
706
707 let _ = Command::new("git")
708 .args([
709 "-C",
710 &main_dir.to_string_lossy(),
711 "branch",
712 &branch_name_str,
713 &start_point,
714 ])
715 .output_with_context()
716 .await;
717
718 let retry_output = Command::new("git")
719 .args([
720 "-C",
721 &main_dir.to_string_lossy(),
722 "worktree",
723 "add",
724 &worktree_dir.to_string_lossy(),
725 &branch_name_str,
726 ])
727 .output_with_context()
728 .await;
729
730 let mut retry_stdout = String::new();
731 let mut retry_stderr = String::new();
732 let mut retry_error = String::new();
733 match retry_output {
734 Ok(output) => {
735 retry_stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
736 retry_stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
737 tracing::warn!(
738 task_id,
739 stdout = %retry_stdout,
740 stderr = %retry_stderr,
741 "worktree creation retry failed"
742 );
743 }
744 Err(err) => {
745 retry_error = err.to_string();
746 tracing::warn!(
747 task_id,
748 error = %retry_error,
749 "worktree creation retry failed to run"
750 );
751 }
752 }
753
754 if fs::metadata(&worktree_dir).await.is_err() {
755 anyhow::bail!(
756 "failed to create worktree at {} for task {} (stdout: {}, stderr: {}, retry stdout: {}, retry stderr: {}, retry error: {})",
757 worktree_dir.display(),
758 task_id,
759 stdout,
760 stderr,
761 retry_stdout,
762 retry_stderr,
763 retry_error
764 );
765 }
766 }
767 }
768 }
769
770 if !task_id.starts_with("internal:")
774 && let Ok(issue_num) = task_id.parse::<u64>()
775 && let Ok(gh) = GhHttp::new()
776 {
777 match gh
778 .link_issue_to_branch(repo, issue_num, &branch_name_str)
779 .await
780 {
781 Ok(id) => {
782 tracing::info!(task_id, branch = %branch_name_str, linked = %id, "linked issue to branch");
783 }
784 Err(e) => {
785 tracing::debug!(task_id, error = %e, "failed to link issue to branch (non-fatal)");
786 }
787 }
788 }
789
790 if let Err(e) = store::store_set_result(
792 store,
793 repo,
794 task_id,
795 &[
796 (
797 "worktree",
798 serde_json::json!(worktree_dir.display().to_string()),
799 ),
800 ("branch", serde_json::json!(branch_name_str)),
801 ],
802 )
803 .await
804 {
805 tracing::warn!(task_id, err = %e, "failed to save worktree info to store (non-fatal)");
806 }
807
808 tracing::info!(
809 task_id,
810 worktree = %worktree_dir.display(),
811 branch = %branch_name_str,
812 "worktree ready"
813 );
814
815 Ok(WorktreeSetup {
816 work_dir: worktree_dir,
817 branch: branch_name_str,
818 default_branch,
819 main_project_dir: main_dir,
820 })
821}
822
823async fn discard_worktree(main_dir: &Path, worktree_dir: &Path) {
825 let _ = Command::new("git")
826 .args([
827 "-C",
828 &main_dir.to_string_lossy(),
829 "worktree",
830 "remove",
831 "--force",
832 &worktree_dir.to_string_lossy(),
833 ])
834 .output_with_context()
835 .await;
836 if fs::metadata(worktree_dir).await.is_ok() {
837 let _ = fs::remove_dir_all(worktree_dir).await;
838 }
839 let _ = Command::new("git")
840 .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
841 .output_with_context()
842 .await;
843}
844
845async fn find_existing_worktree(worktrees_base: &Path, task_id: &str) -> Option<PathBuf> {
846 let (prefix_new, legacy_prefixes) = if let Some(num) = task_id.strip_prefix("internal:") {
847 (
848 format!("internal-{num}-"),
849 vec![
850 format!("gh-task-internal-{num}-"),
851 format!("gh-issue-internal-{num}-"),
852 ],
853 )
854 } else {
855 let sanitized_id = sanitize_task_id(task_id);
856 (
857 format!("gh-issue-{sanitized_id}-"),
858 vec![format!("gh-task-{sanitized_id}-")],
859 )
860 };
861
862 let mut entries = match fs::read_dir(worktrees_base).await {
863 Ok(e) => e,
864 Err(e) => {
865 tracing::warn!(
866 error = %e,
867 path = %worktrees_base.display(),
868 "failed to read worktrees directory while searching for existing worktree"
869 );
870 return None;
871 }
872 };
873 loop {
874 let next_entry = match entries.next_entry().await {
875 Ok(Some(entry)) => entry,
876 Ok(None) => break,
877 Err(e) => {
878 tracing::warn!(error = %e, "failed to read directory entry while searching for worktree");
880 continue;
881 }
882 };
883
884 let name = next_entry.file_name().to_string_lossy().to_string();
885 let matches =
886 name.starts_with(&prefix_new) || legacy_prefixes.iter().any(|p| name.starts_with(p));
887 if matches {
888 match next_entry.metadata().await {
889 Ok(metadata) if metadata.is_dir() => return Some(next_entry.path()),
890 Ok(_) => {}
891 Err(e) => {
892 tracing::warn!(
893 error = %e,
894 path = %next_entry.path().display(),
895 "failed to read metadata for candidate worktree entry"
896 );
897 }
898 }
899 }
900 }
901
902 None
903}
904
905#[cfg(test)]
906mod tests {
907 use futures::future;
908 use tokio::time;
909
910 use std::env;
911 use std::fs as std_fs;
912 use std::process;
913 use std::time::Duration;
914
915 use super::*;
916
917 #[test]
918 fn keep_conflicted_rebase_when_retries_or_pr() {
919 assert!(keep_conflicted_rebase(1, None));
920 assert!(keep_conflicted_rebase(0, Some(12)));
921 assert!(keep_conflicted_rebase(2, Some(12)));
922 assert!(!keep_conflicted_rebase(0, None));
923 }
924
925 fn git(dir: &Path, args: &[&str]) {
927 let mut cmd = process::Command::new("git");
928 cmd.current_dir(dir);
929 if args.first() == Some(&"commit") {
931 cmd.args(["-c", "commit.gpgsign=false"]);
932 }
933 let out = cmd
934 .args(args)
935 .output()
936 .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
937 assert!(
938 out.status.success(),
939 "git {:?} failed:\nstdout: {}\nstderr: {}",
940 args,
941 String::from_utf8_lossy(&out.stdout),
942 String::from_utf8_lossy(&out.stderr)
943 );
944 }
945
946 #[tokio::test]
950 async fn resolve_branch_start_point_prefers_remote_over_default() {
951 let remote = tempfile::tempdir().unwrap();
952 git(remote.path(), &["init", "--bare"]);
953
954 let setup = tempfile::tempdir().unwrap();
956 git(
957 setup.path(),
958 &["clone", remote.path().to_str().unwrap(), "."],
959 );
960 git(setup.path(), &["config", "user.email", "t@t.com"]);
961 git(setup.path(), &["config", "user.name", "T"]);
962
963 std_fs::write(setup.path().join("README.md"), "main").unwrap();
965 git(setup.path(), &["add", "."]);
966 git(setup.path(), &["commit", "-m", "init"]);
967 git(setup.path(), &["push", "origin", "HEAD:main"]);
968
969 git(
971 setup.path(),
972 &["checkout", "-b", "gh-issue-42-fix-login-bug"],
973 );
974 std_fs::write(setup.path().join("feature.txt"), "work").unwrap();
975 git(setup.path(), &["add", "."]);
976 git(setup.path(), &["commit", "-m", "feature work"]);
977 git(
978 setup.path(),
979 &["push", "origin", "gh-issue-42-fix-login-bug"],
980 );
981
982 let local = tempfile::tempdir().unwrap();
985 git(
986 local.path(),
987 &["clone", remote.path().to_str().unwrap(), "."],
988 );
989 git(local.path(), &["config", "user.email", "t@t.com"]);
990 git(local.path(), &["config", "user.name", "T"]);
991 git(local.path(), &["fetch", "--all"]);
992 let has_local = process::Command::new("git")
994 .args([
995 "-C",
996 local.path().to_str().unwrap(),
997 "rev-parse",
998 "--verify",
999 "gh-issue-42-fix-login-bug",
1000 ])
1001 .output()
1002 .unwrap()
1003 .status
1004 .success();
1005 assert!(!has_local, "local branch should not exist before the test");
1006
1007 let repo_root = local.path().to_str().unwrap();
1008
1009 let start =
1011 resolve_branch_start_point(repo_root, "gh-issue-42-fix-login-bug", "main").await;
1012 assert_eq!(
1013 start, "origin/gh-issue-42-fix-login-bug",
1014 "should use remote branch as start point when origin/<branch> exists"
1015 );
1016 }
1017
1018 #[tokio::test]
1022 async fn resolve_branch_start_point_prefers_origin_default_over_local() {
1023 let remote = tempfile::tempdir().unwrap();
1024 git(remote.path(), &["init", "--bare"]);
1025
1026 let local = tempfile::tempdir().unwrap();
1027 git(
1028 local.path(),
1029 &["clone", remote.path().to_str().unwrap(), "."],
1030 );
1031 git(local.path(), &["config", "user.email", "t@t.com"]);
1032 git(local.path(), &["config", "user.name", "T"]);
1033
1034 std_fs::write(local.path().join("README.md"), "main").unwrap();
1036 git(local.path(), &["add", "."]);
1037 git(local.path(), &["commit", "-m", "init"]);
1038 git(local.path(), &["push", "origin", "HEAD:main"]);
1039 git(local.path(), &["fetch", "--all"]);
1040
1041 let repo_root = local.path().to_str().unwrap();
1042
1043 let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
1045 assert_eq!(
1046 start, "origin/main",
1047 "should anchor on origin/<default_branch> instead of local default"
1048 );
1049 }
1050
1051 fn git_stdout(dir: &Path, args: &[&str]) -> String {
1053 let out = process::Command::new("git")
1054 .args(args)
1055 .current_dir(dir)
1056 .output()
1057 .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
1058 assert!(
1059 out.status.success(),
1060 "git {:?} failed:\nstdout: {}\nstderr: {}",
1061 args,
1062 String::from_utf8_lossy(&out.stdout),
1063 String::from_utf8_lossy(&out.stderr)
1064 );
1065 String::from_utf8_lossy(&out.stdout).trim().to_string()
1066 }
1067
1068 #[tokio::test]
1073 #[serial_test::serial(orch_home)]
1074 async fn setup_worktree_anchors_on_origin_not_local_main() {
1075 let orch_home_dir = tempfile::tempdir().unwrap();
1077 let prev_orch_home = env::var("ORCH_HOME").ok();
1078 unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1080
1081 let remote = tempfile::tempdir().unwrap();
1083 git(remote.path(), &["init", "--bare"]);
1084
1085 let project = tempfile::tempdir().unwrap();
1087 git(
1088 project.path(),
1089 &["clone", remote.path().to_str().unwrap(), "."],
1090 );
1091 git(project.path(), &["config", "user.email", "t@t.com"]);
1092 git(project.path(), &["config", "user.name", "T"]);
1093
1094 std_fs::write(project.path().join("README.md"), "pushed\n").unwrap();
1096 git(project.path(), &["add", "."]);
1097 git(project.path(), &["commit", "-m", "pushed baseline"]);
1098 git(project.path(), &["push", "origin", "HEAD:main"]);
1099 let pushed_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);
1100
1101 git(project.path(), &["remote", "set-head", "origin", "main"]);
1103
1104 std_fs::write(project.path().join("LOCAL_ONLY.md"), "unpushed\n").unwrap();
1106 git(project.path(), &["add", "."]);
1107 git(project.path(), &["commit", "-m", "local unpushed commit"]);
1108 let local_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);
1109 assert_ne!(
1110 pushed_sha, local_sha,
1111 "precondition: local main must be ahead of origin/main"
1112 );
1113
1114 let setup = setup_worktree(
1116 "internal:1",
1117 "leak guard",
1118 project.path(),
1119 &None,
1120 "test/repo",
1121 )
1122 .await
1123 .expect("setup_worktree should succeed");
1124
1125 let wt_sha = git_stdout(&setup.work_dir, &["rev-parse", "HEAD"]);
1127 assert_eq!(
1128 wt_sha, pushed_sha,
1129 "worktree HEAD must equal origin/main, not local main"
1130 );
1131 assert_ne!(
1132 wt_sha, local_sha,
1133 "worktree must NOT include the operator's unpushed commit"
1134 );
1135 assert!(
1136 !setup.work_dir.join("LOCAL_ONLY.md").exists(),
1137 "unpushed-only file must not appear in the worktree"
1138 );
1139
1140 match prev_orch_home {
1142 Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1144 None => unsafe { env::remove_var("ORCH_HOME") },
1146 }
1147 }
1148
1149 #[tokio::test]
1151 #[serial_test::serial(orch_home)]
1152 async fn setup_worktree_keeps_the_conflicted_rebase_for_a_conflict_task() {
1153 let orch_home_dir = tempfile::tempdir().unwrap();
1154 let prev_orch_home = env::var("ORCH_HOME").ok();
1155 unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1157
1158 let remote = tempfile::tempdir().unwrap();
1159 git(remote.path(), &["init", "--bare"]);
1160 let project = tempfile::tempdir().unwrap();
1161 git(
1162 project.path(),
1163 &["clone", remote.path().to_str().unwrap(), "."],
1164 );
1165 git(project.path(), &["config", "user.email", "t@t.com"]);
1166 git(project.path(), &["config", "user.name", "T"]);
1167 std_fs::write(project.path().join("f.txt"), "base\n").unwrap();
1168 git(project.path(), &["add", "."]);
1169 git(project.path(), &["commit", "-m", "base"]);
1170 git(project.path(), &["push", "origin", "HEAD:main"]);
1171 git(project.path(), &["remote", "set-head", "origin", "main"]);
1172
1173 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1174 let id = store
1175 .create_internal("test/repo", "conflict", "", "test", "1", None)
1176 .await
1177 .unwrap();
1178 let task_id = format!("internal:{id}");
1179 let opt = Some(Arc::clone(&store));
1180
1181 let setup = setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1182 .await
1183 .unwrap();
1184 let wt = setup.work_dir.clone();
1185 git(&wt, &["config", "user.email", "t@t.com"]);
1186 git(&wt, &["config", "user.name", "T"]);
1187 std_fs::write(wt.join("f.txt"), "agent\n").unwrap();
1188 git(&wt, &["commit", "-am", "agent change"]);
1189 git(&wt, &["push", "origin", "HEAD"]);
1190
1191 std_fs::write(project.path().join("f.txt"), "main\n").unwrap();
1193 git(project.path(), &["commit", "-am", "main change"]);
1194 git(project.path(), &["push", "origin", "HEAD:main"]);
1195 git(&wt, &["fetch", "origin"]);
1196 let rebase = process::Command::new("git")
1197 .args(["rebase", "origin/main"])
1198 .current_dir(&wt)
1199 .output()
1200 .unwrap();
1201 assert!(!rebase.status.success(), "precondition: rebase conflicts");
1202 assert!(git_ops::rebase_in_progress(&wt).await);
1203
1204 store.increment(id, "merge_conflict_retries").await.unwrap();
1205
1206 setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1207 .await
1208 .unwrap();
1209 git_ops::rebase_on_default(&wt, "main").await;
1210 assert!(
1211 git_ops::rebase_in_progress(&wt).await,
1212 "the rebase auto_merge left must survive dispatch"
1213 );
1214
1215 match prev_orch_home {
1216 Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1218 None => unsafe { env::remove_var("ORCH_HOME") },
1220 }
1221 }
1222
1223 #[tokio::test]
1224 #[serial_test::serial(orch_home)]
1225 async fn setup_worktree_keeps_the_conflicted_rebase_when_the_task_has_a_pr() {
1226 let orch_home_dir = tempfile::tempdir().unwrap();
1227 let prev_orch_home = env::var("ORCH_HOME").ok();
1228 unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1230
1231 let remote = tempfile::tempdir().unwrap();
1232 git(remote.path(), &["init", "--bare"]);
1233 let project = tempfile::tempdir().unwrap();
1234 git(
1235 project.path(),
1236 &["clone", remote.path().to_str().unwrap(), "."],
1237 );
1238 git(project.path(), &["config", "user.email", "t@t.com"]);
1239 git(project.path(), &["config", "user.name", "T"]);
1240 std_fs::write(project.path().join("f.txt"), "base\n").unwrap();
1241 git(project.path(), &["add", "."]);
1242 git(project.path(), &["commit", "-m", "base"]);
1243 git(project.path(), &["push", "origin", "HEAD:main"]);
1244 git(project.path(), &["remote", "set-head", "origin", "main"]);
1245
1246 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1247 let id = store
1248 .create_internal("test/repo", "conflict", "", "test", "1", None)
1249 .await
1250 .unwrap();
1251 let task_id = format!("internal:{id}");
1252 let opt = Some(Arc::clone(&store));
1253
1254 let setup = setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1255 .await
1256 .unwrap();
1257 let wt = setup.work_dir.clone();
1258 git(&wt, &["config", "user.email", "t@t.com"]);
1259 git(&wt, &["config", "user.name", "T"]);
1260 std_fs::write(wt.join("f.txt"), "agent\n").unwrap();
1261 git(&wt, &["commit", "-am", "agent change"]);
1262 git(&wt, &["push", "origin", "HEAD"]);
1263
1264 std_fs::write(project.path().join("f.txt"), "main\n").unwrap();
1265 git(project.path(), &["commit", "-am", "main change"]);
1266 git(project.path(), &["push", "origin", "HEAD:main"]);
1267 git(&wt, &["fetch", "origin"]);
1268 let rebase = process::Command::new("git")
1269 .args(["rebase", "origin/main"])
1270 .current_dir(&wt)
1271 .output()
1272 .unwrap();
1273 assert!(!rebase.status.success(), "precondition: rebase conflicts");
1274 assert!(git_ops::rebase_in_progress(&wt).await);
1275
1276 store
1277 .set_fields(id, &[("pr_number", serde_json::json!(7))])
1278 .await
1279 .unwrap();
1280
1281 setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1282 .await
1283 .unwrap();
1284 git_ops::rebase_on_default(&wt, "main").await;
1285 assert!(
1286 git_ops::rebase_in_progress(&wt).await,
1287 "the rebase auto_merge left must survive dispatch when the task has a PR"
1288 );
1289
1290 match prev_orch_home {
1291 Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1293 None => unsafe { env::remove_var("ORCH_HOME") },
1295 }
1296 }
1297
1298 #[tokio::test]
1301 async fn resolve_branch_start_point_falls_back_to_local_default() {
1302 let local = tempfile::tempdir().unwrap();
1303 git(local.path(), &["init"]);
1304 git(local.path(), &["config", "user.email", "t@t.com"]);
1305 git(local.path(), &["config", "user.name", "T"]);
1306 git(local.path(), &["checkout", "-b", "main"]);
1307 std_fs::write(local.path().join("README.md"), "main").unwrap();
1308 git(local.path(), &["add", "."]);
1309 git(local.path(), &["commit", "-m", "init"]);
1310
1311 let repo_root = local.path().to_str().unwrap();
1312
1313 let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
1315 assert_eq!(
1316 start, "main",
1317 "should fall back to local default_branch when no remote refs exist"
1318 );
1319 }
1320
1321 #[test]
1322 fn branch_name_basic() {
1323 let name = branch_name("42", "Fix login bug");
1324 assert_eq!(name, "gh-issue-42-fix-login-bug");
1325 }
1326
1327 #[test]
1328 fn branch_name_internal_task() {
1329 let name = branch_name("internal:8", "Fix login bug");
1330 assert_eq!(name, "internal-8-fix-login-bug");
1331 }
1332
1333 #[test]
1334 fn branch_name_special_chars() {
1335 let name = branch_name("7", "Add OAuth2/OIDC (Google & GitHub)");
1336 assert_eq!(name, "gh-issue-7-add-oauth2-oidc-google-github");
1337 }
1338
1339 #[test]
1340 fn branch_name_truncates_long_slug() {
1341 let title =
1342 "This is a very long task title that should be truncated to forty characters maximum";
1343 let name = branch_name("1", title);
1344 let slug = name.strip_prefix("gh-issue-1-").unwrap();
1346 assert!(slug.len() <= 40, "slug length {} > 40", slug.len());
1347 }
1348
1349 #[test]
1350 fn branch_name_trims_trailing_dashes() {
1351 let name = branch_name("5", "Fix bug---");
1352 assert!(
1353 !name.ends_with('-'),
1354 "branch name should not end with dash: {name}"
1355 );
1356 }
1357
1358 #[test]
1359 fn branch_name_empty_title() {
1360 let name = branch_name("99", "");
1361 assert_eq!(name, "gh-issue-99");
1362 }
1363
1364 #[test]
1365 fn branch_name_empty_title_internal() {
1366 let name = branch_name("internal:99", "");
1367 assert_eq!(name, "internal-99");
1368 }
1369
1370 #[test]
1371 fn branch_name_all_special_chars() {
1372 let name = branch_name("10", "--- ??? ---");
1373 assert_eq!(name, "gh-issue-10");
1374 assert_ne!(name, "");
1375 }
1376
1377 #[test]
1378 fn branch_name_chinese_chars_no_panic() {
1379 let name = branch_name("265", "implement 用户认证 user auth");
1380 assert!(name.starts_with("gh-issue-265-"));
1381 assert_ne!(name, "");
1382 let slug = name.strip_prefix("gh-issue-265-").unwrap();
1383 assert!(slug.len() <= 40, "slug too long: {}", slug.len());
1384 assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
1385 }
1386
1387 #[test]
1388 fn task_id_from_worktree_name_parses_issue_branches() {
1389 assert_eq!(
1390 task_id_from_worktree_name("gh-issue-42-fix-login"),
1391 Some("42".to_string())
1392 );
1393 assert_eq!(
1394 task_id_from_worktree_name("gh-task-42-fix-login"),
1395 Some("42".to_string())
1396 );
1397 }
1398
1399 #[test]
1400 fn task_id_from_worktree_name_parses_internal_branches() {
1401 assert_eq!(
1402 task_id_from_worktree_name("internal-8-fix-login"),
1403 Some("internal:8".to_string())
1404 );
1405 assert_eq!(
1406 task_id_from_worktree_name("gh-issue-internal-8-fix-login"),
1407 Some("internal:8".to_string())
1408 );
1409 }
1410
1411 #[test]
1412 fn task_id_from_worktree_name_returns_none_for_unknown_names() {
1413 assert!(task_id_from_worktree_name("random-worktree").is_none());
1414 }
1415
1416 #[test]
1417 fn branch_name_emoji_no_panic() {
1418 let name = branch_name("265", "fix 🚀 deployment pipeline 🔥");
1419 assert!(name.starts_with("gh-issue-265-"));
1420 let slug = name.strip_prefix("gh-issue-265-").unwrap();
1421 assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
1422 }
1423
1424 #[test]
1425 fn branch_name_all_non_ascii_falls_back_to_task_id() {
1426 let name = branch_name("265", "用户认证 실행 тест");
1427 assert_eq!(name, "gh-issue-265");
1428 }
1429
1430 #[tokio::test]
1431 async fn find_existing_worktree_returns_none_for_missing() {
1432 let dir = tempfile::tempdir().unwrap();
1433 assert!(find_existing_worktree(dir.path(), "42").await.is_none());
1434 }
1435
1436 #[tokio::test]
1437 async fn find_existing_worktree_matches_prefix() {
1438 let dir = tempfile::tempdir().unwrap();
1439 let wt_dir = dir.path().join("gh-issue-42-fix-login-bug");
1440 fs::create_dir(&wt_dir).await.unwrap();
1441
1442 let result = find_existing_worktree(dir.path(), "42").await;
1443 assert_eq!(result, Some(wt_dir));
1444 }
1445
1446 #[tokio::test]
1447 async fn find_existing_worktree_matches_internal_prefix() {
1448 let dir = tempfile::tempdir().unwrap();
1449 let wt_dir = dir.path().join("internal-8-fix");
1450 fs::create_dir(&wt_dir).await.unwrap();
1451
1452 let result = find_existing_worktree(dir.path(), "internal:8").await;
1453 assert_eq!(result, Some(wt_dir));
1454 }
1455
1456 #[tokio::test]
1457 async fn find_existing_worktree_matches_legacy_gh_task_prefix() {
1458 let dir = tempfile::tempdir().unwrap();
1460 let wt_dir = dir.path().join("gh-task-internal-8-fix");
1461 fs::create_dir(&wt_dir).await.unwrap();
1462
1463 let result = find_existing_worktree(dir.path(), "internal:8").await;
1464 assert_eq!(result, Some(wt_dir));
1465 }
1466
1467 #[tokio::test]
1468 async fn find_existing_worktree_matches_legacy_external_prefix() {
1469 let dir = tempfile::tempdir().unwrap();
1471 let wt_dir = dir.path().join("gh-task-42-fix-login-bug");
1472 fs::create_dir(&wt_dir).await.unwrap();
1473
1474 let result = find_existing_worktree(dir.path(), "42").await;
1475 assert_eq!(result, Some(wt_dir));
1476 }
1477
1478 #[tokio::test]
1479 async fn find_existing_worktree_ignores_other_tasks() {
1480 let dir = tempfile::tempdir().unwrap();
1481 fs::create_dir(dir.path().join("gh-issue-43-other-task"))
1482 .await
1483 .unwrap();
1484
1485 assert!(find_existing_worktree(dir.path(), "42").await.is_none());
1486 }
1487
1488 #[tokio::test]
1492 async fn resolve_parent_branch_no_store_returns_none() {
1493 let dir = tempfile::tempdir().unwrap();
1494 let result = resolve_parent_branch(&None, Some(1), dir.path()).await;
1495 assert!(result.is_none());
1496 }
1497
1498 #[tokio::test]
1500 async fn resolve_parent_branch_no_parent_id_returns_none() {
1501 let dir = tempfile::tempdir().unwrap();
1502 let result = resolve_parent_branch(&None, None, dir.path()).await;
1503 assert!(result.is_none());
1504 }
1505
1506 #[tokio::test]
1508 async fn resolve_parent_branch_empty_parent_branch_returns_none() {
1509 let db_dir = tempfile::tempdir().unwrap();
1510 let db_path = db_dir.path().join("test.db");
1511 let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1512
1513 let parent_id = store
1515 .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1516 .await
1517 .unwrap();
1518
1519 let dir = tempfile::tempdir().unwrap();
1520 let store_opt = Some(store);
1521 let result = resolve_parent_branch(&store_opt, Some(parent_id), dir.path()).await;
1522 assert!(result.is_none());
1523 }
1524
1525 #[tokio::test]
1527 async fn resolve_parent_branch_returns_parent_branch_and_worktree() {
1528 let db_dir = tempfile::tempdir().unwrap();
1529 let db_path = db_dir.path().join("test.db");
1530 let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1531
1532 let parent_id = store
1534 .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1535 .await
1536 .unwrap();
1537 store
1538 .set_fields(
1539 parent_id,
1540 &[("branch", serde_json::json!("gh-issue-99-parent-task"))],
1541 )
1542 .await
1543 .unwrap();
1544
1545 let worktrees_base = tempfile::tempdir().unwrap();
1546 let store_opt = Some(store);
1547 let result =
1548 resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;
1549
1550 let (branch, wt) = result.expect("should return parent branch");
1551 assert_eq!(branch, "gh-issue-99-parent-task");
1552 assert_eq!(wt, worktrees_base.path().join("gh-issue-99-parent-task"));
1553 }
1554
1555 #[tokio::test]
1557 async fn resolve_parent_branch_prefers_existing_worktree_path() {
1558 let db_dir = tempfile::tempdir().unwrap();
1559 let db_path = db_dir.path().join("test.db");
1560 let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1561
1562 let worktrees_base = tempfile::tempdir().unwrap();
1563 let parent_wt_dir = worktrees_base.path().join("custom-worktree-path");
1565 fs::create_dir_all(&parent_wt_dir).await.unwrap();
1566
1567 let parent_id = store
1568 .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1569 .await
1570 .unwrap();
1571 store
1572 .set_fields(
1573 parent_id,
1574 &[
1575 ("branch", serde_json::json!("gh-issue-99-parent-task")),
1576 (
1577 "worktree",
1578 serde_json::json!(parent_wt_dir.to_string_lossy().as_ref()),
1579 ),
1580 ],
1581 )
1582 .await
1583 .unwrap();
1584
1585 let store_opt = Some(store);
1586 let result =
1587 resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;
1588
1589 let (branch, wt) = result.expect("should return parent branch");
1590 assert_eq!(branch, "gh-issue-99-parent-task");
1591 assert_eq!(wt, parent_wt_dir);
1592 }
1593
1594 #[tokio::test]
1599 async fn concurrent_worktree_checks_no_starvation() {
1600 let temp_dir = tempfile::tempdir().unwrap();
1601 let worktrees_base = temp_dir.path().join("worktrees");
1602 fs::create_dir_all(&worktrees_base).await.unwrap();
1603
1604 let wt_dir = worktrees_base.join("gh-issue-123-test");
1606 fs::create_dir_all(&wt_dir).await.unwrap();
1607 let gitdir_target = temp_dir
1609 .path()
1610 .join(".git")
1611 .join("worktrees")
1612 .join("gh-issue-123-test");
1613 fs::create_dir_all(&gitdir_target).await.unwrap();
1614 let git_file = wt_dir.join(".git");
1615 fs::write(&git_file, format!("gitdir: {}\n", gitdir_target.display()))
1616 .await
1617 .unwrap();
1618
1619 let handles: Vec<_> = (0..20)
1622 .map(|i| {
1623 let wb = worktrees_base.clone();
1624 let wd = wt_dir.clone();
1625 tokio::spawn(async move {
1626 if i % 2 == 0 {
1627 list_project_worktrees(&wb).await.ok();
1628 } else {
1629 validate_worktree_gitdir(&wd).await;
1630 }
1631 })
1632 })
1633 .collect();
1634
1635 let results = time::timeout(Duration::from_secs(10), async {
1637 future::join_all(handles).await
1638 })
1639 .await;
1640
1641 assert!(
1642 results.is_ok(),
1643 "concurrent worktree checks timed out (starvation?)"
1644 );
1645 }
1646
1647 #[test]
1650 fn normalize_branch_name_strips_origin_prefix() {
1651 assert_eq!(
1652 normalize_branch_name("origin/main"),
1653 Some("main".to_string())
1654 );
1655 assert_eq!(
1656 normalize_branch_name("origin/develop"),
1657 Some("develop".to_string())
1658 );
1659 }
1660
1661 #[test]
1662 fn normalize_branch_name_strips_full_ref_path() {
1663 assert_eq!(
1664 normalize_branch_name("refs/remotes/origin/main"),
1665 Some("main".to_string())
1666 );
1667 assert_eq!(
1668 normalize_branch_name("refs/remotes/origin/develop"),
1669 Some("develop".to_string())
1670 );
1671 }
1672
1673 #[test]
1674 fn normalize_branch_name_strips_remotes_prefix() {
1675 assert_eq!(
1676 normalize_branch_name("remotes/origin/main"),
1677 Some("main".to_string())
1678 );
1679 }
1680
1681 #[test]
1682 fn normalize_branch_name_passes_through_plain_branch() {
1683 assert_eq!(normalize_branch_name("main"), Some("main".to_string()));
1684 assert_eq!(normalize_branch_name("master"), Some("master".to_string()));
1685 assert_eq!(
1686 normalize_branch_name("feature/foo"),
1687 Some("feature/foo".to_string())
1688 );
1689 }
1690
1691 #[test]
1692 fn normalize_branch_name_rejects_empty_and_refs_only() {
1693 assert_eq!(normalize_branch_name(""), None);
1694 assert_eq!(normalize_branch_name(" "), None);
1695 assert_eq!(
1696 normalize_branch_name("refs/heads/main"),
1697 Some("main".to_string())
1698 );
1699 }
1700}