Skip to content

fix: resolve every no-argument default through @, which outside a worktree names HEAD's branch - #4521

Merged
max-sixty merged 7 commits into
mainfrom
fix/switch-at-outside-worktree
Oct 20, 2026
Merged

max-sixty merged 7 commits into
mainfrom
fix/switch-at-outside-worktree

Conversation

@max-sixty

@max-sixty max-sixty commented Oct 20, 2026 •

Copy link
Copy Markdown
Owner

Since v0.80.0, wt switch @ run outside any worktree treats the directory it runs in as a detached worktree. This happens from a bare repository's directory (or the proj/ holding proj/.git → .bare) and from a normal repository's .git directory. It prints Already on worktree for detached worktree @ <dir>, runs pre-switch hooks with no branch, and cds into the directory. v0.80.0 switched to the worktree of the branch HEAD names.

#4496 routed wt switch arguments through Repository::resolve_worktree. Its @ arm expected current_worktree().root() to fail outside a worktree, but WorkingTree::root() falls back to the cwd. @ now resolves to the registered worktree at the cwd's root and, where none is registered, falls through to the branch HEAD names, as expand_selector already reads @. The unreachable GitError::NotInWorktree is removed.

One definition of the current worktree

The no-argument forms of other commands read current_worktree().root() and .branch() directly, so "the current worktree" had a second definition, and outside every worktree the two disagreed: wt remove and wt remove @ took different code paths and gave different answers. Every no-argument default is now selector.unwrap_or("@"), so each command has one path with or without an argument:

  • wt remove with no argument goes through validate_remove_targets with ["@"]. Its separate single-target path is gone, and so is the @ guard an earlier commit on this branch added beside it.
  • CommandEnv::for_action and for_action_loading_config are deleted. wt merge, wt step commit, wt step squash (including --show-prompt / --dry-run), wt hook and wt hook show use CommandEnv::for_selector("@").
  • wt step diff resolves @ the way it resolves --branch.
  • wt step copy-ignored defaults --to to @. Run from a bare repository's directory, it used to copy ignored files into the bare repository itself (in v0.80.0 too).
  • wt config state and wt step push --no-ff use require_selected_branch("@"); Repository::require_current_branch is deleted.

Inside a worktree these commands behave as before. Repository::rooted_at keeps the invoking repository when the selected worktree is the one it was discovered in, and @ matches the worktree by path, so detached worktrees and duplicate checkouts of one branch resolve to themselves. require_selected_branch no longer names the detached worktree the user is standing in: wt config state vars set there says Cannot set variable: not on a branch (detached HEAD) with a plain git switch <branch> hint.

Behavior change outside a worktree

From a bare repository's directory or a .git directory, wt remove, wt merge, wt step commit, wt step squash, wt step diff and wt hook now act on the worktree of the branch HEAD names, where they used to treat the directory itself as a worktree. wt config state … --branch @ and --to @ act on HEAD's branch there too. For wt remove, the default-branch refusal is what guards this case: with HEAD on the default branch, wt remove and wt remove @ both refuse with Cannot remove the default branch main. It only protects HEAD's branch when the cached default branch matches HEAD. Where HEAD's branch has no worktree, the commands that need a worktree fail with Branch <name> has no worktree, and wt remove deletes the branch alone if it is integrated.

The fall-through applies only outside every work tree. Inside a work tree git doesn't have registered at that path, such as a worktree moved without git worktree repair, @ still names the directory, so wt remove there refuses with No worktree @ <dir> rather than pruning the branch's stale registration.

Verification

The release review's scripts, rerun against main, v0.80.0 and this branch, show wt switch @ from proj/, proj/.bare and repo/.git again landing in the HEAD branch's worktree, with pre-switch hooks seeing that branch and path. New or changed integration tests, each of which fails without its fix:

  • test_switch_at_outside_a_worktree_names_the_head_branch: wt switch @ from a .git directory.
  • test_bare_repo_at_from_bare_directory_names_head_branch: wt switch @ and wt step copy-ignored from a bare repository's directory.
  • test_bare_repo_remove_from_bare_directory_targets_head_branch: wt remove and wt remove @ give identical output there and refuse as default branch.
  • test_bare_repo_previews_from_bare_directory_use_head_branch: wt hook show and wt step squash --show-prompt read HEAD's branch's worktree, not the primary one.
  • test_remove_no_argument_in_moved_worktree_refuses: wt remove from a moved worktree refuses and leaves its checkout intact.
  • test_vars_set_in_detached_worktree: the detached-HEAD message for the no-argument form.

This was written by Claude Code on behalf of max-sixty

max-sixty and others added 2 commits October 19, 2026 22:26
Since #4496 (0c75655), `wt switch` resolves its argument through
`Repository::resolve_worktree`. Its `@` arm expected
`current_worktree().root()` to fail outside a worktree, but
`WorkingTree::root()` falls back to the cwd itself. From a bare
repository's directory, or from a normal repository's `.git` directory,
`@` therefore resolved to that directory as a detached worktree:
`wt switch @` reported "Already on worktree for detached worktree",
ran pre-switch hooks with no branch, and cd'd into the directory.
v0.80.0 switched to the worktree of the branch HEAD names.

`@` now resolves to the registered worktree at the cwd's root, and,
where none is registered, falls through to the branch HEAD names, which
is how `expand_selector` already reads `@`. The `GitError::NotInWorktree`
error the old arm mapped to was unreachable and is removed.

`wt step copy-ignored` without `--to` used `root()` the same way, so
from a bare repository's directory it copied ignored files into the
bare repository itself. Its destination now defaults to `@`.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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.

Run outside every worktree, wt remove @ and wt remove with no argument now give different answers. The no-argument form still fails with "Worktree not found at

". @ falls through to the branch HEAD names and removes that branch's worktree and branch. The PR body names this change. I'm holding the approval because it widens a deletion: it adds a target that wt remove used to refuse, and that target isn't the worktree the user is in.

Reproduced on this branch with a proj/.git → .bare layout, worktrees main and feature, bare HEAD set to refs/heads/feature, and wt config state default-branch set main. From proj/:

$ wt remove @ --yes --foreground
◎ Removing feature worktree...
✓ Removed feature worktree & branch (no added changes on main, ⊂)
$ wt remove --yes
✗ Failed to remove worktree
  Worktree not found at …/proj

If default-branch detection runs uncached, it infers feature from HEAD and refuses ("Cannot remove the default branch feature"). So the default-branch refusal only protects HEAD's branch when the configured default branch and HEAD agree.

The fall-through makes sense for switch and copy-ignored, since both just need a destination. For remove, "Prefer a clear failure" (AGENTS.md → Data Safety) argues for keeping @ an error when the cwd isn't a worktree, as the no-argument form already does. One way to do that is to keep resolve_worktree's @ arm path-only for removal, either through a flag or a remove-side check that @ matched a registered worktree, and let the other callers fall through. Whether wt remove @ from a bare directory should remove anything is a product call for you.

Outside a worktree `@` now resolves to the branch HEAD names, which suits
switch and copy-ignored but would let `wt remove @` from a bare repo's
directory remove that branch's worktree. Removal acts only on the worktree
the user is in, so refuse as the no-argument form does.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
worktrunk-bot
worktrunk-bot previously approved these changes Oct 20, 2026
@max-sixty

Copy link
Copy Markdown
Owner Author

prints "Already on worktree for detached worktree @

", runs

I don't understand these line breaks in the quotes?

then: explain why wt remove @ is different from wt remove? I worry we've made a mistake prior

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Line breaks: the body has <dir> bare in prose (e.g. "Already on worktree for detached worktree @ <dir>", "Worktree not found at <dir>"). GitHub reads <dir> as the obsolete HTML <dir> element, a block-level list, so it breaks the line and swallows the text. Wrapping the messages in backticks, or writing &lt;dir&gt;, fixes it.

wt remove @ vs wt remove: in the current head they behave the same, and the difference is only in which code path gets there. That split has been there since before this PR, which may be the mistake you mean:

  • No argument (remove.rs:470) never resolves a selector. It removes RemoveTarget::WorktreePath(current_worktree().root()), and prepare_worktree_removal fails with Worktree not found at <dir> when no registered worktree is at that path.
  • @ goes through validate_remove_targets → resolve_worktree. On main that worked out the same, because @ resolved to Worktree { path: cwd } and hit the same lookup. This PR lets @ fall through to HEAD's branch outside a worktree, so removal needed its own guard (remove.rs:178) to avoid removing a worktree the user isn't in. That's the case my earlier review flagged.

The guard works, but it rebuilds the no-argument behavior next to it, with a different message (No worktree @ <dir> vs Worktree not found at <dir>). A tighter version: in validate_remove_targets, map @ straight to RemoveTarget::WorktreePath(current_worktree.clone()), the exact target the no-argument form uses, and skip resolve_worktree for it. Then the two forms share one target by construction. The guard, its list_worktrees scan, and the message difference go away, and inside a worktree nothing changes, since resolve_worktree("@") already returns Worktree { path: root } there. Pushing that is your call, since this is your branch.

@max-sixty

Copy link
Copy Markdown
Owner Author

we want to map @ to HEAD.

but why not map to arg to HEAD too?

think of ways of addressing this at a deeper, broader level, so we reduce the number of code paths, canonicalize, etc

@worktrunk-bot
worktrunk-bot dismissed their stale review October 20, 2026 08:02

The maintainer has since asked whether no-argument removal should map to HEAD too, and for a deeper rework of the code paths. The approved head refuses that case, so the design is open again.

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Agreed, no argument should mean @. The root cause sits under both forms: outside a work tree, WorkingTree::root() returns the cwd as if it were a worktree root, while current_worktree().branch() returns the branch HEAD names. So "current" has two definitions there, a fake path and a real branch, and each command picks one. This PR fixed that for @ in resolve_worktree. Every no-argument default still reads root() directly.

A broader shape, in three parts:

  1. One definition of "current". resolve_worktree("@") is the only resolver of "the worktree I mean". Inside a registered worktree it's that worktree, and outside every worktree it's HEAD's branch. Any no-argument default becomes selector.unwrap_or("@"), so a command has one path whether or not it gets an argument.
  2. Collapse the paired call sites. Each of these keeps a separate no-argument path today:
    • wt remove: remove.rs:470 builds WorktreePath(root()) by hand. With branches = ["@"] it goes through validate_remove_targets like any argument, and the @ guard added at remove.rs:178 gets deleted rather than mirrored.
    • CommandEnv::for_action / for_action_loading_config (context.rs:33) become for_selector("@"). That covers wt merge, wt step commit, wt step squash and wt hook. The Some(b) => for_selector(b), None => for_action() matches in merge.rs:167 and commit.rs:70 go away.
    • wt step diff (diff.rs:29) has the same pair.
    • wt config state: 11 None => require_current_branch(...) arms next to Some(b) => require_selected_branch(b, ...) become require_selected_branch(branch.unwrap_or("@"), ...). These already agree outside a worktree, because both read HEAD's branch, so this is just less code.
    • copy-ignored --to is already done in this PR. wt step promote keeps its ^ default from the main worktree, which is a deliberate product rule.
  3. Make the fake path unrepresentable. Once those callers are gone, the cwd fallback in root() only serves callers that need a directory to run git in: CI-status lookups, config loading, the picker. Splitting it into a root() that errors outside a work tree and a separately named root_or_cwd() for those callers means a new command can't treat the bare directory as a worktree by accident. That's how both this bug and the copy-ignored one got in.

The behavior change, so it's a deliberate choice: from a bare repo's directory or a .git directory, wt remove, wt merge, wt step commit and wt hook would all act on the worktree of the branch HEAD names, where today they work on the cwd as if it were a worktree. For wt remove, the default-branch refusal still applies. As my earlier review noted, though, it only protects HEAD's branch when the cached default branch matches HEAD.

Parts 1 and 2 would fit in this PR as one more commit, and part 3 is a natural follow-up. I can push either if you'd like. I haven't pushed anything because it's your branch.

max-sixty and others added 2 commits October 20, 2026 08:41
"The current worktree" had two definitions. `resolve_worktree("@")` reads
the registered worktree at the cwd, else the branch HEAD names, while the
no-argument forms read `current_worktree().root()` and `.branch()`
directly. Outside every worktree, `root()` falls back to the cwd, so the
two disagreed: `wt remove @` and `wt remove` took different paths and gave
different answers from a bare repository's directory.

Every no-argument default is now `selector.unwrap_or("@")`, so each command
has one path with or without an argument:

- `wt remove` with no argument goes through `validate_remove_targets` with
  `["@"]`. The single-target path and the `@` guard beside it are gone.
- `CommandEnv::for_action` and `for_action_loading_config` are deleted;
  `wt merge`, `wt step commit`, `wt step squash` (including its preview),
  `wt hook` and `wt hook show` use `for_selector("@")`.
- `wt step diff` resolves `@` like `--branch`.
- `wt config state` and `wt step push --no-ff` use
  `require_selected_branch("@")`; `require_current_branch` is deleted.

`Repository::rooted_at` keeps the invoking repository when the selected
worktree is the one it was discovered in, so inside a worktree these
commands run exactly as before. `require_selected_branch` no longer names
a detached worktree the user is standing in.

From a bare repository's directory or a `.git` directory, these commands
now act on the worktree of the branch HEAD names, where they used to treat
the directory itself as a worktree. For `wt remove`, the default-branch
refusal guards that case.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
@max-sixty max-sixty changed the title fix(switch): resolve @ outside a worktree to the branch HEAD names fix: resolve every no-argument default through @, which outside a worktree names HEAD's branch Oct 20, 2026

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

From a linked worktree that was moved without git worktree repair, wt remove with no argument now prunes that worktree's own registration. It then tries to delete the branch. The directory the user is standing in is left with a dangling .git file, so git status there fails with fatal: not a git repository. Uncommitted files stay on disk, but they're no longer in a checkout. Main refuses in the same spot with Worktree not found at <dir>.

The fall-through in resolve_worktree's @ arm (inline) causes this. It fires whenever the cwd's root isn't a registered worktree, not only when the cwd is outside a work tree. In a moved worktree, git rev-parse --show-toplevel succeeds, so the cwd is inside a work tree. @ falls through to HEAD's branch, and the inventory still has that branch at its old, missing path. wt remove then takes the stale-worktree path that wt remove <branch> uses: prune, then delete the branch if integrated. That's fine when the user names the branch, but here they meant the directory they're in.

Reproduced on this head against a main build:

$ git worktree add ../feat -b feat && mv ../feat ../moved && cd ../moved && echo dirty > u.txt
$ wt remove --yes --foreground        # main
✗ Failed to remove worktree
  Worktree not found at …/moved
$ wt remove --yes --foreground        # this PR
✗ Failed to delete branch feat
  fatal: not a git repository: (null)
$ git status
fatal: not a git repository: (null)

This widens what wt remove can delete, so I'm holding approval. Everything else in the refactor matches the PR description: the remove, hook, config-state and bare-repository integration tests pass locally (463 tests).

Comment thread src/git/repository/worktrees.rs Resolved
max-sixty and others added 2 commits October 20, 2026 09:28
The no-argument `wt remove` now shares the validated path, whose
WORKTRUNK_FIRST_OUTPUT early exit the time-to-first-output benchmark
relies on but no test reached.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
`@` fell through to HEAD's branch whenever the cwd's root wasn't a
registered worktree, including a worktree moved without `git worktree
repair`. There `wt remove` pruned the branch's stale registration and
left the cwd's checkout with a dangling .git file. Fall through only
outside every work tree; inside an unregistered one, `@` names this
directory, which holds no worktree.

Co-Authored-By: Claude Opus 5.5 (1M context) <[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.

The moved-worktree case is fixed. On this head, wt remove, wt remove @, wt merge and wt hook show all refuse with No worktree @ <dir> from an unrepaired moved worktree, and the checkout and its untracked file are left intact.

I'm still not approving, because wt remove from a bare repository's directory can now remove HEAD's branch's worktree and branch. That widens what wt remove can delete, and the repo's review guidance (.claude/skills/running-tend/references/review-pr.md → Data-Loss Surface: Hold for Human Review) leaves those merges to you. I found nothing else on this head.

@max-sixty
max-sixty merged commit a457359 into main Oct 20, 2026
38 checks passed
@max-sixty
max-sixty deleted the fix/switch-at-outside-worktree branch October 20, 2026 18:15
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.

2 participants