Skip to content

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

fix(hooks): resolve project config from the worktree the hook acts on (#2690)

Maximilian Roos78b3a9587206
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 9f27e2e11..5c8941d04 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -148,6 +148,13 @@ impl FailureStrategy {
#[derive(Clone, Copy, Debug)]
pub struct CommandContext<'a> {
+ /// The repository, rooted at the worktree this operation acts on.
+ ///
+ /// For hooks this field is load-bearing: `ctx.repo.load_project_config()` is
+ /// how a hook gets its `.config/wt.toml`, so whichever worktree `repo` is
+ /// rooted at decides which file is read. The per-hook mapping (and why each
+ /// construction site picks the root it does) is the spec in the
+ /// [`super::hooks`] module docs.
pub repo: &'a Repository,
pub config: &'a UserConfig,
/// Current branch name, if on a branch (None in detached HEAD state).
diff --git a/src/commands/context.rs b/src/commands/context.rs
index e7a924be5..72ee2e860 100644
--- a/src/commands/context.rs
+++ b/src/commands/context.rs
@@ -48,16 +48,19 @@ impl CommandEnv {
/// Load the command environment for a named worktree (by branch name).
///
- /// Resolves the worktree path from the branch name rather than using
- /// the current working directory.
+ /// Resolves the worktree path from the branch name rather than the current
+ /// directory, and roots `repo` at that worktree — so a command run with
+ /// `--branch <b>` (e.g. `wt step commit --branch <b>`) and its hooks
+ /// (`pre-commit` / `post-commit`) operate on, and resolve `.config/wt.toml`
+ /// from, `<b>`'s worktree rather than the cwd. See the `commands::hooks`
+ /// module docs for the hook config-resolution rule.
pub fn for_branch(config: UserConfig, branch: &str) -> anyhow::Result<Self> {
- let repo = Repository::current()?;
- let worktree_path = repo
+ let worktree_path = Repository::current()?
.worktree_for_branch(branch)?
.ok_or_else(|| anyhow::anyhow!("no worktree for branch '{branch}'"))?;
Ok(Self {
- repo,
+ repo: Repository::at(&worktree_path)?,
branch: Some(branch.to_string()),
config,
worktree_path,
diff --git a/src/commands/hooks.rs b/src/commands/hooks.rs
index 5a0b4f292..1636dd771 100644
--- a/src/commands/hooks.rs
+++ b/src/commands/hooks.rs
@@ -2,6 +2,32 @@
//!
//! See [`super::hook_announcement`] for the announcement format / grammar that
//! the background path emits before spawning pipelines.
+//!
+//! # Which `.config/wt.toml` a hook reads
+//!
+//! A hook resolves its project config from `ctx.repo.load_project_config()` —
+//! [`execute_hook`], [`prepare_background_pipelines`], and
+//! [`super::command_approval::approve_hooks`] all do this — and
+//! `Repository::project_config_path` keys that off whichever worktree
+//! `ctx.repo` was rooted at. So the rule reduces to **`ctx.repo` is rooted at
+//! the worktree the hook acts on** (not, in general, where `wt` was invoked),
+//! and the construction sites enforce it:
+//!
+//! | Hook | `ctx.repo` rooted at → config from | Set in |
+//! |---|---|---|
+//! | `pre-remove` | the worktree being removed (still on disk at hook time); if it has no `.config/wt.toml`, the post-removal working directory (`RemoveResult.main_path`) — the **primary worktree** for `wt remove`, the merge destination for `wt merge` | `output::handlers::execute_pre_remove_hooks_if_needed`; approval mirrors it in `main.rs` (`wt remove`) and `merge::collect_merge_commands` (`wt merge`) |
+//! | `post-merge`, `post-remove`, `post-switch` after a removal | the destination — for `wt merge`, the target branch's worktree (else the primary); for `wt remove`, the primary worktree — the removed/feature worktree is gone by then | `worktree::finish::finish_after_merge`, `output::handlers::spawn_hooks_after_remove` (and `merge::collect_merge_commands` for approval) |
+//! | `pre-commit` / `post-commit` | the worktree being committed — the cwd worktree, or `<b>`'s worktree for `wt step commit --branch <b>` | `commands::commit`, `step::commit` (via `CommandEnv::for_branch`) |
+//! | `wt switch`'s `pre-start` / `post-start` / `post-switch` | the worktree `wt switch` ran in — the new worktree doesn't exist yet when these are approved, and for `wt switch --create` it's a fresh checkout of that worktree's HEAD anyway | `worktree::switch` |
+//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in (= where they run) | the respective command entry points |
+//!
+//! `WORKTRUNK_PROJECT_CONFIG_PATH` overrides the path regardless of the root
+//! (test isolation). User config (`~/.config/worktrunk/config.toml`) is global
+//! and unaffected. When a hook's worktree and its approval-time stand-in differ
+//! (the `wt switch --create` row), the approval prompt may list slightly
+//! different commands than execute — see that row's note for why it's harmless
+//! in practice; `pre-remove` and the merge/remove `post-*` hooks are approved
+//! against the exact config they execute against.
use std::collections::HashMap;
use std::path::{Path, PathBuf};
@@ -395,6 +421,10 @@ pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>
/// Looks up user/project configs, prepares + name-checks steps, and groups
/// them by source so each source spawns as an independent pipeline. Each
/// group is returned with its `(hook_type, display_path)` metadata.
+///
+/// Project config comes from `ctx.repo.load_project_config()` — see the
+/// module-level "Which `.config/wt.toml` a hook reads" docs for which worktree
+/// `ctx.repo` is rooted at per hook type.
pub(crate) fn prepare_background_pipelines<'c>(
ctx: &CommandContext<'c>,
hook_type: HookType,
@@ -729,6 +759,10 @@ pub(crate) fn lookup_hook_configs<'a>(
/// `--no-hooks` reminder. This is the canonical operation-driven entry point;
/// the only path that should bypass it is `wt hook <type>` (which calls
/// [`run_hooks_foreground`] directly so failures don't carry the hint).
+///
+/// Project config comes from `ctx.repo.load_project_config()` — see the
+/// module-level "Which `.config/wt.toml` a hook reads" docs for which worktree
+/// `ctx.repo` is rooted at per hook type.
pub(crate) fn execute_hook(
ctx: &CommandContext,
hook_type: HookType,
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index a9c076a3f..61a4f4a3a 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -1,6 +1,8 @@
+use std::path::Path;
+
use anyhow::Context;
use worktrunk::HookType;
-use worktrunk::config::{Approvals, MergeConfig, UserConfig};
+use worktrunk::config::{Approvals, MergeConfig, ProjectConfig, UserConfig};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, info_message};
@@ -72,45 +74,72 @@ pub struct MergeOptions<'a> {
pub format: crate::cli::SwitchFormat,
}
-/// Collect all commands that will be executed during merge.
+/// Collect all commands that will be executed during merge, for batch approval.
+///
+/// Returns (commands, project_identifier). Each hook is approved against the
+/// `.config/wt.toml` of the worktree it runs in (and is resolved from):
///
-/// Returns (commands, project_identifier) for batch approval.
+/// - `pre-commit` / `post-commit` / `pre-merge` → the feature worktree
+/// (= `repo`'s cwd).
+/// - `post-merge` / `post-remove` / `post-switch` → the merge destination
+/// (`destination_path`); these run after the feature worktree is removed.
+/// - `pre-remove` → the feature worktree if it has a `.config/wt.toml` (it's
+/// still on disk when the hook runs), else the destination — mirroring
+/// `output::handlers::execute_pre_remove_hooks_if_needed`, the executor for
+/// both `wt remove` and `wt merge`'s teardown.
fn collect_merge_commands(
repo: &Repository,
+ destination_path: &Path,
commit: bool,
verify: bool,
will_remove: bool,
squash_enabled: bool,
) -> anyhow::Result<(Vec<ApprovableCommand>, String)> {
- let mut all_commands = Vec::new();
- let project_config = match repo.load_project_config()? {
- Some(cfg) => cfg,
- None => return Ok((all_commands, repo.project_identifier()?)),
- };
-
- let mut hooks = Vec::new();
+ let mut feature_hooks = Vec::new();
+ let mut destination_hooks = Vec::new();
+ let mut needs_pre_remove = false;
// Pre-commit hooks run when a commit will actually be created
let will_create_commit = repo.current_worktree().is_dirty()? || squash_enabled;
if commit && verify && will_create_commit {
- hooks.push(HookType::PreCommit);
- hooks.push(HookType::PostCommit);
+ feature_hooks.push(HookType::PreCommit);
+ feature_hooks.push(HookType::PostCommit);
}
if verify {
- hooks.push(HookType::PreMerge);
- hooks.push(HookType::PostMerge);
+ feature_hooks.push(HookType::PreMerge);
+ destination_hooks.push(HookType::PostMerge);
if will_remove {
- hooks.push(HookType::PreRemove);
- hooks.push(HookType::PostRemove);
- hooks.push(HookType::PostSwitch);
+ needs_pre_remove = true;
+ destination_hooks.push(HookType::PostRemove);
+ destination_hooks.push(HookType::PostSwitch);
}
}
- all_commands.extend(collect_commands_for_hooks(&project_config, &hooks));
+ let feature_config = repo.load_project_config()?;
+ // Load the destination's config if a destination-bucket hook needs it, or
+ // if `pre-remove` has to fall back to it (the feature worktree has no
+ // `.config/wt.toml` — same fallback the executor takes).
+ let destination_config =
+ if !destination_hooks.is_empty() || (needs_pre_remove && feature_config.is_none()) {
+ ProjectConfig::load(&Repository::at(destination_path)?, true)
+ .context("Failed to load project config")?
+ } else {
+ None
+ };
+
+ let mut all_commands = Vec::new();
+ if let Some(cfg) = feature_config.as_ref() {
+ all_commands.extend(collect_commands_for_hooks(cfg, &feature_hooks));
+ }
+ if let Some(cfg) = destination_config.as_ref() {
+ all_commands.extend(collect_commands_for_hooks(cfg, &destination_hooks));
+ }
+ if needs_pre_remove && let Some(cfg) = feature_config.as_ref().or(destination_config.as_ref()) {
+ all_commands.extend(collect_commands_for_hooks(cfg, &[HookType::PreRemove]));
+ }
- let project_id = repo.project_identifier()?;
- Ok((all_commands, project_id))
+ Ok((all_commands, repo.project_identifier()?))
}
pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
@@ -173,6 +202,13 @@ 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.
+ let destination_path = match &target_worktree_path {
+ Some(path) => path.clone(),
+ None => repo.home_path()?,
+ };
// Quick check for command approval: will removal be attempted?
// The authoritative guard is prepare_merge_removal (shared with wt remove),
@@ -182,8 +218,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
let remove_requested = remove && !on_target;
// Collect and approve all commands upfront for batch permission request
- let (all_commands, project_id) =
- collect_merge_commands(repo, commit, verify, remove_requested, squash_enabled)?;
+ let (all_commands, project_id) = collect_merge_commands(
+ repo,
+ &destination_path,
+ commit,
+ verify,
+ remove_requested,
+ squash_enabled,
+ )?;
// Approve all commands in a single batch (shows templates, not expanded values)
let approvals = Approvals::load().context("Failed to load approvals")?;
diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rs
index 7c1846157..3f2175b8d 100644
--- a/src/commands/worktree/finish.rs
+++ b/src/commands/worktree/finish.rs
@@ -156,10 +156,19 @@ pub fn finish_after_merge(
};
if verify {
- // Post-merge hooks run in the destination worktree (target), but bare vars
- // point to the Active (feature branch) per the template variable model.
- // The destination worktree is the execution context (cwd).
- let ctx = CommandContext::new(repo, config, Some(current_branch), &destination_path, yes);
+ // Post-merge hooks run in the destination worktree (target), and resolve
+ // their `.config/wt.toml` from there — root `ctx.repo` at the
+ // destination (the feature worktree may be gone by now). Bare template
+ // vars still point to the Active (feature branch) per the template
+ // variable model; those are repo-wide lookups, unaffected by the root.
+ let dest_repo = Repository::at(&destination_path).unwrap_or_else(|_| repo.clone());
+ let ctx = CommandContext::new(
+ &dest_repo,
+ config,
+ Some(current_branch),
+ &destination_path,
+ yes,
+ );
let display_path = if removed {
crate::output::post_hook_display_path(&destination_path)
} else {
diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rs
index d522bbf5c..5565da361 100644
--- a/src/commands/worktree/types.rs
+++ b/src/commands/worktree/types.rs
@@ -204,6 +204,18 @@ pub enum RemoveResult {
}
impl RemoveResult {
+ /// Path of the removed worktree, if this result removed one.
+ ///
+ /// `None` for branch-only deletions — they have no worktree, so no
+ /// `pre-remove` hook runs and there's no worktree-local `.config/wt.toml`
+ /// to consult.
+ pub fn removed_worktree_path(&self) -> Option<&Path> {
+ match self {
+ RemoveResult::RemovedWorktree { worktree_path, .. } => Some(worktree_path),
+ RemoveResult::BranchOnly { .. } => None,
+ }
+ }
+
/// Convert to a JSON value for structured output.
pub fn to_json(&self) -> serde_json::Value {
match self {
diff --git a/src/git/repository/config.rs b/src/git/repository/config.rs
index 2b73e3ad7..b00e5a347 100644
--- a/src/git/repository/config.rs
+++ b/src/git/repository/config.rs
@@ -544,6 +544,12 @@ impl Repository {
/// bare repos). For bare repos at the bare root (outside any worktree),
/// falls back to the primary worktree. Returns `None` when no worktree can
/// be determined (bare repo with no linked worktrees).
+ ///
+ /// "The current worktree" is whatever this `Repository` was rooted at, so
+ /// the answer to "which `.config/wt.toml` does a hook read" is decided by
+ /// the caller's choice of root. That policy — which worktree each hook type
+ /// is resolved against — is the spec in the `commands::hooks` module docs
+ /// (`src/commands/hooks.rs`).
pub fn project_config_path(&self) -> anyhow::Result<Option<PathBuf>> {
if let Ok(path) = std::env::var("WORKTRUNK_PROJECT_CONFIG_PATH") {
return Ok(Some(PathBuf::from(path)));
diff --git a/src/main.rs b/src/main.rs
index 2856c9231..219c4ac7e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1,5 +1,6 @@
use std::collections::HashSet;
use std::io::Write;
+use std::path::Path;
use anyhow::Context;
use clap::FromArgMatches;
@@ -893,31 +894,56 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
.into());
}
- // Resolve current worktree context for hook approval
- let current_wt = repo.current_worktree();
- let approve_worktree_path = current_wt.root()?;
- let approve_branch = current_wt
+ // Branch context for the approval prompt. Templates are shown
+ // unexpanded, so the exact branch is immaterial — `project_id`
+ // (which selects the approvals namespace) doesn't depend on it.
+ let approve_branch = repo
+ .current_worktree()
.branch()
.context("Failed to determine current branch")?;
- // Helper: approve remove hooks using current worktree context
- // Returns true if hooks should run (user approved)
- let approve_remove = |yes: bool| -> anyhow::Result<bool> {
+ // Helper: approve remove hooks. `pre-remove` runs in each worktree
+ // being removed and resolves *that* worktree's `.config/wt.toml`
+ // (falling back to the primary worktree's when the removed one has
+ // none — same rule as `execute_pre_remove_hooks_if_needed`), so
+ // it's approved per worktree against that config; `post-remove` and
+ // `post-switch` run in the primary worktree afterwards (the removed
+ // worktree is gone) and are approved once against its config. The
+ // `Repository` rooted at each path is what selects the config — see
+ // [`Repository::project_config_path`]. Returns true if every prompt
+ // was accepted (or there was nothing to approve).
+ let approve_remove = |removed_worktree_paths: &[&Path], yes: bool| -> anyhow::Result<bool> {
+ let decline_msg = "Commands declined, continuing removal";
+ let primary_path = repo.home_path()?;
+ let primary_repo = || Repository::at(&primary_path).unwrap_or_else(|_| repo.clone());
+ for &wt_path in removed_worktree_paths {
+ let wt_repo = match Repository::at(wt_path) {
+ Ok(r) if r.load_project_config().ok().flatten().is_some() => r,
+ _ => primary_repo(),
+ };
+ let ctx = CommandContext::new(
+ &wt_repo,
+ &config,
+ approve_branch.as_deref(),
+ wt_path,
+ yes,
+ );
+ if !approve_or_skip(&ctx, &[HookType::PreRemove], decline_msg)? {
+ return Ok(false);
+ }
+ }
+ let pr = primary_repo();
let ctx = CommandContext::new(
- &repo,
+ &pr,
&config,
approve_branch.as_deref(),
- &approve_worktree_path,
+ &primary_path,
yes,
);
approve_or_skip(
&ctx,
- &[
- HookType::PreRemove,
- HookType::PostRemove,
- HookType::PostSwitch,
- ],
- "Commands declined, continuing removal",
+ &[HookType::PostRemove, HookType::PostSwitch],
+ decline_msg,
)
};
@@ -943,7 +969,8 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
}
// "Approve at the Gate": approval happens AFTER validation passes
- let run_hooks = verify && approve_remove(yes)?;
+ let removed_path = result.removed_worktree_path();
+ let run_hooks = verify && approve_remove(removed_path.as_slice(), yes)?;
let mut announcer = HookAnnouncer::new(&repo, &config, false);
handle_remove_output(&result, args.foreground, run_hooks, false, &mut announcer)?;
@@ -977,10 +1004,17 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {
return Ok(());
}
- // Approve hooks (only if we have valid plans)
- // TODO(pre-remove-context): Approval context uses current worktree,
- // but hooks execute in each target worktree.
- let run_hooks = verify && approve_remove(yes)?;
+ // Approve hooks (only if we have valid plans). Each removed
+ // worktree's `pre-remove` is approved against that worktree's
+ // own config — see `approve_remove` above.
+ let pre_remove_targets: Vec<&Path> = plans
+ .others
+ .iter()
+ .chain(&plans.branch_only)
+ .chain(plans.current.iter())
+ .filter_map(|r| r.removed_worktree_path())
+ .collect();
+ let run_hooks = verify && approve_remove(&pre_remove_targets, yes)?;
// Execute all validated plans: others first, branch-only next, current last
let show_branch =
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 01a2cabf6..73fd7f5b1 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -1189,8 +1189,20 @@ fn execute_pre_remove_hooks_if_needed(
return Ok(());
};
+ // `pre-remove` runs in — and reads `.config/wt.toml` from — the worktree
+ // being removed. It's still on disk here (removal happens after this), so
+ // resolve the config from there rather than from `repo`, which is rooted at
+ // the post-removal working directory (usually the primary worktree, or the
+ // merge destination). If the removed worktree carries no `.config/wt.toml`
+ // — e.g. it was branched before the project added one — fall back to `repo`
+ // so a project-wide `pre-remove` on the default branch still applies. The
+ // `wt remove` approval helper in `main.rs` resolves the same config.
+ let pre_remove_repo = match Repository::at(ctx.worktree_path) {
+ Ok(wt_repo) if wt_repo.load_project_config().ok().flatten().is_some() => wt_repo,
+ _ => repo.clone(),
+ };
let command_ctx = CommandContext::new(
- repo,
+ &pre_remove_repo,
&config,
ctx.branch_name,
ctx.worktree_path,
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 9e0e4824c..5fdb8a4f3 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -1745,6 +1745,57 @@ fn test_merge_primary_on_different_branch_dirty(mut repo: TestRepo) {
));
}
+/// `wt merge`'s teardown hooks resolve `.config/wt.toml` from the destination
+/// worktree, not the feature worktree being merged: `post-merge` always (it
+/// runs in the target), and `pre-remove` when the feature worktree has no
+/// `.config/wt.toml` of its own (the same fallback the executor takes). Here
+/// only the destination — `main`'s worktree — carries the config; the feature
+/// branch was created before it was added.
+#[rstest]
+fn test_merge_teardown_hooks_read_destination_worktree_config(mut repo: TestRepo) {
+ use crate::common::wait_for_file_content;
+
+ let feature_wt = repo.add_worktree_with_commit("feature-pm", "feature.txt", "x", "feat: x");
+
+ let pre_remove_marker = repo.root_path().join("pre-remove-ran.txt");
+ let post_merge_marker = repo.root_path().join("post-merge-ran.txt");
+ repo.write_project_config(&format!(
+ r#"pre-remove = "echo 'removing {{{{ branch }}}}' > {}"
+[post-merge]
+sync = "echo 'merged {{{{ branch }}}}' > {}"
+"#,
+ pre_remove_marker.to_slash_lossy(),
+ post_merge_marker.to_slash_lossy(),
+ ));
+ repo.commit("Add merge hooks on main");
+
+ let output = repo
+ .wt_command()
+ .current_dir(&feature_wt)
+ .args(["merge", "--yes"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt merge failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ wait_for_file_content(&post_merge_marker);
+ 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"
+ );
+ // pre-remove runs synchronously before removal; the feature worktree has no
+ // `.config/wt.toml`, so it falls back to the destination's.
+ assert_eq!(
+ std::fs::read_to_string(&pre_remove_marker).unwrap().trim(),
+ "removing feature-pm",
+ "pre-remove should fall back to the destination worktree's config"
+ );
+}
+
#[rstest]
fn test_merge_race_condition_commit_after_push(mut repo_with_feature_worktree: TestRepo) {
let repo = &mut repo_with_feature_worktree;
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 0a514d58e..afeeac2e5 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1710,6 +1710,54 @@ 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.
+#[rstest]
+fn test_pre_remove_hook_reads_removed_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");
+ 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()
+ ),
+ )
+ .unwrap();
+
+ // `--force` because `.config/wt.toml` is untracked in the removed worktree;
+ // `--yes` to skip the approval prompt.
+ let output = repo
+ .wt_command()
+ .args([
+ "remove",
+ "--foreground",
+ "--force",
+ "--yes",
+ "feature-local-hook",
+ ])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt remove failed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ wait_for_file_content(&marker_file);
+ 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"
+ );
+}
+
#[rstest]
fn test_pre_remove_hook_failure_aborts(mut repo: TestRepo) {
// Create project config with failing hook
diff --git a/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap
index 43321ef30..ab4f57b9b 100644
--- a/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap
+++ b/tests/snapshots/integration__integration_tests__merge__step_commit_branch_flag.snap
@@ -14,10 +14,15 @@ info:
COLUMNS: "500"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMON_DIR: ""
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
@@ -34,13 +39,17 @@ info:
WORKTRUNK_COMMIT__GENERATION__COMMAND: "cat >/dev/null && echo 'feat: add feature file'"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -50,6 +59,6 @@ exit_code: 0
----- stderr -----
▲ Auto-staging 1 untracked path:
  feature_file.txt
-◎ Generating commit message and committing changes...
+◎ Generating commit message and committing changes... (1 file, +1)
  feat: add feature file
✓ Committed changes @ [HASH]