Commit Graph
5396 Commits
Author SHA1 Message Date
Maximilian Roos 0a276126c5 refactor: serialize branch variables without intermediate collections 2026-10-22 14:33:33 +00:00
Maximilian Roos 18d79911d3 fix: propagate variable listing read failures 2026-10-22 13:03:36 +00:00
Maximilian Roos 0a9fa9ee64 Keep branch variable reads and clears within their exact branch 2026-10-22 10:09:13 +00:00
Maximilian RoosandClaude Opus 5.5 a63c1c3e2a feat(plugin): run every Claude hook through wt config plugins claude hook (#4305)
Routes all eight Claude Code hook events through the existing Rust
dispatcher added in #4304. Hook commands become literal invocations that
pass the plugin directory validator, and the plugin no longer requires
`jq`. The README requires `wt` v0.81.0 or later.

On `wt` v0.80.0 or earlier, worktree creation and removal fail, and
activity markers and EnterWorktree auto-approval stop working. The
latter hooks retain `|| true`, so the failures stay nonblocking and
EnterWorktree falls back to a permission prompt. The dispatcher
preserves existing-branch reopening and safe removal of unmerged work.
Updates the hook layout assertions and the skill's create-or-reopen
guidance, and removes the obsolete shell pipeline explanation.

Local validation: the project gate passed for the corrected skills at
`1a9ebd12c` in an isolated target directory (5,392 tests passed, one
skipped, plus Clippy, formatting, docs, and snapshots). Docs mirror sync
and all five dispatcher integration tests pass. The later
documentation-only follow-ups clarify the README's attribution of
payload parsing and the measured cleanup behavior. `claude plugin
validate plugins/worktrunk` passed its directory checks with the
existing missing-version warning; it excludes the catalog's safety scan
and policy review.

Independent Opus 5.5 review found no code defects and verified the
older-version failure. Further passes reviewed the corrected skills,
mirrors and live cleanup evidence with no remaining findings.

Cleanup was verified live on Claude Code 2.1.308 in an isolated
repository: reopening an existing worktree through both `claude
--worktree` and `EnterWorktree({name})`, then `/exit`, shows Keep /
Remove with Keep selected. Keep leaves its branch and checkout intact
and emits no `WorktreeRemove`. A fresh CLI-created worktree shows the
same prompt; choosing Remove emits `WorktreeRemove` and removes the
synthetic checkout and merged branch. The rationale now reflects that
confirmation instead of claiming automatic cleanup.

Reopening is already present in the [base create
hook](https://github.com/max-sixty/worktrunk/blob/d965d819f226ad7ac853efed8b2a996bb0c880a6/plugins/worktrunk/hooks/hooks.json#L72):
it clears `--create` for an existing local branch. Both the [base remove
hook](https://github.com/max-sixty/worktrunk/blob/d965d819f226ad7ac853efed8b2a996bb0c880a6/plugins/worktrunk/hooks/hooks.json#L82)
and the dispatcher check for `.git` and invoke `wt -C <path> remove
--foreground <path>`, with no force flags. This cutover preserves that
deletion scope and its safeguards.

> _This was written by Codex on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-22 01:20:20 -07:00
Maximilian Roos ab9cecb171 Fix demo command tracking and simplify Try it copy (#4546)
Demoshell's guide needs Bash to report command exit status before it can
verify successful steps. Put the command-tracker prompt and OSC 133 exit
markers in the startup rcfile, skipping the initial prompt so Studio
does not mistake it for the app exiting. Keep the recipe and published
guide representation aligned with the working demo.

Shorten the Try it page to the introduction, loading note, full-page
fallback, attribution, and install link. This follows
[#4280](https://github.com/max-sixty/worktrunk/pull/4280).

Validation: ARM64 Alpine recipe and guide walkthrough; startup,
failed-command, and successful-command marker checks; published demo
walkthrough; docs sync test and build; rendered copy review.

The full local gate ran 5,392 tests: 5,389 passed and three PowerShell
tests failed because the installed PowerShell 7.5.2 crashes with `Stack
overflow.` even on `pwsh -NoProfile -Command '1 + 1'` outside the
repository. Pre-commit checks pass separately.

> _This was written by Codex on behalf of max-sixty_
2026-10-22 00:36:59 -07:00
d965d819f2 docs: add an unlinked browser demo for production testing (#4280)
Adds a **Try it** page at `/try-it/`, available by direct URL while
production embedding is tested; excluded from navigation, site search,
and the sitemap, with a noindex directive, with a live Worktrunk demo in
a browser-local Alpine ARM64 VM via [Demoshell](https://demoshell.com).
Nothing downloads until Run is pressed. The page includes Demoshell
attribution and a permanent full-page fallback link.

The VM definition lives in `docs/demos/demoshell/`: the setup recipe,
Bash startup rcfile, and guide. The guide covers list → create → edit →
list → merge, followed by an optional manual picker step. Merge commits
the change automatically. Studio must launch Bash explicitly: changing
root's login shell does not replace its running ash session. The prompt
retains the `arm64js:` prefix required by Demoshell's command tracker.
The README maps each file to its Studio field and provides an ARM64
Alpine Docker check using the same Bash entry point.

**Production test rollout:** `m/tui:worktrunk` resolves from the allowed
`worktrunk.dev` origin. The recipe, startup file, and guide draft are
entered in Studio, but the final snapshot upload is stalled at 1% after
setup completes. The currently published snapshot predates the prompt
repair, and visitors still receive the old guide. The page is
intentionally unlinked so it can be merged and tested on the accepted
production origin before broader exposure. The corrected snapshot must
finish saving, then the new guide must be published and tested in a
fresh visitor session.

Validation: the required command patterns and output checks pass on
ARM64 Alpine with `wt v0.81.0`. In the real Studio preview, applying the
Bash/prompt corrections allowed the required steps to check off, merge
to commit automatically, and the shell to return to main. The optional
picker opens and exits; its guide step uses manual completion because
Demoshell did not detect the alternate-screen exit. Local docs build,
type checks, plugin/site tests, and docs sync passed. Final snapshot
publication and a fresh end-to-end run remain blocked by the upload.

The sidebar-order test accepts Astro page routes, and the page-outline
test exempts `/try-it/`, whose table of contents is disabled to give the
demo more width.

Disclosure from the original author: they run Demoshell. Hosting is free
for eligible open-source projects, and the embed carries attribution.

> _This was written by Codex on behalf of max-sixty_

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: Maximilian Roos <m@maxroos.com>
2026-10-21 19:40:15 -07:00
Maximilian Roosandworktrunk-bot b3d6fd2700 Clarify recovery hints and file-operation diagnostics (#4346)
GitHub PR-not-found errors keep the selected repository and its source
in the diagnosis, preserve the CLI error, and render `gh repo
set-default` as a separate recovery hint. Relocation warnings identify
the blocking path and explain that `--clobber` backs it up; config
migration hints name the command that applies the updates.

Copy and promote failures use the shared path formatter and retain their
underlying I/O errors. Failed copies name both source and destination,
including when the source is readable and the destination is invalid.
Promote recovery commands use shell-quoted paths.

Validation: the required local pre-merge gate passes 5,392 tests (one
skipped), Clippy, formatting, locked dependencies, documentation and
doctests. Focused error-path tests check quoted paths, destination
context and retained I/O causes; command snapshots cover the recovery
hints. Independent review found no remaining issues.

Remote patch coverage is 90.06% (136/151 lines) against a 98.55% gate.
The 15 misses are existing filesystem-failure paths whose diagnostic
formatting changed; exercising most would require races, fault injection
or special permission/ownership fixtures. The maintainer approved
landing with this coverage gap and the independent subagent review after
the automated review job completed without posting a verdict. Linux,
macOS and Windows CI, including all advisory affected-tests jobs,
passed.

> _This was written by Codex on behalf of max-sixty_

---------

Co-authored-by: worktrunk-bot <worktrunk-bot@users.noreply.github.com>
2026-10-21 10:32:29 -07:00
45d9b4e842 Run Worktrunk Tend workflows with Codex on gpt-6-sol (#4240)
Switch Worktrunk's Tend agent workflows to Codex on `gpt-6-sol`,
generated with Tend 0.3.14. Mackup's existing account rotator owns
subscription refresh (`codex.auth_refresh: false`) and publishes
access-only `CODEX_AUTH_JSON` plus `CODEX_ACCOUNT`. This removes the
proposed hosted refresh workflow and its separate login/PAT requirement.
The unused hosted-refresh PAT secret has been removed.

Validation: `actionlint` and the complete branch whitespace check pass.
An independent code review found no issues. GitHub CI, including
Codecov, passes at `8e842331aa0f29949579050551dd2d0b67fb04b1`, and
worktrunk-bot approved that exact commit. A real Codex 0.160.0 request
to `gpt-6-sol` succeeded with an access-only credential derived from a
saved login selected by Mackup's allocator. All 5,388 Rust tests passed
(one skipped), along with documentation checks and the final full
pre-commit run.

Cutover requires maintainer merge authorization. Mackup reads ownership
from the default branch and the `tend` environment admits only main, so
credential publication and a hosted Codex run follow the merge. After
landing, run the allocator, verify the published account and secret
timestamp, rerun `tend check`, and validate a hosted agent run; retry
any agent job that starts before publication. Current `tend check`
passes every check except the missing Codex consumer credential. This
supersedes the earlier dedicated-login premerge condition; hosted
operation is not yet validated.

> _This was written by Codex on behalf of max-sixty_

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
Co-authored-by: Codex <noreply@openai.com>
2026-10-21 10:19:04 -07:00
Worktrunk Bot be5c53205f perf(commit): skip the second staging pass when no pre-commit hook ran (#4540) 2026-10-21 01:24:02 -07:00
Maximilian RoosandClaude Opus 5.5 e5946590f8 test(foreground_jobs): list the terminal's processes when a shell wait times out (#4539)
`foreground_jobs::bash_wrapper_preserves_protected_prompt` hit its 20s
`Shell::wait_for` timeout in 3 of 4 local full-suite runs while the
host's load average was 330–490. Each failure stalled right after `wt
0`, with a child process holding the terminal, but the panic message
didn't name the child. The test passes at normal load, under CPU
busy-loops, and under `taskpolicy -b` throttling, so the cause is still
unknown.

The timeout message now includes `ps -o
pid,ppid,pgid,stat,wchan,etime,command -t <pty>`. With a temporary
`sleep 60` added to the test's wrapper command, the failure reads:

```
  PID  PPID  PGID STAT WCHAN  ELAPSED COMMAND
44618 44597 44618 Ss   -        00:20 /bin/bash --noprofile --norc -i
44813 44618 44813 S+   -        00:20 /bin/sh …/repo/native-wrapper-command 0
44869 44813 44813 S+   -        00:20 sleep 60
```

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 21:23:52 -07:00
Maximilian RoosandClaude Opus 5.5 d6cb21a241 fix(remove): derive the trash directory in wt _drain-trash instead of taking it as an argument (#4536)
The hidden `wt _drain-trash <dir>` deleted every `<name>-<digits>` entry
in whatever directory it was given, with no prompt: `wt _drain-trash ~`
would delete `~/backup-2024` and `~/proj-2` and leave a `~.lock` beside
it. Worktrunk only ever passed `repo.wt_trash_dir()`, but nothing tied
the argument to a trash directory. It now takes no argument and drains
`<git-common-dir>/wt/trash` of the repository it discovers; outside a
repository it fails and deletes nothing. Both spawn sites run it as `wt
-C <git-common-dir> _drain-trash`, since a removal's spawn cwd can be
the empty placeholder of the worktree it just removed (`wt remove -D` of
a bare repository's primary worktree from inside it), which in a sibling
layout is in no repository.

Discovering the repository in the child exposed a second problem:
detached children inherited the parent's git discovery variables. Run as
a `!wt` alias, `wt remove` of the current worktree inherits a `GIT_DIR`
naming that worktree's gitdir, which the removal prunes, so the drain
failed with "not a git repository" and the trash stayed. Background hook
pipelines already failed the same way. `spawn_detached_exec` now scrubs
inherited discovery variables, as every other child whose cwd `wt`
chooses does (`scrub_git_discovery_env_vars`).

Tests: `test_drain_trash_derives_the_trash_from_the_repository` covers
both the scratch-directory case (fails, deletes nothing) and a drain
from `.git/wt`. `test_remove_drains_trash_under_inherited_git_dir`
covers the alias case, and it fails without the scrub.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 18:23:47 -07:00
93beb0670d fix: return one complete JSON result for switch (#4345)
JSON switches now emit one result after synchronous work, including any
--execute command, finishes. Accepted invocations return the existing
success fields, or an object with an `error` string when target
discovery, configuration, directory directives, or execution fails.
Execute output goes to stderr, and child errors retain exit and signal
metadata. Typed Git diagnostics retain captured Git details and recovery
hints, including commands for a branch left behind after failed worktree
creation. Argument errors and picker cancellation produce no JSON;
background hooks remain independent.

Validation: the full project gate passed (5,028 tests, one skipped),
plus focused checks covering early and late failures, child output and
signals, picker behavior, and plain output. Generated help,
documentation synchronization and build, and independent review passed.
The change also removes a synthetic stdin write from an existing
noninteractive alias-refusal test that raced with process exit.

> _This was written by Codex on behalf of max-sixty_

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 17:13:25 -07:00
Maximilian RoosandClaude Opus 5.5 3ec0bf71a1 fix(remove): recheck cleanliness after stopping the fsmonitor daemon (#4456)
Removal's dirty-worktree gate runs before wt stops the fsmonitor daemon,
since the daemon answers that `git status` cheaply. A file written while
the daemon shuts down therefore reached the rename unchecked. With
`core.fsmonitor` configured, removal now runs the gate once more after
the stop, with fsmonitor disabled, which rescans without starting a new
daemon in the worktree about to go.

The first gate stays, so a dirty worktree is still refused off the
daemon's answer with its daemon left running. Under fsmonitor the
post-stop rescan is what a clean removal passes: one full re-stat per
removal there, which also makes `wt` stricter than `git worktree remove`
against a stale daemon answer. Without fsmonitor nothing changes.
`--force` skips both gates, as before.

This narrows the earlier version of this PR, which bypassed fsmonitor
for every removal and stacked on #4454; it now targets `main` on its
own.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 15:53:52 -07:00
Maximilian RoosandClaude Opus 5.5 ab2a1e3a2e fix(remove): warn when a submodule holds commits on no remote (#4460)
Removing a worktree deletes its submodules' module stores, and with them
any commit no remote-tracking ref reaches, including reflog-only ones.
Removal now warns before proceeding:

```
▲ Submodule submod has commits on no remote; removing the worktree deletes them
```

It still removes, so shallow or SHA-fetched pins (which can look the
same) never need `--force`. `--force` skips the check, having already
consented to losing what the worktree holds. The picker removes
silently, as it does for everything else.

This replaces the earlier refuse-unless-`--force` version of this PR,
per the decision to warn instead. The test-only commit routing
`GIT_EXEC_PATH` to Git's real exec path is kept, since `git submodule`
needs Git's helpers when wt runs as `git wt`.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 15:53:48 -07:00
Maximilian RoosandClaude Opus 5.5 af3c278fa9 fix(remove): stop suggesting -D when refusing to remove the default branch (#4535)
`wt remove main` refuses with `Cannot remove the default branch main`,
then hinted `To force-delete, run wt remove -D main`, pointing at the
one outcome the guard exists to prevent. The refusal now stands alone;
`-D` still bypasses the guard for anyone who means it.

This replaces #4455, which would have let `--no-delete-branch` remove
the default branch's worktree; the guard stays as it is.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 15:28:42 -07:00
Maximilian RoosandClaude Opus 5.5 e42f0f6fef Release v0.81.0 (#4534)
Release v0.81.0: version bump and the 0.81.0 changelog section.

Cut from main at 0559edce3. Release checks run on that commit: the local
pre-merge gate passed (5,377 tests), the data-loss surface review was
adjudicated and signed off by the maintainer, the documentation review
findings landed in #4531, and the changelog passed a claim-by-claim
verification run that came back clean. The `nightly` workflow on the cut
commit is the remaining cross-platform gate before merge.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
v0.81.0
2026-10-20 14:12:04 -07:00
Worktrunk Botandworktrunk-bot a4a3063c71 test(remove): retry the drain when a forked child still holds the trash lock (#4530)
The nightly `feature-powerset` job
[failed](https://github.com/max-sixty/worktrunk/actions/runs/39376521570)
in
`git::remove::tests::drain_trash_deletes_staged_entries_once_the_lock_is_free`
(added in #4516) with `assertion failed:
staged_trash_entries(&trash).is_empty()`. This is a race in the test,
not a bug in the drain. After the test drops its lock holder, it expects
the next `drain_trash` to get the lock. But another test in the same
process can fork a child while the holder is open. That child inherits
the descriptor, and the flock stays held until it execs. The drain sees
`WouldBlock` and exits, leaving the deletion to the holder, as designed.
`test_configure_shell_opens_rc_with_exclusive_lock` has the same race on
the rc-file lock.

Both tests now wait for the release through the shared
`testing::wait_for` helper. It polls with a bounded timeout and stops at
the first success, so on Windows the test never asks a handle that
already holds the lock to take it again.

Verification: I reproduced the race with a scratch test that ran the
same lock/release/drain sequence 2000 times while four threads spawned
`true` in a loop. The first drain left the entry behind in 17–20 of the
2000 iterations. With the retry, no iteration left it. Both tests pass
locally, and clippy is clean.

The same window exists in production, but it only delays cleanup: a
staged entry waits in the trash until the next removal's drain. The doc
comment on `trash_drain_running` already accepts a similar window, so
this PR doesn't change the drain itself.

Refs #4509

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-10-20 13:48:59 -07:00
Maximilian RoosandClaude Opus 5.5 0559edce3b fix(signals): stop foreground loops when wt itself receives Ctrl-C (#4533)
## What regressed

Since v0.80.0, Ctrl-C during `wt remove a b c` no longer stops the batch
when the pre-remove hook catches SIGINT and exits normally, as
pre-commit does (`trap '...' INT; exit 130`). Reproduced with a hook
that traps INT, exits 130 and otherwise sleeps, plus a process-group
SIGINT: v0.80.0 stops at `a` and keeps every worktree; current main
removes `b` and `c`, branches included, and runs their hooks. `wt step
prune` did the same with a hook that exits 0 after catching the key:
every candidate was removed and wt exited 0.

Two changes combined. #4400 moved foreground children into the caller's
native job group and followed the shell's wait-and-cooperative-exit
rule, so a child that handles the key keeps its own exit status. #4357
made a multi-target remove continue past a failing target.

## The rule

Max chose the batch-runner convention (make, ninja, cargo) over the
shell's: Ctrl-C that wt itself receives stops the current command. The
terminal delivers SIGINT to the whole foreground job, so wt receives the
key alongside the child. A shell waits and exits only if the child died
of the signal, because the child might be an interactive program using
Ctrl-C as input. A batch runner's steps aren't interactive, and the user
pressing Ctrl-C means "stop the batch". For a destructive loop like
remove or prune, that rule is also the one the data-safety principle
asks for.

The child still handles the key its own way, and wt never signals it for
INT. Once the child exits, the command starts nothing more and exits
interrupted (native SIGINT re-raise / 130), whatever status the child
chose. Numeric exit codes such as 130 are still never read as
cancellation; wt's own receipt is the evidence.

## What changes

- `src/signal_forwarder.rs`: the existing per-operation cancellation
(`CommandOperation`) gains a SIGINT flag beside its SIGTERM one.
Foreground scopes register it, so the scope reports cancellation when
its child exits, and later admissions in the same command are refused.
The output drain's fresh flag, which existed to ignore keys the children
had already handled, is gone.
- Covered loops: hook pipelines (including Warn-strategy post-* hooks),
multi-step aliases, `for-each`, multi-target `remove` and `prune`.
- A command's final interactive child keeps the key as input and its own
exit status: help and `config show` pagers, `--execute` programs and
custom `wt-*` subcommands opt in through `Cmd::hand_off_terminal`
(`TerminalInterrupt::ChildInput`). So does an alias's last serial step
(`ForegroundStdin::HandOff`), since the alias is the whole command;
`agent = "claude"` keeps claude's status after the user stops a turn
with Ctrl-C. Otherwise pressing Ctrl-C in `less`, a REPL started by `-x`
or such an alias, then quitting normally, would turn into exit 130.
Earlier alias steps, concurrent groups and every hook step still cancel.
- Unchanged: between children, idle SIGINT still kills wt natively.
Detached background hooks, timeout-bounded captures in their own process
group and the picker hold no foreground scope. A SIGINT sent only to wt
is still not forwarded to the child; wt waits for it to finish, then
stops. Windows is unchanged: wt installs no console Ctrl-C handler, so
the default handler already ends wt and nothing more starts.
- AGENTS.md "Signal Handling" and the `signal_forwarder` / `shell_exec`
/ `concurrent` module docs state the new rule.

## Verification

- New unix integration tests, each pressing Ctrl-C (a group SIGINT)
after wt has admitted a child that catches it: `remove` with a hook
exiting 130 and with one exiting 0 keeps both targets; a post-start
pipeline doesn't run its next step after a step exits 130; `for-each`
visits one worktree when the child exits 0. All four fail on the old
semantics. `test_alias_last_step_keeps_status_after_caught_ctrl_c`
covers the alias handoff. The exit-0 remove case also fails if the scope
stops reporting the latch and only refuses later admissions, since the
current target would still be removed.
- Existing tests that asserted the old rule now assert cancellation: the
PTY `caught_keyboard_interrupt_cancels_following_step`,
`test_alias_pid_signal_policy` (PID-only INT) and
`test_alias_group_sigint_does_not_escalate`. The children still handle
every key exactly once and wt never dies while they run.
`test_alias_caught_sigint_preserves_successful_descendant_output` is
deleted because its premise is the old rule. The pager and
custom-subcommand cases in
`custom_commands_and_help_pagers_preserve_native_signals` pass
unchanged.
- The alias signal harness moved to `tests/common` as `SignalJob` for
reuse.
- `cargo nextest run --all-features` (5377 passed), `cargo clippy
--all-targets --all-features -- -D warnings`, pre-commit on the changed
files. Manual repro of remove and prune before and after.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 12:31:58 -07:00
Maximilian RoosandClaude Opus 5.5 a4573593db fix: resolve every no-argument default through @, which outside a worktree names HEAD's branch (#4521)
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_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 11:15:23 -07:00
Maximilian RoosandClaude Opus 5.5 1fe07b3145 fix(switch): refuse --path naming the bare repository; drop rm -rf hint for --path (#4532)
Two problems with the new `wt switch --path` flag from #4317, found in
release review.

**Bare repository moved aside.** `wt switch --create x --path proj.git
--clobber` in a bare clone with no worktrees printed `Moved ~/proj.git
to ~/proj.git.bak.<ts> (--clobber)` and created a worktree in the
repository's place. `reject_path_overlapping_worktrees` skipped a
requested path equal to any entry it checks, which is right for a
registered worktree (`validate_worktree_creation` reports it by branch)
but nothing later checks the git common dir. The guard now refuses that
case with `--path <dir> is the repository's git directory`. The template
route has the same exposure and is left to #4461; this guard runs only
for `--path`.

While there, the guard compares paths with `canonicalize_with_parents`
rather than `dunce::canonicalize`, so a deep Windows path and the short
root containing it get the same prefix spelling for `starts_with` (the
#3898 mismatch).

**`rm -rf` hint for a user-named directory.** When the `--path`
directory exists, the hint suggested `rm -rf <path>`, though `--path`
can name any directory, such as a project. For `--path` it now reads `To
place the worktree elsewhere, choose a different --path; to overwrite
(with backup), run wt switch --create --clobber <branch> --path=<path>`.
The template route's hint is unchanged.

**Verification:** reproduced both on a build of `main` and confirmed the
fix on this branch. `test_bare_repo_switch_path_rejects_the_repository`
fails with the old guard (its snapshot shows the `Moved … (--clobber)`
line), and the `switch_path_occupied` snapshot shows the new hint.
`test_switch_path_naming_another_worktree` pins that `--path` naming
another branch's worktree, with `--clobber`, still reports that
worktree's branch and leaves it in place. Ran the switch,
bare-repository and error-display integration tests, clippy, and
pre-commit.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 10:50:24 -07:00
Maximilian RoosandClaude Opus 5.5 13d4d5b4e2 docs: release 0.81 documentation review fixes (#4531)
Applies the documentation review of the 0.81.0 candidate
(v0.80.0..15b1ed10c: CLI help, generated and authored site pages, skill
and plugin copies). Each claim was checked against the code, and the
behavioral ones against a build of this branch on scratch repos.
Generated pages, skill mirrors, `list-v2.json` and help snapshots are
regenerated from their sources.

- `wt hook` "Interactive hooks": says which hooks inherit stdin (a
command running alone in the foreground) and which get empty stdin
(concurrent commands, background `post-*` hooks, prune's fanned-out
hooks). The pass-values-as-arguments example moves to the end of
"Template variables".
- Extending: the hooks/aliases stdin row states the rule in the same
words for both.
- Shell integration: "Why shell integration exists" and "Checking
status" state their content instead of only linking away. "Files
created" again distinguishes appended lines (bash, zsh, PowerShell) from
whole files (fish, Nushell), and notes that the PowerShell profiles are
created if missing.
- `wt step prune` min-age guard: says what the guard prevents, where a
branch-only candidate's age comes from, and when a branch with no reflog
looks new again.
- `wt step squash` backup: covers everything staged (by hand or by
`--stage`), not only changes staged beforehand.
- `wt merge`: the long help defines the source before using it;
`--branch` help says "defaults to the current branch".
- `wt remove` JSON: `detached_worktree` is the detached worktree at the
branch's expected location, which the removal leaves in place.
- `wt switch`: shorter "Custom path" sentence; "Starting list-only"
becomes "Hiding the preview".
- `list-v2.json`: "probe" becomes "check", as in the list help.
- Agent integration page: drops the incomplete Codex hooks sentence;
OpenCode's `worktree.directory` "is ignored", and new branches start
from the default branch.
- Claude Code `WorktreeCreate` (site page and plugin README): the hook
runs plain `wt switch` when the branch already exists, which returns its
worktree.
- Plugin README: the activity-tracking example no longer repeats the
hook list above it.

No finding was skipped. Three were adapted: the squash text names
hand-staged changes as well as `--stage`; the `wt merge` text keeps the
word "source", which later paragraphs use; the plugin README keeps the
example's `wt list` sentence and drops only the repeated mechanism.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 10:50:00 -07:00
Maximilian RoosandClaude Opus 5.5 15b1ed10ce fix(config): keep approvals and [projects] entries saved under v0.80.0 identifiers (#4526)
Since v0.80.0, #4421 changed the project identifier for three kinds of
remote: a non-default SSH port joins the host (`host:2222/o/r`, was
`host/o/r`), hosts are lowercased (`github.com/o/r`, was
`GitHub.com/o/r`), and `git+ssh://` / `ssh+git://` URLs parse
(`github.com/o/r`, was the raw URL). Approvals and `[projects."…"]`
settings saved under the old identifier silently stopped applying. A
non-interactive `wt switch --create` then failed with "Cannot prompt for
approval" for hooks the user had approved, and ignored the project's
`worktree-path`.

`Repository::project_identifier` now returns a `ProjectId` that carries
the current identifier plus, where it differs, the identifier v0.80.0
computed for the same remote. `legacy_project_identifier` in
`src/git/url.rs` is a frozen copy of the pre-#4421 rule. It returns
nothing for an `ssh://` IPv6 remote, whose v0.80.0 identifier
(`[2001/o/r`) collided across distinct hosts.

`matching_keys`, the one matcher behind both approvals and `[projects]`
settings, also matches keys against the legacy identifier and ranks them
below every key matching the current one. Settings under a current key
override legacy ones field by field. Approvals under either key apply,
so approving a new command (saved under the current identifier) keeps
the earlier approvals in force without any migration. The per-project
`wt config approvals` operations (stale approvals in `list`, `clear`,
`clear --stale`) treat the legacy exact key like the current one. Writes
and the displayed identifier stay on the current identifier. Most of the
diff is the read APIs switching from `&str` to `&ProjectId`.

For the port case this restores v0.80.0's sharing. The legacy key
`host/o/r` is also the live key of the same project on port 22, so a
repo on `host:2222` reads approvals and settings saved for the port-22
remote, including ones saved after upgrading, and clearing from it
removes them. #4421 had separated those; telling old entries from new
ones would need provenance in `approvals.toml`, which this PR doesn't
add. Keys written under `host:2222/o/r` apply only to that remote.

Verification: I reproduced the regression with the v0.80.0 and main
binaries for all three remote forms, using approvals and `worktree-path`
keyed under the old identifier. On this branch, `wt switch --create`
(stdin closed) runs the approved hook in the legacy `worktree-path`
again, as on v0.80.0. New tests: an integration test running `wt switch
--create` with a case per remote form, an updated identifier-selection
test, and unit tests for the legacy derivation, ranking and clear. The
integration tests fail when the legacy identifier is withheld. Lib and
bin tests, the approval, config, hook, merge and prune integration
tests, clippy, rustdoc and pre-commit pass.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:40:59 -07:00
Maximilian RoosandClaude Opus 5.5 12d33b3e30 fix(shell): keep the Nushell wrapper working when its stdout is redirected (#4525)
Since #4400 rewrote the Nushell wrapper around `try … finally`,
redirecting the stdout of a `wt` command that prints nothing there
aborts the wrapper. `nu --no-config-file -c 'source init.nu; cd repo; wt
switch --create y o> /dev/null; print $env.PWD'` prints `repo.y` on
v0.80.0, but on main it fails with `nu::shell::cant_convert ... can't
convert nothing to string` at the `try {`, stops the script, and loses
the cd.

Nushell 0.116 fails to convert a `try … finally` that evaluates to
nothing under `o>` or `o+e>`. A plain `try`, `| ignore` and `e>` are
unaffected. The wrapper's `try … finally` now evaluates to a record
holding the exit code and captured stdout, and the wrapper returns
stdout or propagates the failure after the block, as v0.80.0 did. A
failure's stdout still prints inside the block, so a failing cd
directive can't drop it, and the `finally` still applies the directive
and removes the temp files on Ctrl-C. Returning `""` from the empty
branch would also have avoided the error, but it prints a blank line
when `wt switch` is the last command of a `nu -c` script.

Verified with nu 0.116.0 against v0.80.0, main and this branch: `o>
/dev/null`, `o> file`, `| ignore`, `e> /dev/null`, `o+e> /dev/null`,
plain and captured (`let x = (wt switch …)`) calls, a stdout-producing
command redirected and piped, a failing command (exit 1 with no source
trace, with and without `o>`), and `--execute` under `o>` all match
v0.80.0 on this branch. Main fails the `o> /dev/null`, `o> file`, `o+e>`
and `--execute` under `o>` cases. An interactive PTY session runs `wt
switch` with and without `o> /dev/null` and changes directory both
times. The new `test_nu_wrapper_redirected_stdout_applies_cd` fails on
main with the same `cant_convert` error and passes here. The nushell,
shell-wrapper, init and foreground-job integration tests (291) pass with
`--features shell-integration-tests`.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:40:43 -07:00
Maximilian RoosandClaude Opus 5.5 d890a16645 fix(templates): add the tojson filter for structured vars (#4524)
Since the minijinja 3 upgrade in #4442, `{{ vars.cfg }}` renders a JSON
object or array var in Python style (`{'port': 3000}`) where v0.80.0
rendered JSON, and `{{ vars.cfg | tojson }}` fails with "unknown filter"
because minijinja's `json` feature was off. Since #3129 removed JSON on
hook stdin, templates are how hooks get structured values, so they had
no way to pass one to `jq` or `curl -d`.

This enables the `json` feature and documents `tojson` beside the vars
dot-access example in `wt hook --help`. `tojson` writes `'`, `<`, `>`
and `&` inside strings as `\u` escapes, which JSON parsers decode; the
shell formatter still single-quotes the result, so `-d {{ vars.config |
tojson }}` passes one argument.

Two adjustments come with the feature. It makes minijinja choose JSON
autoescaping from a template name ending in `.json`, `.js`, `.yaml` or
`.yml`, as it already did HTML escaping for `.html`. Worktrunk's
template names are config keys, so a custom column named `json` would
have rendered JSON-quoted cells, and one named `html` already rendered
HTML-escaped cells; the shared template environment now turns name-based
autoescaping off. minijinja's `tojson` also writes an undefined value as
`null`, so a wrapper rejects it the way printing does, and a mistyped
`vars` key errors instead of sending `null`.

Verified by rerunning the release-review repro against the branch
binary: `{{ vars.cfg | tojson }}` now renders `{"list": [1, 2], "port":
3000}`, and a custom column named `json` or `html` renders the raw
value. New coverage: a doc-template test for the documented `curl`
example in POSIX mode, a missing-key `tojson` error case, and the
custom-column test now uses a header named `json`. Each of the three
fails with its part of the change reverted.

Bare `{{ vars.cfg }}` still renders Python-style; `tojson` is the
supported way to get JSON.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:40:22 -07:00
Maximilian RoosandClaude Opus 5.5 4874f33c29 fix(alias): report an alias child killed by a signal other than INT/TERM (#4523)
Since v0.80.0, an alias whose child dies by a signal other than
SIGINT/SIGTERM (for example `crash = "kill -KILL $$"`, or a segfaulting
program) exits 128+N with no output. v0.80.0 printed `✗ Killed by signal
N`. #4352 and #4400 limited interrupt classification to SIGINT/SIGTERM,
so these deaths now reach `alias_error_wrapper`, which turns every child
exit code into a silent `AlreadyDisplayed`. wt exits normally rather
than dying by the signal, so the shell reports nothing either.

`alias_error_wrapper` now maps a child exit with a physical signal to
`WorktrunkError::Interrupted`, the variant custom subcommands (`wt-foo`)
already use for the same case. It renders `Killed by signal N` and exits
128+N. SIGINT and SIGTERM still short-circuit earlier and are re-raised
for the shell to report, as AGENTS.md "Signal Handling" specifies, so
`kill -TERM $$` stays silent from wt. Hooks and `wt step for-each`
already report the signal in their own failure lines and are unchanged.

Verified with the release-review repros: SEGV and KILL aliases print `✗
Killed by signal 11` / `9` and exit 139 / 137, matching v0.80.0, for
single, multi-step and concurrent aliases; `exit 2` stays silent. The
new unix-only `test_step_alias_killed_by_signal` snapshot fails without
the fix.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:40:07 -07:00
Maximilian RoosandClaude Opus 5.5 9f08a95720 fix(commit): stage before pre-commit hooks as well as after (#4520)
Since v0.80.0, pre-commit hooks during `wt merge` and `wt step squash`
no longer see the uncommitted changes in the index. #4321 moved the
squash path to run hooks before staging so a formatter hook's edits
would land in the squash commit. A hook that reads the index
(`pre-commit run`, lint-staged, `git diff --cached`) then saw nothing
staged and passed, so a merge that v0.80.0 blocked committed the
offending changes.

All commit paths now stage, run the pre-commit hooks, and stage again
with the same `--stage` mode. Hooks see the changes, formatter edits
still land in the commit, and the generated commit message reads the
post-hook index. The second staging warns only about untracked paths the
hooks created. This also applies to `wt step commit` and `wt merge
--no-squash`, which ran hooks before staging even in v0.80.0, so an
index-reading hook now blocks those commits too, and a failed hook
leaves the changes staged there as it already did for squash.

Verified with the release-review repros: a `git diff --cached` gate and
a pre-commit-framework `pre-commit run` gate both block `wt merge` and
`wt step squash` again, as on v0.80.0, where main committed the changes.
A `sed` formatter hook's edit is in the commit and in the prompt the
commit-message command receives, with a clean tree afterwards. The new
`test_pre_commit_hook_sees_staged_changes` covers `wt merge` and `wt
step commit` and fails without the fix.
`test_step_commit_refuses_hook_created_conflict` now unstages in its
hook, because `git merge` refuses to start once the index is staged. The
other snapshot changes move the auto-staging warning ahead of the hook
output.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:39:44 -07:00
Maximilian RoosandClaude Opus 5.5 6826904e3d fix(shell_exec): write small command input to a pipe, not a temp file (#4519)
Since v0.80.0, an unusable `TMPDIR` broke every command that passes
input to a child: background hooks never spawned ("Failed to prepare
detached input"), `wt step for-each` failed, `wt list` lost the
working-tree diff of a worktree with untracked files (`git add
--pathspec-from-file=-` failed), and background `wt remove` exited 1
after already removing the worktree. #4400 moved this input from a pipe
to an anonymous temp file, even when it was empty.

The temp file exists so that no writer thread can block on a child that
doesn't read its input. A pipe meets that requirement when the whole
input fits in its buffer, so on Unix `buffered_stdin` now writes the
input into a fresh pipe with a nonblocking writer before spawn and
closes the writer. Only input larger than the pipe buffer (64 KiB on
macOS and Linux) falls back to the temp file, and that case still needs
a usable `TMPDIR`. Windows keeps the temp file.

Verified with the release-review repros: with `TMPDIR=/nonexistent/dir`,
the post-start hook runs, `for-each` succeeds, `wt list` shows the dirty
worktree, and `wt remove` exits 0, matching v0.80.0. The existing list
TMPDIR test now adds an untracked file and requires empty stderr, and a
new remove test covers the detached cleanup; both fail without the fix.
The existing `test_cmd_with_stdin` covers empty input and a 1.7 MB input
that takes the temp-file path.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:39:28 -07:00
Maximilian RoosandClaude Opus 5.5 54b6de1b52 fix(shell): skip the shell config scan when the install offer can't prompt (#4522)
Since v0.80.0, every `wt switch` without an active shell wrapper spawns
`pwsh` when PowerShell is installed, adding about 150-200 ms per call.
That includes non-interactive calls such as `wt switch -c x --format
json` from agents. #4422 made the shell config scan ask the installed
`pwsh` for its profile path, and `prompt_shell_integration` ran that
scan before checking whether it could prompt. When it can't prompt (no
TTY, `--execute`, or a previously declined offer), both outcomes of the
scan print the same install hint.

The can't-prompt check now runs before the scan, so those calls spawn
neither `pwsh` nor `nu`.

Verified with logging `pwsh`/`nu` shims on PATH and the `-vv` trace: a
non-TTY `wt switch b1` and `wt switch -c x1 --format json` spawned `nu`
and `pwsh` on main and neither on this branch, and printed the same
hint. Under `script` (a TTY), the switch still runs both probes and
shows the install prompt. `test_switch_hint_skips_shell_config_scan`
asserts through mock call logs that neither probe runs, and fails
without the fix. It replaces `test_switch_offer_after_powershell_query`,
which tested cancelling the scan's `pwsh` query in a non-TTY switch, a
query that no longer happens there. That cancellation coverage moves to
a PTY test, `test_offer_stops_on_cancelled_powershell_query`: on a
terminal, SIGINT or SIGTERM in the query stops the switch with no offer,
and an ordinary exit 130 still falls back to the offer.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:39:00 -07:00
Maximilian RoosandClaude Opus 5.5 7d59f69ea9 fix(copy-ignored): give copied files their source's mtime (#4518)
Since v0.80.0, `wt step copy-ignored` produces stale cargo builds. #4319
stamps every copied file with one time taken after `git worktree add`,
so a copied `target/` looks newer than the sources that checkout just
wrote, and cargo treats it as up to date. Repro: build v1 in main,
commit v2 without rebuilding, `wt switch --create feat`, `wt step
copy-ignored`, `cargo build`. On main cargo finishes in 0.00s and the
binary prints v1; v0.80.0 (which kept source mtimes through clonefile on
macOS) recompiles and prints v2.

This gives each copied regular file its source's mtime, as `cp -a` does,
on every platform, and removes the stamp parameter. That still covers
#4248's Linux case, where parallel copies ordered files by scheduling:
#4319's own table shows `cp -a` recompiles the same two units as the
stamp. `wt step promote`'s cross-device fallback shares the helper, so
it now keeps mtimes too, like `mv` across filesystems. Symlinks and
directories keep the copy time, as in v0.80.0.

Verified on macOS: the repro above now recompiles and prints v2, and a
tree with 2020-dated ignored files keeps the same mtimes as v0.80.0. The
new integration test copies files with distinct past mtimes through a
directory entry and a top-level entry; it fails on main and passes here.
The read-only unit test now asserts the source mtime.

Not covered, on v0.80.0 either: copying into an existing worktree whose
sources were checked out before the source worktree's build still leaves
outputs newer than those sources, so cargo reuses them.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 08:38:49 -07:00
Maximilian Roos 6cbabac59e Give stdin to the foreground pipeline that owns it (#4451)
Concurrent prune hooks and picker removals can compete with the caller
for terminal input. Carry stdin ownership through foreground execution:
standalone removal and aliases inherit input, while concurrent prune and
picker removal hooks receive closed stdin.

Validation: 156 focused tests pass under Rust 1.98. Claude source review
is clean; Codex reviewed the import-only follow-up.

> _This was written by Codex on behalf of max-sixty_
2026-10-19 22:20:35 -07:00
Maximilian RoosandClaude Opus 5.5 25d0c44b0b fix(remove): drain the trash with one background process per repository (#4516)
A prune of many worktrees started one `rm -rf` per staged worktree. On a
193-worktree prune those processes competed for the disk: together they
deleted about 1,500 files/s on 3 cores, while a single `rm` alone
managed 3,000–5,400 files/s on under one core. Read-only directories
(`dr-xr-xr-x`, as installers leave them) also made `rm -rf` fail, so
those entries stayed in `.git/wt/trash/` and every later sweep retried
them.

Removal now starts a hidden `wt _drain-trash`, which holds
`.git/wt/trash.lock` and deletes every staged entry, including entries
staged while it runs. A removal or sweep that finds the lock held starts
nothing, so a prune runs about one deleter. The sweep after `wt remove`
drains leftovers immediately rather than waiting 24 hours. Priority is
unchanged (`taskpolicy -b` on macOS).

The drain uses wt's own walker (`src/remove_dir.rs`), which `wt remove
--foreground` and `wt config state clear` also use:

- On Unix it opens each directory relative to its parent's descriptor
with `O_NOFOLLOW` and unlinks relative to the holding directory. The old
path-based walker could follow a directory swapped for a symlink
mid-walk and delete outside the tree; a swap-race script reproduced
that, and the new walker lost nothing in 20 runs.
- It grants the owner `rwx` on each directory it enters, so read-only
and unreadable trees are deleted, never changing a symlink's target.
Linux's `fchmodat` has no `AT_SYMLINK_NOFOLLOW`, so there it opens the
directory with `O_PATH | O_NOFOLLOW` and changes the mode through
`/proc/self/fd`.
- Subdirectories are removed sequentially, so open descriptors stay
bounded by depth. On a 199k-entry pnpm `node_modules` it deleted about
twice as fast as `rm -rf`.
- On Windows it uses `std::fs::remove_dir_all`, which removes junctions
without following them.

> _This was written by Claude Code on behalf of max-sixty_

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 22:12:31 -07:00
Worktrunk Bot 4cb4267619 feat(templates): add expected_worktree_path_of_branch() template function (#4502) 2026-10-18 22:33:02 -07:00
Maximilian Roos 5e5c65b2bb fix: identify detached worktrees by their paths (#4498)
`wt step for-each` identified detached worktrees by their directory
basename, so Codex checkouts all appeared as `worktrunk (detached)`.
Show the full display path for every detached checkout, including a lone
checkout with a generic directory name. Labels now identify the location
independently of other worktrees.

Off-template branches use `branch @ path`; branches at their configured
location use the branch name. Failure messages reuse the label's
styling. Extend the integration snapshot with a lone generic directory,
another detached checkout, and an off-template branch.

Validation: 21 focused integration tests and all pre-commit checks pass.
Opus reviewed the implementation and live success/failure output.

> _This was written by Codex on behalf of max-sixty_
2026-10-17 22:54:10 -07:00
Maximilian Roos 55d302dbb2 fix(switch): return wt switch - to the worktree it left, not the first checkout of its branch (#4497) 2026-10-17 22:33:46 -07:00
Maximilian RoosandClaude Opus 5.5 0c75655c6c fix: resolve worktree arguments once and pass the resolved worktree through (#4496)
Follow-up to the survey on #4493. Several commands resolved a worktree
argument, kept only the branch or only the path, and looked the other
half up again. Each re-lookup could disagree with the first. This
resolves the argument once and passes the resolved worktree through.

| Case | Before | After |
|---|---|---|
| `wt switch origin/feature` (`feature` has a worktree) | pre-switch
hook got `branch=origin/feature` and no `target_worktree_path` | hook
gets `branch=feature` and the worktree path |
| `wt step promote <second copy>` of a branch checked out twice | acted
on the first copy, failed partway, left the main worktree and that copy
detached | refuses before touching anything, listing both checkouts |
| the same with no argument from the second copy, or with the default
branch checked out twice | same partial failure | same refusal |
| `wt switch @` from a second copy or a detached worktree | landed in
the first copy, or errored | `already_at` the current worktree |
| bare-repo worktree-path warning for `@` / `-` / `pr:N` | skipped
through a hand-kept list of shortcuts | names the branch the shortcut
resolves to; the list is gone |

### `wt switch`

`SwitchTarget` holds the resolved destination (an existing worktree, or
a branch to create one for) plus the forge's answer for `pr:`/`mr:`. The
bare-repo warning, the pre-switch hooks, and `plan_switch` all read it,
so the hooks no longer run their own copy of resolution. Arguments other
than `pr:`/`mr:` and `--create` names go through
`Repository::resolve_worktree`, which is what makes `@` resolve by path;
the remote-prefix strip applies to a `BranchOnly` result.

A pre-switch hook can change what the argument names: the fetch-if-stale
hook the docs suggest makes a remote-only branch appear. So when a hook
actually ran (`execute_hook` now reports whether one did), the pipeline
locates the argument again through the same `SwitchTarget::locate`, on a
fresh `Repository`, and plans against that. The forge is not queried
twice. `--base` and `--create` validation still run after the hooks.

Two behaviour changes follow. Naming errors (`wt switch -` with no
history, a path holding no worktree) now fail before the pre-switch
hooks run rather than after. And when a hook ran, the rest of the switch
reads repository state as the hook left it, `.config/wt.toml` included.

### Promote and the other `--branch` callers

`Repository::require_worktree` returns the branch along with the path,
so `CommandEnv::for_selector`, `copy-ignored`, and promote use the
resolved pair instead of looking one up from the other. Promote resolves
every route (argument, `@`, `^`) to a worktree and refuses when either
branch is checked out more than once.

### Not covered

`wt switch -` still records the previous location as a branch name, so
it can't return to the second copy of a duplicated branch or to a
detached worktree. Changing what the history records is a separate
change.

### Testing

New integration tests cover each row above, plus a pre-switch hook that
fetches, with both `late` and `origin/late`. The hook-fetch tests also
pass on `main`; they pin the behaviour that resolving before the hooks
could break. Every other new test fails on `main`. The full pre-merge
gate passes locally. Codex and a separate Claude agent reviewed it, the
latter twice.

> _This was written by Claude Code on behalf of max-sixty_

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-17 21:27:39 -07:00
Maximilian Roos 4416f64e46 Honor resolved paths and forge settings (#4495)
Several paths reconstructed default values instead of consuming the
configured or server-provided result. This could configure an unusable
fork push URL, recommend editing the wrong zsh file, or report
misleading worktree information.

- Preserve Gitea's API clone URLs for fork pushes and missing-remote
suggestions, including HTTP schemes, ports, and deployment paths.
- Scope GitHub and GitLab protocol lookups to the selected host.
- Name the resolved zsh configuration path and selected command in
compinit advice.
- Compare prune candidates through project-config resolution, so shared
absolute overrides do not falsely imply different hooks.
- Deduplicate statusline branches only when a linked checkout still
matches its configured path and its displayed directory contains the
branch. Main checkouts and checkouts whose branch has drifted from the
configured path retain the branch label.

The audit followed the default-template assumption fixed in
[#4491](https://github.com/max-sixty/worktrunk/pull/4491).

Validation: regression coverage for the affected checkout, shell, prune,
and statusline behavior; the project pre-merge gate; and independent
code review with live CLI checks of custom directory names and ZDOTDIR
installation.

> _This was written by Codex on behalf of max-sixty_
2026-10-17 16:22:41 -07:00
Maximilian Roos 1e2b627a97 docs(statusline): clarify the footer spacing allowance (#4494)
Clarify that the five-column margin approximates Claude Code's footer
spacing: COLUMNS contains the full terminal width, while neighboring
content uses variable additional space that Claude Code handles by
truncating the statusline. Also correct the command name and the
description of direct TTY detection. Comments only; runtime behavior is
unchanged.

> _This was written by Codex on behalf of max-sixty_
2026-10-17 15:44:08 -07:00
Worktrunk Botandworktrunk-bot 00cf0ed9ea fix(switch): name the configured worktree path in the bare-repo warning (#4491)
In a bare repo at a hidden path (e.g. `project/.git`), `wt switch` warns
that the configured `worktree-path` will place worktrees badly. The
"worktrees will be at …" path in that warning was hard-coded to the
default template's `{{ repo }}.{{ branch }}` shape, but the warning
fires for any template that references `{{ repo }}`. So a custom
template got a wrong prediction:

```
worktree-path = "{{ repo_path }}/../{{ repo }}-wt/{{ branch | sanitize }}"

▲ Bare repo at project/.git — worktrees will be at project/.git.feature
✓ Created branch feature and worktree @ …/project/.git-wt/feature
```

The example is now computed with `compute_worktree_path`, the same
function the switch uses to place the worktree. It is shown relative to
the project's parent, so the default template's output is unchanged (the
existing `bare_repo_worktree_path_prompt_non_interactive_warning`
snapshot still passes).

`test_bare_repo_worktree_path_warning_uses_configured_template` sets the
template above and asserts that the warning names
`project/.git-wt/feature` and that the worktree lands there. Before the
fix, it fails with the `.git.feature` message.

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-10-17 15:19:22 -07:00
Worktrunk Botandworktrunk-bot ca0563dc8d feat(plugin): route OpenCode 2 worktrees through wt switch and wt remove (#4489)
Under OpenCode 2, the plugin that `wt config plugins opencode install`
writes now registers a `worktrunk` worktree strategy. Worktrees that
OpenCode creates and removes then go through `wt switch --create` and
`wt remove`, the same way the Claude Code plugin's
`WorktreeCreate`/`WorktreeRemove` hooks already route them. This was
requested in #4488. I ran the strategy locally against a scratch repo
with this branch's `wt` and a fake OpenCode context. I haven't run it
inside a real OpenCode 2 session, which CI can't drive.

How each callback maps
([`dev/opencode-plugin.ts`](https://github.com/max-sixty/worktrunk/blob/1c906f5599d7a16df832c56c51aa82d13c82bbd3/dev/opencode-plugin.ts)):

- **create**: runs `wt switch [--create] <name> [--base <ref>] --no-cd
--format=json` in the source checkout and returns `.path`. OpenCode's
`branch` input is a [starting ref, not a branch
name](https://github.com/anomalyco/opencode/blob/dev/packages/plugin/src/worktree.ts),
so `<name>` is the basename of the directory OpenCode suggests (the name
the user typed, or a generated slug). The path comes from
`worktree-path`, since OpenCode accepts a different directory than the
one it suggested. An existing branch is reopened, as in #4487. Passing a
starting ref for an existing branch is refused rather than ignored.
- **remove**: runs `wt remove --foreground [--force] <dir>`. It does
nothing if the checkout is already gone.
- **list**: reads `git worktree list --porcelain -z` and reports the
first record as `root`. Bare and prunable entries are skipped.

Things a maintainer may want to weigh:

- **On by default.** OpenCode selects a strategy as soon as a plugin
adds one. Every OpenCode 2 user with the plugin installed switches to
worktrunk-managed worktrees, and OpenCode's `worktree.directory` setting
stops applying. This matches the Claude Code plugin. The docs page says
so.
- **No force prompt on a dirty worktree.** OpenCode only offers to force
when the error is an instance of its own `Worktree.OperationError`
([`operationError`](https://github.com/anomalyco/opencode/blob/dev/packages/core/src/worktree.ts)
uses `instanceof`). A standalone plugin file can't import that class:
the CLI's runtime shim for `@opencode/plugin` doesn't export `Worktree`.
A dirty removal fails with worktrunk's own message instead (`Cannot
remove worktree: … has uncommitted changes`), and nothing is deleted.
- **Default base.** With no starting ref, the new branch starts from
worktrunk's default (the default branch). OpenCode's `git` strategy uses
the source checkout's HEAD instead.

<details><summary>Local check</summary>

A Node harness imported the plugin, called `setup` with a stub
`ctx.worktree.transform`, and ran each callback against a fresh repo
with `target/debug/wt` on PATH:

- create → `ocrepo.brave-tiger` (the `worktree-path` default), and
`list` returned root + that worktree
- create with `branch: "brave-tiger"` → a second worktree based on it
- create for an existing branch with a starting ref → refused. Without a
ref → reopened the existing worktree
- remove of a dirty worktree → wt's error. With `force` → removed. A
repeat remove → no-op
- final `list` → root only

`test_docs_are_in_sync` and the 14 `opencode` integration tests pass.

</details>

Closes #4488

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-10-17 15:06:01 -07:00
Worktrunk Bot 2d10b78242 chore: correct stale comments and make the orphan-branch prune test keep an unmerged orphan (#4490) 2026-10-17 12:57:12 -07:00
Worktrunk Bot d14f217c66 fix(switch): resolve a worktree path for pre-switch hook variables (#4493) 2026-10-17 12:50:24 -07:00
Worktrunk Bot 56890db5a5 fix(plugin): reopen an existing worktree from the WorktreeCreate hook (#4487) 2026-10-16 13:39:32 -07:00
Worktrunk Bot a633331f42 chore: correct stale help-rendering docs and drop an unused table indent parameter (#4484) 2026-10-16 10:33:08 -07:00
Worktrunk Bot bcd42cb7b5 test(copy-ignored): set the comparison file's mode instead of inheriting the umask (#4485) 2026-10-16 10:28:38 -07:00
Worktrunk Bot b43e44d17c fix(picker): show an orphan branch's commits in the log tab (#4470)
> _This was written by Codex on behalf of max-sixty_
2026-10-15 20:34:31 -07:00
Worktrunk Bot 7c265fc730 Note in wt switch docs that Alt is Option on macOS (#4483)
> _This was written by Codex on behalf of max-sixty_
2026-10-15 20:34:27 -07:00
dependabot[bot] aa828a3716 chore: bump taiki-e/install-action from 2.87.27 to 2.87.28 (#4475)
> _This was written by Codex on behalf of max-sixty_
2026-10-15 20:34:01 -07:00
Worktrunk Bot 0149f79e10 chore: update tend workflows (0.3.13 → 0.3.14) (#4478)
> _This was written by Codex on behalf of max-sixty_
2026-10-15 20:33:56 -07:00
Worktrunk Bot 0ec7b6d52a fix(tests): stop wt immediately in the startup-interrupt foreground test (#4477) 2026-10-15 14:16:54 -07:00
Worktrunk Bot 8ba948e2ca chore: correct stale comments and tighten a statusline width test (#4479) 2026-10-15 13:50:46 -07:00