Skip to content

feat(switch): rank picker matches by the distinct worktree path - #3208

Merged
max-sixty merged 3 commits into
mainfrom
picker-path-tiebreak
Jun 25, 2026
Merged

max-sixty merged 3 commits into
mainfrom
picker-path-tiebreak

Conversation

@max-sixty

@max-sixty max-sixty commented Jun 24, 2026 •

Copy link
Copy Markdown
Owner

The interactive wt switch picker built the string skim's matcher sees (search_text) from each row's absolute worktree path. Every row therefore shared the same ~/workspace/ prefix, and skim's default [Score, Begin, End] tiebreak (on a score tie it prefers the earliest match position) biased matches toward that shared noise. Two coupled changes make the matcher rank on the part of a row that actually distinguishes it.

Part A: path-scheme tiebreak

skim's Path scheme sets last_match = true (prefer the query's rightmost occurrence) and front-loads the PathName tiebreak criterion (rank matches in the leaf segment, at or after the last /, above matches in a parent directory). Set directly on the builder:

.last_match(true)
.tiebreak(vec![
    RankCriteria::Score,
    RankCriteria::PathName,
    RankCriteria::Begin,
    RankCriteria::End,
])

These are set as the two underlying knobs rather than .scheme(MatchScheme::Path). The brief flagged .scheme() as a silent no-op through the library builder, but that is not the case for skim 4.8.0: SkimOptionsBuilder::build() is a manual wrapper that calls SkimOptions::build() (self.final_build().map(SkimOptions::build)), and SkimOptions::build() is exactly where the scheme expands. Verified empirically: .scheme(MatchScheme::Path) yields last_match=true and tiebreak [Score, PathName, Score, Begin, End]. So .scheme() would work; the reason to set the knobs directly is that the scheme inserts a duplicate Score criterion (harmless, since the first wins, but an artifact), whereas the direct form gives the clean [Score, PathName, Begin, End].

The scrollbar gap that motivated the original concern is a different mechanism: scrollbar's default comes from a clap default_value attribute that the derive-builder path doesn't apply (so it falls back to String::default()), not from SkimOptions::build() going uncalled.

Known interaction

PathName reads the whole search_text, including the trailing gutter glyph each row folds in for sigil-filtering. Local-branch rows use / as that glyph, which PathName reads as a path separator, so on a score tie a local-branch row sorts just under a worktree/remote row whose glyph (+/@/^/|) is not a separator. The effect is confined to exact ties (PathName is the second criterion) and only reorders rows; the alternative (changing the gutter sigils or dropping the path scheme) costs more than the tie-order quirk, so it rides along, documented in the code.

Part B: distinct path

search_text now strips the shared worktree parent from each worktree path, so the matcher indexes only the distinguishing tail (worktrunk.skim-features, not the full absolute path). The base is list_worktrees()[0].path.parent(), computed once before the per-row loop; a worktree outside that parent keeps its full path via the strip_prefix fallback.

I first used primary_worktree() for the base, but review surfaced three problems with it, all of which dissolve by sourcing the base from list_worktrees() instead:

  • primary_worktree() is not network-free for bare repos: it routes through default_branch(), which can git ls-remote on the first call per repo.
  • primary_worktree() resolves to repo_path(), which is dunce::canonicalized. The row paths come from list_worktrees() (raw git worktree list --porcelain). Those are two different derivations, so they could in principle diverge (e.g. /private/var vs /var) and silently defeat the strip. Sourcing the base from list_worktrees() too means base and rows share one canonicalization, so the strip can't miss.
  • primary_worktree() returns None for a bare repo whose default branch has no worktree; list_worktrees()[0] yields a base whenever any worktree exists.

list_worktrees()[0] is the main worktree for normal repos and the first linked worktree for bare ones; either way its parent is the shared sibling parent. It is already cached by the time the skeleton renders (the rows were just built from it), so this adds no network or extra git work.

Only search_text changes; the rendered Path column is a separate field and is untouched. --prs rows build their own search_text with no worktree path, so they are unaffected.

Verification

  • New unit test search_text_strips_shared_worktree_parent pins the exact stripped format and the out-of-tree fallback, reading the inside row's path back via worktree_for_branch so it strips a real list_worktrees() path.
  • Drove the picker interactively against a repo with namespaced worktrees (api/users, users/api, db/users, feature/payment, payment/refund). Querying users matched only the three *users* rows, not all six. Querying claude, a fragment that lives only in the now-stripped shared parent (~/.claude/jobs/...), matched zero rows, where before it would have fuzzy-matched .claude on every row.
  • Multi-angle review (8 finder angles + adversarial verify) drove the move to list_worktrees() and the documented tiebreak interaction above.
  • cargo run -- hook pre-merge --yes passes (4180 tests, lints).

This was written by Claude Code on behalf of max

The interactive `wt switch` picker fed skim each row's absolute worktree
path, so every row shared the `~/workspace/` prefix and the default
`[Score, Begin, End]` tiebreak biased matches toward that shared noise.

Two coupled changes make the matcher rank on the distinguishing part of a row:

- Strip the primary worktree's parent from the matcher's `search_text`, so
  skim indexes only the distinct leaf (`repo.feature`). Out-of-tree worktrees
  keep their full path via the `strip_prefix` fallback. Only `search_text`
  changes; the rendered Path column is untouched.
- Set skim's path scheme directly on the builder (`last_match(true)` +
  `tiebreak([Score, PathName, Begin, End])`), so leaf-segment matches outrank
  parent-directory ones.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@worktrunk-bot

Copy link
Copy Markdown
Collaborator

My approval stands — the two red checks are PTY timing flakes, not regressions from this change.

Test linux macos windows code-coverage (linux)
test_switch_picker_alt_r_keeps_cursor_sticky ✅ ❌ (job) ✅ ✅
test_switch_picker_prs_gitlab_list ❌ (advisory job) — ✅ ✅

Each test failed on exactly one platform and passed on the other two-plus. A real regression in the matcher search_text would fail the same test deterministically everywhere. Both failures are the same shape — Timed out after 30s waiting for expected content … to appear on screen (switch_picker.rs:463, the wait_for_stable_with_content helper) — i.e. the preview pane/screen lagged past the 30s window under CI load. On the macos run the cursor > was correctly on wt-keep but the preview still showed main's pane.

The change is also behaviorally inert for both of these paths:

  • test_switch_picker_prs_gitlab_list drives --prs mode. --prs rows have no worktree path, so search_text is unchanged (worktree_path() is None → path_str empty → "{branch_name} {gutter}", exactly as before). The new path_base strip only touches worktree rows.
  • test_switch_picker_alt_r_keeps_cursor_sticky types no filter query — it navigates with Down + alt-r only. With an empty query skim ranks all items at equal score in insertion order, so the tiebreak/last_match knobs and the stripped search_text content don't affect row ordering or the sticky-cursor slot mapping.

Leaving the approval in place rather than dismissing (per repo policy on unrelated flakes). The required test (macos) check is red, so a rerun of just that job is needed before merge — gh run rerun --failed returns 403 while other jobs in the run are still in progress, so it's best kicked off once the run settles.

Review of the path-tiebreak change surfaced three issues with sourcing the
strip base from `primary_worktree()`:

- the "network-free" claim was wrong for bare repos (`primary_worktree()` ->
  `default_branch()` can `ls-remote` on first call);
- `repo_path()` is dunce-canonicalized, a different derivation than the row
  paths (from `list_worktrees()`), so the two could in principle diverge and
  silently defeat the strip;
- `primary_worktree()` returns `None` for a bare repo with no default-branch
  worktree.

Deriving the base from `list_worktrees()[0].path.parent()`, the same source the
row paths come from, dissolves all three: shared canonicalization, no network,
and a base whenever any worktree exists. The test now reads the inside row's
path back via `worktree_for_branch` so it exercises the real list-worktrees
path.

Also documented the one tiebreak interaction the review confirmed: local-branch
rows fold in `/` as their gutter glyph, which skim's `PathName` reads as a path
separator, so on a score tie they sort just under worktree/remote rows whose
glyph is not a separator.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
worktrunk-bot
worktrunk-bot previously approved these changes Jun 24, 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.

codecov/patch is red on ad6a38e — one uncovered added line, progressive_handler.rs:565. It's the text(2) failure-message argument of the multi-line assert_eq!: that expression only evaluates when the assertion fails, so on a passing run codecov marks it a miss. The message is also redundant — assert_eq! already prints both the actual and expected values on mismatch. Collapsing the assert onto one line puts text(2) back on a counted line and drops the redundant arg, closing the gap.

Dismissing my approval until the patch gate is green (per the repo's codecov-gates-merge policy); re-approving once it clears.

@worktrunk-bot
worktrunk-bot dismissed their stale review June 24, 2026 18:28

codecov/patch is red — one uncovered added line (progressive_handler.rs:565). Re-approve once the patch gate clears.

… leaf assert

The multi-line `assert_eq!(text(2), ..., "...{:?}", text(2))` put the failure
message's `text(2)` on its own line, which a passing run never evaluates, so
codecov/patch counted it uncovered (96.55% vs 97.57% target). Binding the row
text to locals first evaluates them on the success path and drops the dead
message-only line. Verified with `cargo llvm-cov nextest` that every added line
in the diff is now covered.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit 0d0fcac into main Jun 25, 2026
46 of 47 checks passed
@max-sixty
max-sixty deleted the picker-path-tiebreak branch June 25, 2026 02:28
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.62.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

- **Browse open PRs/MRs in the `wt switch` picker, with live CI**: The picker now streams a live CI/review-status column per row — priming from the local cache, then fetching live (it previously showed only cached numbers with no network). A new `--prs` flag adds the repository's open PRs (GitHub) / MRs (GitLab) as rows alongside your worktrees, each with `pr` / `comments` / `log` preview tabs loaded from the forge in the background; selecting one fetches its branch and switches. Rows whose branch is already shown aren't duplicated, so `--prs` differs from plain `wt switch` only by the extra rows. [Docs](https://worktrunk.dev/switch/) ([#3128](max-sixty/worktrunk#3128), [#3169](max-sixty/worktrunk#3169), [#3189](max-sixty/worktrunk#3189), [#3252](max-sixty/worktrunk#3252))

- **`main…±` diff column shows by default in `wt list`**: The `main…±` column (lines changed since the merge-base with the default branch) now renders in the default `wt list` and picker, served from a persistent cache rather than a history walk. `--full` now adds only the columns that reach off-machine — CI status and LLM branch summaries — and `wt list --format=json` populates `main.diff` for every item, not just under `--full`. ([#3236](max-sixty/worktrunk#3236))

- **`[list] columns` selects and orders the columns `wt list` shows**: A new `[list] columns` user-config key (also settable via `--config-set`) takes an ordered array of column names — built-in (`branch`, `status`, `ci`, `path`, …) and `[list.custom-columns]` headers alike — and renders exactly those, in that order. Where v0.61.0's custom columns *add* columns, this *selects and reorders* the whole set; omit the key for the default layout. (`WORKTRUNK__LIST__COLUMNS` isn't supported yet and warns if set.) ([#3141](max-sixty/worktrunk#3141))

- **Picker PR preview shows full PR/MR detail**: The `pr` tab now renders the PR/MR title, markdown description, author, draft state, comment count, bold branch name, and underlined URL for any row whose branch has an open PR — not just `--prs` rows — and the `comments` tab fetches the real thread. The title and description ride the CI fetch the picker already makes; the comment thread is fetched lazily in the background, once per row. ([#3167](max-sixty/worktrunk#3167), [#3197](max-sixty/worktrunk#3197), [#3223](max-sixty/worktrunk#3223), [#3195](max-sixty/worktrunk#3195), [#3231](max-sixty/worktrunk#3231))

- **Interactive picker runs on Windows**: The `wt switch` picker was Unix-only because its preview-tab keys shelled out through a per-process state file `cmd.exe` lacks; tab state moved to an in-memory atomic with native skim callbacks, lifting the platform gate. ([#3217](max-sixty/worktrunk#3217))

- **Picker keyboard shortcuts**: `Alt-y` copies the selected branch name, `Alt-o` opens the row's PR/MR in the browser, and `Alt-r` refreshes the list (picking up worktrees created or removed elsewhere). (Breaking: in the picker, remove moved from `Alt-r` to `Alt-x`) ([#3233](max-sixty/worktrunk#3233))

- **Picker uses the full terminal**: List height scales with the terminal (a roughly even split with the preview, minimum 3 rows) instead of a fixed 12-row cap, the table lays out at full width so toggling the preview off with `Alt-p` reveals the freed columns with no reflow, and a scrollbar appears when the list overflows. ([#3205](max-sixty/worktrunk#3205), [#3214](max-sixty/worktrunk#3214), [#3198](max-sixty/worktrunk#3198))

- **Picker filters on more of each row**: Typing a gutter sigil filters by row kind (`+` for linked worktrees, `@` for the current one), the fuzzy matcher ranks on the distinguishing path segment rather than the shared parent prefix, and rows with a PR/MR also match on its number, title, and author. ([#3143](max-sixty/worktrunk#3143), [#3208](max-sixty/worktrunk#3208), [#3252](max-sixty/worktrunk#3252))

- **Picker visual polish**: The legend recolored to dim-cyan and reordered so navigation leads, and preview loading placeholders moved to the dim-hint style (`↳` transient, `○` settled, `▲` failed). ([#3237](max-sixty/worktrunk#3237), [#3253](max-sixty/worktrunk#3253))

- **"Still waiting" status for slow commit-message generation**: A configured `commit.generation` command captures stdout, so a slow or hung LLM previously showed nothing while `wt step commit`/`squash` waited. After a 2s delay worktrunk now shows a dim, in-place `○ Waiting for the commit message (Ns)` status, escalating at 10s to reveal the exact shell-escaped invocation in a gutter beneath it; the block clears on completion, mirroring `wt list`'s stall footer. ([#3178](max-sixty/worktrunk#3178))

- **"Still waiting" status extended to more slow commands**: The same waiting status now covers three more foreground commands that were silent while a captured subprocess ran — the `wt config show --full` commit-generation self-test, the `wt switch pr:`/`mr:` host lookup, and the `wt config show --full` version check. The version check no longer caps its fetch at an aggressive 5s, instead showing the status while a slow-but-working request completes (with a generous ceiling so a non-interactive run can't hang). ([#3183](max-sixty/worktrunk#3183))

- **`wt config state logs profile` performance profiler**: A new subcommand turns a `-vv` `[wt-trace]` capture (a path argument, `-` for stdin, or the default `trace.log`) into a performance profile: subprocess time by command shape, the slowest calls, parallelism and peak concurrency, redundant cache-miss re-runs, and — for `wt list`/picker captures — derived latencies and a collect timeline. `--format=json` emits the same data, and every `-vv` bug-report bundle now inlines a rendered profile. ([#3184](max-sixty/worktrunk#3184), [#3186](max-sixty/worktrunk#3186))

- **`WORKTRUNK_VERBOSE` env var**: `WORKTRUNK_VERBOSE=0|1|2` mirrors `-v`/`-vv`, combined with any flag via `max` (the env sets a floor the flag can raise). Unlike the flags it's honored on the shell-completion path, which returns before flag parsing — so a slow tab-completion can be profiled for the first time. ([#3166](max-sixty/worktrunk#3166))

- **Aliases inherit the wrapped command's completion**: An alias that forwards `{{ args }}` to a single `wt` command (`co = "wt switch {{ args }}"`) now completes that command's arguments and flags — `wt co <Tab>` completes branches like `wt switch <Tab>` — instead of a generic stub. Bare dispatchers and multi-`{{ args }}` aliases keep the stub. ([#3172](max-sixty/worktrunk#3172), thanks @yzx9)

- **`wt step copy-ignored --require-include`**: A new `--require-include` flag makes the copy a no-op unless a `.worktreeinclude` file exists in the source worktree (matching Claude Code desktop, where that file is required), reporting why it skipped as a hint in text mode and a `reason` field in `--format=json`. ([#3196](max-sixty/worktrunk#3196), thanks @yzx9)

- **`wt step tether` honors `-C`**: The global `-C <path>` flag now sets the tethered command's working directory (`wt step tether -C frontend -- npm run dev`); teardown still watches the worktree root, so the command is reaped when the worktree is removed. ([#3207](max-sixty/worktrunk#3207))

- **Statusline rate-limit pace color grades by severity**: The pace segment's color now deepens (dim → dim-yellow → yellow) with the projected throttling severity, so an early-window burst stays muted while a costly projected lockout stands out. The displayed pace number is unchanged. ([#3229](max-sixty/worktrunk#3229))

### Fixed

- **Picker `Alt-x` removal updates the row in place**: Removing a worktree no longer re-collects the whole list (a flicker that reset the cursor to the top): an unmerged worktree's row morphs into a branch-only row while the worktree is removed in the background, and a merged worktree's row drops with the cursor landing on the row that slid up. A removal that can't safely happen — the current or main worktree, or a dirty or locked one — is declined with the same diagnostic `wt remove` prints, rather than a dead keypress or a disruptive `cd` home. The post-removal cursor lands by row identity, so it stays correct even under an active filter. ([#3262](max-sixty/worktrunk#3262), [#3199](max-sixty/worktrunk#3199), [#3211](max-sixty/worktrunk#3211), [#3225](max-sixty/worktrunk#3225))

- **Picker preview refreshes when its background fetch lands**: A diff/log/PR-view fetch that completed after its triggering keystroke used to sit unshown until the next keypress; the pane now updates on its own when the fetch lands. ([#3247](max-sixty/worktrunk#3247))

- **Picker rows stay aligned while filtering**: Typing a filter no longer slides the matched row left and drops its leading sigil, and `Alt-l`/`Alt-h` no longer scroll the list off its gutter. ([#3213](max-sixty/worktrunk#3213), [#3226](max-sixty/worktrunk#3226))

- **fish completions no longer recurse to the call-stack limit**: With worktrunk's fish lazy-load wrapper installed, co

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