Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(plugin): run every Claude hook through `wt config plugins claude hook` (#4305)
Maximilian Roosa63c1c3e2ac1
diff --git a/plugins/worktrunk/AGENTS.md b/plugins/worktrunk/AGENTS.mdindex 215255d7f..8294cfdea 100644--- a/plugins/worktrunk/AGENTS.md+++ b/plugins/worktrunk/AGENTS.md@@ -6,6 +6,7 @@ The repository root is the marketplace for Claude Code and Codex and the Gemini- Repo-local maintainer skills live in .claude/skills/; .agents/skills points there. This symlink does not work on Windows checkouts with core.symlinks=false.- Claude discovers plugins/worktrunk/hooks/hooks.json by convention. The Codex manifest defines hooks inline so Codex does not load Claude events from that same file. Gemini has its own root hooks/hooks.json.+- Claude hooks run `wt config plugins claude hook`, which dispatches on the payload event. Keep commands literal for Anthropic's plugin directory validator, and `$CLAUDE_PLUGIN_ROOT` unbraced for fish.- All three integrations call plugins/worktrunk/hooks/wt.sh. On Windows, Codex commandWindows calls hooks/wt.cmd to find Git Bash before running wt.sh. The command must parse in cmd.exe, Windows PowerShell, and pwsh; test it in all three shells with a plugin path containing spaces. Marker failures must not raise hook errors.- The Codex manifest uses the native PLUGIN_ROOT variable, braced as `${PLUGIN_ROOT}` in Windows commands for Codex's textual substitution. SessionEnd has a three-second timeout, Codex's event ceiling.- The shared skills mirror exposes wt-switch-create to Codex and Gemini, even though only Claude can switch the current session directory. Keep one authored skill tree.diff --git a/plugins/worktrunk/README.md b/plugins/worktrunk/README.mdindex 0c7e6a76d..6be6a2c91 100644--- a/plugins/worktrunk/README.md+++ b/plugins/worktrunk/README.md@@ -2,8 +2,7 @@Git worktree management CLI integration with activity tracking.-Requires the `wt` CLI ([worktrunk.dev](https://worktrunk.dev)) and `jq` (used-by the worktree-lifecycle hooks).+Requires `wt` v0.81.0 or later ([worktrunk.dev](https://worktrunk.dev)).## Features@@ -13,7 +12,7 @@ by the worktree-lifecycle hooks).## What the hooks run-Every hook calls `wt` through `hooks/wt.sh`:+Every hook runs `wt config plugins claude hook` through `hooks/wt.sh`; that subcommand reads Claude Code's hook payload and acts on its event:- **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` (plain `wt switch` when the branch already exists, which returns its worktree) 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.diff --git a/plugins/worktrunk/hooks/hooks.json b/plugins/worktrunk/hooks/hooks.jsonindex 56a5d36be..3230c6268 100644--- a/plugins/worktrunk/hooks/hooks.json+++ b/plugins/worktrunk/hooks/hooks.json@@ -5,7 +5,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker set π€ || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -16,7 +16,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker set π¬ || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -27,7 +27,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker set π¬ || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -38,7 +38,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude approve-enter-worktree || bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker set π¬ || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -48,7 +48,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker set π¬ || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -59,7 +59,7 @@"hooks": [{"type": "command",- "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$CLAUDE_PROJECT_DIR\" config state marker clear || true"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook || true"}]}@@ -69,7 +69,7 @@"hooks": [{"type": "command",- "command": "bash -c 'set -o pipefail; name=$(jq -er .name) || exit 1; cd \"${CLAUDE_PROJECT_DIR:-.}\" || exit 1; create=--create; git rev-parse --verify --quiet \"refs/heads/$name\" >/dev/null 2>&1 && create=; bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" switch $create \"$name\" --no-cd --format=json | jq -er .path'"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook"}]}@@ -79,7 +79,7 @@"hooks": [{"type": "command",- "command": "bash -c 'p=$(jq -er .worktree_path) || exit 1; [ -e \"$p/.git\" ] || exit 0; bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" -C \"$p\" remove --foreground \"$p\"'"+ "command": "bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" config plugins claude hook"}]}diff --git a/plugins/worktrunk/skills/wt-switch-create/SKILL.md b/plugins/worktrunk/skills/wt-switch-create/SKILL.mdindex 2b084ef18..95dc6bcfb 100644--- a/plugins/worktrunk/skills/wt-switch-create/SKILL.md+++ b/plugins/worktrunk/skills/wt-switch-create/SKILL.md@@ -46,15 +46,16 @@ read-only task gets one all the same.<!-- Maintainers: rationale.md (same directory) covers the harness rules anddesign choices behind this β read it before re-adding guards or routes. -->-1. **Pick the branch name** if none was given: short, from the task and+1. **Pick a new branch name** if none was given: short, from the task andconsistent with existing worktree names, or, mid-session, from the workbeing moved; with nothing to derive from, ask.2. **With no repo argument, create and enter in one call:**`EnterWorktree({name: "<branch>"})`. Worktrunk's `WorktreeCreate` hook runs- `wt switch --create`, so the result is an ordinary `wt` worktree in the- default layout, and the user sees no confirmation prompt. On success,- do the task (or, with no task text, confirm it's ready and wait).+ `wt switch --create` for a new branch or `wt switch` for an existing one,+ creating its checkout if needed. The result is an ordinary `wt` worktree,+ and the user sees no confirmation prompt. On success, do the task (or,+ with no task text, confirm it's ready and wait).Mid-session, carry uncommitted work across: `git stash push -u` before the`EnterWorktree` call, then `git stash pop` after β the call re-roots the@@ -62,8 +63,8 @@ design choices behind this β read it before re-adding guards or routes. -->3. **Otherwise create it with `wt` and enter by path.** Two cases reach here: arepo argument, which step 2 can't target, and a failed step 2, whose error- says which β `β Branch <branch> already exists`, or `Already in a worktree- session`. Create with a `Bash` call (omit `-C <repo>` for this repo):+ says `Already in a worktree session`. Create with a `Bash` call (omit+ `-C <repo>` for this repo):```wt -C <repo> switch --create <branch> --no-cd --format=jsondiff --git a/plugins/worktrunk/skills/wt-switch-create/rationale.md b/plugins/worktrunk/skills/wt-switch-create/rationale.mdindex bafbfe9e7..fe518af5e 100644--- a/plugins/worktrunk/skills/wt-switch-create/rationale.md+++ b/plugins/worktrunk/skills/wt-switch-create/rationale.md@@ -12,6 +12,7 @@ repo). Entry β the confirmation, both `EnterWorktree` routes, and what eachleaves behind at exit β was re-run live on 2026-07-28 against Claude Code2.1.220 and wt v0.69.2. The confirmation hook and `cd`-before-entry for anotherrepo were verified live on 2026-09-16 against Claude Code 2.1.273 (#4149).+Hook-based exit cleanup was checked live on Claude Code 2.1.308 on 2026-10-22.Re-verify against current versions before relying on a specific behavior; the*shape* of the argument should outlive the details.Binary symbol names are deliberately omitted β they re-minify every build.@@ -21,11 +22,11 @@ Binary symbol names are deliberately omitted β they re-minify every build.Steps are numbered as in `SKILL.md`; step 1, picking the branch name, needsno rationale.-2. `EnterWorktree({name})` for a new branch in this repo. It creates through- worktrunk's `WorktreeCreate` hook (`wt switch --create`), so the result is- an ordinary `wt` worktree, and it passes no `path`, which is what keeps M2's- confirmation from firing. It fails on an existing branch and from a session- that already entered a worktree, and it has no repo targeting.+2. `EnterWorktree({name})` in this repo. Worktrunk's `WorktreeCreate` hook runs+ `wt switch --create` for a new branch or `wt switch` for an existing one,+ creating its checkout if needed. Passing no `path` keeps M2's confirmation+ from firing. It fails from a session that already entered a worktree, and+ it has no repo targeting.3. Otherwise `wt -C <repo> switch --create <branch> --no-cd --format=json` inBash, then, for another repo, `cd <repo>`, then `EnterWorktree({path})`.`wt` solves repo targeting (`-C` works from anywhere), existing-branch@@ -167,13 +168,13 @@ Verified: from a worktrunk session, `cd` into a prql worktree under `/tmp`, then### The confirmation hook-The plugin's `PermissionRequest` command runs the hidden-`wt config plugins claude approve-enter-worktree`, which reads the hook payload-and prints an `allow` decision when the call is `EnterWorktree` and its `path`-is a worktree of the repository the payload's `cwd` is in, at the path the-`worktree-path` template gives its branch. Anything else leaves stdout empty-and exits 1, which leaves the dialog (or, where no dialog can show, the denial)-in place. The tool's own validation still runs after an approval.+The plugin's hooks run the hidden `wt config plugins claude hook`, which reads+the hook payload. For `PermissionRequest` it prints an `allow` decision when+the call is `EnterWorktree` and its `path` is a worktree of the repository the+payload's `cwd` is in, at the path the `worktree-path` template gives its+branch. Anything else leaves stdout empty, which leaves the dialog (or, where+no dialog can show, the denial) in place. The tool's own validation still runs+after an approval.The rule extends Claude Code's exemption rather than overriding its check.Claude Code enters a worktree under `.claude/worktrees/` without asking because@@ -193,17 +194,16 @@ another repo before entering. The check lives in `wt` because it is`branch_mismatch`; a script over `wt list --format=json` would inherit thatcommand's user config, where `list.full` adds CI fetches and LLM summaries(33s measured on a 54-worktree repository) and `list.json-schema` and `list.branches` change-the output's shape. A `wt` too old to have the subcommand fails it, which-leaves the dialog as it was before the hook existed.--The approval shares one `hooks.json` command with the π¬ marker,-`wt β¦ approve-enter-worktree || wt β¦ marker set π¬`, because Claude Code runs-all matching hooks in parallel. A separate `EnterWorktree` entry would still-fire the catch-all marker hook, and the launch worktree would read π¬ while the-session works on. With one command, an approval skips the marker and every-other permission request sets it as before. The `permission_prompt`-notification can't set it either: Claude Code sends it only after a shown-prompt has waited about six seconds.+the output's shape. A `wt` too old to have the subcommand fails it, and the+hook command's `|| true` leaves the dialog as it was before the hook existed.++The approval shares one hook with the π¬ marker, setting the marker only when+it doesn't approve, because Claude Code runs all matching hooks in parallel. A+separate `EnterWorktree` entry would still fire the catch-all marker hook, and+the launch worktree would read π¬ while the session works on. With one hook,+an approval skips the marker and every other permission request sets it as+before. The `permission_prompt` notification can't set it either: Claude Code+sends it only after a shown prompt has waited about six seconds.Verified live in `--permission-mode default` sessions: a same-repo entry, and across-repo entry after `cd`, both reported "Allowed by PermissionRequest hook"@@ -272,32 +272,25 @@ integrated machine and a no-op elsewhere. Don't drop it.The `name` route is worth having because it never asks M2's confirmation, withor without worktrunk's hook, and it creates and enters in one call. The sameplugin hook backs `isolation: "worktree"` agents, so the worktree it produces is-the one `wt` would have made either way. Three properties come with it, all-verified live:--1. **An untouched worktree is cleaned up at exit, branch included.** With no- changed files, no commits, and no user-set session title, the exiting- session removes it through the plugin's `WorktreeRemove` hook, which is- `wt remove`, so a clean fully-merged branch goes too. Verified end-to-end:- `EnterWorktree({name: "probe"})`, then `/exit`, leaves neither `repo.probe`- nor the `probe` branch; one untracked file is enough for exit to report- "Keeping worktreeβ¦" and leave both. This is a feature at this scale β a- research task that wrote nothing leaves nothing to prune β and it is the- reason step 2's worktrees are not described as durable. Path-entered- worktrees are always left in place ("worktree at <path> left in place").-2. **It hard-fails on an existing branch.** The hook runs `wt switch --create`,- and a nonzero hook exit fails creation outright, with no git fallback- (binary: "Other exit codes - worktree creation failed"; docs: "the hook- replaces the default git behavior"). The failure is clean: `wt`'s own- `β Branch <branch> already exists` surfaces and nothing is created.+the one `wt` would have made either way. Three properties come with it:++1. **Exit asks whether to keep or remove a hook-created worktree.** Claude+ Code 2.1.308 cannot infer unpushed commits in a worktree returned by a+ `WorktreeCreate` hook. Even an untouched session gets a Keep / Remove+ prompt, with Keep selected by default. This also applies when the hook+ reopens an existing worktree. Keep leaves the checkout and branch intact;+ Remove invokes `WorktreeRemove`, which uses normal `wt remove` safeguards.+2. **It enters an existing branch's worktree.** The dispatcher uses `wt switch`+ without `--create`, creating the checkout if needed.3. **It only works on a session's first entry, and only in its own repo.** Froma session already in a worktree it returns "Already in a worktree session.Pass `path` to switch into another existing worktree", and it has no `-C`.-Each failure names the route out, which is why step 3 needs no pre-check: try-the cheap call, read the error, fall back. The hook contract (stdout's last-non-empty line must be an existing directory) stays the hook's business, since-the skill reads only the tool result.+Step 3 handles repo targeting and a session's later entries. Other hook+failures surface directly, with no git fallback: the hook replaces the default+git behavior. The hook contract (stdout's last non-empty line must be an+existing directory) stays the hook's business, since the skill reads only the+tool result.### Why escalate instead of grinding through absolute paths@@ -316,21 +309,6 @@ fires only on an actual reset. Cheap to attempt, and the handback is actionableand durable (a `~/workspace` entry, set once, covers every future cross-repotask).-## The hooks.json pipefail wrapper (agent-isolation path, not this skill)--`WorktreeCreate` pipes `jq | xargs wt | jq`; without `pipefail` the trailing-`jq` exits 0 on empty input and swallows a `wt` failure, so Claude Code saw a-"successful" hook with no path. Hook commands are spawned with an empty args-array and `shell: true` (binary), i.e. `/bin/sh -c` on Unix β bash 3.2 on-macOS but dash on many Linuxes. dash rejects `set -o pipefail` fatally-(`set` is a POSIX special builtin; no dash release through 0.5.12 supports-pipefail β only post-0.5.12 upstream git and distro backports such as-Debian's 0.5.12-7). And `/bin/sh -c` is evidently not universal: one user's-hooks ran under fish (worktrunk PR #2962), which has no shell options at-all. Hence the explicit `bash -c 'set -o pipefail; β¦'` wrapper. Verified-end-to-end: success prints the path and exits 0; an existing-branch failure-exits 1 with empty stdout.-## Known limits (deliberate)- Another repo is reachable only through `additionalDirectories` ("How they@@ -347,7 +325,3 @@ exits 1 with empty stdout.- A subagent's `cd` doesn't carry to its next call, and it gets no reset notice(M1), so from a subagent step 3 can't enter another repo's worktree: theentry reaches the hook with the subagent's own repo as `cwd`.-- `wt switch --create` is not idempotent. If that ever changes upstream- (enter-if-exists), step 3's existing-branch retry collapses to nothing, and- the hook stops failing on an existing branch, which removes one of the two- reasons step 3 exists.diff --git a/skills/wt-switch-create/SKILL.md b/skills/wt-switch-create/SKILL.mdindex 2b084ef18..95dc6bcfb 100644--- a/skills/wt-switch-create/SKILL.md+++ b/skills/wt-switch-create/SKILL.md@@ -46,15 +46,16 @@ read-only task gets one all the same.<!-- Maintainers: rationale.md (same directory) covers the harness rules anddesign choices behind this β read it before re-adding guards or routes. -->-1. **Pick the branch name** if none was given: short, from the task and+1. **Pick a new branch name** if none was given: short, from the task andconsistent with existing worktree names, or, mid-session, from the workbeing moved; with nothing to derive from, ask.2. **With no repo argument, create and enter in one call:**`EnterWorktree({name: "<branch>"})`. Worktrunk's `WorktreeCreate` hook runs- `wt switch --create`, so the result is an ordinary `wt` worktree in the- default layout, and the user sees no confirmation prompt. On success,- do the task (or, with no task text, confirm it's ready and wait).+ `wt switch --create` for a new branch or `wt switch` for an existing one,+ creating its checkout if needed. The result is an ordinary `wt` worktree,+ and the user sees no confirmation prompt. On success, do the task (or,+ with no task text, confirm it's ready and wait).Mid-session, carry uncommitted work across: `git stash push -u` before the`EnterWorktree` call, then `git stash pop` after β the call re-roots the@@ -62,8 +63,8 @@ design choices behind this β read it before re-adding guards or routes. -->3. **Otherwise create it with `wt` and enter by path.** Two cases reach here: arepo argument, which step 2 can't target, and a failed step 2, whose error- says which β `β Branch <branch> already exists`, or `Already in a worktree- session`. Create with a `Bash` call (omit `-C <repo>` for this repo):+ says `Already in a worktree session`. Create with a `Bash` call (omit+ `-C <repo>` for this repo):```wt -C <repo> switch --create <branch> --no-cd --format=jsondiff --git a/skills/wt-switch-create/rationale.md b/skills/wt-switch-create/rationale.mdindex bafbfe9e7..fe518af5e 100644--- a/skills/wt-switch-create/rationale.md+++ b/skills/wt-switch-create/rationale.md@@ -12,6 +12,7 @@ repo). Entry β the confirmation, both `EnterWorktree` routes, and what eachleaves behind at exit β was re-run live on 2026-07-28 against Claude Code2.1.220 and wt v0.69.2. The confirmation hook and `cd`-before-entry for anotherrepo were verified live on 2026-09-16 against Claude Code 2.1.273 (#4149).+Hook-based exit cleanup was checked live on Claude Code 2.1.308 on 2026-10-22.Re-verify against current versions before relying on a specific behavior; the*shape* of the argument should outlive the details.Binary symbol names are deliberately omitted β they re-minify every build.@@ -21,11 +22,11 @@ Binary symbol names are deliberately omitted β they re-minify every build.Steps are numbered as in `SKILL.md`; step 1, picking the branch name, needsno rationale.-2. `EnterWorktree({name})` for a new branch in this repo. It creates through- worktrunk's `WorktreeCreate` hook (`wt switch --create`), so the result is- an ordinary `wt` worktree, and it passes no `path`, which is what keeps M2's- confirmation from firing. It fails on an existing branch and from a session- that already entered a worktree, and it has no repo targeting.+2. `EnterWorktree({name})` in this repo. Worktrunk's `WorktreeCreate` hook runs+ `wt switch --create` for a new branch or `wt switch` for an existing one,+ creating its checkout if needed. Passing no `path` keeps M2's confirmation+ from firing. It fails from a session that already entered a worktree, and+ it has no repo targeting.3. Otherwise `wt -C <repo> switch --create <branch> --no-cd --format=json` inBash, then, for another repo, `cd <repo>`, then `EnterWorktree({path})`.`wt` solves repo targeting (`-C` works from anywhere), existing-branch@@ -167,13 +168,13 @@ Verified: from a worktrunk session, `cd` into a prql worktree under `/tmp`, then### The confirmation hook-The plugin's `PermissionRequest` command runs the hidden-`wt config plugins claude approve-enter-worktree`, which reads the hook payload-and prints an `allow` decision when the call is `EnterWorktree` and its `path`-is a worktree of the repository the payload's `cwd` is in, at the path the-`worktree-path` template gives its branch. Anything else leaves stdout empty-and exits 1, which leaves the dialog (or, where no dialog can show, the denial)-in place. The tool's own validation still runs after an approval.+The plugin's hooks run the hidden `wt config plugins claude hook`, which reads+the hook payload. For `PermissionRequest` it prints an `allow` decision when+the call is `EnterWorktree` and its `path` is a worktree of the repository the+payload's `cwd` is in, at the path the `worktree-path` template gives its+branch. Anything else leaves stdout empty, which leaves the dialog (or, where+no dialog can show, the denial) in place. The tool's own validation still runs+after an approval.The rule extends Claude Code's exemption rather than overriding its check.Claude Code enters a worktree under `.claude/worktrees/` without asking because@@ -193,17 +194,16 @@ another repo before entering. The check lives in `wt` because it is`branch_mismatch`; a script over `wt list --format=json` would inherit thatcommand's user config, where `list.full` adds CI fetches and LLM summaries(33s measured on a 54-worktree repository) and `list.json-schema` and `list.branches` change-the output's shape. A `wt` too old to have the subcommand fails it, which-leaves the dialog as it was before the hook existed.--The approval shares one `hooks.json` command with the π¬ marker,-`wt β¦ approve-enter-worktree || wt β¦ marker set π¬`, because Claude Code runs-all matching hooks in parallel. A separate `EnterWorktree` entry would still-fire the catch-all marker hook, and the launch worktree would read π¬ while the-session works on. With one command, an approval skips the marker and every-other permission request sets it as before. The `permission_prompt`-notification can't set it either: Claude Code sends it only after a shown-prompt has waited about six seconds.+the output's shape. A `wt` too old to have the subcommand fails it, and the+hook command's `|| true` leaves the dialog as it was before the hook existed.++The approval shares one hook with the π¬ marker, setting the marker only when+it doesn't approve, because Claude Code runs all matching hooks in parallel. A+separate `EnterWorktree` entry would still fire the catch-all marker hook, and+the launch worktree would read π¬ while the session works on. With one hook,+an approval skips the marker and every other permission request sets it as+before. The `permission_prompt` notification can't set it either: Claude Code+sends it only after a shown prompt has waited about six seconds.Verified live in `--permission-mode default` sessions: a same-repo entry, and across-repo entry after `cd`, both reported "Allowed by PermissionRequest hook"@@ -272,32 +272,25 @@ integrated machine and a no-op elsewhere. Don't drop it.The `name` route is worth having because it never asks M2's confirmation, withor without worktrunk's hook, and it creates and enters in one call. The sameplugin hook backs `isolation: "worktree"` agents, so the worktree it produces is-the one `wt` would have made either way. Three properties come with it, all-verified live:--1. **An untouched worktree is cleaned up at exit, branch included.** With no- changed files, no commits, and no user-set session title, the exiting- session removes it through the plugin's `WorktreeRemove` hook, which is- `wt remove`, so a clean fully-merged branch goes too. Verified end-to-end:- `EnterWorktree({name: "probe"})`, then `/exit`, leaves neither `repo.probe`- nor the `probe` branch; one untracked file is enough for exit to report- "Keeping worktreeβ¦" and leave both. This is a feature at this scale β a- research task that wrote nothing leaves nothing to prune β and it is the- reason step 2's worktrees are not described as durable. Path-entered- worktrees are always left in place ("worktree at <path> left in place").-2. **It hard-fails on an existing branch.** The hook runs `wt switch --create`,- and a nonzero hook exit fails creation outright, with no git fallback- (binary: "Other exit codes - worktree creation failed"; docs: "the hook- replaces the default git behavior"). The failure is clean: `wt`'s own- `β Branch <branch> already exists` surfaces and nothing is created.+the one `wt` would have made either way. Three properties come with it:++1. **Exit asks whether to keep or remove a hook-created worktree.** Claude+ Code 2.1.308 cannot infer unpushed commits in a worktree returned by a+ `WorktreeCreate` hook. Even an untouched session gets a Keep / Remove+ prompt, with Keep selected by default. This also applies when the hook+ reopens an existing worktree. Keep leaves the checkout and branch intact;+ Remove invokes `WorktreeRemove`, which uses normal `wt remove` safeguards.+2. **It enters an existing branch's worktree.** The dispatcher uses `wt switch`+ without `--create`, creating the checkout if needed.3. **It only works on a session's first entry, and only in its own repo.** Froma session already in a worktree it returns "Already in a worktree session.Pass `path` to switch into another existing worktree", and it has no `-C`.-Each failure names the route out, which is why step 3 needs no pre-check: try-the cheap call, read the error, fall back. The hook contract (stdout's last-non-empty line must be an existing directory) stays the hook's business, since-the skill reads only the tool result.+Step 3 handles repo targeting and a session's later entries. Other hook+failures surface directly, with no git fallback: the hook replaces the default+git behavior. The hook contract (stdout's last non-empty line must be an+existing directory) stays the hook's business, since the skill reads only the+tool result.### Why escalate instead of grinding through absolute paths@@ -316,21 +309,6 @@ fires only on an actual reset. Cheap to attempt, and the handback is actionableand durable (a `~/workspace` entry, set once, covers every future cross-repotask).-## The hooks.json pipefail wrapper (agent-isolation path, not this skill)--`WorktreeCreate` pipes `jq | xargs wt | jq`; without `pipefail` the trailing-`jq` exits 0 on empty input and swallows a `wt` failure, so Claude Code saw a-"successful" hook with no path. Hook commands are spawned with an empty args-array and `shell: true` (binary), i.e. `/bin/sh -c` on Unix β bash 3.2 on-macOS but dash on many Linuxes. dash rejects `set -o pipefail` fatally-(`set` is a POSIX special builtin; no dash release through 0.5.12 supports-pipefail β only post-0.5.12 upstream git and distro backports such as-Debian's 0.5.12-7). And `/bin/sh -c` is evidently not universal: one user's-hooks ran under fish (worktrunk PR #2962), which has no shell options at-all. Hence the explicit `bash -c 'set -o pipefail; β¦'` wrapper. Verified-end-to-end: success prints the path and exits 0; an existing-branch failure-exits 1 with empty stdout.-## Known limits (deliberate)- Another repo is reachable only through `additionalDirectories` ("How they@@ -347,7 +325,3 @@ exits 1 with empty stdout.- A subagent's `cd` doesn't carry to its next call, and it gets no reset notice(M1), so from a subagent step 3 can't enter another repo's worktree: theentry reaches the hook with the subagent's own repo as `cwd`.-- `wt switch --create` is not idempotent. If that ever changes upstream- (enter-if-exists), step 3's existing-branch retry collapses to nothing, and- the hook stops failing on an existing branch, which removes one of the two- reasons step 3 exists.diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex f265180ba..57dcda35c 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -5770,110 +5770,66 @@ fn test_plugin_layout_is_consolidated() {}assert!(skill_dirs > 0, "skills/ holds no skill directories");- // The WorktreeRemove hook must not force-delete unmerged branches (#2939).- // Claude Code auto-fires WorktreeRemove on session exit for any worktree- // with a clean working tree, so a hook command containing `-D` /- // `--force-delete` silently discards committed-but-unpushed work β the only- // recovery path is `git fsck`. The safe default retains unmerged branches- // and prints a `wt remove -D <branch>` hint for the user to act on.- let hooks = read("plugins/worktrunk/hooks/hooks.json");let hooks_json = json("plugins/worktrunk/hooks/hooks.json");-- // Claude hands each hook command to the user's LOGIN shell before `bash`- // launches, so the outer command line must parse under fish/zsh/bash. fish- // rejects bash brace syntax ("Variables cannot be bracketed"), so the plugin- // root must be referenced as `$CLAUDE_PLUGIN_ROOT`, never `${CLAUDE_PLUGIN_ROOT}`.- let all_commands: Vec<&str> = hooks_json["hooks"]+ let commands: Vec<(&str, &str)> = hooks_json["hooks"].as_object().expect("hooks.json must have a `hooks` object")- .values()- .flat_map(|event| event.as_array().expect("each hook event must be an array"))- .flat_map(|group| {- group["hooks"]+ .iter()+ .flat_map(|(event, groups)| {+ groups.as_array()- .expect("each hook group must have a `hooks` array")- })- .map(|hook| {- hook["command"]- .as_str()- .expect("each hook must define a command")+ .expect("each hook event must be an array")+ .iter()+ .flat_map(|group| {+ group["hooks"]+ .as_array()+ .expect("each hook group must have a `hooks` array")+ })+ .map(move |hook| {+ (+ event.as_str(),+ hook["command"]+ .as_str()+ .expect("each hook must define a command"),+ )+ })}).collect();- for cmd in &all_commands {- assert!(- cmd.contains("$CLAUDE_PLUGIN_ROOT") && !cmd.contains("${CLAUDE_PLUGIN_ROOT}"),- "hook command must use unbraced $CLAUDE_PLUGIN_ROOT (braces break fish \- login-shell parsing: \"fish: Variables cannot be bracketed\"). command:\n{cmd}"- );- }- let marker_commands = all_commands- .iter()- .filter(|command| command.contains("config state marker"))- .collect::<Vec<_>>();+ // Every hook runs the same literal command: `wt config plugins claude+ // hook` reads Claude Code's payload and dispatches on the event, so the+ // behavior lives in `wt` and is tested in `claude_hook.rs`. Anthropic's+ // plugin directory refuses a hook command whose path the shell computes or+ // that carries an inline program. The root stays unbraced: Claude hands+ // each command to the user's login shell before `bash` launches, and fish+ // rejects `${CLAUDE_PLUGIN_ROOT}` ("Variables cannot be bracketed"). The+ // marker events end in `|| true`: a `wt` too old to have `hook` exits 2,+ // which Claude Code reads as blocking the prompt, tool call, permission,+ // or stop. The worktree events must fail when `wt` does.+ const HOOK: &str = r#"bash "$CLAUDE_PLUGIN_ROOT/hooks/wt.sh" config plugins claude hook"#;+ let mut events: Vec<&str> = commands.iter().map(|(event, _)| *event).collect();+ events.sort_unstable();assert_eq!(- marker_commands.len(),- 6,- "expected all 6 Claude marker hooks (UserPromptSubmit, Notification, \- PreToolUse, PermissionRequest, Stop, SessionEnd); a newly added one \- must be pinned too. hooks.json:\n{hooks}"+ events,+ [+ "Notification",+ "PermissionRequest",+ "PreToolUse",+ "SessionEnd",+ "Stop",+ "UserPromptSubmit",+ "WorktreeCreate",+ "WorktreeRemove",+ ]);- for command in marker_commands {- assert!(- command.contains(r#"-C "$CLAUDE_PROJECT_DIR""#),- "marker hook must pin the directory it resolves against, or a shell \- `cd` during a turn retargets it to another repository (#3921). \- command:\n{command}"- );+ for (event, command) in &commands {+ let expected = if event.starts_with("Worktree") {+ HOOK.to_string()+ } else {+ format!("{HOOK} || true")+ };+ assert_eq!(*command, expected, "{event} hook command drifted");}- let worktree_remove_cmd = hooks_json["hooks"]["WorktreeRemove"][0]["hooks"][0]["command"]- .as_str()- .expect("WorktreeRemove hook must define a command");- assert!(- !worktree_remove_cmd.contains(" -D") && !worktree_remove_cmd.contains("--force-delete"),- "WorktreeRemove hook must not pass -D / --force-delete (silently destroys \- committed-but-unpushed work on session-exit auto-remove; see #2939). \- hooks.json:\n{hooks}"- );-- // The WorktreeRemove hook must resolve against the worktree path Claude- // Code hands it, not the session's project dir. The `claude agents` view- // spans every repo with a background session and is often launched from a- // parent directory that merely contains them, so `CLAUDE_PROJECT_DIR` names- // the wrong repo or none at all, `wt remove <path>` dies with `fatal: not a- // git repository`, and the session row is left undeletable (#3754, after- // the #3489 anchor proved insufficient). `-C "$p"` is layout-independent: a- // linked worktree carries a `.git` file pointing at its owning repository.- assert!(- worktree_remove_cmd.contains("-C \"$p\"")- && !worktree_remove_cmd.contains("CLAUDE_PROJECT_DIR"),- "WorktreeRemove hook must resolve via -C \"$p\" (the worktree path Claude Code \- handed it), never CLAUDE_PROJECT_DIR β the agents view is multi-repo, so no \- single project dir is correct for every session (#3754). \- command:\n{worktree_remove_cmd}"- );-- // The WorktreeCreate hook pipes `wt β¦ --format=json | jq -er .path`. Without- // `set -o pipefail` the pipeline's exit status is jq's, and `jq -er .path`- // on the empty stdout of a failed `wt` exits 0 on jq 1.6 β so a `wt` failure- // (e.g. an existing-branch collision after the branch/worktree were already- // created) is swallowed and Claude Code reports the misleading "hook- // succeeded but returned no worktree path" instead of wt's real error- // (#3545). pipefail makes the pipeline surface wt's nonzero exit regardless- // of jq version. The wrapper must be `bash -c` (dash rejects `set -o- // pipefail` fatally; some login shells are fish, which has no shell options)- // β see skills/wt-switch-create/rationale.md, "The hooks.json pipefail wrapper".- let worktree_create_cmd = hooks_json["hooks"]["WorktreeCreate"][0]["hooks"][0]["command"]- .as_str()- .expect("WorktreeCreate hook must define a command");- assert!(- worktree_create_cmd.contains("set -o pipefail"),- "WorktreeCreate hook pipes `wt β¦ | jq -er .path`; without `set -o pipefail` a \- failed wt with empty stdout is swallowed (jq 1.6 exits 0 on empty input) and \- Claude Code reports \"hook succeeded but returned no worktree path\" instead \- of wt's real error (#3545). command:\n{worktree_create_cmd}"- );-// The product description must not drift across tools. Byte-identical is// schema-impossible (Codex omits the activity clause, Gemini says// "extension"), but every manifest shares the canonical opening sentence.@@ -6371,7 +6327,7 @@ fn test_claude_hook_commands_parse_in_all_shells() {/// directions are pinned below β a skeleton is a no-op, a clean worktree is/// still removed, a dirty one still fails β so neither a blanket `exit 0` nor a/// swallowed `wt remove` failure can satisfy this test. It runs the real command-/// out of `hooks.json`, which parses its stdin with `jq`.+/// out of `hooks.json`.#[cfg(all(unix, feature = "shell-integration-tests"))]#[rstest]fn test_worktree_remove_hook_skips_path_holding_no_worktree(mut repo: TestRepo) {@@ -6396,9 +6352,8 @@ fn test_worktree_remove_hook_skips_path_holding_no_worktree(mut repo: TestRepo)// Fire the hook exactly as Claude Code does: the recorded path on stdin, the// plugin root in the environment. No `CLAUDE_PROJECT_DIR` β the hook- // resolves the repository from the worktree path via `-C "$p"` and must- // never consult a project dir (#3754), so setting one here would be dead- // setup.+ // resolves the repository from the worktree path and must never consult a+ // project dir (#3754), so setting one here would be dead setup.let run_hook = |worktree_path: &Path| -> Output {let mut cmd = std::process::Command::new("bash");repo.configure_wt_cmd(&mut cmd);@@ -6412,7 +6367,10 @@ fn test_worktree_remove_hook_skips_path_holding_no_worktree(mut repo: TestRepo).stderr(Stdio::piped()).spawn().expect("failed to spawn bash");- let payload = serde_json::json!({ "worktree_path": worktree_path.to_str().unwrap() });+ let payload = serde_json::json!({+ "hook_event_name": "WorktreeRemove",+ "worktree_path": worktree_path.to_str().unwrap(),+ });child.stdin.take()