Skip to content

fix(hooks): resolve wt switch's post-switch hooks from the new worktree - #2703

Merged
max-sixty merged 2 commits into
mainfrom
switch-create-hook-config
May 11, 2026
Merged

max-sixty merged 2 commits into
mainfrom
switch-create-hook-config

Conversation

@max-sixty

Copy link
Copy Markdown
Owner

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 fix(prune): approve each pruned worktree's pre-remove #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.

max-sixty and others added 2 commits May 11, 2026 02:11
…tree

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 commit eliminates the 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.

### Testing

Four integration tests (`tests/integration_tests/switch.rs`),
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` (covers 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).

Existing hook / switch suites pass; the existing
`test_switch_pr_hooks_see_pr_vars` still exercises the primary-worktree
fallback (PR head ref has no `.config/wt.toml`).
`cargo run -- hook pre-merge --yes` is green (3633 tests).

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts:
#	src/commands/hooks.rs
@max-sixty
max-sixty merged commit 5384f62 into main May 11, 2026
33 checks passed
@max-sixty
max-sixty deleted the switch-create-hook-config branch May 11, 2026 09:28
max-sixty added a commit that referenced this pull request May 11, 2026
… ref (#2711)

`Repository::project_config_at_ref` (added in #2703) runs `git show
<ref>:.config/wt.toml`. If the ref starts with `-` — e.g. a branch
literally named `-foo` — git's option parser rejects the argument as a
flag and the helper silently returns `None` even though the file exists.
Passing `--end-of-options` tells git's parser everything after it is
positional, which fixes the bare-ref case used by `wt switch`'s
`pre-start` / `post-start` / `post-switch` hook-approval gate.

The vulnerable refs in practice are the explicit `--create --base <ref>`
argument, a local branch name, and `<remote>/<branch>` — `HEAD` /
`FETCH_HEAD` are safe. Creating such a branch is hard but possible (`git
update-ref refs/heads/-foo HEAD`), and the fix is one extra arg.

Added a unit test that creates `refs/heads/-foo` via `update-ref`
(modern git rejects `git branch -- -foo`) and asserts the config
round-trips through `project_config_at_ref`.

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

## Summary

Each worktree's `.config/wt.toml` now stands alone. When the worktree a
hook acts on has no `.config/wt.toml`, no project hooks run — the
primary worktree's config is no longer consulted as a fallback. A
present-but-malformed config aborts the operation with the parse error
instead of silently using a different one.

## Why

The fallback (#2690, extended to `wt switch` in #2703) was an internal
detail meant to keep worktrees branched off *before* a hook was added
still firing the hook. But it made which file each hook actually reads
ambiguous — Codex flagged this in review of #2703 (P3): a destination
worktree with a malformed `.config/wt.toml` silently ran the *primary's*
hooks instead of surfacing the parse error.

Removing the fallback gives a cleaner model: each worktree owns its
config. Users who want a hook to apply project-wide commit it on the
default branch — new worktrees branched off that branch inherit it.
Worktrees branched off *before* the commit no longer fire the hook
silently, which was the leaky part.

## Behavior change

A `pre-remove` hook added on `main` no longer fires when removing a
feature worktree that predates the commit adding it. To restore that
behavior, branch the feature off `main` again (or commit the hook on the
feature branch itself).

## What changed

- `Repository::project_config_at_ref` now returns
`anyhow::Result<Option<ProjectConfig>>` — `Ok(None)` for refs with no
`.config/wt.toml`, `Err` for present-but-malformed.
- Dropped the fallback from
`commands::project_config::collect_remove_hook_commands` (the shared
helper introduced in #2709) and from
`output::handlers::execute_pre_remove_hooks_if_needed`,
`worktree::switch::{switch_hook_project_config, hook_repo_for_worktree,
spawn_switch_background_hooks}`, and
`worktree::finish::finish_after_merge`.
- Updated the `commands::hooks` spec docstring — table rows lose the
fallback sub-clauses; trailing paragraph drops the fallback handling.

## Tests

- Unit test `project_config_at_ref_reads_committed_config` now asserts
`Err` on malformed committed config (was `None`).
- Added `test_switch_existing_aborts_on_malformed_destination_config`
and `test_remove_aborts_on_malformed_worktree_config` for the end-to-end
abort path.
- Updated three tests that relied on the fallback to commit configs on
the relevant branches instead: `test_switch_pr_hooks_see_pr_vars`
(commits on `pr-source`),
`test_merge_teardown_hooks_read_destination_worktree_config` →
`..._read_acting_worktree_config` (feature carries pre-remove),
`test_approval_prompt_remove_decline` (commits before creating the
worktree to remove). Snapshot regenerated for the last.

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