Worktree cleanup deletes a branch with unmerged commits
Ending a Claude Code worktree session removed the worktree and its branch, even when it had commits that were never pushed or merged.
- Agents
- Claude Code
- Reported
- Source checked
- Tags
- git, worktree, data-loss
Symptom
Commits you made in an agent's worktree are gone after the session ends. git log --all shows no trace of them.
Cause
Session cleanup removed the worktree and deleted its branch without checking for unmerged or unpushed commits. The commits became dangling objects.
Fix
Before removing a worktree, refuse if the branch has commits that aren't on the base branch. To recover, find the dangling commits with git fsck and branch them before git gc runs.
# Guard before removing an agent worktree
if [ -n "$(git -C "$WT" log --oneline main..HEAD)" ]; then
echo "unmerged commits in $WT, keeping it"; exit 1
fi
git worktree remove "$WT"
# Recovery
git fsck --unreachable | grep commit