Hmbown/CodeWhale · error

git worktree add failed for branch

Error message

git worktree add failed for branch {} at {}{}{}

What it means

Raised by `provision_worktree` (crates/lane/src/worktree.rs) when the `git worktree add` subprocess exits non-zero. The library captures git's stderr and appends it to the message: "git worktree add failed for branch {branch} at {path}: {detail}".

Solutions

  1. Read the appended git stderr in the message — it names the exact git cause (e.g. 'already exists').
  2. Delete or pick a new branch name if it already exists (`git branch -D <branch>`), or clean the stale worktree path (`git worktree prune`).
  3. Verify base_ref exists (`git rev-parse --verify <base>`); use HEAD or a valid ref.
  4. Ensure the target path does not already contain files before provisioning.

Example fix

// before: reusing a branch from a previous run
provision_worktree(&spec)?; // branch 'lane/a' still exists
// after
cleanup_worktree(&spec)?; // or: git branch -D lane/a
provision_worktree(&spec)?;
Defensive patterns

Strategy: try-catch

Validate before calling

// check branch/path/base before calling
let branch_taken = Command::new("git").args(["rev-parse", "--verify", &spec.branch]).output()?.status.success();
anyhow::ensure!(!branch_taken, "branch {} already exists", spec.branch);
anyhow::ensure!(!spec.path.exists(), "worktree path {} exists", spec.path.display());

Try / catch

match provision_worktree(&spec) {
    Err(e) if e.to_string().contains("git worktree add failed") => {
        // run `git worktree prune`, delete stale branch, retry once
    }
    other => other?,
}

Prevention

When it happens

Trigger: `git worktree add -b <branch> <path> <base>` fails because the branch already exists, the target path already exists and is non-empty, the base ref is unknown, or the repo is bare/corrupt.

Common situations: Re-running provisioning after a partial previous run left the branch behind; reusing a lane name whose old branch was not yet cleaned; pointing base_ref at a ref that was rebased away; path collision with an existing checkout.

Understand the failure class

Background: "git command failed": what it means when a tool shells out to git and git exits non-zero — this error's family across 21 libraries.

Related errors


AI-assisted analysis of Hmbown/CodeWhale@73e0f67d83 (2026-09-22). Data as JSON: /api/errors/4933b34de0e873d7. Report an issue: GitHub.

Appendix: source

Thrown at crates/lane/src/worktree.rs:60

    let base = spec.base_ref.as_deref().unwrap_or("HEAD");
    // Capture git output instead of inheriting the caller's terminal. Runtime
    // callers include the raw-mode TUI launch screen, where even one inherited
    // progress/error line corrupts the alternate-screen buffer.
    let output = Command::new("git")
        .current_dir(&spec.repo_root)
        .args([
            "worktree",
            "add",
            "-b",
            &spec.branch,
            &spec.path.to_string_lossy(),
            base,
        ])
        .output()
        .context("git worktree add")?;
    if !output.status.success() {
        let detail = String::from_utf8_lossy(&output.stderr).trim().to_string();
        bail!(
            "git worktree add failed for branch {} at {}{}{}",
            spec.branch,
            spec.path.display(),
            if detail.is_empty() { "" } else { ": " },
            detail
        );
    }
    Ok(ProvisionedWorktree {
        path: spec.path.clone(),
        branch: spec.branch.clone(),
    })
}

/// Remove a worktree when TTL has expired (or immediately when TTL is 0).
///
/// `stopped_at` is RFC3339. When `ttl_secs` is `None`, no cleanup is performed.
///
/// Removal only ever touches a path that git identifies as a managed worktree

View on GitHub (pinned to 73e0f67d83)