Commit Graph
155 Commits
Author SHA1 Message Date
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
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 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 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 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
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 3e17648ae4 Preserve native Git paths and pass removal arguments without shell interpolation (#4453)
Lossy path decoding and shell interpolation can change the filesystem
target. Preserve native Git paths, carry native argv through the
existing command runner, and pass cleanup paths as positional arguments
to fixed scripts. Remove the path-conversion errors and duplicate
detachment code.

Use the existing Rust branch-deletion logic in the detached fallback,
replacing the shell topology parser. Capture the invoking target and
expected tip before scheduling; recheck live checkout ownership before
deleting. This incorporates and supersedes
https://github.com/max-sixty/worktrunk/pull/4462.

Validation: 272 focused tests pass under Rust 1.98. Claude reviewed the
source; its technical findings are addressed, with the follow-up
reviewed independently by Codex.

> _This was written by Codex on behalf of max-sixty_
2026-10-12 19:28:25 -07:00
Worktrunk Botandworktrunk-bot 6b0f8e2bdb fix(shell): discover the Unix PowerShell profile from the installed pwsh (#4422)
On Unix, shell installation now asks the installed PowerShell runtime
for `$PROFILE.CurrentUserCurrentHost`, so a custom `XDG_CONFIG_HOME`
selects the profile PowerShell actually loads. Install, uninstall and
configuration detection share the cached result. The local query uses
`-NoProfile`, disables telemetry and update checks, and uses the
existing five-second probe timeout. Missing, failing or invalid runtime
output retains the conventional fallback. Windows continues to use the
known Documents folder candidates for both PowerShell editions.

Native SIGINT/SIGTERM cancels installation before profile writes,
including when descendants keep the probe's output pipes open. The
shared timed-command primitive now observes the child's native terminal
status without reaping its leader until process-group teardown
completes, preserving the existing process-ID safety guarantee. Typed
interruption also propagates through diagnostics, switch/remove
warnings, and installation offers before another probe or hint mutation
starts.

Validation covers custom-XDG installation and removal,
malformed/unavailable runtime fallback, native interruption versus
ordinary exit 130, pipe-holding descendants, bounded timeouts, and real
pwsh profile discovery without executing user profiles. Regression tests
exercise both the shell-installation flow and the shared timeout
primitive.

An obsolete profile previously written under `~/.config` while a custom
XDG location was active is no longer an install/uninstall candidate;
PowerShell did not load it, and treating it as configured would preserve
the original bug.

Closes #4419.

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

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-10-11 03:12:05 -07:00
Maximilian Roos 160071dcd4 fix(shell): use installation status for activation advice (#4343)
Merge and remove recommend restarting when the current shell's
integration is installed but inactive, and installation when it is
missing or outdated. The installer’s existing scan now also owns the
installed-state checks used by warnings and first-run advice; the
separate detector is removed. This handles current fish and Nushell
wrappers and recognizes legacy fish integration as needing migration.

Completion-file inspection belongs to installation planning. An
unreadable completion path no longer makes an installed wrapper appear
absent or prevents config status reporting. Installation retains
completion previews and preserves a file created after confirmation was
shown.

Validation: actual Claude full review found no material code downsides.
Real-command and PTY regressions cover current versus login shell,
legacy/current fish, Nushell, missing/directory completion paths,
accepted installation, and completion-file races. The full project gate
passed: 5,205 tests passed and one skipped, with Clippy, formatting,
documentation, lockfile and doctest checks passing.

> _This was written by Codex on behalf of max-sixty_
2026-10-10 15:27:46 -07:00
Maximilian Roos 62b82ae923 Explain discarded changes and provide safe squash recovery (#4347)
Removing a dirty worktree recommends `git stash -u` when untracked files
need preserving. Forced removal lists the changes it will discard from a
fresh inventory after approved pre-remove hooks. An unreadable index
produces Git’s diagnostic and still permits forced removal; SIGINT and
SIGTERM cancel before deletion and stop the remaining batch through the
existing native cancellation path.

Squashing staged work prints the backup ref and a command to recover its
exact saved commit in a new worktree. Recovery preserves current
branches, staging, and unstaged or untracked files. Git continues to own
the backup and reflog.

Validated against main `913ff0547`: the required pre-merge gate passed
5,208 tests with one skipped, including forced-removal disclosure,
corrupt-index diagnostics, native cancellation, and executed recovery
commands. Formatting, Clippy, documentation sync and doctests pass.
Independent source/caller review found no remaining issues.

> _This was written by Codex on behalf of max-sixty_
2026-10-10 14:06:15 -07:00
Maximilian Roos cd6732e93a fix: preserve native foreground job control (#4400)
Foreground hooks could hang when they changed terminal settings:
Worktrunk created a separate process group without giving it the
terminal, so the kernel stopped the child with SIGTTOU. Foreground
commands now stay in the caller's native job group, consistently for
single and concurrent commands. Terminal access, Ctrl-C and job
suspension follow the shell's native behavior.

### Design

- `signal_forwarder` owns foreground cancellation and child admission.
Native SIGINT/SIGTERM deaths stop later hooks and worktree steps; a
child that catches Ctrl-C keeps its ordinary exit semantics, including
exit code 130. SIGTERM addressed to wt cancels its owned work even when
a child catches it.
- `shell_exec` and concurrent output share that lifecycle. Output drains
stop on cancellation; complete buffered stdin uses an anonymous
temporary file instead of writer threads. Real process pipelines remain
pipes. Buffered stdin therefore requires temporary storage and is
seekable.
- Help and preview pagers use Git's pager selection and the same process
primitives. Interactive pager cancellation propagates silently, and
preview deadlines cover output and child waits.
- Shell wrappers apply directory directives and clean temporary files
while preserving native interrupt behavior. Nushell integration now
requires 0.113 or newer and uses native `finally` cleanup.

Nushell 0.116's `finally` itself can abort a noninteractive script after
Ctrl-C even when the child catches it and exits successfully.
Worktrunk's directory change and cleanup still complete; the same
script-continuation difference reproduces in a minimal Nushell
`try/finally` without Worktrunk.

Bash applies aborted-line cleanup through a writable `PROMPT_COMMAND`.
With a readonly prompt command or `set -a`, it applies ordinary cleanup
while preserving that configuration; Ctrl-C can leave the pending
directory directive unapplied.

The main behavioral coverage uses real children and PTYs: terminal
ownership/settings, raw and caught Ctrl-C, PID-targeted cancellation,
stopped jobs, concurrent output, pagers, and generated shell wrappers.
Module contracts describe ownership and platform differences.

### Validation

The complete project pre-merge gate passes locally, including the
real-shell/PTY suite, Clippy, formatting, locked dependencies, and
documentation checks. The change also received an independent Opus
correctness and simplicity review, with fixes reviewed through
convergence. macOS runtime validation is local; Linux and Windows run in
CI.

Closes #4389. Thanks to @user753 for the reproduction.

> _This was written by Codex on behalf of max-sixty_
2026-10-08 16:31:37 -07:00
Maximilian Roos fc044f985e fix(remove): continue after per-target execution failures (#4357)
A pre-remove hook or synchronous Git failure in one target currently
stops a multi-target removal before later targets are attempted.
Continue with the remaining valid targets, report each ordinary failure,
and return exit status 1 if any target failed. JSON includes successful
targets in execution order, including branch-only removal and the
current worktree executed last.

SIGINT and SIGTERM cancel the batch immediately with exit status 130 or
143. Preserve the underlying error in foreground removal diagnostics so
a captured Git interruption reaches the batch cancellation check.

Validation: 5,068 tests passed (one skipped), doctests and documentation
build passed, and all final pre-commit checks passed. Integration
coverage exercises hook and execution-time removal failures in
foreground/background modes, correct JSON attribution, and hook/Git
interruptions, including a detached checkout. Four Git-interruption
regressions fail against the original executable and pass with this
change; independent review found no remaining issues. Help and generated
documentation checks passed after updating from main.

> _This was written by Codex on behalf of max-sixty_
2026-10-03 11:11:05 -07:00
d0594169d4 fix(remove): don't point at a detached worktree removed in the same run (#4313)
#3791 made a branch-only `wt remove` name the detached worktree still
sitting at the branch's path, with a hint to run `wt remove <that
path>`. When the user does that in the same command, `wt remove feature
../repo.feature`, the worktree removal runs first. The branch-only line
then still reports the now-deleted directory and suggests removing it:

```
✓ Removed worktree @ ~/repo.both-detached (detached HEAD, no branch to delete)
○ No worktree found for branch both-detached; a detached worktree is @ ~/repo.both-detached
↳ To remove the detached worktree, run wt remove ~/repo.both-detached
✓ Removed branch both-detached (same commit as main, _)
```

`--format=json` carries the same stale `detached_worktree` path. The
annotation is computed per target inside `validate_remove_targets`,
before the other targets are known. This PR clears it after the loop
when another plan in the same run (`others` or `current`) removes that
path. The check runs after the loop because the path argument can come
before or after the branch. A path target that failed validation isn't
removed, so its hint stays.

`test_remove_branch_and_its_detached_worktree_together` fails on `main`
with the output above and passes with the fix. All 142 `remove::`
integration tests, including the new one, pass locally.

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
Co-authored-by: Claude <noreply@anthropic.com>
2026-09-28 00:29:29 -07:00
5177031444 fix(remove): name the detached worktree a branch-only removal leaves behind (#3791)
`wt remove <branch>` on a worktree whose HEAD has since been detached
reported `○ No worktree found for branch <name>` and said nothing more,
while a directory sat at exactly that branch's path. That line is true —
detaching severs the only link git records between a worktree and its
branch, so the branch really has no worktree — but it reads as "nothing
is there".

The removal now names what it leaves behind:

```console
$ wt remove feature
○ No worktree found for branch feature; a detached worktree is @ ~/repo.feature
↳ To remove the detached worktree, run wt remove ~/repo.feature
✓ Removed branch feature (same commit as main, _)
```

`--format=json` carries the same fact as `detached_worktree` on a
branch-only removal, since the human line goes to stderr and "a script
checking the exit code sees a clean run" was half of what the issue
reported.

The directory is found by matching the `worktree-path` template, which
after a detach is all that still connects the two. That is a weaker
association than the rest of the module draws — the template records
where a worktree *would* go, not that this one belongs to that branch —
and it is why this only ever adds a line. A mention that occasionally
points at a coincidence costs nothing. Three states go unmatched, each
because naming them would mislead: a worktree checked out on some
*other* branch (that branch names it), the main worktree (whose
path-based removal `wt remove` refuses, so the hint would be a dead
end), and a prunable entry (nothing on disk to point at).

<details>
<summary>Why this doesn't refuse the removal, and what changed from the
earlier commits on this branch</summary>

The first four commits made `wt remove <branch>` refuse in this
situation, following the issue's "either remove the worktree, or
refuse". Reviewing the premise rather than the menu, refusing was the
wrong call:

- **Nothing was ever lost.** `SafeDelete` — the default — retains an
unintegrated branch, so the only refs the old behavior deleted were ones
worktrunk's own six-condition integration test defines as lossless. Even
`wt remove -D` on an unmerged branch leaves the commits reachable: a
detached worktree's HEAD is a GC root, and the commit survives `gc
--prune=now` with no branch pointing at it.
- **So the refusal protected nothing in three of four cases** —
`--no-delete-branch`, unintegrated `SafeDelete`, and integrated
`SafeDelete` — and in the fourth the user had typed `-D`.
- **It contradicted the addressing model.** `CLAUDE.md`: a path "names
what a branch cannot (a detached worktree, one of two checkouts of a
branch)". The guard let a branch reach one anyway, via a path template.
- **It cost real work**: one branch with a detached directory at its
path failed a whole multi-branch cleanup.

`detached_worktree_for` survives to find the path; it no longer decides
whether the command runs. The scoping the guard had accumulated over
three review rounds — a branch-existence check, a `deletion_mode` gate —
goes with it, since an extra line of output needs no narrowing.

Two fixes from those rounds stand on their own and are kept:

- **The double-escaped hint path.** `format_path_for_display` already
returns a shell-ready token, so composing it with `suggest_command`
escaped it twice: a worktree under `$HOME` rendered as `wt remove
'~/repo.feature'`, where the quoting suppresses the tilde expansion, and
a path needing real quoting came out carrying literal quote characters.
Three call sites had it, two predating this branch.
`format_path_for_display` now documents the trap, which until then lived
only in `pr_mr_switch_hint`'s docstring.
- **`live_sibling_checkout`'s docstring**, explaining why that predicate
stays on `exists()` rather than the `worktree_is_unusable` union the
rest of the removal path uses: the two disagree only on a present
directory that no longer holds its worktree, and since the predicate
only ever gates a deletion, it takes the conservative test.

</details>

## Testing

`test_remove_branch_whose_worktree_was_detached` pins the behavior —
branch removed, worktree untouched, output naming it — and
`test_remove_json_reports_detached_worktree` pins the machine channel.
Snapshots cover the wording, the `--no-delete-branch` no-op, an
unintegrated branch whose ref is retained, a prunable entry (which is
named nothing, having nothing on disk), a detached main worktree (where
the default-branch refusal is still the accurate answer), and the
multi-target case.

Fixes #3769

Thanks to @chachi for the report — the repro runs exactly as written,
and the diagnosis in it (the branch→worktree lookup, not detached
removal) is what this addresses.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-09-27 23:44:50 -07:00
DDL 96a00efbe1 Fix background force-delete for flag-like branches (#4253)
## Summary

- Pass the branch name after `--` in the detached background
force-delete fallback.
- Add an end-to-end regression test for a plumbing-created `-x` branch
when the staged rename fails.

## Root cause

The rename-failure fallback generated `git branch -D <branch>`. Git
interpreted a valid flag-like ref as an option, so the worktree
disappeared but the branch remained.

## Tests

- Confirmed the new regression test timed out on the old command while
waiting for `refs/heads/-x` to be deleted.
- Confirmed the regression test and all four background fallback
integration tests pass after the fix.
- `cargo test test_build_remove_command`
- `cargo run -- hook pre-merge --yes` (4964 passed, 1 skipped)
2026-09-23 23:55:41 -07:00
DDL c2feef082f Prevent removal of submodule changes hidden by config (#4252)
## Summary

- make worktree clean checks override `submodule.<name>.ignore`
- preserve initialized submodule changes during ordinary `wt remove`
- add an end-to-end regression test for `ignore=all`

## Root cause

`WorkingTree::is_dirty` and `dirty_files` inherited the user's submodule
ignore setting. With `submodule.<name>.ignore=all`, Git reported a
modified initialized submodule as clean. Worktrunk then used the
internally required `git worktree remove --force`, deleting the worktree
and its uncommitted submodule change.

The clean checks now pass `--ignore-submodules=none`, matching the
existing plumbing diff behavior and keeping display preferences out of
destructive safety decisions.

## Verification

- Red: the new test reproduced successful removal and loss of the
modified worktree on the old code
- Green: targeted regression and related tests passed
- `cargo run -- hook pre-merge --yes`
  - 4,963 tests passed
  - 1 skipped
  - fmt, Clippy, doctests, rustdoc, lockfile, and snapshot checks passed
2026-09-23 23:12:07 -07:00
Maximilian RoosandClaude Opus 5 2a4aa28c26 fix(remove): plan no branch deletion for an orphan worktree's unborn branch (#4233)
An orphan worktree (`git worktree add --orphan`) has an unborn branch
until its first commit: `HEAD` names `refs/heads/<branch>`, but no such
ref exists. `wt remove` planned a branch deletion for it anyway, so it
misreported the branch or failed:

- A live orphan worktree: `wt remove fresh` printed `↳ Branch unmerged;
to delete, run wt remove -D fresh`, a command that then fails with `No
branch named fresh`. With `--foreground` it removed the worktree and
then exited 1 with git's `fatal: Needed a single revision`.
- A stale one (directory or `.git` gone): `wt remove fresh` printed `✓
Pruned stale worktree for fresh` followed by `○ Branch fresh retained;
has unmerged changes` and the same `wt remove -D` hint.

Now the removal planner treats an unborn branch as having nothing to
delete and plans `Keep` for it, the way it already handles a branch that
a sibling checkout still uses. The output is just `✓ Removed fresh
worktree` (or `◎ Removing fresh worktree in background`) or `✓ Pruned
stale worktree for fresh`. The planner reads this from the ref snapshot
it already holds, so it adds no git call. The picker's removal goes
through the same planner.

`test_remove_orphan_worktree` removes a live and a stale orphan
worktree, each with a remote-tracking branch of the same name. The
remote branch catches a check that counts remote branches, which would
take the branch for existing.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 02:36:57 -07:00
Maximilian RoosandClaude Opus 5 3de0b5f29a fix(prune): unregister stale worktrees whose directory remains (#4228)
Git calls a worktree entry prunable once the `.git` its registration
names is gone. That happens when the whole directory is deleted, and
also when only the `.git` file goes: macOS's `$TMPDIR` sweep deletes
idle files and keeps directories, which left two such checkouts
registered in a real repo. Worktrunk unregistered stale entries with
`git worktree remove`, which refuses an entry whose directory remains
(`validation failed … .git does not exist`, `--force --force` included).
#4226 stopped that from failing `wt step prune` by skipping the entry,
so it stayed `⊟` forever, and `wt remove` refused it with
`WorktreeMissing`.

`Repository::prune_worktree_entry` now reproduces `git worktree prune`
for the one named entry. Under the registry write lock it finds the
registration whose `gitdir` names the path, repeats git's
`should_prune_worktree` test (no `locked` file, nothing at the recorded
`.git`), and deletes `.git/worktrees/<id>`, which is git's
`delete_git_dir`. The directory and any files in it stay. The test runs
at deletion time, so an entry locked or reconnected since the scan is
refused rather than unregistered.

No git command does this for one entry: `git worktree prune` takes no
path, `remove` and `move` fail validation, and `repair` relinks rather
than unregisters. A repo-wide `git worktree prune` also unregisters
entries `wt step prune` deliberately keeps: branches with unmerged
commits, detached HEADs holding the only reference to their commits
(which `git gc` can then delete), the default branch's worktree, and
unborn orphans. The rationale sits in the `prune_worktree_entry`
docstring.

What changes for users:

- `wt step prune` and `wt remove <branch>` unregister a stale entry
whether its directory is gone or only its `.git` is. `wt remove feature`
on a recreated directory used to fail with `✗ Worktree directory missing
for feature`. It now prints `✓ Pruned stale worktree & removed branch
feature (same commit as main, _)` and leaves the directory in place.
- The picker's branch-only removal now unregisters the stale entry
before deleting the branch. Before, it deleted only the branch, leaving
an entry that named a deleted branch, which `wt step prune` skips as
unborn.
- A worktree path that became a regular file counts as having no `.git`,
matching git, instead of refusing.
- Messages no longer call every stale entry "directory missing". The
switch/merge/push error reads `Worktree for X is stale; its directory or
.git is gone`, the `⊟` legend reads `Prunable (worktree directory or its
.git gone)`, and the retained-branch line reads `Pruned stale worktree
for X`. Where the directory remains, that error's hint offers `git
worktree repair <path>` instead of `git worktree prune`, which would
sweep every stale entry in the repo.

Unregistering deletes the entry's index, per-worktree reflog and any
in-progress rebase, merge, cherry-pick, revert or bisect state. While
the entry exists, `git worktree repair <path>` restores all of it
(recreating the directory first if it went too); afterwards staged files
survive only as dangling blobs. So here worktrunk is more careful than
`git worktree prune`. `Repository::stale_worktree_work` reads the
registration: `diff-index --cached --quiet HEAD` against its index, plus
the same state files `WorkingTree::operation_in_progress` reads, now
shared as `operation_in_progress_at`. An entry holding either is kept:

- `wt step prune` skips it silently, as it skips a dirty or locked
worktree.
- `wt remove` refuses with `✗ Worktree for feature is stale but holds
staged changes` (or `… with a rebase in progress`) and `↳ To discard the
stale worktree, run wt remove -f feature; to restore it, run git
worktree repair <path>`. `--force` waives the check, as it waives a live
worktree's uncommitted changes.
- On an unborn `HEAD` the index is compared against the empty tree, as
`git diff --cached` does, so an orphan worktree with nothing staged
still unregisters. A check that fails for any other reason keeps the
entry.

The deletion-time test in `prune_worktree_entry` closes the gap after
the check: a stale entry has no `.git` to stage through, and one
repaired in between is refused.

Tests: unit tests cover `prune_worktree_entry`'s refusals (live, locked,
unregistered, a `.git` it can't stat), each stale shape (absent,
directory without `.git`, path now a file), and its wait on the registry
lock. Removing either check or the lock fails them. The picker tests
cover both a pruned stale entry and a failed prune that keeps the
branch, `wt remove` on a detached stale entry is pinned to its error,
and a shim that fails the branch's CAS delete checks that prune still
unregisters the entry and reports the kept branch. The two tests that
use a permission bit as the failure trigger skip under root, which
ignores it. The prune and picker tests cover a directory that remains.
`test_prune_surfaces_failing_metadata_prune` now triggers the failure
with a read-only registration directory.
`test_prune_metadata_removals_serialize` and its two git shims are
removed: they intercepted `git worktree remove` teardowns, which this
path no longer runs. For the work guard, a unit test runs
`stale_worktree_work` on clean, staged, bisecting, `--no-checkout` (no
index), unborn-with-a-staged-file and unborn-with-an-emptied-index
registrations. `test_prune_keeps_stale_entries_holding_work` checks that
prune keeps a staged branch entry and a bisecting detached one while
pruning a clean one. `test_remove_stale_worktree_holding_staged_changes`
pins the refusal and checks that `wt remove -f` then prunes the entry
and leaves the files.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-22 01:01:32 -07:00
Maximilian RoosandClaude Opus 5 4594691b3f Remove the cache epoch (#4203)
Removes `CACHE_EPOCH` and the machinery around it, added in #4181.

**Time-sensitive:** 0.79.0 is merged to `main` but not tagged and not on
crates.io, so the epoch has never reached a user. Landing this before
the tag means it never ships.

## What it was protecting

Two corner cases in 0.78.0 made `wt remove` delete an unmerged branch
without `-D`, each needing two conditions at once. Reproduced against
the v0.78.0 binary:

- `diff.relative` set **and** the command run from a subdirectory the
branch's changes sat entirely outside. Run from the repository root with
the same config, 0.78.0 correctly retains the branch.
- `submodule.<name>.ignore` set (git config or `.gitmodules`) **and** a
submodule bump as the branch's only change.

In both, 0.78.0 reports `✓ Removed branch feature (no added changes on
main, ⊂)` and 0.79.0 retains it. #4146 fixed how the answer is computed,
but 0.78.0 cached its wrong answer keyed on the branch and target tips
with no expiry, so the fix can't reach an entry already on disk.

## Why it goes

The epoch fires at most once per repository, on the first command after
upgrading, and pays off only for a user who hit one of those corner
cases *and* has a live cached key *and* then removes that branch.
Against that it carried a stamp file, a tree wipe, a global mutex on
every cache read and write, a documented hole when two versions share a
repository, and a failure path where an undeletable directory left the
reader with exactly the entries the wipe existed to discard.

So nothing replaces it: a repository that hit one of the corner cases
under 0.78.0 keeps that cached answer after upgrading, exactly as it
would have kept it on 0.78.0. `wt config state cache clear` drops it for
anyone who asks. The changelog entry describes both corner cases and
stays descriptive — it names no remediation.

## No new negative behavior

0.78.0 and 0.79.0 read any entry already on disk identically — across
`v0.78.0..HEAD` the key functions, the kind set, the consumers of both
integration probes, and `check_integration`'s priority order are all
unchanged, and no cached struct changed shape. They diverge only on a
cache miss, where 0.79.0 is right and 0.78.0 was wrong. So 0.79.0
without the epoch is a strict improvement on 0.78.0, and at worst a tie.

## Also

- **Release skill:** two rules. A correctness or data-loss entry states
the conditions the bug needed, joined with "and", established by
reproducing against the previous release rather than read off the diff —
without that, an entry like this one reads as though it fired for
everyone. And entries describe: imperative guidance only for a material
issue that affects a sizable share of users, which is rare.
- **`src/summary.rs`:** keeps the caveat that the summary cache hashes
the diff while the prompt sits downstream of that hash, which previously
lived only in the docstring this removes.
- **`CLAUDE.md`:** records that not versioning the cache is the
decision, and that a generator change says in its PR what the old
answers get wrong.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-20 16:45:14 -07:00
Maximilian RoosandClaude Opus 5 f813615551 Release v0.79.0 (#4181)
Cuts 0.79.0 from `75baa2cd3`. Minor bump: `cargo semver-checks` reports
five breaking library lints, so patch is disallowed pre-1.0.

Two commits — the changelog and version bump, plus one fix the release's
data-loss review turned up.

## The cache fix

`has-added-changes` and `merge-add-probe` are keyed on the branch and
target tips with no TTL and no invalidation, so an entry answers for
whatever code wrote it until its key recurs — which on a finished branch
is never.

#4146 moved every diff `wt` parses onto plumbing so display config can
no longer change what it reads. The porcelain reads it replaced wrote
those two kinds, and under `diff.relative` or `submodule.<name>.ignore`
they could record a branch's changes as absent. Nothing clears the cache
on upgrade, so a poisoned entry outlives the fix: `wt remove` reads the
old answer and deletes the branch without `-D`.

The exposure is narrow — it needs one of those two settings, and for
`diff.relative` also a run from a subdirectory the branch's changes sit
outside. The commits stay in the object store; it's the ref that goes.
But nothing about the upgrade clears it, so for an affected repository
the fix in #4146 does nothing until the cache is discarded. Reproduced
against the fixed binary with a hand-written pre-upgrade entry:

```
✓ Removed branch feature (no added changes on main, ⊂)
branch still present? DELETED
```

`CACHE_EPOCH` in `src/cache.rs` versions what the cached values mean.
`ensure_epoch` runs from `cache_dir`, the one funnel every read and
write passes through, and discards a tree stamped with a different
epoch. The lock spans the removal, not just the bookkeeping, because `wt
list` fans the SHA-keyed reads over a thread pool. The sweep attempts
every kind and returns the first error, so one undeletable directory
doesn't strand the rest in `read_dir` order. Both `wt config state
clear` and `wt config state cache clear` drop the stamp with the entries
it describes, so a cleared tree re-stamps on the next command rather
than vouching for whatever lands there next.

`UNVERSIONED_KINDS` exempts `summary`, `ci-status` and `pr-number`, so
an upgrade doesn't charge a model call per branch and a forge round-trip
for a diff fix. `ci-status` and `pr-number` hold the forge's own answer,
so no change to how `wt` computes things can make them wrong. `summary`
is exempt on weaker grounds, stated as such in the docstring: its key
hashes the diff, but the prompt template and `llm::prepare_diff`'s
filtering sit downstream of that hash, so rewording the prompt does
leave a stale summary — accepted because the value is display-only, and
closing it means hashing the rendered prompt rather than bumping the
epoch.

Known residual, deliberately deferred: the stamp records the last
worktrunk to *check* a tree, not what wrote each entry, so a 0.78.0
binary run afterwards writes porcelain answers this one trusts. Closing
that means putting the epoch in each entry's path, which invalidates by
construction and costs the same in a later release. It is named in the
`CACHE_EPOCH` comment.

`TestRepo::assemble` stamps the tree it builds, since a test that seeds
`.git/wt/cache/` by hand means entries this version produced.
`test_remove_branch_only_unmerged_ignores_cache_from_an_older_epoch`
covers the upgrade, a table-driven unit test covers all three stamp
states and the exemption, and both clear handlers are pinned against
dropping their `clear_epoch` call. Each assertion was checked under
mutation rather than left to pass by construction.

## Checks

`cargo run -- hook pre-merge --yes` green (4925 tests). This PR runs the
full cross-platform matrix itself — `full-tests` on macOS, Linux,
Windows and git 2.43.0, plus feature-powerset, nix-flake and the release
targets — and `nightly.yaml` re-runs on the merged tip before the tag,
since the green run on the cut-from tip predates the cache fix.
Changelog verified over three passes against the diffs, the pre-change
files, the rendered docs, and a forced `cargo-semver-checks` run.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-17 21:20:30 -07:00
Maximilian RoosandClaude Opus 5 e13643d698 fix(git): run diffs through plumbing so user git config can't change what wt reads (#4146)
Porcelain `git diff` reads display configuration that changes what it
reports, and `wt` parsed its output. With `diff.relative = true`, `wt
remove <branch>` run from a subdirectory deleted an unmerged branch
whose changes sat outside that directory, reporting "no added changes".
`color.ui = always` and `diff.external` put escape codes or an external
tool's output into the commit, squash, and summary prompts.

Every diff `wt` parses, counts, caches, renders, or sends to an LLM now
runs `diff-tree`, `diff-index`, or `diff-files`, which ignore that
configuration. This follows the plumbing question raised in the review
of #4112.

## Where to look

- `src/git/repository/diff.rs`: `PreparedDiff` is the one path for
rendered and prompted diffs, with working-tree, staged, and commit-pair
sides read from the real index or a borrowed `TempIndex`. It restores
the `git diff` defaults plumbing lacks (rename detection, textconv,
hidden intent-to-add entries), overrides `submodule.<name>.ignore`
(which plumbing still honors), names the output format, and ends
revisions with `--`. `DIFF_PREFIX_OVERRIDES` is gone.
- `src/git/repository/integration.rs`: `has_added_changes_by_sha` runs
`diff-tree --quiet --ignore-submodules=none`, and both sides of the
patch-id squash-merge check pass `--ignore-submodules=none` too.
`BranchDiffSpec` carries a resolved `diff_base`, since `diff-tree` has
no three-dot form and `--merge-base` refuses several merge bases. The
empty tree follows the repository's object format, so a SHA-256
repository can make its first commit.
- `HEAD±`, `main…±`, `changed_files`, `unmerged_paths`, the picker's
per-commit log stats, and the commit, squash, and merge diffstats read
plumbing too, all with `--ignore-submodules=none`. `main…±` sparse
pathspecs now resolve from the repository root.

Two related fixes where user config meets the commands that write:

- `wt merge --no-ff` builds its merge commit with `commit-tree`, which
ignores `commit.gpgSign`; it now passes `--gpg-sign` when that setting
is on.
- `wt step rebase` and `wt merge` pass `--no-update-refs`, so
`rebase.updateRefs` can't move other branches stacked in the rebased
range.

`wt step diff` stays porcelain (`TempIndex::stream_diff`), because it
shows the user git's own view. `has_staged_changes` and the `git status`
checks are untouched, since #4112 rewrites them.

## Behavior users can see

Picker diff previews, LLM summaries, and prompts no longer follow
`diff.external`, `diff.noprefix`, or `color.ui = always`. `main…±`
detects renames whatever `diff.renames` says.

## Testing

New tests cover branch deletion under `diff.relative`, a submodule bump
under `submodule.<name>.ignore = all` (including a squash merge that
dropped or carried the bump), prompts under hostile diff config, a
`main/` directory beside the `main` target, criss-cross merge bases,
intent-to-add entries and renames in the fallback commit message, a
SHA-256 first commit, sparse checkout from a subdirectory, a signed
`--no-ff` merge, and a stacked branch under `rebase.updateRefs`. Each
fails with its fix reverted, except the criss-cross case, whose fix
removed the code path it would revert to.
`diff_tree_failure_is_command_error` covers the integration check's
error branch. Running the suite with a hostile global gitconfig swapped
into the test harness leaves only the harness's own porcelain assertions
and intended display output failing.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 13:58:18 -07:00
DDL 2f2ed12130 fix(git): protect untracked files hidden by config (#4111) 2026-09-15 00:29:49 -07:00
DDL 3a6d9c6238 fix(git): scrub inherited GIT_DIR on worktree-local plumbing (#4082) 2026-09-14 00:33:13 -07:00
Worktrunk Botandworktrunk-bot 3f87fec5a7 Leave the branch template variable unset in a detached worktree (#4010)
## Problem

In a detached worktree, `CommandContext::branch_or_head` substituted the
literal `HEAD` for `{{ branch }}`. `HEAD` is a non-empty string git
happily resolves as a ref, so every guard written around `branch` passed
and the command ran against the wrong thing — the reported case ended in
`git push origin --delete HEAD`. It also disagreed with `wt list
--format=json`, which reports `branch: null` for the same worktree, and
with the hook docs, which say undefined variables error so a template
can guard them.

## Solution

`branch` is now absent in a detached worktree rather than falling back.
`{% if branch %}` guards it the way the docs already prescribe for
`upstream`; an unguarded `{{ branch }}` is an undefined-variable error
naming the template and listing the variables that *are* in scope. This
is the first of the two options in #4009 — the one the reporter picked.

The removal path needed the same treatment on its own:
`spawn_hooks_after_remove` took the removed branch as `&str` and both
detached call sites passed the literal `HEAD`, which
`PostRemoveContext::extra_vars` then applied *after* the base context —
so `post-remove` still saw `branch = HEAD` even with the base fix in
place. It takes `Option<&str>` now. That is the hook where the issue's
own command belongs, so it's covered by its own regression test
(`test_user_post_remove_branch_unset_in_detached_worktree`, which
reproduces `branch=[HEAD]` without the change).

Riding along:

- The `base` and `target` branch names derived from the current branch
follow `branch` and stay unset too — both for a **manual** `wt hook
<type>` and for the `pre-switch` hooks `wt switch` fires, which
previously rendered `base` as an empty string. The directional *path*
vars (`base_worktree_path`, `target_worktree_path`) still apply — the
worktree exists whether or not it is on a branch.
- `vars` is now inserted as the **empty map** when `branch` is absent,
not skipped. Per-branch vars are keyed by branch, so a detached worktree
has none either way (`wt config state vars set` can't even write there —
it goes through `require_current_branch`), but keeping the object
defined means `{{ vars.key | default('x') }}` still renders under
SemiStrict instead of erroring on an undefined `vars`. Same reason
`list::custom_columns` injects an empty map for a branchless row.
- The verbose variables table rendered a detached `branch` as `(unused)`
under `VarScope::Referenced` — the label that means "the scope gate
saved us the work", which is wrong for a cheap var computed regardless.
`ALWAYS_COMPUTED_VARS` in `expansion.rs` marks it `(unset)`, the label
for a var the operation genuinely couldn't supply.
- The `hook` long-help sentence about unset `base` / `target` scoped
them to a manual `wt hook`; both are now operation-driven cases too
(`base` in a `pre-switch` from a detached worktree, `target` in a
removal that lands in one), so it's worded generically and the three doc
mirrors are regenerated.
- The `hook` long-help JSON-context example read `ctx['branch']`
unguarded — the same unguarded case in Python, which now raises
`KeyError`. It uses `ctx.get('branch', '')` and the section says why.
- `target` — the branch the user lands on after a removal — followed the
same rule on review: `PostRemoveContext::new` built it with
`unwrap_or_default()`, so a **detached primary worktree** handed
`post-remove` an empty string and made `wt -v` print `target = ` instead
of `target = (unset)`. It's `Option<String>` now, pushed only when there
is one. `commit` / `short_commit` keep their `""` shape — they predate
this and `PostRemoveContext::new` documents the choice. The `pre-remove`
half of the same removal built its extra vars by hand and had the same
`unwrap_or_default()`; it goes through `TemplateVars::with_target_opt` +
`as_extra_vars` now — the builder `wt hook pre-remove` already used — so
both hooks of one removal agree.
- The `HEAD` literal survives in exactly one place: the background
pipeline's **log file name** (`spawn_hook_pipeline_quiet`), which needs
some string and never reaches a template.

`branch_or_head` had no callers left, so it's deleted.
`TemplateVars::with_base` takes `Option<&str>` and a new
`with_target_opt` sits beside `with_target`, so the optional-branch call
sites keep the POSIX path conversion in the builder rather than
re-inlining it.

## Behavior change worth a look

This is deliberate — it's what the issue asks for — but it turns
previously-working shapes into errors, each pinned by a test that this
PR updates rather than deletes:

- `wt step for-each -- echo '{{ branch }}'` now fails at the detached
worktree instead of printing `HEAD`, and (as with any undefined
variable) the loop stops there. Not a new failure mode: `{{ upstream }}`
already behaved this way at the first non-tracking worktree.
`test_for_each_detached_branch_variable_unguarded` snapshots it.
- A project `pre-remove` or `post-remove` hook that references `{{
branch }}` unguarded now blocks `wt remove` on a detached worktree until
it's guarded (or `--no-hooks`).
`test_pre_remove_hook_branch_expansion_detached_head` previously
asserted `branch=HEAD`; it now uses the guarded form and asserts
`branch=`.
- A `pre-switch` hook run from a detached worktree gets no `base` rather
than an empty one. An unguarded `{{ base }}` errors where it used to
render nothing.

If any of these should instead render an empty string rather than error,
that's a different fix — say the word and I'll redo it that way.

## Testing

`test_alias_branch_unset_in_detached_worktree`
(`tests/integration_tests/step_alias.rs`) and
`test_user_post_remove_branch_unset_in_detached_worktree`
(`tests/integration_tests/user_hooks.rs`) are the reproductions: both
fail with `HEAD` before their respective fixes and pass now.
`test_user_remove_hooks_target_unset_with_detached_primary_worktree`
(both `pre-remove` and `post-remove` of one removal) and
`test_user_pre_switch_base_unset_in_detached_worktree` pin the `target`
and `base` cases; both use `{% if x is defined %}` rather than `{% if x
%}`, since an empty string and an absent var are indistinguishable under
the plain guard, and each half fails on its pre-fix shape.

`cargo run -- hook pre-merge --yes` is green apart from three failures
that reproduce with these changes stashed, on this branch, in the same
sandbox — `test_copy_ignored_preserves_file_executable_permissions`
(expects 0644, gets 0664 under the runner's umask 002) plus
`test_powershell_skipped_when_installed_no_profile` and
`test_nushell_install_target_is_a_vendor_autoload_dir` (the sandbox
home's shell state). Clippy `--all-targets --all-features` and `cargo
fmt --check` are clean.

<details><summary>Manual check against the issue's repro</summary>

```console
$ git worktree add --detach ../repo.scratch HEAD && cd ../repo.scratch

$ wt -v guarded          # probe = 'echo "[{% if branch %}{{ branch }}{% endif %}]"'
○ guarded template variables:
  branch                = (unset)
  worktree_path         = /tmp/…/repo.scratch
…
[]

$ wt probe               # probe = 'echo "[{{ branch }}]"'
✗ Failed to expand probe: undefined value @ line 1
  echo "[{{ branch }}]"
↳ Available variables: args, cwd, main_worktree, repo, repo_path, repo_root, worktree, worktree_name, worktree_path

$ cd ../repo && wt probe # unchanged on a branch
[main]
```

</details>

---

Closes #4009 — automated triage

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-09-05 13:22:49 -07:00
Maximilian Roos baf161bf60 Run switch --execute as literal argv (#3977)
## Summary

- Treat `wt switch -x` as one program plus arguments that bypass
Worktrunk shell parsing; program lookup and argument decoding use native
operating-system behavior.
- Launch the program from `wt` in the selected worktree, preserving
terminal access, signals, and exit status.
- Remove the shell exec directive, shell-specific escaping, and implicit
`sh` dependency. Shell wrappers now carry only the directory change.
- Make the Nushell wrapper recognize clustered execute flags such as
`-cx`, stop scanning at `--`, and warn when a retired exec-file wrapper
buffers stdout away from the terminal.

Shell syntax remains explicit: `-x sh -- -c 'code . && test -f
Cargo.toml'`. On Windows, shell shims need their extension (`-x
code.cmd`) or an explicit shell such as `-x cmd.exe -- /C code`.

This completes the argv cutover proposed in #2860 and removes the
remaining Nushell-on-Windows problem in #3944. It adds no PATHEXT
lookup, custom Windows quoting, or PowerShell launcher path, and still
removes 597 lines from `src` and `templates` on net.

## Validation

- `cargo run -- hook pre-merge --yes`
- 4,712 tests passed; one skipped
- Formatting, clippy, docs, doctests, lockfile, and snapshot checks
passed

Thanks @omgreenfield for testing the migration path in #2860.

Closes #2860
Closes #3944

> _This was written by Codex on behalf of @max-sixty_
2026-09-01 10:36:30 -07:00
Maximilian Roos df2bc6e7f1 Require Git 2.43 and test it nightly (#3895)
Worktrunk now uses Git 2.43 as its tested support baseline and checks
the version once before dispatching a command. Git 2.43 is Ubuntu
24.04's system package, so CI can exercise the full supported range with
an exact nightly row. This is a policy cutoff rather than a feature
boundary; Git-dependent commands on older versions fail centrally
instead of accumulating compatibility branches. The Git-independent
`config shell` namespace remains available so shell startup and
generated integration still work while Git is upgraded.

The existing nightly full-test matrix gains an exact Git 2.43.0 row.
Test fixtures that isolate PATH retain the runner-selected Git instead
of falling back to an older platform Git. `wt step relocate` uses `git
switch` because Git 2.43 does not support `git checkout
--end-of-options`, and the worktree-registration test now lets each Git
version generate metadata it can consume.

Tested with the full 4,680-test suite on exact Git 2.43.0 and the normal
development environment. Also validated the Ubuntu 24.04 amd64 package
installation and the workflow with `actionlint`.

> _This was written by Codex on behalf of @max-sixty_
2026-08-24 11:24:22 -07:00
Maximilian Roos 8e405bced9 docs: rebuild the site with Astro and Starlight (#3866)
The docs now build with Astro and Starlight instead of Zola. This
removes the Tera 2 migration blocker from #3827 while keeping the
published routes, anchors, generated references, metadata, and crawler
URLs stable. It replaces the approach closed in #3840.

## What changed

- Move the site into Starlight, with a custom Worktrunk homepage and a
shared copper, gold, paper, and ink design system.
- Keep generated docs as portable Markdown. The Rust sync pipeline no
longer needs Zola shortcodes, template escaping, ANSI-to-HTML
conversion, or reverse transforms for skill and README output.
- Preserve terminal semantics and command-only copying, add responsive
handling for short wide tables, retain stable heading IDs, and give
repeated command-reference headings useful search labels.
- Move docs CI and publishing to Node, Astro, and built-site contract
tests. The tests cover public routes, links, assets, metadata,
navigation, tables, terminal frames, and compatibility aliases.
- Record demo themes from isolated environments, add a mobile core demo,
and test the recording contract. The matching mobile assets are
published in `max-sixty/worktrunk-assets`.

Closes #3827.

## Verification

- `cargo run -- hook pre-merge --yes` (4,660 tests)
- `npm --prefix docs run check`
- `npm --prefix docs test` (9 tests)
- `npm --prefix docs run build` (16 pages)
- `npm --prefix docs run test:site` (12 tests)
- `pytest docs/demos/tests/test_recording.py` (4 tests)

> _This was written by Codex on behalf of max-sixty_
2026-08-22 00:01:58 -07:00
Maximilian RoosandClaude Opus 5 7aba380f0c fix(remove): gate removal on the registration, not the repository (#3808)
`wt remove --force` deleted a live worktree of this same repository,
uncommitted work included, whenever that worktree had been moved onto
another worktree's registered path.

The guard added in #3785 asks which *repository* the occupant answers
to: a linked worktree's git dir sits under `<common>/worktrees/`, the
main worktree's *is* the common dir, anything else is someone else's. A
sibling worktree moved onto the path satisfies that — its git dir sits
under `<common>/worktrees/` like any worktree of this repo — so it
passed, and the fast path renamed the directory into trash and handed
the `rm -rf` to a detached process. It is not prunable either: its
gitdir file points at a location that exists, so the `is_prunable` arm
from the same PR doesn't catch it.

Git's own validation is one level finer. `validate_worktree` requires
the directory to point back at *this registration*, and refuses this
removal with `--force`:

```console
$ git -C repo worktree remove --force ../repo.feature
fatal: validation failed, cannot remove working tree:
  '.../repo.feature' does not point back to '.git/worktrees/repo.feature'
```

<details>
<summary>Reproducer, verified against a build of main</summary>

The occupant has to be *moved* onto the path rather than created there —
`git worktree add` refuses a registered path, which is what leaves a
plain `mv` as the way this state arises.

```console
$ git -C repo worktree add ../repo.feature -b feature
$ git -C repo worktree add ../repo.bar -b bar
$ rm -rf ../repo.feature && mv ../repo.bar ../repo.feature
$ echo PRECIOUS > ../repo.feature/precious.txt
$ wt remove --force --yes feature
◎ Removing feature worktree (--force) & branch in background (same commit as main, _)
$ ls ../repo.feature
ls: ../repo.feature: No such file or directory
```

</details>

## The fix

The gate is now git's comparison at git's granularity: the directory's
`.git` must name *this* registration, and that registration's `gitdir`
file must name the directory back. Repository-level ownership stays as
the weaker half of the conjunction — it is what rejects a `.git` file
pointing at another repository — and the main worktree is the same test
where there is no registration to point back at.

`ensure_belongs_to_repo` becomes `ensure_holds_this_worktree`, since it
no longer merely asks about repository membership.

Resolution moves to `Repository::git_dir_at`, the fs-only resolver the
`wt list` prewarm already used (`derive_worktree_git_dir`), generalized
to answer for a directory rather than for a known worktree of this repo:
its main-worktree branch returned `git_common_dir()` on trust, and now
canonicalizes the `.git` it actually found. It also never walks up to a
parent, which is what git reads too — `git rev-parse --git-dir` in an
emptied worktree can resolve the *enclosing* repository.

That settles a second thing the old docstring got wrong. It claimed the
plan→rename window was "narrower than `ensure_clean`'s"; in fact
`ensure_clean` re-runs `git status` while this gate answered from
`GIT_DIRS`, memoized process-wide, so the second call was vacuous and
the window — which contains the approval prompt and the `pre-remove`
hook — was unguarded. `git_dir_at` reads the filesystem on every call,
so the check at the rename now re-decides.

The refusal was `Directory @ … is not this repository's worktree`, which
is false in the sibling case: it *is* one of this repository's
worktrees, just not the one registered there. Its hint didn't fit either
— "move the directory aside, then run `git worktree prune`" is a
repo-wide prune, and with a sibling moved aside *both* registrations are
prunable, so following it clears both and leaves a live checkout that
has stopped being a worktree:

```console
$ mv ../repo.feature ../repo.aside && git worktree prune -v
Removing worktrees/repo.feature: gitdir file points to non-existent location
Removing worktrees/repo.other: gitdir file points to non-existent location
$ git -C ../repo.aside status
fatal: not a git repository: (null)
```

So the error carries where the occupant's own registration records it,
and each case gets the remedy that fits. Moving it back to that path
leaves prune with only the stale entry to clear:

```console
$ wt remove --force --yes feature
✗ Directory @ ../repo.feature does not hold the worktree registered there
↳ Removing it could destroy the worktree registered @ ../repo.other; move the directory back there, then run git worktree prune
```

That path is read through `canonicalize_with_parents`, because a
relative `gitdir` entry resolves against `<common>/worktrees/<id>` and
would otherwise reach the hint with the `..` chain still in it — and
plain canonicalization can't normalize a directory that no longer
exists, which is the case the arm is reached for. Normalizing there also
makes `crate::path::paths_match`, the crate's canonicalizing comparison
over that same helper, the right test for the gate, so there is no
second comparison beside it.

The gate's fail-closed behavior now rests on that helper resolving `..`
through the filesystem rather than collapsing it lexically — across a
symlink the two readings name different directories — so `src/path.rs`
records the constraint where a lexical rewrite would otherwise read as a
tidy-up.

The FAQ's "What can Worktrunk delete?" paragraph carried the same "a
*different* repository" framing and is corrected.

## Scope

Pre-existing, and 0.73.0 already narrowed it — 0.72.0 had no ownership
check at all and deleted foreign clones too. The guard has two call
sites (`prepare_worktree_removal` at planning, `stage_worktree_removal`
at the rename), so this reaches `wt merge --remove`, `wt step prune`,
and picker removal, not only `wt remove`.

One incidental tightening: `wt remove <bare-repo-path>` previously
passed the guard (a bare root's git dir *is* the common dir) and was
stopped only by the dirty check, which `--force` skips. It now refuses
at the guard.

<details>
<summary>One residual, left alone</summary>

`git worktree repair <path>` after the `mv` produces a *double
registration*: both `worktrees/repo.bar/gitdir` and
`worktrees/repo.feature/gitdir` come to record the same path, and `git
worktree list` reports two worktrees there. In that state the new gate
accepts the removal — the occupant does point at the `feature`
registration, and that registration does point back — while git refuses,
because its path→worktree lookup happens to match the `bar` entry first.
Closing it means knowing the registration id at the gate, or scanning
every `worktrees/*/gitdir` for duplicate claims. Unchanged by this PR,
and reachable only via `mv` followed by `repair`.

</details>

## Testing

Five new tests, each confirmed to fail with the line it covers reverted
and to leave the others passing. Three drive the binary:

- **the sibling case** — follows #3785's data-safety model: asserts the
filesystem afterwards, not just the exit code, since removal stages by
rename and deletes in a detached process. Snapshots the refusal, so the
hint and the path it names are pinned. Fails with the pointer-back
conjunct removed, while the foreign-repo test still passes without it —
the two cover different halves.
- **the re-check at the rename** — a `pre-remove` hook repoints the
worktree's `.git` at a sibling's registration after planning has already
cleared it, which is what makes the second gate's freshness observable.
Fails when resolution routes back through the `GIT_DIRS`-cached
`git_dir()`.
- **a relative `gitdir` entry** — removal succeeds, and git reads the
rewritten entry back, which is what makes it the form git itself writes.
Rewriting the entry rather than setting `worktree.useRelativePaths`
keeps the test independent of the git version that introduced the
option.

Two sit at the gate, where the CLI can't reach:

- **both worktree shapes are accepted** — including the main worktree,
whose git dir *is* the common dir. `wt remove` rejects the main worktree
well upstream of this gate and a bare repository's worktrees are all
linked, so nothing through the CLI would notice that arm inverting.
- **the refusal names a normalized path** — asserted against
`Diagnostic::render`, since the path is in the hint and `Display`
carries only the title.

Local gate green: 4607 tests, lints, doctests, rustdoc under
`-Dwarnings`.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 03:59:58 -07:00
Maximilian RoosandClaude Fable 5 0cb3cc1ef7 test(remove): cover the reap guard's spared branch deterministically (#3805)
The controlling-terminal guard's sparing branch had no CI coverage.
`test_remove_reap_kills_process` branches on the suite's own terminal —
none in CI, so CI only ever exercised the kill side, and the branch that
protects an interactive process from `--reap` ran only on dev boxes.

`test_remove_reap_spares_terminal_process` gives the child its own PTY
instead of reading the suite's, so the spared branch runs everywhere.
`portable_pty` makes the child a session leader with that PTY as its
controlling terminal, which is exactly the property the guard reads. A
spared process and an undiscovered one produce identical output ("No
processes to reap"), so the test proves discovery sees the child first,
then pins the guard's verdict in-process, then asserts the child
survives removal.

The reap phase prints before `handle_remove_output` runs the removal, so
both tests now wait for the worktree to actually disappear — without it,
a `wt` that gave up after the reap phase would still satisfy every
output assertion. Both presence polls also move onto `wait_for`, the
existing presence-poll helper, instead of hand-rolled deadline loops.

`tests/CLAUDE.md` picks up two entries this work surfaced. The first is
the slow-timeout triage signature: a kill at the 180s bound is a
duration symptom with two causes, and the durations around it tell CPU
starvation (a sibling worktree's build) from a blocked call inside the
test. It records `threads-required` as starvation's only lever and why
it stays unset. The second distinguishes a bounded poll on one
identified `ErrorKind` from a retry, so `pin_test_binary` and
`forward_with_etxtbsy_retry` don't read as violations of the No Retries
doctrine — the opening sentence is narrowed to the re-run it actually
bans.

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

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-12 10:19:33 -07:00
Maximilian RoosandClaude Opus 5 715af4cd72 fix(tests): pin the spawned wt binary against concurrent cargo uplifts (#3784)
Two test-suite flakes fixed at the root, both dependencies on machine
load and concurrent builds.

**Concurrent-cargo spawn `NotFound`.** Cargo uplifts `target/debug/wt`
by removing the path and recreating it, so a second `cargo` against the
same target directory leaves the binary every test spawns absent for a
fraction of a millisecond per rebuild — the one-off `NotFound` spawn
failures that pass on re-run. `wt_bin()` now returns a hardlink pinned
under `target/debug/wt-test-bin/<mtime>-<len>/`: the uplift unlinks only
the uplifted name, so the pin keeps serving the observed binary through
any number of concurrent rebuilds, at no disk cost beyond the `deps/`
artifact whose inode it shares. `test_wt_spawns_are_pinned` keeps every
spawn routed through it. Reproduced by re-creating the uplift every 200
ms alongside a full `cargo nextest run`: 302 of 4583 tests failed before
this change (147 as direct `NotFound` spawn panics, five of them
byte-identical to the original shell-wrapper report), 4585 of 4585 after
— with an unrelated external cargo also rebuilding `wt` mid-validation,
absorbed the same way.

**`--reap` probe races.** `test_remove_reap_kills_process` predicted the
reap guard's verdict with its own `lsof`/`ps` snapshot, and under load
either probe's spawn can stall past the 5 s bound, whose fail-safe empty
result flips the outcome — a prediction `wt` then contradicts, or `wt`
reporting "No processes to reap" for a live child. The prediction now
reads the session's controlling terminal directly (`/dev/tty` opens iff
the session has one — the property the child inherits at spawn), the
probe timeout is env-pinnable (`WORKTRUNK_TEST_PROBE_TIMEOUT_MS`, set to
60 s in the static test baseline; production keeps its 5 s bound), and
the discovery poll uses the suite's 60 s presence-poll convention.
Looped 15/15 green at load average ~60, where the previous shape failed
2/10.

Not covered here, noted as follow-ups: benches still spawn
`env!("CARGO_BIN_EXE_wt")` directly (same hazard, separate runner,
outside the guard's scan), and the reap "spared" branch has no
deterministic end-to-end test (needs a PTY-held child).

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

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-09 07:06:08 -07:00
Maximilian Roos cf822f75cf fix(worktree): guard a registered path that no longer holds its worktree (#3785)
A registered worktree's path was trusted to still hold that worktree.
Three defects followed, one of them destroying data, and the check that
would have caught them — where it existed at all — was `Path::exists()`.

## `wt remove --force` deleted an unrelated repository

A clone that came to sit at a stale registration's path was removed
whole, including uncommitted work and, for a repo never pushed, the only
copy of its objects. wt's own hint routed the user there: the dirty gate
reads `git status` in that directory, reports the occupant's changes as
this worktree's, and offers `--force` as the cure.

```console
$ wt remove feature
✗ Cannot remove worktree: feature has uncommitted changes
  ?? precious.txt                                          # ← the other repo's file
↳ ... to lose uncommitted changes, run wt remove --force feature
```

git refuses that same removal, `--force` included (`validation failed …
is not a .git file`). Worktrunk's fast path renames the directory into
trash rather than asking git to, so git's validation never ran.
`ensure_belongs_to_repo` makes it, comparing the directory's git dir
against this repository's: a linked worktree's sits under
`<common>/worktrees/`, the main worktree's *is* the common dir, anything
else answers to someone else. One comparison covers both worktree kinds
and also rejects a `.git` file pointing at another repo, which git's
shape test accepts.

It runs at planning, ahead of the dirty gate, and again at the rename
for callers that stage without planning. Now:

```console
$ wt remove --force feature
✗ Directory @ ../repo.feature is not this repository's worktree
↳ Removing it could destroy unrelated data; move the directory aside, then run git worktree prune
```

## A recreated worktree directory leaked git's exit 128

`wt switch`, `wt merge`, and `wt step push` walked into `git rev-parse
--git-dir failed (exit 128)`. Two of them probed `Path::exists()` first,
which a deleted-and-recreated directory passes; the third asked nothing.

`worktree_is_unusable` is the union of both tests, because neither
implies the other. `exists()` catches the absent directory; git's
`prunable` catches the recreated one. `prunable` alone is *not* the
wider test it looks like — git withholds the attribute from a **locked**
worktree even when its directory is gone, since prunability is its
pruning policy and a lock means "don't prune this":

```console
$ git worktree list --porcelain          # wt2 locked, all three directories removed
worktree /tmp/ptest/wt1
prunable gitdir file points to non-existent location
worktree /tmp/ptest/wt2
locked removable media                   # ← no prunable line
worktree /tmp/ptest/wt3
prunable gitdir file points to non-existent location
```

A locked worktree on an unmounted volume is exactly what
`prepare_worktree_removal`'s lock guard exists for, so a `prunable`-only
test would read it as healthy. All three commands now give the message
the merely-deleted case already gave.

`wt remove` keeps `exists()`, deliberately: there it is the precondition
for the cleanup path rather than a health test, since
`prune_worktree_entry` unregisters via `git worktree remove`, which
skips validation only while the directory is absent. No scoped git
command clears the recreated case, so it reports and names the repo-wide
`git worktree prune` that does.

## `wt switch docs/` missed a branch sitting right there

Git's ref format forbids a trailing `/`, so the branch lookup never had
a candidate — and shell completion produces exactly that spelling
whenever a `docs` directory sits beside the branch. Selectors are
normalized before resolution.

## Resolving selectors through one ladder

The three fixes landed in three of the four places that assemble "expand
shortcuts, try the branch, try the path, classify the failure" by hand.
Each gated its path attempt on "did something rewrite this token?",
answered by comparing an expansion's output against its input:

| where | the comparison |
|---|---|
| `resolve_worktree` | `branch == name` |
| `plan_switch` | `target.branch == branch` |
| `target_worktree_at_path` | `target.filter(\|t\| *t == resolved)` |
| `resolve_base_ref` | `resolved == base` |

That is a fact the rewriting step knows, re-derived downstream from its
output, and it is wrong in both directions. A shortcut can expand to the
token it was given — `-` pointing at the branch you are already on — and
string equality reads that as a literal, turning the path arm back on
for a token nobody typed. Normalization breaks it the other way, which
is why the trailing-separator fix needed threading through three call
sites.

`Selector` carries the fact instead: `expand_shortcut` reports whether
it fired, `wt switch` reports its `pr:`/`mr:` dispatch and remote-prefix
strip, and `names_a_path()` replaces all four comparisons.
`resolve_selector` is the ladder, and `plan_switch` expands into it
rather than re-implementing its phases.

`names_a_path()` gates both path steps together — the worktree-by-path
lookup and the directory verdict — which is what `wt switch --create`
needs: the argument names a branch to create, so `branch_only()` takes
the arm off at the producer rather than each consumer re-testing
`create`.

It also reaches the directory verdict, so `ResolvedWorktree` gains
`NoWorktreeAtPath` and the four sites that called `path_selector_error`
themselves stop re-deriving it. The docstring defending that laziness
didn't survive checking — the function returns on `is_valid_branch_name`
before touching the filesystem, so every ordinary branch name already
short-circuited.

|  | before | after |
|---|---|---|
| `normalize_selector` call sites | 3 | 1 |
| `path_selector_*` call sites | 4 | 2 |
| "was it rewritten?" comparisons | 4 | 0 |

## Navigating the diff

- `src/git/repository/mod.rs` — `Selector`, `normalize_selector`, the
new `ResolvedWorktree` variant.
- `src/git/repository/worktrees.rs` — `expand_shortcut`,
`expand_selector`, `resolve_selector`, `usable_worktree_for_branch`.
- `src/git/repository/working_tree.rs` — `ensure_belongs_to_repo`, the
ownership check.
- `src/git/remove.rs`, `src/commands/repository_ext.rs` — where it gates
removal, and why before the dirty gate.
- Call sites: `commands/worktree/switch.rs`,
`commands/worktree/push.rs`, `commands/merge.rs`, `commands/remove.rs`,
`git/repository/config.rs`.

## Size

Comments and docstrings are the largest share: the ownership check and
the four conditions behind the directory verdict all look like things to
simplify away, so the reason each exists is recorded where it's
enforced.

| | + | − |
|---|---:|---:|
| Production code | 277 | 142 |
| Comments & docstrings | 320 | 75 |
| Tests | 325 | 8 |
| Snapshots | 186 | 0 |
| Docs | 6 | 0 |
| **Total** | **1114** | **225** |

## Testing

Seven new tests. The data-safety one drives the real binary and asserts
the filesystem afterwards, not just the exit code — removal stages by
rename and deletes in a detached process, so a passing exit would not
have caught a staged-then-deleted tree. The others cover the recreated
directory (switch and remove), the trailing separator, `--create`
against a worktree registered at that path, and, at the unit boundary,
the four states of `worktree_is_unusable` — healthy, absent,
locked-and-absent, recreated — and the selector's path-ness, including
the degenerate case string equality got wrong. Each new test was
confirmed to fail with its fix reverted.

One more covers an omitted merge target in a repo whose default branch
can't be determined. `^` had a test for that error; the omitted-target
route to the same message had none. The gap predates this branch — the
closure is byte-identical to the one it replaces and codecov records
those lines as missed at the base commit too — but relocating them into
`resolve_target_selector` re-counted them as patch lines, which is what
surfaced it.

Local gate green: 4593 tests, lints, doctests, rustdoc under
`-Dwarnings`.

<details>
<summary>Behavioral matrix, verified against a build</summary>

```console
docs/ (trailing sep)      ▲ Worktree for docs @ ../repo.docs
detached by path          ▲ Worktree for detached worktree @ ../repo.det
leftover dir              ✗ No worktree @ ../repo.leftover
recreated dir             ✗ Worktree directory missing for rec
shortcut ^                ▲ Worktree for main @ ../repo
remove leftover           ✗ No worktree @ ../repo.leftover
--base docs/              ✓ Created branch nf from docs
foreign-repo remove       ✗ Directory @ ../repo.frn is not this repository's worktree
                             precious.txt survives
```

</details>

<details>
<summary>Also swept, and one thing left alone</summary>

Three more instances of the same shape, fixed here:

- `resolve_base_ref` was the fourth copy of the comparison, so `--base
docs/` now resolves too.
- `hint_for_repo` suggested `wt switch ^` after an existence probe a
recreated directory passes, pointing at a worktree the switch then
refuses.
- The pre-switch hook's `target` var used the bare shortcut expander, so
a hook saw `docs/` where the switch resolved `docs`.

The identical unborn/stale default-branch block in
`require_target_branch` and `require_target_ref` is extracted. The rest
of that pair differs in its existence predicate, extra arms, and final
error; sharing it would cost more in parameters than the duplication
does.

Left alone: `live_sibling_checkout` decides whether another worktree
still holds a branch during removal, and also uses `exists()`. Switching
it to `prunable` would make branch deletion *more* likely in a corner
case where the detached path already answers the other way. That is a
data-safety surface and a separate decision.

</details>

> _This was written by Claude Code on behalf of max-sixty_
2026-08-09 06:23:21 -07:00
Maximilian RoosandClaude Opus 5 f3ea2fd598 fix(errors): report a directory holding no worktree as a directory (#3773)
Passing a path that holds no worktree used to be reported as a missing
branch:

```
$ wt remove /repo/.claude/worktrees/ghost
✗ No branch named /repo/.claude/worktrees/ghost
↳ To list branches, run wt list --branches --remotes
```

The argument is plainly a path; the error calls it a branch and sends
the user to a listing it could never appear in. Now:

```
$ wt remove /repo/.claude/worktrees/ghost
✗ No worktree @ /repo/.claude/worktrees/ghost
↳ The directory exists but is not a worktree; to list worktrees, run wt list
```

#3767 fixed the hook that produced the leftover directory in #3753; this
fixes the message a person gets when they type such a path themselves,
which judewang named there as why it was hard to diagnose. Ref #3753.

Two neighbouring commands had the same cause and are also fixed. `wt
switch <path>` and `wt merge <path>` used to offer `wt switch --create
<path>`, which fails with `fatal: … is not a valid branch name`; and `wt
config state marker set --branch <path> foo` **succeeded silently**,
storing state keyed by a path string.

## How the decision is made

`Repository::path_selector_error` reports a directory only when all four
conditions hold. Each is here because dropping it made `wt` assert
something false, reproduced against a build:

| Condition | Without it |
|---|---|
| Git could never accept the selector as a branch name | `wt step rebase
HEAD~9` reports revision syntax as a path |
| A directory is there | `wt remove docs` stops meaning the branch when
`docs/` sits beside it |
| No worktree of this repo is registered at it | a *detached* worktree —
reachable by path alone — is reported as absent, contradicting the `wt
list` in the hint |
| It holds no git data | a sibling repo's live checkout, or a bare
repository, is called a leftover only the user can delete |

That last one is the data-safety case: the new variant's hint says only
the user can delete the directory, so a false positive reads as an
invitation to `rm -rf` a checkout with uncommitted work. Absence of git
data is *established* rather than assumed — `symlink_metadata` with only
`NotFound` counting, so an unreadable clone or a dangling `.git` symlink
withholds the claim instead of earning it.

The first condition is git's own ref-format rules, implemented
in-process and pinned against `git check-ref-format` by a test.

## Navigating the diff

- `src/git/repository/worktrees.rs` — `Repository::path_selector_error`
and `holds_git_data`, with the rationale for each condition recorded
where it's enforced.
- `src/git/repository/branch.rs` — `is_valid_branch_name`, the
ref-format predicate.
- `src/git/error.rs` — the new `GitError::WorktreeNotFoundAtPath`
variant.
- `src/git/repository/config.rs` — `target_branch_at_path` →
`target_worktree_at_path`, returning the worktree whole rather than
collapsing "no worktree here" with "a detached worktree here".
- Call sites: `commands/remove.rs`, `commands/worktree/switch.rs`,
`commands/config/state.rs`.

Reporting a detached *target* made `DetachedHead`'s fixed hint wrong:
`git switch` acts on the tree it runs in, so `wt merge ../B` was telling
the user to switch the tree they were standing in. The variant now
carries the detached worktree when that isn't the current one, and the
hint becomes `git -C ../B switch <branch>` — the same reason
`OperationInProgress` carries `branch`. Set at the three sites where the
detached worktree isn't the current one (`require_target_branch`,
`require_selected_branch`, and `wt step promote`, which raises this
about the main worktree); every other site passes `None` and renders as
before.

140 of the 257 added production lines are comments and docstrings —
three of the four conditions look like obvious things to simplify away,
so the reason each exists is written down next to it.

## Testing

Unit tests at the resolver boundary cover each condition and its
complement, both `directory_exists` arms, the shortcut-expansion route
(`wt merge -`), detached targets, revision syntax, unresolvable `.git`
entries, and bare repositories. Two integration tests drive the real
binary end-to-end against `../repo.leftover` — `wt remove` and `wt
switch` — covering the relative-path spelling and each command's wiring,
and the `switch` snapshot pins the thing that would regress silently:
that no `--create` hint is offered for a name git would reject.

The ref-format predicate is verified beyond its committed table: 2,791
generated names were run against real `git check-ref-format` with zero
disagreements, and two review passes did the same over their own inputs.
That sweep isn't committed — it needs Python and a live `git` — so the
committed table is what guards against drift.

Not exercised locally: the Windows-specific behaviours are reasoned, not
run — `Path::new("foo.").is_dir()` succeeding against `foo`, and
drive-relative `C:foo`. CI exercises the platform but not those inputs.

<details>
<summary>Known gaps this would ship with</summary>

- `wt switch docs/` (trailing slash, branch `docs` has a worktree,
`./docs` is a source directory) answers `No worktree @ docs/`. True,
unhelpful. The real fix is stripping trailing separators before
resolution — a resolution change, not a message change. On Windows it
reads `No worktree @ …/docs`, because `path_slash`'s `to_slash_lossy`
rebuilds the string from `Path::components()` there and drops the
trailing separator — still true of the path, minus the character that
explains it. The doc comment on `path_selector_error` now says so rather
than promising a spelling guarantee that holds on one platform.
- A worktree whose registration was pruned out from under it gets a
safe-but-vague message. The useful answer is a distinct `git worktree
repair`-or-delete diagnosis; that's new detection, and nobody has
reported hitting it.
- Under `-C`, a `./`-prefixed selector renders a visible `/./` (`wt -C
repo remove ./ghost` → `repo/./ghost`). Cosmetic; tidying it would
discard the trailing separator the `docs/` case needs.
- `require_target_branch` and `require_target_ref` remain near-copies of
one ladder, and this adds a line to each. Pre-existing; extracting it is
a separate refactor.
- `CommandEnv::require_branch` passes `worktree: None` unconditionally,
and `CommandEnv::for_selector` builds an env whose `worktree_path` is
the worktree the *argument* named — so a future caller combining the two
would get the unqualified hint. Nothing reaches that combination today:
`merge` and `squash` are the only `require_branch` callers and both
build with `for_action`, and the one `for_selector` caller (`wt step
commit --branch`) never calls it.

Two pre-existing bugs surfaced while reviewing this, unrelated to the
diff and reproducible by branch name: `wt remove` will trash a clone
that now sits at a registered worktree's path, and a recreated worktree
directory leaks a raw `git rev-parse --git-dir failed (exit 128)`.

</details>

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-08 13:06:02 -07:00
Maximilian RoosandClaude Opus 5 860fa02ecf fix(output): don't panic when a --format=json consumer closes the pipe (#3746)
`print_json` — the pretty-JSON printer behind `--format=json` — lived in
`src/commands/list/mod.rs`, under the one command that happened to need
it first, while `wt list statusline` and `wt config approvals list`
reached across for it. It now lives in `src/output/json.rs`, re-exported
as `crate::output::print_json`.

Moving it surfaced thirty other call sites that had each open-coded the
same two lines, and that those two lines were not equivalent everywhere.
Four printed through anstream's `println!` (via `worktrunk::styling`),
the other twenty-six through std's. anstream drops a `BrokenPipe` write
error; std panics. So on main today:

```console
$ wt config state get --format=json | head -3
{
  "ci_status": [
    {
thread 'main' panicked at library/std/src/io/stdio.rs:1165:9:
failed printing to stdout: Broken pipe (os error 32)
```

while `wt config show --format=json | head -3` exits cleanly — same
command family, different behavior, decided by which macro happened to
be imported in that file. `EPIPE` depends on whether a reader is still
attached, not on how much is written, so this is a race rather than a
size threshold: an output that fits the pipe buffer usually lands before
the consumer goes away, which is why it stayed hidden rather than why it
is safe. A three-byte write panics just as readily once the reader has
closed.

All thirty-six call sites now go through `print_json`, and `print_json`
prints through anstream, so no `--format=json` surface panics on a
closed pipe. The command above now exits 0 with an empty stderr; also
checked by hand on `wt list`, `wt step prune --dry-run`, `wt config
show`, `wt step eval`, `wt config approvals list`, and `wt list
statusline`.

`wt switch --format=json` is the one surface that isn't a `print_json`
caller: it emits its single result as one compact line, which is what a
shell loop reads, so converting it would change a machine-readable
format for no gain. It gets the same anstream printer instead, which is
the part that matters here.

`wt list statusline --format=json` had a third instance hiding in its
schema-1 empty path, a bare `println!("[]")` on std's macro — on the
surface that runs on every prompt redraw. It now serializes an empty
array through `print_json`, which emits the same two bytes;
`test_statusline_json_outside_worktree` already asserted them. A
module-level `println` import would have been wrong there, since the
text statusline's `println!` deliberately bypasses anstream so its
pre-rendered ANSI survives a non-tty stdout.

Pruned eight now-dead entries from `STDOUT_ALLOWED_PATHS` in
`tests/integration_tests/output_system_guard.rs`. Centralizing these
writes left seven allowlisted files with no direct `println!` at all, so
their exemptions covered no code and the guard quietly stopped
protecting exactly the files this branch touched; a stray `println!` in
`merge.rs` or `remove.rs` fails the test again. (`alias.rs`'s entry was
already dead.)

Serialization is otherwise byte-identical: serde escapes control
characters, so raw ANSI never reaches this output and anstream's
stripping is a no-op on it.

`src/commands/CLAUDE.md` gains one line under "Adding a CLI Command"
stating the rule — stdout through anstream, `print_json` as the printer,
switch's compact line as the one shape difference — so the next JSON
surface doesn't open-code it again.

Two `print_json` calls the diff rewrote were uncovered on the base
commit, which pulled their misses into `codecov/patch` without any
behavior changing. Rather than hand over a waiver, both now have tests:
`wt remove --format=json` with no branch argument (the single-worktree
path, distinct from the named removals already tested) and `wt step
for-each --format=json` interrupted mid-loop, which still owes its
consumer the results collected before the signal. Each was
mutation-checked — deleting the line under test fails it — because a
one-item array is what both the abort and completion paths produce, so a
weaker assertion would pass either way.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-05 23:03:14 -07:00
Maximilian RoosandClaude Opus 5 5c42c5b7d5 feat: machine-readable approval state and branch-removal outcomes (#3710)
Two of the five machine-readable-output requests NathanaelRea opened
(#3696–#3700), reviewed as a set and implemented where the gap was real.

## `wt config approvals list --format=json` (#3698)

The command already computed the four distinctions an orchestrator needs
— no commands, approved, approval-required, and stale — read-only,
without prompting or writing. It had no `--format` flag, so the only way
to learn that a non-interactive run would stop for approval was to run
the operation and catch `NotInteractive`, or to pass `--yes` and approve
whatever was there.

```json
{
  "state": "approval_required",
  "commands": [
    {"phase": "post-start", "name": "dev", "template": "npm run dev", "approved": false},
    {"phase": "pre-merge", "template": "cargo test", "approved": true}
  ],
  "stale": ["some removed command"]
}
```

`state` is what a caller branches on. `stale` stays a separate list
rather than a fourth `state`, because it co-occurs with all three — and
those are the approvals `--yes` would silently re-approve after their
command template changed, which is exactly what an orchestrator
preserving the approval model needs to see.

A flag on the existing read command rather than a new `status` verb,
matching `wt config show`, `wt config state get`, `wt config state
logs`, and `wt list`.

Closes #3698.

## `branch_outcome` on removal (#3700, partly)

`wt remove --format=json` reported the branch as one boolean, collapsing
five internal outcomes into two values:

| Internal outcome | `branch_deleted` was |
|---|---|
| `Deleted` | `true` |
| `Deferred` — handed to a detached process, result never observed |
`true` |
| `NotAttempted` — no branch, or `--no-delete-branch` | `false` |
| `Retained` — a sibling worktree has it checked out | `false` |
| `Retained` — **the CAS refused; the ref moved under us** | `false` |

The last row is the exact race #3700 asks for protection against.
Worktrunk already deletes with `git update-ref -d <ref> <oid>` and
already fails closed when the ref has moved — then reported it as the
same `false` that means "you asked me not to". And `Deferred` reported
`true` on intent.

`branch_outcome` names it instead: `deleted`, `deferred`,
`not_attempted`, `retained_unmerged`, `retained_checked_out`,
`retained_raced`, `retained_failed`. A caller that sees `retained_raced`
knows to re-read the ref and retry, which is what the guard detects it
for.

**This does not close #3700.** That issue asks for an *input* — a
caller-supplied expected OID that makes `wt` fail closed against the
orchestrator's own observation. This is an *output*. They land in the
same place on the default path, because the integration check already
refuses to delete unintegrated content, so the caller was never going to
lose commits — they just couldn't classify the refusal. Where the gap is
real is `--force-delete` / `-D`, which takes the early return in
`delete_branch_if_safe` and runs `git branch -D` with no integration
check and no CAS. If an `--expected-oid` flag lands, it has to gate that
path.

## Notes

- **Output-format break.** `branch_deleted` is replaced, not
supplemented, on `wt remove --format=json` and on `wt step prune
--format=json`'s live path. Per CLAUDE.md, output formatting is on the
flexible side of the interface line; flagging it here so the release
changelog picks it up.
- **`wt step prune --dry-run` keeps `branch_deleted`.** A dry run
predicts; it runs nothing to have an outcome. Different thing, different
name, documented as such.
- **`retained_raced` and `retained_checked_out` have no deterministic
CLI trigger.** Both come from windows between `wt`'s own fresh read and
the ref mutation, which no hook can be scheduled inside. They're covered
at the unit level (`branch_fate_from_result_mapping`,
`branch_fate_json_outcome_is_distinct_per_fate`, and
`cas_rejects_delete_when_branch_advances` in `src/git/remove.rs`, which
drives the race with a stale snapshot). The integration tests cover the
two reachable contrasts: `retained_unmerged` via a `pre-remove` hook
that commits, and `not_attempted` via `--no-delete-branch`.
- **`print_json` lives under `src/commands/list/`** and now has a third
caller from outside that module. Worth a more central home; not moved
here.

## The other three

Reviewed but not implemented:

- **#3696** — already possible. `wt --config-set 'list.json-schema = 2'
list --format=json` pins the schema per invocation above every config
layer, as does `WORKTRUNK_LIST__JSON_SCHEMA`. Answered on the issue;
what's left is a docs gap and making an out-of-range value fail rather
than degrade in JSON mode.
- **#3697** — the machine-readable error channel. A real gap and the one
policy call in the set; not started.
- **#3699** — aimed at `wt config state logs --format=json`, which is a
directory listing reconstructed from paths, under a model that
overwrites. The append-only run record it wants is `commands.jsonl`.

## Testing

`cargo run -- hook pre-merge --yes` green: 4533 tests, clippy, fmt,
doctests, rustdoc, docs sync.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-02 11:17:27 -07:00
Maximilian RoosandClaude Opus 5 bbd24fb8f3 refactor(remove): make one function own the pre-removal gate (#3694)
Follow-up to #3690, which recorded the decision that removal's final
dirty-worktree gate is answered by the fsmonitor daemon, exactly as `git
worktree remove`'s own gate is. The decision went into the
`src/git/remove.rs` module spec — but the default removal path never
reads that module.

Both paths ran the same three ordered steps before the worktree
directory stopped existing: dirty-worktree gate, fsmonitor stop, rename
into trash. They were two copies with near-identical comments.
`execute_instant_removal_or_fallback` (`src/output/handlers.rs`, the
default background path for `wt remove` and `wt merge --remove`)
assembled them inline and never called `remove_worktree_with_cleanup`,
so a reader working on the gate that issue #3646 was actually about
would not find the reasoning written for it.

`stage_worktree_removal` now owns all three steps and both paths call
it. The gate becomes one decision instead of a sequence each caller
re-assembles, and the ordering rationale — why the gate precedes the
daemon stop, why the stop precedes the rename — lives on the function
that implements it. The rename-and-prune step it previously named
becomes the private `rename_into_trash`.

No behavior change.

## Stale spec claims this surfaced

- `stop_fsmonitor_daemon` documented three callers ("the library
`remove_worktree_with_cleanup`, the foreground handler, and the
background `spawn_background_removal`"). The foreground handler goes
through `remove_worktree_with_cleanup`, so it was two; after this change
it is one.
- The module opened by calling itself "the canonical removal flow used
by `wt remove`, `wt merge --remove`, and the TUI picker". `wt merge
--remove` takes the background path, and so does `wt remove` unless
`--foreground` is passed.

## Test

Nothing pinned the final gate on the **default** path — the existing
test covers `--foreground` only. Planning validates cleanliness before
`pre-remove` runs, so a hook that dirties the worktree can only be
caught by the gate immediately before the mutation. The test is now
parameterized over both execution modes.

Verified by mutation rather than by assuming the assertion binds: with
the gate disabled, the background case reports `Removed
feature-hook-dirties worktree & branch` and destroys the hook's file,
which is the data-loss scenario #3646 described.

Ref #3646

> _This was written by Claude Code on behalf of Maximilian_

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-01 20:45:30 -07:00
Maximilian Roos 1eded27943 Simplify forge, shell integration, and removal internals (#3662)
This consolidates cross-cutting models that had accumulated parallel
representations, while preserving the CLI and config interfaces.

## What changed

- Forge identity now flows through one `ForgeKind`, with boundary-safe
network-host classification shared by CI, remote references, and
structured repository metadata. Branded SSH aliases such as
`github-personal` remain outside provider dispatch and receive an
actionable `forge.platform` diagnostic when forge data is requested.
- Worktree removal now uses one owned target type and rechecks uncached
worktree topology immediately before compare-and-swap branch deletion,
retaining branches that gained a live or locked checkout.
- Shell integration no longer implements the retired single-file
directive writer. Stale wrappers receive repair guidance, execution
fails closed, and child processes cannot inherit the retired
sourceable-file capability.
- Zsh and Git-version probes are shared, while dead mocks, redundant
dependency edges, serializer detours, pass-through types, and duplicate
tests are removed.

The removal guard deliberately distinguishes live, stale-prunable, and
locked registrations. The detached cleanup path performs the same
record-aware check before deleting a branch ref.

## Testing

`cargo run -- hook pre-merge --yes` passed after merging current
`origin/main`: 4,489 tests, Clippy, formatting, lockfile checks, docs,
doctests, and snapshot review.

> _This was written by Claude Code on behalf of max_.
2026-07-30 02:10:07 -07:00
Maximilian Roos 6d09125b7b test: converge suite on semantic boundaries (#3663)
This follows the first test-simplification tranche by converging the
remaining suite around distinct semantic and pragmatic contracts rather
than raw case count. The branch removes false-confidence tests, invalid
setup variants, repetitive snapshots, and expensive PTY overlap while
strengthening the retained route, precondition, and interaction proofs.

## What changed

- Replace obsolete CI-status integration mocks and blank snapshots with
direct provider semantics, mixed-priority cases, and strict
GitHub/GitLab route assertions.
- Remove free-riding merge, push, remove, list, security, config, and
switch cases whose setup never reached the named behavior; consolidate
repetitive direct cases into labeled tables.
- Reduce the switch picker from 42 PTYs to 19 distinct terminal
contracts, using causal release gates for asynchronous loading and
repaint behavior.
- Add a cached main-only picker fixture, eliminating 138 unnecessary Git
subprocesses across the retained PTYs, and integrate it with main's
generated hermetic standard fixture.
- Tighten test guidance around proving setup preconditions and mock
invocation routes, and correct the comments-tab help text and generated
mirrors.

## Reviewer map

- `tests/integration_tests/ci_status.rs` and
`src/commands/list/ci_status/`: provider semantics and route coverage.
- `tests/integration_tests/switch_picker.rs`, `src/commands/picker/`,
and `src/testing/`: retained PTY contracts, causal mocks, and fixture
design.
- `tests/integration_tests/config_show.rs`, `src/config/deprecation.rs`,
`src/config/expansion.rs`, and worktree type/resolve tests:
direct-boundary consolidation.
- `tests/CLAUDE.md`: the testing rules extracted from the
false-confidence cases found during the survey.

The measured loop removed 98 tests, 65 snapshots, and 23 picker PTYs.
Controlled warm Nextest execution improved from a 79.593-second mean to
72.574 seconds (8.8%), while comparable production-line coverage moved
from 97.32% to 97.23%. The tracked PR diff is a net deletion of more
than 5,700 lines.

## Validation

- `cargo run -- hook pre-merge --yes` after syncing current `main`:
4,468 passed, one configured skip; docs, doctests, clippy, formatting,
policy checks, and snapshots green.
- `task coverage` on the completed change before the base sync: 4,465
passed, one configured skip; 97.23% comparable production-line coverage.
- Three independent final audits found no remaining lost beliefs,
fixture hazards, or safe PTY consolidations.

> _This was written by Claude Code on behalf of max_.
2026-07-30 00:01:32 -07:00
Maximilian RoosandClaude Opus 5 4554f50ce6 perf(tests): stop leaking a temp dir per test, and measure where the suite's CPU goes (#3604)
Measured where the test suite's CPU actually goes, fixed what was doing
real extra work, and added `task profile-tests` so the measurement is
repeatable.

## Baseline

`cargo nextest run --features shell-integration-tests` on an 18-core
M-series machine: 4,570 tests, ~95s wall, **988 CPU-seconds (332 user +
655 sys)**.

Two thirds is kernel time, so the cost is process creation and
filesystem churn rather than computation. The integration binary is 86%
of summed self-time: 2,184 tests at ~0.6s each, each spawning `wt` (a 65
MB debug binary, ~11ms CPU per spawn against 2.6ms for a trivial
process) and `git` against a fresh fixture copy. It sits in a broad
middle, not a few outliers: 73% of self-time is in tests taking 0.25 to
2.0s.

## One leaked temp directory per test

`isolated_test_cwd()` held a `TempDir` in a `LazyLock`. Statics don't
run destructors at process exit and nextest runs one process per test,
so every test leaked an empty directory into the system temp root.
Measured with `TMPDIR` pointed at a fresh directory: **704 per
integration-suite run**. This machine had accumulated **454,907 entries,
353,268 of them empty strays older than a day**.

Stale entries are cheap to ignore but expensive to enumerate, and
`git::recover::recover_from_path` reads every ancestor directory of a
deleted CWD:

| temp root | `test_recover_from_path_returns_none_for_unrelated_path` |
|---|---|
| 454k entries | 14.2s (34.4s on a quieter run) |
| empty | 0.27s |

One fixed directory replaces it. Leaks per run: 704 to 0, verified
across full suite runs, and the directory is still empty after ~9,000
test executions.

I also checked whether a crowded temp root slows ordinary temp
operations. It does not: create, populate and delete of a fixture-sized
tree ran at 21ms/iter in a 454k-entry parent against 40 to 60ms in an
empty one. The leak's cost is concentrated entirely in code that
enumerates.

## Fixture temp dirs no longer sit in the shared temp root

The fixtures created their temp directories directly in the system temp
dir, among however many entries the machine had put there.
`test_temp_root()` (`$TMPDIR/wt`) roots them one level in, and
`test_tempdir()` replaces `TempDir::new()` across every `TestRepo`
constructor, the mock-command helper, the `temp_home` fixture and the
recovery tests. That test again: **14.2s to 0.06s**.

Two constraints worth knowing, both found by trying the more aggressive
version first:

- **A cache-dir root fails.** `~/Library/Caches` is under `/Users/`,
which a conditional `includeIf "gitdir:/Users/"` matches, so 16 picker
tests fail their commits under `commit.gpgsign` — they drive git through
`Repository::run_command`, the production API with no isolated config.
`step_promote` above was not a one-off: the suite was hermetic against
host git config only because macOS puts `$TMPDIR` outside `/Users/`.
That is the hole the next section closes — at the layer that covers
in-process git, not by choosing where temp files live.
- **The root's name is load-bearing.** A unix socket path cannot exceed
`sun_path`, 104 bytes on macOS. The canonicalized per-user `$TMPDIR` is
56, and `test_copy_ignored_skips_non_regular_files` binds a listener 89
bytes in. `worktrunk-tests` (16 bytes with its slash) overflowed by two;
`wt` costs 3 of the 14 spare.

The ~240 tests that call `tempfile` directly still use the system temp
dir. They are transient and a clean run leaks nothing, so converting
them is tidiness rather than a fix.

## A test that passed by accident of TMPDIR location

`step_promote::test_promote_bare_repo_with_worktrees` drove git through
bare `Cmd::new("git")` instead of `configure_git_env`, so the host's
config applied. A conditional `includeIf "gitdir:/Users/"` enabling
`commit.gpgsign` fails its commit, but only when `TMPDIR` sits inside
the matched tree. macOS puts `TMPDIR` under `/var/folders`, so it
passed; pointing `TMPDIR` anywhere under the home directory failed it.

## The suite was not actually isolated from the developer's git config

Chasing the temp-root change turned up a real hole. `TestRepo` exposes
the production `Repository` type, and `Repository::run_command` builds a
plain `Cmd::new("git")` with no `GIT_CONFIG_GLOBAL`, so it inherits the
test process's own environment. Separately, a bare `wt_command()` had no
`GIT_CONFIG_GLOBAL` at all and fell through to `~/.gitconfig`. 280
`Repository::at/current/discover` constructions across 31 test files and
156 direct `run_command*` calls in test code sat on that path.

Signing was only the symptom that surfaced. Confirmed leaking from a
real developer config: `commit.gpgsign`, `core.fsmonitor` (spawns a
daemon per fixture repo), `worktree.guessremote` (changes `git worktree
add`, directly under test), `help.autocorrect = prompt` (a mistyped git
command blocks). Structurally: `core.hooksPath`, `credential.helper`,
`filter.*` clean/smudge and `diff.external` all execute arbitrary
programs; `url.*.insteadOf` rewrites remotes; `merge.conflictstyle`,
`diff.context`, `rebase.autostash`, `fetch.prune`, `push.default` all
change what the code under test observes. That set is unbounded, which
is why hardening each fixture's local config was rejected — a denylist
can't cover it, and local config cannot unset an inherited `[include]`
or `credential.helper` at all.

The floor is one constant, `shell_exec::HERMETIC_TEST_GIT_ENV` — the
deny pair pointing `GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` at a path
that does not exist, plus the settings the suite needs through
`GIT_CONFIG_COUNT` / `GIT_CONFIG_KEY_n` / `GIT_CONFIG_VALUE_n` — applied
to every child at its spawn site. There is no git-config file anywhere
in the repo. For the spawn sites the harness owns (`git_test_env`,
`configure_git_cmd`, `isolate_subprocess_env` for `wt` children,
`pty_env_vars` for `env_clear`ed PTY children) that's ordinary per-child
env. For the git that *production* code spawns while a test drives it
in-process, the test never holds the command — so the harness flips an
atomic latch (`shell_exec::enable_hermetic_test_env`, called from the
fixture constructors), and `Cmd`, the choke point every production spawn
passes through, applies the floor to each child while the latch is set.
Setting env on a child is safe; it was setting the test process's *own*
env that wasn't (`set_var` races the other test threads), and the latch
dissolves the need for it — no `unsafe`, no pre-`main` constructor, no
cargo `[env]`. Because the latch lives in the binary, every runner
agrees by construction: `cargo test`, nextest, `cargo llvm-cov`, `cargo
bench`, an IDE, a debugger, a directly executed
`target/debug/deps/integration-*`. `.config/nextest.toml` was tested and
rejected, and is now ruled out standing: nextest 0.9.132 has no `[env]`
key, and a `$NEXTEST_ENV` setup script would miss the three non-nextest
runners CI uses (`cargo llvm-cov`, the Nix `cargo test` derivation,
`cargo bench`). A runner-specific knob doesn't fail loudly when another
runner misses it — it yields a different result, usually in the coverage
job whose numbers gate a merge. `tests/CLAUDE.md` → One Result Per Test,
Whatever Runs It records the rule; `.config/nextest.toml` points at it
from the place someone would be tempted.

Acceptance test, since the suite passed before only by accident of
`$TMPDIR` sitting outside `/Users/`: with `test_temp_root()` temporarily
pointed under `$HOME` so a conditional `includeIf "gitdir:/Users/"`
fires, the picker tests go from **20 of 38 failing to 38 of 38
passing**.

**The cost:** the latch is a test-serving switch compiled into
`shell_exec` — one static, one relaxed load per spawn, marked
`TODO(hermetic-env)` with the structural alternative (threading an
explicit env value through `Repository`). `cargo run -- <cmd>` is
untouched: nothing in production latches it, so a developer's own
invocations keep their aliases, credential helper, and identity. The one
production git spawn that bypasses `Cmd` (the fsmonitor daemon launch)
re-applies the floor by hand. (Two earlier shapes were tried and
replaced: cargo's `[env]`, which taxed every `cargo run` and vanished
whenever a test binary ran outside cargo, and a pre-`main` constructor
crate, which every test target had to link and which put the floor on
developers' `cargo bench`-adjacent runs too.)

## In-process tests were reading the developer's worktrunk config too

`config_path()`'s third priority is the real
`~/.config/worktrunk/config.toml`, and a lib-crate test cannot set the
second for itself — `set_var` is `unsafe` and this crate forbids
`unsafe`. So a test reaching priority 3 got the developer's own config.
A `panic!` build of the guard named the live callers immediately:
`git::repository::tests::prewarm_*` read it on every run, and
`set_skip_shell_integration_prompt` /
`set_skip_commit_generation_prompt` reach the same resolver to
**write**.

Priority 3 is now absent under `#[cfg(test)]`, which is compiled out of
the real binary — so unlike the git floor above, this one costs `cargo
run` nothing. It returns `None` rather than panicking like
`approvals_path()`: that guards a mutation target where silent absence
would let a test believe it saved something, whereas this is a lookup
whose absent state is already handled — `require_config_path()` turns it
into an error, so a write still fails loudly while a best-effort read
preloads nothing.

The guard covers lib-crate tests only; `src/commands/` and `src/output/`
link the lib in non-test mode. Nothing there exercises the fall-through
today (968 bin-crate tests create no config under a scratch `$HOME`), so
that is a requirement on new tests, recorded in `tests/CLAUDE.md`.
`system_config_path()` stays unguarded on purpose — machine-wide file,
and `config::deprecation`'s `PendingDefault` rules need the lookup.

## Merging main's parallel fix

#3620 attacked the same in-process hole from the other side, writing
`LOCAL_TEST_CONFIG` into each fixture's own `.git/config`. The two
compose rather than compete and both are kept: the floor denies the
host's config to every git, and the local config supplies what a
hermetic in-process git still needs — an identity, which the floor
deliberately withholds because it has per-command homes already
(`git_test_env`, `LOCAL_TEST_CONFIG`) and `useConfigOnly` fails loudly
if a path misses both. main's structure (`TestConfigPaths`,
`TestRepo::bare`) is kept as-is.

Two docstrings were true on each side and false together:
`test_gitconfig_path` restated the gitconfig inline, and
`LOCAL_TEST_CONFIG` said in-process git reads the developer's
`~/.gitconfig`, which is what the floor prevents. `test_gitconfig_path`
also held its `TempDir` in a `LazyLock`, the leak this PR removes. Both
are moot now: the function is gone with the files.

## Why there is no gitconfig file

The isolation went through two file-based shapes before this one, and
neither earned its keep. Denial never needed a file, because
`GIT_CONFIG_GLOBAL` and `GIT_CONFIG_SYSTEM` *are* the denial; the file
existed only to *set* things, and `GIT_CONFIG_COUNT` is git's
environment spelling of `-c`. Deleting both files also deletes the
`[include]` that kept them from drifting, the per-process write that
broke `test (windows)` on a shared path, and the config-path argument
threaded through 22 call sites.

The floor that remains is the deny pair plus two settings.
`user.useConfigOnly` is a backstop: denial alone leaves git *guessing*
an identity from the OS username and hostname rather than failing, which
is the one way a hermetic suite could still author a commit as the
developer. Nothing exercises it, and that is the reason to keep it.
`rerere.enabled = false` is *set* rather than left unset, so the suite's
rerere state cannot depend on what a fixture happens to carry.
`commit.gpgsign`, `advice.mergeConflict` and `advice.resolveConflict`
are gone: denial leaves git on its own default for the first, and the
snapshot layer strips the gutter-prefixed `hint:` lines the other two
quieted (they vary across git versions), so nothing depends on
suppressing them at the source. The long-dead
`tests/fixtures/template-repo/` fixture went with them.

Once the latch made denial universal, the redundant copies went too:
`git_test_env` no longer restates the deny pair per command (the floor
is denial's only writer, so its value is uniform across every
transport), `LOCAL_TEST_CONFIG` dropped its `commit.gpgsign` (denial
guarantees the default), the platform-dependent `NULL_DEVICE` constant
is deleted, and the `.env.GIT_CONFIG_GLOBAL` snapshot redaction is gone
— the recorded value is one cross-platform constant, so there is nothing
volatile to redact.

I removed `rerere.enabled` first, on a local measurement that was wrong,
and CI failed on all three platforms. The standard fixture is built once
into `target/debug/wt-test-fixtures/` and copied per test, and that
cached copy held an `rr-cache` directory left by a rebase run while the
floor still enabled rerere. Git turns rerere on by itself whenever
`rr-cache` exists, so every local test kept the behavior the change had
just removed, while CI built the fixture fresh and lost it.
`tests/CLAUDE.md` now records the trap: clear the fixture cache before
trusting a local measurement of a git-config change.

**Why the floor can't live in a fixture:** every other test variable is
set on a *child* — `git_test_env` on a git command,
`configure_cli_command` on a `wt` subprocess. In-process git is not a
child the test configures: `Repository::run_command` is production code
building a plain `Cmd::new("git")`, and the test never holds that
command, so there is no place to set env on it — while setting the test
process's own environment is the one thing a test can't do safely
(`set_var` races the other test threads). The identity did move to the
fixtures and the per-command env this way; the denial reaches
production's children through the latch at `Cmd`, the choke point they
all pass through.

Two things fall out of `-c` semantics, both pinned:

- **It outranks a repository's own config**, where a global file would
yield to it. So `init.defaultBranch` cannot live in the floor:
`default_branch.rs` sets that key in a repo to prove `wt` reads it, and
an entry would silently win. The three harness `git init` calls that
relied on the floor now name their branch, as the other two already did.
- **A PTY child is `env_clear`ed**, so it inherits nothing and used to
get the floor through the file. It now gets the family from
`configure_pty_command`, the choke point every PTY spawn routes through,
and again from `pty_env_vars`, whose vector declares a PTY `wt` child's
complete environment. Each copy is pinned by its own test, because the
settings only quiet advice and refuse a guessed identity, so no PTY
assertion would catch their loss.

Four tests wrote their own gitconfig to get `init.defaultBranch` plus an
identity; the harness supplies both, so those writes are gone too. Net
45 lines lighter, and no snapshot changed.

## Measurement

`task profile-tests` builds first, then runs the suite under bash's
`time` keyword (task's own interpreter, mvdan/sh, parses `time` but
hardcodes `user`/`sys` to zero): CPU totals on the console, every
per-test duration in the default profile's `junit.xml`. It began three
sizes larger — a scratch-`TMPDIR` leak check that dragged a `sun_path`
byte budget into the Taskfile, a `/usr/bin/time` dependency GNU-less
Linux lacks, and a `perf` nextest profile whose console slow-listing
restated what junit already carries — and each piece fell to the same
question, whether the measuring goal needed it. Method and how to read
the numbers: `tests/CLAUDE.md` under Profiling the Suite.

## Found, measured, not changed

**The gate keeps a duplicate cargo artifact set.** `RUSTFLAGS='-D
warnings'` on the insta step is part of cargo's fingerprint, so it forks
all 343 crates into a second artifact set: 261 CPU-seconds to prime plus
a duplicate of `target/debug/deps` (`target/debug` here is 35 GB, in a
52 GB `target/`). I removed it and then put it back: the clippy step
that would cover it runs on ubuntu only, while the cross-platform matrix
runs `wt hook pre-merge --yes insta`, so this RUSTFLAGS is the only
thing denying warnings on macOS and Windows. `[lints.rust] warnings =
"deny"` would keep that coverage everywhere without forking the graph
(verified locally: fails on a planted unused variable, recompiles only
worktrunk and wt-perf, feature-check commands still pass), but it also
makes plain local builds fail on warnings and newly exposes `cargo msrv
verify` and the minimal-versions job. That is a workflow call. The
duplication is a one-time cost per artifact set rather than per-edit, so
it is second-order next to the ~600 CPU-seconds each suite run costs.

**`recover_from_path` enumerates every ancestor up to `/`.** At each
ancestor it reads the directory and stats `.git` in every child.
Bounding the child scan to the first *existing* ancestor would preserve
both documented layouts (sibling and nested) and both of that module's
regression tests, but it would break a custom `worktree-path` layout
where the repo is a child of a higher ancestor, so it needs a decision
about which layouts recovery must support.

**Nothing in the gate is the biggest cost; concurrency is.** The five
`[[pre-merge]]` keys are one table, so they run concurrently, and each
is a cargo command that wants the whole machine. They serialize on
cargo's build-directory lock (`Blocking waiting for file lock on build
directory` appears in every run) while test execution overlaps another
step's build. The `lockfile` comment says it "must be first", which
concurrent execution does not provide. Separately, agent worktrees run
whole gates at once: during this work a second worktree ran its own `wt
hook pre-merge` alongside mine, load average hit **154 on 18 cores**,
and the same suite took 147.7s instead of 92.9s.

## Tried and rejected

`[profile.dev] debug = "line-tables-only"` first measured 14% less CPU,
but per-spawn CPU was unchanged, which did not fit the proposed
mechanism. Re-measuring both configurations on a quiet machine gave
602.6s (baseline) against 606.5s (line-tables). The original delta was
contention from a sibling worktree running its own suite.

macOS Gatekeeper (`syspolicyd`) looked like a candidate at 230% CPU, but
300 spawns of the freshly built `wt` cost it 0s, and 0.2s after a
relink, against 0.4s during a 10s idle baseline.

## Verification

`cargo run -- hook pre-merge --yes` green, 4,611 tests passed, run
against a freshly built fixture cache after the switch to the latch. The
latch was verified to be the only source of the variables: the invoking
shell carries no `GIT_CONFIG_*`, and the meta-tests
(`in_process_git_reads_only_the_hermetic_config` asserting the *origin*
of every resolved setting, `pty_env_vars_carry_the_git_config_floor`,
and the `isolate_subprocess_env` scrub test asserting the floor is
re-set after the scrub) pin each transport. Across earlier runs one hit
a single intermittent PTY failure in `shell_wrapper` (exit 127) that
passes 3/3 in isolation and whose code path never touches `wt_command()`
or the shared cwd; a later run was green under heavier load than the one
that failed.

## Review round

A full review of the branch (three finder lenses, findings adversarially
verified) landed one more commit:

- **The wrapper-suite PTY children never got the floor.**
`configure_pty_command` env-clears, skips the `Cmd` latch, and sets the
real `HOME`, and the shell-wrapper call sites layer only fixture paths
and an identity on top. Every git those ~89 tests ran therefore read the
developer's real `~/.gitconfig` (and lost the gpgsign shield when
`LOCAL_TEST_CONFIG` dropped it). The floor now rides that choke point,
pinned by `configure_pty_command_carries_the_git_config_floor`; every
raw `CommandBuilder` site was checked to route through it.
- **`task profile-tests` could never report CPU.** mvdan/sh's `time`
hardcodes `user`/`sys` to `0m0.000s`, so the numbers the docs said to
track were unproducible; now `bash -c 'time "$@"' bash ...`. Measured
post-fix: user 5m47s / sys 12m8s, a 67.7% kernel share, confirming the
two-thirds claim above; the integration mean measured ~1s and the docs
were corrected from ~0.6s.
- Smaller: two raw `Command::new("git")` asserts in `remove.rs` tests
now go through `configure_git_cmd`; the hermetic meta-test keys on
`--show-scope` scopes rather than git's origin-path spelling; the dead
`template-repo` fixture is deleted; three test `git init`s name `-b
main`; doc corrections (sun_path arithmetic, recover-walk attribution,
dead `[TEST_GIT_CONFIG]` remnants, volatile counts).

Final gate on the finished tree: green, 4,612 tests. Deferred with
rationale: ~985 snapshots carry stale env-block metadata (insta never
compares it; it churns on future re-records), `$TMPDIR/wt` is not
per-user on Linux (a root run poisons it for later users), and
`spawn_detached_exec_*` / `step tether` do not hand-apply the floor (no
in-process test reaches them today).

> _This was written by Claude Code on behalf of Maximilian_

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 21:20:26 -07:00
Maximilian RoosandClaude Opus 5 e9f69b2038 fix(remove): prune the named worktree's metadata, not the repository's (#3650)
Every stale-metadata cleanup in the removal chain ran a bare `git
worktree prune`. That command takes no path filter: it walks *every*
entry in `.git/worktrees/` and unregisters each one whose directory it
cannot find at that instant. A worktree that is merely absent right now
— an unmounted volume, a dropped network mount, a half-finished `mv` —
is indistinguishable from a deleted one, so removing worktree A also
unregistered bystander B.

B's committed work survives (refs and objects are shared) and its files
stay on disk, but its admin dir does not: the index, `ORIG_HEAD`, the
per-worktree reflog, `refs/worktree/*` and `refs/bisect/*`, and any
in-progress rebase or merge go with it.

Verified on git 2.55, in a scratch repo:

```console
$ git worktree prune -v          # no --expire; no grace period
Removing worktrees/wtB: gitdir file points to non-existent location

$ git -C wtB status              # after the "volume" comes back
fatal: not a git repository: (null)

$ git worktree repair wtB
error: unable to locate repository; .git file does not reference a repository
```

`git worktree repair` relinks an admin dir; it cannot recreate one.

## The change

`Repository::prune_worktrees()` is replaced by
`prune_worktree_entry(path)`, which runs `git worktree remove <path>`.
Git skips its clean check when the directory is already gone, so that
deletes exactly one `.git/worktrees/<id>`. All three call sites already
had the target in hand:

- `stage_worktree_removal` — the `wt remove` fast path, after the rename
into the trash
- `prepare_worktree_removal`'s missing-directory fallback
- `wt step prune`'s stale-detached candidate

No repo-wide prune remains anywhere in the codebase; a removal's blast
radius now equals its intent.

## Locked worktrees

A repo-wide prune silently skips a locked entry, whereas `git worktree
remove` fails on one. Only the missing-directory fallback can reach a
locked worktree — it resolves one before the lock guard below it — so
that site skips the call explicitly, preserving the previous outcome.

`pruned_from` stays unconditional there. It is what the sibling-checkout
guard in Phase 4 tests, not a record of whether the metadata went;
making it conditional would have quietly disabled a data-safety check.

## Tests

Two integration tests cover both `wt remove` routes: remove one worktree
while a sibling's directory is displaced, restore the sibling, assert it
is still registered. Both fail against the old behavior with the
bystander missing from `git worktree list` — confirmed by temporarily
reverting the primitive to `git worktree prune` and re-running. `wt step
prune`'s site is covered by the existing
`test_prune_stale_detached_worktree`.

`test_prune_skips_prunable_candidate_whose_preparation_fails` forced a
preparation failure by shimming `git` to fail `worktree prune`; its own
guard assertion (`"the shim never fired"`) caught that the shim had
stopped firing. The shim now targets `worktree remove`. The test's
subject — a failing preparation skips the candidate rather than failing
the run — is unchanged.

Local gate green: 4634 tests, lints, doctests.
`RUSTDOCFLAGS="-Dwarnings" cargo doc` also checked separately, since a
broken intra-doc link passes pre-commit but fails CI.

## Not done here

`wt step prune` keeps stale-detached candidates on the write side of the
scan lock. The stated rationale — that they race sibling prunes — no
longer holds now that each names its own entry, so a `TODO(prune)` marks
the move to the read-side fan-out as a separate concurrency change.


---

## Review response

The `tend` reviewer verified the change and then held the merge for a
human on deletion-surface policy rather than on any defect. It raised
one inline comment, which does not hold up:

> This inner `if wt.locked.is_none()` is unreachable-when-false: the
early `return Err(WorktreeLocked)` at line 215 means `wt.locked` is
always `None` by the time control reaches here.

Line 215 is a comment added by this PR, not a `return`. The lock check
is at line 232, inside the `else` arm, which runs only when the `if`
above it is false. A locked worktree whose directory is missing takes
the `if` branch and reaches the guard with `locked` still set, so the
guard is live.

The comment that misled it was genuinely ambiguous, and is reworded.

## Patch coverage

The first push measured 69.23% of diff hit. Seven of the eight missed
lines were avoidable: `prune_worktree_entry` had copied
`remove_worktree`'s seven-line `GitError::Other` block to produce the
`&str` that `run_command` takes, and that error closure never runs.
Every caller's path comes from `list_worktrees`, which already parses
git's porcelain as UTF-8, so it collapses to one line:

```rust
let path_str = path.to_str().context("worktree path is not valid UTF-8")?;
```

One miss remains: the `tracing::debug!` inside
`stage_worktree_removal`'s fail-soft arm, which fires only when the
metadata prune fails after a successful rename. That line predates this
change — only its message was reworded, which codecov counts as new.
Restoring the old wording would make the message inaccurate (it now
prunes one entry, not the repository's), so the wording stands and the
line stays uncovered.

## Reconciled with #3647

`main` landed [#3647](https://github.com/max-sixty/worktrunk/pull/3647)
while this PR sat in CI, fixing the same lock-safety issue from the
other side: a top-of-arm `if wt.locked.is_some() { return
Err(WorktreeLocked) }` placed *before* the missing-directory fallback,
where this branch had kept the guard in the `else` arm and skipped the
prune for a locked entry.

The two auto-merge with **no textual conflict**, which is the hazard.
The merged arm carried main's top guard *and* this branch's `if
wt.locked.is_none()` skip, while dropping the `else`-arm guard the skip
was paired with — leaving the inner check dead and its comment
describing a route the merge had foreclosed, under a green CI.

`main`'s placement is the better one and now owns lock handling alone,
so the fallback calls `prune_worktree_entry(&wt.path)` unconditionally.
What this PR contributes is unchanged and orthogonal to #3647: prune the
named worktree's metadata, not the repository's.

Caught by the reviewer's second pass, which read the merge tree rather
than the branch. Gate re-run green on the reconciled tree: 4641 tests.

> _This was written by Claude Code on behalf of Maximilian_

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 22:41:51 -07:00
Worktrunk Botandworktrunk-bot cc8aef3079 fix(remove): honor worktree lock when directory is missing (#3647)
## Problem

In `prepare_worktree_removal` (`src/commands/repository_ext.rs`), the
missing-directory fallback was tested before the lock guard. A worktree
that was locked **and** whose directory was currently absent skipped
`WorktreeLocked` entirely: its registration was pruned and it fell
through to branch deletion — precisely the case `git worktree lock`
exists for (removable media, a network mount, a dropped VPN).

Reproduced against the current code: `wt remove <locked-worktree>` with
the directory removed reported `✓ Pruned stale worktree & removed branch
…`, silently bypassing the lock.

## Solution

Hoist the lock check above the missing-directory check in the
`Current`/`Path` arm, so the lock is honored regardless of whether the
directory is present. `--force` still does not override the lock,
matching `git worktree remove`. The duplicate lock check in the `else`
branch is removed (it's now unreachable there).

Blast radius is only the direct `wt remove` path: `wt step prune`
already skips locked worktrees during candidate collection, and the
`Branch` arm bails with "gained a worktree" before any deletion when a
worktree entry (locked or not) exists.

The FAQ's guarantee — *"Neither `git worktree remove` nor `wt remove`
(even with `--force`) will delete [locked worktrees]"* — is left
unchanged: it now describes the actual behavior. Fixing the code to
match the documented guarantee is the stronger outcome than weakening
the doc to describe a bypass.

## Testing

Added `test_remove_locked_worktree_directory_missing` to
`tests/integration_tests/remove.rs`: it locks a worktree, removes its
directory externally, then asserts `wt remove` fails, the branch
survives, and the stale registration is not pruned. The test fails on
the pre-fix code (branch deleted, registration pruned) and passes after.
The existing locked-worktree and pruned-missing-directory tests remain
green, and `cargo clippy --bin wt` is clean.

---
Closes #3645 — automated triage

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
2026-07-28 20:36:18 -07:00
Maximilian RoosandClaude Fable 5 c90c4b1b77 refactor(remove): report a removal's branch fate, not its plan's intent (#3637)
Follow-up to #3633, which patched the most visible symptom (prune's
summary counting candidate kinds). This lands the structural fix behind
that class: the removal chain returned nothing from execution, so
everything downstream reported the plan's intent as if it were the
outcome. The type even said so — `RemoveResult` was produced by
`prepare_worktree_removal` before anything ran, and the codebase
couldn't agree on what it was (`RemovePlans` in remove.rs, `plan` in
prune, `result` in the handler).

## The plan/outcome split

`RemoveResult` → `RemovalPlan` (variant `RemovedWorktree` → `Worktree`),
and `handle_remove_output` now returns a `BranchFate`: `Deleted` /
`Retained` / `NotAttempted` observed synchronously, `Deferred` only for
the detached legacy fallback whose outcome this process never sees.
Consumers report the fate:

- `wt remove --format=json` said `"branch_deleted": true` while stderr
said `▲ Removed worktree but kept branch feature (not integrated)` — a
pre-remove hook had advanced the branch, the SafeDelete re-check
declined, and stdout reported the plan anyway. Now `false`.
- `wt step prune`'s summary counts executed outcomes, so a deletion
declined mid-run reads `✓ Pruned 1 worktree`, matching the per-item line
above it. A declined *orphan* deletion (no worktree entry, nothing
removed at all) now drops out of the removed list entirely instead of
being counted as either lie.
- The detached fallback emits the "kept branch" correction in the one
case it can know (no CAS tail to append), instead of letting the
progress message's "worktree & branch" stand uncorrected.

The picker's `foreground: true, silent: true` contradiction collapses
into one `RemovalExecution::{Foreground, Background(fallback), Silent}`
axis, and the four hand-rolled capture-refs-then-CAS-delete sites share
one `worktrunk::git::execute_branch_deletion` — the single spelling of
"the plan said delete; do it now, against fresh refs".

## For the reviewer

`src/output/handlers.rs` carries the bulk: each execution path
constructs its fate where it observes the result, and rendering
decisions (foreground propagates deletion errors, background warns,
silent does neither) are unchanged. The merge with #3631's concurrent
prune rework is the diff's riskiest region — the worker result channel
widened from `Result<bool>` to `Result<Option<bool>>` so fates flow back
through the done-channel and the collector stamps
`candidate.deletes_branch` before the summary and JSON read it.
Deliberately *not* done: reusing the planner from `wt merge`'s finish
path (its divergences — clean-check strictness, preserve-vs-error on
primary, merge-target — are intentional), and threading the fallback
mode structurally (it just relocates an unreachable arm).

Zero snapshot churn: the change is provably invisible wherever intent
matched outcome. The divergence cases are pinned end-to-end by tests
whose hook must be the branch tip to pass. The one deterministically
unreachable arm is the detached-fallback warning (needs a
cross-filesystem rename failure); expect `codecov/patch` to flag those
few lines.

> _This was written by Claude Code on behalf of max_

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-28 15:49:33 -07:00
4af04c2260 fix(remove, prune, merge): target the named worktree, retain shared branches (#3533)
Follow-up to the discussion on #3480: [@max-sixty
asked](https://github.com/max-sixty/worktrunk/pull/3480#issuecomment-5039137116)
to have `wt remove` honor an explicit path generally. #3607 has since
landed the resolution half, `Repository::resolve_worktree`, which turns
a path into a worktree. This is the removal half, and it is the part
resolution cannot decide: which worktree to act on is a naming question,
whether the branch may be deleted is not.

## Problem

`wt remove` threw the resolved answer away. For any non-current worktree
it re-targeted by branch name, and `prepare_worktree_removal` mapped
that branch back to git's *first-listed* worktree. Two failures
followed, both silent.

**The wrong worktree is removed.** With `feature` checked out twice:

```console
$ git worktree list
…/dup    [feature]
…/first  [feature]

$ wt remove …/first
◎ Removing feature worktree & branch in background (same commit as main, _)
```

`…/dup` is gone. `…/first`, the one named, is still there.

**The survivor is left broken.** The shared branch is deleted with it.
Worktrunk deletes branches with `git update-ref -d`, git's
compare-and-swap primitive, which unlike `git branch -d` does not refuse
a ref that is checked out somewhere:

```console
$ git worktree list
…/first  0000000 [feature]

$ git -C …/first rev-parse HEAD
fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree.
```

`wt step prune` reached the same deletion unattended, and `wt merge`
reached it with a freshly integrated branch, so nothing else declined. A
branch gets a second worktree only through `git worktree add --force`;
worktrunk never does it itself.

## Fix

**Remove the worktree that was named.** `wt remove` drops non-current
worktrees via `RemoveTarget::Path`. `wt step prune` does the same: its
candidates already carry a path, and targeting a *stale* entry by branch
name resolved to a live worktree that the same prune had just skipped as
too young, then removed it.

**Retain a branch another worktree holds.** One predicate,
`live_sibling_checkout`, answers "would deleting this ref orphan a
checkout?", and every path that can delete a branch asks it:
`prepare_worktree_removal`'s worktree and pruned-branch-only arms
(covering `wt remove`, `wt step prune`, and the picker, which already
targeted by path) and `wt merge`'s finish. A hit forces
`BranchDeletionMode::Keep`, the single chokepoint every deletion path
honors, and names the surviving checkout:

```console
$ wt remove …/dup
◎ Removing feature worktree in background
○ Branch feature retained; still checked out @ …/first
```

A sibling whose *directory* is already gone is stale metadata, not a
checkout with anything to lose, so it does not retain: removing the last
live checkout still deletes the branch.

**`-D` is refused out loud.** Everywhere else `-D` is the override that
wins, so one that cannot be honored warns rather than passing quietly:

```console
$ wt remove …/dup -D
◎ Removing feature worktree in background
▲ Branch feature retained despite -D; still checked out @ …/first
```

The ordinary single-checkout case is unchanged, and a retained branch
skips the integration check entirely rather than computing a verdict it
would discard.

#3480's duplicate-checkout hint now points at `wt remove <path>`, which
this makes the safe answer.

## Testing

Full gate green. New coverage, each case asserting the survivor still
resolves `HEAD`, which is the corruption in question:

- `remove`: by path, by name, refused `-D`, the pruned-directory
fallback, and the mirror case where a stale sibling must *not* retain.
- `step prune`: a stale entry whose branch is live in an age-skipped
worktree. This test is what surfaced the wrong-worktree bug in prune.
- `merge`: merging a branch that a `--force` duplicate also holds.

## Not addressed

`wt step prune`'s summary counts candidates rather than outcomes, so a
retained branch still reports `✓ Pruned 1 branch`. The per-item line
above it already says the branch was retained. Fixing the count means
threading removal outcomes back through prune's accounting, which is a
separate change.

> _This was written by Claude Code on behalf of Maximilian Roos_

---------

Co-authored-by: worktrunk-bot <254187624+worktrunk-bot@users.noreply.github.com>
Co-authored-by: Maximilian Roos <m@maxroos.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 09:57:34 -07:00
Maximilian RoosandClaude Opus 5 a285ed308d refactor(tests): bring the mock-stub env vars under the WORKTRUNK_TEST_ prefix (#3621)
`MOCK_CONFIG_DIR` and `MOCK_CALL_LOG_DIR` were the only two
worktrunk-invented environment variables without the `WORKTRUNK_`
prefix. That is not just a naming inconsistency:
`isolate_subprocess_env` scrubs the parent environment by prefix —
`GIT_*` and `WORKTRUNK_*` — so an unprefixed name is the one thing a
test child inherits from whoever ran the suite. Renaming them brings
them under that scrub.

- `MOCK_CONFIG_DIR` → `WORKTRUNK_TEST_MOCK_CONFIG_DIR`
- `MOCK_CALL_LOG_DIR` → `WORKTRUNK_TEST_MOCK_CALL_LOG_DIR`

`TEST` rather than a bare `WORKTRUNK_` because both are read only by
`tests/helpers/mock-stub` — they are the protocol between the harness
and its helper binary, and `wt` itself never reads either one. That
matches the ~15 existing `WORKTRUNK_TEST_*` knobs.

## The snapshot half

Mechanical but not a substitution: the `env:` block is byte-sorted by
key, so the renamed entry moves position within it and a `sed` in place
would leave it where the old name sorted. All 971 affected blocks were
rewritten by dropping the old line, inserting the new one, and
re-sorting — the aggregate diff is exactly one removed and one added
line per file:

```
971 files changed, 971 insertions(+), 971 deletions(-)
-    MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+    WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"
```

The redaction placeholder follows its neighbours' convention in
`add_standard_env_redactions` (`WORKTRUNK_TEST_NU_VENDOR_AUTOLOAD_DIR` →
`[TEST_NU_VENDOR_AUTOLOAD]`), so it now reads `[TEST_MOCK_CONFIG]`
rather than repeating the full key. `MOCK_CALL_LOG_DIR` appears in no
snapshot — its two call sites are `.output()` assertion tests — so it
needs no redaction.

## Keeping it from regressing

`tests/CLAUDE.md` gains the rule under "Where a new environment variable
goes": name it `WORKTRUNK_TEST_*`, and the rule covers the
harness↔helper-binary protocol, not just knobs `wt` itself reads.
Without it the next helper-binary variable gets named `MOCK_*` again and
the hermeticity hole reopens.

## Verification

`cargo run -- hook pre-merge --yes` passes (exit 0) on the merged tree:
4607 tests including `--features shell-integration-tests`, `pre-commit
run --all-files`, clippy, doctests. No pending snapshots. A repo-wide
sweep finds no remaining unprefixed spelling.

## Merged main

#3620 landed while this was in flight and regenerated several `for_each`
snapshots that still carried the old key, so main is merged in here. It
resolved with no conflicts, and the result is what you'd want rather
than what git happened to produce: those blocks now carry #3620's new
keys (`GIT_ALLOW_PROTOCOL`, `CLAUDE_CONFIG_DIR`,
`WORKTRUNK_TEST_PARENT_SHELL`) *and* the renamed key, each in sorted
position. The sweep and the gate above both ran after the merge.

#3620 also rewrote the "Where a new environment variable goes" section
this branch adds to — three layers became four. Both edits survived; the
new naming paragraph follows the updated layer list.

The two advisory `affected tests` checks are red for the same reason,
and merging clears them: `cargo affected` errors on `git diff stdout was
not valid UTF-8`, because the diff from this PR's base contains 16
binary files — the `tests/fixtures/standard/` git objects and index
files that #3620 deleted. This branch's own commit contributes none. A
PR based after #3620 won't see them.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

> _This was written by Claude Code on behalf of Maximilian Roos_

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-07-26 21:44:57 -07:00
Maximilian RoosandClaude Opus 5 14580de79c feat(worktree): accept a worktree path wherever a branch is accepted (#3607)
Follow-up to the [`wt remove <path>` discussion on
#3480](https://github.com/max-sixty/worktrunk/pull/3480#issuecomment-5039137116),
widened from that one command to the whole surface. #3480 has since
landed and is merged in here — its duplicate-checkout warning composes
with this: the warning names the shadowed worktrees, and a path is how
you then address one.

## Audit

Verified against the built binary. wt had three answers to "what does
this token mean?":

| Route | `@` `-` `^` | worktree path | `pr:N` |
|---|---|---|---|
| `wt switch` (`resolve_switch_target`) | yes | only if absolute or ≥2
components, and not `--create` | yes |
| `wt remove` (`resolve_worktree_arg`) | yes | any token | no |
| everything else (raw `worktree_for_branch`) | **no** | **no** | no |

Same token, same cwd, two answers:

```console
$ wt remove inner     # ✓ Removed innerbranch worktree & branch
$ wt switch inner     # ✗ No branch named inner
```

And outside switch/remove the shortcuts didn't work at all — `wt step
diff --branch @` was `✗ Branch @ has no worktree`, while `wt config
state marker set --branch @` silently wrote state under the literal key
`@`. Separately, wt prints paths as `~/…` but wouldn't accept that form
back.

## Change

One canonicalizer in the lib, `Repository::resolve_worktree`, absorbing
the path fallback that lived in the bin crate's `resolve_worktree_arg`
(now deleted). Resolution order is documented once, on that function:
`@`, then `-`/`^`, then a branch with a worktree, then a path naming a
registered worktree, then the branch alone.

**Branch-first, everywhere.** A directory never shadows a branch that
shares its name; a path answers only what a branch cannot — a detached
worktree, or one of two checkouts of the same branch (#3480's case). The
`looks_like_path` shape gate is gone, so a single-component path
resolves like any other.

Two shapes cover what callers need: `require_worktree` for commands that
need a worktree to operate in, `require_selected_branch` for arguments
that key by branch. The merge/rebase target validators fall through to
the same path lookup, so a target can be named by the worktree it's
checked out in.

Routed through it: `switch` (including `--base`), `remove`, `step commit
--branch`, `step diff --branch` and its target, `step copy-ignored
--from`/`--to`, `step promote`, `step relocate`, `config state --branch`
(9 sites), and `merge` / `step rebase` / `step squash` / `step push`
targets.

`resolve_input_path` — already documented as the one resolution point
for user-supplied paths — now expands a leading `~`, so the tilde form
worktrunk prints is a form it reads back. `~user` stays literal; wt
doesn't reimplement that shell feature.

## Documentation

A path is an alias, not a second addressing scheme, so it is stated once
rather than on every argument: one paragraph in `wt switch`'s help and
one sentence on the addressing line in `worktrunk.md`. Argument
descriptions still read as branches. The two exceptions are the
arguments whose descriptions are already catalogues of accepted forms —
`wt switch`'s (`Branch, worktree path, shortcut, or PR/MR URL`) and `wt
remove`'s, which has named the path since before this branch. The
Worktree Model section of `CLAUDE.md` records which way to document it,
so the next argument doesn't grow its own copy.

## Two silent no-ops fixed along the way

- `wt step relocate <unmatched>` matched arguments against branch names
by string equality, so a typo filtered everything out and the empty
result rendered as `○ All worktrees are at expected paths` — a success
message for work that never happened. Every way an argument can fail to
land on a relocatable worktree now errors, including the detached and
prunable cases the new path route makes reachable.
- A selector matching nothing was reported as a branch without a
worktree, hinting `wt switch <token>` — which creates a worktree only
when the branch exists, so for a mistyped path it would just fail again.
`WorktreeSelectorNotFound` now says `No branch or worktree named X`; a
branch that genuinely exists without a checkout keeps the create hint.

## Testing

Full gate green: 4596 tests, lints, docs sync, `--features
shell-integration-tests` clippy. `codecov/patch` is 99.25% of diff hit
against a 97.93% target. New coverage:

- Unit: branch-and-path equivalence, branch-beats-same-named-directory,
detached-by-path (and its `require_selected_branch` refusal), shortcuts
never treated as paths, branch-only fallthrough, and the two distinct
not-found errors. Plus `expand_tilde` round-tripping
`format_path_for_display`.
- Integration: `switch` by relative/single-component/absolute/tilde
path, `--base` by path, `step diff --branch` by path and `@` (asserted
equal to the by-branch output), `config state --branch` set via `@` and
read via the worktree path, and both new relocate errors.

`wt remove`'s resolution is unchanged — it already had this rule; it now
shares the implementation. The 106-test `remove::` suite is untouched
and green.

- Integration: `wt step push <worktree-path>` (the
`require_target_branch` half of the target fallback), and `wt step
relocate` against a prunable worktree.

One diff line is unhit: `expand_tilde`'s fallback when `home_dir()`
returns `None`, which has no deterministic trigger. The `@`-resolution
backstop in `resolve_worktree` is untested for the same reason — no CLI
route reaches it — so it kept its original `match` arm rather than being
re-indented into the diff.

## Left out

`wt config state default-branch set` and `previous-branch set` take a
branch name as a *value to store* rather than a selector, so they still
take it literally.

> _This was written by Claude Code on behalf of Maximilian Roos_

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 09:10:46 -07:00
a0c1b662d2 perf(fsmonitor): resolve all daemons in one lsof spawn (#3581)
## Why

`wt remove`'s end-of-command fsmonitor sweep forked one `lsof` per
*machine-wide* `git fsmonitor--daemon` — and with `core.fsmonitor`
enabled globally, a machine accumulates one daemon per repo ever touched
(100+ is routine). So every `wt remove` paid ~100 process spawns. The
cost is superlinear under load, not linear: a fork storm makes macOS
Gatekeeper/XProtect assess each new image under contention, inflating
per-spawn cost for everything else on the box, sweeps included. The
`~50ms each` figure in the old docstring was measured *under that load*
and read as a fixed per-call cost — so the sweep looked merely slow
rather than self-amplifying. Two concurrent test suites driving hundreds
of `wt remove` calls pinned all 18 cores (load average 142) with nothing
hot in `htop`.

This was diagnosed and measured before (#2814 added the sweep; #3401
wrote the cost into the docstring and explicitly changed no behavior)
but never fixed.

## The fix

Resolve every daemon in a single `lsof -a -p <pid1,pid2,…> -U -F pn`
call and split its output on the `p<pid>` record boundary, handing each
PID exactly the output the per-PID call produced — so classification and
the whole data-safety contract in the module docs are unchanged.
Verified end-to-end against a live 108-daemon machine with a PATH shim
counting invocations: **108 spawns → 1**.

Two details the batched path must preserve, each covered by a new test:

- **Don't gate on `lsof`'s exit status.** It exits non-zero when *any*
requested PID vanished mid-scan, while still printing full records for
every survivor. Gating would drop the whole sweep whenever one daemon
happened to exit — the common case on a busy machine.
- **A PID with no record is dropped**, never synthesized as a
socket-less entry. A socket-less entry reads as orphan class 1 and gets
SIGTERM/SIGKILL — on a possibly-recycled PID.

## Also here

- **Test consolidation.** Three integration fixtures built their branch
set by spawning git per loop iteration. A new
`TestRepo::create_branches` creates them in one `git update-ref
--stdin`. The over-threshold completion test drops **10.5s → 1.4s**
(~230 git spawns → 5); `switch_picker` and `statusline` branch loops get
the same treatment. `mock-stub` gains an opt-in `MOCK_CALL_LOG_DIR` call
log so a test can assert *spawn count*, not just response — deliberately
outside the repo under test, since a log written inside the tree would
dirty it mid-`wt merge`.
- **Docs.** Dropped the "disable `core.fsmonitor` globally" workaround
from the troubleshooting docs (canonical `skills/`, mirror regenerated).
It stays enabled by choice, and the daemons were never the actual
fseventsd CPU driver.

- **CI hardening.** pre-commit.ci's `typos` hook maps the token
`pn`→`on` and had auto-rewritten `lsof -F pn` to the broken `lsof -F on`
(offset+name — no `p<pid>` records, so the parser reaps nothing). Pinned
`pn` in `.typos.toml` next to the existing `PN`-from-`PNGs` entry that
documents the same mapping, and added a test covering the empty-PID-set
early return (flagged by `codecov/patch`).

## Testing

New unit tests cover `daemons_from_batched_lsof` against real captured
`lsof -F pn` output, a vanished-PID gap, and empty output; the rewritten
integration test asserts exactly one `lsof` spawn with a comma-joined
PID list. Full integration suite green (1960 passed), clippy and fmt
clean.

> _This was written by Claude Code on behalf of max_

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2026-07-24 17:27:36 -07:00
Maximilian Roos edcfe5fe0c fix: honour -C in the statusline and in every supplied path (#3567)
`-C` sets the repository discovery path but never chdir's the process,
so anything reading `std::env::current_dir()` silently ignores it. Two
places did.

## `wt list statusline` described the wrong worktree

`wt -C /path/to/other/worktree list statusline` printed the statusline
for the *cwd's* worktree, and from a directory outside any repo it
printed nothing at all.

Both formats now resolve their worktree through
`Repository::current_worktree()`, which anchors to the discovery path.
That accessor already exists for this bug class (its docstring cites
#2625), so this is routing the statusline onto the canonical path rather
than adding a new one.

Details worth knowing while reading the diff:

- `--format=json` was mostly right already. It picked its worktree via
`current_worktree()` and only its "are we in a worktree" gate read the
cwd, so it misbehaved just when the process cwd sat outside a repo
(printed `[]`). That gate moves to `current_worktree()` and the `cwd`
binding is gone.
- `git_status_segments` now takes a `WorkingTree` instead of
`(&Repository, &Path)`. That also settles a split inside it: the
worktree lookup used the cwd while the no-worktree fallback used
`repo.current_worktree()`.
- `--format=claude-code` is unchanged where it matters. The directory
Claude Code sends on stdin still wins, since that names the session's
directory rather than wt's. With no stdin it falls back to the same
worktree as the other formats, so it honours `-C` too.

Four integration tests. Three run from the main worktree with `-C`
pointed at a `feature` worktree, one per format; the existing statusline
tests all set the child's cwd, which is the route that already worked.
The fourth pins the claude-code split: when stdin names a directory in a
*different* repository, the worktree comes from stdin while
`list_worktrees` comes from wt's discovery path, so nothing matches and
only the branch is reported. That fallback previously had no test, which
is what `codecov/patch` caught on the first push.

Discovering the `Repository` from the stdin directory instead would
remove that split, but it would miss the `prewarm` cache (keyed on the
base path) that this prompt-redraw hot path depends on, so the split
stays and is now asserted rather than incidental.

## Supplied paths resolved from the shell, not from `-C`

`wt switch ../repo.feature` and `wt remove ../repo.feature` joined the
argument onto the process cwd. With `-C` in play that split the
invocation in two — wt chose the repository, the shell chose the path —
and the combination resolved to nothing, so `switch` reported "No branch
named ../repo.feature". `--config`, `WORKTRUNK_CONFIG_PATH`,
`WORKTRUNK_SYSTEM_CONFIG_PATH`, and the trace file of `wt config state
logs profile` name a file the same way and had the same gap: `wt -C repo
--config mycfg.toml config show` reported "Config file not found" for a
file sitting in `repo/`.

Git resolves the paths in its command line against its own `-C`, because
it chdir's there before doing anything else. wt's `-C` sets a discovery
path instead, so `resolve_input_path` joins onto that — one resolution
point for all five, so they cannot drift apart. It returns the path
untouched when `-C` was not given, rather than joining `.` onto it: the
process cwd already resolves those, and the join would surface as a
stray `./` in output. `Path::join` leaves an absolute path alone, which
drops an `is_absolute` branch and, in `resolve.rs`, a fallible
`current_dir()` call.

Three neighbours are deliberately outside the rule, and the docstring
says why:

- Paths wt derives itself — a worktree root from `git worktree list`, an
XDG config directory — arrive absolute.
- `WORKTRUNK_PROJECT_CONFIG_PATH` resolves from the worktree root, its
documented base, because the project config is per-worktree.
- `WORKTRUNK_BIN` and `XDG_CONFIG_DIRS` are never opened by wt: the
first is expanded later by the generated shell wrapper, and the XDG spec
already requires the second to be absolute.

Four integration tests, one per surface, each running from *outside* the
repo with `-C` pointed into it — the neighbouring tests run from a cwd
inside the repo, which is the route that works under either rule. All
four fail against the old code: `switch` with "No branch named
../repo.feature-detached", `remove` by leaving the worktree standing,
and the two config paths by not finding their file.

The `set_base_path` docstring picks up the rule, so the next reader has
one place to find it: `-C` is the base for the two things git takes from
its chdir — the repository discovered, and every path the user names —
while the process cwd stays the answer to where the user's shell
physically is.

## Noticed, not touched

`run_json` and `git_status_segments` duplicate the
worktree-lookup-and-populate sequence (`list_worktrees` → find by root →
`is_home` → `build_worktree_item` → `populate_item` with identical
`CollectOptions`). Worth collapsing separately.

> _This was written by Claude Code on behalf of max_
2026-07-24 15:57:23 -07:00
Maximilian RoosandClaude Fable 5 e02453aa5f feat(list): demote branch-worktree mismatch from red flag to dim info (#3419)
Implements option 3 ("demote the presentation") from the design proposal
in #3415, for #3389: worktrees created by agent harnesses at their own
conventional paths (`.claude/worktrees/…`) made every `wt list` row
carry a red `⚑` at merge-conflict severity.

The list predicate, JSON fields, and Path-column behavior are unchanged;
only the presentation changes:

- `⚑` renders dim yellow (was red) in `wt list`, the picker, and the
`--help` legend: below the full-yellow actionable states (prunable,
locked), above plain dim.
- Priority within the status slot becomes `✘ > ⤴ > ⤵ > ⊟ > ⊞ > ⚑ > /`:
the yellow actionable states (prunable, locked) now outrank the
informational glyph instead of being masked by it. The JSON schema-1
`state` field follows the same priority; schema-2 booleans are
independent and unaffected.
- The inline notice on `wt switch` / `wt remove` / `wt merge` / `wt step
prune` is gone entirely: the `wt list` glyph is the state's one surface.
The `expected_path` plumbing is deleted end to end, so switching to an
existing worktree no longer expands the `worktree-path` template at all
(it only ran to feed the notice).

Before/after on a repo with agent worktrees:

```
+ claude/frosty-kilby-92c7d3     ⚑_        (red ⚑, reads as an error)
+ claude/frosty-kilby-92c7d3     ⚑_        (dim-yellow ⚑, reads as a note)
```

Option 1 from the design doc (narrowing the predicate so only genuine
collisions flag at all) can land separately on top of this.

Well-tested: the pre-merge gate passes (4390 tests), snapshots reviewed
line-by-line (glyph color and priority changes in list/help output; the
notice lines removed from switch/remove output), the removed-notice
tests renamed to pin the silence, and clippy is clean including
`--features shell-integration-tests`. Verified live: `wt list` shows the
dim-yellow flag; `wt switch`/`wt remove` print nothing about the
mismatch.

Thanks to @dmsmidt for the report in #3389.

> _This was written by Claude Code on behalf of max_

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-12 15:27:17 -07:00
Maximilian RoosandClaude Fable 5 57b303fda2 fix(nix): provide lsof to the flake's test sandbox (#3410)
The nix-flake job has failed on main since #3396:
`test_remove_reap_kills_process` discovers its child via `lsof -d cwd`,
but the flake's `worktrunk-tests` check didn't provide `lsof`, so
`processes_under` fails to spawn it, returns an empty list forever, and
the test's 5s discovery poll panics with `child <pid> never discovered`.
Failing main run:
https://github.com/max-sixty/worktrunk/actions/runs/29066326142.

Three changes:

- `flake.nix`: add `pkgs.lsof` to the test check's inputs, the same
pattern as `git`/`python3`/`procps`. `ps` (procps) already works in the
sandbox, so /proc-based process inspection is available there and the
test should be genuinely exercised rather than excluded.
- `.github/workflows/nightly.yaml`: add `flake.nix`, `flake.lock`, and
`nix/**` to the trigger paths (push and PR gate). A flake change
couldn't previously trigger the nix-flake job that validates it; this PR
relies on the fixed trigger for its own validation.
- `tests/integration_tests/remove.rs`: point the discovery-timeout panic
message at lsof, so the next environment missing it doesn't need
re-diagnosing.

Validation: nix isn't available locally, so the proof is this PR's own
nightly run going green on the nix-flake job.

> _This was written by Claude Code on behalf of max_

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 23:29:40 -07:00