Skip to main content

orch/engine/runner/
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::cmd::CommandErrorContext;
7use crate::engine::runner::git_ops;
8use crate::engine::runner::git_ops::RebaseOutcome;
9use crate::engine::runner::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/// 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 cloned = match super::cow::create_worktree(
643            &main_dir,
644            &project_name(&main_dir),
645            &worktree_dir,
646            &branch_name_str,
647            &default_branch,
648        )
649        .await
650        {
651            Ok(()) => {
652                tracing::info!(task_id, "worktree cloned from project template");
653                true
654            }
655            Err(e) => {
656                tracing::debug!(task_id, error = %e, "copy-on-write worktree unavailable, using git worktree add");
657                false
658            }
659        };
660
661        if !cloned {
662            let output = Command::new("git")
663                .args([
664                    "-C",
665                    &main_dir.to_string_lossy(),
666                    "worktree",
667                    "add",
668                    &worktree_dir.to_string_lossy(),
669                    &branch_name_str,
670                ])
671                .output_with_context()
672                .await?;
673
674            if !output.status.success() && fs::metadata(&worktree_dir).await.is_err() {
675                let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
676                let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
677                // Retry: prune and recreate
678                tracing::warn!(
679                    task_id,
680                    stdout = %stdout,
681                    stderr = %stderr,
682                    "worktree creation failed, retrying after prune"
683                );
684
685                let _ = Command::new("git")
686                    .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
687                    .output_with_context()
688                    .await;
689
690                let _ = Command::new("git")
691                    .args([
692                        "-C",
693                        &main_dir.to_string_lossy(),
694                        "branch",
695                        "-D",
696                        &branch_name_str,
697                    ])
698                    .output_with_context()
699                    .await;
700
701                let _ = Command::new("git")
702                    .args([
703                        "-C",
704                        &main_dir.to_string_lossy(),
705                        "branch",
706                        &branch_name_str,
707                        &start_point,
708                    ])
709                    .output_with_context()
710                    .await;
711
712                let retry_output = Command::new("git")
713                    .args([
714                        "-C",
715                        &main_dir.to_string_lossy(),
716                        "worktree",
717                        "add",
718                        &worktree_dir.to_string_lossy(),
719                        &branch_name_str,
720                    ])
721                    .output_with_context()
722                    .await;
723
724                let mut retry_stdout = String::new();
725                let mut retry_stderr = String::new();
726                let mut retry_error = String::new();
727                match retry_output {
728                    Ok(output) => {
729                        retry_stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
730                        retry_stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
731                        tracing::warn!(
732                            task_id,
733                            stdout = %retry_stdout,
734                            stderr = %retry_stderr,
735                            "worktree creation retry failed"
736                        );
737                    }
738                    Err(err) => {
739                        retry_error = err.to_string();
740                        tracing::warn!(
741                            task_id,
742                            error = %retry_error,
743                            "worktree creation retry failed to run"
744                        );
745                    }
746                }
747
748                if fs::metadata(&worktree_dir).await.is_err() {
749                    anyhow::bail!(
750                        "failed to create worktree at {} for task {} (stdout: {}, stderr: {}, retry stdout: {}, retry stderr: {}, retry error: {})",
751                        worktree_dir.display(),
752                        task_id,
753                        stdout,
754                        stderr,
755                        retry_stdout,
756                        retry_stderr,
757                        retry_error
758                    );
759                }
760            }
761        }
762    }
763
764    // Link issue to branch via GitHub API (Development sidebar).
765    // Must happen before the agent pushes — createLinkedBranch only works
766    // for branches that don't yet exist on GitHub.
767    if !task_id.starts_with("internal:")
768        && let Ok(issue_num) = task_id.parse::<u64>()
769        && let Ok(gh) = GhHttp::new()
770    {
771        match gh
772            .link_issue_to_branch(repo, issue_num, &branch_name_str)
773            .await
774        {
775            Ok(id) => {
776                tracing::info!(task_id, branch = %branch_name_str, linked = %id, "linked issue to branch");
777            }
778            Err(e) => {
779                tracing::debug!(task_id, error = %e, "failed to link issue to branch (non-fatal)");
780            }
781        }
782    }
783
784    // Save worktree info to store
785    if let Err(e) = store::store_set_result(
786        store,
787        repo,
788        task_id,
789        &[
790            (
791                "worktree",
792                serde_json::json!(worktree_dir.display().to_string()),
793            ),
794            ("branch", serde_json::json!(branch_name_str)),
795        ],
796    )
797    .await
798    {
799        tracing::warn!(task_id, err = %e, "failed to save worktree info to store (non-fatal)");
800    }
801
802    tracing::info!(
803        task_id,
804        worktree = %worktree_dir.display(),
805        branch = %branch_name_str,
806        "worktree ready"
807    );
808
809    Ok(WorktreeSetup {
810        work_dir: worktree_dir,
811        branch: branch_name_str,
812        default_branch,
813        main_project_dir: main_dir,
814    })
815}
816
817/// Find an existing worktree by task ID prefix.
818async fn discard_worktree(main_dir: &Path, worktree_dir: &Path) {
819    let _ = Command::new("git")
820        .args([
821            "-C",
822            &main_dir.to_string_lossy(),
823            "worktree",
824            "remove",
825            "--force",
826            &worktree_dir.to_string_lossy(),
827        ])
828        .output_with_context()
829        .await;
830    if fs::metadata(worktree_dir).await.is_ok() {
831        let _ = fs::remove_dir_all(worktree_dir).await;
832    }
833    let _ = Command::new("git")
834        .args(["-C", &main_dir.to_string_lossy(), "worktree", "prune"])
835        .output_with_context()
836        .await;
837}
838
839async fn find_existing_worktree(worktrees_base: &Path, task_id: &str) -> Option<PathBuf> {
840    let (prefix_new, legacy_prefixes) = if let Some(num) = task_id.strip_prefix("internal:") {
841        (
842            format!("internal-{num}-"),
843            vec![
844                format!("gh-task-internal-{num}-"),
845                format!("gh-issue-internal-{num}-"),
846            ],
847        )
848    } else {
849        let sanitized_id = sanitize_task_id(task_id);
850        (
851            format!("gh-issue-{sanitized_id}-"),
852            vec![format!("gh-task-{sanitized_id}-")],
853        )
854    };
855
856    let mut entries = match fs::read_dir(worktrees_base).await {
857        Ok(e) => e,
858        Err(e) => {
859            tracing::warn!(
860                error = %e,
861                path = %worktrees_base.display(),
862                "failed to read worktrees directory while searching for existing worktree"
863            );
864            return None;
865        }
866    };
867    loop {
868        let next_entry = match entries.next_entry().await {
869            Ok(Some(entry)) => entry,
870            Ok(None) => break,
871            Err(e) => {
872                // Log the error but continue scanning - a single entry error shouldn't stop us
873                tracing::warn!(error = %e, "failed to read directory entry while searching for worktree");
874                continue;
875            }
876        };
877
878        let name = next_entry.file_name().to_string_lossy().to_string();
879        let matches =
880            name.starts_with(&prefix_new) || legacy_prefixes.iter().any(|p| name.starts_with(p));
881        if matches {
882            match next_entry.metadata().await {
883                Ok(metadata) if metadata.is_dir() => return Some(next_entry.path()),
884                Ok(_) => {}
885                Err(e) => {
886                    tracing::warn!(
887                        error = %e,
888                        path = %next_entry.path().display(),
889                        "failed to read metadata for candidate worktree entry"
890                    );
891                }
892            }
893        }
894    }
895
896    None
897}
898
899#[cfg(test)]
900mod tests {
901    use futures::future;
902    use tokio::time;
903
904    use std::env;
905    use std::fs as std_fs;
906    use std::process;
907    use std::time::Duration;
908
909    use super::*;
910
911    #[test]
912    fn keep_conflicted_rebase_when_retries_or_pr() {
913        assert!(keep_conflicted_rebase(1, None));
914        assert!(keep_conflicted_rebase(0, Some(12)));
915        assert!(keep_conflicted_rebase(2, Some(12)));
916        assert!(!keep_conflicted_rebase(0, None));
917    }
918
919    /// Helper: run a git command in `dir`, panicking on failure.
920    fn git(dir: &Path, args: &[&str]) {
921        let mut cmd = process::Command::new("git");
922        cmd.current_dir(dir);
923        // Global commit.gpgsign calls the operator's signer (1Password)
924        if args.first() == Some(&"commit") {
925            cmd.args(["-c", "commit.gpgsign=false"]);
926        }
927        let out = cmd
928            .args(args)
929            .output()
930            .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
931        assert!(
932            out.status.success(),
933            "git {:?} failed:\nstdout: {}\nstderr: {}",
934            args,
935            String::from_utf8_lossy(&out.stdout),
936            String::from_utf8_lossy(&out.stderr)
937        );
938    }
939
940    /// When `origin/<branch>` exists, `resolve_branch_start_point` should
941    /// return `"origin/<branch>"` so that the worktree starts from the
942    /// already-committed work, not from the default branch tip.
943    #[tokio::test]
944    async fn resolve_branch_start_point_prefers_remote_over_default() {
945        let remote = tempfile::tempdir().unwrap();
946        git(remote.path(), &["init", "--bare"]);
947
948        // Set up a working clone to push branches to the remote.
949        let setup = tempfile::tempdir().unwrap();
950        git(
951            setup.path(),
952            &["clone", remote.path().to_str().unwrap(), "."],
953        );
954        git(setup.path(), &["config", "user.email", "t@t.com"]);
955        git(setup.path(), &["config", "user.name", "T"]);
956
957        // Initial commit on main.
958        std_fs::write(setup.path().join("README.md"), "main").unwrap();
959        git(setup.path(), &["add", "."]);
960        git(setup.path(), &["commit", "-m", "init"]);
961        git(setup.path(), &["push", "origin", "HEAD:main"]);
962
963        // Feature branch with a distinct commit.
964        git(
965            setup.path(),
966            &["checkout", "-b", "gh-issue-42-fix-login-bug"],
967        );
968        std_fs::write(setup.path().join("feature.txt"), "work").unwrap();
969        git(setup.path(), &["add", "."]);
970        git(setup.path(), &["commit", "-m", "feature work"]);
971        git(
972            setup.path(),
973            &["push", "origin", "gh-issue-42-fix-login-bug"],
974        );
975
976        // Local repo: clone + fetch, but NO local branch (simulates cleanup
977        // with keep_remote_branch=true where local branch was deleted).
978        let local = tempfile::tempdir().unwrap();
979        git(
980            local.path(),
981            &["clone", remote.path().to_str().unwrap(), "."],
982        );
983        git(local.path(), &["config", "user.email", "t@t.com"]);
984        git(local.path(), &["config", "user.name", "T"]);
985        git(local.path(), &["fetch", "--all"]);
986        // Confirm the local branch does NOT exist; only the remote tracking ref.
987        let has_local = process::Command::new("git")
988            .args([
989                "-C",
990                local.path().to_str().unwrap(),
991                "rev-parse",
992                "--verify",
993                "gh-issue-42-fix-login-bug",
994            ])
995            .output()
996            .unwrap()
997            .status
998            .success();
999        assert!(!has_local, "local branch should not exist before the test");
1000
1001        let repo_root = local.path().to_str().unwrap();
1002
1003        // With remote branch present → should prefer origin/<branch>.
1004        let start =
1005            resolve_branch_start_point(repo_root, "gh-issue-42-fix-login-bug", "main").await;
1006        assert_eq!(
1007            start, "origin/gh-issue-42-fix-login-bug",
1008            "should use remote branch as start point when origin/<branch> exists"
1009        );
1010    }
1011
1012    /// When `origin/<branch>` does NOT exist but `origin/<default_branch>` does,
1013    /// `resolve_branch_start_point` should anchor on the remote default branch
1014    /// so unpushed local commits on `main` don't leak into the worktree.
1015    #[tokio::test]
1016    async fn resolve_branch_start_point_prefers_origin_default_over_local() {
1017        let remote = tempfile::tempdir().unwrap();
1018        git(remote.path(), &["init", "--bare"]);
1019
1020        let local = tempfile::tempdir().unwrap();
1021        git(
1022            local.path(),
1023            &["clone", remote.path().to_str().unwrap(), "."],
1024        );
1025        git(local.path(), &["config", "user.email", "t@t.com"]);
1026        git(local.path(), &["config", "user.name", "T"]);
1027
1028        // Commit something so origin/main exists.
1029        std_fs::write(local.path().join("README.md"), "main").unwrap();
1030        git(local.path(), &["add", "."]);
1031        git(local.path(), &["commit", "-m", "init"]);
1032        git(local.path(), &["push", "origin", "HEAD:main"]);
1033        git(local.path(), &["fetch", "--all"]);
1034
1035        let repo_root = local.path().to_str().unwrap();
1036
1037        // Branch "no-such-branch" has never been pushed, but origin/main exists.
1038        let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
1039        assert_eq!(
1040            start, "origin/main",
1041            "should anchor on origin/<default_branch> instead of local default"
1042        );
1043    }
1044
1045    /// Capture stdout of a git command in `dir`.
1046    fn git_stdout(dir: &Path, args: &[&str]) -> String {
1047        let out = process::Command::new("git")
1048            .args(args)
1049            .current_dir(dir)
1050            .output()
1051            .unwrap_or_else(|e| panic!("git {args:?} failed to start: {e}"));
1052        assert!(
1053            out.status.success(),
1054            "git {:?} failed:\nstdout: {}\nstderr: {}",
1055            args,
1056            String::from_utf8_lossy(&out.stdout),
1057            String::from_utf8_lossy(&out.stderr)
1058        );
1059        String::from_utf8_lossy(&out.stdout).trim().to_string()
1060    }
1061
1062    /// End-to-end guard for the operator-main-leak fix: when the operator's
1063    /// local `main` has commits that are not yet pushed, `setup_worktree`
1064    /// must branch from `origin/main` and produce a worktree whose HEAD is
1065    /// the pushed tip — never the local-only tip.
1066    #[tokio::test]
1067    #[serial_test::serial(orch_home)]
1068    async fn setup_worktree_anchors_on_origin_not_local_main() {
1069        // Isolate ORCH_HOME so the worktree lands in a temp dir.
1070        let orch_home_dir = tempfile::tempdir().unwrap();
1071        let prev_orch_home = env::var("ORCH_HOME").ok();
1072        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1073        unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1074
1075        // Bare "remote".
1076        let remote = tempfile::tempdir().unwrap();
1077        git(remote.path(), &["init", "--bare"]);
1078
1079        // Operator's project clone.
1080        let project = tempfile::tempdir().unwrap();
1081        git(
1082            project.path(),
1083            &["clone", remote.path().to_str().unwrap(), "."],
1084        );
1085        git(project.path(), &["config", "user.email", "t@t.com"]);
1086        git(project.path(), &["config", "user.name", "T"]);
1087
1088        // Pushed baseline on main.
1089        std_fs::write(project.path().join("README.md"), "pushed\n").unwrap();
1090        git(project.path(), &["add", "."]);
1091        git(project.path(), &["commit", "-m", "pushed baseline"]);
1092        git(project.path(), &["push", "origin", "HEAD:main"]);
1093        let pushed_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);
1094
1095        // Ensure origin/HEAD is set so detect_default_branch resolves "main".
1096        git(project.path(), &["remote", "set-head", "origin", "main"]);
1097
1098        // Operator's WIP: an unpushed local commit on top of main.
1099        std_fs::write(project.path().join("LOCAL_ONLY.md"), "unpushed\n").unwrap();
1100        git(project.path(), &["add", "."]);
1101        git(project.path(), &["commit", "-m", "local unpushed commit"]);
1102        let local_sha = git_stdout(project.path(), &["rev-parse", "HEAD"]);
1103        assert_ne!(
1104            pushed_sha, local_sha,
1105            "precondition: local main must be ahead of origin/main"
1106        );
1107
1108        // Run setup_worktree for a fresh internal task (skips GitHub linking).
1109        let setup = setup_worktree(
1110            "internal:1",
1111            "leak guard",
1112            project.path(),
1113            &None,
1114            "test/repo",
1115        )
1116        .await
1117        .expect("setup_worktree should succeed");
1118
1119        // Worktree must sit on the pushed tip, not the local-only tip.
1120        let wt_sha = git_stdout(&setup.work_dir, &["rev-parse", "HEAD"]);
1121        assert_eq!(
1122            wt_sha, pushed_sha,
1123            "worktree HEAD must equal origin/main, not local main"
1124        );
1125        assert_ne!(
1126            wt_sha, local_sha,
1127            "worktree must NOT include the operator's unpushed commit"
1128        );
1129        assert!(
1130            !setup.work_dir.join("LOCAL_ONLY.md").exists(),
1131            "unpushed-only file must not appear in the worktree"
1132        );
1133
1134        // Restore ORCH_HOME.
1135        match prev_orch_home {
1136            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1137            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1138            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1139            None => unsafe { env::remove_var("ORCH_HOME") },
1140        }
1141    }
1142
1143    /// auto_merge leaves a conflicted rebase for the agent, dispatch must not abort it.
1144    #[tokio::test]
1145    #[serial_test::serial(orch_home)]
1146    async fn setup_worktree_keeps_the_conflicted_rebase_for_a_conflict_task() {
1147        let orch_home_dir = tempfile::tempdir().unwrap();
1148        let prev_orch_home = env::var("ORCH_HOME").ok();
1149        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1150        unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1151
1152        let remote = tempfile::tempdir().unwrap();
1153        git(remote.path(), &["init", "--bare"]);
1154        let project = tempfile::tempdir().unwrap();
1155        git(
1156            project.path(),
1157            &["clone", remote.path().to_str().unwrap(), "."],
1158        );
1159        git(project.path(), &["config", "user.email", "t@t.com"]);
1160        git(project.path(), &["config", "user.name", "T"]);
1161        std_fs::write(project.path().join("f.txt"), "base\n").unwrap();
1162        git(project.path(), &["add", "."]);
1163        git(project.path(), &["commit", "-m", "base"]);
1164        git(project.path(), &["push", "origin", "HEAD:main"]);
1165        git(project.path(), &["remote", "set-head", "origin", "main"]);
1166
1167        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1168        let id = store
1169            .create_internal("test/repo", "conflict", "", "test", "1", None)
1170            .await
1171            .unwrap();
1172        let task_id = format!("internal:{id}");
1173        let opt = Some(Arc::clone(&store));
1174
1175        let setup = setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1176            .await
1177            .unwrap();
1178        let wt = setup.work_dir.clone();
1179        git(&wt, &["config", "user.email", "t@t.com"]);
1180        git(&wt, &["config", "user.name", "T"]);
1181        std_fs::write(wt.join("f.txt"), "agent\n").unwrap();
1182        git(&wt, &["commit", "-am", "agent change"]);
1183        git(&wt, &["push", "origin", "HEAD"]);
1184
1185        // main moves on with a conflicting change, then the rebase stops on it
1186        std_fs::write(project.path().join("f.txt"), "main\n").unwrap();
1187        git(project.path(), &["commit", "-am", "main change"]);
1188        git(project.path(), &["push", "origin", "HEAD:main"]);
1189        git(&wt, &["fetch", "origin"]);
1190        let rebase = process::Command::new("git")
1191            .args(["rebase", "origin/main"])
1192            .current_dir(&wt)
1193            .output()
1194            .unwrap();
1195        assert!(!rebase.status.success(), "precondition: rebase conflicts");
1196        assert!(git_ops::rebase_in_progress(&wt).await);
1197
1198        store.increment(id, "merge_conflict_retries").await.unwrap();
1199
1200        setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1201            .await
1202            .unwrap();
1203        git_ops::rebase_on_default(&wt, "main").await;
1204        assert!(
1205            git_ops::rebase_in_progress(&wt).await,
1206            "the rebase auto_merge left must survive dispatch"
1207        );
1208
1209        match prev_orch_home {
1210            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1211            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1212            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1213            None => unsafe { env::remove_var("ORCH_HOME") },
1214        }
1215    }
1216
1217    #[tokio::test]
1218    #[serial_test::serial(orch_home)]
1219    async fn setup_worktree_keeps_the_conflicted_rebase_when_the_task_has_a_pr() {
1220        let orch_home_dir = tempfile::tempdir().unwrap();
1221        let prev_orch_home = env::var("ORCH_HOME").ok();
1222        // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1223        unsafe { env::set_var("ORCH_HOME", orch_home_dir.path()) };
1224
1225        let remote = tempfile::tempdir().unwrap();
1226        git(remote.path(), &["init", "--bare"]);
1227        let project = tempfile::tempdir().unwrap();
1228        git(
1229            project.path(),
1230            &["clone", remote.path().to_str().unwrap(), "."],
1231        );
1232        git(project.path(), &["config", "user.email", "t@t.com"]);
1233        git(project.path(), &["config", "user.name", "T"]);
1234        std_fs::write(project.path().join("f.txt"), "base\n").unwrap();
1235        git(project.path(), &["add", "."]);
1236        git(project.path(), &["commit", "-m", "base"]);
1237        git(project.path(), &["push", "origin", "HEAD:main"]);
1238        git(project.path(), &["remote", "set-head", "origin", "main"]);
1239
1240        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1241        let id = store
1242            .create_internal("test/repo", "conflict", "", "test", "1", None)
1243            .await
1244            .unwrap();
1245        let task_id = format!("internal:{id}");
1246        let opt = Some(Arc::clone(&store));
1247
1248        let setup = setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1249            .await
1250            .unwrap();
1251        let wt = setup.work_dir.clone();
1252        git(&wt, &["config", "user.email", "t@t.com"]);
1253        git(&wt, &["config", "user.name", "T"]);
1254        std_fs::write(wt.join("f.txt"), "agent\n").unwrap();
1255        git(&wt, &["commit", "-am", "agent change"]);
1256        git(&wt, &["push", "origin", "HEAD"]);
1257
1258        std_fs::write(project.path().join("f.txt"), "main\n").unwrap();
1259        git(project.path(), &["commit", "-am", "main change"]);
1260        git(project.path(), &["push", "origin", "HEAD:main"]);
1261        git(&wt, &["fetch", "origin"]);
1262        let rebase = process::Command::new("git")
1263            .args(["rebase", "origin/main"])
1264            .current_dir(&wt)
1265            .output()
1266            .unwrap();
1267        assert!(!rebase.status.success(), "precondition: rebase conflicts");
1268        assert!(git_ops::rebase_in_progress(&wt).await);
1269
1270        store
1271            .set_fields(id, &[("pr_number", serde_json::json!(7))])
1272            .await
1273            .unwrap();
1274
1275        setup_worktree(&task_id, "conflict", project.path(), &opt, "test/repo")
1276            .await
1277            .unwrap();
1278        git_ops::rebase_on_default(&wt, "main").await;
1279        assert!(
1280            git_ops::rebase_in_progress(&wt).await,
1281            "the rebase auto_merge left must survive dispatch when the task has a PR"
1282        );
1283
1284        match prev_orch_home {
1285            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1286            Some(v) => unsafe { env::set_var("ORCH_HOME", v) },
1287            // SAFETY: nextest runs each test in its own process, so no other test touches the environment
1288            None => unsafe { env::remove_var("ORCH_HOME") },
1289        }
1290    }
1291
1292    /// When neither `origin/<branch>` nor `origin/<default_branch>` exist,
1293    /// fall back to the local default branch name as a last resort.
1294    #[tokio::test]
1295    async fn resolve_branch_start_point_falls_back_to_local_default() {
1296        let local = tempfile::tempdir().unwrap();
1297        git(local.path(), &["init"]);
1298        git(local.path(), &["config", "user.email", "t@t.com"]);
1299        git(local.path(), &["config", "user.name", "T"]);
1300        git(local.path(), &["checkout", "-b", "main"]);
1301        std_fs::write(local.path().join("README.md"), "main").unwrap();
1302        git(local.path(), &["add", "."]);
1303        git(local.path(), &["commit", "-m", "init"]);
1304
1305        let repo_root = local.path().to_str().unwrap();
1306
1307        // No remote at all → fall back to "main".
1308        let start = resolve_branch_start_point(repo_root, "no-such-branch", "main").await;
1309        assert_eq!(
1310            start, "main",
1311            "should fall back to local default_branch when no remote refs exist"
1312        );
1313    }
1314
1315    #[test]
1316    fn branch_name_basic() {
1317        let name = branch_name("42", "Fix login bug");
1318        assert_eq!(name, "gh-issue-42-fix-login-bug");
1319    }
1320
1321    #[test]
1322    fn branch_name_internal_task() {
1323        let name = branch_name("internal:8", "Fix login bug");
1324        assert_eq!(name, "internal-8-fix-login-bug");
1325    }
1326
1327    #[test]
1328    fn branch_name_special_chars() {
1329        let name = branch_name("7", "Add OAuth2/OIDC (Google & GitHub)");
1330        assert_eq!(name, "gh-issue-7-add-oauth2-oidc-google-github");
1331    }
1332
1333    #[test]
1334    fn branch_name_truncates_long_slug() {
1335        let title =
1336            "This is a very long task title that should be truncated to forty characters maximum";
1337        let name = branch_name("1", title);
1338        // slug part should be max 40 chars
1339        let slug = name.strip_prefix("gh-issue-1-").unwrap();
1340        assert!(slug.len() <= 40, "slug length {} > 40", slug.len());
1341    }
1342
1343    #[test]
1344    fn branch_name_trims_trailing_dashes() {
1345        let name = branch_name("5", "Fix bug---");
1346        assert!(
1347            !name.ends_with('-'),
1348            "branch name should not end with dash: {name}"
1349        );
1350    }
1351
1352    #[test]
1353    fn branch_name_empty_title() {
1354        let name = branch_name("99", "");
1355        assert_eq!(name, "gh-issue-99");
1356    }
1357
1358    #[test]
1359    fn branch_name_empty_title_internal() {
1360        let name = branch_name("internal:99", "");
1361        assert_eq!(name, "internal-99");
1362    }
1363
1364    #[test]
1365    fn branch_name_all_special_chars() {
1366        let name = branch_name("10", "--- ??? ---");
1367        assert_eq!(name, "gh-issue-10");
1368        assert_ne!(name, "");
1369    }
1370
1371    #[test]
1372    fn branch_name_chinese_chars_no_panic() {
1373        let name = branch_name("265", "implement 用户认证 user auth");
1374        assert!(name.starts_with("gh-issue-265-"));
1375        assert_ne!(name, "");
1376        let slug = name.strip_prefix("gh-issue-265-").unwrap();
1377        assert!(slug.len() <= 40, "slug too long: {}", slug.len());
1378        assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
1379    }
1380
1381    #[test]
1382    fn task_id_from_worktree_name_parses_issue_branches() {
1383        assert_eq!(
1384            task_id_from_worktree_name("gh-issue-42-fix-login"),
1385            Some("42".to_string())
1386        );
1387        assert_eq!(
1388            task_id_from_worktree_name("gh-task-42-fix-login"),
1389            Some("42".to_string())
1390        );
1391    }
1392
1393    #[test]
1394    fn task_id_from_worktree_name_parses_internal_branches() {
1395        assert_eq!(
1396            task_id_from_worktree_name("internal-8-fix-login"),
1397            Some("internal:8".to_string())
1398        );
1399        assert_eq!(
1400            task_id_from_worktree_name("gh-issue-internal-8-fix-login"),
1401            Some("internal:8".to_string())
1402        );
1403    }
1404
1405    #[test]
1406    fn task_id_from_worktree_name_returns_none_for_unknown_names() {
1407        assert!(task_id_from_worktree_name("random-worktree").is_none());
1408    }
1409
1410    #[test]
1411    fn branch_name_emoji_no_panic() {
1412        let name = branch_name("265", "fix 🚀 deployment pipeline 🔥");
1413        assert!(name.starts_with("gh-issue-265-"));
1414        let slug = name.strip_prefix("gh-issue-265-").unwrap();
1415        assert!(slug.is_ascii(), "slug contains non-ASCII: {slug}");
1416    }
1417
1418    #[test]
1419    fn branch_name_all_non_ascii_falls_back_to_task_id() {
1420        let name = branch_name("265", "用户认证 실행 тест");
1421        assert_eq!(name, "gh-issue-265");
1422    }
1423
1424    #[tokio::test]
1425    async fn find_existing_worktree_returns_none_for_missing() {
1426        let dir = tempfile::tempdir().unwrap();
1427        assert!(find_existing_worktree(dir.path(), "42").await.is_none());
1428    }
1429
1430    #[tokio::test]
1431    async fn find_existing_worktree_matches_prefix() {
1432        let dir = tempfile::tempdir().unwrap();
1433        let wt_dir = dir.path().join("gh-issue-42-fix-login-bug");
1434        fs::create_dir(&wt_dir).await.unwrap();
1435
1436        let result = find_existing_worktree(dir.path(), "42").await;
1437        assert_eq!(result, Some(wt_dir));
1438    }
1439
1440    #[tokio::test]
1441    async fn find_existing_worktree_matches_internal_prefix() {
1442        let dir = tempfile::tempdir().unwrap();
1443        let wt_dir = dir.path().join("internal-8-fix");
1444        fs::create_dir(&wt_dir).await.unwrap();
1445
1446        let result = find_existing_worktree(dir.path(), "internal:8").await;
1447        assert_eq!(result, Some(wt_dir));
1448    }
1449
1450    #[tokio::test]
1451    async fn find_existing_worktree_matches_legacy_gh_task_prefix() {
1452        // Old worktrees created before the rename should still be found
1453        let dir = tempfile::tempdir().unwrap();
1454        let wt_dir = dir.path().join("gh-task-internal-8-fix");
1455        fs::create_dir(&wt_dir).await.unwrap();
1456
1457        let result = find_existing_worktree(dir.path(), "internal:8").await;
1458        assert_eq!(result, Some(wt_dir));
1459    }
1460
1461    #[tokio::test]
1462    async fn find_existing_worktree_matches_legacy_external_prefix() {
1463        // Old external worktrees with gh-task- prefix should still be found
1464        let dir = tempfile::tempdir().unwrap();
1465        let wt_dir = dir.path().join("gh-task-42-fix-login-bug");
1466        fs::create_dir(&wt_dir).await.unwrap();
1467
1468        let result = find_existing_worktree(dir.path(), "42").await;
1469        assert_eq!(result, Some(wt_dir));
1470    }
1471
1472    #[tokio::test]
1473    async fn find_existing_worktree_ignores_other_tasks() {
1474        let dir = tempfile::tempdir().unwrap();
1475        fs::create_dir(dir.path().join("gh-issue-43-other-task"))
1476            .await
1477            .unwrap();
1478
1479        assert!(find_existing_worktree(dir.path(), "42").await.is_none());
1480    }
1481
1482    // --- resolve_parent_branch tests ---
1483
1484    /// No store → always returns None.
1485    #[tokio::test]
1486    async fn resolve_parent_branch_no_store_returns_none() {
1487        let dir = tempfile::tempdir().unwrap();
1488        let result = resolve_parent_branch(&None, Some(1), dir.path()).await;
1489        assert!(result.is_none());
1490    }
1491
1492    /// parent_id = None → always returns None regardless of store.
1493    #[tokio::test]
1494    async fn resolve_parent_branch_no_parent_id_returns_none() {
1495        let dir = tempfile::tempdir().unwrap();
1496        let result = resolve_parent_branch(&None, None, dir.path()).await;
1497        assert!(result.is_none());
1498    }
1499
1500    /// Parent exists but has empty branch → returns None so child gets its own branch.
1501    #[tokio::test]
1502    async fn resolve_parent_branch_empty_parent_branch_returns_none() {
1503        let db_dir = tempfile::tempdir().unwrap();
1504        let db_path = db_dir.path().join("test.db");
1505        let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1506
1507        // Create parent task — branch defaults to empty string
1508        let parent_id = store
1509            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1510            .await
1511            .unwrap();
1512
1513        let dir = tempfile::tempdir().unwrap();
1514        let store_opt = Some(store);
1515        let result = resolve_parent_branch(&store_opt, Some(parent_id), dir.path()).await;
1516        assert!(result.is_none());
1517    }
1518
1519    /// Parent has a branch set → child inherits that branch and worktree path.
1520    #[tokio::test]
1521    async fn resolve_parent_branch_returns_parent_branch_and_worktree() {
1522        let db_dir = tempfile::tempdir().unwrap();
1523        let db_path = db_dir.path().join("test.db");
1524        let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1525
1526        // Create parent task and set its branch
1527        let parent_id = store
1528            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1529            .await
1530            .unwrap();
1531        store
1532            .set_fields(
1533                parent_id,
1534                &[("branch", serde_json::json!("gh-issue-99-parent-task"))],
1535            )
1536            .await
1537            .unwrap();
1538
1539        let worktrees_base = tempfile::tempdir().unwrap();
1540        let store_opt = Some(store);
1541        let result =
1542            resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;
1543
1544        let (branch, wt) = result.expect("should return parent branch");
1545        assert_eq!(branch, "gh-issue-99-parent-task");
1546        assert_eq!(wt, worktrees_base.path().join("gh-issue-99-parent-task"));
1547    }
1548
1549    /// When parent has both branch and a worktree path that exists, use the worktree path.
1550    #[tokio::test]
1551    async fn resolve_parent_branch_prefers_existing_worktree_path() {
1552        let db_dir = tempfile::tempdir().unwrap();
1553        let db_path = db_dir.path().join("test.db");
1554        let store = Arc::new(TaskStore::open_single(&db_path).await.unwrap());
1555
1556        let worktrees_base = tempfile::tempdir().unwrap();
1557        // Create the parent worktree directory
1558        let parent_wt_dir = worktrees_base.path().join("custom-worktree-path");
1559        fs::create_dir_all(&parent_wt_dir).await.unwrap();
1560
1561        let parent_id = store
1562            .create_internal("owner/repo", "parent task", "", "issue", "99", None)
1563            .await
1564            .unwrap();
1565        store
1566            .set_fields(
1567                parent_id,
1568                &[
1569                    ("branch", serde_json::json!("gh-issue-99-parent-task")),
1570                    (
1571                        "worktree",
1572                        serde_json::json!(parent_wt_dir.to_string_lossy().as_ref()),
1573                    ),
1574                ],
1575            )
1576            .await
1577            .unwrap();
1578
1579        let store_opt = Some(store);
1580        let result =
1581            resolve_parent_branch(&store_opt, Some(parent_id), worktrees_base.path()).await;
1582
1583        let (branch, wt) = result.expect("should return parent branch");
1584        assert_eq!(branch, "gh-issue-99-parent-task");
1585        assert_eq!(wt, parent_wt_dir);
1586    }
1587
1588    /// Regression test: concurrent calls to list_project_worktrees and
1589    /// validate_worktree_gitdir should not starve the Tokio worker thread
1590    /// pool. This was broken by blocking Path::exists/is_dir calls in async
1591    /// functions (issue #2467).
1592    #[tokio::test]
1593    async fn concurrent_worktree_checks_no_starvation() {
1594        let temp_dir = tempfile::tempdir().unwrap();
1595        let worktrees_base = temp_dir.path().join("worktrees");
1596        fs::create_dir_all(&worktrees_base).await.unwrap();
1597
1598        // Create a fake worktree with valid gitdir
1599        let wt_dir = worktrees_base.join("gh-issue-123-test");
1600        fs::create_dir_all(&wt_dir).await.unwrap();
1601        // Create .git as a file pointing to a real directory (worktree link)
1602        let gitdir_target = temp_dir
1603            .path()
1604            .join(".git")
1605            .join("worktrees")
1606            .join("gh-issue-123-test");
1607        fs::create_dir_all(&gitdir_target).await.unwrap();
1608        let git_file = wt_dir.join(".git");
1609        fs::write(&git_file, format!("gitdir: {}\n", gitdir_target.display()))
1610            .await
1611            .unwrap();
1612
1613        // Spawn many concurrent tasks - if any use blocking calls, they'll
1614        // block the worker thread and cause timeout or deadlock.
1615        let handles: Vec<_> = (0..20)
1616            .map(|i| {
1617                let wb = worktrees_base.clone();
1618                let wd = wt_dir.clone();
1619                tokio::spawn(async move {
1620                    if i % 2 == 0 {
1621                        list_project_worktrees(&wb).await.ok();
1622                    } else {
1623                        validate_worktree_gitdir(&wd).await;
1624                    }
1625                })
1626            })
1627            .collect();
1628
1629        // Wait with timeout to detect starvation
1630        let results = time::timeout(Duration::from_secs(10), async {
1631            future::join_all(handles).await
1632        })
1633        .await;
1634
1635        assert!(
1636            results.is_ok(),
1637            "concurrent worktree checks timed out (starvation?)"
1638        );
1639    }
1640
1641    // --- normalize_branch_name tests ---
1642
1643    #[test]
1644    fn normalize_branch_name_strips_origin_prefix() {
1645        assert_eq!(
1646            normalize_branch_name("origin/main"),
1647            Some("main".to_string())
1648        );
1649        assert_eq!(
1650            normalize_branch_name("origin/develop"),
1651            Some("develop".to_string())
1652        );
1653    }
1654
1655    #[test]
1656    fn normalize_branch_name_strips_full_ref_path() {
1657        assert_eq!(
1658            normalize_branch_name("refs/remotes/origin/main"),
1659            Some("main".to_string())
1660        );
1661        assert_eq!(
1662            normalize_branch_name("refs/remotes/origin/develop"),
1663            Some("develop".to_string())
1664        );
1665    }
1666
1667    #[test]
1668    fn normalize_branch_name_strips_remotes_prefix() {
1669        assert_eq!(
1670            normalize_branch_name("remotes/origin/main"),
1671            Some("main".to_string())
1672        );
1673    }
1674
1675    #[test]
1676    fn normalize_branch_name_passes_through_plain_branch() {
1677        assert_eq!(normalize_branch_name("main"), Some("main".to_string()));
1678        assert_eq!(normalize_branch_name("master"), Some("master".to_string()));
1679        assert_eq!(
1680            normalize_branch_name("feature/foo"),
1681            Some("feature/foo".to_string())
1682        );
1683    }
1684
1685    #[test]
1686    fn normalize_branch_name_rejects_empty_and_refs_only() {
1687        assert_eq!(normalize_branch_name(""), None);
1688        assert_eq!(normalize_branch_name("   "), None);
1689        assert_eq!(
1690            normalize_branch_name("refs/heads/main"),
1691            Some("main".to_string())
1692        );
1693    }
1694}