Skip to content

fix(switch): name a PR base under its remote when it has no local branch - #3951

Merged
max-sixty merged 9 commits into
mainfrom
base-pr-remote-qualified
Aug 29, 2026
Merged

max-sixty merged 9 commits into
mainfrom
base-pr-remote-qualified

Conversation

@max-sixty

@max-sixty max-sixty commented Aug 28, 2026 •

Copy link
Copy Markdown
Owner

wt switch --create X --base pr:N (and --base mr:N) against a same-repo PR failed whenever the PR's source branch was not already a local branch — the usual shape when branching off someone else's PR:

$ wt switch --create feat/review --base pr:101
◎ Fetching base PR #101...
  Fix authentication bug in login flow (#101)
  by @alice · open · feature-auth · https://github.com/owner/repo/pull/101
◎ Fetching feature-auth from origin...
✗ No branch, tag, or commit named feature-auth

The fetch writes only refs/remotes/<remote>/<branch>, and git's rev-parse never expands a bare name to a remote-tracking ref, so the base validation rejected the very name the fetch had just made available. resolve_remote_ref_as_base now falls back to <remote>/<branch> when no local branch has that name, which is what resolve_base_ref already does for a remote-only base — and it earns its place for the same second reason documented there, since git worktree add -b <name> <path> <bare-remote-only-branch> drops the -b and creates the remote branch's own name. A source branch that does exist locally resolves exactly as before, so no previously-working invocation changes and both --base pr: snapshots are untouched.

Adjacent problems this deliberately leaves alone

Found while reviewing the change, all pre-existing and none of them the reported defect:

  • {{ base_worktree_path }} is undefined rather than empty whenever the base branch has no worktree, and minijinja runs SemiStrict, so a hook or --execute template naming it dies with undefined value — after git worktree add has already run. The pre-flight can't catch it because it validates variable names against the available set, not resolution. General to every --base, not just pr:.
  • --base pr:N bases on the local branch when one exists, even if it sits behind the head just fetched, so the new branch can start from a stale copy of the PR. Always naming the remote-tracking ref would fix this, at the cost of the case above for every pr: base plus a changed success line and a changed base_branch in --format json.
  • A local branch literally named origin/<pr-source-branch> shadows the remote-tracking ref in the new fallback, so git worktree add fails with ambiguous object name. Same exposure the existing remote-only base path has, and it fails loudly rather than picking the wrong commit.

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

max-sixty and others added 7 commits August 28, 2026 16:04
…nfig says

`wt switch --create <name> --base origin/<branch>` must not leave the new
branch tracking a differently-named base: under `push.default = upstream` a
bare `git push` would then push the new work onto the base (#713). It got
that from `-c branch.autoSetupMerge=simple`, injected only when the user had
not set the key — so `true` and `always` still reached the footgun, and
`false` and `inherit` denied a same-named branch the tracking that is the
point of it.

Force the `-c` instead. It outranks every config file, so `--create`
produces the same tracking on every machine.

Explicit `--track` / `--no-track` chosen from a name comparison was the
other candidate, and it is wrong twice over. `strip_remote_prefix` splits
`<remote>/<branch>` at the first slash, but git maps a remote-tracking ref
back to its branch through the fetch refspec: with a remote named
`team/fork`, `--create fork/release --base team/fork/release` got
`merge = refs/heads/release`, reintroducing #713, while `--create release`
from the same base got no upstream at all. And `--track` is a hard demand
where `simple` is best-effort — in a single-branch clone holding a
hand-fetched ref it failed the whole command with "starting point
'origin/release' is not a branch", after the branch name was taken. Both are
now regression tests.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBxMUZo7awheuY85PNXCjE
…ng name

A same-repo PR/MR fetch writes only refs/remotes/<remote>/<branch>, and git's
rev-parse never expands a bare name to a remote-tracking ref, so `wt switch
--create X --base pr:N` failed the base validation with "No branch, tag, or
commit named <branch>" whenever the PR's source branch wasn't already a local
branch. Returning <remote>/<branch> matches how the non-shortcut path spells a
remote-only base, and bases the new branch on the head just fetched rather than
on a local branch of the same name.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AX1JmjFMeCEsT3fTzHW4qm
Review feedback on #3950: the forced `-c` was scoped to `--create` while the
help text described one rule, and the DWIM path was left on the user's
`branch.autoSetupMerge`. Under `false` or `inherit`, `wt switch feature` from
`origin/feature` then produced an untracked branch, though the docs promise a
tracking one — and the same values `--create` had just stopped trusting.

Drop the condition. One rule now decides every upstream `wt switch` sets: a
new branch tracks the remote branch it starts from only when the two share a
name. DWIM always shares it; `--create` from a differently-named base does
not. The help text says that once instead of naming `--create` an exception.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBxMUZo7awheuY85PNXCjE
`--base pr:N` / `--base mr:N` against a same-repo PR fetches the source branch
into `refs/remotes/<remote>/<branch>` and then handed the base back under its
bare name. Git's rev-parse never expands a bare name to a remote-tracking ref,
so whenever the source branch wasn't already a local branch — the usual shape
for someone else's PR — the base validation rejected it with "No branch, tag,
or commit named <branch>".

Fall back to `<remote>/<branch>` when no local branch of that name exists, the
same spelling `resolve_base_ref` already gives a remote-only base. A source
branch that is local resolves exactly as before.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AX1JmjFMeCEsT3fTzHW4qm
…t simple declines

Review polish on #3950. Both docstrings asserted that a bare remote-only branch
name is invisible to `git worktree add`. It isn't: `worktree add` DWIMs the
bare form even where `rev-parse` won't resolve it — with `-b` given, git's DWIM
discards it and creates the same-named branch instead. So the remote
qualification `resolve_base_ref` applies is load-bearing for
`resolve_switch_target`'s validation, not for what the creation can see, and
`base_pr_upstream` exists because the PR's source branch may carry any name,
not because the name is unreadable.

Also assert what `test_switch_create_base_outside_fetch_refspec` claims — that
`simple` declines the tracking rather than guessing — and scope the DWIM
matrix's docstring to the values it enumerates.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01NBxMUZo7awheuY85PNXCjE
…o base-pr-remote-qualified

# Conflicts:
#	src/commands/worktree/types.rs

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

Verified the regression and the fix against the merged tree: reverting just the ref_exists branch in resolve_remote_ref_as_base makes the new test fail with the exact reported error (✗ No branch, tag, or commit named feature-auth), and with it in place all five test_switch_base_pr_* tests pass. The origin/<branch> spelling also matches what git worktree add needs — I confirmed separately that a local branch literally named origin/feature-auth makes it hard-fail with fatal: ambiguous object name, so the third bullet in your details block holds.

Four inline suggestions below: the new test hand-rolls String::from_utf8_lossy(...).trim().to_string() around git_command() four times, which is what TestRepo::git_output and TestRepo::head_sha already do — git_output is used 165 times across tests/integration_tests/, including twice within 200 lines of the new test. Applying all four cuts ~36 lines. Plus one on the docstring you touched.

Two things beyond that:

No CI matrix will run on this PR. ci.yaml triggers on pull_request: branches: [main] and this targets switch-explicit-track-flags, so lint, test (linux|macos|windows), and code-coverage never register — pre-commit.ci is the only green here. I ran cargo test --test integration test_switch_base_pr on Linux; Windows and macOS stay unexercised until this retargets to main or #3950 lands.

The --base pr: upstream carve-out is now visible in the output. For a remote-only source branch the success line becomes Created branch feat/review-101 from origin/feature-auth, and the branch does get branch.feat/review-101.merge = refs/heads/feature-auth from the explicit set_config for #2497. But the "Creating a branch" section of after_long_help states the rule as universal — "a new branch tracks the remote branch it starts from only when the two share a name … --create feature --base origin/release … gets no upstream" — so the output now shows exactly the shape the docs use as their counter-example while doing the opposite. The behavior is pre-existing; only the display is new, which is why I'd hang a clause off the Shortcuts section's existing fork sentence rather than treat it as part of this fix.

Comment thread tests/integration_tests/switch.rs Resolved
Comment thread tests/integration_tests/switch.rs Resolved
Comment thread tests/integration_tests/switch.rs Resolved
Comment thread tests/integration_tests/switch.rs Resolved
Comment thread src/commands/worktree/switch.rs Resolved
Review feedback: the new test hand-rolled the trim-and-stringify the helpers
already do. Also states the base's spelling in the summary line of
`resolve_remote_ref_as_base`, which the caller reads as its contract.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AX1JmjFMeCEsT3fTzHW4qm
Base automatically changed from switch-explicit-track-flags to main August 29, 2026 00:25
@max-sixty
max-sixty merged commit b2fcaf1 into main Aug 29, 2026
36 checks passed
@max-sixty
max-sixty deleted the base-pr-remote-qualified branch August 29, 2026 00:54
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.76.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

- **`wt switch --execute` takes a program, not a shell string**: `-x` names one program, with everything after `--` passed as literal argv. Worktrunk spawns it as a child rather than running it in your interactive shell, so shell functions and its `cd` no longer reach you. `-x sh -- -c '…'` recovers shell syntax, not functions. (Breaking: existing `-x` strings, plus `WORKTRUNK_DIRECTIVE_EXEC_FILE` and `WORKTRUNK_SHELL`.) ([#3977](max-sixty/worktrunk#3977), closes [#2860](max-sixty/worktrunk#2860), fixes [#3944](max-sixty/worktrunk#3944), thanks @omgreenfield for testing the migration path)

- **Worktrunk decides tracking for the branches it creates**: a new branch gets an upstream only when its name matches the remote branch it starts from, whatever `branch.autoSetupMerge` says: `--create release --base origin/release` tracks, `--create feature --base origin/release` does not. Under `autoSetupMerge = false` this previously exited 128 after creating the worktree. ([#3913](max-sixty/worktrunk#3913), [#3950](max-sixty/worktrunk#3950), fixes [#3937](max-sixty/worktrunk#3937), thanks @mjakl for reporting and diagnosing)

- **Retired config keys are no longer read**: `commit.generation.template-file` and `squash-template-file` are gone — put the file's contents in `template` or `squash-template`. There is no migration: the key stays, warns as unknown on every load, and the prompt reverts to the built-in default. Setting both `template` and `template-file` used to fail the load; it now loads `template`. `switch.picker.timeout-ms` likewise warns rather than being stripped. (Breaking.) ([#3949](max-sixty/worktrunk#3949))

- **Project aliases and hooks can use `wt switch --execute`**: their bodies previously refused it. Worktrunk now starts the program itself instead of handing shell text to your shell, and the command-approval gate remains the control on project-defined commands. ([#3977](max-sixty/worktrunk#3977))

- **Established automation and LLM customization interfaces are now stable**: `wt step eval`, `wt step for-each`, `wt step prune`, LLM branch summaries, `wt config state vars`, and `commit.generation.template-append` are no longer marked experimental. ([#3949](max-sixty/worktrunk#3949))

- **`wt step prune` stages removals concurrently again**: only the `git worktree remove` teardowns serialize, so dirty checks, fsmonitor shutdown, and the trash rename overlap. The `prune_e2e/live` benchmark median went from 377 ms to 222 ms. ([#3954](max-sixty/worktrunk#3954))

- **`wt config approvals add` reads as a review rather than a warning**: it opens with a cyan `Review 1 command for repo:` instead of a yellow `▲ … needs approval to execute`. The execution-time gate is unchanged. ([#3953](max-sixty/worktrunk#3953))

### Fixed

- **The `wt switch` picker survives a preview longer than 65,535 lines**: skim keeps the pane's line count in a `u16`, so a larger diff aborted `wt` with exit 101 seconds after it painted — on screen the picker looked like it closed by itself. Panes now cap at 60,000 lines and say so. ([#3959](max-sixty/worktrunk#3959), fixes [#3958](max-sixty/worktrunk#3958), thanks @sandertammesoo for reporting and diagnosing)

- **The nushell wrapper propagates exit codes without a POSIX shell**: it reported a failing `wt` by spawning `sh`, so on Windows every failing command printed a ``Command `sh` not found`` trace and exit 1 whatever the real code was. Nushell's wrapper is a static file, so rerun `wt config shell install` to pick this up. ([#3945](max-sixty/worktrunk#3945))

- **The picker no longer shows one detached worktree's diff for another**: previews were keyed by branch name, so every detached row shared the key `(detached)`. Rows now key by canonical identity, which also lets `wt remove feature ~/repo.feature` plan that worktree once instead of failing on the second. ([#3926](max-sixty/worktrunk#3926))

- **`wt switch pr:<n>` gives `pre-switch` hooks the real branch**: `branch` and `target` held the literal `pr:3933`, and `target_worktree_path` was unset even when that branch had a worktree. `pr_number` and `pr_url` are now set for same-repo PRs, not only forks. ([#3941](max-sixty/worktrunk#3941), fixes [#3934](max-sixty/worktrunk#3934), thanks @robsonpeixoto for reporting)

- **`wt config shell install` no longer replaces an rc file created while it was checking**: the missing-file path refuses to clobber and fails with a rerun hint. A dangling rc symlink is preserved and rejected rather than overwritten. ([#3929](max-sixty/worktrunk#3929))

- **`wt switch --create X --base pr:<n>` works when the PR branch has no local branch**: the fetch writes only the remote-tracking ref, and git won't expand a bare name to one, so the command failed with `No branch, tag, or commit named …`. The base is now named under its remote. ([#3951](max-sixty/worktrunk#3951))

- **`wt switch --create` streams `git worktree add` instead of stalling**: where a sandbox denied the timed wait's pipe or `sigaction`, the command waited out git's entire run and then reported `Failed to wait for command` for work that had already succeeded. ([#3881](max-sixty/worktrunk#3881))

- **Claude Code activity markers stay on the session's launch worktree**: the plugin's marker hooks pass `-C "$CLAUDE_PROJECT_DIR"`, so a `cd` mid-session no longer marks another repository. A session launched outside a repository gets no marker. ([#3956](max-sixty/worktrunk#3956))

### Documentation

- **`--execute` documents how to get a variable into a shell body**: each position is substituted verbatim, so a variable spliced into `sh -c` text is re-parsed by that shell and splits on spaces. The help now shows passing it as a separate argument and referencing it positionally. ([#3977](max-sixty/worktrunk#3977))

- **The clone-local default-branch override is documented**: `wt config state default-branch set` writes `worktrunk.default-branch` to the clone's local git config — machine-local, never committed, and shared by every linked worktree. `set` warns when the branch isn't checked out locally, and `wt list` skips its comparisons until it is. ([#3947](max-sixty/worktrunk#3947), [#3948](max-sixty/worktrunk#3948), fixes [#3946](max-sixty/worktrunk#3946), thanks @danielo515 for the request)

- **The docs site renders code with the CLI's own colors**: terminal examples reproduce each snapshot's exact ANSI roles, while command references and the homepage command comparison get clap and shell syntax color from paired light/dark themes. File excerpts gain a path tab, and code wraps instead of scrolling on mobile. ([#3936](max-sixty/worktrunk#3936), [#3938](max-sixty/worktrunk#3938), [#3939](max-sixty/worktrunk#3939), [#3942](max-sixty/worktrunk#3942))

- **The `pre-start` upstream example uses `--base`**: it showed `wt switch --create feature origin/feature`, which `wt switch` rejects. ([#3955](max-sixty/worktrunk#3955))

### Internal

- **Library API rework** (Breaking library API): `cargo-semver-checks` fails ten lints — `RemoteRefProvider` and its provider structs give way to `ForgeKind` dispatch, the `--execute` rework retires the fish and PowerShell `ShellEscapeMode` escapes and `WORKTRUNK_SHELL_ENV_VAR`, `BranchRef` swaps `full_ref`/`worktree_path` for `id`, and accessors including `Branch::unset_upstream` and `ProjectConfig::ci_platform` are gone. ([#3913](max-sixty/worktrunk#3913), [#3926](max-sixty/worktrunk#3926), [#3949](max-sixty/worktrunk#3949), [#3963](max-sixty/worktrunk#3963), [#3977](max-sixty/worktrunk#3977))

- **Hook pipelines and `wt list` collection lost two indirection layers**: the background pipeline carries `PreparedStep` directly, and 15 marker task types collapse into one exhaustive dispatch. The synthesized-`--force` submodule path keeps its dirty re-check and destructive command under one lock, so prune's narrower locking doesn't widen that window. ([#3964](max-sixty/worktrunk#3964), [#3954](max-sixty/worktrunk#3954))

## Install worktrunk 0.76.0

### Install prebuilt binaries via shell script

```sh
curl --proto '=https' --tlsv1.2 -LsSf https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-installer.sh | sh && wt config shell install
```

### Install prebuilt binaries via powershell script

```sh
powershell -ExecutionPolicy Bypass -c "irm https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-installer.ps1 | iex"; git-wt config shell install
```

### Install prebuilt binaries via Homebrew

```sh
brew install worktrunk && wt config shell install
```

## Download worktrunk 0.76.0

|  File  | Platform | Checksum |
|--------|----------|----------|
| [worktrunk-aarch64-apple-darwin.tar.xz](https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-aarch64-apple-darwin.tar.xz) | Apple Silicon macOS | [checksum](https://github.com/max-sixty/worktrunk/releases/download/v0.76.0/worktrunk-aarch64-apple-darwin.tar.xz.sha256) |
| [worktrunk-x86_64-ap

See merge request: Harmonybrew/homebrew-core!18482
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