Skip to content

fix(merge): honor git worktree lock when cleaning up - #4073

Merged
max-sixty merged 6 commits into
max-sixty:mainfrom
Duang777:fix/merge-honors-worktree-lock
Sep 13, 2026
Merged

max-sixty merged 6 commits into
max-sixty:mainfrom
Duang777:fix/merge-honors-worktree-lock

Conversation

@Duang777

Copy link
Copy Markdown
Contributor

Summary

  • wt merge built a RemovalPlan by hand and skipped the lock check wt remove already had, so a successful merge could rename a git worktree lock'd feature worktree into trash and report success.
  • After merge, a locked worktree is now kept (Worktree preserved (locked)) the same way a primary worktree is kept. The shared staging path also refuses a lock, including under --force, so every removal caller is covered.

Test plan

  • cargo test --lib -- git::remove::tests (includes stage_refuses_locked_worktree and stage_refuses_locked_worktree_even_with_force)
  • cargo test --test integration test_merge_preserves_locked_worktree
  • cargo test --test integration test_merge_fast_forward
  • cargo test --test integration test_remove_locked (existing lock tests still pass)
  • git worktree lock . in a feature worktree, then wt merge — merge succeeds, worktree stays, message names the lock reason

Made with Cursor

Merge built a removal plan by hand and skipped the lock check wt remove
already had, so a successful merge could trash a locked feature worktree.
Keep the worktree after merge, and refuse the lock on the shared staging
path so every caller is covered.

Co-authored-by: Cursor <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wt merge really did rename a locked worktree into the trash, and putting the guard in stage_worktree_removal so every removal caller inherits it — rather than only patching merge's hand-built plan — is the right depth for it. I'm not approving: the diff changes the removal path in src/git/remove.rs (the trash rename and the git worktree remove fallback), and this repo's review policy holds changes to that surface for a human rather than a bot sign-off. Requesting @max-sixty.

lint is red — rustfmt wants the new test line wrapped. Suggestion inline; cargo fmt --check is clean with it applied.

Outside the diff, wt merge --help no longer describes what the code does. Step 7 of the pipeline in src/cli/mod.rs still reads "Removes the worktree and branch. Use --no-remove to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved." — the same enumeration you took from four conditions to five in finish.rs's module docstring, minus the new one. That block is the primary source for the command pages, so the mirrors under docs/src/content/docs/ and skills/worktrunk/reference/ regenerate from it (cargo test --test integration test_docs_are_in_sync). Say the word and I'll push that commit.

What I verified
  • git_dir()/locked is the right file: git worktree lock --reason writes .git/worktrees/<id>/locked with a trailing newline, and rev-parse --git-dir from the linked worktree resolves to that admin dir. trim() covers the newline.
  • cargo check --lib --tests clean; git::remove::tests::stage_refuses_* both pass locally.
  • No caller of stage_worktree_removal is newly broken by the added error: prepare_worktree_removal rejects a locked worktree in its path arm before planning, and prune's gather_check_items never selects one, so the new gate is a backstop rather than a new refusal on an existing path.

Comment thread src/git/remove.rs Resolved
Comment thread src/git/remove.rs Resolved
Comment thread src/git/remove.rs Resolved
Comment thread src/git/remove.rs Resolved
Use path_dir_name for the locked-worktree error, rustfmt the new test,
and document the file read as a stale-cache close rather than a lock-order
constraint. wt merge --help now names a locked worktree as preserved.

Co-authored-by: Cursor <[email protected]>
@Duang777

Copy link
Copy Markdown
Contributor Author

Addressed the review: rustfmt, path_dir_name, the stale-cache rationale, and wt merge --help now names a locked worktree as preserved (docs and help snapshots regenerated).

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

All four are applied verbatim in 54eaf4834f6540f2a3c278a62be936284419ba08, and you beat me to the help-text follow-up — nothing left for me to push.

What I re-checked: path_dir_name is the same function WorktreeInfo::dir_name() delegates to, so a detached locked worktree now reports the same name through both WorktreeLocked constructions. The stale-RepoCache rationale replaced the lock-order claim in all three places it appeared — the stage_worktree_removal docstring, the inline comment beside the check, and lock_reason's docstring, which carried the same wrong claim and which I hadn't flagged. Step 7 now reads "already on the target branch, in the primary worktree, or locked" in src/cli/mod.rs, and the three generated mirrors plus both help snapshots match it — six sites in sync, with check-docs and lint green at that head.

My position is unchanged, and it isn't about these fixes: the diff still changes the removal path in src/git/remove.rs (the trash rename and the git worktree remove fallback), which this repo holds for a human rather than a bot sign-off. Still @max-sixty's call. test (linux|macos|windows) and codecov/patch are in flight at that head.

codecov/patch missed the no-reason preserve message and the unreadable
locked-file path. Exercise both, and drop a matches! in the force test
that llvm-cov counted as a miss.

Co-authored-by: Cursor <[email protected]>

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two small things on the current head; neither touches the fix itself, and the verdict still sits with @max-sixty for the reason already on the thread.

The FAQ's statement of the lock guarantee is still written as a list of commands. What can Worktrunk delete? says "Neither git worktree remove nor wt remove (even with --force) will delete them" — that paragraph is where a user goes to find out whether locking a worktree actually protects it, and before this PR it was quietly false for the other command that removes worktrees. Putting the guard in stage_worktree_removal makes the guarantee path-independent rather than wt remove's, so naming wt merge there (or restating it as "no worktrunk removal path") is what carries the fix to where it's documented. Root CLAUDE.md → Data Safety asks for exactly that review: "Review new code that changes this surface against those sections." It's outside the diff — say the word and I'll push the commit.

The other is inline: the new snapshot carries an assertion_line key. insta strips that on accept, and it's the only snapshot under tests/snapshots/ that has one — the sibling merge_preserves_locked_worktree_no_reason.snap added in the follow-up commit doesn't. Left in, it pins a line number that goes stale as merge.rs moves and produces a spurious diff on the next regeneration.

The FAQ still said only wt remove honors git worktree lock. The guard
now lives on every removal path, so the page that documents the
guarantee has to name merge too. Also drop assertion_line from the
new snapshot so insta will not rewrite it later.

Co-authored-by: Cursor <[email protected]>
@Duang777

Copy link
Copy Markdown
Contributor Author

Addressed the remaining nits in f641dc9:

  • FAQ lock guarantee now names every Worktrunk removal path (wt remove and wt merge), including --force. Generated skill mirrors regenerated via test_docs_are_in_sync.
  • Dropped assertion_line from merge_preserves_locked_worktree.snap so insta will not rewrite it later.

Still waiting on @max-sixty for the src/git/remove.rs surface.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Both are applied as asked in f641dc9ac, and the FAQ edit is actually stronger than what I flagged: restating the guarantee as "nor any Worktrunk removal path … even with --force" is accurate beyond the two commands it names. Every removal flow reaches stage_worktree_removal through one of the two entry points in src/output/handlers.rs — remove_worktree_with_cleanup on the synchronous path, execute_instant_removal_or_fallback on the background one — so wt step prune and the picker's removal inherit the same refusal, and the sentence stays true if another caller is added later. All three copies of the page moved together and check-docs is green at this head. On the snapshot, grep -rl assertion_line tests/snapshots/ now comes back empty.

Nothing left on my side — no commit for me to push, and you're right that the src/git/remove.rs surface is @max-sixty's call rather than mine.

codecov/patch, code-coverage, test (linux), lint, and check-docs have all passed at f641dc9ac; test (macos) and test (windows) are still running.

Comment thread CHANGELOG.md Outdated

### Fixed

- **`wt merge` honors `git worktree lock`**: merge constructed a removal plan by hand and skipped the lock check `wt remove` already had, so a successful merge renamed a locked feature worktree into trash and reported success. It now keeps the worktree (`Worktree preserved (locked)`) the same way it keeps a primary worktree, and the shared staging path refuses a lock even if a caller skips planning.

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@worktrunk-bot can we totally rewrite this line, it's super confusing

do we now reproduce git's behavior? let's say that if so

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rewritten in 3a55a2e23. It leads with the behavior instead of the removal-plan internals, and answers your question inline — we reproduce git's refusal, not its escape hatch:

  • wt merge no longer deletes a worktree locked with git worktree lock: its cleanup step removed the worktree anyway and reported success. The merge now completes and prints Worktree preserved (locked), and every Worktrunk removal path refuses a lock even under --force — what git worktree remove does, minus git's -f -f override. Unlock with git worktree unlock <path> first.

The lock check this PR adds to stage_worktree_removal is git's behavior: git refuses a locked worktree, and a single --force does not override it either. Where we diverge is the override — worktrunk's --force means worktree dirt and --force-delete means branch safety, so there is no -f -f equivalent and WorktreeLocked points at git worktree unlock <path> instead. That is why the entry says "minus git's -f -f override" rather than claiming a straight match.

The other half has no git analogue to reproduce: git never removes a worktree as a side effect of a merge, so wt merge completing and printing Worktree preserved (locked) rather than erroring is worktrunk's own call — the same shape as the existing --no-remove and primary-worktree preserves.

I also added the #4073 citation and thanks @Duang777, which the entry was missing; the release skill's CHANGELOG conventions ask for both on an external contribution.

git 2.55.0 behavior I checked against
$ git worktree lock --reason "keep this" ../wt1

$ git worktree remove ../wt1
fatal: cannot remove a locked working tree, lock reason: keep this
use 'remove -f -f' to override or unlock first
exit=128

$ git worktree remove --force ../wt1
fatal: cannot remove a locked working tree, lock reason: keep this
use 'remove -f -f' to override or unlock first
exit=128

$ git worktree remove --force --force ../wt1
exit=0

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up on the same line: the branch had gone CONFLICTING against main — #4077 landed its own ### Fixed entry in this exact spot at 23:31, which is what turned pre-commit.ci red (its "mergeable check" reports a merge conflict, not a lint failure). That predates the rewrite; f641dc9ac conflicted with the current main too.

Merged main in as ac2704aa0 and kept both entries, with #4077's wt step prune bullet in the position it already holds on main and this one after it — reorder if you read the lock fix as the higher-interest of the two. test_docs_are_in_sync and the test_help* snapshots still pass across the merge, which was the part worth checking: main brought in #4079's heading-anchor scoping and this PR edits src/cli/mod.rs, so the generated mirrors could have drifted.

All four required checks pass at ac2704aa0 — test (linux|macos|windows) and fast-checks — along with lint, check-docs, code-coverage, codecov/patch, and pre-commit.ci. affected tests (windows, advisory) is still running.

Lead with the user-visible behavior instead of the removal-plan internals, and state what the new refusal matches in git worktree remove.
@max-sixty
max-sixty merged commit 48626f2 into max-sixty:main Sep 13, 2026
40 checks passed
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.78.0

Created-by: HarmonybrewBot
Commit-by: HarmonybrewBot
Merged-by: HarmonybrewBot
Description: Created by `brew bump`

---

Created with `brew bump-formula-pr`.<details>
  <summary>release notes</summary>
  <pre>## Release Notes

### Improved

- **Hook scripts read renamed context keys**: the JSON piped to every hook drops `worktree`, `repo_root`, `main_worktree`, and `main_worktree_path` in favour of `worktree_path`, `repo_path`, `repo`, and `primary_worktree_path`. Config templates migrate on load, so hooks written with the old names keep working; scripts reading the JSON, `--execute` templates, and `--var` overrides need updating. (Breaking.) ([#4080](max-sixty/worktrunk#4080))

- **`wt config plugins pi` installs for Pi; oh-my-pi moves to `wt config plugins omp`**: `pi install` wrote an oh-my-pi hook, which Pi never loads; Pi users re-run it to get a Pi extension. Existing oh-my-pi hooks keep working, listed as outdated until `wt config plugins omp install`. (Breaking: scripts that run `wt config plugins pi` for oh-my-pi need `omp`.) [Docs](https://worktrunk.dev/claude-code/#oh-my-pi) ([#4135](max-sixty/worktrunk#4135), thanks @ashebanow)

- **Interactive prompts no longer open with a blank line**: `wt config shell install`, `wt config plugins claude install`, and the commit-message setup offer in `wt merge` began with one. ([#4059](max-sixty/worktrunk#4059))

- **`wt config show` gives a single `wt config shell install` hint**: an outdated wrapper, a fish wrapper at the deprecated `conf.d` path, and missing fish completions each printed their own hint. The zsh `compinit` snippet is now syntax-highlighted. ([#4059](max-sixty/worktrunk#4059))

- **`wt config update --output <path>` confirms the write**: it now prints `✓ Wrote user config migration @ ~/migrated.toml` where it printed nothing. `--output=-` stays silent. ([#4053](max-sixty/worktrunk#4053))

### Fixed

- **Removal no longer discards untracked files hidden by `status.showUntrackedFiles = no`**: under that setting, a worktree holding only untracked files looked clean, so `wt remove`, `wt merge`, and `wt step prune` removed it without `--force`. Safety checks now always count untracked files, and auto-staging warnings list every file they stage. ([#4111](max-sixty/worktrunk#4111), thanks @Duang777)

- **`wt remove` and `wt merge` check the right worktree under an inherited `GIT_DIR`**: run from a `!wt` git alias or a git hook, which pass `GIT_DIR` down, `wt remove` could delete a dirty worktree without `--force`, and `wt merge` could refuse a clean merge. Both now check the worktree they act on. ([#4082](max-sixty/worktrunk#4082), thanks @Duang777)

- **`wt merge` no longer deletes a worktree locked with `git worktree lock`**: the merge completes and prints `Worktree preserved (locked)`. Every Worktrunk removal refuses a locked worktree, even with `--force`; run `git worktree unlock <path>` first. ([#4073](max-sixty/worktrunk#4073), thanks @Duang777)

- **`wt config update` no longer overwrites a config edited while its prompt is open**: it wrote the pre-prompt snapshot over the newer file and reported success. It now fails with the path and leaves the newer file; re-running previews the current contents. ([#4127](max-sixty/worktrunk#4127), thanks @zach-hammad-vs for reporting)

- **`wt step prune` no longer deletes a branch created minutes ago from an older commit**: `--min-age` aged a branch without a worktree by its commit's date, so a new branch off a day-old commit was pruned on the next run. Age now comes from the branch's oldest reflog entry. ([#4077](max-sixty/worktrunk#4077))

- **A comment or blank line above an inline config section no longer breaks the config**: a save or migration that rewrote `commit = { … }` as `[commit]` put that line inside the brackets. `wt switch`, `wt merge`, `wt remove`, and several `wt step` commands then failed with `Failed to load config`; `wt list` warned and ran without the config. Saves also dropped unrecognized keys from inline sections. ([#4120](max-sixty/worktrunk#4120), thanks @zach-hammad-vs for reporting)

- **Config saves keep the trailing comment on a value they rewrite**: a save such as answering the commit-generation offer dropped the comment after each value it rewrote, including one after an inline section's closing brace. ([#4138](max-sixty/worktrunk#4138))

- **Ignored project-config keys warn from every worktree**: an unknown key in `.config/wt.toml`, or one that belongs in user config such as `[merge]`, warned only in the main worktree, so `wt merge` from a linked worktree ignored it silently. ([#4145](max-sixty/worktrunk#4145), thanks @ee-prog for reporting)

- **`wt merge` skips `post-commit` when it removes that hook's worktree**: before, the hook ran in the primary worktree when the removed one sat inside the repository, and otherwise didn't run. The merge now prints `▲ Skipped post-commit`; move work that must finish there to `pre-remove`. ([#4049](max-sixty/worktrunk#4049))

- **`wt switch` recovers from a removed worktree in a bare repository**: `wt switch` and the picker surfaced git's raw `fatal: Unable to read current working directory` instead, and the removed-directory message lacked `wt switch ^`. ([#4067](max-sixty/worktrunk#4067))

- **`wt config shell install fish` puts the wrapper where fish reads it under a custom `$XDG_CONFIG_HOME`**: the wrapper always went to `~/.config/fish/functions/`, so install reported success while `wt switch` changed no directory. On Windows, the fish completion moves from `%APPDATA%\fish\completions` to the wrapper's directory. ([#4107](max-sixty/worktrunk#4107))

- **`wt config shell install zsh` honours `$ZDOTDIR` only when it is absolute**: an empty or relative value resolved against the current directory, so install appended to a `.zshrc` under the current directory and reported success while the file zsh reads went untouched. A non-absolute value now falls back to `$HOME`. ([#4085](max-sixty/worktrunk#4085))

- **`wt config shell install` for Nushell no longer deletes a `wt.nu` under the current directory**: an empty or relative `$XDG_CONFIG_HOME` resolved against it, so install removed a `nushell/vendor/autoload/wt.nu` beneath it unread, as a stale wrapper. It now falls back to `~/.config`, which also fixes unread `tea` logins that let `wt switch pr:<n>` treat a Gitea host as GitHub. ([#4104](max-sixty/worktrunk#4104))

- **`wt switch --create` names the branch a failed worktree add leaves behind**: `git worktree add -b` writes the branch ref before populating the worktree, so a failure in between left the branch with no worktree, and the next attempt reported a name collision. The error now says how to delete or reuse it. ([#4109](max-sixty/worktrunk#4109), thanks @technicalpickles for reporting)

- **`wt config shell install` no longer tells an already-wrapped shell to restart**: reinstalling from a shell with the wrapper loaded, such as after a version bump, printed `↳ Restart shell to activate shell integration`. ([#4059](max-sixty/worktrunk#4059))

- **`wt config shell install` migrates a deprecated `conf.d` fish wrapper when `~/.config/fish/functions` is missing**: before, only `wt config shell install fish` migrated it. `wt config show` now reports that wrapper even when fish isn't on `PATH`. ([#4059](max-sixty/worktrunk#4059))

- **Plugin status and uninstall checks ask the agent CLIs**: `wt config show` could list an installed Claude Code plugin or Gemini CLI extension as not installed, and `wt config plugins claude|codex uninstall` could report success over a marketplace still configured. A repeat Claude uninstall now runs both removals instead of stopping at `Plugin not installed`. ([#4048](max-sixty/worktrunk#4048), [#4054](max-sixty/worktrunk#4054))

- **`wt config plugins opencode install` no longer writes the plugin into the current directory**: with `OPENCODE_CONFIG_DIR` set but empty, it wrote `plugins/worktrunk.ts` there, typically inside a repository, reporting success though OpenCode never saw it. An empty value now counts as unset. ([#4084](max-sixty/worktrunk#4084))

- **The OpenCode plugin clears its activity marker when OpenCode 1 disposes it**: only explicit session deletion cleared it, so a finished session kept its `💬` and `wt list` showed it as active until `wt config state marker clear` was run by hand. ([#4129](max-sixty/worktrunk#4129), thanks @drewdas for reporting)

- **`wt config update` migrates `[ci] platform` into a `[forge]` section that only sets `hostname`**: that config, common with GitHub Enterprise and self-hosted GitLab, kept the deprecated key with no deprecation warning. ([#4061](max-sixty/worktrunk#4061))

- **Deprecated keys in an inline `[projects]` entry now migrate**: `"example.com/org/repo" = { merge = { no-ff = true } }` skipped the migration the section form got, so the per-project setting was ignored. ([#4122](max-sixty/worktrunk#4122), thanks @zach-hammad-vs for reporting)

- **A deprecated config section the migration can't rewrite now warns**: `select = "not a table"`, or a `[select]` whose `[switch.picker]` destination is already set, was ignored without a message. It now reports `unknown field select (will be ignored)`. ([#4121](max-sixty/worktrunk#4121), thanks @zach-hammad-vs for reporting)

- **`wt config update` no longer changes what a template renders**: it could rename `{{ repo_root }}` inside a quoted s

See merge request: Harmonybrew/homebrew-core!20435
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants