Repository navigation
fix(hooks): resolve wt switch's post-switch hooks from the new worktree - #2703
Merged
Merged
Conversation
…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
worktrunk-bot
approved these changes
May 11, 2026
This was referenced May 11, 2026
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]>
Merged
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
PR #2690 made every hook resolve its
.config/wt.tomlfrom the worktree it acts on, with one documented exception:wt switch'spre-start/post-start/post-switchstill 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 addruns after the approval gate. This PR eliminates that exception by reading the base ref's committed.config/wt.tomlfor the pre-creation approval and template pre-flight, so the prompt always lists the exact commandsexecute_switchand the background spawn will run.What changed
execute_switchandspawn_switch_background_hooksnow root their hookCommandContextat the new/destination worktree (via the newhook_repo_for_worktree), falling back to the primary worktree's config if the destination has none — same rule asexecute_pre_remove_hooks_if_needed.approve_switch_hooksandvalidate_switch_templatestake a pre-resolvedOption<&ProjectConfig>rather than readingctx.repo.load_project_config().run_switch(and the picker) computes it once via the newswitch_hook_project_config:SwitchPlan::Existing→Repository::at(dest).load_project_config().SwitchPlan::Create/Regular→git show <base-ref>:.config/wt.tomlvia the newbase_ref_for_create, which mirrors howexecute_switchpicks thegit worktree addargument: explicit--createbase 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 apre-starton the resolved remote ref can't run unapproved.SwitchPlan::Create/ForkRef→git fetch -- <remote> <ref_path>thengit show FETCH_HEAD:.config/wt.toml.execute_switchre-fetches at run time (idempotent).wt switch pr:N/mr:Nis 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.--no-hooks/--no-verifyis 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 thegit showpath: pipes the content throughworktrunk::config::migrate_contentso deprecated patterns still parse, thentoml::from_str::<ProjectConfig>. Never writes a.newmigration file — the content comes from an arbitrary ref, not the user's working copy.WORKTRUNK_PROJECT_CONFIG_PATHoverrides the path regardless of the ref, the same asproject_config_path.approve_or_skip_with_configincommand_approval.rsis the switch-side approval entry point. Takes the already-resolvedProjectConfigand reusescollect_commands_for_hooks/approve_command_batch; the approvals namespace (project_identifier) still comes fromctx.reposince it's repo-wide.commands::hooksmodule docstring drops thewt switchexception row. The new row describes the new/destination-worktree resolution and thegit showmechanism for--create, and the trailing paragraph now states the invariant directly — every hook is approved against the same.config/wt.tomlit executes against. Thewt step pruneover-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-baserunspre-start/post-startfromother-base's committed config; the cwd worktree has none.test_switch_existing_reads_destination_worktree_config—wt switch destrunspost-switchfromdest's.config/wt.toml.test_switch_pr_reads_pr_ref_config—wt switch pr:42against 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--yesthe PR'spost-startruns against the new worktree.test_switch_create_honors_project_config_path_override—WORKTRUNK_PROJECT_CONFIG_PATHwins 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-remotecheckout.defaultRemoteDWIM) andproject_config_at_ref_reads_committed_config(committed, missing, bad-ref, and malformed-TOML cases).The existing
test_switch_pr_hooks_see_pr_varsstill 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 --yesis green.