Repository navigation
fix(prune): unregister stale worktrees whose directory remains - #4228
Conversation
Git calls a worktree entry prunable once the `.git` its registration names is gone, whether the whole directory went or only that file did; macOS's `$TMPDIR` sweep deletes idle files and keeps directories. Worktrunk unregistered stale entries with `git worktree remove`, which refuses an entry whose directory remains, `--force` included, so #4226 made prune skip them and `wt remove` refused them with `WorktreeMissing`. `prune_worktree_entry` now does what `git worktree prune` does to one entry: under the registry lock it repeats git's `should_prune_worktree` test (not locked, nothing at the recorded `.git`) and deletes `.git/worktrees/<id>`, leaving the directory in place. No git command does this for one entry. `git worktree prune` takes no path, and a repo-wide sweep would also unregister entries prune keeps: unmerged branches, and detached HEADs whose commits then become unreachable. `wt remove` and `wt step prune` therefore unregister a stale entry in either shape. The picker's branch-only removal now prunes the stale entry before deleting the branch, instead of leaving an entry that names a deleted branch. Messages that called every stale entry "directory missing" now say it is stale. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
worktrunk-bot
left a comment
There was a problem hiding this comment.
The reimplementation of git's prune test reads faithfully — I checked should_prune_worktree's two halves against git 2.55 by experiment and git worktree list / git worktree prune do report and unregister a .git-gone entry with its directory intact, so the premise holds. Four things below; the first is why this is a comment rather than an approval.
The two stale shapes are not equally recoverable
A worktree whose .git file went but whose directory remains is fully recoverable: git worktree repair <path> rewrites the .git file, clears prunable, and the per-worktree index survives, so staged and unstaged changes come back. A worktree whose whole directory went is not recoverable at all. This PR collapses the two into one treatment, and prune_worktree_entry's remove_dir_all on the registration is what closes the repair window — the docstring's own point that repair relinks an admin dir rather than recreating one.
Verified against git 2.55
$ git worktree add ../wt1 -b f1
$ echo staged >> ../wt1/f && (cd ../wt1 && git add f) && echo dirty >> ../wt1/f
$ rm ../wt1/.git
$ git worktree list --porcelain | tail -2
branch refs/heads/f1
prunable gitdir file points to non-existent location
$ git worktree repair "$(cd ../wt1 && pwd)"
error: unable to locate repository; .git file broken: …/wt1/.git
repair: .git file broken: …/wt1
$ git worktree list --porcelain | tail -2 # no prunable line
branch refs/heads/f1
$ (cd ../wt1 && git status --short)
MM f
Exit status is 1 and the diagnostic goes to stderr, but the repair happened: the entry is live again and both the staged and unstaged edits are intact.
For the case that motivates the PR — macOS's $TMPDIR sweep taking idle .git files out of live checkouts — the working tree is intact and "repair it" is at least as plausibly what the user wants as "unregister it and delete the branch", which wt step prune --yes now does silently on an integrated branch. Naming git worktree repair <path> somewhere on the stale path (the ⊟ hint, or prune's dry-run line when the directory remains) would keep the recoverable case recoverable without giving up the fix. Alternatively keep the shapes distinct so the recoverable one takes an explicit ask.
Either way the verdict isn't mine: per .claude/skills/running-tend/references/review-pr.md → "Data-Loss Surface: Hold for Human Review", a diff that widens what a deletion reaches is held for a human. Requesting your review is moot since you wrote it.
WorktreeMissing's hint still points at the repo-wide sweep
The title now covers both shapes, but the hint under it in GitError::fmt is unchanged: To clean up, run git worktree prune. That is the command whose blast radius the new prune_worktree_entry docstring spends a paragraph arguing against, and relocate.rs's equivalent hint moved to wt step prune in this same PR — so the two now disagree about what to tell the user.
One hint serves two callers, which is the wrinkle: from usable_worktree_for_branch (wt switch / wt merge / wt step push) the scoped answer is wt remove <branch>, which this PR just made work for the .git-gone shape; from the detached arm in repository_ext.rs the branch field holds a directory name, so wt remove would loop back to the same error and wt step prune is the only wt spelling that clears it. Which way to split it is a judgment call — but the repo-wide command isn't the one the rest of the PR argues for.
is_prunable's own docstring still says the directory is gone
repository_ext.rs swapped !wt.path.exists() for wt.is_prunable(), which makes that predicate the gate for the whole stale-entry path. Its docstring on WorktreeInfo in src/git/mod.rs still reads "prunable (directory deleted but git still tracks metadata)" and "Prunable worktrees cannot be operated on - the directory doesn't exist" — the claim this PR disproves, on the definition a later reader would take as the contract. The same wording survives in four more places the terminology pass didn't reach: the duplicate sentence on ListItem::is_prunable, ListItem::placeholder's "A prunable worktree's directory is gone" (whose twin in collect/execution.rs you did update), the ⊟: Prunable (directory missing) line in status_symbols.rs's module docstring (the code-side mirror of the legend updated in src/cli/mod.rs), and for_each.rs's "Filter out prunable worktrees (directory deleted)". All outside the diff — say the word and I'll push the five.
codecov/patch is red at 85%
68/80 patch lines. Two of the twelve misses aren't this PR's: handlers.rs's RetainedCheckedOut and RetainedRaced arms were already uncovered on 7193c09, and the mechanical info_message(&branch_info) → {branch_info} rewrite pulled them into the patch. The other ten look closable, which would put the patch at 78/80.
The ten, and what triggers each
repository_ext.rs, the detached-prunableWorktreeMissingreturn (4 lines). Before this PR that arm was reached by the recreated-directory-with-branch case, whichtest_remove_worktree_directory_recreatedcovered; that case now succeeds instead, so the arm lost its only trigger and nothing exerciseswt remove <path>on a detached stale entry.test_prune_stale_detached_worktree's setup transplanted intotests/integration_tests/remove.rscovers it.picker/mod.rs, the failed-prunetracing::warn!and early return (2 lines). The read-only-registration trick this PR just introduced intest_prune_surfaces_failing_metadata_pruneworks here too, alongsidetest_do_removal_branch_only_prunes_stale_entry.worktrees.rs,absent's stat-error arm (4 lines). Reachable on unix by chmod-ing the worktree's parent to0o000sosymlink_metadata(<path>/.git)returnsEACCESrather thanNotFound.
Per CLAUDE.md → Coverage this gates the merge even though GitHub marks it non-required.
Covers the stat-error refusal, the picker's failed-prune path, and `wt remove` on a detached stale entry, and updates the docstrings that still described every prunable worktree as one whose directory is gone. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
worktrunk-bot
left a comment
There was a problem hiding this comment.
One finding on the new tests. The earlier review's hold still stands, so this is a comment rather than an approval.
Both permission-gated tests fail as root instead of skipping
prune_worktree_entry_keeps_an_entry_it_cannot_check and test_prune_surfaces_failing_metadata_prune build their triggers out of mode bits — 0o000 on the worktree's parent directory, 0o555 on the registration directory — and euid 0 ignores both. Under root the first test's symlink_metadata on <guarded>/wt/.git succeeds, so prune_worktree_entry bails with is no longer stale; its .git exists and the Failed to check assertion fails. The second's remove_dir_all succeeds, so the prune succeeds and a failing metadata prune is a failed removal, not a silent skip fails. Both report as failures, not skips.
That environment is supported here: .codex/cloud.sh states that setup and maintain "run as root, which is how Codex Cloud runs the agent — so the tests that need an unprivileged uid skip, as they already do", and root CLAUDE.md points contributors at that setup. The suite already carries the probe-and-skip idiom for exactly this — test_remove_foreground_succeeds_with_stuck_directory in tests/integration_tests/remove.rs and test_remove_dir_with_progress_skips_unreadable_subtree in src/remove_dir.rs, whose comment names the reason ("euid 0 ignores DAC mode bits"). Suggestions inline for both.
Worth naming why the second one is new exposure: the git worktree remove shim it replaced failed the same way for any uid, so swapping to a permission bit is what made that test uid-dependent.
… delete euid 0 ignores DAC mode bits, so the two tests that trigger a failed prune with a permission bit now probe and skip under root, as the suite's other permission tests do. A shim that fails the CAS delete while keeping the ref covers prune reporting the pruned entry before the kept branch. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Unregistering a stale worktree deletes its index and any in-progress operation state, which `git worktree repair` can restore only while the registration exists. `Repository::stale_worktree_work` reads the registration's index against its HEAD and its operation state files; `wt step prune` skips an entry holding either, and `wt remove` refuses with a repair hint unless `--force` names it. `WorktreeMissing` now offers `git worktree repair <path>` when the directory remains. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
worktrunk-bot
left a comment
There was a problem hiding this comment.
Two findings on the work guard. The first has inline suggestions; the second is a decision.
The repair hints double-escape their path
format_path_for_display already shell-escapes — its own doc comment gives /Users/alex/repo → ~/repo and /Users/alex/my repo → '/Users/alex/my repo', and it only takes the tilde form when the remainder needs no quoting, precisely because "tilde doesn't expand inside quotes". Both new hints wrap that result in escape() a second time. ~ isn't in shell-escape's unix whitelist (a-zA-Z0-9-_=/,.+), so a worktree anywhere under $HOME — the normal place for one — renders:
↳ To restore the worktree, run git worktree repair '~/code/myproject.feature-auth'
Pasted, that gives fatal: Invalid path '<cwd>/~': No such file or directory (git 2.55). A path that needed quoting comes out doubly quoted — ''\''/tmp/my repo'\''' — naming a path that doesn't exist either. The WorktreeLocked arm below is the pattern the rest of the file follows: let path_display = format_path_for_display(path);, no escape.
Nothing catches it because every fixture path is inside the whitelist: /tmp/repo.stale-branch in worktree_errors_render, and the redacted _REPO_.feature in the new remove_stale_worktree_holding_staged_changes snapshot. A worktree_errors_render case with a ~-prefixed path would pin it.
Suggestions inline for both lines. Happy to push them as a commit if you'd rather.
An unborn registration turns wt remove into a raw git failure
stale_worktree_work runs diff-index --cached HEAD against the registration, and on an unborn HEAD git exits 128 (fatal: bad revision 'HEAD') — so prepare_worktree_removal propagates a CommandError from self.stale_worktree_work(&wt.path)?. Keeping the entry is right; the index there holds the only copy of the staged files. But wt remove <branch> now surfaces the plumbing invocation instead of a message, and nothing tells the user that -f is the way through.
That shape doesn't error today: on main, wt.branch.is_some() && !wt.path.exists() takes the branch-only fallback before the prunable arm, so wt remove on an orphan worktree whose directory went reaches the prune rather than a command failure. So this is a regression against main for that one shape, not just a new refusal.
Reproduction
$ git worktree add --orphan -b fresh ../wt-orphan
$ echo work > ../wt-orphan/first.txt && git -C ../wt-orphan add first.txt
$ rm -f ../wt-orphan/.git
$ git worktree list --porcelain | tail -3
HEAD 0000000000000000000000000000000000000000
branch refs/heads/fresh
prunable gitdir file points to non-existent location
$ git --git-dir .git/worktrees/wt-orphan diff-index --ignore-submodules=none --cached --quiet HEAD --
fatal: bad revision 'HEAD'
exit=128
stale_worktree_work_reads_the_registration pins this as is_err(), so it's deliberate at the API; the question is what wt remove does with it.
Either a StaleWorktreeWork variant for "couldn't tell" so the refusal renders with the same title and -f hint, or an unborn-HEAD special case that answers from the index alone. wt step prune needs nothing — its matches!(…, Ok(None)) already skips silently, as it does for a dirty worktree.
Comment rather than approve for the reason the first review gave: the diff widens what an unregistration reaches, which .claude/skills/running-tend/references/review-pr.md → "Data-Loss Surface: Hold for Human Review" holds for a human. The work guard narrows it back and the git worktree repair hint answers that review's first point — with the escaping fixed, the recoverable case is genuinely recoverable. I also checked the claim the hint makes for the directory-gone shape: mkdir <path> && git worktree repair <path> does clear prunable and bring the index back (git status reports MD), exit 1 and the .git file broken diagnostic notwithstanding.
…st the empty tree `format_path_for_display` already shell-escapes, so wrapping it in `escape()` again left `~` unexpanded and double-quoted paths needing quotes. On an unborn HEAD, `diff-index --cached HEAD` fails, which turned `wt remove` on a stale orphan worktree into a raw git error; the index is now compared against the empty tree there, as `git diff --cached` does. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
worktrunk-bot
left a comment
There was a problem hiding this comment.
One new finding on 4302f4a5c, plus a duplication note. Still a comment rather than an approval, for the data-safety reason the first review gave.
The test's docstring now contradicts the assertions under it
stale_worktree_work_reads_the_registration's doc comment still closes with "a HEAD the index can't be read against is an error rather than a clean answer". That is the behavior this commit replaced, and the two lines it described are in this diff: the unborn case now asserts Ok(Some(StagedChanges)) and the new unborn_empty case asserts Ok(None). Neither is an error, and nothing in the suite now pins the old claim, so the doc comment is the one place a reader looking for stale_worktree_work's contract on an unborn HEAD gets the pre-fix answer. Suggestion inline.
The HEAD-or-empty-tree rule now has two spellings
WorkingTree::index_base is the existing home for it, and its doc comment claims the role explicitly: "The tree-ish the index is compared against for staged changes: HEAD, or the empty tree on an unborn branch. Porcelain git diff --cached picks this itself; plumbing (diff-index --cached) needs it spelled out." The new rev-parse --verify --quiet HEAD / empty_tree_sha pair in stale_worktree_work re-derives that rule, necessarily — a stale registration has no WorkingTree to call it on — so the two can't share code as written, and a later change to either (a different unborn test, a different base) has nothing pointing at the other.
Worth deciding which: hoist the rule to a Repository helper taking a git dir and have index_base delegate, or leave both and cross-reference them in their doc comments. Happy to push either.
|
Confirming both findings from that review are closed on 4302f4a — the new head's own findings are in my 07:30 review. Double-escaped hints. The display test pins the regression: a path needing quotes renders Unborn registration. I checked the two exit codes the new code depends on against git 2.55, on an orphan registration whose Also clear since the earlier reviews: |
`WorkingTree::index_base` and `stale_worktree_work` both chose between HEAD and the empty tree; `Repository::index_base_for` now owns that rule and both call it. Also corrects the stale-work test's docstring, which still described an unborn HEAD as an error. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
…#4302) A detached worktree mid-rebase takes the name of the branch it is rebasing, found by running `git rev-parse --git-dir` from the worktree's path. For a stale entry whose directory remains but whose `.git` is gone, that lookup walks up to whatever repository encloses the directory, so a detached worktree nested inside the main worktree (e.g. `repo/.worktrees/x`) was named after the main worktree's rebase. #4228 (unreleased) lets `wt step prune` and `wt remove` unregister such entries, which turned the mislabel into data loss: with the main worktree rebasing an integrated branch, `wt step prune` judged the stale detached entry by that branch and deleted its registration, leaving commits held only by its detached HEAD unreferenced. `wt remove <path>` did the same instead of refusing. The 0.80.0 release's data-loss review found it; reproduced end-to-end before the fix, and after it prune keeps the entry and `wt remove` refuses. A stale entry's git dir is its registration `<common>/worktrees/<id>`, so `finalize_worktrees` now reads a stale entry's rebase state from there via the existing `Repository::registration_at`; live detached worktrees still use `rev-parse`. `test_finalize_worktree_stale_reads_its_own_rebase` covers both a nested stale entry (must get no label) and a stale entry that is itself mid-rebase (labelled from its registration). > _This was written by Claude Code on behalf of max-sixty_ Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Bumps 0.79.0 → 0.80.0 and adds the `## 0.80.0` changelog section, cut from `12efb5159`. The bump is minor because the library API breaks (see Verification). ## Verification - `cargo run -- hook pre-merge --yes` on the cut tip: 4985 passed. - `nightly.yaml` on `12efb5159`, all jobs green including feature-powerset: https://github.com/max-sixty/worktrunk/actions/runs/36338233859 - `cargo semver-checks check-release -p worktrunk` reports five major-level lints, the removals and signature changes listed in the Internal entry. - Changelog: repeated verification passes against source until one came back clean. Fixed headlines name the condition a bug needed rather than its worst case, and near-zero-reach fixes are folded into two roll-up bullets, per #4295. - Data-loss surface review over `v0.79.0..HEAD` with independent finders. The one real finding, a nested stale detached worktree read as the enclosing repo's rebase so `wt step prune` could unregister it, was fixed in #4302. The review also found a squash regression in the backup path, fixed in #4303. The remaining candidates were adjudicated acceptable and signed off: #4228 unregistering stale worktrees whose directory remains (files stay on disk; the branch is deleted only if integrated), #4206 leaving a detached `HEAD` on Ctrl-C during a slow commit hook, #4251 allowing `--no-squash` merges with untracked files, #4219 dropping `--no-hooks` from the skill example, and #4279's `docker stop` recipe. #4252 closes a submodule data-loss path. > _This was written by Claude Code on behalf of max-sixty_ 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Git calls a worktree entry prunable once the
.gitits registration names is gone. That happens when the whole directory is deleted, and also when only the.gitfile goes: macOS's$TMPDIRsweep deletes idle files and keeps directories, which left two such checkouts registered in a real repo. Worktrunk unregistered stale entries withgit worktree remove, which refuses an entry whose directory remains (validation failed … .git does not exist,--force --forceincluded). #4226 stopped that from failingwt step pruneby skipping the entry, so it stayed⊟forever, andwt removerefused it withWorktreeMissing.Repository::prune_worktree_entrynow reproducesgit worktree prunefor the one named entry. Under the registry write lock it finds the registration whosegitdirnames the path, repeats git'sshould_prune_worktreetest (nolockedfile, nothing at the recorded.git), and deletes.git/worktrees/<id>, which is git'sdelete_git_dir. The directory and any files in it stay. The test runs at deletion time, so an entry locked or reconnected since the scan is refused rather than unregistered.No git command does this for one entry:
git worktree prunetakes no path,removeandmovefail validation, andrepairrelinks rather than unregisters. A repo-widegit worktree prunealso unregisters entrieswt step prunedeliberately keeps: branches with unmerged commits, detached HEADs holding the only reference to their commits (whichgit gccan then delete), the default branch's worktree, and unborn orphans. The rationale sits in theprune_worktree_entrydocstring.What changes for users:
wt step pruneandwt remove <branch>unregister a stale entry whether its directory is gone or only its.gitis.wt remove featureon a recreated directory used to fail with✗ Worktree directory missing for feature. It now prints✓ Pruned stale worktree & removed branch feature (same commit as main, _)and leaves the directory in place.wt step pruneskips as unborn..git, matching git, instead of refusing.Worktree for X is stale; its directory or .git is gone, the⊟legend readsPrunable (worktree directory or its .git gone), and the retained-branch line readsPruned stale worktree for X. Where the directory remains, that error's hint offersgit worktree repair <path>instead ofgit worktree prune, which would sweep every stale entry in the repo.Unregistering deletes the entry's index, per-worktree reflog and any in-progress rebase, merge, cherry-pick, revert or bisect state. While the entry exists,
git worktree repair <path>restores all of it (recreating the directory first if it went too); afterwards staged files survive only as dangling blobs. So here worktrunk is more careful thangit worktree prune.Repository::stale_worktree_workreads the registration:diff-index --cached --quiet HEADagainst its index, plus the same state filesWorkingTree::operation_in_progressreads, now shared asoperation_in_progress_at. An entry holding either is kept:wt step pruneskips it silently, as it skips a dirty or locked worktree.wt removerefuses with✗ Worktree for feature is stale but holds staged changes(or… with a rebase in progress) and↳ To discard the stale worktree, run wt remove -f feature; to restore it, run git worktree repair <path>.--forcewaives the check, as it waives a live worktree's uncommitted changes.HEADthe index is compared against the empty tree, asgit diff --cacheddoes, so an orphan worktree with nothing staged still unregisters. A check that fails for any other reason keeps the entry.The deletion-time test in
prune_worktree_entrycloses the gap after the check: a stale entry has no.gitto stage through, and one repaired in between is refused.Tests: unit tests cover
prune_worktree_entry's refusals (live, locked, unregistered, a.gitit can't stat), each stale shape (absent, directory without.git, path now a file), and its wait on the registry lock. Removing either check or the lock fails them. The picker tests cover both a pruned stale entry and a failed prune that keeps the branch,wt removeon a detached stale entry is pinned to its error, and a shim that fails the branch's CAS delete checks that prune still unregisters the entry and reports the kept branch. The two tests that use a permission bit as the failure trigger skip under root, which ignores it. The prune and picker tests cover a directory that remains.test_prune_surfaces_failing_metadata_prunenow triggers the failure with a read-only registration directory.test_prune_metadata_removals_serializeand its two git shims are removed: they interceptedgit worktree removeteardowns, which this path no longer runs. For the work guard, a unit test runsstale_worktree_workon clean, staged, bisecting,--no-checkout(no index), unborn-with-a-staged-file and unborn-with-an-emptied-index registrations.test_prune_keeps_stale_entries_holding_workchecks that prune keeps a staged branch entry and a bisecting detached one while pruning a clean one.test_remove_stale_worktree_holding_staged_changespins the refusal and checks thatwt remove -fthen prunes the entry and leaves the files.🤖 Generated with Claude Code