Skip to content

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

feat(plugin): add `wt config plugins claude hook` for the Claude hooks (#4304)

Maximilian Roos2661ba15bff7
diff --git a/docs/src/content/docs/tips-patterns.md b/docs/src/content/docs/tips-patterns.md
index 099c7b4f0..7b34d25bf 100644
--- a/docs/src/content/docs/tips-patterns.md
+++ b/docs/src/content/docs/tips-patterns.md
@@ -274,7 +274,7 @@ To scope environment variables to a worktree β€” a tool's package path, a profil
```sh
# .envrc
-export MY_PACKAGES_PATH="$PWD/.packages"
+export MY_PACKAGES_PATH="$(expand_path .packages)"
```
Run `direnv allow` once per worktree to trust the file ([getting started](https://direnv.net/#getting-started)). After that, switching into a worktree loads the env; switching out unloads it.
diff --git a/plugins/worktrunk/.claude-plugin/icon.png b/plugins/worktrunk/.claude-plugin/icon.png
new file mode 100644
index 000000000..2bf47407f
Binary files /dev/null and b/plugins/worktrunk/.claude-plugin/icon.png differ
diff --git a/plugins/worktrunk/.claude-plugin/plugin.json b/plugins/worktrunk/.claude-plugin/plugin.json
index ec82a3411..196b7cc3c 100644
--- a/plugins/worktrunk/.claude-plugin/plugin.json
+++ b/plugins/worktrunk/.claude-plugin/plugin.json
@@ -2,6 +2,17 @@
"name": "worktrunk",
"description": "Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows. This plugin provides configuration guidance (LLM commit messages, project hooks, worktree paths) and automatic activity tracking (πŸ€–/πŸ’¬ indicators in `wt list` showing active Claude sessions).",
"author": {
- "name": "Worktrunk"
- }
+ "name": "Worktrunk",
+ "url": "https://github.com/max-sixty/worktrunk"
+ },
+ "homepage": "https://worktrunk.dev",
+ "repository": "https://github.com/max-sixty/worktrunk",
+ "license": "MIT OR Apache-2.0",
+ "keywords": [
+ "git",
+ "worktree",
+ "claude-code",
+ "agent"
+ ],
+ "icon": "./.claude-plugin/icon.png"
}
diff --git a/plugins/worktrunk/README.md b/plugins/worktrunk/README.md
index 048de3364..1d996282b 100644
--- a/plugins/worktrunk/README.md
+++ b/plugins/worktrunk/README.md
@@ -11,6 +11,14 @@ by the worktree-lifecycle hooks).
2. **Activity tracking** β€” Shows which branches have active Claude sessions via indicators in `wt list`
3. **`/wt-switch-create` command** β€” Creates a worktrunk worktree and moves the current Claude session into it
+## What the hooks run
+
+Every hook calls `wt` through `hooks/wt.sh`:
+
+- **Activity markers**: `UserPromptSubmit`, `Notification`, `Stop`, and `PreToolUse` on `AskUserQuestion` set the branch's marker with `wt config state marker set`; `SessionEnd` clears it.
+- **Worktree creation and removal**: when Claude Code creates or removes a worktree, the `WorktreeCreate` and `WorktreeRemove` hooks run `wt switch --create` and `wt remove` in place of Claude Code's own `git worktree` commands, so the worktree follows worktrunk's path layout and runs the project's approved worktrunk hooks.
+- **`EnterWorktree` approval**: the `PermissionRequest` hook allows an `EnterWorktree` call without a dialog when its path is a worktree of the current repository at the location worktrunk's `worktree-path` template gives its branch. Every other request shows Claude Code's usual dialog and sets the branch's marker to πŸ’¬ while it waits.
+
## Examples
**Activity tracking across worktrees**
diff --git a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
index 261d41c90..b2f6ea45a 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md
@@ -266,7 +266,7 @@ To scope environment variables to a worktree β€” a tool's package path, a profil
```sh
# .envrc
-export MY_PACKAGES_PATH="$PWD/.packages"
+export MY_PACKAGES_PATH="$(expand_path .packages)"
```
Run `direnv allow` once per worktree to trust the file ([getting started](https://direnv.net/#getting-started)). After that, switching into a worktree loads the env; switching out unloads it.
diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.md
index 261d41c90..b2f6ea45a 100644
--- a/skills/worktrunk/reference/tips-patterns.md
+++ b/skills/worktrunk/reference/tips-patterns.md
@@ -266,7 +266,7 @@ To scope environment variables to a worktree β€” a tool's package path, a profil
```sh
# .envrc
-export MY_PACKAGES_PATH="$PWD/.packages"
+export MY_PACKAGES_PATH="$(expand_path .packages)"
```
Run `direnv allow` once per worktree to trust the file ([getting started](https://direnv.net/#getting-started)). After that, switching into a worktree loads the env; switching out unloads it.
diff --git a/src/cli/config.rs b/src/cli/config.rs
index d6e4947bf..8f299ed06 100644
--- a/src/cli/config.rs
+++ b/src/cli/config.rs
@@ -548,7 +548,11 @@ Skips gracefully if the statusline is already configured."#
)]
InstallStatusline,
- /// Internal: the plugin's PermissionRequest hook, reading its payload from stdin
+ /// Internal: the plugin's hook command, reading Claude Code's hook payload from stdin
+ #[command(hide = true)]
+ Hook,
+
+ /// Internal: the PermissionRequest hook of plugin copies that predate `hook`
#[command(hide = true, name = "approve-enter-worktree")]
ApproveEnterWorktree,
}
diff --git a/src/commands/config/mod.rs b/src/commands/config/mod.rs
index bcaad28dd..e8c9ce39d 100644
--- a/src/commands/config/mod.rs
+++ b/src/commands/config/mod.rs
@@ -25,8 +25,8 @@ pub use omp::{handle_omp_install, handle_omp_uninstall};
pub use opencode::{handle_opencode_install, handle_opencode_uninstall};
pub use pi::{handle_pi_install, handle_pi_uninstall};
pub use plugins::{
- handle_claude_approve_enter_worktree, handle_claude_install, handle_claude_install_statusline,
- handle_claude_uninstall,
+ handle_claude_approve_enter_worktree, handle_claude_hook, handle_claude_install,
+ handle_claude_install_statusline, handle_claude_uninstall,
};
pub use show::handle_config_show;
pub use state::{
diff --git a/src/commands/config/plugins.rs b/src/commands/config/plugins.rs
index 018938069..ddb21bf3b 100644
--- a/src/commands/config/plugins.rs
+++ b/src/commands/config/plugins.rs
@@ -1,12 +1,14 @@
//! Plugin management commands for AI coding tools.
-use std::path::PathBuf;
+use std::io::Write;
+use std::path::{Path, PathBuf};
use anyhow::{Context, bail};
use color_print::cformat;
use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::path::paths_match;
-use worktrunk::styling::{eprintln, info_message, progress_message, success_message};
+use worktrunk::shell_exec::Cmd;
+use worktrunk::styling::{eprintln, info_message, println, progress_message, success_message};
use super::show::{claude_config_dir, is_claude_available, is_statusline_configured};
use crate::commands::is_worktree_at_expected_path;
@@ -107,51 +109,193 @@ pub fn handle_claude_uninstall(yes: bool) -> anyhow::Result<()> {
Ok(())
}
-/// The fields of a Claude Code `PermissionRequest` hook payload this handler
-/// reads.
+/// A Claude Code hook payload, by the event the plugin's hook command
+/// received. Each variant carries only the fields its handler reads.
+#[derive(serde::Deserialize)]
+#[serde(tag = "hook_event_name")]
+enum ClaudeHook {
+ UserPromptSubmit {},
+ Notification {},
+ PreToolUse {},
+ PermissionRequest(PermissionRequest),
+ Stop {},
+ SessionEnd {},
+ WorktreeCreate { name: String },
+ WorktreeRemove { worktree_path: PathBuf },
+}
+
+/// The fields of a `PermissionRequest` payload the approval reads. Each
+/// defaults, so a payload missing one declines rather than failing the hook.
#[derive(serde::Deserialize)]
struct PermissionRequest {
+ #[serde(default)]
tool_name: String,
+ #[serde(default)]
cwd: PathBuf,
+ #[serde(default)]
tool_input: serde_json::Value,
}
-/// Handle `wt config plugins claude approve-enter-worktree`, the plugin's
-/// `PermissionRequest` hook.
+/// Handle `wt config plugins claude hook`, the command behind every hook in
+/// the plugin's `hooks/hooks.json`.
///
-/// Claude Code confirms an `EnterWorktree` into any worktree outside its own
-/// `.claude/worktrees/`, which in worktrunk's layout is every worktree, and a
-/// background session waits at that dialog until someone attaches. This
-/// extends Claude Code's exemption to worktrunk's managed location: it prints
-/// the `allow` decision when the call's `path` names a worktree of the
-/// repository the payload's `cwd` is in, sitting at the path the
-/// `worktree-path` template gives its branch. Every other payload exits 1 with
-/// nothing on stdout, so the dialog appears and the hook command's `||` sets
-/// the πŸ’¬ marker.
+/// Claude Code pipes each hook's payload to stdin; `hook_event_name` picks the
+/// action. Keeping the logic here rather than in the hook commands leaves each
+/// command a literal path and literal arguments, which Anthropic's plugin
+/// directory requires, and needs no `jq`.
+///
+/// - Activity markers resolve against `CLAUDE_PROJECT_DIR`, the directory the
+/// session launched in, so a shell `cd` during a turn can't retarget them to
+/// another repository (#3921). A marker failure never fails the hook.
+/// - `PermissionRequest` approves an `EnterWorktree` into a worktrunk-managed
+/// worktree (see [`approves_enter_worktree`]) and otherwise marks the
+/// session πŸ’¬ while the dialog waits. One hook does both because Claude Code
+/// runs every matching hook in parallel.
+/// - `WorktreeCreate` runs `wt switch --create` and prints the new worktree's
+/// path, which Claude Code reads as the hook's answer. A failure exits
+/// nonzero with nothing on stdout (#3545).
+/// - `WorktreeRemove` resolves against the worktree path Claude Code hands
+/// over, never `CLAUDE_PROJECT_DIR`: the `claude agents` view spans
+/// repositories, so no single project dir is right for every session
+/// (#3754). It never force-deletes, since Claude Code fires it on session
+/// exit for any clean worktree (#2939).
+///
+/// Each action runs this `wt` binary again with the command a user would type,
+/// so the hook behaves exactly as that command does.
+pub fn handle_claude_hook() -> anyhow::Result<()> {
+ let hook: ClaudeHook = serde_json::from_reader(std::io::stdin().lock())
+ .context("Failed to parse Claude Code hook payload")?;
+ let project_dir = match std::env::var_os("CLAUDE_PROJECT_DIR").filter(|dir| !dir.is_empty()) {
+ Some(dir) => PathBuf::from(dir),
+ None => std::env::current_dir().context("Failed to read the current directory")?,
+ };
+
+ match hook {
+ ClaudeHook::UserPromptSubmit {} => set_marker(&project_dir, &["set", "πŸ€–"]),
+ ClaudeHook::Notification {} | ClaudeHook::PreToolUse {} | ClaudeHook::Stop {} => {
+ set_marker(&project_dir, &["set", "πŸ’¬"])
+ }
+ ClaudeHook::SessionEnd {} => set_marker(&project_dir, &["clear"]),
+ ClaudeHook::PermissionRequest(request) => {
+ // A payload `wt` can't resolve, such as a `cwd` in no repository,
+ // declines, leaving the dialog.
+ if approves_enter_worktree(&request).unwrap_or(false) {
+ return print_allow_decision();
+ }
+ set_marker(&project_dir, &["set", "πŸ’¬"])
+ }
+ ClaudeHook::WorktreeCreate { name } => {
+ let stdout = run_wt(
+ Cmd::new(wt_binary()?)
+ .args(["switch", "--create", &name, "--no-cd", "--format=json"])
+ .current_dir(&project_dir),
+ )?;
+ let created: serde_json::Value = serde_json::from_slice(&stdout)
+ .context("Failed to parse `wt switch --format=json` output")?;
+ let path = created["path"]
+ .as_str()
+ .context("`wt switch --format=json` output has no `path`")?;
+ println!("{path}");
+ Ok(())
+ }
+ ClaudeHook::WorktreeRemove { worktree_path } => {
+ // Already gone, or never a worktree: nothing for wt to remove.
+ if !worktree_path.join(".git").exists() {
+ return Ok(());
+ }
+ let path = worktree_path.to_string_lossy();
+ run_wt(Cmd::new(wt_binary()?).args([
+ "-C",
+ path.as_ref(),
+ "remove",
+ "--foreground",
+ path.as_ref(),
+ ]))?;
+ Ok(())
+ }
+ }
+}
+
+/// Handle `wt config plugins claude approve-enter-worktree`, the
+/// `PermissionRequest` hook of plugin copies installed before
+/// [`handle_claude_hook`] existed. Marketplace installs don't update on their
+/// own, so those copies keep calling it: it prints the allow decision, or exits
+/// 1 so their hook command's `||` sets the πŸ’¬ marker.
pub fn handle_claude_approve_enter_worktree() -> anyhow::Result<()> {
let request: PermissionRequest = serde_json::from_reader(std::io::stdin().lock())
.context("Failed to parse PermissionRequest payload")?;
+ if approves_enter_worktree(&request)? {
+ return print_allow_decision();
+ }
+ Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())
+}
+
+/// Prints the `PermissionRequest` decision that allows the call.
+fn print_allow_decision() -> anyhow::Result<()> {
+ print_json(&serde_json::json!({
+ "hookSpecificOutput": {
+ "hookEventName": "PermissionRequest",
+ "decision": { "behavior": "allow" },
+ }
+ }))
+}
+
+/// Sets or clears the activity marker of the worktree at `dir`, ignoring
+/// failure.
+fn set_marker(dir: &Path, args: &[&str]) -> anyhow::Result<()> {
+ let dir = dir.to_string_lossy();
+ let _ = run_wt(
+ Cmd::new(wt_binary()?)
+ .args(["-C", dir.as_ref(), "config", "state", "marker"])
+ .args(args.iter().copied()),
+ );
+ Ok(())
+}
+
+/// The running `wt` binary, which the hook runs again for each action.
+fn wt_binary() -> anyhow::Result<String> {
+ let exe = std::env::current_exe().context("Failed to resolve wt binary path")?;
+ Ok(exe.to_string_lossy().into_owned())
+}
- if request.tool_name == "EnterWorktree"
- && let Some(path) = request.tool_input.get("path").and_then(|p| p.as_str())
- {
- let path = request.cwd.join(path);
- let repo = Repository::at(&request.cwd)?;
- let config = repo.user_config();
- let managed = repo.list_worktrees()?.iter().any(|wt| {
- paths_match(&wt.path, &path) && is_worktree_at_expected_path(wt, &repo, config)
- });
- if managed {
- return print_json(&serde_json::json!({
- "hookSpecificOutput": {
- "hookEventName": "PermissionRequest",
- "decision": { "behavior": "allow" },
- }
- }));
+/// Runs `cmd`, passing its stderr through, and returns its stdout. A failure
+/// exits with the child's status, its own error already on stderr.
+fn run_wt(cmd: Cmd) -> anyhow::Result<Vec<u8>> {
+ let output = cmd.run().context("Failed to run wt")?;
+ std::io::stderr()
+ .write_all(&output.stderr)
+ .context("Failed to write wt's stderr")?;
+ if !output.status.success() {
+ return Err(WorktrunkError::AlreadyDisplayed {
+ exit_code: output.status.code().unwrap_or(1),
}
+ .into());
}
+ Ok(output.stdout)
+}
- Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into())
+/// Whether a `PermissionRequest` is an `EnterWorktree` the plugin approves.
+///
+/// Claude Code confirms an `EnterWorktree` into any worktree outside its own
+/// `.claude/worktrees/`, which in worktrunk's layout is every worktree, and a
+/// background session waits at that dialog until someone attaches. This
+/// extends Claude Code's exemption to worktrunk's managed location: the call's
+/// `path` names a worktree of the repository the payload's `cwd` is in,
+/// sitting at the path the `worktree-path` template gives its branch.
+fn approves_enter_worktree(request: &PermissionRequest) -> anyhow::Result<bool> {
+ if request.tool_name != "EnterWorktree" {
+ return Ok(false);
+ }
+ let Some(path) = request.tool_input.get("path").and_then(|p| p.as_str()) else {
+ return Ok(false);
+ };
+ let path = request.cwd.join(path);
+ let repo = Repository::at(&request.cwd)?;
+ let config = repo.user_config();
+ Ok(repo
+ .list_worktrees()?
+ .iter()
+ .any(|wt| paths_match(&wt.path, &path) && is_worktree_at_expected_path(wt, &repo, config)))
}
/// Whether Claude Code lists the worktrunk plugin, or `None` where its answer
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index ae48d57ab..826ed28b3 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -35,14 +35,14 @@ pub(crate) use alias::{
};
pub(crate) use config::{
add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show, handle_cache_clear,
- handle_cache_get, handle_claude_approve_enter_worktree, handle_claude_install,
- handle_claude_install_statusline, handle_claude_uninstall, handle_codex_install,
- handle_codex_uninstall, handle_config_create, handle_config_show, handle_config_update,
- handle_hints_clear, handle_hints_get, handle_logs_list, handle_logs_profile,
- handle_omp_install, handle_omp_uninstall, handle_opencode_install, handle_opencode_uninstall,
- handle_pi_install, handle_pi_uninstall, handle_state_clear, handle_state_clear_all,
- handle_state_get, handle_state_set, handle_state_show, handle_vars_clear, handle_vars_get,
- handle_vars_list, handle_vars_set, list_approvals,
+ handle_cache_get, handle_claude_approve_enter_worktree, handle_claude_hook,
+ handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,
+ handle_codex_install, handle_codex_uninstall, handle_config_create, handle_config_show,
+ handle_config_update, handle_hints_clear, handle_hints_get, handle_logs_list,
+ handle_logs_profile, handle_omp_install, handle_omp_uninstall, handle_opencode_install,
+ handle_opencode_uninstall, handle_pi_install, handle_pi_uninstall, handle_state_clear,
+ handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,
+ handle_vars_clear, handle_vars_get, handle_vars_list, handle_vars_set, list_approvals,
};
pub(crate) use configure_shell::{
handle_configure_shell, handle_show_theme, handle_unconfigure_shell,
diff --git a/src/main.rs b/src/main.rs
index 11458f565..56db44556 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -44,12 +44,12 @@ use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge,
use commands::{
HookCliArgs, MergeFlagOverrides, MergeOptions, RebaseResult, SquashResult, add_approvals,
clear_approvals, flag_pair, handle_alias_dry_run, handle_alias_show, handle_cache_clear,
- handle_cache_get, handle_claude_approve_enter_worktree, handle_claude_install,
- handle_claude_install_statusline, handle_claude_uninstall, handle_codex_install,
- handle_codex_uninstall, handle_completions, handle_config_create, handle_config_show,
- handle_config_update, handle_configure_shell, handle_custom_command, handle_hints_clear,
- handle_hints_get, handle_hook_show, handle_init, handle_list, handle_logs_list,
- handle_logs_profile, handle_merge, handle_omp_install, handle_omp_uninstall,
+ handle_cache_get, handle_claude_approve_enter_worktree, handle_claude_hook,
+ handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,
+ handle_codex_install, handle_codex_uninstall, handle_completions, handle_config_create,
+ handle_config_show, handle_config_update, handle_configure_shell, handle_custom_command,
+ handle_hints_clear, handle_hints_get, handle_hook_show, handle_init, handle_list,
+ handle_logs_list, handle_logs_profile, handle_merge, handle_omp_install, handle_omp_uninstall,
handle_opencode_install, handle_opencode_uninstall, handle_pi_install, handle_pi_uninstall,
handle_promote, handle_rebase, handle_remove_command, handle_show_theme, handle_squash,
handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,
@@ -661,6 +661,7 @@ fn handle_plugins_command(action: ConfigPluginsCommand, yes: bool) -> anyhow::Re
ConfigPluginsClaudeCommand::Install => handle_claude_install(yes),
ConfigPluginsClaudeCommand::Uninstall => handle_claude_uninstall(yes),
ConfigPluginsClaudeCommand::InstallStatusline => handle_claude_install_statusline(yes),
+ ConfigPluginsClaudeCommand::Hook => handle_claude_hook(),
ConfigPluginsClaudeCommand::ApproveEnterWorktree => {
handle_claude_approve_enter_worktree()
}
diff --git a/tests/integration_tests/claude_hook.rs b/tests/integration_tests/claude_hook.rs
new file mode 100644
index 000000000..798d30fcb
--- /dev/null
+++ b/tests/integration_tests/claude_hook.rs
@@ -0,0 +1,190 @@
+//! `wt config plugins claude hook`, the command behind every hook in the
+//! Claude Code plugin's `hooks/hooks.json`.
+use crate::common::{TestRepo, repo};
+use rstest::rstest;
+use std::io::Write as _;
+use std::path::Path;
+use std::process::{Command, Output, Stdio};
+
+/// Runs the hook with `payload` on stdin, as Claude Code does from `cwd` for
+/// a session launched in `project_dir`.
+fn run_hook(repo: &TestRepo, cwd: &Path, project_dir: &Path, payload: &str) -> Output {
+ let mut cmd = repo.wt_command();
+ cmd.env("CLAUDE_PROJECT_DIR", project_dir);
+ spawn_hook(cmd, cwd, payload)
+}
+
+/// Runs the hook with no `CLAUDE_PROJECT_DIR`, so it falls back to `cwd`.
+fn run_hook_without_project_dir(repo: &TestRepo, cwd: &Path, payload: &str) -> Output {
+ let mut cmd = repo.wt_command();
+ cmd.env_remove("CLAUDE_PROJECT_DIR");
+ spawn_hook(cmd, cwd, payload)
+}
+
+fn spawn_hook(mut cmd: Command, cwd: &Path, payload: &str) -> Output {
+ cmd.args(["config", "plugins", "claude", "hook"])
+ .current_dir(cwd)
+ .stdin(Stdio::piped())
+ .stdout(Stdio::piped())
+ .stderr(Stdio::piped());
+ let mut child = cmd.spawn().unwrap();
+ child
+ .stdin
+ .take()
+ .unwrap()
+ .write_all(payload.as_bytes())
+ .unwrap();
+ child.wait_with_output().unwrap()
+}
+
+/// The activity marker of the worktree at `dir`.
+fn marker(repo: &TestRepo, dir: &Path) -> String {
+ let output = repo
+ .wt_command()
+ .args(["config", "state", "marker", "get"])
+ .current_dir(dir)
+ .output()
+ .unwrap();
+ String::from_utf8(output.stdout).unwrap().trim().to_string()
+}
+
+fn stdout(output: &Output) -> String {
+ String::from_utf8_lossy(&output.stdout).into_owned()
+}
+
+/// Markers land on the session's launch worktree even after a shell `cd`
+/// moves the hook's cwd elsewhere (#3921).
+#[rstest]
+fn test_claude_hook_markers_follow_project_dir(mut repo: TestRepo) {
+ let feature = repo.add_worktree("feature");
+ let root = repo.root_path().to_path_buf();
+
+ let prompt = run_hook(
+ &repo,
+ &feature,
+ &root,
+ r#"{"hook_event_name":"UserPromptSubmit","prompt":"hi"}"#,
+ );
+ assert!(prompt.status.success());
+ assert_eq!(marker(&repo, &root), "πŸ€–");
+ assert_eq!(marker(&repo, &feature), "");
+
+ let stop = run_hook(&repo, &feature, &root, r#"{"hook_event_name":"Stop"}"#);
+ assert!(stop.status.success());
+ assert_eq!(marker(&repo, &root), "πŸ’¬");
+
+ let end = run_hook(
+ &repo,
+ &feature,
+ &root,
+ r#"{"hook_event_name":"SessionEnd","reason":"exit"}"#,
+ );
+ assert!(end.status.success());
+ assert_eq!(marker(&repo, &root), "");
+}
+
+/// A marker that can't be set never fails the hook.
+#[rstest]
+fn test_claude_hook_marker_failure_succeeds(repo: TestRepo) {
+ let missing = repo.home_path().join("missing");
+ let output = run_hook(
+ &repo,
+ repo.root_path(),
+ &missing,
+ r#"{"hook_event_name":"Notification","message":"waiting"}"#,
+ );
+ assert!(output.status.success());
+ assert_eq!(stdout(&output), "");
+}
+
+/// `PermissionRequest` answers an `EnterWorktree` into a managed worktree with
+/// the allow decision and leaves the marker unset; any other request prints
+/// nothing, so the dialog stays, and marks the session πŸ’¬ while it waits.
+#[rstest]
+fn test_claude_hook_permission_request(mut repo: TestRepo) {
+ let feature = repo.add_worktree("feature");
+ let root = repo.root_path().to_path_buf();
+ let request = |tool: &str, tool_input: serde_json::Value| {
+ serde_json::json!({
+ "hook_event_name": "PermissionRequest",
+ "tool_name": tool,
+ "cwd": root,
+ "tool_input": tool_input,
+ })
+ .to_string()
+ };
+
+ let allowed = run_hook(
+ &repo,
+ &root,
+ &root,
+ &request("EnterWorktree", serde_json::json!({ "path": feature })),
+ );
+ assert!(allowed.status.success(), "{allowed:?}");
+ let decision: serde_json::Value = serde_json::from_slice(&allowed.stdout).unwrap();
+ assert_eq!(
+ decision["hookSpecificOutput"]["decision"]["behavior"],
+ "allow"
+ );
+ assert_eq!(marker(&repo, &root), "");
+
+ for (tool, tool_input) in [
+ ("Bash", serde_json::json!({ "command": "ls" })),
+ ("EnterWorktree", serde_json::json!({})),
+ ] {
+ run_hook(&repo, &root, &root, r#"{"hook_event_name":"SessionEnd"}"#);
+ let declined = run_hook(&repo, &root, &root, &request(tool, tool_input));
+ assert!(declined.status.success(), "{declined:?}");
+ assert_eq!(stdout(&declined), "");
+ assert_eq!(marker(&repo, &root), "πŸ’¬");
+ }
+}
+
+/// `WorktreeCreate` prints the new worktree's path; a failed create exits
+/// nonzero with nothing on stdout, so Claude Code reports wt's error rather
+/// than a successful hook with no path (#3545). Without `CLAUDE_PROJECT_DIR`
+/// the hook creates from its own cwd.
+#[rstest]
+fn test_claude_hook_worktree_create(repo: TestRepo) {
+ let root = repo.root_path().to_path_buf();
+ let payload = r#"{"hook_event_name":"WorktreeCreate","name":"agent-task"}"#;
+
+ let created = run_hook_without_project_dir(&repo, &root, payload);
+ assert!(created.status.success(), "{created:?}");
+ let path = stdout(&created);
+ let path = Path::new(path.trim_end());
+ assert!(path.join(".git").exists(), "no worktree at {path:?}");
+ assert!(path.ends_with("repo.agent-task"), "{path:?}");
+
+ let collision = run_hook(&repo, &root, &root, payload);
+ assert!(!collision.status.success());
+ assert_eq!(stdout(&collision), "");
+}
+
+/// `WorktreeRemove` resolves against the path Claude Code hands it, even when
+/// the session's project dir is no repository at all (#3754), and keeps an
+/// unmerged branch rather than force-deleting it (#2939).
+#[rstest]
+fn test_claude_hook_worktree_remove(mut repo: TestRepo) {
+ let feature = repo.add_worktree("feature");
+ repo.commit_in_worktree(&feature, "work.txt", "work", "unpushed work");
+ let outside = repo.home_path().to_path_buf();
+
+ let payload = serde_json::json!({
+ "hook_event_name": "WorktreeRemove",
+ "worktree_path": feature,
+ });
+ let output = run_hook(&repo, &outside, &outside, &payload.to_string());
+ assert!(output.status.success(), "{output:?}");
+ assert!(!feature.exists());
+ let branches = repo
+ .git_command()
+ .args(["branch", "--list", "feature"])
+ .run()
+ .unwrap();
+ assert!(String::from_utf8_lossy(&branches.stdout).contains("feature"));
+
+ // A path that is already gone is nothing to remove.
+ let again = run_hook(&repo, &outside, &outside, &payload.to_string());
+ assert!(again.status.success());
+}
diff --git a/tests/integration_tests/mod.rs b/tests/integration_tests/mod.rs
index bfc30ed7e..eb93c35dc 100644
--- a/tests/integration_tests/mod.rs
+++ b/tests/integration_tests/mod.rs
@@ -11,6 +11,7 @@ pub mod approval_ui;
pub mod approvals;
pub mod bare_repository;
pub mod ci_status;
+pub mod claude_hook;
pub mod completion;
pub mod completion_validation;
pub mod config_init;
diff --git a/tests/integration_tests/output_system_guard.rs b/tests/integration_tests/output_system_guard.rs
index 86da6be60..ec529439c 100644
--- a/tests/integration_tests/output_system_guard.rs
+++ b/tests/integration_tests/output_system_guard.rs
@@ -74,6 +74,9 @@ const STDOUT_ALLOWED_PATHS: &[&str] = &[
"commands/configure_shell.rs",
// JSON output for wt switch --format=json
"commands/worktree/switch.rs",
+ // The WorktreeCreate path that wt config plugins claude hook answers
+ // Claude Code with
+ "commands/config/plugins.rs",
// Migrated TOML output for wt config update --output=- (pipeable)
"commands/config/update.rs",
// Hook listing for wt hook show (paged), and the wt hook --dry-run preview