Skip to content

fix(prune): approve each pruned worktree's pre-remove - #2701

Merged
max-sixty merged 1 commit into
mainfrom
prune-pre-remove-approval
May 11, 2026
Merged

max-sixty merged 1 commit into
mainfrom
prune-pre-remove-approval

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

wt step prune approved [pre-remove, post-remove, post-switch] as one batch against the cwd worktree's .config/wt.toml. But each pruned worktree's pre-remove actually executes against that worktree's own config (with a primary-worktree fallback), so a pre-remove in a pruned worktree's branch-local config that the cwd config lacks — and that isn't already in approvals.toml — ran without ever appearing in the approval prompt. The analogous gap was fixed for wt remove and wt merge in #2690; this brings wt step prune in line.

Approach

A new approve_prune_hooks in src/commands/step/prune.rs mirrors the executors' config resolution (output::handlers::execute_pre_remove_hooks_if_needed and spawn_hooks_after_remove): collect pre-remove from every CheckSource::Linked worktree (each against its own config, falling back to the primary's), plus post-remove/post-switch once against the primary, then approve the deduped union in a single approve_command_batch call — the same shape as merge::collect_merge_commands. gather_check_items runs before the approval so the candidate set is known.

The parallel integration checks haven't run when approval happens, so this approves pre-remove for every linked worktree prune might prune — a superset of what executes. The dedup-by-template collapses the common case where multiple worktrees fall back to the primary's config. Stale-metadata and orphan-branch removals are correctly excluded: they resolve to RemoveResult::BranchOnly, which runs no hooks. The new spec entry in src/commands/hooks.rs documents the over-approval.

Also dropped the Repository::at(&primary_path).unwrap_or_else(|_| repo.clone()) defensive fallback in main.rs's approve_remove and in the new approve_prune_hooks. home_path() already propagates; the fallback only added silent substitution of the cwd-rooted repo (potentially a worktree being removed) when Repository::at somehow fails on a path home_path() just produced. Plain ? is honest, and identical to every code path tests exercise.

Tests

  • test_prune_branch_local_pre_remove_needs_approval — the regression: a pruned worktree carrying a branch-local pre-remove the cwd config lacks aborts prune (needs-approval, non-interactive). Without the fix, the command succeeds and the hook runs.
  • test_prune_runs_branch_local_pre_remove_hook — --yes runs the branch-local hook and prunes the worktree.
  • test_approval_prompt_prune_decline (PTY) — declining the prompt prints "Commands declined, continuing removal" and prune continues without the hook.

`wt step prune` approved `[pre-remove, post-remove, post-switch]` as one
batch against the *cwd worktree's* `.config/wt.toml`, but each pruned
worktree's `pre-remove` actually executes against *that worktree's* own
config (with a primary-worktree fallback) — so a `pre-remove` in a
pruned worktree's branch-local config that the cwd config lacks, and
that isn't already in `approvals.toml`, ran without ever appearing in
the approval prompt. The analogous gap was fixed for `wt remove` and
`wt merge` in #2690; this brings `wt step prune` in line.

A new `approve_prune_hooks` mirrors the executors' config resolution
(`execute_pre_remove_hooks_if_needed` and `spawn_hooks_after_remove`):
collect `pre-remove` from every linked worktree prune might prune (each
against its own `.config/wt.toml`, falling back to the primary's), plus
`post-remove`/`post-switch` once against the primary, then approve the
deduped union in a single `approve_command_batch` call. Because the
parallel integration checks haven't run when approval happens, this is
a superset of what executes — the new spec entry in `src/commands/hooks.rs`
documents the over-approval. Stale and orphan-branch removals run no
hooks (`RemoveResult::BranchOnly`), so they're correctly excluded.

Also dropped the `Repository::at(&primary_path).unwrap_or_else(|_| repo.clone())`
defensive fallback in `main.rs`'s `approve_remove` and in `approve_prune_hooks`:
`home_path()` already propagates, so silently substituting the cwd-rooted
`repo` (potentially a worktree being removed) would just read the wrong
config. Plain `?` is honest and identical to every test path.

Tests: `test_prune_branch_local_pre_remove_needs_approval` is the regression
(verified to fail with the fix reverted); `test_prune_runs_branch_local_pre_remove_hook`
covers the `--yes` happy path; `test_approval_prompt_prune_decline` (PTY)
covers the interactive-decline path.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@max-sixty
max-sixty merged commit f2ae7b7 into main May 11, 2026
33 checks passed
@max-sixty
max-sixty deleted the prune-pre-remove-approval branch May 11, 2026 08:59
max-sixty added a commit that referenced this pull request May 11, 2026
…tree (#2703)

PR #2690 made every hook resolve its `.config/wt.toml` from the worktree
it acts on, with one documented exception: `wt switch`'s `pre-start` /
`post-start` / `post-switch` still read the invoking worktree's config.
The carve-out was there because the new worktree doesn't exist yet when
those hooks are *approved* — `git worktree add` runs after the approval
gate. This PR eliminates that exception by reading the base ref's
committed `.config/wt.toml` for the pre-creation approval and template
pre-flight, so the prompt always lists the exact commands
`execute_switch` and the background spawn will run.

### What changed

- **`execute_switch`** and **`spawn_switch_background_hooks`** now root
their hook `CommandContext` at the new/destination worktree (via the new
`hook_repo_for_worktree`), falling back to the primary worktree's config
if the destination has none — same rule as
`execute_pre_remove_hooks_if_needed`.
- **`approve_switch_hooks`** and **`validate_switch_templates`** take a
pre-resolved `Option<&ProjectConfig>` rather than reading
`ctx.repo.load_project_config()`. `run_switch` (and the picker) computes
it once via the new `switch_hook_project_config`:
- `SwitchPlan::Existing` → `Repository::at(dest).load_project_config()`.
- `SwitchPlan::Create` / `Regular` → `git show
<base-ref>:.config/wt.toml` via the new `base_ref_for_create`, which
mirrors how `execute_switch` picks the `git worktree add` argument:
explicit `--create` base if one was resolved, else the existing local
branch, else its single remote's tracking ref, else (multi-remote)
`<checkout.defaultRemote>/<branch>` when that matches one of the remotes
— replicating git's DWIM so a `pre-start` on the resolved remote ref
can't run unapproved.
- `SwitchPlan::Create` / `ForkRef` → `git fetch -- <remote> <ref_path>`
then `git show FETCH_HEAD:.config/wt.toml`. `execute_switch` re-fetches
at run time (idempotent). `wt switch pr:N` / `mr:N` is explicit network
work, so fetching at the approval gate is in keeping; the security note
this closes is that for a fork PR the approval prompt now reads the PR's
tree, not the local repo's, so what's listed and what runs can't
diverge.
- Skipped entirely when `--no-hooks` / `--no-verify` is in effect, so
the resolution (including any fetch or primary-config parse) doesn't
fire when the result is unused.
- **`Repository::project_config_at_ref(gitref)`** is the helper for the
`git show` path: pipes the content through
`worktrunk::config::migrate_content` so deprecated patterns still parse,
then `toml::from_str::<ProjectConfig>`. Never writes a `.new` migration
file — the content comes from an arbitrary ref, not the user's working
copy. `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of
the ref, the same as `project_config_path`.
- **`approve_or_skip_with_config`** in `command_approval.rs` is the
switch-side approval entry point. Takes the already-resolved
`ProjectConfig` and reuses `collect_commands_for_hooks` /
`approve_command_batch`; the approvals namespace (`project_identifier`)
still comes from `ctx.repo` since it's repo-wide.
- **Spec**: `commands::hooks` module docstring drops the `wt switch`
exception row. The new row describes the new/destination-worktree
resolution and the `git show` mechanism for `--create`, and the trailing
paragraph now states the invariant directly — every hook is approved
against the same `.config/wt.toml` it executes against. The `wt step
prune` over-approval caveat from #2701 is preserved as the one
documented exception.

### Testing

Four integration tests in `tests/integration_tests/switch.rs`, each
verified to fail before the change:

- `test_switch_create_reads_base_branch_config` — `wt switch --create
new --base other-base` runs `pre-start` / `post-start` from
`other-base`'s committed config; the cwd worktree has none.
- `test_switch_existing_reads_destination_worktree_config` — `wt switch
dest` runs `post-switch` from `dest`'s `.config/wt.toml`.
- `test_switch_pr_reads_pr_ref_config` — `wt switch pr:42` against a PR
ref that carries `.config/wt.toml`: non-interactive shows the PR's hook
in the approval prompt and bails without running it; with `--yes` the
PR's `post-start` runs against the new worktree.
- `test_switch_create_honors_project_config_path_override` —
`WORKTRUNK_PROJECT_CONFIG_PATH` wins everywhere, including the base-ref
preview.

Plus two focused unit tests:
`base_ref_for_create_picks_the_checkout_ref` (the four arms, including
the multi-remote `checkout.defaultRemote` DWIM) and
`project_config_at_ref_reads_committed_config` (committed, missing,
bad-ref, and malformed-TOML cases).

The existing `test_switch_pr_hooks_see_pr_vars` still passes — it
exercises the primary-worktree fallback (PR head ref has no
`.config/wt.toml`, so the on-disk config in the
cwd-which-is-also-primary wins). `cargo run -- hook pre-merge --yes` is
green.

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
max-sixty added a commit that referenced this pull request May 11, 2026
…lution (#2708)

Each of the three `pre-remove` config-resolution call sites — the two
approval helpers (`main.rs::approve_remove`,
`prune::approve_prune_hooks`) and the executor
(`handlers::execute_pre_remove_hooks_if_needed`) — used a `match` that
incidentally swallowed `Err(_)` from `Repository::at(wt_path)` into the
legitimate "no `.config/wt.toml`" fallback. Rewrite as two-step so
`Repository::at` errors propagate; the fallback now fires only when the
removed worktree has no project config.

The executor's inline comment notes why we propagate here rather than
follow the `UserConfig::load()` silent-skip a few lines above: user
config can be benignly malformed, but a path git no longer recognizes as
a worktree is a different kind of failure.

Follows the same shape as the sibling fix in #2701, which replaced
`Repository::at(&primary_path).unwrap_or_else(|_| repo.clone())` with
`?` for the same reason.

`merge.rs::collect_merge_commands` already uses `?` for its
`Repository::at(destination_path)` (refactored in #2690), so it's
untouched.

Co-authored-by: Claude <[email protected]>
max-sixty added a commit that referenced this pull request May 11, 2026
…ve/merge/prune (#2709)

## Summary

`wt remove`, `wt merge`, and `wt step prune` all approve `pre-remove`
against each removed worktree's own `.config/wt.toml` (with
primary-worktree fallback) plus `post-remove`/`post-switch` against the
primary's. The pattern was duplicated in three places — subtle enough
that #2701 had to fix it separately for prune after #2690 fixed it for
remove/merge, and #2708 then had to fix the `Repository::at`
`Err`-swallowing in three places independently. This consolidates the
three call sites into one shared helper, so the next fix-this-pattern PR
only has to touch one place.

## Changes

- `src/commands/project_config.rs` — new
`collect_remove_hook_commands(primary_repo, paths)`. Returns the
`Vec<ApprovableCommand>` for `pre-remove` (per-worktree, with primary
fallback) + `post-remove`/`post-switch` (primary), deduped by template.
Carries forward #2708's `Repository::at(wt_path)?` propagation.
- `src/main.rs::approve_remove` — replaced the per-worktree
`approve_or_skip` loop with a single-batch flow. `wt remove` switches
from N+1 prompts to one combined batch (strictly fewer prompts in
practice; approvals saved by the first prompt would have suppressed
later identical ones anyway).
- `src/commands/merge.rs::collect_merge_commands` —
`pre-remove`/`post-remove`/`post-switch` now come from the helper; merge
keeps its inline `pre-commit`/`post-commit`/`pre-merge`/`post-merge`
collection and bundles everything into the same `approve_command_batch`
call.
- `src/commands/step/prune.rs::approve_prune_hooks` — one-line helper
call. The "over-approval superset" exception remains in the local
docstring.
- `src/commands/hooks.rs` — the "Which `.config/wt.toml` a hook reads"
spec docstring now points at the shared helper.

The executor `output::handlers::execute_pre_remove_hooks_if_needed`
still has its own copy of the pattern (an executor-side, not
approval-side, concern) — left as-is.

## Test plan

- [x] `cargo run -- hook pre-merge --yes` — 3660 tests pass; clippy
clean.
- Existing `wt remove` / `wt merge` / `wt step prune` approval tests
cover both branches of the helper (per-worktree config vs primary
fallback).

Co-authored-by: Claude <[email protected]>
@max-sixty max-sixty mentioned this pull request May 13, 2026
max-sixty added a commit that referenced this pull request May 13, 2026
Release v0.50.0.

Highlights:

- Experimental Azure DevOps support (#1256, thanks @mikeyroush; fixes
#1144 from @dlecan) — `wt switch pr:<N>`, `wt list --full`, and `wt
config show --full` recognize Azure DevOps via the `az` CLI.
- Experimental Gitea CI-status detection (#2702) on top of the Gitea
`pr:` shortcut (#1320, thanks @SjB).
- Hooks now resolve `.config/wt.toml` from the worktree they act on —
the primary-worktree fallback is gone, and `post-remove` reads the
removed worktree's config (snapshotted before removal). Approval prompts
collect hook commands from the same worktree. Breaking change for setups
that relied on the primary-worktree fallback; the changelog entry has
the recovery action. (#2690, #2703, #2714, #2717, #2701, #2708, #2727,
#2736, #2748)
- The `wt switch` picker's `alt-r` removal no longer runs unapproved
project hooks (#2746) — the picker's removal path is now routed through
`handle_remove_output` and consults the existing approval state
read-only.
- `wt config alias show` with no name lists every alias's full
definition (#2684, #2691); `wt --help` switches to a compact aliases
pointer (#2688).
- `wt list --branches` warm-run perf: SHA-keyed cache for `main↕` and
`Remote⇅` ahead/behind counts; shared push-remote URL and local-branch
scan (#2704, #2718, #2673).
- Claude Code plugin ships the `wt-switch-create` skill (#2737, thanks
@onetom for #2631).

See `CHANGELOG.md` for the full list (8 Improved, 5 Fixed, 5 Internal).

semver-checks reports breaking library-API changes (new enum variants
without `#[non_exhaustive]`, removed `Branch::github_push_url`, new
trait method on `RemoteRefProvider`), which mandates at minimum a minor
bump pre-1.0.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants