Skip to content

feat(switch): allow opt-in navigation to branch-mismatched worktrees - #4480

Closed
BenJurewicz wants to merge 6 commits into
max-sixty:mainfrom
BenJurewicz:warn-on-worktree-path-mismatch
Closed

BenJurewicz wants to merge 6 commits into
max-sixty:mainfrom
BenJurewicz:warn-on-worktree-path-mismatch

Conversation

@BenJurewicz

Copy link
Copy Markdown
  • Add --allow-branch-mismatch to navigate to an existing worktree at the requested branch’s expected path, even when it contains another branch or a detached checkout. Warn without changing the checkout.
  • Add switch.allow-branch-mismatch, disabled by default, and --no-allow-branch-mismatch to override it per command.
  • Preserve branch-lookup priority and strict behavior for --create, --path, and PR/MR selectors.
  • Use the actual checkout identity for hooks, JSON output, and --execute. Refresh the worktree listing after pre-switch hooks and reject a fallback whose branch or registration changed.
  • Update command help, configuration examples, generated documentation, and regression coverage.

TLDR: Allow for switching to a worktree with a mismatched branch

Add the opt-in switch.allow-branch-mismatch setting with a false default.
Preserve explicit false values when project settings override global
configuration.

Validation at this commit on Linux aarch64: all six switch configuration
unit tests pass (cargo test --locked --lib test_switch_config).
Add paired branch-mismatch flags and honor the switch configuration
preference. Navigate to a usable occupying worktree without changing
its checkout, and use its actual branch for hooks, JSON, and execution.
Keep creation, explicit placement, and PR/MR selection strict.

Include the generated command help and documentation for the flags.

Validation at this commit on Linux aarch64: 255 existing switch tests,
56 help tests, and documentation sync pass, using cargo test --locked
--features shell-integration-tests --test integration with the
integration_tests::switch::, test_help, and test_docs_are_in_sync filters.
Cover command-line and configuration enablement, explicit overrides,
detached checkout navigation, warning output, and hook context.
Assert that navigation preserves the checkout and untracked files.

Validation at this commit on Linux aarch64: all seven branch-mismatch
integration cases pass (cargo test --locked --features
shell-integration-tests --test integration branch_mismatch).
Describe expected-path fallback, configuration enablement, and the
per-command override. Document branch lookup priority and the creation,
placement, and PR/MR exclusions. Update generated guides and examples.

Validation at this commit on Linux aarch64: documentation sync, user
config example sync, and all 56 help tests pass, using cargo test --locked
--features shell-integration-tests --test integration with the
test_docs_are_in_sync, test_config_source_generates_example_toml, and
test_help filters.
Reload the worktree listing after opt-in selection so pre-switch hooks can create a destination without leaving planning on a stale inventory. Preserve the destination commit identity for detached fallback hooks.

Cover hook mutations and failures, branch priority, strict creation and PR selection, unusable registrations, ordinary directories, default-branch navigation, and the parent-shell directory change.

Validation on Linux aarch64: 5,342 tests pass, with one skipped. Formatting, all-target/all-feature Clippy, doctests, documentation sync, and the Rust documentation build pass.

@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.

This adds a CLI flag pair and a switch.allow-branch-mismatch config key. AGENTS.md ("Project Status") calls both product decisions and protected interfaces once released, so @max-sixty should decide whether to ship them. I'm leaving this as a comment rather than an approval.

The capability is mostly available already. wt switch resolves a worktree's path as a selector, including detached and other-branch checkouts (wt switch ../repo.feature), and the picker can select those rows too. The occupied-path error already names that path. If the goal is to shorten the recovery from that error, a smaller change would be to add wt switch <path> to the WorktreePathOccupied hint, which today suggests only cd <path> && git switch <branch>. This PR instead adds about 150 lines to the switch pipeline: a second target resolution before hooks, a rebuilt Repository for planning, and a post-hook identity check. That is a lot of new state for a case one hint line could cover.

The config default also changes what wt switch feature -x '<cmd>' means. With it on, the command runs on whatever branch occupies feature's template path, and only a warning on stderr signals the difference. Scripts and agents that pass a branch name usually assume {{ branch }} is that branch. A per-invocation flag keeps that choice explicit. A persistent default makes it apply silently.

One correctness gap: once a mismatch is selected, plan_switch returns SwitchPlan::Existing before it resolves the branch again, and require_unchanged checks only the occupant. If a pre-switch hook creates a worktree for the requested branch elsewhere, the switch still goes to the mismatched checkout. That contradicts the documented "branch lookup still takes priority" behavior. It is narrow, but the comment above planning_repo says hooks "may create a destination", and the mismatch path never looks for one.

Resolve the requested branch against the refreshed worktree listing before using an expected-path fallback. A worktree created for that branch by a pre-switch hook takes priority. Emit the mismatch warning only when the fallback is selected.

Cover branch priority both before and during pre-switch hooks, including the selected branch, path, and absence of a fallback warning.

Validation on Linux aarch64: 5,343 tests pass, with one skipped, using RUSTFLAGS="-D warnings" cargo nextest run --locked --all-features --no-fail-fast. Formatting, all-target/all-feature Clippy with warnings denied, and doctests pass.
@BenJurewicz

Copy link
Copy Markdown
Author

Changed it such that if a pre-switch hook creates a worktree somewhere else, that worktree is picked instead

@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.

Moving the fallback after branch resolution closes the hook-created-destination gap, and the during_hook case pins it. The warning now prints only when the fallback is actually used. Whether to ship the flag and config key is still up to @max-sixty, as noted in the earlier review.

@BenJurewicz

BenJurewicz commented Oct 15, 2026 •

Copy link
Copy Markdown
Author

FYI Reasoning for the feature:

I use worktrunk manually to be able to work on or review multiple branches at the same time.
Sometimes I will switch branches in one of the worktrees and then returning to it breaks my flow, since a simple wt switch branch-name stops working and instead I have to cd manually.

For that reason I wanted to add a config flag that will switch me to that worktree and then notify me that the branch is wrong

CLI flags are mostly for being able to overwrite config in scripts or be able to test it quickly.

The feature is disabled by default so there is no impact on users who do not need such a feature or use worktrunk only through their AI agents.
I agree that the current default behavior of erroring with a helpful cd ... && git switch ... command is a better default for AI agents, but I think this is a better default for humans.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Thanks, that use case explains the config key. Coming back to a worktree you've moved to another branch is a real gap, because wt switch <branch> is what you'd naturally reach for.

One thing to weigh on "no impact on users who only use worktrunk through AI agents": switch.allow-branch-mismatch lives in user config, so it also applies to agents running as the same user. A person who turns it on for themselves changes what their agent's wt switch feature -x '<cmd>' lands on. The warning goes to stderr, and the agent may not notice it. The default protects users who never enable the key, but not the agent sessions of someone who does. The flag pair doesn't have this problem, since each invocation opts in.

Whether that tradeoff is worth it is still @max-sixty's call.

@max-sixty

Copy link
Copy Markdown
Owner

worktrunk support branches and paths, so we should use one of those; not a "worktree that resolves under a different branch name based on the default path".

lmk if I'm misunderstanding.

the API is intentionally closely curated so we're very careful about adding new flags

@BenJurewicz

Copy link
Copy Markdown
Author

worktrunk support branches and paths, so we should use one of those; not a "worktree that resolves under a different branch name based on the default path".

lmk if I'm misunderstanding.

the API is intentionally closely curated so we're very careful about adding new flags

What would be your suggestion in solving my issue?
I'd like to have a way that allows me to move between worktrees without having to remember their full/relative paths and at the same time not being blocked by the fact that a worktree contains a incorrect branch.

Changing a error to a warning seemed the simplest to me and thats the path that I chose, but I'm interested in hearing your suggestion.
Currently I am using this branch, but I'd prefer to upstream my work so that I do not have to continuously fix my branch to work with changes upstream.

My proposition would be to change the error to a error with a conformation of something like "do you want to go to that worktree nonetheless? [y/N]" and maybe a option to change if the default is yes or no. Then agents using it with without a interactive tty would just get the error, while humans would get the same message but instead of being asked to type the cd manually, they could just press y.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

One thing that may already cover most of this without a new flag: the error names the branch the worktree is on now, and wt switch <that-branch> takes you there, because branch lookup checks every worktree, not just the expected path. For example, if repo.feature has been switched to other, wt switch feature errors with ... at the expected path .../repo.feature on branch other, and wt switch other then lands in repo.feature. Running wt switch with no argument opens the picker, which lists every worktree, so you can pick it there without knowing its branch or path.

Whether the error should also offer a [y/N] prompt on a TTY is @max-sixty's call.

@BenJurewicz

Copy link
Copy Markdown
Author

I'd prefer a way that does not require another command.

If you think that there is no way to achieve what I want in a upstremable way, then as long as this error is reported in a script friendly way, I could probably have a simple bash wrapper that achieves my desired functionality.

@max-sixty

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Today the error isn't script-friendly. It exits 1, prints only prose on stderr, and --format=json writes nothing to stdout, so a wrapper can't tell it apart from other failures without parsing the message.

A wrapper doesn't need the error, though. It can compute the expected path itself with wt step eval and then switch by path, which already works for a worktree on another branch. With the default worktree-path template:

wts() {
  wt switch "$@" && return
  local rc=$? p
  p=$(wt step eval "{{ repo_path }}/../{{ repo }}.{{ \"$1\" | sanitize }}") || return "$rc"
  [ -d "$p" ] || return "$rc"
  wt switch "$p"
}

If you've set a custom template, put it in that step eval string. I tested this in a scratch repo with repo.feature switched to other. wts feature prints the occupied-path error and then lands in repo.feature with exit 0. wts nosuch still fails with No branch named nosuch, because no directory exists at its expected path. One thing to know: the fallback runs after any failure for a branch whose expected path exists, not only after the occupied-path error. A hook failure on a normal switch would also send you to that directory.

@max-sixty

Copy link
Copy Markdown
Owner

@BenJurewicz very reasonable!

@worktrunk-bot can we think about to make this scriptable?

for example, is there a command to generate the expected path? then it might be easily scriptable, if we can set the path to switch to successfully

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Not today. Switching by path already works for a worktree on another branch: wt switch ../repo.feature lands there. The missing piece is getting the expected path for a branch. The closest existing tool is worktree_path_of_branch() in templates, but it returns where the branch is checked out, so it's empty in exactly this case. The wt step eval wrapper above works only because it repeats the worktree-path template by hand, so it breaks for anyone with a custom or per-project template.

Two small ways to close that gap without a new switch flag or config key:

  1. A template function that renders the configured path for a branch, e.g. {{ default_worktree_path("feature") }} (the name is a placeholder). It would reuse compute_worktree_path, the function wt switch itself uses, so it picks up custom and per-project templates and the default branch's location automatically. It sits next to worktree_path_of_branch in expansion.rs. The wrapper then becomes:

    wts() {
      wt switch "$@" && return
      local rc=$? p
      p=$(wt step eval "{{ default_worktree_path('$1') }}") || return "$rc"
      [ -d "$p" ] && wt switch "$p" || return "$rc"
    }

    It's also useful outside this case, for example in hooks or scripts that need to know where wt switch --create will put a branch.

  2. A structured error under --format=json. Today the occupied-path error (switch.rs) prints prose only, and stdout is empty. Writing something like {"error": "worktree_path_occupied", "path": ..., "occupant": ...} to stdout would let a wrapper fall back only on this error, not on any failure (the caveat on the wrapper above). It's a bigger change: it sets a precedent for JSON errors across switch.

(1) is the smaller one, and it's enough for Ben's wrapper. I can open a PR for it if you want it.

@max-sixty

Copy link
Copy Markdown
Owner

yes let's build (1)

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Opened #4502 with this as expected_worktree_path(branch). I picked the name because "default" could read as the default branch, and "expected path" matches the occupied-path error. With it, the wrapper's lookup is wt step eval "{{ expected_worktree_path('$1') }}", and it follows custom and per-project worktree-path templates.

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