Sub topic 12
Removing worktrees and branches safely
This chapter covers the last stage of the parallel-agent workflow: removing finished worktrees and their branches without losing work. It assumes you can create worktrees with git worktree add, that you have merged agent branches into main, and that you are comfortable with git status and git branch. The earlier chapters set up one worktree and one agent/ branch per task. Here they come down again.
What a worktree consists of
Cleanup is safer once you know what you are deleting. A linked worktree has three parts:
- The working directory, for example
../myrepo-auth, holding checked-out files plus anything untracked or ignored. - The administrative record, a folder under
.git/worktrees/in the main repository. It tracks the worktree's path, its HEAD and its lock state. - The branch, for example
agent/auth, a ref stored in the shared repository.
Each part can be deleted separately, and each can be left behind separately. Deleting the directory with rm -rf leaves the record and the branch. Removing the worktree with Git leaves the branch. Deleting the branch needs the worktree to be gone first. The commands below handle these parts in order.
The normal sequence
After you merge an agent branch, run these from the main worktree:
git worktree remove ../myrepo-auth
git branch -d agent/auth
git worktree prunegit worktree remove deletes the directory and its administrative record in one step. git branch -d deletes the branch only if its commits are already reachable from your current branch (or from its upstream, if it has one). git worktree prune clears any leftover records. It is usually a no-op after remove, but it is cheap and catches earlier mistakes.
The order matters. Git refuses to delete a branch that is checked out in any worktree, so git branch -d agent/auth fails while ../myrepo-auth still exists.
What the safety checks do
Each command has a guard, and each guard has a force option. Use the force option only after you know what it will destroy.
| Command | Refuses when | Override | What the override costs |
|---|---|---|---|
| `git worktree remove <path>` | The worktree has modified tracked files or untracked files | `--force` | Uncommitted edits and untracked files are deleted |
| `git worktree remove <path>` | The worktree is locked | `--force --force` | Same as above, plus the lock is ignored |
| `git branch -d <branch>` | The branch has commits not merged into HEAD or its upstream | `git branch -D <branch>` | Unmerged commits lose their branch name |
| `git worktree prune` | The worktree is locked | Unlock it first | None |
Two details trip people up.
First, the cleanliness check counts untracked files but not ignored ones. If an agent created a new file and never ran git add, remove stops and tells you. A .env that you copied in and that .gitignore covers is deleted silently, as is node_modules/. This is usually what you want, but check for ignored output you meant to keep, such as logs or test reports. Copy these out before you remove the worktree.
Second, git branch -d checks against the branch you are on, not against main by name. Run it from main, or -d may refuse a branch that is in fact merged, or accept one that is merged only into some other branch.
Checking before you delete
Look at what you are about to remove before running anything destructive.
git worktree list
git -C ../myrepo-auth status --short
git branch --merged main
git branch --no-merged maingit -C <path> runs a command inside a worktree without changing your shell's directory. An empty status --short means nothing uncommitted. --merged lists branches whose tips are already in main, which are safe for -d. --no-merged lists branches that hold work main does not have yet. An agent branch in that list needs a decision: merge it, keep it, or discard it on purpose.
For a stricter yes/no test that works in scripts, use git merge-base --is-ancestor. It exits with status 0 when the first commit is contained in the second:
git merge-base --is-ancestor agent/auth main && echo "merged" || echo "not merged"Deciding what to do with each worktree
Worktrees you deleted by hand
Sometimes a worktree directory disappears without Git's involvement: someone ran rm -rf, a cleanup tool swept the parent folder, or a temporary disk was wiped. Git still has the administrative record, and the branch is still "checked out" as far as it knows. Two symptoms follow:
git worktree listshows the entry, markedprunablein recent Git versions.git branch -d agent/authfails because the branch is considered checked out.
Fix both with prune. Preview first:
git worktree prune --dry-run -v
git worktree prune -v
git branch -d agent/authGit also prunes stale records on its own during garbage collection, but only after an expiry period (three months by default), so do not wait for it.
Locking worktrees that should survive
Prune treats a missing directory as abandoned. That is wrong when the worktree lives on a removable drive or a network mount that is simply not attached right now. git worktree lock marks a worktree so that neither prune nor a plain remove will touch it:
git worktree lock --reason "on external drive" ../myrepo-search
git worktree list --porcelain
git worktree unlock ../myrepo-searchThe --porcelain output is stable and meant for scripts. It lists locked along with the reason, and prunable for entries whose directory is gone. Locks also work as a guard for a long-running agent: lock its worktree at start, and a cleanup script cannot remove it mid-task. Unlock it when the agent finishes.
If the directory has only moved, do not delete and recreate it. git worktree move ../myrepo-auth ../elsewhere/auth relocates it and updates the record. git worktree repair fixes the links if you moved a directory by hand.
Shared state that outlives a worktree
Removing a worktree does not remove everything the agent touched, because some state belongs to the repository, not the worktree:
- Stashes.
git stashentries live in the shared repository. A stash an agent made in../myrepo-authis still ingit stash listafter the worktree is gone. - Local config. Settings the agent wrote with
git config(without--worktree) apply to the whole repository. - Hooks and remotes. An agent that changed
.git/hooksor added a remote changed it for every worktree. - Remote branches. If the agent pushed
agent/auth, the remote copy remains after you delete the local one. Delete it withgit push origin --delete agent/authonce you are sure.
After cleanup, check git stash list and git remote -v for anything you did not expect.
Recovering a branch you deleted too soon
git branch -D prints the commit the branch pointed to:
Deleted branch agent/auth (was 3f9c2ab).Until Git's garbage collection removes unreachable commits, that hash is enough to bring the branch back:
git branch agent/auth 3f9c2abIf you lost the output, git reflog shows where HEAD has been, which often includes the agent's last commit if you ever checked the branch out in the main worktree. A commit made only inside a removed linked worktree is harder to find, so do not count on recovery. Check before deleting.
A cleanup script
This script automates the checks above. It removes a worktree and branch only when the directory exists, has no changes and the branch is already in main. Anything else is reported and left alone. Run it from the main worktree, not from a linked one.
#!/usr/bin/env bash
set -euo pipefail
repo=$(git rev-parse --show-toplevel)
name=$(basename "$repo")
base=main
if [ "$(git branch --show-current)" != "$base" ]; then
echo "Switch to $base in the main worktree first." >&2
exit 1
fi
for task in auth billing search; do
path="../$name-$task"
branch="agent/$task"
if [ ! -d "$path" ]; then
echo "skip $task: no worktree at $path"
continue
fi
if [ -n "$(git -C "$path" status --porcelain)" ]; then
echo "keep $task: uncommitted changes in $path"
continue
fi
if ! git merge-base --is-ancestor "$branch" "$base"; then
echo "keep $task: $branch is not merged into $base"
continue
fi
git worktree remove "$path"
git branch -d "$branch"
echo "removed $task"
done
git worktree prune
git worktree listThe script never uses --force or -D. A worktree it skips needs a human decision, which is the point.
Exercise
You merged agent/billing into main with a squash merge. git worktree remove ../myrepo-billing succeeded, but git branch -d agent/billing now says the branch is not fully merged. Why does this happen, how do you confirm the work is safe, and which command finishes the cleanup?
Show answer
A squash merge records the agent's changes as one new commit on main, so the agent's original commits are not ancestors of main, and -d cannot see them as merged. To confirm the work is safe, run git diff main...agent/billing and check that every change it shows is already in main (or compare the squash commit's content with the branch). Once you are sure, delete the branch with git branch -D agent/billing, and note the hash it prints in case you need to restore it.
Exercise
A teammate's cleanup tool deleted ../myrepo-search with rm -rf. Now git branch -d agent/search fails because the branch is checked out. What do you run, in what order, and what would you do first if you were unsure?
Show answer
Run git worktree prune --dry-run -v first to preview which records Git considers stale. Then run git worktree prune, which removes the record for the missing directory, and finally git branch -d agent/search (or -D if the branch was not merged and you have reviewed it). If the directory was only on a detached drive, do not prune. Reattach the drive, or lock the worktree in future with git worktree lock.