Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(hooks): structurally close the approval-boundary TOCTOU class (#2806)
Maximilian Roos84fb34c11ae4
diff --git a/CLAUDE.md b/CLAUDE.mdindex 1f565781f..b45b34595 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -281,11 +281,11 @@ When adding a new code path that loops over child processes, call `.interrupt_ex### Project Commands Run Only After Approval-**Policy:** project-defined commands — `pre-*` / `post-*` hooks, `[aliases]`, `--execute` bodies from project config — are arbitrary code shipped in a repo the user may have just cloned, so they run only after the approval system (`Approvals` plus `approve_command_batch` / `approve_or_skip` in `src/commands/command_approval.rs`) clears them. Never build a code path that runs project commands without that gate. A context that can't prompt for approval — a TUI mid-render, a background recovery path — must consult the approval state read-only and run only the already-approved commands, skipping the rest: `commands::picker::do_removal` checks `Approvals` (no prompt) and passes `verify` to `handle_remove_output` accordingly.+**Policy:** project-defined commands (`pre-*` / `post-*` hooks, `[aliases]`, `--execute` bodies from project config) are arbitrary code shipped in a repo the user may have just cloned, so they run only after the approval system (`Approvals` plus `approve_command_batch` / `approve_or_skip` in `src/commands/command_approval.rs`) clears them. Never build a code path that runs project commands without that gate. A context that can't prompt (a TUI mid-render, a background recovery path) consults the approval state read-only and runs only the already-approved subset: `commands::picker::do_removal` builds the plan via `HookPlan::approve_readonly` (no prompt).**Why:** the gate is the only thing between `git clone && wt switch` and a `post-switch` hook running `curl … | sh`. A "we already validated the operation, so run the hooks too" shortcut turns every command that touches project config into remote code execution.-**Implementation:** the operation entry points (`wt remove` / `wt merge` / `wt step prune` / `wt switch`) approve the command set up front, then thread the answer through as `verify` / `run_hooks`; when it's false, `execute_pre_remove_hooks_if_needed`, `spawn_hooks_after_remove`, and the switch/merge equivalents early-return. Gate first, run second — never the reverse.+**Implementation:** the operation-driven hooks (`pre-merge`, `post-merge`, `pre-remove`, `post-remove`, `post-switch`, `pre-start`, `post-start`) are gated *before* a state mutation and run *after* it, so a second config read could select an unapproved command. `src/commands/hook_plan.rs` closes this structurally: each gate (`wt remove` / `wt merge` / `wt step prune` / `wt switch`) selects the command set once into an immutable `ApprovedHookPlan` (`HookPlan::approve`); the executor consumes only that value via `execute_planned_hook` / `register_planned` and holds no `ProjectConfig` to re-derive from, so re-selection is a compile error, not a review check. An empty plan (`--no-hooks`, declined, or no project config) runs nothing. The adjacent hooks with no gate→exec mutation (`pre-commit`, `post-commit`, `pre-switch`, `wt hook <type>`, aliases) still resolve config at invocation via `execute_hook` / `HookAnnouncer::register`. See `src/commands/hook_plan.rs` and the `commands::hooks` module spec.## Hook Output Logsdiff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex b36ab3325..222420643 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -348,35 +348,3 @@ pub fn approve_commit_template_append(}Ok(Some(owned))}--/// Like [`approve_or_skip`] but approves against an already-resolved-/// `ProjectConfig` rather than `ctx.repo.load_project_config()`.-///-/// `wt switch`'s post-switch hooks (`pre-start` / `post-start` / `post-switch`)-/// resolve their config from the new/destination worktree, which for-/// `--create` doesn't exist yet at approval time — the config is read from the-/// base ref via `git show` and passed in here so the prompt lists the exact-/// commands the hooks will execute. `project_id` (the approvals namespace) is-/// still taken from `ctx.repo`: it's repo-wide and independent of which-/// worktree the commands come from.-pub fn approve_or_skip_with_config(- ctx: &super::command_executor::CommandContext<'_>,- project_config: Option<&worktrunk::config::ProjectConfig>,- hook_types: &[HookType],- on_decline: &str,-) -> anyhow::Result<bool> {- let Some(project_config) = project_config else {- return Ok(true); // no project config = no commands to approve- };- let commands = collect_commands_for_hooks(project_config, hook_types);- if commands.is_empty() {- return Ok(true);- }- let project_id = ctx.repo.project_identifier()?;- let approvals = Approvals::load().context("Failed to load approvals")?;- let approved = approve_command_batch(&commands, &project_id, &approvals, ctx.yes, false)?;- if !approved {- worktrunk::styling::eprintln!("{}", worktrunk::styling::info_message(on_decline));- }- Ok(approved)-}diff --git a/src/commands/hook_plan.rs b/src/commands/hook_plan.rsnew file mode 100644index 000000000..659b29c4f--- /dev/null+++ b/src/commands/hook_plan.rs@@ -0,0 +1,521 @@+//! The frozen, approved command plan that closes the approval-boundary TOCTOU.+//!+//! # The invariant+//!+//! `CLAUDE.md` → "Project Commands Run Only After Approval". Project-defined+//! hook commands are arbitrary code shipped in a repo the user may have just+//! cloned; they run only after the approval gate clears them.+//!+//! # Why this type exists+//!+//! Selection (*which* `(source, hook_type, name, template)` tuples run),+//! authorization (project templates ∈ [`Approvals`]) and rendering+//! (template → shell string, needs live git) are three separate concerns.+//! Operation-driven hooks (`pre-merge`, `post-merge`, `pre-remove`,+//! `post-remove`, `post-switch`, `pre-start`, `post-start`) are gated *before*+//! a state mutation (auto-rebase rewrites the feature `.config/wt.toml`; a+//! merge moves the target ref; a removal scrubs the worktree; `git worktree+//! add` materializes a `--create` worktree) and executed *after* it. When+//! selection runs a second time at execution (`load_project_config()` again),+//! the mutated on-disk config can yield an *unapproved* command. On a fresh+//! clone that is remote code execution.+//!+//! The structural fix: **the gate performs selection exactly once and freezes+//! it into an [`ApprovedHookPlan`]. Executors consume only that value.** They+//! hold no [`ProjectConfig`] and call no `load_project_config()` for the+//! covered hook types — re-derivation is a compile error, not a review check.+//! The `Repository` an executor still holds is used only for *rendering*+//! ([`render_planned`] takes the frozen [`CommandConfig`] list, never config),+//! 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+//! `&[(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.+//!+//! `ApprovedHookPlan` is obtainable *only* via [`HookPlan::approve`] (the+//! interactive / `--yes` gate) or `HookPlan::approve_readonly` (the picker,+//! which can't prompt mid-render; `#[cfg(unix)]`). [`HookPlanBuilder::add`] — the sole+//! config→commands step for the covered hooks — is the only place+//! `load_project_config()`'s result is selected from.++use std::path::{Path, PathBuf};++use anyhow::Context as _;+use worktrunk::HookType;+use worktrunk::config::{Approvals, Command, CommandConfig, ProjectConfig, UserConfig};+use worktrunk::git::add_hook_skip_hint;++use super::command_approval::approve_command_batch;+use super::command_executor::{+ CommandContext, FailureStrategy, PipelineKind, execute_pipeline_foreground, prepare_steps,+};+use super::hook_announcement::SourcedStep;+use super::hook_filter::HookSource;+use super::hooks::{+ HookAnnouncer, into_source_groups, lookup_hook_configs, sourced_steps_to_foreground,+};+use super::project_config::{ApprovableCommand, Phase};++/// One `(hook_type, anchor)`'s frozen, source-tagged selection.+///+/// `User` entries precede `Project` so the flat render order matches the+/// existing background grouping (a user-hook failure must not abort project+/// hooks). Each `CommandConfig` is an owned clone — frozen data, no config+/// 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.+struct PlanEntry {+ hook_type: HookType,+ anchor: PathBuf,+ selection: Selection,+}++/// A selected-but-not-yet-authorized plan. Built only by [`HookPlanBuilder`].+pub struct HookPlan {+ entries: Vec<PlanEntry>,+}++/// Accumulates per-anchor selections from each 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+/// command gates.+pub struct HookPlanBuilder {+ entries: Vec<PlanEntry>,+}++impl HookPlanBuilder {+ pub fn new() -> Self {+ Self {+ entries: Vec::new(),+ }+ }++ /// Select `hook_types` anchored at `anchor`, from the already-resolved+ /// `project_config` (the gate snapshots / `git show`s it) plus user config.+ ///+ /// `project_id` scopes the user-config hook lookup. Source identity is+ /// preserved so source-scoped behavior survives into execution.+ pub fn add(+ &mut self,+ anchor: &Path,+ hook_types: &[HookType],+ project_config: Option<&ProjectConfig>,+ user: &UserConfig,+ project_id: Option<&str>,+ ) -> &mut Self {+ let user_hooks = user.hooks(project_id);+ for &hook_type in hook_types {+ let (user_cfg, proj_cfg) = lookup_hook_configs(&user_hooks, project_config, hook_type);+ let mut selection: Selection = Vec::new();+ if let Some(cfg) = user_cfg {+ selection.push((HookSource::User, cfg.clone()));+ }+ if let Some(cfg) = proj_cfg {+ selection.push((HookSource::Project, cfg.clone()));+ }+ if selection.is_empty() {+ continue;+ }+ match self+ .entries+ .iter_mut()+ .find(|e| e.hook_type == hook_type && e.anchor == anchor)+ {+ Some(e) => {+ // A repeated `(hook_type, anchor)` add must not interleave+ // sources: `into_source_groups` requires User entries+ // contiguous before Project ones. Stable sort by+ // `HookSource` (User < Project) keeps that structurally,+ // not by caller convention.+ e.selection.extend(selection);+ e.selection.sort_by_key(|(source, _)| *source);+ }+ None => self.entries.push(PlanEntry {+ hook_type,+ anchor: anchor.to_path_buf(),+ selection,+ }),+ }+ }+ self+ }++ pub fn finish(self) -> HookPlan {+ HookPlan {+ entries: self.entries,+ }+ }+}++impl Default for HookPlanBuilder {+ fn default() -> Self {+ Self::new()+ }+}++impl HookPlan {+ /// The project-source templates the prompt must show, deduped by template+ /// so the same command across several anchors prompts once (the common+ /// case: every removal in a batch lands in the same primary worktree).+ fn approvable(&self) -> Vec<ApprovableCommand> {+ let mut seen = std::collections::HashSet::new();+ let mut out = Vec::new();+ for entry in &self.entries {+ for (source, cfg) in &entry.selection {+ if *source != HookSource::Project {+ continue;+ }+ for cmd in cfg.commands() {+ if seen.insert(cmd.template.clone()) {+ out.push(ApprovableCommand {+ phase: Phase::Hook(entry.hook_type),+ command: Command::new(cmd.name.clone(), cmd.template.clone()),+ });+ }+ }+ }+ }+ out+ }++ /// Interactive / `--yes` gate. Reuses [`approve_command_batch`] so the+ /// prompt, the `--yes` path, and the saved approvals are byte-identical to+ /// before. `Ok(None)` means the user declined — the caller prints its own+ /// "continuing without hooks" message and proceeds with+ /// [`ApprovedHookPlan::empty`].+ ///+ /// When no project-source command needs the gate (no project config, or+ /// only user hooks), this returns the frozen plan **without** loading+ /// `Approvals` or requiring `project_id`. That keeps a malformed+ /// `approvals.toml` or an unresolvable project identifier from aborting a+ /// command that has nothing to authorize, matching the pre-plan behaviour+ /// where the empty-batch fast path ran before any approval state was+ /// touched. `project_id` is therefore `Option`: it is consulted only when+ /// there is something to approve, where it must be present.+ pub fn approve(+ self,+ project_id: Option<&str>,+ yes: bool,+ ) -> anyhow::Result<Option<ApprovedHookPlan>> {+ let approvable = self.approvable();+ if approvable.is_empty() {+ return Ok(Some(ApprovedHookPlan {+ entries: self.entries,+ }));+ }+ let project_id =+ project_id.context("project identifier is required to approve project commands")?;+ let approvals = Approvals::load().context("Failed to load approvals")?;+ let approved = approve_command_batch(&approvable, project_id, &approvals, yes, false)?;+ if !approved {+ return Ok(None);+ }+ Ok(Some(ApprovedHookPlan {+ entries: self.entries,+ }))+ }++ /// The picker can't prompt mid-render, so it runs only the already-approved+ /// project pipelines and silently drops the rest (keeping user pipelines).+ /// Strictly the CLAUDE.md "consult the approval state read-only and run+ /// only the already-approved commands, skipping the rest" rule. An absent+ /// `project_id` (unresolvable identifier) drops every project pipeline —+ /// fail-closed, never run unapproved.+ #[cfg(unix)]+ pub fn approve_readonly(+ self,+ approvals: &Approvals,+ project_id: Option<&str>,+ ) -> ApprovedHookPlan {+ let mut entries = self.entries;+ for entry in &mut entries {+ entry.selection.retain(|(source, cfg)| {+ *source != HookSource::Project+ || project_id.is_some_and(|pid| {+ cfg.commands()+ .all(|c| approvals.is_command_approved(pid, &c.template))+ })+ });+ }+ entries.retain(|e| !e.selection.is_empty());+ ApprovedHookPlan { entries }+ }+}++/// The only value executors accept. Constructible solely via+/// [`HookPlan::approve`] / `HookPlan::approve_readonly` / [`Self::empty`].+/// Holds no `Repository` / `ProjectConfig`, only the frozen selection.+pub struct ApprovedHookPlan {+ entries: Vec<PlanEntry>,+}++impl ApprovedHookPlan {+ /// No hooks: `--no-hooks`, declined approval, or no project config. Every+ /// covered executor consumes this and runs nothing.+ pub fn empty() -> Self {+ Self {+ entries: Vec::new(),+ }+ }++ /// The frozen selection for `(hook_type, anchor)`, by exact match.+ ///+ /// Every covered gate anchors at the identical path its executor passes:+ /// the `RemoveResult` worktree/destination path threaded unchanged, the+ /// `SwitchPlan`/`SwitchResult` destination, or the merge feature root+ /// (`current_worktree().root()` on the same `Repository`, cached, so the+ /// gate and `finish_after_merge` produce the same `PathBuf`). The invariant+ /// is gate-anchor == executor-anchor; this method does not paper over a+ /// violation with a "sole entry" guess that would silently run a different+ /// worktree's hook. A miss returns `&[]` — no hooks run, which surfaces+ /// visibly rather than as a wrong-worktree execution.+ fn lookup(&self, hook_type: HookType, anchor: &Path) -> &[(HookSource, CommandConfig)] {+ self.entries+ .iter()+ .find(|e| e.hook_type == hook_type && e.anchor == anchor)+ .map(|e| e.selection.as_slice())+ .unwrap_or(&[])+ }+}++/// Render the frozen selection into source-tagged steps. Takes the frozen+/// `CommandConfig` list, never config — re-selection is impossible. `ctx`'s+/// `Repository` is used only for template expansion.+fn render_planned(+ entries: &[(HookSource, CommandConfig)],+ ctx: &CommandContext<'_>,+ extra_vars: &[(&str, &str)],+ hook_type: HookType,+) -> anyhow::Result<Vec<SourcedStep>> {+ let mut out = Vec::new();+ for (source, cfg) in entries {+ let is_pipeline = cfg.is_pipeline();+ for step in prepare_steps(cfg, ctx, extra_vars, hook_type, *source)? {+ out.push(SourcedStep {+ step,+ source: *source,+ is_pipeline,+ });+ }+ }+ Ok(out)+}++/// Foreground execution of a covered hook from the approved plan.+///+/// Replaces `execute_hook` for `pre-merge` / `pre-remove` / `pre-start`. The+/// 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.+pub fn execute_planned_hook(+ plan: &ApprovedHookPlan,+ anchor: &Path,+ ctx: &CommandContext<'_>,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ failure_strategy: FailureStrategy,+ display_path: Option<&Path>,+) -> anyhow::Result<()> {+ let sourced = render_planned(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)?;+ if sourced.is_empty() {+ return Ok(());+ }+ let kind = PipelineKind::Hook {+ hook_type,+ display_path: display_path.map(Path::to_path_buf),+ };+ let foreground = sourced_steps_to_foreground(sourced, &kind);+ execute_pipeline_foreground(&foreground, ctx.repo, ctx.worktree_path, failure_strategy)+ .map_err(add_hook_skip_hint)+}++/// Register a covered background hook (`post-merge` / `post-remove` /+/// `post-switch` / `post-start`) from the approved plan onto `announcer`.+///+/// The plan-backed counterpart of `HookAnnouncer::register`: steps are+/// 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`]).+pub fn register_planned(+ announcer: &mut HookAnnouncer<'_>,+ plan: &ApprovedHookPlan,+ anchor: &Path,+ ctx: &CommandContext<'_>,+ hook_type: HookType,+ extra_vars: &[(&str, &str)],+ display_path: Option<&Path>,+) -> anyhow::Result<()> {+ let sourced = render_planned(plan.lookup(hook_type, anchor), ctx, extra_vars, hook_type)+ .context("failed to render planned hooks")?;+ let dp = display_path.map(Path::to_path_buf);+ announcer.extend(+ into_source_groups(sourced)+ .into_iter()+ .map(|g| (*ctx, hook_type, dp.clone(), g)),+ );+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn project_cfg(toml: &str) -> ProjectConfig {+ toml::from_str(toml).unwrap()+ }++ /// The plan freezes the selection at build time: once approved, the+ /// authorized command set is fixed and the executor's `lookup` returns it+ /// from the frozen value alone — there is no `Repository`/`ProjectConfig`+ /// on `ApprovedHookPlan` to re-derive a (mutated) command from. This is the+ /// structural property that closes the TOCTOU class.+ #[test]+ fn approved_plan_lookup_is_frozen_and_anchor_scoped() {+ let user = UserConfig::default();+ let gate_cfg = project_cfg(r#"post-merge = "echo approved""#);++ let mut builder = HookPlanBuilder::new();+ builder.add(+ Path::new("/dest"),+ &[HookType::PostMerge],+ Some(&gate_cfg),+ &user,+ None,+ );+ // `--yes` ⇒ approved without writing approvals.+ let plan = builder+ .finish()+ .approve(Some("proj"), true)+ .unwrap()+ .expect("yes-approval never declines");++ // The frozen selection is exactly the gate config's command. A later+ // on-disk mutation is unrepresentable here: `lookup` consults only the+ // plan (no config handle in scope).+ let sel = plan.lookup(HookType::PostMerge, Path::new("/dest"));+ assert_eq!(sel.len(), 1);+ let (source, cfg) = &sel[0];+ assert_eq!(*source, HookSource::Project);+ let templates: Vec<_> = cfg.commands().map(|c| c.template.as_str()).collect();+ assert_eq!(templates, vec!["echo approved"]);++ // A hook type that was never planned yields nothing — the executor+ // cannot conjure one from config it doesn't hold.+ assert!(+ plan.lookup(HookType::PreMerge, Path::new("/dest"))+ .is_empty()+ );+ }++ /// The picker's read-only gate keeps user pipelines but drops project+ /// pipelines whose templates aren't already approved (no prompt).+ #[cfg(unix)]+ #[test]+ fn approve_readonly_drops_unapproved_project_keeps_user() {+ let user = UserConfig {+ hooks: toml::from_str(r#"pre-remove = "echo user-hook""#).unwrap(),+ ..UserConfig::default()+ };+ let proj = project_cfg(r#"pre-remove = "echo project-hook""#);++ let mut builder = HookPlanBuilder::new();+ builder.add(+ Path::new("/wt"),+ &[HookType::PreRemove],+ Some(&proj),+ &user,+ None,+ );+ let plan = builder+ .finish()+ // Empty approvals ⇒ the project pipeline is unapproved.+ .approve_readonly(&Approvals::default(), Some("proj"));++ let sel = plan.lookup(HookType::PreRemove, Path::new("/wt"));+ assert_eq!(+ sel.iter().map(|(s, _)| *s).collect::<Vec<_>>(),+ vec![HookSource::User],+ "unapproved project pipeline dropped, user pipeline kept"+ );++ // With the project command approved, it survives the read-only gate.+ let mut approvals = Approvals::default();+ approvals+ .approve_command("proj".to_string(), "echo project-hook".to_string(), None)+ .unwrap();+ let mut builder = HookPlanBuilder::new();+ builder.add(+ Path::new("/wt"),+ &[HookType::PreRemove],+ Some(&proj),+ &user,+ None,+ );+ let plan = builder.finish().approve_readonly(&approvals, Some("proj"));+ let sel = plan.lookup(HookType::PreRemove, Path::new("/wt"));+ assert_eq!(+ sel.iter().map(|(s, _)| *s).collect::<Vec<_>>(),+ vec![HookSource::User, HookSource::Project],+ );+ }++ /// Repeated `(hook_type, anchor)` adds must keep User entries contiguous+ /// before Project ones — `into_source_groups` (a user-hook failure must+ /// not abort project hooks) depends on it. Structural via the stable sort+ /// in `add`, not caller convention.+ #[test]+ fn duplicate_add_keeps_sources_grouped() {+ let user = UserConfig {+ hooks: toml::from_str(r#"post-merge = "echo u""#).unwrap(),+ ..UserConfig::default()+ };+ let proj = project_cfg(r#"post-merge = "echo p""#);++ let mut builder = HookPlanBuilder::new();+ // Same (PostMerge, /dest) added twice — the interleave-prone path.+ builder.add(+ Path::new("/dest"),+ &[HookType::PostMerge],+ Some(&proj),+ &user,+ None,+ );+ builder.add(+ Path::new("/dest"),+ &[HookType::PostMerge],+ Some(&proj),+ &user,+ None,+ );+ let plan = builder+ .finish()+ .approve(Some("proj"), true)+ .unwrap()+ .unwrap();+ let sources: Vec<_> = plan+ .lookup(HookType::PostMerge, Path::new("/dest"))+ .iter()+ .map(|(s, _)| *s)+ .collect();+ // All User before all Project, never interleaved.+ let first_project = sources.iter().position(|s| *s == HookSource::Project);+ assert!(+ first_project.is_none_or(|i| sources[i..].iter().all(|s| *s == HookSource::Project)),+ "sources interleaved: {sources:?}"+ );+ }+}diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 4def6b13a..7d3a67378 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -5,59 +5,54 @@//!//! # Which `.config/wt.toml` a hook reads//!-//! **Every hook is anchored to one worktree — the worktree it's *about*.** It-//! reads that worktree's `.config/wt.toml`. When the worktree isn't on disk at-//! the moment we need to read it, read a snapshot.+//! 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.//!-//! Most hooks resolve their project config from `ctx.repo.load_project_config()`-//! — [`execute_hook`], [`prepare_background_pipelines`], and-//! [`super::command_approval::approve_hooks`] all do this — so the construction-//! sites just have to root `ctx.repo` at the anchor worktree. Two hooks resolve-//! the config from a snapshot instead, because the anchor isn't on disk at-//! preparation time: see "Snapshot paths" below.+//! **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+//! 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.//!-//! Each worktree's `.config/wt.toml` stands alone — there is 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.-//!-//! | Hook | Anchor worktree | Set in |+//! | Plan-backed hook | Anchor worktree | Gate builds the plan in |//! |---|---|---|-//! | `pre-remove`, `post-remove` | the worktree being removed (`pre-remove` reads it on disk; `post-remove` reads a snapshot taken before removal, stashed on [`super::worktree::RemoveResult::RemovedWorktree::removed_project_config`]) | `output::handlers::execute_pre_remove_hooks_if_needed` and `output::handlers::spawn_hooks_after_remove`; the three approval call sites (`main.rs`'s `approve_remove` for `wt remove`, `merge::collect_merge_commands` for `wt merge`, `step::prune::approve_prune_hooks` for `wt step prune`) all delegate to [`super::project_config::collect_remove_hook_commands`] |-//! | `post-merge` | the merge destination (target branch's worktree if it has one, otherwise the primary) | `worktree::finish::finish_after_merge`; approval in `merge::collect_merge_commands` |-//! | `post-switch` after a removal | the post-removal working directory the user lands in ([`super::worktree::RemoveResult::destination_path`]) — usually the primary worktree, cwd when the primary worktree is itself removed (bare repo), the merge destination for `wt merge` | `output::handlers::spawn_hooks_after_remove`; approval through `collect_remove_hook_commands` |-//! | `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 new (`--create`) or destination (`wt switch <existing>`) worktree | `worktree::switch` — `hook_repo_for_worktree` (execution); `switch_hook_project_config` (approval / pre-flight, see Snapshot paths below) |-//! | `pre-switch`, `pre-merge`, `wt hook <type>`, aliases | the worktree `wt` was invoked in | the respective command entry points |-//!-//! ## Snapshot paths-//!-//! Two hooks need the anchor's config when the anchor itself isn't on disk:+//! | `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` |//!-//! - **`post-remove`** runs after the anchor worktree was just deleted. The-//! removed worktree's `ProjectConfig` is loaded by `prepare_worktree_removal`-//! (or `finish_after_merge` for `wt merge`) *before* the deletion and stashed-//! on `RemoveResult::RemovedWorktree::removed_project_config`. The executor-//! reads it via [`HookAnnouncer::register_with_project_config`].-//! - **`wt switch --create`'s post-switch hooks** (approval-time only) anchor at-//! a worktree that doesn't exist yet — `git worktree add` runs after the-//! approval gate. The approval prompt and template pre-flight read the base-//! ref's committed `.config/wt.toml` via `git show` (`git fetch`ing a-//! `pr:`/`mr:` fork head first), assembled by `switch_hook_project_config` and-//! passed to [`super::command_approval::approve_or_skip_with_config`]. By-//! execution time the worktree exists and the executor reads its on-disk-//! config the normal way.-//!-//! Different physical sources, same role: produce the anchor's config when the-//! anchor isn't on disk.+//! **Invocation-resolved (no gate→exec mutation):** `pre-commit`,+//! `post-commit`, `pre-switch`, `wt hook <type>`, aliases. They resolve config+//! from `ctx.repo.load_project_config()` at invocation via [`execute_hook`] /+//! [`HookAnnouncer::register`]. Two facts make that re-read safe, and a new+//! call site must preserve **both**: (1) nothing between the gate and the+//! executor mutates the worktree `.config/wt.toml`; (2) the executor reads+//! through the **same `Repository` instance** the gate used —+//! `load_project_config` reads the working-tree file and memoizes it in a+//! never-invalidated `OnceCell` (`RepoCache::project_config`), so the+//! executor's call is a cache hit returning the gate's exact bytes. A+//! refactor that runs an uncovered executor through a fresh `Repository::at()`+//! (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.//!+//! 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-//! (test isolation). User config (`~/.config/worktrunk/config.toml`) is global-//! and unaffected. Every hook is approved against the same `.config/wt.toml`-//! it executes against. The one exception is `wt step prune`, which calls-//! [`super::project_config::collect_remove_hook_commands`] over every linked-//! worktree it might prune (the integrated set isn't known until the checks-//! run), a superset of what executes.+//! (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.use std::collections::HashMap;use std::path::{Path, PathBuf};@@ -280,11 +275,10 @@ impl<'a> HookAnnouncer<'a> {/// Prepare and add user+project pipelines for a single hook type, reading/// the project config from `ctx.repo.load_project_config()` — the worktree- /// this hook acts on, per the spec. Use [`Self::register_with_project_config`]- /// when the anchor worktree isn't on disk and the config came from a- /// snapshot or git ref (`post-remove` after the worktree is gone; `wt- /// switch`'s post-switch hooks before `--create` materializes the new- /// worktree).+ /// this hook acts on. Used by the invocation-resolved hooks+ /// (`pre-commit` / `post-commit` and `wt hook <type>`'s filter path), where+ /// nothing mutates config between approval and execution. The plan-backed+ /// hooks use [`super::hook_plan::register_planned`] instead.pub fn register(&mut self,ctx: &CommandContext<'_>,@@ -293,27 +287,13 @@ impl<'a> HookAnnouncer<'a> {display_path: Option<&Path>,) -> anyhow::Result<()> {let project_config = ctx.repo.load_project_config()?;- self.register_with_project_config(+ let pipelines = prepare_background_pipelines(ctx,project_config.as_ref(),hook_type,extra_vars,display_path,- )- }-- /// Like [`Self::register`], but reads the project config from an explicit- /// snapshot instead of `ctx.repo.load_project_config()`.- pub fn register_with_project_config(- &mut self,- ctx: &CommandContext<'_>,- project_config: Option<&worktrunk::config::ProjectConfig>,- hook_type: HookType,- extra_vars: &[(&str, &str)],- display_path: Option<&Path>,- ) -> anyhow::Result<()> {- let pipelines =- prepare_background_pipelines(ctx, project_config, hook_type, extra_vars, display_path)?;+ )?;self.extend(pipelines);Ok(())}@@ -480,13 +460,10 @@ pub(crate) fn into_source_groups(flat: Vec<SourcedStep>) -> Vec<Vec<SourcedStep>/// group is returned with its `(hook_type, display_path)` metadata.////// `project_config` is the resolved `.config/wt.toml` for this hook's anchor-/// worktree — normally `ctx.repo.load_project_config()` (what-/// [`HookAnnouncer::register`] passes), or a snapshot / git-ref-derived config-/// when the anchor isn't on disk at preparation time: `post-remove` (worktree-/// just removed; config snapshotted on [`super::worktree::RemoveResult::RemovedWorktree`])-/// and `wt switch`'s post-switch hooks before `--create` materializes the new-/// worktree (config from the base ref via `git show`). See the module-level-/// "Which `.config/wt.toml` a hook reads" docs.+/// worktree, passed by [`HookAnnouncer::register`] from+/// `ctx.repo.load_project_config()`. Only the invocation-resolved hooks reach+/// here; plan-backed hooks render from the frozen plan instead (see the+/// module-level "Which `.config/wt.toml` a hook reads" docs).pub(crate) fn prepare_background_pipelines<'c>(ctx: &CommandContext<'c>,project_config: Option<&worktrunk::config::ProjectConfig>,diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 74e26de6c..f4615bfa2 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -2,18 +2,16 @@ use std::path::Path;use anyhow::Context;use worktrunk::HookType;-use worktrunk::config::{Approvals, MergeConfig, UserConfig};+use worktrunk::config::{MergeConfig, UserConfig};use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};-use super::command_approval::{approve_command_batch, approve_commit_template_append};+use super::command_approval::approve_commit_template_append;use super::command_executor::FailureStrategy;use super::commit::{CommitOptions, HookGate};use super::context::CommandEnv;-use super::hooks::{HookAnnouncer, execute_hook};-use super::project_config::{- ApprovableCommand, collect_commands_for_hooks, collect_remove_hook_commands,-};+use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder, execute_planned_hook};+use super::hooks::HookAnnouncer;use super::repository_ext::RepositoryCliExt;use super::template_vars::TemplateVars;use super::worktree::{@@ -76,67 +74,94 @@ pub struct MergeOptions<'a> {pub format: crate::cli::SwitchFormat,}-/// Collect all commands that will be executed during merge, for batch approval.+/// 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:///-/// Returns (commands, project_identifier). Each hook is approved against the-/// `.config/wt.toml` of the worktree it runs in (and is resolved from):+/// - `pre-commit` / `post-commit` / `pre-merge` / `pre-remove` / `post-remove`+/// → the feature worktree (`repo`'s cwd).+/// - `post-merge` / `post-switch` → the merge destination.///-/// - `pre-commit` / `post-commit` / `pre-merge` → the feature worktree-/// (= `repo`'s cwd).-/// - `post-merge` → the merge destination (`destination_path`).-/// - `pre-remove` / `post-remove` / `post-switch` (when the feature worktree-/// is being removed) → resolved by [`collect_remove_hook_commands`], which-/// reads `pre-remove` from the feature worktree's own `.config/wt.toml`-/// and `post-remove` / `post-switch` from the destination — mirroring-/// `output::handlers::execute_pre_remove_hooks_if_needed`. No fallback-/// between worktrees — each `.config/wt.toml` stands alone.-fn collect_merge_commands(+/// `pre-commit`/`post-commit` execute via the unchanged commit/squash path+/// (no gate→exec state mutation precedes the commit), but are included here so+/// the single approval prompt is byte-identical to before; the TOCTOU-covered+/// hooks (`pre-merge` onward) execute *only* from the returned plan.+///+/// `Ok(None)` ⇒ the user declined; the caller proceeds without hooks.+#[allow(clippy::too_many_arguments)]+fn approve_merge_plan(repo: &Repository,+ config: &UserConfig,+ feature_root: &Path,destination_path: &Path,+ project_id: &str,commit: bool,verify: bool,will_remove: bool,squash_enabled: bool,-) -> anyhow::Result<(Vec<ApprovableCommand>, String)> {+ yes: bool,+) -> anyhow::Result<Option<ApprovedHookPlan>> {+ let pid = Some(project_id);++ // Every feature-worktree hook shares one anchor: the feature worktree's+ // canonical root, the exact path `finish_after_merge` records as+ // `RemoveResult::worktree_path` and `handle_merge` passes as the+ // `pre-merge` executor anchor, so every plan lookup is an exact match.+ // `pre-commit`/`post-commit` run via the unchanged `execute_hook` path and+ // are listed only so the single prompt is complete; their anchor is never+ // looked up.let mut feature_hooks = Vec::new();- let mut destination_hooks = Vec::new();-- // Pre-commit hooks run when a commit will actually be createdlet will_create_commit = repo.current_worktree().is_dirty()? || squash_enabled;if commit && verify && will_create_commit {feature_hooks.push(HookType::PreCommit);feature_hooks.push(HookType::PostCommit);}-if verify {feature_hooks.push(HookType::PreMerge);- destination_hooks.push(HookType::PostMerge);+ }+ if verify && will_remove {+ feature_hooks.push(HookType::PreRemove);+ feature_hooks.push(HookType::PostRemove);}- let mut all_commands = Vec::new();- if let Some(cfg) = repo.load_project_config()? {- all_commands.extend(collect_commands_for_hooks(&cfg, &feature_hooks));+ // 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.+ let mut builder = HookPlanBuilder::new();+ if !feature_hooks.is_empty() {+ let feature_cfg = repo.load_project_config()?;+ builder.add(+ feature_root,+ &feature_hooks,+ feature_cfg.as_ref(),+ config,+ pid,+ );}- if !destination_hooks.is_empty() || (verify && will_remove) {- let destination_repo = Repository::at(destination_path)?;- if !destination_hooks.is_empty()- && let Some(cfg) = destination_repo.load_project_config()?- {- all_commands.extend(collect_commands_for_hooks(&cfg, &destination_hooks));- }- if verify && will_remove {- let current_wt = repo.current_worktree();- let feature_path = current_wt.path();- // The feature worktree is removed; the user lands in the merge- // destination, so `post-switch` reads `destination_path`'s config.- all_commands.extend(collect_remove_hook_commands(- &[feature_path],- &[destination_path],- )?);+ 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()?;+ builder.add(+ destination_path,+ &[HookType::PostMerge],+ dest_cfg.as_ref(),+ config,+ pid,+ );+ if will_remove {+ builder.add(+ destination_path,+ &[HookType::PostSwitch],+ dest_cfg.as_ref(),+ config,+ pid,+ );}}- Ok((all_commands, repo.project_identifier()?))+ builder.finish().approve(pid, yes)}pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {@@ -214,21 +239,28 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let on_target = current_branch == target_branch;let remove_requested = remove && !on_target;- // Collect and approve all commands upfront for batch permission request- let (all_commands, project_id) = collect_merge_commands(+ // Build and approve the frozen hook plan once, at the gate. Every covered+ // hook (`pre-merge` / `post-merge` / `pre-remove` / `post-remove` /+ // `post-switch`) executes only from this immutable value — re-reading the+ // (by-then-rebased / merged) on-disk config is structurally impossible.+ let project_id = repo.project_identifier()?;+ // One anchor for every feature-worktree hook: the canonical root, the same+ // value `finish_after_merge` records as `RemoveResult::worktree_path`.+ let feature_root = current_wt.root()?;+ let plan = approve_merge_plan(repo,+ config,+ &feature_root,&destination_path,+ &project_id,commit,verify,remove_requested,squash_enabled,+ yes,)?;-- // Approve hook commands in a single batch (shows templates, not expanded- // values). The project commit-append is gated separately below so that- // declining it never skips hooks.- let approvals = Approvals::load().context("Failed to load approvals")?;- let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;+ let approved = plan.is_some();+ let plan = plan.unwrap_or_else(ApprovedHookPlan::empty);// Commit-phase gate uses the original `verify` (before the shadow below) so it can// distinguish --no-hooks from declined-approval; CommitOptions and handle_squash@@ -332,7 +364,9 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {if let Some(p) = target_worktree_path.as_deref() {vars = vars.with_target_worktree_path(p);}- execute_hook(+ execute_planned_hook(+ &plan,+ &feature_root,&ctx,HookType::PreMerge,&vars.as_extra_vars(),@@ -367,6 +401,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {remove,verify,yes,+ plan: &plan,},)?;diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex b5795b62c..1ddd48c96 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -11,6 +11,7 @@ mod for_each;mod hook_announcement;mod hook_commands;mod hook_filter;+pub(crate) mod hook_plan;pub(crate) mod hooks;pub(crate) mod init;pub(crate) mod list;diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 4f5a7ea1f..6c4fb5fdc 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -105,14 +105,15 @@ use anyhow::Context;// bounded/unbounded/Sender are re-exported by skim::preludeuse skim::prelude::*;use skim::reader::CommandCollector;+use worktrunk::HookType;use worktrunk::config::Approvals;use worktrunk::git::{Repository, current_or_recover};use worktrunk::styling::eprintln;+use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};use super::hooks::HookAnnouncer;use super::list::collect;use super::list::progressive::RenderTarget;-use super::project_config::collect_remove_hook_commands;use super::repository_ext::{RemoveTarget, RepositoryCliExt};use super::template_vars::TemplateVars;use super::worktree::{@@ -166,7 +167,7 @@ struct PickerCollector {/// its `pre-remove` / `post-remove` / `post-switch` hooks only when every/// one is in here — the picker can't show an approval prompt mid-render, so/// unapproved project commands are skipped, never run. See- /// [`removal_hooks_approved`].+ /// [`approved_removal_plan`].approvals: Arc<Approvals>,}@@ -177,9 +178,10 @@ impl PickerCollector {/// silent (TUI) mode — the git worktree removal with no `wt`-generated/// messages, spinner, or `cd` directive (skim owns the terminal). Its/// `pre-remove` / `post-remove` / `post-switch` hooks run only when they're- /// already approved ([`removal_hooks_approved`] — a read-only `Approvals`- /// check, no prompt): the picker can't prompt mid-render, so unapproved- /// project commands are skipped, never run. (A hook that *does* run still+ /// already approved ([`approved_removal_plan`] — a read-only `Approvals`+ /// filter, no prompt): the picker can't prompt mid-render, so unapproved+ /// project commands are dropped from the plan, never run. (A hook that+ /// *does* run still/// streams its own output to stderr, like any hook — a rough edge of/// removing inside the picker.) A `BranchOnly` result just deletes the/// branch if it's safe to.@@ -204,13 +206,12 @@ impl PickerCollector {..} => {let main_repo = Repository::at(main_path)?;- let verify =- removal_hooks_approved(&main_repo, main_path, worktree_path, approvals)?;+ let plan = approved_removal_plan(&main_repo, main_path, worktree_path, approvals)?;let mut announcer = HookAnnouncer::new(&main_repo, main_repo.user_config(), false);handle_remove_output(result,/* foreground */ true,- verify,+ &plan,/* quiet */ true,/* silent */ true,&mut announcer,@@ -362,20 +363,37 @@ impl CommandCollector for PickerCollector {/// 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 removal_hooks_approved(+fn approved_removal_plan(main_repo: &Repository,main_path: &Path,worktree_path: &Path,approvals: &Approvals,-) -> anyhow::Result<bool> {- let commands = collect_remove_hook_commands(&[worktree_path], &[main_path])?;- if commands.is_empty() {- return Ok(true); // nothing to run — `verify` is moot- }- let project_id = main_repo.project_identifier()?;- Ok(commands- .iter()- .all(|c| approvals.is_command_approved(&project_id, &c.command.template)))+) -> anyhow::Result<ApprovedHookPlan> {+ // 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 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 mut builder = HookPlanBuilder::new();+ builder.add(+ worktree_path,+ &[HookType::PreRemove, HookType::PostRemove],+ removed_cfg.as_ref(),+ user,+ pid,+ );+ builder.add(+ main_path,+ &[HookType::PostSwitch],+ dest_cfg.as_ref(),+ user,+ pid,+ );+ Ok(builder.finish().approve_readonly(approvals, pid))}pub fn handle_picker(@@ -537,8 +555,8 @@ pub fn handle_picker(// Cleaned up in PreviewState::Drop.let signal_path = state.path.with_extension("remove");- // Approvals snapshot for the session — alt-r removals consult it (read-only)- // to decide whether their hooks may run; see `removal_hooks_approved`.+ // Approvals snapshot for the session: alt-r removals consult it read-only+ // to filter the hook plan; see `approved_removal_plan`.let approvals = Arc::new(Approvals::load().context("Failed to load approvals")?);let collector = PickerCollector {@@ -803,7 +821,7 @@ pub fn handle_picker(// new/destination worktree's, or for `--create` the base ref's) so the// approval prompt lists the exact commands `execute_switch` will run.let hook_project_config = switch_hook_project_config(&repo, &plan)?;- let hooks_approved = approve_switch_hooks(+ let (hooks_approved, hook_plan) = approve_switch_hooks(&repo,&config,&plan,@@ -826,7 +844,8 @@ pub fn handle_picker(hook_project_config.as_ref(),)?;- let (result, branch_info) = execute_switch(&repo, plan, &config, false, hooks_approved)?;+ let (result, branch_info) =+ execute_switch(&repo, plan, &config, false, hooks_approved, &hook_plan)?;// Compute path mismatch lazily (deferred from plan_switch for existing worktrees).// Skip for detached HEAD worktrees (branch is None).@@ -865,6 +884,7 @@ pub fn handle_picker(false,&extra_vars,hooks_display_path.as_deref(),+ &hook_plan,)?;}}@@ -906,10 +926,7 @@ fn resolve_identifier(#[cfg(test)]pub mod tests {use super::preview::{PreviewLayout, PreviewMode, PreviewStateData};- use super::{- PickerAction, PickerCollector, drain_stashed_warnings, removal_hooks_approved,- resolve_identifier,- };+ use super::{PickerAction, PickerCollector, drain_stashed_warnings, resolve_identifier};use crate::commands::worktree::RemoveResult;use std::fs;use std::sync::Mutex;@@ -1031,7 +1048,6 @@ pub mod tests {force_worktree: false,expected_path: None,removed_commit: None,- removed_project_config: None,};PickerCollector::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -1128,7 +1144,6 @@ pub mod tests {force_worktree: false,expected_path: None,removed_commit: None,- removed_project_config: None,};PickerCollector::do_removal(&repo, &result, &Approvals::default()).unwrap();@@ -1175,16 +1190,11 @@ pub mod tests {force_worktree: false,expected_path: None,removed_commit: None,- removed_project_config: None,};- // Empty approvals → the hook is unapproved.+ // Empty approvals → `approve_readonly` drops the unapproved project+ // `pre-remove` pipeline from the plan, so it never runs.let approvals = Approvals::default();- assert!(- !removal_hooks_approved(&repo, test.path(), &wt_path, &approvals).unwrap(),- "an unapproved pre-remove hook is not approved"- );-PickerCollector::do_removal(&repo, &result, &approvals).unwrap();assert!(!wt_path.exists(), "worktree should be removed");assert!(!marker.exists(), "unapproved pre-remove hook must not run");diff --git a/src/commands/project_config.rs b/src/commands/project_config.rsindex 40a23769b..099e29d38 100644--- a/src/commands/project_config.rs+++ b/src/commands/project_config.rs@@ -1,9 +1,7 @@-use std::collections::HashSet;use std::fmt;-use std::path::Path;use worktrunk::config::{Command, ProjectConfig};-use worktrunk::git::{HookType, Repository};+use worktrunk::git::HookType;/// What triggered a project command — determines the label in approval prompts.#[derive(Clone)]@@ -63,71 +61,6 @@ pub fn collect_commands_for_hooks(commands}-/// Collect the project commands that run as part of removing a set of worktrees.-///-/// Each `pre-remove` and `post-remove` reads the removed worktree's own-/// `.config/wt.toml` — both hooks are *about* that worktree, and at approval-/// time it's still on disk. `post-switch` reads the destination worktree's-/// config — the post-removal working directory the user lands in, which-/// `prepare_worktree_removal` records as [`super::worktree::RemoveResult`]'s-/// `main_path` (the primary worktree, except cwd when the primary worktree is-/// itself being removed; the merge destination for `wt merge`). Pass those-/// `destination_path()`s in — the gate must read the same config the executor-/// will (`output::handlers::spawn_hooks_after_remove`).-///-/// No fallback to another worktree's config, mirroring the executors-/// (`output::handlers::execute_pre_remove_hooks_if_needed` and the-/// `post-remove` snapshot path in `spawn_hooks_after_remove`). A-/// present-but-malformed worktree config surfaces as an error so the user-/// fixes it rather than silently running a different one.-///-/// Templates are deduped so the approval prompt shows each command once — so-/// `destination_paths` may contain duplicates (the common case: every removal-/// lands in the same primary worktree).-///-/// Callers feed the result into [`super::command_approval::approve_command_batch`].-/// `wt merge` prepends its own `pre-commit` / `post-commit` / `pre-merge` /-/// `post-merge` commands to the same batch; `wt remove` and `wt step prune`-/// approve the helper's output on its own.-pub fn collect_remove_hook_commands(- removed_worktree_paths: &[&Path],- destination_paths: &[&Path],-) -> anyhow::Result<Vec<ApprovableCommand>> {- let mut commands: Vec<ApprovableCommand> = Vec::new();-- for &wt_path in removed_worktree_paths {- // A `Repository::at` failure means git can't recognize the path as a- // worktree — propagate rather than silently fall back. See #2708.- let wt_repo = Repository::at(wt_path)?;- if let Some(cfg) = wt_repo.load_project_config()? {- commands.extend(collect_commands_for_hooks(- &cfg,- &[HookType::PreRemove, HookType::PostRemove],- ));- }- }-- // `destination_paths` is usually one worktree repeated (every removal lands- // in the same primary) — read each one's config at most once.- let mut seen_dests: HashSet<&Path> = HashSet::new();- for &dest_path in destination_paths {- if !seen_dests.insert(dest_path) {- continue;- }- // Propagate a `Repository::at` failure rather than silently skipping- // — same as the removed-worktree loop above. See #2708.- let dest_repo = Repository::at(dest_path)?;- if let Some(cfg) = dest_repo.load_project_config()? {- commands.extend(collect_commands_for_hooks(&cfg, &[HookType::PostSwitch]));- }- }-- let mut seen = HashSet::new();- commands.retain(|cmd| seen.insert(cmd.command.template.clone()));-- Ok(commands)-}-/// Collect commands for every project-config alias, in `BTreeMap` (alphabetical) order.////// Mirrors `approve_alias_commands` in `command_approval.rs`: unnamed steps withindiff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 2fe61047a..977ca0d14 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -318,26 +318,10 @@ impl RepositoryCliExt for Repository {.ok().map(|s| s.trim().to_string());- // Snapshot the removed worktree's `.config/wt.toml` before removal so- // `post-remove` can read it after the directory is gone. `pre-remove`- // runs against the same config from disk; both hooks are *about* the- // removed worktree — see the spec in `commands::hooks`.- //- // A parse failure here is intentionally not propagated: the executor- // (`output::handlers::execute_pre_remove_hooks_if_needed`) re-reads- // the config from disk and surfaces the parse error with its full- // chain via `print_command_error`. `pre-remove` aborts before- // `post-remove` fires, so the snapshot being `None` in the malformed- // case is invisible to the user. Routing the parse error through- // `prepare_worktree_removal` instead would land it in `main.rs`'s- // `record_error`, which renders only the top message — a pre-existing- // display gap orthogonal to this work.- let removed_project_config = Repository::at(&worktree_path)?- .load_project_config()- .ok()- .flatten()- .map(Box::new);-+ // 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.Ok(RemoveResult::RemovedWorktree {main_path,worktree_path,@@ -349,7 +333,6 @@ impl RepositoryCliExt for Repository {force_worktree,expected_path,removed_commit,- removed_project_config,})}diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex 44b6473b8..e939d2d32 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -10,13 +10,13 @@ use anyhow::Context;use color_print::cformat;use crossbeam_channel as chan;use rayon::prelude::*;-use worktrunk::config::{Approvals, UserConfig};+use worktrunk::HookType;+use worktrunk::config::UserConfig;use worktrunk::git::{BranchDeletionMode, RefSnapshot, Repository, WorktreeInfo};use worktrunk::styling::{eprintln, hint_message, info_message, println, success_message};-use super::super::command_approval::approve_command_batch;+use super::super::hook_plan::{ApprovedHookPlan, HookPlanBuilder};use super::super::hooks::HookAnnouncer;-use super::super::project_config::collect_remove_hook_commands;use super::super::repository_ext::{RemoveTarget, RepositoryCliExt};use crate::output::handle_remove_output;@@ -140,7 +140,7 @@ fn try_remove(repo: &Repository,config: &UserConfig,foreground: bool,- run_hooks: bool,+ hook_plan: &ApprovedHookPlan,worktrees: &[WorktreeInfo],snapshot: &RefSnapshot,check_lock: &RwLock<()>,@@ -196,7 +196,7 @@ fn try_remove(}};let mut announcer = HookAnnouncer::new(repo, config, true);- handle_remove_output(&plan, foreground, run_hooks, true, false, &mut announcer)?;+ handle_remove_output(&plan, foreground, hook_plan, true, false, &mut announcer)?;announcer.flush()?;Ok(true)}@@ -400,27 +400,32 @@ fn render_dry_run(Ok(())}-/// Approve the project commands `wt step prune` may run, mirroring the-/// executors' `.config/wt.toml` resolution via-/// [`collect_remove_hook_commands`].+/// Build and approve, once, the frozen hook plan `wt step prune` may run.////// `pre-remove` runs only when a *live linked* worktree is removed (stale-/// metadata and orphan-branch removals delete just the branch — no/// `pre-remove`/`post-remove`/`post-switch`). The integration checks haven't-/// run yet, so every linked worktree is fed to the helper — its `pre-remove`-/// approval is a superset of what executes. `post-switch` resolves from the-/// primary worktree's config: a prune candidate is never the primary worktree,-/// so each removal's `RemoveResult::destination_path()` is `home_path()`. No-/// fallback between worktrees — each `.config/wt.toml` stands alone.+/// run yet, so every linked worktree is fed to the plan — its `pre-remove`+/// 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.///-/// Returns `true` when hooks should run, `false` when the user declined.+/// A declined prompt yields an empty plan — every executor runs no hooks.fn approve_prune_hooks(repo: &Repository,+ config: &UserConfig,worktrees: &[WorktreeInfo],check_items: &[CheckItem],yes: bool,-) -> anyhow::Result<bool> {+) -> anyhow::Result<ApprovedHookPlan> {let primary_path = repo.home_path()?;+ // Non-fatal: prune candidates with no project hooks must still prune even+ // when the project identifier can't be resolved (the plan ends up empty+ // and `approve` never needs it).+ let project_id = repo.project_identifier().ok();+ let pid = project_id.as_deref();let removed_worktree_paths: Vec<&Path> = check_items.iter()@@ -429,23 +434,37 @@ fn approve_prune_hooks(_ => None,}).collect();- let all_commands =- collect_remove_hook_commands(&removed_worktree_paths, &[primary_path.as_path()])?;- if all_commands.is_empty() {- return Ok(true);+ 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(),+ config,+ pid,+ );}+ let primary_cfg = Repository::at(&primary_path)?.load_project_config()?;+ builder.add(+ &primary_path,+ &[HookType::PostSwitch],+ primary_cfg.as_ref(),+ config,+ pid,+ );- let project_id = repo.project_identifier()?;- let approvals = Approvals::load().context("Failed to load approvals")?;- let approved = approve_command_batch(&all_commands, &project_id, &approvals, yes, false)?;- if !approved {- eprintln!(- "{}",- info_message("Commands declined, continuing removal without hooks")- );+ match builder.finish().approve(pid, yes)? {+ Some(plan) => Ok(plan),+ None => {+ eprintln!(+ "{}",+ info_message("Commands declined, continuing removal without hooks")+ );+ Ok(ApprovedHookPlan::empty())+ }}- Ok(approved)}/// Remove worktrees and branches integrated into the default branch.@@ -496,11 +515,12 @@ pub fn step_prune(// the actually-pruned set.let check_items = gather_check_items(&repo, worktrees, default_branch.as_deref())?;- // For non-dry-run, approve hooks upfront so we can remove inline.- let run_hooks = if dry_run {- false // unused in dry-run path+ // For non-dry-run, build & approve the frozen hook plan upfront so we can+ // remove inline. Dry-run runs no hooks → empty plan.+ let hook_plan = if dry_run {+ ApprovedHookPlan::empty()} else {- approve_prune_hooks(&repo, worktrees, &check_items, yes)?+ approve_prune_hooks(&repo, &config, worktrees, &check_items, yes)?};let mut removed: Vec<Candidate> = Vec::new();@@ -640,7 +660,7 @@ pub fn step_prune(&repo,&config,foreground,- run_hooks,+ &hook_plan,worktrees,&snapshot_arc,&check_lock,@@ -696,7 +716,7 @@ pub fn step_prune(&repo,&config,foreground,- run_hooks,+ &hook_plan,worktrees,&snapshot_arc,&check_lock,@@ -718,7 +738,7 @@ pub fn step_prune(&repo,&config,foreground,- run_hooks,+ &hook_plan,worktrees,&snapshot_arc,&check_lock,diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rsindex 255c762a8..6c9ac0aa2 100644--- a/src/commands/worktree/finish.rs+++ b/src/commands/worktree/finish.rs@@ -31,6 +31,7 @@ use super::resolve::path_mismatch;use super::types::RemoveResult;use crate::commands::command_executor::CommandContext;use crate::commands::context::CommandEnv;+use crate::commands::hook_plan::{ApprovedHookPlan, register_planned};use crate::commands::hooks::HookAnnouncer;use crate::commands::repository_ext::{check_not_default_branch, compute_integration_reason, is_primary_worktree,@@ -47,6 +48,9 @@ pub struct FinishAfterMergeArgs<'a> {pub remove: bool,pub verify: bool,pub yes: bool,+ /// The frozen, approved hook plan. `post-merge` and the removal's+ /// `pre-remove` / `post-remove` / `post-switch` execute only from this.+ pub plan: &'a ApprovedHookPlan,}/// Run the post-merge finish sequence: capture feature identity, optionally@@ -71,6 +75,7 @@ pub fn finish_after_merge(remove,verify,yes,+ plan,} = args;let on_target = current_branch == target_branch;@@ -140,16 +145,9 @@ pub fn finish_after_merge();let expected_path = path_mismatch(repo, current_branch, &worktree_root, config);- // Snapshot the feature worktree's `.config/wt.toml` before removal so- // `post-remove` can read it after the directory is gone — same- // mechanism as `prepare_worktree_removal`. The repo is already rooted- // at the feature worktree (`current_wt`), so `load_project_config`- // reads from there. Parse errors propagate here because they'd abort- // `wt merge` upfront (no removal happens yet, so the executor's- // re-read path that handles them on the `wt remove` side isn't- // reachable from this call).- let removed_project_config = repo.load_project_config()?.map(Box::new);-+ // 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`.let remove_result = RemoveResult::RemovedWorktree {main_path: destination_path.clone(),worktree_path: worktree_root,@@ -161,20 +159,17 @@ pub fn finish_after_merge(force_worktree: false,expected_path,removed_commit: feature_commit.clone(),- removed_project_config,};- handle_remove_output(&remove_result, false, verify, false, false, announcer)?;+ handle_remove_output(&remove_result, false, plan, false, false, announcer)?;true};if verify {- // 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.- // No fallback to `repo`: if the destination has no `.config/wt.toml`,- // no project `post-merge` runs.+ // Post-merge hooks run in the destination worktree (target). `ctx.repo`+ // is rooted there only for template *rendering* (the feature worktree+ // may be gone); the command set is the frozen `plan`, anchored at+ // `destination_path` at the gate — no re-read of the destination's+ // (now post-merge) `.config/wt.toml`.let dest_repo = Repository::at(&destination_path)?;let ctx = CommandContext::new(&dest_repo,@@ -193,7 +188,10 @@ pub fn finish_after_merge(if let Some(p) = target_worktree_path {vars = vars.with_target_worktree_path(p);}- announcer.register(+ register_planned(+ announcer,+ plan,+ &destination_path,&ctx,HookType::PostMerge,&vars.as_extra_vars(),diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex 53fc2dfa2..eab5de865 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -11,18 +11,25 @@ use worktrunk::path::to_posix_path;use crate::commands::command_executor::CommandContext;use crate::commands::command_executor::FailureStrategy;-use crate::commands::hooks::execute_hook;+use crate::commands::hook_plan::{ApprovedHookPlan, execute_planned_hook};impl<'a> CommandContext<'a> {- /// Execute pre-start commands sequentially (blocking)+ /// Execute pre-start commands sequentially (blocking) from the frozen plan.///- /// Runs user hooks first, then project hooks.- /// Shows path in hook announcements when shell integration isn't active (user's shell- /// won't cd to the new worktree, so they need to know where hooks ran).- ///- /// `extra_vars`: Additional template variables (e.g., `base`, `base_worktree_path`).- pub fn execute_pre_start_commands(&self, extra_vars: &[(&str, &str)]) -> anyhow::Result<()> {- execute_hook(+ /// 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.+ /// 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_start_commands(+ &self,+ extra_vars: &[(&str, &str)],+ plan: &ApprovedHookPlan,+ anchor: &Path,+ ) -> anyhow::Result<()> {+ execute_planned_hook(+ plan,+ anchor,self,HookType::PreStart,extra_vars,diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 9d3b212ba..22ce57377 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -34,9 +34,10 @@ use super::resolve::{};use super::types::{CreationMethod, SwitchBranchInfo, SwitchPlan, SwitchResult};use crate::cli::SwitchFormat;-use crate::commands::command_approval::{approve_hooks, approve_or_skip_with_config};+use crate::commands::command_approval::approve_hooks;use crate::commands::command_executor::FailureStrategy;use crate::commands::command_executor::{CommandContext, build_hook_context};+use crate::commands::hook_plan::{ApprovedHookPlan, HookPlanBuilder, register_planned};use crate::commands::hooks::{HookAnnouncer, execute_hook};use crate::commands::template_vars::TemplateVars;use crate::output::{@@ -857,6 +858,7 @@ pub fn execute_switch(config: &UserConfig,force: bool,run_hooks: bool,+ hook_plan: &ApprovedHookPlan,) -> anyhow::Result<(SwitchResult, SwitchBranchInfo)> {match plan {SwitchPlan::Existing {@@ -1137,7 +1139,7 @@ pub fn execute_switch(vars = vars.with_pr(Some(*number), Some(ref_url));}}- ctx.execute_pre_start_commands(&vars.as_extra_vars())?;+ ctx.execute_pre_start_commands(&vars.as_extra_vars(), hook_plan, &worktree_path)?;}// Record successful switch in history@@ -1429,8 +1431,9 @@ fn hook_repo_for_worktree(worktree_path: &Path) -> anyhow::Result<Repository> {/// prompt listing the exact commands `execute_switch` will run, including for/// `wt switch pr:N` against a fork's hooks.///-/// Returns `true` if hooks are approved to run.-/// Returns `false` if hooks should be skipped (`!verify` or user declined).+/// Returns `(hooks_approved, plan)`. `hooks_approved` is `false` and the plan+/// empty when `!verify` or the user declined; the covered switch hooks+/// (`pre-start` / `post-start` / `post-switch`) execute only from `plan`.pub(crate) fn approve_switch_hooks(repo: &Repository,config: &UserConfig,@@ -1438,23 +1441,36 @@ pub(crate) fn approve_switch_hooks(yes: bool,verify: bool,project_config: Option<&ProjectConfig>,-) -> anyhow::Result<bool> {+) -> anyhow::Result<(bool, ApprovedHookPlan)> {if !verify {- return Ok(false);+ return Ok((false, ApprovedHookPlan::empty()));}- let ctx = CommandContext::new(repo, config, plan.branch(), plan.worktree_path(), yes);- let on_decline = if plan.is_create() {- "Commands declined, continuing worktree creation without hooks"- } else {- "Commands declined, switching without hooks"- };- approve_or_skip_with_config(- &ctx,- project_config,+ // Non-fatal: a destination with no project hooks must still switch even+ // when the project identifier can't be resolved (the plan ends up empty+ // and `approve` never needs it).+ let project_id = repo.project_identifier().ok();+ let pid = project_id.as_deref();+ let mut builder = HookPlanBuilder::new();+ builder.add(+ plan.worktree_path(),switch_post_hook_types(plan.is_create()),- on_decline,- )+ project_config,+ config,+ pid,+ );+ match builder.finish().approve(pid, yes)? {+ Some(approved) => Ok((true, approved)),+ None => {+ let on_decline = if plan.is_create() {+ "Commands declined, continuing worktree creation without hooks"+ } else {+ "Commands declined, switching without hooks"+ };+ eprintln!("{}", info_message(on_decline));+ Ok((false, ApprovedHookPlan::empty()))+ }+ }}/// Spawn post-switch (and post-start for creates) background hooks.@@ -1465,17 +1481,36 @@ pub(crate) fn spawn_switch_background_hooks(yes: bool,extra_vars: &[(&str, &str)],hooks_display_path: Option<&Path>,+ hook_plan: &ApprovedHookPlan,) -> anyhow::Result<()> {- // Background hooks run in the new/destination worktree and resolve their- // `.config/wt.toml` from there. No fallback — if the worktree has no- // `.config/wt.toml`, no project hooks fire.+ // 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())?;let ctx = CommandContext::new(&hook_repo, config, branch, result.path(), yes);let mut announcer = HookAnnouncer::new(&hook_repo, config, false);- announcer.register(&ctx, HookType::PostSwitch, extra_vars, hooks_display_path)?;+ register_planned(+ &mut announcer,+ hook_plan,+ result.path(),+ &ctx,+ HookType::PostSwitch,+ extra_vars,+ hooks_display_path,+ )?;if matches!(result, SwitchResult::Created { .. }) {- announcer.register(&ctx, HookType::PostStart, extra_vars, hooks_display_path)?;+ register_planned(+ &mut announcer,+ hook_plan,+ result.path(),+ &ctx,+ HookType::PostStart,+ extra_vars,+ hooks_display_path,+ )?;}announcer.flush()}@@ -1589,7 +1624,7 @@ pub fn run_switch(// "Approve at the Gate": collect and approve hooks upfront// This ensures approval happens once at the command entry point// If user declines, skip hooks but continue with worktree operation- let hooks_approved = approve_switch_hooks(+ let (hooks_approved, hook_plan) = approve_switch_hooks(&repo,config,&plan,@@ -1616,7 +1651,8 @@ pub fn run_switch(let (source_branch, source_path) = capture_switch_source(&repo, is_recovered);// Execute the validated plan- let (result, branch_info) = execute_switch(&repo, plan, config, yes, hooks_approved)?;+ let (result, branch_info) =+ execute_switch(&repo, plan, config, yes, hooks_approved, &hook_plan)?;// --format=json: write structured result to stdout. All behavior (hooks,// --execute, shell integration) proceeds normally — format only affects output.@@ -1692,6 +1728,7 @@ pub fn run_switch(yes,&extra_vars,hooks_display_path.as_deref(),+ &hook_plan,)?;}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 5c3a781c2..fac5558bb 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -4,7 +4,6 @@use std::path::{Path, PathBuf};-use worktrunk::config::ProjectConfig;use worktrunk::git::{BranchDeletionMode, RefType};/// Flags indicating which merge operations occurred@@ -139,14 +138,6 @@ impl SwitchPlan {}}- /// Get the branch name for this plan. `None` for detached HEAD worktrees.- pub fn branch(&self) -> Option<&str> {- match self {- SwitchPlan::Existing { branch, .. } => branch.as_deref(),- SwitchPlan::Create { branch, .. } => Some(branch),- }- }-/// Returns true if this plan will create a new worktree.pub fn is_create(&self) -> bool {matches!(self, SwitchPlan::Create { .. })@@ -183,16 +174,6 @@ pub enum RemoveResult {/// Used for post-remove hook template variables so they reference the/// removed worktree's state, not the execution context.removed_commit: Option<String>,- /// The removed worktree's `.config/wt.toml`, snapshotted before- /// deletion. `pre-remove` reads it on disk (the worktree is still- /// there); `post-remove` reads this snapshot (the worktree is gone by- /// then). `None` when the removed worktree had no `.config/wt.toml`.- /// Both hooks are *about* the removed worktree — see the spec in- /// `commands::hooks` "Which `.config/wt.toml` a hook reads".- ///- /// Boxed because `ProjectConfig` is ~600 bytes and would otherwise- /// dominate the variant size (clippy `large_enum_variant`).- removed_project_config: Option<Box<ProjectConfig>>,},/// Branch exists but has no worktree - attempt branch deletion only.///@@ -379,7 +360,6 @@ mod tests {force_worktree: false,expected_path: None,removed_commit: Some("abc1234567890".to_string()),- removed_project_config: None,};match result {RemoveResult::RemovedWorktree {@@ -393,7 +373,6 @@ mod tests {force_worktree,expected_path,removed_commit,- removed_project_config: _,} => {assert_eq!(main_path.to_str().unwrap(), "/main");assert_eq!(worktree_path.to_str().unwrap(), "/worktree");@@ -479,7 +458,6 @@ mod tests {force_worktree: true,expected_path: None,removed_commit: None, // Detached HEAD may not have meaningful commit- removed_project_config: None,};match result {RemoveResult::RemovedWorktree {diff --git a/src/main.rs b/src/main.rsindex 4af402bf5..5711e6188 100644--- a/src/main.rs+++ b/src/main.rs@@ -7,7 +7,7 @@ use clap::FromArgMatches;use clap::error::ErrorKind as ClapErrorKind;use color_print::{ceprintln, cformat};use std::process;-use worktrunk::config::{Approvals, UserConfig, set_config_path};+use worktrunk::config::{UserConfig, set_config_path};use worktrunk::git::{ErrorExt, Repository, ResolvedWorktree, WorktrunkError, current_or_recover, cwd_removed_hint,set_base_path,@@ -16,10 +16,10 @@ use worktrunk::styling::{eprintln, error_message, format_with_gutter, hint_message, info_message, warning_message,};-use commands::command_approval::approve_command_batch;+use commands::hook_plan::{ApprovedHookPlan, HookPlanBuilder};use commands::hooks::HookAnnouncer;-use commands::project_config::collect_remove_hook_commands;use commands::worktree::RemoveResult;+use worktrunk::HookType;mod cli;mod commands;@@ -901,37 +901,58 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {.into());}- // Helper: approve every command the removal will run, in one batch.- // `pre-remove` / `post-remove` resolve their `.config/wt.toml` from- // each worktree being removed (`removed_worktree_paths`); `post-switch`- // resolves from each removal's post-removal destination- // (`destination_paths` — `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. The shared helper assembles them all, dedup'd by template.- // Returns `true` when the prompt was accepted or there was nothing to- // approve.- let approve_remove =- |removed_worktree_paths: &[&Path], destination_paths: &[&Path], yes: bool| -> anyhow::Result<bool> {- let commands = collect_remove_hook_commands(- removed_worktree_paths,- destination_paths,- )?;- if commands.is_empty() {- return Ok(true);+ // 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.+ let approve_remove = |removed_worktree_paths: &[&Path],+ destination_paths: &[&Path],+ yes: bool|+ -> anyhow::Result<ApprovedHookPlan> {+ if !verify {+ return Ok(ApprovedHookPlan::empty());+ }+ // Non-fatal: a worktree with no project hooks must remove even+ // when the project identifier can't be resolved (the plan ends+ // up empty and `approve` never needs it). Matches the pre-plan+ // behaviour where the empty-batch fast path ran first.+ let project_id = repo.project_identifier().ok();+ let pid = project_id.as_deref();+ 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(),+ &config,+ pid,+ );+ }+ let mut seen_dests = std::collections::HashSet::new();+ for &dest in destination_paths {+ if !seen_dests.insert(dest) {+ continue;}- let project_id = repo.project_identifier()?;- let approvals = Approvals::load().context("Failed to load approvals")?;- let approved =- approve_command_batch(&commands, &project_id, &approvals, yes, false)?;- if !approved {+ let cfg = Repository::at(dest)?.load_project_config()?;+ builder.add(dest, &[HookType::PostSwitch], cfg.as_ref(), &config, pid);+ }+ match builder.finish().approve(pid, yes)? {+ Some(plan) => Ok(plan),+ None => {eprintln!("{}",info_message("Commands declined, continuing removal without hooks"));+ Ok(ApprovedHookPlan::empty())}- Ok(approved)- };+ }+ };let branches = args.branches;@@ -955,18 +976,17 @@ 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(- result.removed_worktree_path().as_slice(),- result.destination_path().as_slice(),- yes,- )?;+ let plan = approve_remove(+ result.removed_worktree_path().as_slice(),+ result.destination_path().as_slice(),+ yes,+ )?;let mut announcer = HookAnnouncer::new(&repo, &config, false);handle_remove_output(&result,args.foreground,- run_hooks,+ &plan,false,false,&mut announcer,@@ -1018,8 +1038,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {all_plans().filter_map(|r| r.removed_worktree_path()).collect();let destination_targets: Vec<&Path> =all_plans().filter_map(|r| r.destination_path()).collect();- let run_hooks =- verify && approve_remove(&removed_targets, &destination_targets, yes)?;+ let plan = approve_remove(&removed_targets, &destination_targets, yes)?;// Execute all validated plans: others first, branch-only next, current lastlet show_branch =@@ -1029,7 +1048,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {handle_remove_output(result,args.foreground,- run_hooks,+ &plan,false,false,&mut announcer,diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex ebb512fd1..87beaf5b9 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -11,13 +11,14 @@ use worktrunk::styling::{eprint, format_bash_with_gutter, stderr};use crate::commands::command_executor::CommandContext;use crate::commands::command_executor::FailureStrategy;-use crate::commands::hooks::{HookAnnouncer, execute_hook};+use crate::commands::hook_plan::{ApprovedHookPlan, execute_planned_hook, register_planned};+use crate::commands::hooks::HookAnnouncer;use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};use crate::commands::worktree::hooks::PostRemoveContext;use crate::commands::worktree::{RemoveResult, SwitchBranchInfo, SwitchResult};-use worktrunk::config::{ProjectConfig, UserConfig};+use worktrunk::config::UserConfig;use worktrunk::git::ErrorExt;use worktrunk::git::GitError;use worktrunk::git::IntegrationReason;@@ -732,19 +733,24 @@ pub fn execute_user_command(command: &str, display_path: Option<&Path>) -> anyho/// When `quiet` is true (prune context), suppresses informational messages/// like "No worktree found for branch X" that are noise in batch operations.///+/// `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.+////// When `silent` is true (the TUI picker — this runs while skim owns the/// terminal), a `RemovedWorktree` result is removed with no progress/success/// messages, no trash-cleanup spinner, and no `cd` directive: just the git-/// removal plus the usual `verify`-gated `pre-remove` / `post-remove` /-/// `post-switch` hooks. (The picker can't prompt for approval mid-render, so it-/// passes `verify` from a read-only `Approvals` check — see `do_removal`.) The-/// removal runs inline regardless of `foreground` (there's no detached `rm` to-/// background to). `silent` has no effect on `BranchOnly` results — the picker-/// handles that arm itself.+/// removal plus the planned `pre-remove` / `post-remove` / `post-switch`+/// hooks. (The picker can't prompt mid-render, so its `plan` comes from a+/// read-only `Approvals` filter — see `do_removal`.) The removal runs inline+/// regardless of `foreground` (there's no detached `rm` to background to).+/// `silent` has no effect on `BranchOnly` results — the picker handles that+/// arm itself.pub fn handle_remove_output(result: &RemoveResult,foreground: bool,- verify: bool,+ plan: &ApprovedHookPlan,quiet: bool,silent: bool,announcer: &mut HookAnnouncer<'_>,@@ -761,7 +767,6 @@ pub fn handle_remove_output(force_worktree,expected_path,removed_commit,- removed_project_config,} => handle_removed_worktree_output(RemovedWorktreeOutputContext {main_path,@@ -774,9 +779,8 @@ pub fn handle_remove_output(force_worktree: *force_worktree,expected_path: expected_path.as_deref(),removed_commit: removed_commit.as_deref(),- removed_project_config: removed_project_config.as_deref(),+ plan,foreground,- verify,silent,},announcer,@@ -908,9 +912,6 @@ fn spawn_hooks_after_remove(removed_branch: &str,announcer: &mut HookAnnouncer<'_>,) -> anyhow::Result<()> {- if !ctx.verify {- return Ok(());- }let Ok(config) = UserConfig::load() else {return Ok(());};@@ -934,26 +935,29 @@ fn spawn_hooks_after_remove(// branch since both post-remove and post-switch are consequences of that removal.let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);- // `post-remove` is *about* the removed worktree, so its project config- // comes from the snapshot taken before removal — the worktree itself is- // gone by now. `post-switch` is *about* the destination worktree (where- // the user landed), so its config loads from `remove_ctx` (rooted at- // `ctx.main_path`) the normal way.- announcer.register_with_project_config(+ // `post-remove` is *about* the removed worktree (gone by now); it was+ // selected and frozen into `plan` at the gate, anchored at the removed+ // worktree path. `remove_ctx` (rooted at `ctx.main_path`) only renders.+ register_planned(+ announcer,+ ctx.plan,+ ctx.worktree_path,&remove_ctx,- ctx.removed_project_config,worktrunk::HookType::PostRemove,&extra_vars,display_path,)?;- // Post-switch: only when the user actually changed directory.- // Uses its own context with the destination branch for template variables.+ // Post-switch: only when the user actually changed directory. Anchored at+ // the destination worktree (where the user landed) at the gate.if ctx.changed_directory {let dest_branch = repo.worktree_at(ctx.main_path).branch()?;let switch_ctx =CommandContext::new(repo, &config, dest_branch.as_deref(), ctx.main_path, false);- announcer.register(+ register_planned(+ announcer,+ ctx.plan,+ ctx.main_path,&switch_ctx,worktrunk::HookType::PostSwitch,&[],@@ -1186,12 +1190,11 @@ struct RemovedWorktreeOutputContext<'a> {force_worktree: bool,expected_path: Option<&'a Path>,removed_commit: Option<&'a str>,- /// The removed worktree's `.config/wt.toml`, snapshotted before removal.- /// Used by `post-remove` (the worktree is gone by the time it runs);- /// `pre-remove` reads the same file on disk via `Repository::at`.- removed_project_config: Option<&'a ProjectConfig>,+ /// The frozen, approved hook plan. `pre-remove` / `post-remove` /+ /// `post-switch` execute only from this — no `.config/wt.toml` re-read,+ /// no `ProjectConfig` snapshot to thread.+ plan: &'a ApprovedHookPlan,foreground: bool,- verify: bool,/// TUI (picker) path: do the git removal and hook registration but emit no/// progress/success messages, no trash-cleanup spinner, and no `cd`/// directive — see [`handle_remove_output`].@@ -1202,23 +1205,15 @@ fn execute_pre_remove_hooks_if_needed(repo: &Repository,ctx: &RemovedWorktreeOutputContext<'_>,) -> anyhow::Result<()> {- if !ctx.verify {- return Ok(());- }-let Ok(config) = UserConfig::load() else {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). No fallback to `repo`: if the removed worktree- // carries no `.config/wt.toml`, no project `pre-remove` runs. A- // present-but-malformed config surfaces as an error from- // `load_project_config`, which aborts removal. The `wt remove` approval- // helper in `main.rs` resolves the same config.+ // `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.let pre_remove_repo = Repository::at(ctx.worktree_path)?;let command_ctx = CommandContext::new(&pre_remove_repo,@@ -1244,7 +1239,9 @@ fn execute_pre_remove_hooks_if_needed(("target_worktree_path", &target_path_str),];- execute_hook(+ execute_planned_hook(+ ctx.plan,+ ctx.worktree_path,&command_ctx,worktrunk::HookType::PreRemove,&extra_vars,diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 85163e76e..fd7bb1d9c 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -3771,3 +3771,104 @@ fn test_merge_removes_branch_when_local_main_diverged_from_upstream("feature branch should be deleted after a clean merge");}++/// Approval-boundary TOCTOU regression: a `post-merge` command that exists only+/// in the *feature branch's* committed `.config/wt.toml` 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.+///+/// 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+/// post-merge, spawned by the same `announcer.flush()` before `wt merge`+/// returns) writes `control`. Observing `control` proves the post-merge+/// background runner has started and drained for this scenario on this+/// machine/load — the dominant CI-load failure mode (cold spawn under+/// llvm-cov) is then excluded, so the injected marker's absence is meaningful+/// rather than a fixed-timeout false negative. Sibling detached pipelines+/// (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),+) {+ let (repo, feature_wt) = merge_scenario;++ // Markers live at the repo root — they outlive the feature worktree, which+ // `wt merge` removes.+ let control = repo.root_path().join("post-merge-control-ran");+ let injected = repo.root_path().join("injected-post-merge-ran");++ // Positive control: a user-config `post-merge` (needs no approval, always+ // selected). Its marker landing is the causal bound for the assertion.+ repo.write_test_config(&format!(+ "[post-merge]\ncontrol = \"touch {}\"\n",+ 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"]);++ 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)+ );++ // 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_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}"+ );+}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex c481fcd27..329b24d9d 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -1851,10 +1851,11 @@ 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 (the shared `collect_remove_hook_commands` helper). 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`.+/// 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@@ -1895,6 +1896,44 @@ fn test_remove_no_fallback_to_primary_pre_remove(mut repo: TestRepo) {);}+/// 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:+/// the plan rewrite briefly loaded `Approvals` unconditionally).+#[rstest]+fn test_remove_no_project_hooks_ignores_malformed_approvals(mut repo: TestRepo) {+ let worktree_path = repo.add_worktree("feature-no-hooks");++ // No `.config/wt.toml` anywhere ⇒ the hook plan is empty. A broken+ // approvals file would only matter if there were a command to check.+ repo.write_test_approvals("this is not = = valid toml");++ let output = repo+ .wt_command()+ .args([+ "remove",+ "--foreground",+ "--force",+ "--yes",+ "feature-no-hooks",+ ])+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "remove with no project hooks must not parse approvals.toml; stderr:\n{stderr}"+ );+ assert!(+ !stderr.contains("Failed to parse approvals"),+ "approvals must not be loaded for an empty plan; stderr:\n{stderr}"+ );+ assert!(+ !worktree_path.exists(),+ "feature worktree should be removed"+ );+}+#[rstest]fn test_pre_remove_hook_failure_aborts(mut repo: TestRepo) {// Create project config with failing hook