Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

fix(hooks): resolve all hook config from the invoking worktree (#2873)

Maximilian Roos1716ecab379f
diff --git a/docs/content/hook.md b/docs/content/hook.md
index 0f23aef7c..0305fdc25 100644
--- a/docs/content/hook.md
+++ b/docs/content/hook.md
@@ -69,7 +69,7 @@ Manage approvals with `wt config approvals add` and `wt config approvals clear`.
# Configuration
-Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format.
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format. The project config is read from the worktree the command ran in.
## Hook forms
diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.md
index cd73c98db..dbde00f2c 100644
--- a/skills/worktrunk/reference/hook.md
+++ b/skills/worktrunk/reference/hook.md
@@ -60,7 +60,7 @@ Manage approvals with `wt config approvals add` and `wt config approvals clear`.
# Configuration
-Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format.
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format. The project config is read from the worktree the command ran in.
## Hook forms
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 3b41d7c9e..48418a4f0 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -1281,7 +1281,7 @@ Manage approvals with `wt config approvals add` and `wt config approvals clear`.
# Configuration
-Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format.
+Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format. The project config is read from the worktree the command ran in.
## Hook forms
diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rs
index 7f952b13e..7f43e69d8 100644
--- a/src/commands/hook_plan.rs
+++ b/src/commands/hook_plan.rs
@@ -29,9 +29,9 @@
//! so it cannot re-select.
//!
//! The frozen unit is the *selected, source-tagged [`CommandConfig`] list* per
-//! `(HookType, anchor)` — the anchor being the worktree the hook is *about*
-//! (its config source). Rendering stays deferred (post-`*` hooks legitimately
-//! need post-operation context like the merge commit), but it consumes
+//! `(HookType, anchor)` — the anchor being the worktree the hook runs in.
+//! Rendering stays deferred (post-`*` hooks legitimately need post-operation
+//! context like the merge commit), but it consumes
//! `&[(HookSource, CommandConfig)]`, so it cannot change the set. The
//! authorization-relevant artifact is the template set, which is exactly what
//! [`Approvals`] stores and the prompt shows.
@@ -68,10 +68,10 @@ use super::project_config::{ApprovableCommand, Phase};
/// handle to re-resolve from.
type Selection = Vec<(HookSource, CommandConfig)>;
-/// One frozen entry: the hook type, the anchor worktree (the `.config/wt.toml`
-/// the hook reads — stored as the caller provides it; the gate and executor
-/// both derive it from the same value, so equality holds without
-/// canonicalization), and that pair's source-tagged selection.
+/// One frozen entry: the hook type, the anchor worktree (the worktree the hook
+/// runs in — stored as the caller provides it; the gate and executor both
+/// derive it from the same value, so equality holds without canonicalization),
+/// and that pair's source-tagged selection.
struct PlanEntry {
hook_type: HookType,
anchor: PathBuf,
@@ -83,7 +83,8 @@ pub struct HookPlan {
entries: Vec<PlanEntry>,
}
-/// Accumulates per-anchor selections from each worktree's resolved config.
+/// Accumulates per-anchor selections from the invoking worktree's resolved
+/// config.
///
/// `add` is the only place `load_project_config()`'s result feeds command
/// selection for the covered hook types — `pub(crate)` and called only from
@@ -100,7 +101,7 @@ impl HookPlanBuilder {
}
/// Select `hook_types` anchored at `anchor`, from the already-resolved
- /// `project_config` (the gate snapshots / `git show`s it) plus user config.
+ /// `project_config` (the gate snapshots it) plus user config.
///
/// `project_id` scopes the user-config hook lookup. Source identity is
/// preserved so source-scoped behavior survives into execution.
@@ -322,10 +323,11 @@ fn render_planned(
/// signature carries no config — only the plan, the render context, and the
/// failure strategy.
///
-/// `anchor` is the worktree the hook's config was selected from at the gate
-/// (usually `ctx.worktree_path`, but for `post-remove` the removed worktree
-/// while `ctx` runs in the destination). It is *not* a config handle — just
-/// the lookup key into the frozen plan.
+/// `anchor` is the worktree the hook runs in (usually `ctx.worktree_path`, but
+/// for `post-remove` the removed worktree while `ctx` runs in the destination).
+/// It is *not* a config handle — just the lookup key into the frozen plan. The
+/// gate always selects from the invoking worktree's config, which need not be
+/// the anchor.
pub fn execute_planned_hook(
plan: &ApprovedHookPlan,
anchor: &Path,
@@ -355,7 +357,8 @@ pub fn execute_planned_hook(
/// rendered from the frozen selection and added via the announcer's existing
/// config-free `extend`, with no `load_project_config()` at execution.
///
-/// `anchor` is the gate's config-source worktree (see [`execute_planned_hook`]).
+/// `anchor` is the worktree the hook runs in — the lookup key into the frozen
+/// plan (see [`execute_planned_hook`]).
pub fn register_planned(
announcer: &mut HookAnnouncer<'_>,
plan: &ApprovedHookPlan,
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 0702de687..b539c5e1f 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -5,26 +5,37 @@
//!
//! # Which `.config/wt.toml` a hook reads
//!
-//! Every hook is anchored to one worktree: the worktree it is *about*. It runs
-//! the commands selected from that worktree's `.config/wt.toml`. Two execution
-//! models split on whether a state mutation separates the approval gate from
-//! execution.
+//! Every hook resolves its commands from the **invoking** worktree's
+//! `.config/wt.toml` — the worktree `wt` ran in, read from its working tree.
+//! That holds regardless of which worktree the hook is *about*: `post-merge`
+//! runs in the merge target and `post-start` in the newly created worktree,
+//! but both select their commands from the invoking worktree's config — the
+//! same file `wt config show` reads.
+//!
+//! Two execution models split on whether a state mutation separates the
+//! approval gate from execution.
//!
//! **Plan-backed (the TOCTOU-covered set):** `pre-merge`, `post-merge`,
//! `pre-remove`, `post-remove`, `post-switch`, `pre-start`, `post-start`. A
//! merge, rebase, removal, or `git worktree add` runs between the gate and
-//! these hooks, so a second config read could select a command the user never
-//! approved. Each command gate selects the commands once and freezes them into
-//! a [`super::hook_plan::ApprovedHookPlan`]; the executor renders and runs only
+//! these hooks; a rebase can even rewrite the invoking worktree's own
+//! `.config/wt.toml`, so a second config read could select a command the user
+//! never approved. Each command gate calls `load_project_config()` on the
+//! invoking worktree once, selects the commands, and freezes them into a
+//! [`super::hook_plan::ApprovedHookPlan`]; the executor renders and runs only
//! that frozen value via [`super::hook_plan::execute_planned_hook`] /
//! [`super::hook_plan::register_planned`], holding no `ProjectConfig` to
//! re-derive from. See the [`super::hook_plan`] module spec.
//!
-//! | Plan-backed hook | Anchor worktree | Gate builds the plan in |
+//! | Plan-backed hook | Runs in (the anchor) | Gate |
//! |---|---|---|
//! | `pre-merge`, `pre-remove`, `post-remove` | the feature/removed worktree | `merge::approve_merge_plan`, `main.rs`'s `approve_remove`, `step::prune::approve_prune_hooks` |
//! | `post-merge`, `post-switch` (after a removal) | the merge/removal destination | the same gates |
-//! | `pre-start`, `post-start`, `post-switch` (on switch) | the new/destination worktree (the `--create` base ref's committed config, read via `git show` by `switch_hook_project_config`) | `worktree::switch::approve_switch_hooks` |
+//! | `pre-start`, `post-start`, `post-switch` (on switch) | the new/destination worktree | `worktree::switch::approve_switch_hooks` |
+//!
+//! "Runs in" is the *anchor* — the executor's plan lookup key and render root,
+//! not a config source. A `pre-start`'s new worktree need not exist when the
+//! gate runs; the config came from the invoking worktree regardless.
//!
//! **Invocation-resolved (no gate→exec mutation):** `pre-commit`,
//! `post-commit`, `pre-switch`, `wt hook <type>`, aliases. They resolve config
@@ -40,19 +51,16 @@
//! (empty cache) breaks (2) and silently reintroduces the TOCTOU even if (1)
//! still holds — there is no compile-time guard here, unlike the plan-backed
//! set. (Aliases get the property structurally instead: the body is frozen
-//! into `AliasEntry` before the gate, like `ApprovedHookPlan`.) Anchors:
-//! `pre-commit`/`post-commit` the worktree being committed (cwd, or `<b>`'s
-//! worktree for `wt step commit --branch <b>`); `pre-switch`, `pre-merge`'s
-//! manual `wt hook`, and aliases the worktree `wt` was invoked in.
+//! into `AliasEntry` before the gate, like `ApprovedHookPlan`.)
+//!
+//! `ctx.repo` is the invoking worktree — except `wt step commit --branch <b>`
+//! and `wt -C <path>` re-root the whole command (the commit, its hooks, and
+//! `ctx.repo` are all `<b>`), so "the invoking worktree" follows them.
//!
-//! Each worktree's `.config/wt.toml` stands alone: no fallback to the primary
-//! worktree's config when the anchor has none, and a present-but-malformed
-//! config aborts the operation rather than silently using a different one.
-//! `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of the root
+//! A present-but-malformed config aborts the operation rather than silently
+//! running something else. `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path
//! (test isolation); user config (`~/.config/worktrunk/config.toml`) is global
-//! and unaffected. `wt step prune` selects over every linked worktree it might
-//! prune (the integrated set isn't known until the checks run), a superset of
-//! what executes.
+//! and unaffected.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index f4615bfa2..33ea65def 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -77,10 +77,13 @@ pub struct MergeOptions<'a> {
/// Build the frozen [`ApprovedHookPlan`] for the merge's covered hooks, gating
/// every project command once.
///
-/// Each hook is anchored to the worktree it reads `.config/wt.toml` from:
+/// Every hook selects its commands from the invoking worktree's
+/// `.config/wt.toml` — `repo`'s cwd, the feature worktree `wt merge` ran in.
+/// The *anchor* — the executor's plan lookup key — is the worktree each hook
+/// runs in:
///
/// - `pre-commit` / `post-commit` / `pre-merge` / `pre-remove` / `post-remove`
-/// → the feature worktree (`repo`'s cwd).
+/// → the feature worktree.
/// - `post-merge` / `post-switch` → the merge destination.
///
/// `pre-commit`/`post-commit` execute via the unchanged commit/squash path
@@ -125,28 +128,27 @@ fn approve_merge_plan(
feature_hooks.push(HookType::PostRemove);
}
- // Read each `.config/wt.toml` only when a hook actually needs it: with
- // `--no-hooks` (`verify` false) nothing is selected, so a malformed or
- // inaccessible destination/feature config must not fail the merge.
+ // Every merge hook resolves against the invoking worktree's
+ // `.config/wt.toml` — the feature worktree `wt merge` ran in. Read once,
+ // inside the `verify` gate: `--no-hooks` selects no hook, so the gate needs
+ // no config.
let mut builder = HookPlanBuilder::new();
- if !feature_hooks.is_empty() {
- let feature_cfg = repo.load_project_config()?;
+ if verify {
+ let project_config = repo.load_project_config()?;
builder.add(
feature_root,
&feature_hooks,
- feature_cfg.as_ref(),
+ project_config.as_ref(),
config,
pid,
);
- }
- if verify {
- // `post-merge` reads the destination; `post-switch` (feature worktree
- // removed → user lands here) reads the same destination config.
- let dest_cfg = Repository::at(destination_path)?.load_project_config()?;
+ // `post-merge` runs in the destination, and `post-switch` lands the
+ // user there (the feature worktree is removed) — both still selected
+ // from the invoking worktree's config.
builder.add(
destination_path,
&[HookType::PostMerge],
- dest_cfg.as_ref(),
+ project_config.as_ref(),
config,
pid,
);
@@ -154,7 +156,7 @@ fn approve_merge_plan(
builder.add(
destination_path,
&[HookType::PostSwitch],
- dest_cfg.as_ref(),
+ project_config.as_ref(),
config,
pid,
);
@@ -224,9 +226,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let target_branch = repo.require_target_branch(target)?;
// Worktree for target is optional: if present we use it for safety checks and as destination.
let target_worktree_path = repo.worktree_for_branch(&target_branch)?;
- // Where `post-merge` / `post-remove` / `post-switch` run (and resolve their
- // `.config/wt.toml`): the target branch's worktree if it exists, else the
- // primary worktree. Mirrors `finish_after_merge`'s destination resolution.
+ // Where `post-merge` / `post-remove` / `post-switch` run: the target
+ // branch's worktree if it exists, else the primary worktree. Mirrors
+ // `finish_after_merge`'s destination resolution. (Config is resolved from
+ // the invoking worktree, not here — see `approve_merge_plan`.)
let destination_path = match &target_worktree_path {
Some(path) => path.clone(),
None => repo.home_path()?,
diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rs
index 932b83732..0042d586e 100644
--- a/src/commands/picker/mod.rs
+++ b/src/commands/picker/mod.rs
@@ -229,9 +229,11 @@ impl PickerCollector {
/// and the TUI stays responsive. A removal failure is logged; the item stays
/// gone from the picker — a tradeoff until we can show in-progress state.
///
- /// `repo` is only used for `BranchOnly` deletion; `RemovedWorktree` removal
- /// is rooted at `main_path` (which may differ from the picker's startup repo
- /// in bare-repo setups).
+ /// `repo` is the worktree the picker is operating from — the config source
+ /// for the removal hooks (see [`approved_removal_plan`]) and the target of
+ /// a `BranchOnly` deletion. `RemovedWorktree` removal itself is rooted at
+ /// `main_path` (which may differ from the picker's startup repo in bare-repo
+ /// setups).
fn do_removal(
repo: &Repository,
result: &RemoveResult,
@@ -244,7 +246,7 @@ impl PickerCollector {
..
} => {
let main_repo = Repository::at(main_path)?;
- let plan = approved_removal_plan(&main_repo, main_path, worktree_path, approvals)?;
+ let plan = approved_removal_plan(repo, main_path, worktree_path, approvals)?;
let mut announcer = HookAnnouncer::new(&main_repo, main_repo.user_config(), false);
handle_remove_output(
result,
@@ -366,16 +368,17 @@ impl CommandCollector for PickerCollector {
/// Whether every `pre-remove` / `post-remove` / `post-switch` command this
/// removal would run is already approved — a read-only check, no prompt.
///
-/// `main_path` is the post-removal destination (where `post-switch` reads its
-/// config, same as the executor); `worktree_path` is the worktree being
-/// removed (where `pre-remove` / `post-remove` read theirs). `wt remove` /
-/// `wt merge` collect the same command set and prompt for it at the gate; the
-/// picker can't prompt mid-render, so it runs the removal's hooks only when
-/// they're already approved (e.g. from a prior `wt remove` / `wt merge`) and
-/// skips them otherwise — unapproved project commands must never run. See
-/// CLAUDE.md → "Project Commands Run Only After Approval".
+/// `repo` is the worktree the picker is operating from; its `.config/wt.toml`
+/// is what every removal hook resolves against, matching `wt remove` /
+/// `wt merge`. `main_path` is the post-removal destination (the `post-switch`
+/// anchor); `worktree_path` is the worktree being removed (the `pre-remove` /
+/// `post-remove` anchor). The picker can't prompt mid-render, so it runs the
+/// removal's hooks only when they're already approved (e.g. from a prior
+/// `wt remove` / `wt merge`) and skips them otherwise — unapproved project
+/// commands must never run. See CLAUDE.md → "Project Commands Run Only After
+/// Approval".
fn approved_removal_plan(
- main_repo: &Repository,
+ repo: &Repository,
main_path: &Path,
worktree_path: &Path,
approvals: &Approvals,
@@ -383,24 +386,23 @@ fn approved_removal_plan(
// Non-fatal: an unresolvable project identifier just means no project
// pipeline can be matched against approvals — `approve_readonly` then
// drops them (fail-closed), rather than aborting the picker removal.
- let project_id = main_repo.project_identifier().ok();
+ let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
- let user = main_repo.user_config();
- let removed_cfg = Repository::at(worktree_path)?.load_project_config()?;
- let dest_cfg = Repository::at(main_path)?.load_project_config()?;
+ let user = repo.user_config();
+ let project_config = repo.load_project_config()?;
let mut builder = HookPlanBuilder::new();
builder.add(
worktree_path,
&[HookType::PreRemove, HookType::PostRemove],
- removed_cfg.as_ref(),
+ project_config.as_ref(),
user,
pid,
);
builder.add(
main_path,
&[HookType::PostSwitch],
- dest_cfg.as_ref(),
+ project_config.as_ref(),
user,
pid,
);
@@ -1240,13 +1242,14 @@ pub mod tests {
])
.unwrap();
- // A `pre-remove` hook in the removed worktree's `.config/wt.toml` that
- // would write a marker (outside the worktree) if it ever ran.
+ // A `pre-remove` hook in the invoking worktree's `.config/wt.toml` —
+ // the config the picker removal resolves against — that would write a
+ // marker if it ever ran.
let marker_dir = tempfile::tempdir().unwrap();
let marker = marker_dir.path().join("pre-remove-ran");
- fs::create_dir_all(wt_path.join(".config")).unwrap();
+ fs::create_dir_all(test.path().join(".config")).unwrap();
fs::write(
- wt_path.join(".config/wt.toml"),
+ test.path().join(".config/wt.toml"),
format!("pre-remove = {:?}\n", format!("touch {}", marker.display())),
)
.unwrap();
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 977ca0d14..f051fcf5b 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -321,7 +321,7 @@ impl RepositoryCliExt for Repository {
// No `.config/wt.toml` snapshot: `pre-remove` / `post-remove` were
// selected and frozen into the `ApprovedHookPlan` at the gate
// (`main.rs`'s `approve_remove`), anchored at this worktree's path, so
- // the executor never re-reads the removed worktree's config.
+ // the executor needs no config — it runs only the frozen plan.
Ok(RemoveResult::RemovedWorktree {
main_path,
worktree_path,
diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rs
index 4f09df3c1..737f13f20 100644
--- a/src/commands/step/prune.rs
+++ b/src/commands/step/prune.rs
@@ -420,8 +420,8 @@ fn render_dry_run(
/// selection is a superset of what executes (extra anchors are simply never
/// looked up). `post-switch` is anchored at the primary worktree: a prune
/// candidate is never the primary, so each removal's
-/// `RemoveResult::destination_path()` is `home_path()`. No fallback between
-/// worktrees — each `.config/wt.toml` stands alone.
+/// `RemoveResult::destination_path()` is `home_path()`. Every hook is selected
+/// from the invoking worktree's `.config/wt.toml`, whatever its anchor.
///
/// A declined prompt yields an empty plan — every executor runs no hooks.
fn approve_prune_hooks(
@@ -437,6 +437,9 @@ fn approve_prune_hooks(
// and `approve` never needs it).
let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
+ // Every prune hook is selected from the invoking worktree's
+ // `.config/wt.toml` — the worktree `wt step prune` ran in.
+ let project_config = repo.load_project_config()?;
let removed_worktree_paths: Vec<&Path> = check_items
.iter()
@@ -448,20 +451,18 @@ fn approve_prune_hooks(
let mut builder = HookPlanBuilder::new();
for &wt_path in &removed_worktree_paths {
- let cfg = Repository::at(wt_path)?.load_project_config()?;
builder.add(
wt_path,
&[HookType::PreRemove, HookType::PostRemove],
- cfg.as_ref(),
+ project_config.as_ref(),
config,
pid,
);
}
- let primary_cfg = Repository::at(&primary_path)?.load_project_config()?;
builder.add(
&primary_path,
&[HookType::PostSwitch],
- primary_cfg.as_ref(),
+ project_config.as_ref(),
config,
pid,
);
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index 6c9ac0aa2..236e98ffe 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -147,7 +147,7 @@ pub fn finish_after_merge(
// No config snapshot: `pre-remove` / `post-remove` were selected and
// frozen into `plan` at the gate (anchored at `feature_path`), so the
- // executor never re-reads the removed worktree's `.config/wt.toml`.
+ // executor needs no config — it runs only the frozen `plan`.
let remove_result = RemoveResult::RemovedWorktree {
main_path: destination_path.clone(),
worktree_path: worktree_root,
diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rs
index 9b9ac0954..4b11b5789 100644
--- a/src/commands/worktree/hooks.rs
+++ b/src/commands/worktree/hooks.rs
@@ -18,7 +18,7 @@ impl<'a> CommandContext<'a> {
///
/// Runs user hooks first, then project hooks. `anchor` is the new
/// worktree's path — the gate selected `pre-start` under it from the
- /// base-ref config; the executor never re-reads the (now on-disk) config.
+ /// invoking worktree's config; the executor never re-reads any config.
/// Shows path in hook announcements when shell integration isn't active
/// (the user's shell won't cd to the new worktree).
pub fn execute_pre_create_commands(
diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rs
index 64b8db4d4..c3befc972 100644
--- a/src/commands/worktree/switch.rs
+++ b/src/commands/worktree/switch.rs
@@ -14,8 +14,7 @@ use dunce::canonicalize;
use serde::Serialize;
use worktrunk::HookType;
use worktrunk::config::{
- ProjectConfig, UserConfig, ValidationScope, expand_template, template_references_var,
- validate_template,
+ UserConfig, ValidationScope, expand_template, template_references_var, validate_template,
};
use worktrunk::git::remote_ref::{
self, AzureDevOpsProvider, GitHubProvider, GitLabProvider, GiteaProvider, RemoteRefInfo,
@@ -1139,11 +1138,12 @@ fn execute_switch(
CreationMethod::Regular { .. } => (None, None),
};
- // Execute pre-start commands. The hook resolves its `.config/wt.toml`
- // from the new worktree (created just above) — see
- // `hook_repo_for_worktree`.
+ // Execute pre-start commands. `hook_repo` roots the render context
+ // in the new worktree (created just above); the commands come from
+ // the frozen `hook_plan`, selected at the gate from the invoking
+ // worktree's config.
if run_hooks {
- let hook_repo = hook_repo_for_worktree(&worktree_path)?;
+ let hook_repo = Repository::at(&worktree_path)?;
let ctx =
CommandContext::new(&hook_repo, config, Some(&branch), &worktree_path, force);
let mut vars = TemplateVars::new()
@@ -1365,109 +1365,12 @@ fn switch_post_hook_types(is_create: bool) -> &'static [HookType] {
}
}
-/// The git ref a `wt switch --create` (or a branchless `wt switch <branch>`
-/// that has to create a worktree) checks out into the new worktree — covers
-/// [`CreationMethod::Regular`] only; [`CreationMethod::ForkRef`] needs a
-/// `git fetch` first and is handled by [`switch_hook_project_config`].
-///
-/// Used to read that ref's committed `.config/wt.toml` before the worktree
-/// exists. Mirrors how [`execute_switch`] picks the `git worktree add`
-/// argument: an explicit `--create` base if one was resolved, else the
-/// existing local branch, else its single remote's tracking ref, else `HEAD`
-/// (the current worktree's tip — git's fallback for `git worktree add -b
-/// <new>` with no base, and the only thing left for a stale default branch).
-fn base_ref_for_create(
- repo: &Repository,
- create_branch: bool,
- base_branch: Option<&str>,
- branch: &str,
-) -> String {
- if create_branch {
- return base_branch.unwrap_or("HEAD").to_string();
- }
- if repo.branch(branch).exists_locally().unwrap_or(false) {
- return branch.to_string();
- }
- let remotes = repo.branch(branch).remotes().unwrap_or_default();
- if remotes.len() == 1 {
- return format!("{}/{}", remotes[0], branch);
- }
- // Multiple remotes: replicate `git worktree add <branch>`'s DWIM — when
- // `checkout.defaultRemote` names one of these remotes, that's the ref the
- // new worktree will check out, so the hook preview must match. Without
- // this, a `pre-start` on `<defaultRemote>/<branch>` could run unapproved
- // because the preview defaulted to `HEAD`.
- if remotes.len() > 1
- && let Ok(Some(default)) = repo.config_value("checkout.defaultRemote")
- && remotes.iter().any(|r| r == &default)
- {
- return format!("{default}/{branch}");
- }
- "HEAD".to_string()
-}
-
-/// The `.config/wt.toml` that `wt switch`'s post-switch hooks (`pre-start` /
-/// `post-start` / `post-switch`) will resolve against, viewed from *before*
-/// the worktree is created — so the approval prompt and the pre-flight
-/// template validation see the exact config `execute_switch` /
-/// [`spawn_switch_background_hooks`] (via [`hook_repo_for_worktree`]) read at
-/// run time.
-///
-/// For an existing destination the worktree is on disk, so its config is read
-/// directly. For `--create` the new worktree is a checkout of the resolved
-/// base ref (or, for `pr:`/`mr:` fork refs, the fetched PR/MR head), so the
-/// committed `.config/wt.toml` at that ref is read via `git show`. In either
-/// case `Ok(None)` means the destination worktree has no `.config/wt.toml`
-/// at all — no project hooks run; the primary worktree's config is not
-/// consulted. A present-but-malformed config surfaces as `Err` so the user
-/// fixes it rather than silently running a different one.
-///
-/// May `git fetch` a `pr:`/`mr:` fork head ref — `wt switch pr:`/`mr:` is the
-/// user explicitly invoking network work, so fetching at the approval gate is
-/// in keeping; `execute_switch` re-fetches (idempotent).
-fn switch_hook_project_config(
- repo: &Repository,
- plan: &SwitchPlan,
-) -> anyhow::Result<Option<ProjectConfig>> {
- match plan {
- SwitchPlan::Existing { path, .. } => Repository::at(path)?.load_project_config(),
- SwitchPlan::Create { method, branch, .. } => {
- let base_ref = match method {
- CreationMethod::ForkRef {
- remote, ref_path, ..
- } => {
- repo.run_command(&["fetch", "--", remote, ref_path])
- .with_context(|| format!("Failed to fetch {ref_path} from {remote}"))?;
- "FETCH_HEAD".to_string()
- }
- CreationMethod::Regular {
- create_branch,
- base_branch,
- ..
- } => base_ref_for_create(repo, *create_branch, base_branch.as_deref(), branch),
- };
- repo.project_config_at_ref(&base_ref)
- }
- }
-}
-
-/// The `Repository` whose `.config/wt.toml` a post-switch hook running in
-/// `worktree_path` should read: the new/destination worktree itself. No
-/// fallback — when the worktree has no `.config/wt.toml`, no project hooks
-/// run, matching what [`switch_hook_project_config`] surfaced to the approval
-/// prompt.
-fn hook_repo_for_worktree(worktree_path: &Path) -> anyhow::Result<Repository> {
- Repository::at(worktree_path)
-}
-
/// Approve switch hooks upfront and show "Commands declined" if needed.
///
-/// `project_config` is the `.config/wt.toml` the post-switch hooks will run
-/// against — the new/destination worktree's (or, for `--create`, the base
-/// ref's), resolved by [`switch_hook_project_config`]. Passing it in (rather
-/// than letting the approval read `ctx.repo`'s config) is what keeps the
-/// prompt listing the exact commands `execute_switch` will run, including for
-/// `wt switch pr:N` against a fork's hooks.
+/// Switch hooks resolve their commands from the invoking worktree's
+/// `.config/wt.toml` — the worktree `wt switch` ran in. Selecting them here,
+/// at the gate, freezes the exact commands `execute_switch` will run into the
+/// [`ApprovedHookPlan`].
///
/// Returns `(hooks_approved, plan)`. `hooks_approved` is `false` and the plan
/// empty when `!verify` or the user declined; the covered switch hooks
@@ -1478,7 +1381,6 @@ fn approve_switch_hooks(
plan: &SwitchPlan,
yes: bool,
verify: bool,
- project_config: Option<&ProjectConfig>,
) -> anyhow::Result<(bool, ApprovedHookPlan)> {
if !verify {
return Ok((false, ApprovedHookPlan::empty()));
@@ -1489,11 +1391,12 @@ fn approve_switch_hooks(
// and `approve` never needs it).
let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
+ let project_config = repo.load_project_config()?;
let mut builder = HookPlanBuilder::new();
builder.add(
plan.worktree_path(),
switch_post_hook_types(plan.is_create()),
- project_config,
+ project_config.as_ref(),
config,
pid,
);
@@ -1523,10 +1426,9 @@ fn spawn_switch_background_hooks(
) -> anyhow::Result<()> {
// Background hooks run in the new/destination worktree. `hook_repo` roots
// the *render* context there; the command set is the frozen `hook_plan`
- // (anchored at the destination at the gate, from the base-ref config for
- // `--create`), so the worktree's on-disk `.config/wt.toml` is never
- // re-read.
- let hook_repo = hook_repo_for_worktree(result.path())?;
+ // (selected at the gate from the invoking worktree's config), so no
+ // `.config/wt.toml` is re-read.
+ let hook_repo = Repository::at(result.path())?;
let ctx = CommandContext::new(&hook_repo, config, branch, result.path(), yes);
let mut announcer = HookAnnouncer::new(&hook_repo, config, false);
@@ -1696,48 +1598,17 @@ impl SwitchPipeline<'_> {
}
})?;
- // Resolve the `.config/wt.toml` the post-switch hooks will run against —
- // the new/destination worktree's (for `--create`, the base ref's, read
- // via `git show` since the worktree doesn't exist yet). Computed once so
- // the approval prompt and the template pre-flight below agree with what
- // `execute_switch` / `spawn_switch_background_hooks` resolve at run time.
- // (May `git fetch` a `pr:`/`mr:` fork head — explicit network work.)
- //
- // Skip entirely when `--no-hooks` / `--no-verify` is in effect: with
- // hooks disabled, the result is never used, and resolving it could fetch
- // from a PR ref or read a primary `.config/wt.toml` the user asked us
- // not to touch.
- let hook_project_config = if verify {
- switch_hook_project_config(repo, &plan)?
- } else {
- None
- };
-
// "Approve at the Gate": collect and approve hooks upfront. Approval
// happens once at the command entry point. If the user declines, skip
- // hooks but continue with the worktree operation.
- let (hooks_approved, hook_plan) = approve_switch_hooks(
- repo,
- config,
- &plan,
- yes,
- verify,
- hook_project_config.as_ref(),
- )?;
+ // hooks but continue with the worktree operation. Switch hooks resolve
+ // their config from the invoking worktree — see `approve_switch_hooks`.
+ let (hooks_approved, hook_plan) = approve_switch_hooks(repo, config, &plan, yes, verify)?;
// Pre-flight: validate all templates before mutation (worktree
// creation). Catches syntax errors and undefined variables early so a
// broken template doesn't leave behind a half-created worktree that
// blocks re-running.
- validate_switch_templates(
- repo,
- config,
- &plan,
- execute,
- execute_args,
- hooks_approved,
- hook_project_config.as_ref(),
- )?;
+ validate_switch_templates(repo, config, &plan, execute, execute_args, hooks_approved)?;
// Execute the validated plan.
let (result, branch_info) =
@@ -2050,10 +1921,9 @@ fn warn_if_execute_form_deprecated(cmd: &str, execute_args: &[String]) {
/// completed successfully — template failure is a missed notification, not a
/// blocking state. The user can fix the template and run `wt hook` manually.
///
-/// `project_config` is the `.config/wt.toml` the post-switch hooks will run
-/// against — the new/destination worktree's (for `--create`, the base ref's),
-/// resolved by [`switch_hook_project_config`] — so the templates checked here
-/// are the ones that will actually be expanded, not the invoking worktree's.
+/// Hook templates checked here come from the invoking worktree's
+/// `.config/wt.toml` — the same config the switch hooks run against — so the
+/// templates validated are the ones that will actually be expanded.
///
/// Validates:
/// - `--execute` command template (if present)
@@ -2066,7 +1936,6 @@ fn validate_switch_templates(
execute: Option<&str>,
execute_args: &[String],
hooks_approved: bool,
- project_config: Option<&ProjectConfig>,
) -> anyhow::Result<()> {
// Validate --execute template and trailing args
if let Some(cmd) = execute {
@@ -2092,11 +1961,15 @@ fn validate_switch_templates(
return Ok(());
}
+ let project_config = repo.load_project_config()?;
let user_hooks = config.hooks(repo.project_identifier().ok().as_deref());
for &hook_type in switch_post_hook_types(plan.is_create()) {
- let (user_cfg, proj_cfg) =
- crate::commands::hooks::lookup_hook_configs(&user_hooks, project_config, hook_type);
+ let (user_cfg, proj_cfg) = crate::commands::hooks::lookup_hook_configs(
+ &user_hooks,
+ project_config.as_ref(),
+ hook_type,
+ );
for (source, cfg) in [("user", user_cfg), ("project", proj_cfg)] {
if let Some(cfg) = cfg {
for cmd in cfg.commands() {
@@ -2279,75 +2152,4 @@ mod tests {
PrProviderChoice::GitHub
);
}
-
- /// `base_ref_for_create` names the ref the new worktree checks out, so the
- /// pre-creation hook-config preview reads the same `.config/wt.toml` the
- /// hooks will run against — mirroring `execute_switch`'s `git worktree add`
- /// argument choice for `CreationMethod::Regular`.
- #[test]
- fn base_ref_for_create_picks_the_checkout_ref() {
- let mut test = TestRepo::with_initial_commit();
- test.setup_remote("main");
- test.run_git(&["branch", "local-feature"]);
- // A branch that lives only on the remote: push it, then drop the local ref.
- test.run_git(&["branch", "remote-feature"]);
- test.run_git(&["push", "origin", "remote-feature"]);
- test.run_git(&["branch", "-D", "remote-feature"]);
-
- // `--create` with an explicit base → that base.
- assert_eq!(
- base_ref_for_create(&test.repo, true, Some("dev"), "feature"),
- "dev"
- );
- // `--create` with no resolvable default branch → `HEAD` (git's own
- // fallback for `git worktree add -b <new>` with no base).
- assert_eq!(
- base_ref_for_create(&test.repo, true, None, "feature"),
- "HEAD"
- );
- // An existing local branch (no worktree yet) → that branch.
- assert_eq!(
- base_ref_for_create(&test.repo, false, None, "local-feature"),
- "local-feature"
- );
- // A branch that exists only on a single remote → its tracking ref.
- assert_eq!(
- base_ref_for_create(&test.repo, false, None, "remote-feature"),
- "origin/remote-feature"
- );
- // No local ref, no remote → `HEAD`.
- assert_eq!(
- base_ref_for_create(&test.repo, false, None, "nowhere"),
- "HEAD"
- );
-
- // A branch on multiple remotes: with `checkout.defaultRemote` set,
- // matches what `git worktree add <branch>` would DWIM to; without it,
- // git would refuse to pick — preview safely defaults to `HEAD`.
- test.setup_custom_remote("upstream", "main");
- test.run_git(&["branch", "shared-feature"]);
- test.run_git(&["push", "origin", "shared-feature"]);
- test.run_git(&["push", "upstream", "shared-feature"]);
- test.run_git(&["branch", "-D", "shared-feature"]);
- // `checkout.defaultRemote` may be set in the user's global config —
- // override locally so the test isn't sensitive to it.
- test.repo
- .set_config("checkout.defaultRemote", "no-such-remote")
- .unwrap();
- let repo = Repository::at(test.root_path()).unwrap();
- // Default doesn't match any remote on the branch → fall back to HEAD.
- assert_eq!(
- base_ref_for_create(&repo, false, None, "shared-feature"),
- "HEAD"
- );
- // With `checkout.defaultRemote = upstream`, that remote's ref wins —
- // matching what `git worktree add shared-feature` would DWIM to.
- repo.set_config("checkout.defaultRemote", "upstream")
- .unwrap();
- let repo = Repository::at(test.root_path()).unwrap();
- assert_eq!(
- base_ref_for_create(&repo, false, None, "shared-feature"),
- "upstream/shared-feature"
- );
- }
}
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 4679898ed..b00e5a347 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -613,46 +613,6 @@ impl Repository {
})
.map(Option::as_ref)
}
-
- /// Parse `.config/wt.toml` as committed at `gitref` (a branch name,
- /// `FETCH_HEAD`, a SHA, …), applying the structural TOML migration so
- /// deprecated patterns still parse.
- ///
- /// Used to preview the project config a not-yet-created worktree will
- /// check out: `wt switch --create`'s hook-approval prompt and template
- /// pre-flight read the base ref this way so they match what the
- /// post-switch hooks execute against once the worktree exists (a checkout
- /// of that ref). `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path
- /// regardless of the ref, the same as [`project_config_path`].
- ///
- /// Unlike [`load_project_config`](Self::load_project_config) this never
- /// touches the working tree and never writes a `.new` migration file —
- /// it must not, since the content comes from an arbitrary ref rather than
- /// the user's working copy. Returns `Ok(None)` only when the ref has no
- /// `.config/wt.toml` (git exits non-zero); a present file that fails to
- /// parse is surfaced as `Err` so the caller can abort rather than silently
- /// fall through to another config.
- ///
- /// [`project_config_path`]: Self::project_config_path
- pub fn project_config_at_ref(&self, gitref: &str) -> anyhow::Result<Option<ProjectConfig>> {
- if std::env::var_os("WORKTRUNK_PROJECT_CONFIG_PATH").is_some() {
- return self.load_project_config();
- }
- // `--end-of-options` keeps a ref like `-foo` from being parsed as a
- // flag (git's option parser would otherwise reject `-foo:.config/wt.toml`).
- let Ok(content) = self.run_command(&[
- "show",
- "--end-of-options",
- &format!("{gitref}:.config/wt.toml"),
- ]) else {
- return Ok(None);
- };
- let migrated = crate::config::migrate_content(&content);
- let config = toml::from_str::<ProjectConfig>(&migrated).with_context(|| {
- format!("Failed to parse committed `.config/wt.toml` at `{gitref}`")
- })?;
- Ok(Some(config))
- }
}
#[cfg(test)]
@@ -660,66 +620,6 @@ mod tests {
use super::*;
use crate::testing::TestRepo;
- #[test]
- fn project_config_at_ref_reads_committed_config() {
- let test = TestRepo::with_initial_commit();
- let repo = Repository::at(test.root_path()).unwrap();
-
- // No `.config/wt.toml` committed yet, and a nonexistent ref → Ok(None).
- assert!(repo.project_config_at_ref("HEAD").unwrap().is_none());
- assert!(repo.project_config_at_ref("no-such-ref").unwrap().is_none());
-
- // Commit one and read it back at that branch.
- test.write_project_config(r#"post-start = "echo hi""#);
- test.run_git(&["add", ".config/wt.toml"]);
- test.run_git(&["commit", "-m", "Add config"]);
- let cfg = repo
- .project_config_at_ref("HEAD")
- .unwrap()
- .expect("config committed at HEAD");
- assert!(cfg.hooks.post_create.is_some());
-
- // A committed file that doesn't parse → Err. Callers must abort rather
- // than silently fall through to a different config.
- test.write_project_config("this is not [ valid toml");
- test.run_git(&["add", ".config/wt.toml"]);
- test.run_git(&["commit", "-m", "Break config"]);
- let err = repo
- .project_config_at_ref("HEAD")
- .expect_err("malformed committed config should surface as Err");
- let msg = format!("{err:#}");
- assert!(
- msg.contains("Failed to parse committed `.config/wt.toml`"),
- "error should name the ref it failed to parse; got: {msg}"
- );
- }
-
- /// A ref literally named `-foo` must round-trip through
- /// [`project_config_at_ref`] without git's option parser eating the
- /// leading `-`. Without `--end-of-options`, `git show` would reject
- /// `-foo:.config/wt.toml` as a flag and the helper would silently
- /// return `None` even though the file exists on the ref.
- #[test]
- fn project_config_at_ref_handles_hyphen_prefixed_ref() {
- let test = TestRepo::with_initial_commit();
- let repo = Repository::at(test.root_path()).unwrap();
-
- test.write_project_config(r#"post-start = "echo hi""#);
- test.run_git(&["add", ".config/wt.toml"]);
- test.run_git(&["commit", "-m", "Add config"]);
-
- // `git branch -- -foo` is rejected by recent git, but `update-ref`
- // happily writes the ref — which is the worst case we want to be
- // robust against.
- test.run_git(&["update-ref", "refs/heads/-foo", "HEAD"]);
-
- let cfg = repo
- .project_config_at_ref("-foo")
- .unwrap()
- .expect("config readable at hyphen-prefixed ref");
- assert!(cfg.hooks.post_create.is_some());
- }
-
#[test]
fn test_get_config_regexp_no_match_returns_empty() {
// Exit 1 from git config --get-regexp means "no keys matched" — must
diff --git a/src/main.rs b/src/main.rs
index 6262a2156..80950f694 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -911,14 +911,12 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
}
// Helper: build and approve, once, the frozen hook plan the
- // removal will run. `pre-remove` / `post-remove` are anchored at
- // each removed worktree (their `.config/wt.toml`); `post-switch`
- // at each removal's post-removal destination
- // (`RemoveResult::destination_path()`, normally the primary
- // worktree, cwd when the primary worktree is itself the removal
- // target). No fallback between worktrees, same rule as the
- // executors. `!verify` (`--no-hooks`) or a declined prompt yields
- // an empty plan — every executor then runs no project hooks.
+ // removal will run. Every hook (`pre-remove` / `post-remove` per
+ // removed worktree, `post-switch` per post-removal destination) is
+ // selected from the invoking worktree's `.config/wt.toml` — the
+ // worktree `wt remove` ran in. `!verify` (`--no-hooks`) or a
+ // declined prompt yields an empty plan — every executor then runs
+ // no project hooks.
let approve_remove = |removed_worktree_paths: &[&Path],
destination_paths: &[&Path],
yes: bool|
@@ -932,13 +930,13 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
// behaviour where the empty-batch fast path ran first.
let project_id = repo.project_identifier().ok();
let pid = project_id.as_deref();
+ let project_config = repo.load_project_config()?;
let mut builder = HookPlanBuilder::new();
for &wt_path in removed_worktree_paths {
- let cfg = Repository::at(wt_path)?.load_project_config()?;
builder.add(
wt_path,
&[HookType::PreRemove, HookType::PostRemove],
- cfg.as_ref(),
+ project_config.as_ref(),
&config,
pid,
);
@@ -948,8 +946,13 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
if !seen_dests.insert(dest) {
continue;
}
- let cfg = Repository::at(dest)?.load_project_config()?;
- builder.add(dest, &[HookType::PostSwitch], cfg.as_ref(), &config, pid);
+ builder.add(
+ dest,
+ &[HookType::PostSwitch],
+ project_config.as_ref(),
+ &config,
+ pid,
+ );
}
match builder.finish().approve(pid, yes)? {
Some(plan) => Ok(plan),
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index dfd3d5bde..7335ad771 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -734,8 +734,8 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho
///
/// `plan` is the frozen, approved hook set; an empty plan (`--no-hooks`,
/// declined, or no project config) runs no project hooks. `pre-remove` /
-/// `post-remove` / `post-switch` execute only from it — never a re-read of
-/// the (by-then-gone) worktree config.
+/// `post-remove` / `post-switch` execute only from it — the selection was
+/// frozen at the gate, never re-read.
///
/// When `silent` is true (the TUI picker — this runs while skim owns the
/// terminal), a `RemovedWorktree` result is removed with no progress/success
@@ -1210,9 +1210,8 @@ fn execute_pre_remove_hooks_if_needed(
// `pre-remove` runs in the worktree being removed (still on disk here).
// `pre_remove_repo` roots the *render* context there for template vars;
- // the command set is the frozen `plan` (anchored at the removed worktree
- // at the gate), so the removed worktree's `.config/wt.toml` is never
- // re-read.
+ // the command set is the frozen `plan` selected at the gate, so no
+ // `.config/wt.toml` is re-read here.
let pre_remove_repo = Repository::at(ctx.worktree_path)?;
let command_ctx = CommandContext::new(
&pre_remove_repo,
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index f1935ab87..0aca5aecd 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -1745,23 +1745,23 @@ fn test_merge_primary_on_different_branch_dirty(mut repo: TestRepo) {
));
}
-/// `wt merge` resolves each hook from the worktree it acts on: `post-merge`
-/// runs in the destination (target's worktree) and reads its config there;
-/// `pre-remove` runs in the feature worktree (still on disk before removal)
-/// and reads its config there. No fallback between worktrees — each
-/// `.config/wt.toml` stands alone.
-#[rstest]
-fn test_merge_teardown_hooks_read_acting_worktree_config(mut repo: TestRepo) {
+/// `wt merge` resolves both teardown hooks from the invoking worktree — the
+/// feature worktree `wt merge` ran in. `post-merge` runs in the merge
+/// destination and `pre-remove` in the feature worktree, but both select their
+/// commands from the feature worktree's `.config/wt.toml`. `main` — the
+/// destination — has no project config, so a destination-sourced `post-merge`
+/// would select nothing and its marker would never appear.
+#[rstest]
+fn test_merge_teardown_hooks_read_invoking_worktree_config(mut repo: TestRepo) {
use crate::common::wait_for_file_content;
let pre_remove_marker = repo.root_path().join("pre-remove-ran.txt");
let post_merge_marker = repo.root_path().join("post-merge-ran.txt");
- // Commit both hooks on `main` so the feature branch inherits them. The
- // feature worktree then defines them in its own `.config/wt.toml` — same
- // text as main's. After the merge lands, main still has these definitions
- // (it fast-forwards to the feature tip), so the `post-merge` hook on the
- // destination (main) fires from main's post-merge config.
+ // Both hooks live only in the feature worktree's `.config/wt.toml`. `main`
+ // — the merge destination — has no project config, so `post-merge` fires
+ // only by resolving against the invoking feature worktree's config.
+ let feature_wt = repo.add_worktree_with_commit("feature-pm", "feature.txt", "x", "feat: x");
let config_body = format!(
r#"pre-remove = "echo 'removing {{{{ branch }}}}' > {}"
[post-merge]
@@ -1770,13 +1770,10 @@ sync = "echo 'merged {{{{ branch }}}}' > {}"
pre_remove_marker.to_slash_lossy(),
post_merge_marker.to_slash_lossy(),
);
- repo.write_project_config(&config_body);
- repo.commit("Add merge hooks on main");
-
- // The feature worktree inherits the same `.config/wt.toml` because it was
- // branched off main after the commit above — the feature worktree owns its
- // own `pre-remove` config locally, no fallback to main needed.
- let feature_wt = repo.add_worktree_with_commit("feature-pm", "feature.txt", "x", "feat: x");
+ std::fs::create_dir_all(feature_wt.join(".config")).unwrap();
+ std::fs::write(feature_wt.join(".config/wt.toml"), &config_body).unwrap();
+ repo.run_git_in(&feature_wt, &["add", ".config/wt.toml"]);
+ repo.run_git_in(&feature_wt, &["commit", "-m", "Add merge hooks"]);
let output = repo
.wt_command()
@@ -1794,14 +1791,14 @@ sync = "echo 'merged {{{{ branch }}}}' > {}"
assert_eq!(
std::fs::read_to_string(&post_merge_marker).unwrap().trim(),
"merged feature-pm",
- "post-merge should run with the destination worktree's config"
+ "post-merge runs in the destination but selects its config from the \
+ invoking feature worktree"
);
- // pre-remove runs synchronously before removal; the feature worktree's
- // own `.config/wt.toml` defines it.
+ // pre-remove runs synchronously in the feature worktree before removal.
assert_eq!(
std::fs::read_to_string(&pre_remove_marker).unwrap().trim(),
"removing feature-pm",
- "pre-remove should run with the feature worktree's own config"
+ "pre-remove should run from the invoking feature worktree's config"
);
}
@@ -3772,17 +3769,17 @@ fn test_merge_removes_branch_when_local_main_diverged_from_upstream(
);
}
-/// Approval-boundary TOCTOU regression: a `post-merge` command that exists only
-/// in the *feature branch's* committed `.config/wt.toml` must not run.
+/// Approval-boundary TOCTOU regression: a `post-merge` command that enters the
+/// invoking worktree's `.config/wt.toml` only via the rebase — after the gate
+/// froze the plan — must not run.
///
-/// The merge destination (the primary worktree on `main`) has no project
-/// config, so the gate freezes an empty *project* `post-merge` selection. The
-/// merge then fast-forwards `main` to the feature tip, bringing the feature's
-/// `.config/wt.toml` (with its injected `post-merge`) onto the destination.
-/// The pre-fix executor re-read the destination's now-mutated config and ran
-/// the never-approved command — remote code execution on a fresh clone. With
-/// the frozen `ApprovedHookPlan` the destination config is read once, before
-/// the merge, so the injected command is never selected.
+/// `wt merge` selects hooks from the feature worktree it runs in, at the gate,
+/// then rebases that worktree onto the target. Here the target branch carries
+/// an un-approved `post-merge`; the feature branch branched before it, so the
+/// gate sees a clean config and freezes an empty *project* selection. The
+/// rebase then brings the target's `.config/wt.toml` into the feature worktree,
+/// but the executor runs only the frozen `ApprovedHookPlan` — a re-read of the
+/// now-mutated config would be remote code execution on a fresh clone.
///
/// The wait is bounded *causally*, not by a fixed sleep: a user-config
/// `post-merge` (no approval, runs via the same background pipeline as project
@@ -3795,9 +3792,7 @@ fn test_merge_removes_branch_when_local_main_diverged_from_upstream(
/// (user vs project source) differ only by a `touch`'s sub-millisecond skew
/// once spawned; the short grace covers it.
#[rstest]
-fn test_post_merge_hook_from_merged_feature_config_does_not_run(
- merge_scenario: (TestRepo, PathBuf),
-) {
+fn test_post_merge_hook_from_rebased_in_config_does_not_run(merge_scenario: (TestRepo, PathBuf)) {
let (repo, feature_wt) = merge_scenario;
// Markers live at the repo root — they outlive the feature worktree, which
@@ -3812,15 +3807,15 @@ fn test_post_merge_hook_from_merged_feature_config_does_not_run(
control.to_slash_lossy()
));
- // Inject the malicious `post-merge` only on the feature branch.
- fs::create_dir_all(feature_wt.join(".config")).unwrap();
- fs::write(
- feature_wt.join(".config/wt.toml"),
- format!(r#"post-merge = "touch {}""#, injected.to_slash_lossy()),
- )
- .unwrap();
- repo.run_git_in(&feature_wt, &["add", ".config/wt.toml"]);
- repo.run_git_in(&feature_wt, &["commit", "-m", "inject post-merge"]);
+ // The target branch (`main`) gains an un-approved `post-merge` after
+ // `feature` branched off, so the gate — reading the feature worktree —
+ // never sees it. The rebase will bring this `.config/wt.toml` into the
+ // feature worktree before the executor runs.
+ repo.write_project_config(&format!(
+ r#"post-merge = "touch {}""#,
+ injected.to_slash_lossy()
+ ));
+ repo.commit("inject post-merge on main");
let output = repo
.wt_command()
@@ -3834,41 +3829,13 @@ fn test_post_merge_hook_from_merged_feature_config_does_not_run(
String::from_utf8_lossy(&output.stderr)
);
- // The merge fast-forwarded `main` to the feature tip, so the destination
- // worktree's `.config/wt.toml` now contains the injected hook. Wait for the
- // control (post-merge ran), then a short grace for the sibling pipeline.
+ // Wait for the control (post-merge ran), then a short grace for the sibling
+ // pipeline.
wait_for_file(&control);
std::thread::sleep(std::time::Duration::from_millis(200));
assert!(
!injected.exists(),
- "an unapproved post-merge command from the merged-in feature config must not run"
- );
-}
-
-/// `wt merge --no-hooks` runs no hooks, so it must not parse the destination's
-/// `.config/wt.toml` at all. A malformed destination config must not fail a
-/// hooks-disabled merge (regression: the plan rewrite read the destination
-/// config unconditionally, before gating on `verify`).
-#[rstest]
-fn test_merge_no_hooks_ignores_malformed_destination_config(merge_scenario: (TestRepo, PathBuf)) {
- let (repo, feature_wt) = merge_scenario;
-
- // Malformed config in the primary worktree = the merge destination.
- repo.write_project_config("post-merge = = not valid toml");
-
- let output = repo
- .wt_command()
- .current_dir(&feature_wt)
- .args(["merge", "--no-hooks", "--yes"])
- .output()
- .unwrap();
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- output.status.success(),
- "--no-hooks merge must not read the destination config; stderr:\n{stderr}"
- );
- assert!(
- !stderr.contains("expected") && !stderr.contains("TOML parse"),
- "destination .config/wt.toml must not be parsed with --no-hooks; stderr:\n{stderr}"
+ "a post-merge that entered the invoking worktree's config only via the \
+ rebase must not run — it was never in the frozen plan"
);
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 6f1bdacd0..03f502ced 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1710,28 +1710,36 @@ approved-commands = ["echo 'hook ran' > {}"]
);
}
-/// `pre-remove` resolves `.config/wt.toml` from the worktree being removed, not
-/// the primary worktree — so a hook added on a feature branch fires even before
-/// that `.config/wt.toml` reaches the default branch. The primary worktree here
-/// has no project config at all; only the removed worktree does.
+/// `pre-remove` resolves `.config/wt.toml` from the invoking worktree — the one
+/// `wt remove` ran in — while its template context (`{{ branch }}` etc.) is the
+/// removed worktree's. The removed worktree's own config is not consulted.
#[rstest]
-fn test_pre_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
+fn test_pre_remove_hook_reads_invoking_worktree_config(mut repo: TestRepo) {
use crate::common::wait_for_file_content;
let worktree_path = repo.add_worktree("feature-local-hook");
let marker_file = repo.root_path().join("pre-remove-ran.txt");
+ let wrong_marker = repo.root_path().join("wrong-marker.txt");
+
+ // A competing hook in the removed worktree, which must be ignored.
std::fs::create_dir_all(worktree_path.join(".config")).unwrap();
std::fs::write(
worktree_path.join(".config/wt.toml"),
- // `{{ branch }}` proves the hook ran with the removed worktree's context.
format!(
- r#"pre-remove = "echo 'removed branch {{{{ branch }}}}' > {}""#,
- marker_file.to_slash_lossy()
+ r#"pre-remove = "echo wrong > {}""#,
+ wrong_marker.to_slash_lossy()
),
)
.unwrap();
- // `--force` because `.config/wt.toml` is untracked in the removed worktree;
+ // The hook that should run lives in the invoking worktree (primary, cwd).
+ // `{{ branch }}` proves it ran with the removed worktree's template context.
+ repo.write_project_config(&format!(
+ r#"pre-remove = "echo 'removed branch {{{{ branch }}}}' > {}""#,
+ marker_file.to_slash_lossy()
+ ));
+
+ // `--force` because the removed worktree has an untracked `.config/wt.toml`;
// `--yes` to skip the approval prompt.
let output = repo
.wt_command()
@@ -1754,34 +1762,45 @@ fn test_pre_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
assert_eq!(
std::fs::read_to_string(&marker_file).unwrap().trim(),
"removed branch feature-local-hook",
- "pre-remove should run with the removed worktree's config"
+ "pre-remove runs from the invoking worktree's config, with the removed worktree's branch"
+ );
+ assert!(
+ !wrong_marker.exists(),
+ "the removed worktree's own config must not be consulted"
);
}
-/// `post-remove` reads the *removed* worktree's `.config/wt.toml`, even though
-/// the worktree is gone by the time the hook runs. The config is snapshotted
-/// before removal and threaded through `RemoveResult` to the executor —
-/// symmetric with `pre-remove`, which reads the same file from disk while it's
-/// still there. Both hooks are *about* the removed worktree.
+/// `post-remove` reads the invoking worktree's `.config/wt.toml`, snapshotted at
+/// the gate — its template context (`{{ branch }}` etc.) is the removed
+/// worktree's, gone by the time the hook runs. The removed worktree's own
+/// config is not consulted.
#[rstest]
-fn test_post_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
+fn test_post_remove_hook_reads_invoking_worktree_config(mut repo: TestRepo) {
use crate::common::wait_for_file_content;
let worktree_path = repo.add_worktree("feature-local-hook");
let marker_file = repo.root_path().join("post-remove-ran.txt");
+ let wrong_marker = repo.root_path().join("wrong-marker.txt");
+
+ // A competing hook in the removed worktree, which must be ignored.
std::fs::create_dir_all(worktree_path.join(".config")).unwrap();
std::fs::write(
worktree_path.join(".config/wt.toml"),
- // `{{ branch }}` proves the hook ran with the removed worktree's
- // template context; the marker living outside the removed worktree
- // (in the primary) lets us assert it after the worktree is gone.
format!(
- r#"post-remove = "echo 'post-remove of {{{{ branch }}}}' > {}""#,
- marker_file.to_slash_lossy()
+ r#"post-remove = "echo wrong > {}""#,
+ wrong_marker.to_slash_lossy()
),
)
.unwrap();
+ // The hook that should run lives in the invoking worktree (primary, cwd).
+ // `{{ branch }}` proves it ran with the removed worktree's template context;
+ // the marker outside the removed worktree survives the removal.
+ repo.write_project_config(&format!(
+ r#"post-remove = "echo 'post-remove of {{{{ branch }}}}' > {}""#,
+ marker_file.to_slash_lossy()
+ ));
+
let output = repo
.wt_command()
.args([
@@ -1803,42 +1822,36 @@ fn test_post_remove_hook_reads_removed_worktree_config(mut repo: TestRepo) {
assert_eq!(
std::fs::read_to_string(&marker_file).unwrap().trim(),
"post-remove of feature-local-hook",
- "post-remove should run with the removed worktree's config, snapshotted before removal"
+ "post-remove runs from the invoking worktree's config, snapshotted before removal"
);
assert!(
!worktree_path.exists(),
"feature worktree should be removed"
);
+ assert!(
+ !wrong_marker.exists(),
+ "the removed worktree's own config must not be consulted"
+ );
}
-/// A worktree with a malformed `.config/wt.toml` makes `wt remove` abort with
-/// the parse error in stderr — no silent fall-through to a different config,
-/// and the worktree stays on disk so the user can fix it.
+/// A malformed `.config/wt.toml` in the invoking worktree makes `wt remove`
+/// abort with the parse error in stderr — no silent fall-through to a different
+/// config, and the worktree stays on disk so the user can fix it.
#[rstest]
-fn test_remove_aborts_on_malformed_worktree_config(mut repo: TestRepo) {
- let worktree_path = repo.add_worktree("feature-bad-config");
- std::fs::create_dir_all(worktree_path.join(".config")).unwrap();
- std::fs::write(
- worktree_path.join(".config/wt.toml"),
- "this is not [ valid toml",
- )
- .unwrap();
+fn test_remove_aborts_on_malformed_invoking_config(mut repo: TestRepo) {
+ let worktree_path = repo.add_worktree("feature-x");
+ // Malformed config in the invoking worktree (primary, cwd).
+ repo.write_project_config("this is not [ valid toml");
let output = repo
.wt_command()
- .args([
- "remove",
- "--foreground",
- "--force",
- "--yes",
- "feature-bad-config",
- ])
+ .args(["remove", "--foreground", "--force", "--yes", "feature-x"])
.output()
.unwrap();
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success(),
- "wt remove should abort on a malformed worktree config; stderr:\n{stderr}"
+ "wt remove should abort on a malformed invoking-worktree config; stderr:\n{stderr}"
);
assert!(
stderr.contains("wt.toml"),
@@ -1850,52 +1863,6 @@ fn test_remove_aborts_on_malformed_worktree_config(mut repo: TestRepo) {
);
}
-/// Removing a worktree that has no `.config/wt.toml` does NOT fall back to the
-/// primary worktree's config: neither for execution (per #2714) nor for
-/// approval (`HookPlanBuilder::add` selects per removed-worktree anchor with no
-/// primary fallback). Without `--yes` and without prior approval, the command
-/// must succeed (the approval prompt has no commands to surface) rather than
-/// block on the primary's `pre-remove`.
-#[rstest]
-fn test_remove_no_fallback_to_primary_pre_remove(mut repo: TestRepo) {
- // Add the feature worktree first, off HEAD, so it doesn't carry the
- // uncommitted config below.
- let worktree_path = repo.add_worktree("feature-no-config");
- let marker_file = repo.root_path().join("pre-remove-ran.txt");
-
- // Primary worktree only — uncommitted, so `feature-no-config` doesn't
- // inherit it.
- repo.write_project_config(&format!(
- r#"pre-remove = "echo ran > {}""#,
- marker_file.to_slash_lossy()
- ));
-
- // No `--yes`: with the bug, the approval helper would surface the primary's
- // `pre-remove` and `wt remove` would abort with "needs approval" because
- // tests don't have a TTY. With the fix, the prompt is empty and removal
- // proceeds. `--force` because the feature branch is unmerged.
- let output = repo
- .wt_command()
- .args(["remove", "--foreground", "--force", "feature-no-config"])
- .output()
- .unwrap();
- let stderr = String::from_utf8_lossy(&output.stderr);
- assert!(
- output.status.success(),
- "wt remove should succeed when the removed worktree has no \
- .config/wt.toml — no fallback to the primary's; stderr:\n{stderr}"
- );
- assert!(
- !worktree_path.exists(),
- "feature worktree should be removed"
- );
- assert!(
- !marker_file.exists(),
- "primary's pre-remove must not fire when the removed worktree has \
- no .config/wt.toml"
- );
-}
-
/// Removing a worktree with no project hooks must not touch approval state.
/// A malformed `approvals.toml` aborts only when there is a project command to
/// authorize; with an empty plan the gate never loads approvals (regression:
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index e2d002875..77f955973 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -985,37 +985,32 @@ cleanup = "echo done"
assert_cmd_snapshot!(cmd);
}
-/// Commit a `pre-remove` hook on the default branch, branch a worktree off that
-/// commit (so it carries the hook in its own `.config/wt.toml`), then drop the
-/// hook from the default branch and advance past the worktree's commit. The
-/// worktree is now integrated (an ancestor of the default branch) and clean,
-/// while the cwd config no longer mentions `pre-remove` — the situation where
-/// prune would otherwise approve against the wrong config. Returns the
-/// worktree path and the marker file the hook writes.
-fn prune_branch_local_pre_remove_setup(
- repo: &mut TestRepo,
-) -> (std::path::PathBuf, std::path::PathBuf) {
+/// Branch a worktree, advance the default branch past it (so it's integrated
+/// and prunable), and put a `pre-remove` hook in the invoking worktree (cwd) —
+/// the config `wt step prune` resolves against. Returns the worktree path and
+/// the marker file the hook writes.
+fn prune_pre_remove_setup(repo: &mut TestRepo) -> (std::path::PathBuf, std::path::PathBuf) {
use path_slash::PathExt as _;
+ let wt_path = repo.add_worktree("merged");
+ // Advance the default branch so `merged` is strictly an ancestor — prune
+ // treats it as integrated and removable.
+ repo.commit("Advance default branch");
+ // The `pre-remove` hook lives in the invoking worktree (cwd), uncommitted.
let marker = repo.root_path().join("prune-pre-remove-ran.txt");
repo.write_project_config(&format!(
r#"pre-remove = "echo ran > {}""#,
marker.to_slash_lossy()
));
- repo.commit("Add pre-remove hook");
- let wt_path = repo.add_worktree("merged-with-hook");
- repo.write_project_config("# no hooks on the default branch\n");
- repo.commit("Drop pre-remove hook");
(wt_path, marker)
}
-/// `wt step prune`'s approval covers each pruned worktree's own `pre-remove`,
-/// not just the cwd config's. A hook that lives only in a pruned worktree's
-/// branch-local `.config/wt.toml` must be approved before it runs — with no TTY
-/// and no prior approval, prune aborts rather than running it silently.
+/// `wt step prune`'s approval covers the `pre-remove` hooks the pruned worktrees
+/// will run — resolved from the invoking worktree's config. With no TTY and no
+/// prior approval, prune aborts rather than running them silently.
#[rstest]
-fn test_prune_branch_local_pre_remove_needs_approval(mut repo: TestRepo) {
- let (wt_path, marker) = prune_branch_local_pre_remove_setup(&mut repo);
+fn test_prune_pre_remove_needs_approval(mut repo: TestRepo) {
+ let (wt_path, marker) = prune_pre_remove_setup(&mut repo);
let output = repo
.wt_command()
@@ -1026,11 +1021,11 @@ fn test_prune_branch_local_pre_remove_needs_approval(mut repo: TestRepo) {
assert!(
!output.status.success(),
- "prune should abort when an un-approved branch-local pre-remove is in scope; stderr:\n{stderr}"
+ "prune should abort when an un-approved pre-remove is in scope; stderr:\n{stderr}"
);
assert!(
stderr.contains("needs approval") && stderr.contains("pre-remove"),
- "prune should surface the pruned worktree's pre-remove for approval; stderr:\n{stderr}"
+ "prune should surface the pre-remove for approval; stderr:\n{stderr}"
);
assert!(
wt_path.exists(),
@@ -1042,13 +1037,13 @@ fn test_prune_branch_local_pre_remove_needs_approval(mut repo: TestRepo) {
);
}
-/// With `--yes`, `wt step prune` runs the approved `pre-remove` hook from each
-/// pruned worktree's own `.config/wt.toml`.
+/// With `--yes`, `wt step prune` runs the `pre-remove` hook from the invoking
+/// worktree's `.config/wt.toml` for each pruned worktree.
#[rstest]
-fn test_prune_runs_branch_local_pre_remove_hook(mut repo: TestRepo) {
+fn test_prune_runs_pre_remove_hook(mut repo: TestRepo) {
use crate::common::wait_for_file_content;
- let (wt_path, marker) = prune_branch_local_pre_remove_setup(&mut repo);
+ let (wt_path, marker) = prune_pre_remove_setup(&mut repo);
let output = repo
.wt_command()
diff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rs
index 9556d1056..6da23defd 100644
--- a/tests/integration_tests/switch.rs
+++ b/tests/integration_tests/switch.rs
@@ -1148,27 +1148,32 @@ fn test_switch_no_config_commands_with_yes(repo: TestRepo) {
);
}
-/// `wt switch --create <new> --base <other>` resolves `pre-start` / `post-start`
-/// from the base branch's committed `.config/wt.toml` — the worktree these hooks
-/// run in is a checkout of that branch. The primary worktree (cwd) has no
-/// project config at all; only `other-base` does, so a regression that read the
-/// invoking worktree's config would run nothing.
-#[rstest]
-fn test_switch_create_reads_base_branch_config(mut repo: TestRepo) {
- // Commit a `.config/wt.toml` on `other-base` only (not on `main`).
+/// `wt switch --create` resolves `pre-start` / `post-start` from the
+/// **invoking** worktree's `.config/wt.toml`, read from its working tree — so
+/// an *uncommitted* config fires the hooks (the regression behind #2856 and
+/// #2818). The base branch's committed `.config/wt.toml` is not consulted, even
+/// though the new worktree is a checkout of it.
+#[rstest]
+fn test_switch_create_reads_invoking_worktree_config(mut repo: TestRepo) {
+ // The base branch carries a *committed* hook that must be ignored.
let other_wt = repo.add_worktree("other-base");
fs::create_dir_all(other_wt.join(".config")).unwrap();
fs::write(
other_wt.join(".config/wt.toml"),
- // `{{ repo_path }}` is the main worktree root regardless of which
- // worktree the hook runs in, so the markers land where the test reads.
- r#"pre-start = "echo pre-start-from-base > {{ repo_path }}/pre-start-marker.txt"
-post-start = "echo post-start-from-base > {{ repo_path }}/post-start-marker.txt"
-"#,
+ r#"post-start = "echo from-base-branch > {{ repo_path }}/base-branch-marker.txt""#,
)
.unwrap();
repo.run_git_in(&other_wt, &["add", ".config/wt.toml"]);
- repo.run_git_in(&other_wt, &["commit", "-m", "Add hooks on other-base"]);
+ repo.run_git_in(&other_wt, &["commit", "-m", "Committed hook on other-base"]);
+
+ // The invoking worktree (`main`, cwd) has an *uncommitted* `.config/wt.toml`.
+ // `{{ repo_path }}` is the main worktree root regardless of which worktree
+ // the hook runs in, so the markers land where the test reads.
+ repo.write_project_config(
+ r#"pre-start = "echo pre-start-from-invoking > {{ repo_path }}/pre-start-marker.txt"
+post-start = "echo post-start-from-invoking > {{ repo_path }}/post-start-marker.txt"
+"#,
+ );
let output = repo
.wt_command()
@@ -1192,31 +1197,43 @@ post-start = "echo post-start-from-base > {{ repo_path }}/post-start-marker.txt"
wait_for_file_content(&pre_marker);
assert_eq!(
fs::read_to_string(&pre_marker).unwrap().trim(),
- "pre-start-from-base",
- "pre-start should run with the base branch's config"
+ "pre-start-from-invoking",
+ "pre-start should run from the invoking worktree's uncommitted config"
);
let post_marker = repo.root_path().join("post-start-marker.txt");
wait_for_file_content(&post_marker);
assert_eq!(
fs::read_to_string(&post_marker).unwrap().trim(),
- "post-start-from-base",
- "post-start should run with the base branch's config"
+ "post-start-from-invoking",
+ "post-start should run from the invoking worktree's uncommitted config"
+ );
+
+ // The base branch's committed hook must never run.
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ assert!(
+ !repo.root_path().join("base-branch-marker.txt").exists(),
+ "the base branch's committed config must not be consulted for `--create`"
);
}
-/// `wt switch <existing>` resolves `post-switch` from the destination worktree's
-/// `.config/wt.toml`, not the worktree `wt switch` ran in. Only the destination
-/// has a project config here.
+/// `wt switch <existing>` resolves `post-switch` from the **invoking** worktree's
+/// `.config/wt.toml` — the worktree `wt switch` ran in — not the destination's.
#[rstest]
-fn test_switch_existing_reads_destination_worktree_config(mut repo: TestRepo) {
+fn test_switch_existing_reads_invoking_worktree_config(mut repo: TestRepo) {
+ // The destination worktree carries its own hook, which must be ignored.
let dest = repo.add_worktree("dest");
fs::create_dir_all(dest.join(".config")).unwrap();
fs::write(
dest.join(".config/wt.toml"),
- r#"post-switch = "echo post-switch-from-dest > {{ repo_path }}/post-switch-marker.txt""#,
+ r#"post-switch = "echo from-dest > {{ repo_path }}/dest-marker.txt""#,
)
.unwrap();
+ // The invoking worktree (`main`, cwd) carries the hook that should run.
+ repo.write_project_config(
+ r#"post-switch = "echo from-invoking > {{ repo_path }}/post-switch-marker.txt""#,
+ );
+
let output = repo
.wt_command()
.args(["switch", "dest", "--yes"])
@@ -1232,20 +1249,26 @@ fn test_switch_existing_reads_destination_worktree_config(mut repo: TestRepo) {
wait_for_file_content(&marker);
assert_eq!(
fs::read_to_string(&marker).unwrap().trim(),
- "post-switch-from-dest",
- "post-switch should run with the destination worktree's config"
+ "from-invoking",
+ "post-switch should run with the invoking worktree's config"
+ );
+
+ // The destination worktree's own hook must never run.
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ assert!(
+ !repo.root_path().join("dest-marker.txt").exists(),
+ "the destination worktree's config must not be consulted"
);
}
-/// A destination worktree with a malformed `.config/wt.toml` makes `wt switch
-/// <existing>` abort with the parse error in stderr — no silent fall-through
-/// to a different config. The path is surfaced so the user can find and fix
-/// the offending file.
+/// A malformed `.config/wt.toml` in the invoking worktree makes `wt switch`
+/// abort with the parse error in stderr — no silent fall-through to a different
+/// config. The path is surfaced so the user can find and fix the offending file.
#[rstest]
-fn test_switch_existing_aborts_on_malformed_destination_config(mut repo: TestRepo) {
- let dest = repo.add_worktree("dest");
- fs::create_dir_all(dest.join(".config")).unwrap();
- fs::write(dest.join(".config/wt.toml"), "this is not [ valid toml").unwrap();
+fn test_switch_aborts_on_malformed_invoking_config(mut repo: TestRepo) {
+ repo.add_worktree("dest");
+ // Malformed config in the invoking worktree (`main`, cwd).
+ repo.write_project_config("this is not [ valid toml");
let output = repo
.wt_command()
@@ -1255,7 +1278,7 @@ fn test_switch_existing_aborts_on_malformed_destination_config(mut repo: TestRep
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
!output.status.success(),
- "wt switch should abort on a malformed destination config; stderr:\n{stderr}"
+ "wt switch should abort on a malformed invoking-worktree config; stderr:\n{stderr}"
);
assert!(
stderr.contains("wt.toml"),
@@ -1263,9 +1286,10 @@ fn test_switch_existing_aborts_on_malformed_destination_config(mut repo: TestRep
);
}
-/// `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path for *every* config read —
-/// including `wt switch --create`'s base-ref preview — so the override file's
-/// hooks run, not the base branch's committed `.config/wt.toml`.
+/// `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path for *every* config read,
+/// so `wt switch --create` resolves its hooks from the override file. The base
+/// branch's committed `.config/wt.toml`, which the new worktree checks out, is
+/// not consulted.
#[rstest]
fn test_switch_create_honors_project_config_path_override(mut repo: TestRepo) {
// The base branch carries a committed hook that must be ignored.
@@ -2616,24 +2640,10 @@ fn test_switch_pr_fork(#[from(repo_with_remote)] repo: TestRepo) {
fn test_switch_pr_hooks_see_pr_vars(#[from(repo_with_remote)] repo: TestRepo) {
// Set up the same fork-PR scenario as test_switch_pr_fork: a refs/pull/42/head on the
// bare remote, origin redirected to GitHub-style URL, and `gh api` mocked.
- // The PR commit carries the project config so the post-switch hooks read it
- // from the new worktree (a checkout of refs/pull/42/head) directly.
repo.run_git(&["checkout", "-b", "pr-source"]);
fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
- // Each hook writes its own marker in the primary worktree so we can verify
- // post-switch + post-start (background) populate pr_number/pr_url too.
- // {{ repo_path }} is always the main repo's working tree.
- fs::create_dir_all(repo.root_path().join(".config")).unwrap();
- fs::write(
- repo.root_path().join(".config/wt.toml"),
- r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"
-post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"
-post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"
-"#,
- )
- .unwrap();
- repo.run_git(&["add", "pr-file.txt", ".config/wt.toml"]);
- repo.run_git(&["commit", "-m", "PR commit with hook config"]);
+ repo.run_git(&["add", "pr-file.txt"]);
+ repo.run_git(&["commit", "-m", "PR commit"]);
let commit_sha = repo
.git_command()
@@ -2646,6 +2656,21 @@ post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_pa
repo.run_git(&["push", "origin", &format!("{}:refs/pull/42/head", sha)]);
repo.run_git(&["checkout", "main"]);
+ // The hooks live in the invoking worktree (`main`), where `wt switch pr:42`
+ // runs — the `pr_*` template vars come from PR resolution, independent of
+ // where the config lives. Each hook writes its own marker in the primary
+ // worktree so we can verify post-switch + post-start (background) populate
+ // pr_number/pr_url too. {{ repo_path }} is always the main repo's working tree.
+ fs::create_dir_all(repo.root_path().join(".config")).unwrap();
+ fs::write(
+ repo.root_path().join(".config/wt.toml"),
+ r#"pre-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/pre_start.txt"
+post-start = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_start.txt"
+post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_path }}/post_switch.txt"
+"#,
+ )
+ .unwrap();
+
let bare_url = String::from_utf8_lossy(
&repo
.git_command()
@@ -2711,17 +2736,16 @@ post-switch = "echo 'pr_number={{ pr_number }} pr_url={{ pr_url }}' > {{ repo_pa
}
}
-/// `wt switch pr:N` resolves `post-start` etc. from the PR's tree — the fetched
-/// head ref, potentially from a fork — and the approval prompt reads that same
-/// PR config, so what the prompt lists can't diverge from what runs. The local
-/// repo has no project config; only the PR commit does. Without `--yes` the
-/// prompt lists the PR's hook and bails (non-interactive); with `--yes` the
-/// hook executes against the new worktree (a checkout of the PR head).
+/// `wt switch pr:N` resolves `post-start` etc. from the **invoking** worktree's
+/// `.config/wt.toml` — not the PR's own committed config, even though the new
+/// worktree is a checkout of the PR head. The approval prompt lists those same
+/// invoking-worktree hooks, so the prompt can't diverge from what runs. The PR
+/// commit here carries a *different* hook that must never run.
#[rstest]
-fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo) {
+fn test_switch_pr_reads_invoking_worktree_config(#[from(repo_with_remote)] repo: TestRepo) {
// Fork-PR scenario (mirrors `test_switch_pr_hooks_see_pr_vars`): a
// refs/pull/42/head on the bare remote, origin redirected to a GitHub URL,
- // `gh api` mocked — but the PR commit carries a `.config/wt.toml`.
+ // `gh api` mocked. The PR commit carries its own `.config/wt.toml`.
repo.run_git(&["checkout", "-b", "pr-source"]);
fs::write(repo.root_path().join("pr-file.txt"), "PR content").unwrap();
fs::create_dir_all(repo.root_path().join(".config")).unwrap();
@@ -2744,11 +2768,17 @@ fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo)
.trim()
.to_string();
repo.run_git(&["push", "origin", &format!("{sha}:refs/pull/42/head")]);
- // Back on `main`, which never had `.config/wt.toml` committed — `pr-source`
- // branched off before that commit, so `git checkout main` drops it from the
- // working tree, leaving the local repo with no project config.
+ // Back on `main`: `pr-source` branched off before the PR commit, so
+ // `git checkout main` drops the PR's `.config/wt.toml` from the working tree.
repo.run_git(&["checkout", "main"]);
+ // The invoking worktree (`main`) carries its own — uncommitted — hook. This
+ // is the only `.config/wt.toml` on disk here, and the one `wt switch pr:42`
+ // must resolve against.
+ repo.write_project_config(
+ r#"post-start = "echo INVOKING-HOOK-RAN > {{ repo_path }}/invoking-hook-marker.txt""#,
+ );
+
let bare_url = String::from_utf8_lossy(
&repo
.git_command()
@@ -2788,27 +2818,32 @@ fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo)
}"#;
let mock_bin = setup_mock_gh_for_pr(&repo, Some(gh_response));
- // (a) Without `--yes`: the approval prompt prints the PR's command template
- // to stderr, then bails (stdin is not a TTY in tests). No worktree, no hook.
+ // (a) Without `--yes`: the approval prompt lists the *invoking* worktree's
+ // hook (never the PR's), then bails (stdin is not a TTY in tests).
let mut cmd = repo.wt_command();
cmd.args(["switch", "pr:42"]);
configure_mock_cli_env(&mut cmd, &mock_bin);
let output = cmd.output().expect("wt switch pr:42 should run");
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("PR-CONFIG-HOOK-RAN"),
- "approval prompt should list the PR ref's post-start hook; stderr:\n{stderr}"
+ stderr.contains("INVOKING-HOOK-RAN"),
+ "approval prompt should list the invoking worktree's post-start hook; stderr:\n{stderr}"
+ );
+ assert!(
+ !stderr.contains("PR-CONFIG-HOOK-RAN"),
+ "the PR ref's committed hook must not appear in the prompt; stderr:\n{stderr}"
);
assert!(
!output.status.success(),
"non-interactive approval should bail without running the hook"
);
assert!(
- !repo.root_path().join("pr-hook-marker.txt").exists(),
+ !repo.root_path().join("invoking-hook-marker.txt").exists(),
"a declined approval must not run the hook"
);
- // (b) With `--yes`: the PR's `post-start` runs against the new worktree.
+ // (b) With `--yes`: the invoking worktree's `post-start` runs; the PR's
+ // committed hook never does.
let mut cmd = repo.wt_command();
cmd.args(["switch", "pr:42", "--yes"]);
configure_mock_cli_env(&mut cmd, &mock_bin);
@@ -2819,12 +2854,17 @@ fn test_switch_pr_reads_pr_ref_config(#[from(repo_with_remote)] repo: TestRepo)
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr),
);
- let marker = repo.root_path().join("pr-hook-marker.txt");
+ let marker = repo.root_path().join("invoking-hook-marker.txt");
wait_for_file_content(&marker);
assert_eq!(
fs::read_to_string(&marker).unwrap().trim(),
- "PR-CONFIG-HOOK-RAN",
- "post-start should run with the PR ref's config"
+ "INVOKING-HOOK-RAN",
+ "post-start should run from the invoking worktree's config"
+ );
+ std::thread::sleep(std::time::Duration::from_millis(500));
+ assert!(
+ !repo.root_path().join("pr-hook-marker.txt").exists(),
+ "the PR ref's committed config must not be consulted"
);
}