Skip to main content

orch/engine/git/
worktree.rs

1//! Git worktree management for task execution.
2//!
3//! Each task runs in an isolated worktree to prevent conflicts.
4//! Worktrees are stored at `~/.orch/worktrees/<project>/<branch>/`.
5
6use crate::engine::git::git_ops;
7use crate::engine::git::git_ops::RebaseOutcome;
8use crate::engine::git::git_ops::StashRebaseOpts;
9use crate::github::http::GhHttp;
10use crate::store;
11use crate::store::TaskStore;
12use crate::sys::cmd::CommandErrorContext;
13use crate::sys::home;
14use std::path::{Path, PathBuf};
15use std::sync::Arc;
16use tokio::fs;
17use tokio::process::Command;
18use tokio::task;
19
20/// Result of worktree setup.
21#[derive(Debug)]
22pub struct WorktreeSetup {
23    /// The directory where the agent will work
24    pub work_dir: PathBuf,
25    /// The branch name
26    pub branch: String,
27    /// The default branch of the repository
28    pub default_branch: String,
29    /// The main project directory (original, not worktree)
30    pub main_project_dir: PathBuf,
31}
32
33/// Canonical project name used under `~/.orch/worktrees/`.
34pub 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
45/// Base worktrees directory for a project.
46pub fn project_worktrees_dir(project_dir: &Path) -> PathBuf {
47    home::worktrees_dir()
48        .unwrap_or_default()
49        .join(project_name(project_dir))
50}
51
52/// List all worktree directories for a project.
53pub 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
71/// Extract a task ID from a worktree directory name.
72pub 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
92/// A content conflict is for the agent when auto_merge already retried or a PR exists
93pub fn keep_conflicted_rebase(merge_conflict_retries: i32, pr_number: Option<i32>) -> bool {
94    merge_conflict_retries > 0 || pr_number.is_some()
95}
96
97/// Abort any rebase in progress for a worktree.
98pub 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
106/// Rebase a worktree on top of `origin/{default_branch}`.
107///
108/// Stashes any uncommitted changes before rebasing to avoid failing the
109/// rebase due to "You have unstaged changes".  The stash is restored after
110/// the rebase succeeds; on failure the stash is preserved for manual recovery.
111pub 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
127/// Generate a branch name from task ID and title.
128///
129/// Format: `internal-{id}-{slug}` for internal tasks, `gh-issue-{id}-{slug}` for external.
130/// Slug is lowercase, non-alphanum→`-`, max 40 chars.
131pub 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    // Collapse consecutive dashes and trim
145    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    // Truncate slug to 40 chars
161    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
171/// Replace characters in `task_id` that are not safe for branch/worktree names.
172fn sanitize_task_id(task_id: &str) -> String {
173    task_id.replace(':', "-")
174}
175
176/// Normalize a git ref output to a plain branch name.
177///
178/// Handles the various output formats that different git versions and
179/// configurations can produce for remote HEAD refs:
180/// - `origin/main` → `main`
181/// - `refs/remotes/origin/main` → `main`
182/// - `remotes/origin/main` → `main`
183/// - `main` → `main`
184fn normalize_branch_name(raw: &str) -> Option<String> {
185    let branch = raw.trim();
186    if branch.is_empty() {
187        return None;
188    }
189
190    // Strip known prefixes in order of specificity.
191    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
204/// Detect the default branch of a repository.
205///
206/// Tries multiple strategies and normalizes the result so callers always
207/// receive a clean branch name like `"main"`, never a raw ref path.
208pub async fn detect_default_branch(project_dir: &Path) -> String {
209    // Strategy 1: symbolic-ref (fast, works when origin/HEAD is set).
210    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    // Strategy 2: rev-parse --abbrev-ref (resolves symref to target).
226    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    // Strategy 3: parse `git remote show origin` output.
242    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
272/// Resolve PROJECT_DIR to the main repo if it's inside a worktree.
273///
274/// This prevents nested worktrees when subtasks inherit a parent's worktree dir.
275pub 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
304/// Resolve the starting point for creating a new local branch.
305///
306/// Preference order:
307/// 1. `origin/<branch>` if it exists — cleanup kept the remote branch after
308///    deleting the local one, so resume from the agent's committed work.
309/// 2. `origin/<default_branch>` if it exists — anchors on the pushed tip of
310///    the default branch so unpushed local commits in the operator's main
311///    checkout don't leak into the worktree.
312/// 3. `default_branch` as a last resort (no origin remote / never fetched).
313pub(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
339/// Validate that a worktree directory has a working gitdir link.
340///
341/// In a git worktree, `.git` is a file containing `gitdir: /path/to/.git/worktrees/<name>`.
342/// Returns `false` when the `.git` file is missing or points to a non-existent gitdir,
343/// indicating the worktree metadata is broken and the directory should be cleaned up.
344pub async fn validate_worktree_gitdir(worktree_dir: &Path) -> bool {
345    let git_file = worktree_dir.join(".git");
346    // Use tokio::fs::metadata for async-safe existence check
347    if fs::metadata(&git_file).await.is_err() {
348        return false;
349    }
350    // In a linked worktree .git is a file; in the main repo it's a directory (always valid).
351    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    // Expected format: "gitdir: /absolute/path/to/.git/worktrees/<name>\n"
359    // Use spawn_blocking for the final exists check on the resolved path
360    if let Some(gitdir_path) = content
361        .lines()
362        .next()
363        .and_then(|l| l.strip_prefix("gitdir: "))
364    {
365        // Use async metadata for the gitdir check too.
366        return fs::metadata(gitdir_path.trim())
367            .await
368            .is_ok_and(|m| m.is_dir());
369    }
370    false
371}
372
373/// Resolve the branch and worktree directory from a parent task, if available.
374///
375/// When a child task is created from a mention on a PR, it should work on the
376/// parent task's branch so changes are committed to the existing PR rather than
377/// a new one being opened.
378#[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        // Use async metadata to avoid blocking the reactor thread.
396        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
414/// Set up a worktree for task execution.
415///
416/// Returns the working directory, branch name, and default branch.
417pub 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    // Resolve to main repo (avoid nested worktrees)
425    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    // Check if we have a saved branch/worktree in store
432    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            // Use spawn_blocking for blocking Path::exists call in async context
470            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            // Child task with no saved branch: inherit parent's branch so we
489            // commit onto the existing PR instead of opening a new one.
490            (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        // No store record — check parent branch, then existing worktree by prefix
497        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    // Abort a leftover rebase unless auto_merge left a content conflict for the agent
525    // Use tokio::fs for async-safe existence check
526    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        // Check for a corrupted git index (e.g. "error: could not write index").
545        // `git status` reads the index; a non-zero exit with index-related stderr
546        // indicates corruption that will cause every subsequent git operation to
547        // fail, leading to an infinite stuck-recovery loop.  When detected, nuke
548        // the worktree and recreate it from scratch below.
549        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            // Remove git worktree reference first, then delete the directory.
571            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 the directory still exists (e.g. worktree remove failed), remove it
583            // manually so the worktree-creation block below re-creates it cleanly.
584            if fs::metadata(&worktree_dir).await.is_ok() {
585                let _ = fs::remove_dir_all(&worktree_dir).await;
586            }
587            // Prune stale worktree metadata so git won't complain on re-add.
588            let _ = Command::new("git")
589                .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
590                .output_with_context()
591                .await;
592        }
593    }
594
595    // Create worktree if it doesn't exist
596    if fs::metadata(&worktree_dir).await.is_err() {
597        tracing::info!(task_id, worktree = %worktree_dir.display(), "creating worktree");
598
599        // Fetch latest so `origin/<default_branch>` (and any pre-existing
600        // remote task branch) is fresh. We deliberately do NOT `git pull` on
601        // the operator's checkout: branching from `origin/<default_branch>`
602        // means unpushed local commits or in-progress work on `main` never
603        // leak into the new worktree.
604        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        // Create local branch. Prefer `origin/<branch>` when it already exists
617        // (recovery case: cleanup deleted local branch but kept the remote),
618        // so the new worktree starts from the agent's committed work instead
619        // of the default branch tip.
620        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        // Create worktree
638        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                // Retry: prune and recreate
684                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    // Link issue to branch via GitHub API (Development sidebar).
771    // Must happen before the agent pushes — createLinkedBranch only works
772    // for branches that don't yet exist on GitHub.
773    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    // Save worktree info to store
791    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
823/// Find an existing worktree by task ID prefix.
824async 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                // Log the error but continue scanning - a single entry error shouldn't stop us
879                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    /// Helper: run a git command in `dir`, panicking on failure.
926    fn git(dir: &Path, args: &[&str]) {
927        let mut cmd = process::Command::new("git");
928        cmd.current_dir(dir);
929        // Global commit.gpgsign calls the operator's signer (1Password)
930        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    /// When `origin/<branch>` exists, `resolve_branch_start_point` should
947    /// return `"origin/<branch>"` so that the worktree starts from the
948    /// already-committed work, not from the default branch tip.
949    #[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        // Set up a working clone to push branches to the remote.
955        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        // Initial commit on main.
964        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        // Feature branch with a distinct commit.
970        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        // Local repo: clone + fetch, but NO local branch (simulates cleanup
983        // with keep_remote_branch=true where local branch was deleted).
984        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        // Confirm the local branch does NOT exist; only the remote tracking ref.
993        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        // With remote branch present → should prefer origin/<branch>.
1010        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    /// When `origin/<branch>` does NOT exist but `origin/<default_branch>` does,
1019    /// `resolve_branch_start_point` should anchor on the remote default branch
1020    /// so unpushed local commits on `main` don't leak into the worktree.
1021    #[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        // Commit something so origin/main exists.
1035        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        // Branch "no-such-branch" has never been pushed, but origin/main exists.
1044        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    /// Capture stdout of a git command in `dir`.
1052    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    /// End-to-end guard for the operator-main-leak fix: when the operator's
1069    /// local `main` has commits that are not yet pushed, `setup_worktree`
1070    /// must branch from `origin/main` and produce a worktree whose HEAD is
1071    /// the pushed tip — never the local-only tip.
1072    #[tokio::test]
1073    #[serial_test::serial(orch_home)]
1074    async fn setup_worktree_anchors_on_origin_not_local_main() {
1075        // Isolate ORCH_HOME so the worktree lands in a temp dir.
1076        let orch_home_dir = tempfile::tempdir().unwrap();
1077        let prev_orch_home = env::var("ORCH_HOME").ok();
1078        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1079        unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1080
1081        // Bare "remote".
1082        let remote = tempfile::tempdir().unwrap();
1083        git(remote.path(), &["init", "--bare"]);
1084
1085        // Operator's project clone.
1086        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        // Pushed baseline on main.
1095        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        // Ensure origin/HEAD is set so detect_default_branch resolves "main".
1102        git(project.path(), &["remote", "set-head", "origin", "main"]);
1103
1104        // Operator's WIP: an unpushed local commit on top of main.
1105        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        // Run setup_worktree for a fresh internal task (skips GitHub linking).
1115        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        // Worktree must sit on the pushed tip, not the local-only tip.
1126        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        // Restore ORCH_HOME.
1141        match prev_orch_home {
1142            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1143            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1144            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1145            None => unsafe { env::remove_var("ORCH_HOME") },
1146        }
1147    }
1148
1149    /// auto_merge leaves a conflicted rebase for the agent, dispatch must not abort it.
1150    #[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        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1156        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        // main moves on with a conflicting change, then the rebase stops on it
1192        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            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1217            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1218            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1219            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        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1229        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            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1292            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1293            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1294            None => unsafe { env::remove_var("ORCH_HOME") },
1295        }
1296    }
1297
1298    /// When neither `origin/<branch>` nor `origin/<default_branch>` exist,
1299    /// fall back to the local default branch name as a last resort.
1300    #[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        // No remote at all → fall back to "main".
1314        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        // slug part should be max 40 chars
1345        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        // Old worktrees created before the rename should still be found
1459        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        // Old external worktrees with gh-task- prefix should still be found
1470        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    // --- resolve_parent_branch tests ---
1489
1490    /// No store → always returns None.
1491    #[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    /// parent_id = None → always returns None regardless of store.
1499    #[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    /// Parent exists but has empty branch → returns None so child gets its own branch.
1507    #[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        // Create parent task — branch defaults to empty string
1514        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    /// Parent has a branch set → child inherits that branch and worktree path.
1526    #[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        // Create parent task and set its branch
1533        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    /// When parent has both branch and a worktree path that exists, use the worktree path.
1556    #[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        // Create the parent worktree directory
1564        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    /// Regression test: concurrent calls to list_project_worktrees and
1595    /// validate_worktree_gitdir should not starve the Tokio worker thread
1596    /// pool. This was broken by blocking Path::exists/is_dir calls in async
1597    /// functions (issue #2467).
1598    #[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        // Create a fake worktree with valid gitdir
1605        let wt_dir = worktrees_base.join("gh-issue-123-test");
1606        fs::create_dir_all(&wt_dir).await.unwrap();
1607        // Create .git as a file pointing to a real directory (worktree link)
1608        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        // Spawn many concurrent tasks - if any use blocking calls, they'll
1620        // block the worker thread and cause timeout or deadlock.
1621        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        // Wait with timeout to detect starvation
1636        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    // --- normalize_branch_name tests ---
1648
1649    #[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}