Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

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

DDL48626f2df936
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 17f820862..18ec95fc3 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -14,6 +14,8 @@
- **`wt step prune` no longer deletes a branch created minutes ago from an older commit**: the min-age guard aged a branch with no worktree by the committer date of the commit it points at, so `git branch <name> main` on a default branch whose last commit was over a day old was pruned on the next run — the case `--min-age` exists to prevent. The branch's age now comes from its oldest reflog entry, written when the branch was created.
+- **`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. ([#4073](https://github.com/max-sixty/worktrunk/pull/4073), thanks @Duang777)
+
- **`wt config update` migrates `[ci] platform` into a `[forge]` section that only sets `hostname`**: the migration stood down whenever a `[forge]` section existed at all, so the config a GitHub Enterprise or self-hosted GitLab user ends up with — `[ci] platform` from before the rename, `[forge] hostname` added later for an SSH host alias — kept the deprecated key with no warning and nothing `wt config update` would do about it. The platform still resolved, so nothing broke; the deprecation notice that precedes `[ci]`'s eventual removal simply never arrived. A `[forge]` that already sets `platform`, or a `forge` that isn't a section, still stands down.
- **`wt config shell install` migrates a fish wrapper at the deprecated `conf.d` path even when `~/.config/fish/functions` doesn't exist yet**: fish was skipped for want of a config location, so the bare command left the deprecated wrapper running and only `wt config shell install fish` migrated it. A worktrunk wrapper at the old path now counts as fish being configured, just at the old path. `wt config show` reports that wrapper too, where before it showed nothing at all for fish unless fish was on `PATH`.
diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.md
index fd9039f49..4ac9ebed4 100644
--- a/docs/src/content/docs/faq.md
+++ b/docs/src/content/docs/faq.md
@@ -196,7 +196,7 @@ To protect a worktree from removal entirely (say it holds a local database), loc
git worktree lock ../myproject.feature-auth --reason "Contains local database"
```
-Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor `wt remove` (even with `--force`) will delete them. Unlock with `git worktree unlock`.
+Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor any Worktrunk removal path — `wt remove` or `wt merge` — will delete them, even with `--force`. Unlock with `git worktree unlock`.
### Branch deletion
diff --git a/docs/src/content/docs/merge.md b/docs/src/content/docs/merge.md
index 6ec75f9c3..33f1afb96 100644
--- a/docs/src/content/docs/merge.md
+++ b/docs/src/content/docs/merge.md
@@ -83,7 +83,7 @@ $ wt merge --no-commit --no-rebase
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
5. **Merge** — Fast-forward merge to the target branch ([`wt step push`](/step/#wt-step-push)). With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.
-7. **Cleanup** — 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.
+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. **Post-remove + post-merge hooks** — Run in background after cleanup.
Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.md
index 011546c03..a4cb371ff 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md
@@ -192,7 +192,7 @@ To protect a worktree from removal entirely (say it holds a local database), loc
git worktree lock ../myproject.feature-auth --reason "Contains local database"
```
-Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor `wt remove` (even with `--force`) will delete them. Unlock with `git worktree unlock`.
+Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor any Worktrunk removal path — `wt remove` or `wt merge` — will delete them, even with `--force`. Unlock with `git worktree unlock`.
### Branch deletion
diff --git a/plugins/worktrunk/skills/worktrunk/reference/merge.md b/plugins/worktrunk/skills/worktrunk/reference/merge.md
index 38320323a..37d505f0d 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/merge.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/merge.md
@@ -69,7 +69,7 @@ $ wt merge --no-commit --no-rebase
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).
5. **Merge** — Fast-forward merge to the target branch ([`wt step push`](https://worktrunk.dev/step/#wt-step-push)). With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.
-7. **Cleanup** — 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.
+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. **Post-remove + post-merge hooks** — Run in background after cleanup.
Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 011546c03..a4cb371ff 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -192,7 +192,7 @@ To protect a worktree from removal entirely (say it holds a local database), loc
git worktree lock ../myproject.feature-auth --reason "Contains local database"
```
-Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor `wt remove` (even with `--force`) will delete them. Unlock with `git worktree unlock`.
+Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor any Worktrunk removal path — `wt remove` or `wt merge` — will delete them, even with `--force`. Unlock with `git worktree unlock`.
### Branch deletion
diff --git a/skills/worktrunk/reference/merge.md b/skills/worktrunk/reference/merge.md
index 38320323a..37d505f0d 100644
--- a/skills/worktrunk/reference/merge.md
+++ b/skills/worktrunk/reference/merge.md
@@ -69,7 +69,7 @@ $ wt merge --no-commit --no-rebase
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).
5. **Merge** — Fast-forward merge to the target branch ([`wt step push`](https://worktrunk.dev/step/#wt-step-push)). With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.
-7. **Cleanup** — 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.
+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. **Post-remove + post-merge hooks** — Run in background after cleanup.
Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 49ba3019e..69e38314a 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1493,7 +1493,7 @@ $ wt merge --no-commit --no-rebase
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
5. **Merge** — Fast-forward merge to the target branch ([`wt step push`](/step/#wt-step-push)). With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.
-7. **Cleanup** — 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.
+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. **Post-remove + post-merge hooks** — Run in background after cleanup.
Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index d61c4bb0a..96bf5a8a0 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -7,10 +7,11 @@
//! 1. Capture the feature worktree's path + commit BEFORE removal — afterward
//! the worktree directory is gone, but post-merge hooks still need to
//! reference it via Active template overrides.
-//! 2. Decide whether to remove the feature worktree. Four conditions block
-//! removal: `--no-remove`, on-target, primary-worktree, and default-branch.
-//! Otherwise `ensure_clean` gates removal and `handle_remove_output`
-//! performs it (sharing the same code path as `wt remove`).
+//! 2. Decide whether to remove the feature worktree. Five conditions block
+//! removal: `--no-remove`, on-target, primary-worktree, locked, and
+//! default-branch. Otherwise `ensure_clean` gates removal and
+//! `handle_remove_output` performs it (sharing the same code path as
+//! `wt remove`).
//! 3. Register the post-merge hook with the announcer. The caller owns
//! `flush()` because it's a command-level lifecycle operation, not part of
//! the finish sequence.
@@ -124,6 +125,17 @@ pub fn finish_after_merge(
} else if is_primary_worktree(repo)? {
eprintln!("{}", info_message("Worktree preserved (primary worktree)"));
false
+ } else if let Some(reason) = repo.current_worktree().lock_reason()? {
+ // `git worktree lock` is "don't remove this", not "don't merge".
+ // Merge already succeeded; skip cleanup the same way `--no-remove`
+ // and primary-worktree do. `stage_worktree_removal` also refuses a
+ // lock, so a path that skips this check still cannot trash the dir.
+ let msg = match reason {
+ Some(r) => format!("Worktree preserved (locked: {r})"),
+ None => "Worktree preserved (locked)".to_string(),
+ };
+ eprintln!("{}", info_message(msg));
+ false
} else {
// Phase 3: reject removing default branch (merge always uses SafeDelete).
check_not_default_branch(repo, current_branch, &BranchDeletionMode::SafeDelete)?;
diff --git a/src/git/remove.rs b/src/git/remove.rs
index 7f0c555a6..117a17158 100644
--- a/src/git/remove.rs
+++ b/src/git/remove.rs
@@ -23,9 +23,11 @@
//! Steps 1-3 are [`stage_worktree_removal`]; 4-5 are the rest of
//! [`remove_worktree_with_cleanup`].
//!
-//! 1. **Clean check** (skipped with [`RemoveOptions::force_worktree`]). The
-//! final dirty-worktree gate, immediately before the mutation. Why it
-//! precedes the stop below: [`stage_worktree_removal`], "Why this order".
+//! 1. **Lock and clean checks**. A `git worktree lock` is refused
+//! unconditionally (matching `git worktree remove`; `--force` does not
+//! override it). The dirty-worktree gate is skipped with
+//! [`RemoveOptions::force_worktree`]. Why the dirty gate precedes the
+//! stop below: [`stage_worktree_removal`], "Why this order".
//! 2. **fsmonitor daemon stopped** (best effort). [`stop_fsmonitor_daemon`]
//! runs against the target worktree before its path disappears: it sends
//! the graceful `git fsmonitor--daemon stop` IPC request, then verifies the
@@ -98,7 +100,7 @@ use std::path::{Path, PathBuf};
use std::time::Duration;
use crate::git::repository::WorkingTree;
-use crate::git::{IntegrationReason, Repository, WorktreeInfo};
+use crate::git::{GitError, IntegrationReason, Repository, WorktreeInfo, path_dir_name};
use crate::shell_exec::Cmd;
use crate::utils::epoch_now;
@@ -436,7 +438,11 @@ pub fn remove_worktree_with_cleanup(
/// hint leading straight to the deletion the check refuses. And `--force` is
/// the user waiving their own uncommitted changes, never a claim about who
/// owns the directory, so it cannot be allowed to skip it; git's own
-/// validation is likewise unconditional.
+/// validation is likewise unconditional. The lock check sits with ownership:
+/// `--force` does not override `git worktree lock`, and the check reads the
+/// `locked` file rather than `list_worktrees()`, whose `RepoCache` entry
+/// planning already warmed: it would answer from before the approval prompt
+/// and the `pre-remove` hook, which is the window this call closes.
///
/// `wt remove` and `wt merge --remove` have already asked this during
/// planning, where the answer can precede the "Removing …" announcement. The
@@ -446,21 +452,37 @@ pub fn remove_worktree_with_cleanup(
///
/// # Errors
///
-/// The ownership check and the dirty-worktree gate error. A failed rename is
-/// reported as `None`, not an error, and the daemon stop is best-effort
-/// throughout.
+/// The ownership check, the lock check, and the dirty-worktree gate error. A
+/// failed rename is reported as `None`, not an error, and the daemon stop is
+/// best-effort throughout.
pub fn stage_worktree_removal(
repo: &Repository,
worktree_path: &Path,
branch: Option<&str>,
force_worktree: bool,
) -> anyhow::Result<Option<PathBuf>> {
- repo.worktree_at(worktree_path)
- .ensure_holds_this_worktree()?;
+ let worktree = repo.worktree_at(worktree_path);
+ worktree.ensure_holds_this_worktree()?;
+
+ // Lock is the user's explicit "don't remove this". `--force` does not
+ // override it, matching `git worktree remove` and `prepare_worktree_removal`.
+ // Read the `locked` file rather than `list_worktrees()`: its `RepoCache`
+ // entry is already warm from planning, so it would report the lock state
+ // from before the approval prompt and the `pre-remove` hook.
+ if let Some(reason) = worktree.lock_reason()? {
+ let name = branch
+ .unwrap_or_else(|| path_dir_name(worktree_path))
+ .to_string();
+ return Err(GitError::WorktreeLocked {
+ branch: name,
+ path: worktree_path.to_path_buf(),
+ reason,
+ }
+ .into());
+ }
if !force_worktree {
- repo.worktree_at(worktree_path)
- .ensure_clean("remove worktree", branch, true)?;
+ worktree.ensure_clean("remove worktree", branch, true)?;
}
stop_fsmonitor_daemon(&repo.worktree_at(worktree_path));
@@ -478,7 +500,7 @@ pub fn stage_worktree_removal(
/// ([`prune_worktree_entry`](Repository::prune_worktree_entry)) rather than
/// sweeping the repository, so a sibling worktree whose directory happens to
/// be absent right now keeps its registration. A locked worktree never reaches
-/// here — `prepare_worktree_removal` rejects one before staging.
+/// here — [`stage_worktree_removal`] rejects one before the rename.
fn rename_into_trash(repo: &Repository, worktree_path: &Path) -> Option<PathBuf> {
let trash_dir = repo.wt_trash_dir();
let _ = std::fs::create_dir_all(&trash_dir);
@@ -703,6 +725,47 @@ mod tests {
use super::*;
use crate::testing::TestRepo;
+ /// A `git worktree lock` must stop the rename even when the caller skipped
+ /// `prepare_worktree_removal` (merge used to construct a plan by hand).
+ #[test]
+ fn stage_refuses_locked_worktree() {
+ let mut test = TestRepo::with_initial_commit();
+ let worktree_path = test.add_worktree("feature");
+ test.lock_worktree("feature", Some("keep"));
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let err =
+ stage_worktree_removal(&repo, &worktree_path, Some("feature"), false).unwrap_err();
+ assert!(
+ matches!(
+ err.downcast_ref::<GitError>(),
+ Some(GitError::WorktreeLocked { branch, reason, .. })
+ if branch == "feature" && reason.as_deref() == Some("keep")
+ ),
+ "expected WorktreeLocked, got {err:?}"
+ );
+ assert!(
+ worktree_path.exists(),
+ "locked worktree must still be on disk"
+ );
+ }
+
+ /// `--force` waives dirt, not a lock — same as `git worktree remove --force`.
+ #[test]
+ fn stage_refuses_locked_worktree_even_with_force() {
+ let mut test = TestRepo::with_initial_commit();
+ let worktree_path = test.add_worktree("feature");
+ test.lock_worktree("feature", None);
+ let repo = Repository::at(test.root_path()).unwrap();
+
+ let err = stage_worktree_removal(&repo, &worktree_path, Some("feature"), true).unwrap_err();
+ match err.downcast_ref::<GitError>() {
+ Some(GitError::WorktreeLocked { reason: None, .. }) => {}
+ other => panic!("expected WorktreeLocked without a reason, got {other:?}"),
+ }
+ assert!(worktree_path.exists());
+ }
+
/// Registry serialization starts after the fast-path rename, so worktree
/// staging can overlap while metadata teardown remains exclusive.
#[test]
diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rs
index 2f224734c..aaad7d696 100644
--- a/src/git/repository/working_tree.rs
+++ b/src/git/repository/working_tree.rs
@@ -585,6 +585,31 @@ impl<'a> WorkingTree<'a> {
}
}
+ /// Reason recorded by `git worktree lock`, if this worktree is locked.
+ ///
+ /// Reads the `locked` file in the worktree's git dir — the same file git
+ /// writes and `git worktree list --porcelain` reports. Goes to the file
+ /// rather than `list_worktrees()`, whose `RepoCache` entry planning may
+ /// already have warmed with a stale lock state.
+ ///
+ /// `Ok(None)` — not locked. `Ok(Some(None))` — locked with no reason.
+ /// `Ok(Some(Some(reason)))` — locked with a reason.
+ pub fn lock_reason(&self) -> anyhow::Result<Option<Option<String>>> {
+ let lock_path = self.git_dir()?.join("locked");
+ match std::fs::read_to_string(&lock_path) {
+ Ok(contents) => {
+ let trimmed = contents.trim();
+ Ok(Some(if trimmed.is_empty() {
+ None
+ } else {
+ Some(trimmed.to_string())
+ }))
+ }
+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(e) => Err(e).context("Failed to read worktree lock"),
+ }
+ }
+
/// The git operation this worktree is partway through, if any.
///
/// Reads the state files git writes under the worktree's git dir, in the
@@ -1238,6 +1263,21 @@ mod tests {
use crate::shell_exec::Cmd;
use crate::testing::TestRepo;
+ #[test]
+ fn lock_reason_errors_when_locked_is_unreadable() {
+ let mut test = TestRepo::with_initial_commit();
+ let worktree_path = test.add_worktree("feature");
+ let repo = Repository::at(test.root_path()).unwrap();
+ let worktree = repo.worktree_at(&worktree_path);
+ let lock_path = worktree.git_dir().unwrap().join("locked");
+ std::fs::create_dir(&lock_path).unwrap();
+ let err = worktree.lock_reason().unwrap_err();
+ assert!(
+ err.to_string().contains("Failed to read worktree lock"),
+ "expected a lock-file IO error, got {err:?}"
+ );
+ }
+
#[test]
fn submodule_status_empty_is_not_initialized() {
assert!(!has_initialized_submodules_from_status(""));
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 508d1c7ae..f3b942d6d 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -112,6 +112,46 @@ fn test_merge_with_no_remove_flag(merge_scenario: (TestRepo, PathBuf)) {
));
}
+/// `git worktree lock` is the user's explicit "don't remove this".
+/// `wt remove` honors it; `wt merge` used to skip that guard and trash
+/// the locked feature worktree after a successful merge.
+#[rstest]
+fn test_merge_preserves_locked_worktree(merge_scenario: (TestRepo, PathBuf)) {
+ let (repo, feature_wt) = merge_scenario;
+ repo.lock_worktree("feature", Some("agent still running"));
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "merge",
+ &["main"],
+ Some(&feature_wt)
+ ));
+
+ assert!(
+ feature_wt.exists(),
+ "locked feature worktree must survive merge"
+ );
+}
+
+/// Same preserve path as above, but `git worktree lock` with no reason.
+#[rstest]
+fn test_merge_preserves_locked_worktree_no_reason(merge_scenario: (TestRepo, PathBuf)) {
+ let (repo, feature_wt) = merge_scenario;
+ repo.lock_worktree("feature", None);
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "merge",
+ &["main"],
+ Some(&feature_wt)
+ ));
+
+ assert!(
+ feature_wt.exists(),
+ "locked feature worktree must survive merge"
+ );
+}
+
#[rstest]
fn test_merge_already_on_target(repo: TestRepo) {
// Already on main branch (repo root)
diff --git a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
index 86ed51091..515eff98d 100644
--- a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap
@@ -178,7 +178,7 @@ $ wt merge --no-commit --no-rebase
4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](/hook/).
5. **Merge** — Fast-forward merge to the target branch ([`wt step push`](/step/#wt-step-push)). With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.
-7. **Cleanup** — 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.
+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. **Post-remove + post-merge hooks** — Run in background after cleanup.
Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
index 0cdb1d264..d4cc8e07f 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
@@ -162,7 +162,7 @@ Preserve the exact clean commit graph and tip:
4. Pre-merge hooks — Hooks run after rebase, before merge. Failures abort. See wt hook.
5. Merge — Fast-forward merge to the target branch (wt step push). With --no-ff, a merge commit is created instead — semi-linear history after the default rebase, while explicit --no-rebase preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.
6. Pre-remove hooks — Hooks run before removing worktree. Failures abort.
-7. Cleanup — 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.
+7. Cleanup — Removes the worktree and branch. Use --no-remove to keep the worktree. When already on the target branch, in the primary worktree, or locked, the worktree is preserved.
8. Post-remove + post-merge hooks — Run in background after cleanup.
Use --no-commit to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless --no-rebase is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with wt step commit. Requires a clean working tree.
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree.snap b/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree.snap
new file mode 100644
index 000000000..8b4f77190
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree.snap
@@ -0,0 +1,67 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
+  * [HASH] Add feature file
+  feature.txt | 1 +
+  1 file changed, 1 insertion(+)
+✓ Merged to main (1 commit, 1 file, +1)
+○ Worktree preserved (locked: agent still running)
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree_no_reason.snap b/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree_no_reason.snap
new file mode 100644
index 000000000..d2083fa04
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__merge__merge_preserves_locked_worktree_no_reason.snap
@@ -0,0 +1,67 @@
+---
+source: tests/integration_tests/merge.rs
+info:
+ program: wt
+ args:
+ - merge
+ - main
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_ALLOW_PROTOCOL: file
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_AUTHOR_EMAIL: [email protected]
+ GIT_AUTHOR_NAME: Test User
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_EMAIL: [email protected]
+ GIT_COMMITTER_NAME: Test User
+ GIT_CONFIG_COUNT: "2"
+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig
+ GIT_CONFIG_KEY_0: user.useConfigOnly
+ GIT_CONFIG_KEY_1: rerere.enabled
+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig
+ GIT_CONFIG_VALUE_0: "true"
+ GIT_CONFIG_VALUE_1: "false"
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"
+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"
+ PATH: "[PATH]"
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"
+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
+ WORKTRUNK_TEST_PARENT_SHELL: ""
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Merging 1 commit to main @ [HASH] (no commit/squash/rebase needed)
+  * [HASH] Add feature file
+  feature.txt | 1 +
+  1 file changed, 1 insertion(+)
+✓ Merged to main (1 commit, 1 file, +1)
+○ Worktree preserved (locked)