Detecting and Recovering Stale Agent Worktrees

Separate dead worktrees from outdated ones, and save uncertain work first.

Cover illustration for “Detecting and Recovering Stale Agent Worktrees”
Written by
Deja Whitmore-Sands
Published
October 22, 2026
Reading time
9 min read

Agent worktrees fail in two different ways. Some outlive the sessions that created them. Others remain active but start from outdated code. Detecting and recovering stale agent worktrees therefore requires more than a cleanup sweep. Safe recovery begins by separating lifecycle failures from stale-base failures, inspecting both Git’s registry and the disk, and preserving uncertain work before any destructive action.

Why agent worktrees accumulate silently and what that costs

Git worktrees give each AI agent an isolated working directory on the same repository, so parallel agents do not overwrite each other’s files. Creation follows naturally from that isolation model. When an agent is spawned with isolation: "worktree", git worktree add is called automatically. Removal has no corresponding lifecycle trigger. Nothing in the standard agent lifecycle calls git worktree remove when a session ends, an agent crashes, or a branch merges.

Without cleanup, each new session adds more worktrees. The cost is not limited to untidy directories. One project had nearly a hundred worktrees that took up 81 GB under .claude/worktrees/, leaving its disk 97% full. Builds and pre-push checks then failed without clearly pointing to disk exhaustion. Another codebase’s bulk cleanup reduced its worktree count from 256 to 28 and deleted roughly 700 stale local branches across dozens of repositories. Yet disk accumulation is only one shape of the problem. An active worktree can also be stale in its contents.

The two failure classes developers actually face

Class 1 is abandoned or orphaned worktrees, a stale-lifecycle failure. A worktree remains on disk and in Git’s registry after a crash, an abandoned session, or a branch merge, although nothing still uses it. The session ends, but the worktree remains behind. Claude Code issue #26725, filed February 2026, documents a worktree from January 15, 2026 that persisted across dozens of subsequent sessions without a cleanup mechanism. A structural variant arises when someone deletes the directory with rm -rf, leaving a phantom registry entry that still pins the branch and blocks git branch -D.

Class 2 is stale-base worktrees, a stale-content failure. The worktree is live and registered, but its starting commit no longer reflects the repository’s current state. Clean tests cannot establish that the base is current. An agent can modify outdated code, pass targeted tests, report clean gates honestly, and produce a merge that silently reverts intervening work. In one long session, a subagent re-implemented work already committed to main. Two of three implement-queue-worker agents had PR branches with no common ancestor with main, originating from a snapshot 50 commits behind. Removing abandoned directories does not correct this ancestry problem.

Why abandoned worktrees are effectively immortal once dirty

Age thresholds eventually pass, and live-process working-directory locks can clear when processes stop. Uncommitted changes do not disappear through waiting. Neither do unpushed commits on a detached HEAD or unpushed-commit branches. Once those conditions exist, increasing sweep frequency cannot make removal safe, so protected abandoned worktrees continue accumulating unless someone resolves their contents.

Phantom entries persist through a different mechanism. Their directories are already gone, but Git still records the paths and treats the associated branches as checked out. Deleting files has not completed the lifecycle transition. git worktree prune clears these obsolete records, but the standard agent lifecycle does not call it automatically either. Worktrees should be classified early, before abandoned environments accumulate uncommitted state, without relying on a late disk-pressure sweep to recover both storage and unfinished work.

Three distinct states to distinguish before touching any worktree

Registered and present means that git worktree list reports a path and the directory at that path exists. This is the normal registration state, with active use and base currency still to be verified. Registered but missing means Git reports a path that no longer exists because its directory was removed out of band. That phantom entry still pins its branch. This difference tells which files, administrative records, or both need to be dealt with.

Present but unregistered means a directory exists under .claude/worktrees/, or an equivalent root, without appearing in Git’s worktree list. This can follow a parent-repository relocation or a partially failed worktree addition. Git’s pruning command will not touch that directory. Injection-scanner issue #118 describes an unregistered directory that held a file never committed anywhere, which the project had already thought was lost. Blind deletion would have destroyed it permanently, so each state also needs a separate check for uncommitted work wherever contents remain available.

The commands that reveal what Git actually knows about your worktrees

To inspect the registry, run git worktree list --porcelain. Its machine-readable output includes each registered worktree’s path, HEAD commit SHA, and branch reference. The main worktree always appears first in the output. Skip that entry in cleanup logic. Then run git worktree prune --dry-run to find old entries that point to missing directories without removing anything.

To check the remote branch state, run git fetch --prune, then git rev-parse --verify refs/remotes/origin/<branch>, replacing <branch> with the branch being checked. After a successful fetch, failure to resolve that reference indicates that the remote tracking branch no longer exists. That is a candidate signal. Local changes and unpushed commits still need to be checked, and if a remote lookup fails, the branch state must stay unknown because that failure does not prove the branch is absent.

To find present-but-unregistered directories, list the worktree root and compare its directories with the porcelain output. No Git command discovers those directories automatically. For Class 2, inspection must also record the requested remote base’s exact SHA and compare it with local HEAD, including ahead/behind counts and dirty state. These checks answer different questions. The registry describes Git’s known worktrees, the filesystem reveals directories outside that registry, and the SHA comparison establishes whether an agent’s starting point is current.

What higher-level tooling adds beyond raw Git commands

Raw Git commands inspect one repository at a time. They do not cross-reference PR state, branch merge status, or agent lifecycle metadata. Impetus WorktreeManager issue #206, closed September 21, 2026, describes detection that reports abandoned bindings with a reason and a recoverable flag. The manager marks bindings stale without deleting contents, restricts removal to managed stale worktrees under a managed root with a durable binding, and restores recoverable abandoned worktrees to a usable lifecycle state.

Agent-parley 0.13.0, released September 28, 2026, approaches reclamation through project lanes. Its reclaim command enumerates repository worktrees through Git’s porcelain output and attributes each to a lane by branch or path. It reclaims worktrees whose branches are merged, whose lanes are retired, or which are unattached and untouched longer than inactive_after. Dirty worktrees are retained and reported. reclaim --dry-run shows candidate sizes, while explicit --force removal follows a recovery checkpoint.

The injection-scanner issue supplies a complementary warning from manual pruning. “No longer in active use” calls for classification separate from destruction because an unregistered directory can contain otherwise unrecoverable files. A tool can find an abandoned binding or inactive lane without claiming that all the work tied to it can be thrown away. Their shared contribution is richer evidence and a preservation path.

The safe recovery path for Class 1: working from least destructive to most

For Class 1 recovery, fix the registry before touching directories that are still there. After reviewing the dry run, run git worktree prune to clear phantom entries whose directories are already gone. This removes only administrative records. It also resolves the stale registration that can prevent branch deletion. Pruning does not recover deleted contents, and it does not inspect unregistered directories, so those remain separate cases.

Next, check each registered-and-present worktree with git -C <path> status --porcelain. Check for unpushed commits with git -C <path> log @{u}..HEAD, or an equivalent comparison appropriate to the worktree. A clean directory alone is not sufficient evidence. Only after confirming that an abandoned worktree is clean and has no work requiring preservation should removal proceed with git worktree remove <path>, without --force. If Git refuses because the tree is dirty, that refusal is the intended safeguard.

Salvage dirty abandoned worktrees by preserving their changes on a named branch and pushing the resulting commits, or stashing the changes, before removal. The manager’s restore path offers another response to abandonment by returning a recoverable binding to usable service. Disposal need not be the first available action. Present-but-unregistered directories also require review because registration cannot establish what their files contain.

Destructive branch deletion needs its own explicit gate. The bin/worktree-gc tool documented in the Claude Code issue defaults to dry-run reporting, while --apply enables safe, merged-only deletion with -d. Its --apply-force mode additionally enables -D for unmerged branches. An automated reaper should never use git worktree remove --force, because it bypasses the dirty check and can permanently destroy uncommitted work.

The safe recovery path for Class 2: what to do when an agent is already on a stale base

Class 2 recovery concerns the base commit. A worktree can be clean and correctly registered yet still have the wrong starting tree. The recommended detection contract begins before the agent starts. Fetch and resolve the requested remote base, then record the exact remote SHA used for provisioning. Before each new agent turn, compare local HEAD with the remote SHA, since an environment that was suitable earlier may no longer be suitable.

If the worktree is clean, zero commits ahead, and behind the remote, fast-forward it automatically. If it is dirty, ahead, or diverged, block the agent and report the exact local and remote SHAs with ahead/behind counts. Existing work changes the recovery boundary. A behind-only environment is straightforward to update, but someone must decide what to do in those other states before the base changes. That decision is still needed even if tests pass inside the old tree.

Stale session snapshots require a provisioning workaround. In long sessions that have been through /compact, automatic isolation can create a worktree from an outdated snapshot. The coordinator should instead run git worktree add --detach /tmp/wt-task <sha>, where <sha> is the verified current remote HEAD. It should pass that path in the agent’s brief.

Branch reuse creates a related route to stale state. Claude Code derives the branch name from an 8-hex-char prefix of the subagent’s agentId, and an existing name can silently bring prior-session state into new work. Check whether the target name exists before provisioning, then reject it or explicitly reset the branch to the intended SHA after resolving any work that needs preservation. Agentic-coding-tools issue #619 describes the same failure in _branch_creation_start_point, which returned an existing branch without checking whether it was stale against origin/main or the parent branch.

Where automation should stop and human judgment must take over

The objection to automated cleanup is grounded in recorded losses. A reaper that misclassifies a worktree can permanently destroy unpushed work. Safe automation therefore needs positive evidence. Registry pruning for missing directories, read-only classification, and dry-run reporting are suitable automated operations. Removal belongs in that category only when the worktree is clean, its remote branch is absent, and its PR is confirmed merged.

Uncommitted changes, unpushed commits, and present-but-unregistered directories require human decisions. A failed remote lookup also requires review because unknown state is not proof of abandonment. Force must remain outside unattended cleanup flows. An explicit human invocation should follow a recovery checkpoint, as in the reclamation tool’s design, rather than bypass preservation because storage is scarce.

For stale-base prevention, automation belongs before provisioning and at the guarded checks between agent turns. A pre-flight fetch and SHA comparison can catch the problem before an agent produces 15 commits of redundant work. For lifecycle cleanup, the conservative approach is to reap only provably merged worktrees on each preflight cycle and surface everything else for review. Dry-run output should stay the default, and deletion should require an explicit opt-in.

Deja Whitmore-Sands