Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(merge): gate commit-append separately so declining it keeps hooks (#2802)
Maximilian Roos7d09c5da586f
diff --git a/docs/content/hook.md b/docs/content/hook.mdindex 475832e23..8bc0fdb19 100644--- a/docs/content/hook.md+++ b/docs/content/hook.md@@ -61,6 +61,7 @@ Project commands require approval on first run:- Approvals are saved to `~/.config/worktrunk/approvals.toml`- If a command changes, new approval is required+- Declining skips every project command for that operation — including any already approved — and continues without them; saved approvals are unaffected- Use `--yes` to bypass prompts — useful for CI and automation- Use `--no-hooks` to skip hooksdiff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex 38fc0885e..07ba8454e 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -52,6 +52,7 @@ Project commands require approval on first run:- Approvals are saved to `~/.config/worktrunk/approvals.toml`- If a command changes, new approval is required+- Declining skips every project command for that operation — including any already approved — and continues without them; saved approvals are unaffected- Use `--yes` to bypass prompts — useful for CI and automation- Use `--no-hooks` to skip hooksdiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 4745682ec..bd8a9e852 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1250,6 +1250,7 @@ Project commands require approval on first run:- Approvals are saved to `~/.config/worktrunk/approvals.toml`- If a command changes, new approval is required+- Declining skips every project command for that operation — including any already approved — and continues without them; saved approvals are unaffected- Use `--yes` to bypass prompts — useful for CI and automation- Use `--no-hooks` to skip hooksdiff --git a/src/commands/commit.rs b/src/commands/commit.rsindex 228abdb7b..aafe720e4 100644--- a/src/commands/commit.rs+++ b/src/commands/commit.rs@@ -67,8 +67,8 @@ pub struct CommitOptions<'a> {pub warn_about_untracked: bool,pub show_no_squash_note: bool,/// Whether `commit()` runs its own guidance approval gate or trusts a- /// value supplied by the caller (`wt merge` bundles the guidance into- /// its hook-approval batch so the user sees one combined prompt).+ /// value supplied by the caller (`wt merge` resolves the guidance via+ /// `approve_commit_template_append` up front and passes it through).pub guidance: super::step::PreApprovedGuidance,}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 22108310a..74e26de6c 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -6,7 +6,7 @@ use worktrunk::config::{Approvals, MergeConfig, UserConfig};use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};-use super::command_approval::approve_command_batch;+use super::command_approval::{approve_command_batch, approve_commit_template_append};use super::command_executor::FailureStrategy;use super::commit::{CommitOptions, HookGate};use super::context::CommandEnv;@@ -215,7 +215,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let remove_requested = remove && !on_target;// Collect and approve all commands upfront for batch permission request- let (mut all_commands, project_id) = collect_merge_commands(+ let (all_commands, project_id) = collect_merge_commands(repo,&destination_path,commit,@@ -224,27 +224,9 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {squash_enabled,)?;- // Bundle commit guidance into the same batch as hooks so an LLM-bound- // merge produces one approval prompt, not two. Only when a commit will- // actually be created and an LLM is configured.- let will_create_commit = current_wt.is_dirty()? || squash_enabled;- let llm_configured = env- .config- .commit_generation(Some(&project_id))- .is_configured();- let project_append_text: Option<String> = if commit && will_create_commit && llm_configured {- env.repo- .load_project_config()?- .as_ref()- .and_then(|cfg| cfg.commit_template_append().map(str::to_string))- } else {- None- };- if let Some(ref g) = project_append_text {- all_commands.push(ApprovableCommand::commit_template_append(g.clone()));- }-- // Approve all commands in a single batch (shows templates, not expanded values)+ // 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)?;@@ -259,7 +241,10 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {let verify = if approved {verify} else {- eprintln!("{}", info_message("Commands declined, continuing merge"));+ eprintln!(+ "{}",+ info_message("Commands declined, continuing merge without hooks")+ );false};@@ -269,9 +254,20 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// the end.let mut announcer = HookAnnouncer::new(repo, config, false);- let guidance = super::step::PreApprovedGuidance::Resolved(- approved.then_some(project_append_text).flatten(),- );+ // The project commit-append is gated independently of hook approval:+ // declining it drops only the append, never the (possibly already-approved)+ // hooks. Mirrors the standalone `wt step commit` path via the shared gate.+ let will_create_commit = current_wt.is_dirty()? || squash_enabled;+ let llm_configured = env+ .config+ .commit_generation(Some(&project_id))+ .is_configured();+ let project_append = if commit && will_create_commit && llm_configured {+ approve_commit_template_append(&env.context(yes))?+ } else {+ None+ };+ let guidance = super::step::PreApprovedGuidance::Resolved(project_append);// Handle uncommitted changes (skip if --no-commit) - track whether commit occurredlet committed = if commit && current_wt.is_dirty()? {diff --git a/src/commands/step/prune.rs b/src/commands/step/prune.rsindex a35081c38..b043358ac 100644--- a/src/commands/step/prune.rs+++ b/src/commands/step/prune.rs@@ -421,7 +421,10 @@ fn approve_prune_hooks(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"));+ eprintln!(+ "{}",+ info_message("Commands declined, continuing removal without hooks")+ );}Ok(approved)}diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex 6a6709b28..cd5b54f06 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -24,9 +24,9 @@ use super::shared::print_dry_run;/// Caller's stance on project commit-message guidance approval.////// `wt step squash` runs its own gate (the user invokes squash directly, so-/// there's no upstream batch to attach to). `wt merge` bundles the append-/// into its hook-approval batch and passes the result here so the user-/// doesn't see a second prompt mid-flow.+/// there's no upstream decision to attach to). `wt merge` resolves the append+/// through its own `approve_commit_template_append` gate up front and passes+/// the result here so `handle_squash` doesn't gate it a second time.#[derive(Debug, Clone)]pub enum PreApprovedGuidance {/// No pre-approval — `handle_squash` runs its own gate viadiff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex fc55b6ce3..9d3b212ba 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1445,9 +1445,9 @@ pub(crate) fn approve_switch_hooks(let ctx = CommandContext::new(repo, config, plan.branch(), plan.worktree_path(), yes);let on_decline = if plan.is_create() {- "Commands declined, continuing worktree creation"+ "Commands declined, continuing worktree creation without hooks"} else {- "Commands declined"+ "Commands declined, switching without hooks"};approve_or_skip_with_config(&ctx,diff --git a/src/main.rs b/src/main.rsindex da0f7e668..5789e426e 100644--- a/src/main.rs+++ b/src/main.rs@@ -924,7 +924,10 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {let approved =approve_command_batch(&commands, &project_id, &approvals, yes, false)?;if !approved {- eprintln!("{}", info_message("Commands declined, continuing removal"));+ eprintln!(+ "{}",+ info_message("Commands declined, continuing removal without hooks")+ );}Ok(approved)};diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rsindex 2f93b08db..0090f9b54 100644--- a/tests/integration_tests/approval_pty.rs+++ b/tests/integration_tests/approval_pty.rs@@ -725,11 +725,11 @@ command = "tee {prompt_capture_str} > /dev/null && echo 'feat: decline guidance');}-/// `wt merge` with both project hooks and a commit append bundles the two-/// items into the same approval prompt — the user sees one prompt covering-/// both, not one for hooks and a second for the append mid-merge.+/// `wt merge` gates project hooks and the commit append as two independent+/// approvals: the hook batch first, then the append. Approving both lets the+/// hook run and the append reach the LLM.#[rstest]-fn test_merge_bundles_append_into_hook_approval(mut repo: TestRepo) {+fn test_merge_prompts_hooks_and_append_separately(mut repo: TestRepo) {repo.run_git(&["remote", "remove", "origin"]);repo.write_project_config(r#"@@ -755,7 +755,8 @@ command = "tee {prompt_capture_str} > /dev/null && echo 'feat: bundled'"let env_vars = test_env_vars_with_shell(&repo);- let (output, exit_code) = exec_wt_in_pty_cwd(&feature_wt, &["merge"], &env_vars, "y\n");+ // Hook batch prompts first, append prompts second — approve both.+ let (output, exit_code) = exec_wt_in_pty_cwd(&feature_wt, &["merge"], &env_vars, "y\ny\n");assert_eq!(exit_code, 0,@@ -763,17 +764,11 @@ command = "tee {prompt_capture_str} > /dev/null && echo 'feat: bundled'");assert!(output.contains("pre-commit hook"),- "Bundled prompt should list the pre-commit hook command. Output:\n{output}"+ "Hook prompt should list (and run) the pre-commit hook. Output:\n{output}");assert!(output.contains("commit-template-append") && output.contains("Reference the related issue"),- "Bundled prompt should list the commit append. Output:\n{output}"- );- // The downstream commit step must not present a second prompt.- let prompts = output.matches("Allow and remember?").count();- assert_eq!(- prompts, 1,- "Bundled approval should produce exactly one [y/N] prompt. Saw {prompts}. Output:\n{output}"+ "Append prompt should list the commit append. Output:\n{output}");let captured = std::fs::read_to_string(&prompt_capture).expect("captured prompt");@@ -783,6 +778,75 @@ command = "tee {prompt_capture_str} > /dev/null && echo 'feat: bundled'");}+/// Regression: declining the project commit append must NOT skip+/// already-approved hooks. With the hook approved up front, the only prompt is+/// the append; declining it drops the append while the pre-commit hook still+/// runs and the merge succeeds.+#[rstest]+fn test_merge_decline_append_keeps_approved_hooks(mut repo: TestRepo) {+ repo.run_git(&["remote", "remove", "origin"]);++ // Step 1: project config with only the hook; pre-approve it.+ repo.write_project_config(r#"pre-commit = "echo 'pre-commit hook'""#);+ repo.commit("Add pre-commit hook");++ let env_vars = test_env_vars_with_shell(&repo);+ let (add_out, add_exit) =+ exec_wt_in_pty(&repo, &["config", "approvals", "add"], &env_vars, "y\n");+ assert_eq!(+ add_exit, 0,+ "Pre-approving the hook should succeed. Output:\n{add_out}"+ );++ // Step 2: add an unapproved commit append (hook command unchanged, so it+ // stays approved).+ repo.write_project_config(+ r#"pre-commit = "echo 'pre-commit hook'"++[commit.generation]+template-append = "Reference the related issue"+"#,+ );+ repo.commit("Add commit append");++ let feature_wt = repo.add_worktree("feature-decline-append");+ std::fs::write(feature_wt.join("new-file.txt"), "new content").unwrap();++ let prompt_capture = repo.root_path().join("captured-prompt.txt");+ let prompt_capture_str = prompt_capture.display().to_string();+ repo.write_test_config(&format!(+ r#"+[commit.generation]+command = "tee {prompt_capture_str} > /dev/null && echo 'feat: decline append'"+"#+ ));++ // Hook is already approved → no hook prompt. The lone prompt is the+ // append; decline it.+ let (output, exit_code) = exec_wt_in_pty_cwd(&feature_wt, &["merge"], &env_vars, "n\n");++ assert_eq!(+ exit_code, 0,+ "Merge should succeed when only the append is declined. Output:\n{output}"+ );+ assert!(+ output.contains("Project commit guidance declined"),+ "Declining the append should be announced. Output:\n{output}"+ );+ assert!(+ output.contains("pre-commit hook"),+ "Already-approved pre-commit hook must still run when the append is \+ declined. Output:\n{output}"+ );++ let captured = std::fs::read_to_string(&prompt_capture).expect("captured prompt");+ assert!(+ !captured.contains("<project-guidance>")+ && !captured.contains("Reference the related issue"),+ "Declined append must not reach the LLM. Captured:\n{captured}"+ );+}+/// `wt config approvals add` accepts the prompt — covers the success branch of/// `add_approvals` after `approve_command_batch` returns Ok(true).#[rstest]diff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snapindex 3c9e12776..8b92d8238 100644--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_decline.snap@@ -7,7 +7,7 @@ expression: "&output"[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'test command'[0m[2m[36m❯[39m [36mAllow and remember? [1m[y/N][22m[39m n-[2m○[22m Commands declined, continuing worktree creation+[2m○[22m Commands declined, continuing worktree creation without hooks[32m✓[39m [32mCreated branch [1mtest-decline[22m from [1mmain[22m and worktree @ [1m_REPO_.test-decline[22m[39m[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m[33m▲[39m [33mCannot change directory — ran [BIN][22m; shell integration wraps [1mwt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snapindex 46a89f157..acc3810cc 100644--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_mixed_approved_unapproved_decline.snap@@ -9,7 +9,7 @@ expression: "&output"[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'Third command'[0m[2m[36m❯[39m [36mAllow and remember? [1m[y/N][22m[39m n-[2m○[22m Commands declined, continuing worktree creation+[2m○[22m Commands declined, continuing worktree creation without hooks[32m✓[39m [32mCreated branch [1mtest-mixed-decline[22m from [1mmain[22m and worktree @ [1m_REPO_.test-mixed-decline[22m[39m[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m[33m▲[39m [33mCannot change directory — ran [BIN][22m; shell integration wraps [1mwt[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snapindex c4ebaacb9..2691c4e41 100644--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snap+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_prune_decline.snap@@ -7,7 +7,7 @@ expression: "&output"[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'pre-remove hook'[0m[2m[36m❯[39m [36mAllow and remember? [1m[y/N][22m[39m n-[2m○[22m Commands declined, continuing removal+[2m○[22m Commands declined, continuing removal without hooks[36m◎[39m [36mRemoving [1mto-prune[22m worktree...[39m[1G[2K[32m✓[39m [32mRemoved [1mto-prune[22m worktree & branch (same commit as [1mmain[22m,[39m [2m_[22m[32m)[39m [90m(4 files · [BYTES] B[39m[90m)[39m[32m✓[39m [32mPruned 1 worktree & branch[39mdiff --git a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snapindex c1c2c56b6..92ad7e93b 100644--- a/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap+++ b/tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_remove_decline.snap@@ -7,5 +7,5 @@ expression: "&output"[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m'pre-remove hook'[0m[2m[36m❯[39m [36mAllow and remember? [1m[y/N][22m[39m n-[2m○[22m Commands declined, continuing removal+[2m○[22m Commands declined, continuing removal without hooks[36m◎[39m [36mRemoving [1mto-remove[22m worktree & branch in background (same commit as [1mmain[22m,[39m [2m_[22m[36m)[39m