{"record":{"id":"8e51fecc84f70b74","repo":"affaan-m/ECC","slug":"git-worktree-add-failed-stderr","errorCode":null,"errorMessage":"git worktree add failed: {stderr}","messagePattern":"git worktree add failed: (.+?)","errorType":"exception","errorClass":"anyhow::Error","httpStatus":null,"severity":"error","filePath":"ecc2/src/worktree/mod.rs","lineNumber":126,"sourceCode":"\n    // Get current branch as base\n    let base = get_current_branch(repo_root)?;\n\n    std::fs::create_dir_all(&cfg.worktree_root)\n        .context(\"Failed to create worktree root directory\")?;\n\n    let output = Command::new(\"git\")\n        .arg(\"-C\")\n        .arg(repo_root)\n        .args([\"worktree\", \"add\", \"-b\", &branch])\n        .arg(&path)\n        .arg(\"HEAD\")\n        .output()\n        .context(\"Failed to run git worktree add\")?;\n\n    if !output.status.success() {\n        let stderr = String::from_utf8_lossy(&output.stderr);\n        anyhow::bail!(\"git worktree add failed: {stderr}\");\n    }\n\n    tracing::info!(\n        \"Created worktree at {} on branch {}\",\n        path.display(),\n        branch\n    );\n\n    let info = WorktreeInfo {\n        path,\n        branch,\n        base_branch: base,\n    };\n\n    if let Err(error) = sync_shared_dependency_dirs_in_repo(&info, repo_root) {\n        tracing::warn!(\n            \"Shared dependency cache sync warning for {}: {error}\",\n            info.path.display()","sourceCodeStart":108,"sourceCodeEnd":144,"githubUrl":"https://github.com/affaan-m/ECC/blob/01e15490f04e29cfefe3896951f43db46994d8ee/ecc2/src/worktree/mod.rs#L108-L144","documentation":"The worktree creator runs `git -C <repo> worktree add -b <branch> <path> HEAD` and it exited non-zero. The full git stderr is interpolated into the message, so the precise git-level cause is in {stderr}.","triggerScenarios":"git worktree add fails: the branch already exists; the path is inside an existing worktree or is non-empty; HEAD is unborn (no commits) or detached in a bare repo; permission/disk errors; invalid characters in branch or path.","commonSituations":"Reusing a session_id whose branch already exists from a prior run; a previous crash left a worktree at that path; invalid branch-name characters; running against a fresh/bare clone with no HEAD commit.","solutions":["Read the embedded {stderr} first — it names the exact git-level cause.","If the branch already exists, reuse it or delete it (git branch -D) before retrying.","Prune stale worktrees with `git worktree prune` and remove the target path if it is a leftover directory.","Validate the branch name and path with git check-ref-format / path sanity before invoking git."],"exampleFix":"// before\nlet info = create_worktree(repo_root, &path, &branch, base)?;\n\n// after\n// pre-flight: ensure no stale worktree/branch blocks creation\nlet _ = Command::new(\"git\").arg(\"-C\").arg(repo_root)\n    .args([\"worktree\", \"prune\"]).status();\nlet branch_taken = Command::new(\"git\").arg(\"-C\").arg(repo_root)\n    .args([\"rev-parse\", \"--verify\", \"--quiet\", &format!(\"refs/heads/{branch}\")])\n    .status()?.success();\nif branch_taken {\n    anyhow::bail!(\"branch {branch} already exists; reuse or delete it first\");\n}\nlet info = create_worktree(repo_root, &path, &branch, base)?;","handlingStrategy":"try-catch","validationCode":"// Pre-flight checks that mirror git's own constraints.\nuse std::process::Command;\n\nfn branch_exists(repo_root: &Path, branch: &str) -> bool {\n    Command::new(\"git\").arg(\"-C\").arg(repo_root)\n        .args([\"rev-parse\", \"--verify\", \"--quiet\", &format!(\"refs/heads/{branch}\")])\n        .status().map(|s| s.success()).unwrap_or(false)\n}\n\nif branch_exists(repo_root, &branch) {\n    return Err(anyhow::anyhow!(\"branch {branch} already exists; reuse or delete it first\"));\n}\nif path.exists() {\n    return Err(anyhow::anyhow!(\"worktree path {} already exists\", path.display()));\n}","typeGuard":"fn worktree_creation_preconditions_ok(repo_root: &Path, path: &Path, branch: &str) -> bool {\n    !branch_exists(repo_root, branch) && !path.exists()\n}","tryCatchPattern":"match create_worktree(repo_root, &path, &branch, base) {\n    Ok(info) => { /* created */ }\n    Err(e) => {\n        let msg = e.to_string();\n        if msg.contains(\"git worktree add failed\") {\n            // msg already embeds git's stderr; branch on it:\n            // - \"already exists\" -> prune / delete branch / pick a new path and retry\n            // - \"not a valid object name HEAD\" -> ensure HEAD has a commit (non-bare repo)\n            // - permission/disk -> fix environment\n        }\n        return Err(e);\n    }\n}","preventionTips":["Run `git worktree prune` and clean leftover session paths before creating new worktrees.","Validate branch names with `git check-ref-format --branch` before invoking git worktree add.","Derive branch/path from a unique session id so collisions cannot happen across runs."],"tags":["rust","git","worktree","subprocess"],"backgroundTag":null,"analyzedSha":"01e15490f04e29cfefe3896951f43db46994d8ee","analyzedAt":"2026-08-13T00:31:08.655Z","schemaVersion":2},"datasetVersion":"2026-08-13T04:17:16.726Z"}