Skip to content
How to clean up git worktrees from parallel AI agents without losing their work

How to clean up git worktrees from parallel AI agents without losing their work

To clean up git worktrees from parallel AI agents, run git status and git log in each, remove the clean, merged ones with git worktree remove, then delete their branches.

Aaron Delasy
Aaron DelasyFounder

To clean up git worktrees from parallel AI agents, check each one for uncommitted work and unmerged commits with git status and git log, and remove only the clean, merged ones. Google's AI Mode gave me a one-liner for the job with "Careful!" written above it, and the warning is earned. On a test repository with 7 agent worktrees it deleted one agent's uncommitted edit and untracked notes without asking, failed on a folder name with a space in it and left every branch behind.

I ran every command here against that repository on git 2.47.3 on November 24, 2026. It has a bare origin, a main checkout and 7 worktrees in the states agents leave behind: two merged (one of them squash-merged), one with uncommitted work, one locked, one with a space in its folder name, one whose folder I deleted by hand, and one fresh. For the other end of a worktree's life, running several Claude Code agents covers the setup.

Check every worktree before you remove anything

git worktree list shows every worktree with its branch and any locked or prunable flag, and git status --porcelain inside each one shows the work removal would destroy.

bash
git worktree list
text
/src/app            ca7ffd0 [main]
/src/wt/agent two   cc436d5 [agent-two]
/src/wt/agent-a     14740d2 [agent-a]
/src/wt/agent-b     1975743 [agent-b]
/src/wt/agent-c     ca7ffd0 [agent-c]
/src/wt/agent-d     ca7ffd0 [agent-d] locked
/src/wt/agent-e     ca7ffd0 [agent-e] prunable
/src/wt/agent-f     ca7ffd0 [agent-f]

locked means something asked git to keep that worktree, and Claude Code holds that lock while an agent runs, so on a machine full of agents a locked worktree is the one most likely in use right now. prunable means the folder is gone and only git's record of it is left.

For every other worktree I run two checks:

bash
git -C "/src/wt/agent-c" status --porcelain
git log --oneline main..agent-two

In my test the first printed M README.md and ?? notes.md, and the second printed the one commit agent-two had that main didn't. Output from the first is work that dies with the folder, and output from the second is commits that die with the branch. Plain git worktree remove already refuses the first case with contains modified or untracked files, use --force to delete it.

The batch one-liner skips both checks:

bash
git worktree list --porcelain | grep '^worktree' | awk '{print $2}' | tail -n +2 | xargs -I {} git worktree remove --force {}

--force lets git remove a worktree with modified or untracked files, which plain remove refuses. On my test repository the one-liner removed five worktrees, agent-c among them, with its uncommitted README edit and untracked notes file. The agent-c branch had no commits of its own, so that work is gone for good. awk '{print $2}' cut wt/agent two down to wt/agent, and git answered fatal: '/src/wt/agent' is not a working tree. The locked worktree survived only because a lock takes --force twice. The command exited with 123 and left all five branches behind.

Seven test agent worktrees side by side: the force one-liner removed agent-a, agent-b, agent-c with its uncommitted edit and untracked notes, agent-e and agent-f, failed on the agent two folder because of the space in its name, and was refused by the locked agent-d, while a check-first pass removes only the merged agent-a and agent-b

Delete the agent branches that git branch --merged misses

git worktree remove keeps the agent's branch, and git branch -d refuses a branch still checked out in a worktree and, once its upstream is gone, a squash-merged one.

git branch marks the current branch with * and every branch checked out in a linked worktree with +. Deleting a + branch fails with error: cannot delete branch 'agent-a' used by worktree at '/src/wt/agent-a', so remove the worktree first and the branch second.

I tested this batch command for merged branches against those markers:

bash
git branch --merged main | grep -v "^\*\|main" | xargs -n 1 git branch -d

It passed the + itself to git as a branch name (error: branch '+' not found), hit the used-by-worktree error for every + branch, and skipped domain-fix without a word, because the filter drops any name containing "main". It exited with 123 as well.

Squash merges cause the bigger miss. A squash merge lands the branch's changes on main as one new commit, so none of the branch's own commits ever reach main. git branch --merged main left agent-b out of its list, and git log main..agent-b still showed both of its commits after the merge. The same command listed agent-c, whose worktree held uncommitted work, because a branch with no commits of its own counts as merged.

Whether -d refuses a squash-merged branch depends on its upstream. The docs say the branch must be fully merged in its upstream, or in HEAD when it has none. While origin/agent-b existed, git branch -d agent-b went through with a warning that it was not yet merged to HEAD. After I deleted the remote branch and fetched with --prune, git branch -vv showed [origin/agent-b: gone] and -d refused with error: the branch 'agent-b' is not fully merged. A branch that was never pushed gets the same refusal.

So I stopped asking git whether the commits are on main and asked what merging the branch would change. git merge-tree --write-tree computes a merge without touching any checkout and prints the tree it would produce, and when that tree is the one main already has, the branch adds nothing.

bash
git merge-tree --write-tree origin/main agent-b
git rev-parse 'origin/main^{tree}'

The two hashes matched for agent-a and agent-b and differed for agent-two, whose commit never landed. On a conflict merge-tree exits with 1 and the hashes differ, so a conflicted branch never passes for a merged one. The --write-tree mode arrived in git 2.38. When the hashes match, git branch -D is safe, since the capital letter only skips a check you just did properly.

A squash-merged agent branch with two commits beside main's single squash commit: git branch --merged compares commits and leaves the branch out, while git merge-tree --write-tree produces the same tree hash as main, so the branch adds nothing and can be deleted with git branch -D

A pushed agent branch also has a remote copy. git push origin --delete agent-b deletes it on the remote, and git fetch --prune drops the origin/... refs in your clone whose remote branch no longer exists.

Prune, release and repair git's worktree records

Git keeps a record for each worktree under .git/worktrees/, and git worktree prune deletes the records whose folders are gone, such as an agent folder removed with rm -rf.

bash
git worktree prune --dry-run --verbose

That printed Removing worktrees/agent-e: gitdir file points to non-existent location for the folder I had deleted by hand, and changed nothing. Drop --dry-run to do it for real. git gc also runs git worktree prune --expire 3.months.ago, and gc.worktreePruneExpire changes that grace period, so a stale entry is clutter in git worktree list more than a leak.

A locked worktree refuses removal even with one --force, and git prints the reason the lock was taken with:

text
fatal: cannot remove a locked working tree, lock reason: agent still running
use 'remove -f -f' to override or unlock first

I read that reason, then check that no process still runs inside the folder before I release the lock and remove the worktree:

bash
ls -l /proc/*/cwd 2>/dev/null | grep 'wt/agent-d'
git worktree unlock "/src/wt/agent-d"
git worktree remove "/src/wt/agent-d"

In my test the first line printed the process I had left running in agent-d, and nothing once I stopped it. Claude Code releases its own lock when the agent finishes, and its periodic sweep releases a lock left by a session whose process exited, but it never releases a lock you set yourself.

A folder moved with plain mv shows up as prunable too, and a prune would delete the record of a worktree that still exists somewhere else. In my test git worktree repair <new-path> printed repair: gitdir incorrect, and the worktree listed normally again. git worktree move avoids the problem in the first place.

Three kinds of stale worktree record: a folder deleted by hand shows as prunable and git worktree prune removes its record, a folder moved with mv also shows as prunable but needs git worktree repair instead of a prune, and a locked worktree needs its lock released once the agent has stopped before git worktree remove works

What git worktree remove deletes and what keeps running

git worktree remove deletes the worktree folder, its ignored files included, and git's record of it, and stops none of the processes or containers the agent started.

The ignored files surprised me. In my test a plain git worktree remove, without --force, deleted node_modules/, .env and a local database file in an ignored state folder, and exited with 0. git status --porcelain doesn't count ignored files as changes, so "clean" to git can still mean an .env you never copied anywhere else. The local and remote branches stay.

A process I started inside a worktree kept running after git worktree remove, and its working directory link read /src/wt/agent-f (deleted). An agent's dev server or test watcher keeps running the same way and keeps whatever port it opened, so the next agent's server finds that port taken. On Linux, each process's /proc/<pid>/cwd points at its working directory, and for a removed folder this machine showed the (deleted) suffix, so this finds the leftovers:

bash
ls -l /proc/*/cwd 2>/dev/null | grep '(deleted)'

docker compose down removes a project's containers and networks, and its named and anonymous volumes when you add --volumes. Run it inside the worktree before you remove the folder, since the Compose file lives in the folder you are about to delete. The default Compose project name is the directory's basename, so a project in docker compose ls named after a worktree you already removed is one you forgot to stop. Those leftovers hold memory as well as ports.

I run the repository behind Aldena this way, with its own ports, its own dev container (one Compose project per checkout) and its own local database for every worktree. So my order is fixed. I stop the container from inside the worktree, check the worktree, remove it, then delete the branch. du -sh ../wt/* from the main checkout shows me which worktrees to clear first, because every fresh worktree installs its own dependencies.

Teardown order for one agent worktree: stop its containers with docker compose down from inside the worktree, check git status --porcelain and the unmerged commits, run git worktree remove without --force, check the branch with git merge-tree and delete it with git branch -D, then delete the remote branch and prune
CommandRemovesLeaves
git worktree remove <path>The folder, ignored files included, and its .git/worktrees/ recordThe local branch, the remote branch, processes and containers
git worktree remove --force <path>The same, plus uncommitted and untracked changesThe same
rm -rf <path>The folderThe .git/worktrees/ record until a prune, branches, processes
git worktree pruneRecords whose folder is goneEverything else
git branch -d or -D <branch>The local branchThe remote branch
git push origin --delete <branch>The branch on the remoteStale origin/<branch> refs in other clones until they prune
git fetch --pruneorigin/... refs whose remote branch is goneLocal branches
docker compose downThe project's containers and networks, volumes with --volumesExternal volumes

A sweep script that removes idle, merged agent worktrees

sweep-worktrees.sh lists every linked worktree, keeps any that is locked, dirty, touched in the last 3 days or holding changes origin/main lacks, and with SWEEP=1 removes the rest with their branches.

bash
#!/usr/bin/env bash
# sweep-worktrees.sh: list agent worktrees, and with SWEEP=1 remove the ones
# that are clean, idle for DAYS and add nothing to BASE. Needs git 2.38+.
# usage: [SWEEP=1] sweep-worktrees.sh [DAYS=3] [BASE=origin/main]
set -euo pipefail
days=${1:-3}
base=${2:-origin/main}
cutoff=$(( $(date +%s) - days * 86400 ))
base_tree=$(git rev-parse "$base^{tree}")

check() {
  local wt=$1 branch=$2 flags=$3 dirty last merged
  case $flags in
    *locked*) echo "keep  $wt (locked)"; return ;;
    *prunable*) echo "gone  $wt (folder missing, run git worktree prune)"; return ;;
  esac
  case $branch in
    "") echo "keep  $wt (detached HEAD)"; return ;;
    "$base" | "${base#*/}") echo "keep  $wt (base branch)"; return ;;
  esac
  dirty=$(git -C "$wt" status --porcelain | wc -l)
  if [ "$dirty" -gt 0 ]; then
    echo "keep  $wt ($dirty uncommitted or untracked files)"; return
  fi
  last=$(git -C "$wt" log -g -1 --format=%ct HEAD 2>/dev/null || true)
  last=${last:-$(git -C "$wt" log -1 --format=%ct HEAD)}
  if [ "$last" -gt "$cutoff" ]; then
    echo "keep  $wt (HEAD moved in the last $days days)"; return
  fi
  merged=$(git merge-tree --write-tree "$base" "$branch" 2>/dev/null || true)
  if [ "$merged" != "$base_tree" ]; then
    echo "keep  $wt ($branch has changes $base lacks)"; return
  fi
  echo "drop  $wt ($branch)"
  if [ "${SWEEP:-0}" = 1 ]; then
    git worktree remove "$wt"
    git branch -D "$branch"
  fi
}

wt="" branch="" flags="" first=1
while IFS= read -r -d '' line; do
  case $line in
    "worktree "*) wt=${line#worktree }; branch=""; flags="" ;;
    "branch refs/heads/"*) branch=${line#branch refs/heads/} ;;
    locked* | prunable*) flags="$flags ${line%% *}" ;;
    "") if [ "$first" = 1 ]; then first=0; else check "$wt" "$branch" "$flags"; fi ;;
  esac
done < <(git worktree list --porcelain -z)

Run it from the main checkout after a git fetch, since it compares against origin/main.

bash
bash sweep-worktrees.sh
bash sweep-worktrees.sh 7 origin/develop
SWEEP=1 bash sweep-worktrees.sh

The dry run on my test repository, with two more worktrees added and paths shortened:

text
keep  /src/wt/agent three (HEAD moved in the last 3 days)
keep  /src/wt/agent two (agent-two has changes origin/main lacks)
drop  /src/wt/agent-a (agent-a)
drop  /src/wt/agent-b (agent-b)
keep  /src/wt/agent-c (2 uncommitted or untracked files)
keep  /src/wt/agent-d (locked)
gone  /src/wt/agent-e (folder missing, run git worktree prune)
keep  /src/wt/agent-f (HEAD moved in the last 3 days)
keep  /src/wt/domain-fix (HEAD moved in the last 3 days)

SWEEP=1 then removed both drop worktrees and deleted both branches, agent-c's two files were still there afterwards, and a second run changed nothing. With a threshold of 0 days it also removed the fresh worktrees, agent three and domain-fix included, so a space in a path and "main" inside a branch name both survive the parsing. The script reads git worktree list --porcelain -z, which ends each line in a NUL byte instead of a newline, so a path with a space stays whole.

The script never passes --force to git worktree remove, never touches a lock and never deletes a remote branch, because each of those is a call I want to make by hand. Idle time is the last time HEAD moved in that worktree, read from its own reflog, with the last commit date as a fallback. git branch -D runs only after the merge-tree check has shown the branch adds nothing to the base.

Decision flow of the sweep script for each linked worktree: locked means keep, a missing folder means prune, a detached HEAD or the base branch means keep, uncommitted or untracked files mean keep, HEAD moved within the idle threshold means keep, a merge-tree result different from the base tree means keep, and only a worktree that passes every check is removed along with its branch

How Claude Code, worktrunk and git-lanes clean up

Claude Code removes a clean --worktree worktree and its branch when an unnamed interactive session exits, but -p runs get no exit prompt and keep their worktrees.

When the worktree holds changed or untracked files or new commits, Claude Code asks whether to keep or remove it on exit. Removing deletes the worktree directory and its branch with all the work in them, and keeping prints a claude --worktree <name> --resume command for later. A named session prompts even when the worktree is clean, and a worktree another session is using stays. A -p run leaves its worktree and its lock in place until a later session's stale-lock sweep releases the lock, so I release those locks myself and remove the worktrees with plain git worktree remove.

Claude Code also removes a subagent's worktree when the subagent finishes without changes. A periodic sweep removes subagent and background-session worktrees older than cleanupPeriodDays, but keeps any with changed or untracked files or unpushed commits, and it never touches worktrees you made with git worktree add. My sweep script covers those hand-made ones and the -p leftovers.

worktrunk's wt remove deletes the worktree and its branch when merging the branch would add no changes to the default branch, which covers squash and rebase merges, the same idea as my merge-tree check. It refuses uncommitted changes unless you pass --force, and with --force it first saves them to refs/wt-backup/<branch>, a safety net I would like git itself to have. wt merge squashes, rebases and fast-forwards the branch onto the default branch, then removes the worktree and branch unless you pass --no-remove.

git-lanes ends a session with git lanes end, which commits pending changes and removes the worktree, while git lanes abort force-removes the worktree and deletes the branch. @johnlindquist/worktree has wt remove for one worktree, wt purge to pick several to remove at once, and an opt-in wt merge --remove. Its README doesn't say whether removal deletes the branch, so I check git branch afterwards. It also installs a command named wt, the same name as worktrunk's, so pick one of the two per machine.

Table of what each tool removes when an agent worktree is cleaned up: a clean, unnamed Claude Code session removes the worktree and branch on exit, choosing remove for a session with work deletes the work too, and a claude -p run keeps its worktree locked; worktrunk wt remove deletes the worktree and the branch when the branch adds nothing, refusing uncommitted work unless forced, which it saves to refs/wt-backup; git-lanes end commits first and removes the worktree, while abort also deletes the branch and the work; for @johnlindquist/worktree the docs don't state what happens to the branch

How Aldena keeps each conversation's checkout in its own sandbox

Aldena gives each conversation one sandbox, which sleeps 30 minutes after its last command and keeps its files until the conversation sits quiet for 7 days.

Aldena is my product, so read this section as the pitch it is. A conversation in an Aldena project is a chat plus every chat its agents hand work to, and all of them share that sandbox, which runs on a provider the team connects, such as Boat. Claude Code or Codex runs inside it, and the agents clone the repository there, run commands, start the app and run its tests. Two projects never share a filesystem, and you never SSH into anything.

Inside the conversation the Delivery agent hands work to one delegate at a time, so two agents never edit the same checkout at once. It branches, commits, pushes and opens the pull request, then stops, and no agent merges its own work. The org chart decides which agent can hand work to which.

Aldena project canvas where the busy agent cards list their tasks, with the Intake agent delegating to the Requirements and Delivery agents, Delivery delegating to the Backend Build, Frontend Build and Code Review agents, both build agents delegating to Code Review, and the link from Delivery to Code Review lit green while work moves along it

On my own laptop I still run my sweep script. In an Aldena project the sandbox provider bills machine time to the team's own account only while the sandbox runs, Boat by the second, and Aldena adds nothing on top of the team plan.

Ready when you are

Spin up your first project.

One project per client, product, or piece of work, staffed with intake, requirements, build and code review agents.