Skip to content

fix(relocate): skip worktree blocked by an immovable occupant - #3530

Merged
max-sixty merged 3 commits into
mainfrom
nightly/relocate-blocked-occupant-29809337058
Jul 26, 2026
Merged

max-sixty merged 3 commits into
mainfrom
nightly/relocate-blocked-occupant-29809337058

Conversation

@worktrunk-bot

Copy link
Copy Markdown
Collaborator

Problem

wt step relocate could strand a worktree in the internal staging directory and then error out.

When worktree A's target is occupied by worktree B, A depends on B vacating. But if B is itself blocked — its own target is a non-worktree path and --clobber wasn't passed — B never moves. The dependency-resolution loop's no-progress branch assumes "no progress ⟹ a cycle to break," so it temp-moved A into .git/wt/staging/relocate/. finalize_temp_relocations then ran git worktree move <temp> <A's target> into the still-occupied path, which fails and propagates via ? — leaving A relocated into the staging dir rather than at either its original or expected path.

Reproduction

  • A at /w/a wants /w/b; B at /w/b wants /w/c; /w/c is a plain non-worktree file, no --clobber.
  • B is classified target_blocked and never moves.
  • A is temp-moved by break_cycle, then finalize fails with "Failed to move worktree from temp to final location", stranding A in staging.

Fix

is_target_empty only distinguished "occupant moved" from "occupant present"; it couldn't tell a still-pending occupant from a permanently-blocked one. A new blocked_occupant helper detects when a dependent's target is held by a worktree already in the blocked set, and the loop propagates the block to the dependent (skipping it cleanly) instead of handing it to break_cycle. Setting made_progress re-drives the loop so a chain of dependents (A → B → C-blocked) is blocked transitively.

After the fix both worktrees are skipped and the command succeeds:

▲ Skipping beta (target blocked: repo.beta)
↳ To backup blocking paths, use --clobber
▲ Skipping alpha (blocked by beta, which can't be relocated)

○ Relocated 0 worktrees, skipped 2 worktrees

Test

test_relocate_blocked_occupant_skips_dependent sets up exactly this shape and asserts the command succeeds, both worktrees stay put, and nothing is stranded in .git/wt/staging/relocate/. Before the fix the command exited non-zero and alpha was left in the staging dir, so both the snapshot (success: true) and the location assertions would have failed.

Found during the nightly code-quality survey of src/commands/relocate.rs.

When a worktree's target is occupied by another worktree that is itself
blocked (its own target is a non-worktree path with no --clobber), the
dependent could never reach its target. The no-progress branch treated it
as a cycle, temp-moved it into the staging dir, and finalize then failed
moving it into the still-occupied target — erroring out and stranding the
worktree in .git/wt/staging/relocate/.

Detect a blocked occupant and propagate the block to its dependents so
they are skipped cleanly instead of temp-moved.
@worktrunk-bot worktrunk-bot added the nightly-cleanup Issues found by nightly code quality sweep label Jul 21, 2026
The guard's only caller (is_target_empty's Some(false) arm) already
guarantees the target exists, and canonicalize's fallback returns None for
an absent path anyway — so the early return was dead code and the one line
codecov/patch flagged as uncovered. Remove it.

@worktrunk-bot worktrunk-bot left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The fix is correct: blocked_occupant cleanly diverts a dependent away from break_cycle when its occupant is in the blocked set, and setting made_progress = true re-drives the loop so a longer chain (A → B → C-blocked) blocks transitively. Traced the classification-then-execute ordering, the Some(false) arm, and the finalize stranding path — all sound. This is a self-review, so submitting as a comment rather than an approval.

One coverage note: test_relocate_blocked_occupant_skips_dependent is a 2-level chain (alpha → beta-blocked), where beta is already in blocked from new()'s classification. In that shape alpha is blocked on the first pass, and nothing else remains — so the test still passes even if made_progress = true were removed (the loop would fall straight into break_cycle, find everything blocked, and return false). The transitive re-drive the PR body calls out is only exercised by a 3+ level chain (A → B → C-blocked), where B must be blocked in one pass before A can be blocked in the next. Consider adding a 3-worktree variant so a future refactor can't silently drop the re-drive without a failing test. Not blocking — happy to push that test if useful.

The existing test_relocate_blocked_occupant_skips_dependent is a 2-level
chain (alpha -> beta-blocked) where alpha is blocked on the first pass, so
it passes even without the made_progress re-drive. This adds a 3-level
chain (alpha -> beta -> gamma-blocked) that forces the transitive re-drive
to be load-bearing: alpha is parked at a path (aaa-alpha) whose basename
sorts before beta's repo.alpha, so worktree-list order visits the dependent
before its occupant. That leaves alpha pending after pass 1 and only the
re-drive blocks it in pass 2. Without the re-drive, break_cycle temp-moves
alpha and finalize misplaces it into the occupied repo.alpha.
@worktrunk-bot

Copy link
Copy Markdown
Collaborator Author

Pushed the 3-level chain test in b1c85e6 — but building it surfaced a wrinkle worth recording: a naive alpha → beta → gamma-blocked shape doesn't exercise the re-drive on its own.

Worktrees are processed in git worktree list order (git sorts linked worktrees by registration id ≈ path basename), not argument order. If the dependent happens to be iterated after its occupant, both get blocked in a single pass and the re-drive is never needed — so the chain has to force the dependent ahead of its occupant. The test parks alpha at aaa-alpha, whose basename sorts before beta's repo.alpha, so pass 1 visits alpha while beta is still pending, blocks beta, and only the made_progress re-drive runs the pass 2 that blocks alpha.

Verified it's genuinely load-bearing: with made_progress = true removed from the blocked_occupant arm, the test fails — break_cycle temp-moves the still-pending alpha and finalize misplaces it into the occupied repo.alpha (Relocated 1 worktree, skipped 2 instead of skipped 3). Restored, all three skip cleanly. Both the snapshot and a new !repo.alpha/alpha assertion catch the regression.

@max-sixty
max-sixty merged commit cad89ea into main Jul 26, 2026
37 checks passed
@max-sixty
max-sixty deleted the nightly/relocate-blocked-occupant-29809337058 branch July 26, 2026 12:34
social4hyq pushed a commit to social4hyq/homebrew-core that referenced this pull request Sep 20, 2026
worktrunk 0.70.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 step prune` removes worktrees far faster**: Each removal ran a serial chain of ~17 git subprocesses under the scan write lock, re-preparing a plan the scan had already computed and re-stating the worktree right after the fsmonitor daemon stop. The chain is now one check per guarantee, reusing the scan-time plan, and removals run concurrently on the scan lock's read side — the write side is kept for the candidates that need it (hook-bearing, `--foreground`, metadata-pruning, and the current worktree). The documented rust-scale live prune of 24 candidates goes from ~12 s to ~0.6 s wall, and the `prune_e2e/live` benchmark from ~620 ms to ~400 ms. ([#3617](max-sixty/worktrunk#3617), [#3631](max-sixty/worktrunk#3631))

- **`wt step prune --format=json` is ordered, and a failed removal aborts the rest**: Live JSON output is now sorted by scan index, matching `--dry-run`, with the current worktree last. The first failing removal drains the remaining queue unexecuted, matching the serial loop it replaced; in-flight removals complete. ([#3631](max-sixty/worktrunk#3631))

- **A worktree can be named by its path wherever a branch is accepted**: Every argument that takes a branch now also accepts the worktree's own path, resolved after the branch so a directory never shadows a branch sharing its name. A path names what a branch cannot — a detached worktree, or one of two checkouts of the same branch. Relative paths resolve against `-C` and a leading `~` against the home directory, so a path worktrunk printed can be pasted back. [Docs](https://worktrunk.dev/switch/#naming-a-worktree) ([#3607](max-sixty/worktrunk#3607))

- **`wt list` flags a branch checked out in more than one worktree**: Such a branch resolves to whichever worktree git lists first, so every worktree on it now carries `⚑` — `worktree.state` `"duplicate_branch"` in schema 1, a `worktree.duplicate_branch` boolean in schema 2. The flag makes the ambiguity visible in the listing; resolving such a branch from any command warns separately and names a duplicate to drop. ([#3480](max-sixty/worktrunk#3480), [#3606](max-sixty/worktrunk#3606))

- **`wt switch --execute` computes only the template variables its command names**: The switch path built every variable the template context could hold before rendering; it now resolves just the ones the command references. On a clone with no `origin/HEAD` and no cached default branch, that removes a `git ls-remote` the command never asked for — 13 subprocesses and one remote query down to 8 and none. ([#3628](max-sixty/worktrunk#3628))

### Fixed

- **A branch checked out in a second worktree is retained on removal, `-D` included**: `wt remove` and `wt step prune` now act on the worktree named rather than the branch's first checkout, and all three of `wt remove`, `wt step prune`, and `wt merge` keep the branch while another worktree still has it out — deleting the ref would leave that worktree unable to resolve `HEAD`, which is why `git branch -d` refuses the same delete. The retention is reported and names the surviving checkout rather than passing silently. ([#3533](max-sixty/worktrunk#3533))

- **Removal reports what it took, not what it selected**: A removal's summary and JSON described the plan, so a worktree candidate whose branch was retained still counted as `✓ Pruned 1 branch`, and `wt remove --format=json` reported `"branch_deleted": true` beside a stderr line saying the branch was kept. Execution now returns the branch's fate; `wt step prune` counts executed outcomes (`--dry-run` included), both JSON payloads gained `branch_deleted`, and a declined orphan deletion drops out of the removed list rather than being reported as removed. ([#3633](max-sixty/worktrunk#3633), [#3637](max-sixty/worktrunk#3637))

- **Hook previews expand every variable except `vars.*`**: One `vars.` token disabled expansion for the whole command, so `wt hook show --expanded` and `wt hook <type> --dry-run` printed `{{ branch }}` and `{{ repo }}` raw in a listing whose job is to show the expansion. A preview now substitutes a stand-in that renders each `vars.*` reference back as itself, nested access included, while every other variable expands — and no longer spawns the git read that resolving `vars` required. The listing is also derived from the execution path itself, so a context key added there reaches the preview with no second edit. `wt config alias dry-run` shares the renderer, so its help text — which still described the all-or-nothing behavior — was corrected to match. ([#3635](max-sixty/worktrunk#3635), [#3638](max-sixty/worktrunk#3638), [#3639](max-sixty/worktrunk#3639))

- **`wt hook show` no longer prints a bare heading for an empty command list**: A hook type declared as `post-switch = []` has a config entry but no commands, and the section decided it had printed something from the entry rather than from the rows — so it emitted its heading and stopped, and the `(none configured)` line never appeared. Both the user and project sections carried the bug, since the loop and the fallback were duplicated; they now share one renderer that reports whether it wrote any rows. The execution path was already correct: an empty list announces nothing and is omitted from JSON. ([#3641](max-sixty/worktrunk#3641))

- **`wt config shell install` reclaims its own legacy wrapper paths**: Fish sources `conf.d` at startup, so a stale `conf.d/{cmd}.fish` was already loaded by the time fish would autoload the `functions/{cmd}.fish` the install had just written — the old definition won and the new wrapper never loaded. Install decided ownership by reading the file, and left anything unrecognized in place. Ownership now comes from the path: `conf.d/{cmd}.fish` and the stranded nushell `{cmd}.nu` candidates are paths worktrunk computes for the command being installed, so it takes them back whole, unread. Only that exact filename is touched — a neighbour under another name is not worktrunk's — and each removal is reported. `wt config shell uninstall` still reads the header, because it takes no `--cmd` and so cannot know the name; it prompts and previews every file first. (Breaking: install now removes a file at those exact paths regardless of its contents.) ([#3602](max-sixty/worktrunk#3602))

- **Command timeouts actually bound wall-clock, and a default branch guessed while the remote was unreachable isn't cached**: A timeout killed only the direct child, so a surviving grandchild held the output pipe open and the call ran on regardless — a 3 s bound measured at 120 s. A timed command now runs in its own process group and the whole tree is torn down on expiry, which fixes every existing bound including the fsmonitor and reap probes. On top of that, nothing in git bounds `git ls-remote` (an unreachable host costs ~127 s per address on Linux), so default-branch detection abandons the query after 10 s and falls back to local inference — without caching the result, so an outage can't make an inferred default branch permanent. (Breaking: because a timed command gets its own process group, Ctrl-C no longer reaches it; the command waits out the remaining bound.) ([#3603](max-sixty/worktrunk#3603))

- **`wt step relocate` no longer strands a worktree in its staging directory**: When worktree A's target was held by worktree B, and B was itself blocked by a non-worktree path without `--clobber`, the dependency loop read the stall as a cycle, temp-moved A into `.git/wt/staging/relocate/`, then failed moving it into the still-occupied target — leaving A at neither its original nor its expected path. A worktree blocked by an immovable occupant is now skipped. ([#3530](max-sixty/worktrunk#3530))

- **Forge CLI failures are classified by response shape, not by the tool's prose**: `tea api` copies the response body to stdout and exits 0, so an HTTP error never tripped the exit-code gate — a Gitea `APIError` body deserialized into `{state: "", total_count: 0}`, indistinguishable from a commit with no CI statuses, while the PR-list path blamed an API change for what was an API error. Failures from `gh`, `glab`, and `tea` are now keyed on the response envelope, and a non-zero exit keeps meaning the tool itself failed; the CLI's own error text is forwarded rather than reworded, so a bad token surfaces as `gh: Bad credentials (HTTP 401)` instead of a suggestion to re-authenticate. `wt config show --full` reports the Azure DevOps CLI extension alongside the other forge tools. ([#3595](max-sixty/worktrunk#3595), [#3597](max-sixty/worktrunk#3597), [#3605](max-sixty/worktrunk#3605))

- **`wt config plugins claude install-statusline` no longer mistakes another tool's statusline for its own**: The check for an existing worktrunk statusline matched the bare substring `wt `, which an unrelated command like `newt status` satisfies — so `wt config show` reported a foreign statusline as worktrunk's, and the installer early-returned "already configured" and refused to install. It now matches the adjacent `list statusline` token pair, so it works whether the binary is `wt`, `git-wt`, or an absolute path. ([#3595](max-sixty/worktrunk#3595))

- **`[list] task-timeout-ms` is removed**: The per-command bound is gone; `[list] timeout-ms` bounds the whole collect phase. A config that still sets it warns, and `wt config update` strips the key — i

See merge request: Harmonybrew/homebrew-core!15439
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

nightly-cleanup Issues found by nightly code quality sweep

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants