Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(plugin): optional branch name and single-route flow for /wt-switch-create (#3058)
Maximilian Roosfd3ae5bff460
diff --git a/docs/content/claude-code.md b/docs/content/claude-code.mdindex b2c2ec82d..3439a1a5a 100644--- a/docs/content/claude-code.md+++ b/docs/content/claude-code.md@@ -16,7 +16,7 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de| Worktree isolation | ✓ | | | || `/wt-switch-create` command | ✓ | | | |-The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation and `/wt-switch-create` need worktree-lifecycle hooks that only Claude Code exposes, so Codex, OpenCode, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex omits activity tracking because its hooks have no turn-end event, so a 🤖 marker could never clear back to 💬.+The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks and `/wt-switch-create` needs session working-directory switching — both Claude Code-only, so Codex, OpenCode, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex omits activity tracking because its hooks have no turn-end event, so a 🤖 marker could never clear back to 💬.## Installation@@ -101,9 +101,7 @@ Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By d## `/wt-switch-create` command (Claude Code only)-`/wt-switch-create <branch> [<repo>] [-- <task>]` starts work in a fresh worktree without leaving the session. It creates (or re-enters) the named worktrunk worktree — sibling layout `<repo>.<branch>/`, not `.claude/worktrees/` — switches the session's working directory into it, then runs the task there. An optional second token names a different repository to create the worktree in; the task is whatever follows `--` (or, with no `--`, whatever follows the branch). The command rides the same `WorktreeCreate` hook as agent isolation, so the worktree gets worktrunk's naming, hooks, and lifecycle.--On session exit the worktree is offered for removal via the `WorktreeRemove` hook; one with uncommitted changes is kept rather than removed.+`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts work in a fresh worktree without leaving the session. It creates (or re-enters) a worktrunk worktree with `wt switch`, switches the session's working directory into it, then runs the task there. Every argument is optional: a missing branch name is picked from the task, a path-shaped token names a different repository, and the task is whatever follows `--` (or the trailing words, when there is no `--`). The worktree is a normal worktrunk worktree — it persists after the session and is merged or removed with `wt merge` / `wt remove` like any other.## Statusline (Claude Code only)diff --git a/plugins/worktrunk/CLAUDE.md b/plugins/worktrunk/CLAUDE.mdindex 19fee203f..1f1218fc2 100644--- a/plugins/worktrunk/CLAUDE.md+++ b/plugins/worktrunk/CLAUDE.md@@ -73,4 +73,4 @@ Re-add a Codex `hooks.json`, the `hooks` manifest key, the install hints in `src### Accepted tradeoff: shared `skills/` exposes `wt-switch-create`-Codex's `"skills": "./skills/"` and Gemini's `${extensionPath}/skills/` both resolve the entire repo-root `skills/`, including `wt-switch-create`, which depends on Claude session-cwd switching and the `WorktreeCreate` hook neither provides. Accepted: a tool loading a skill it can't act on is harmless, and a single repo-root `skills/` keeps the `worktrunk` skill single-source across all three tools and the docs sync. Don't add per-tool skills subtrees to exclude it.+Codex's `"skills": "./skills/"` and Gemini's `${extensionPath}/skills/` both resolve the entire repo-root `skills/`, including `wt-switch-create`, which depends on Claude session-cwd switching (`EnterWorktree`) that neither provides. Accepted: a tool loading a skill it can't act on is harmless, and a single repo-root `skills/` keeps the `worktrunk` skill single-source across all three tools and the docs sync. Don't add per-tool skills subtrees to exclude it.diff --git a/plugins/worktrunk/README.md b/plugins/worktrunk/README.mdindex 98937bbeb..246c45e4a 100644--- a/plugins/worktrunk/README.md+++ b/plugins/worktrunk/README.md@@ -26,4 +26,4 @@ The skill configures `.config/wt.toml` with project hooks. Pre-start hooks run w**Start work in a fresh worktree**-`/wt-switch-create fix-auth Investigate the 5-minute session timeout` creates a `fix-auth` worktree in worktrunk's normal sibling layout (`<repo>.fix-auth/`), switches the session into it, and starts the task there. On session exit the worktree is offered for removal — a worktree with uncommitted changes is kept rather than removed.+`/wt-switch-create fix-auth Investigate the 5-minute session timeout` creates a `fix-auth` worktree in worktrunk's normal sibling layout (`<repo>.fix-auth/`), switches the session into it, and starts the task there. The branch name is optional (`/wt-switch-create -- <task>`). The worktree persists after the session — merge or remove it with `wt merge` / `wt remove` like any other.diff --git a/plugins/worktrunk/hooks/hooks.json b/plugins/worktrunk/hooks/hooks.jsonindex 79f27839a..d0fbf5acf 100644--- a/plugins/worktrunk/hooks/hooks.json+++ b/plugins/worktrunk/hooks/hooks.json@@ -69,7 +69,7 @@"hooks": [{"type": "command",- "command": "jq -r '.name' | xargs -I{} bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" switch --create {} --no-cd --format=json | jq -r '.path'"+ "command": "bash -c 'set -o pipefail; jq -r .name | xargs -I{} bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" switch --create {} --no-cd --format=json | jq -r .path'"}]}@@ -79,7 +79,7 @@"hooks": [{"type": "command",- "command": "jq -r '.worktree_path' | xargs bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" remove --foreground"+ "command": "bash -c 'set -o pipefail; jq -r .worktree_path | xargs -I{} bash \"$CLAUDE_PLUGIN_ROOT/hooks/wt.sh\" remove --foreground {}'"}]}diff --git a/skills/worktrunk/reference/claude-code.md b/skills/worktrunk/reference/claude-code.mdindex b26761841..f13b9f7c7 100644--- a/skills/worktrunk/reference/claude-code.md+++ b/skills/worktrunk/reference/claude-code.md@@ -9,7 +9,7 @@ Worktrunk ships a plugin for each supported agent CLI. What a plugin provides de| Worktree isolation | ✓ | | | || `/wt-switch-create` command | ✓ | | | |-The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation and `/wt-switch-create` need worktree-lifecycle hooks that only Claude Code exposes, so Codex, OpenCode, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex omits activity tracking because its hooks have no turn-end event, so a 🤖 marker could never clear back to 💬.+The configuration skill is documentation the agent reads to help set up LLM commits, hooks, and troubleshooting. Activity tracking shows which worktrees have running sessions. Worktree isolation needs worktree-lifecycle hooks and `/wt-switch-create` needs session working-directory switching — both Claude Code-only, so Codex, OpenCode, and Gemini users invoke `wt switch --create` and `wt remove` directly. Codex omits activity tracking because its hooks have no turn-end event, so a 🤖 marker could never clear back to 💬.## Installation@@ -103,9 +103,7 @@ Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By d## `/wt-switch-create` command (Claude Code only)-`/wt-switch-create <branch> [<repo>] [-- <task>]` starts work in a fresh worktree without leaving the session. It creates (or re-enters) the named worktrunk worktree — sibling layout `<repo>.<branch>/`, not `.claude/worktrees/` — switches the session's working directory into it, then runs the task there. An optional second token names a different repository to create the worktree in; the task is whatever follows `--` (or, with no `--`, whatever follows the branch). The command rides the same `WorktreeCreate` hook as agent isolation, so the worktree gets worktrunk's naming, hooks, and lifecycle.--On session exit the worktree is offered for removal via the `WorktreeRemove` hook; one with uncommitted changes is kept rather than removed.+`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts work in a fresh worktree without leaving the session. It creates (or re-enters) a worktrunk worktree with `wt switch`, switches the session's working directory into it, then runs the task there. Every argument is optional: a missing branch name is picked from the task, a path-shaped token names a different repository, and the task is whatever follows `--` (or the trailing words, when there is no `--`). The worktree is a normal worktrunk worktree — it persists after the session and is merged or removed with `wt merge` / `wt remove` like any other.## Statusline (Claude Code only)diff --git a/skills/wt-switch-create/SKILL.md b/skills/wt-switch-create/SKILL.mdindex 939ffb9fc..881c7024f 100644--- a/skills/wt-switch-create/SKILL.md+++ b/skills/wt-switch-create/SKILL.md@@ -1,67 +1,90 @@---name: wt-switch-create-description: Create a new worktrunk worktree (optionally in another repo) and switch this session's working directory into it. Use when launching a session that should work in its own worktree (e.g. `/wt-switch-create my-branch -- <task>`, or `/wt-switch-create my-branch ~/workspace/other-repo -- <task>`), or mid-session to move work into a fresh branch.-argument-hint: "<branch-name> [<repo>] [-- task...]"+description: Create a new worktrunk worktree (optionally in another repo) and switch this session's working directory into it. The branch name is optional — one is picked from the task when omitted. Use when launching a session that should work in its own worktree (e.g. `/wt-switch-create -- <task>`, `/wt-switch-create my-branch -- <task>`, or `/wt-switch-create my-branch ~/workspace/other-repo -- <task>`), or mid-session to move work into a fresh branch.+argument-hint: "[<branch>] [<repo>] [-- <task>]"license: MIT OR Apache-2.0-compatibility: Requires the `wt` CLI (https://worktrunk.dev) and this plugin's WorktreeCreate hook+compatibility: Requires the `wt` CLI (https://worktrunk.dev)----Arguments: `$ARGUMENTS`. Grammar: `<branch> [<repo>] [-- <task>]`.+Arguments: `$ARGUMENTS`. Grammar: `[<branch>] [<repo>] [-- <task>]`.-- **branch** — required first token; the branch name for the new worktree.+- **branch** — optional; the branch name for the new worktree. When omitted,+ pick one (step 1 below).- **repo** — optional path; create the worktree in this repo instead of thesession's current one.- **task** — optional; what to do inside the new worktree. No task means enterthe worktree and wait.-Without a `--`: a path-shaped second token (absolute, `~`-relative, `./`- or-`../`-relative, or an existing directory) is the repo, and the task starts-after it. Otherwise the task starts at the second token.+Tokens before the `--` are the branch and/or repo: a path-shaped token+(starting with `/`, `~`, `./`, or `../`) is the repo; any other token is the+branch (`docs` is a branch name, never the `docs/` directory). More than one+branch-shaped token before a `--` doesn't fit the grammar — ask. Without a+`--`, judge where the task starts: leading tokens that read as a branch name+(`fix-auth`) or a repo path are consumed as such, and the rest is the task;+otherwise the whole input is the task (`fix the parser bug` has no+branch-shaped lead — all task).```/wt-switch-create my-feature -- fix the parser bug+/wt-switch-create -- fix the parser bug/wt-switch-create my-feature ~/workspace/other-repo -- fix the parser bug/wt-switch-create my-feature```## What to do-1. **First action — before reading any files or running any commands:**-- - If a repo was given, `cd` into it first with a `Bash` call (the working- directory persists for the rest of the session). `EnterWorktree` has no- repo parameter — it creates the worktree wherever the session is rooted.- - Then call `EnterWorktree({name: "<branch-name>"})`. This re-roots the- session into the new worktree. If a repo was given, confirm the new- worktree landed under it; if not, the `cd` didn't take — report it and- stop.- - It works because this plugin maps `WorktreeCreate` →- `wt switch --create <name> --no-cd --format=json`, so the new worktree- lands in worktrunk's normal sibling layout (`<repo>.<branch>/`), not under- `.claude/worktrees/`.- - `wt switch --create` is idempotent: if the branch already exists, this- just re-enters its worktree.- - If you are *already* inside an `EnterWorktree`-created worktree (e.g. the- background harness isolated this session), **skip `EnterWorktree`** — it- refuses to nest. Reuse the existing worktree and continue. But if a repo- was given and that worktree belongs to a different repo, you can't honor- it — say so and stop rather than running the task in the wrong repo.- - If `EnterWorktree` fails (not a git repo, invalid branch name, etc.),- report the error and stop — do not fall back to working in the original- directory, since that defeats the purpose.--2. After the cwd switch succeeds, do the task in the new worktree. If there was- no task text, confirm the worktree is ready and wait for the next- instruction.+Steps 1–3 come before any other work.++<!-- Maintainers: the design choices here are backed by tested evidence in+rationale.md (same directory) — read it before re-adding guards or routes. -->++1. **Pick the branch name** if none was given: short kebab-case from the task+ ("fix the parser bug" → `fix-parser-bug`) or, mid-session, from the work+ being moved; with nothing to derive from, ask.++2. **Create the worktree** with a `Bash` call (omit `-C <repo>` when no repo+ was given):++ ```+ wt -C <repo> switch --create <branch> --no-cd --format=json+ ```++ Stdout is JSON whose `path` field is the worktree's absolute path (status+ lines go to stderr). On `Branch <branch> already exists`:++ - the user named the branch → rerun the same command without `--create`;+ it enters the existing branch, creating its worktree if missing.+ - the name was picked in step 1 → the user never chose that branch; pick+ another name and rerun.++ Any other failure (not a git repo, invalid name): report it and stop — do+ not do the task in the original directory.++ Mid-session, when the work to move is uncommitted in the current worktree,+ carry it across: `git stash push -u` before creating the worktree, then+ `git -C <path> stash pop` after (the stash is shared across worktrees).++3. **Re-root the session** with `EnterWorktree({path: "<path from the JSON>"})`.++ If it is rejected (worktree in a different repo, session already in a+ worktree, pinned cwd — the rejections are graceful and create nothing),+ leave the session rooted where it is and work in the worktree through+ absolute paths instead; name the worktree path when reporting back. Don't+ try to `cd` there: the harness resets `cd` that leaves the session's+ working directories, and `EnterWorktree` is the supported way to move a+ session.++4. **Do the task** in the worktree. If there was no task text, confirm the+ worktree is ready and wait for the next instruction.## Cleanup-Don't remove the worktree yourself. `ExitWorktree({action: "remove"})` (if the-user asks to leave) or the session-exit prompt routes through this plugin's-`WorktreeRemove` hook → `wt remove --foreground`. A worktree with uncommitted-changes won't be auto-removed without confirmation — that's intended. A branch-with committed-but-unmerged work is retained (with a `wt remove -D <branch>`-hint) instead of being silently force-deleted.+The worktree is a normal worktrunk worktree: it persists after the session+ends, shows up in `wt list`, and is merged or removed with `wt merge` /+`wt remove <branch>` like any other. Don't remove it unprompted. If the user+asks to leave mid-session, `ExitWorktree({action: "keep"})` returns the+session to its original directory; `ExitWorktree` cannot remove a worktree+entered by `path`, so removal is always `wt remove <branch>`.## Scopediff --git a/skills/wt-switch-create/rationale.md b/skills/wt-switch-create/rationale.mdnew file mode 100644index 000000000..54877f3f6--- /dev/null+++ b/skills/wt-switch-create/rationale.md@@ -0,0 +1,148 @@+# wt-switch-create design rationale++Why the skill is one route (`wt` in Bash → `EnterWorktree({path})`) plus one+error-driven fallback, and not the guard-heavy multi-route flow it replaced.+Every claim here was verified against primary sources on 2026-06-11:+Claude Code 2.1.173 (binary inspection + live tool calls + official docs at+code.claude.com/docs) and wt v0.57.0-16-g371d28662 (live runs in a scratch+repo). Re-verify against current versions before relying on a specific+behavior; the *shape* of the argument should outlive the details.++## The design++1. Create the worktree with `wt -C <repo> switch --create <branch> --no-cd+ --format=json` in Bash. `wt` already solves repo targeting (`-C`),+ existing-branch handling (rerun without `--create`), and machine-readable+ output (`.path` on stdout, status on stderr).+2. Re-root the session with `EnterWorktree({path})` — the only supported way+ to move a Claude Code session's root.+3. If (2) is rejected, work in the worktree via absolute paths. Every+ rejection is a graceful, side-effect-free error, so one attempt plus a+ fallback covers every environment without predicting which one we're in.++## wt CLI and git behavior (all live-tested)++- `wt switch --create <branch>` exits 1 with `✗ Branch <branch> already+ exists` whenever the branch exists, with or without a worktree. Its own+ hint names the fix: rerun without `--create`.+- `wt switch <branch>` (no `--create`) exits 0 for an existing branch: it+ creates the worktree if missing (`"action":"created","created_branch":false`)+ or re-enters it (`"action":"existing"`). Per `wt switch --help`: "Without+ --create, the branch must already exist."+- Every `--format=json` variant carries `path` (absolute). Only the JSON goes+ to stdout; all human-readable status, including hook output, goes to stderr —+ which is what makes `.path` extraction safe.+- `wt -C <repo>` works from an unrelated cwd, so the skill never needs `cd`+ to create a worktree in another repo.+- `wt remove`: dirty worktree → refuses (exit 1, hints `--force`); clean but+ unmerged commits → removes the worktree, keeps the branch, hints+ `wt remove -D`; clean and merged → removes worktree and branch.+- The git stash is per-repo, shared across worktrees: `git stash push -u` in+ one worktree pops cleanly in another via `git -C <path> stash pop`,+ untracked files included — the mid-session carry-across in step 2.++## Claude Code behavior++### `EnterWorktree({path})` accepts worktrunk's sibling layout (load-bearing)++On first entry from a session not already in a worktree, the path may be ANY+worktree registered in `git worktree list` of the current repo — there is no+`.claude/worktrees/` restriction. Binary: the managed-location check is+conditional (`requireManagedLocation: <already-in-worktree-session>`); the+restriction applies only when switching from inside a worktree session or+from a pinned agent. Live-tested: a background session entered+`projects.ew-path-test` (sibling layout) by path.++### Every rejection is graceful and side-effect-free++This is what lets the skill replace predictive guards with try-then-fallback.+Observed live, verbatim:++- Cross-repo: `Cannot enter worktree: <path> is not a registered worktree of+ <repo>. Run 'git -C <repo> worktree list' to see registered worktrees.`+- Nesting by name: ``Already in a worktree session. Pass `path` to switch+ into another existing worktree, or use ExitWorktree to leave this one+ before creating a new worktree.``+- Not in a repo: `Cannot enter an existing worktree: the current directory is+ not in a git repository.`+- Removing a path-entered worktree: `This session entered an existing worktree+ (<path>); it was not created by EnterWorktree, so this tool will not remove+ it. Use action: "keep" to return to <original cwd>…`++Binary-confirmed (not live-run): pinned agents (subagent `isolation:+"worktree"` or explicit cwd) can't create by `name` at all and require `path`;+their `path` entry is restricted to `.claude/worktrees/`, so sibling-layout+worktrees are rejected there too — same fallback applies.++### `cd` is not a re-rooting mechanism++The harness resets a `cd` that lands outside the session's working+directories, appending `Shell cwd was reset to <original>` to the result —+reproduced twice. Within the working directories `cd` persists and+`EnterWorktree` *does* read the moved cwd (live: after `cd /tmp`,+`EnterWorktree({path})` failed with "the current directory is not in a git+repository"). So a target repo outside the working directories can never be+reached by `cd`, which is exactly the case where a repo argument matters.+The earlier revision's "some sessions pin the cwd" was a misdiagnosis of+this reset; subagent threads additionally reset cwd between every Bash call+(binary: "Agent threads always have their cwd reset between bash calls").++### Why not `EnterWorktree({name})` + the WorktreeCreate hook++The previous revision's primary route. Rejected for the skill — the hook+itself stays; it is how `isolation: "worktree"` agents get worktrunk+worktrees:++1. **Hard-fails on existing branches.** The hook runs `wt switch --create`,+ and a nonzero hook exit fails worktree creation outright — there is no+ git fallback (binary: "Other exit codes - worktree creation failed";+ docs: "the hook replaces the default git behavior"). That forced a+ second route for existing branches; `path` entry needs no second route.+2. **No repo targeting.** `EnterWorktree({name})` creates the worktree+ wherever the session is rooted; combined with the `cd` reset above, the+ name route can never reach another repo.+3. **Wrong exit-time semantics for durable worktrees.** Worktrees created by+ `name` are tracked for session-exit cleanup: when the session has no+ user-set title, a clean worktree (no changed files, no new commits) is+ *silently auto-removed* at exit (binary: auto-remove iff zero changes,+ zero commits, and no session title; message "Worktree removed (no+ changes)"). A worktrunk worktree the user asked for should outlive the+ session (`wt list`, later `wt merge`). Path-entered worktrees get exactly+ that: left in place, no prompt ("worktree at <path> left in place").+4. **Hook contract details leak into the skill.** stdout's last non-empty+ line must be an existing directory, etc. — irrelevant when the skill reads+ `.path` from `wt --format=json` directly.++### Why no pre-emptive guards++The old flow opened with "if already inside a worktree, reuse it", a+`cd`-then-`pwd` check, and a pinned-cwd branch — each a workaround for a+hypothesis about the harness, one of which (pinned cwd) was simply wrong.+Since every `EnterWorktree` rejection above is graceful and creates nothing,+attempting it and falling back on error covers all of those environments+with zero prediction. Step 2 creates the worktree before step 3 attempts+entry, so even a rejected entry leaves a usable worktree for the fallback.++## 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)++- Cross-repo and pinned/already-in-worktree sessions cannot be re-rooted at+ all (Claude Code restriction, not a skill gap); the fallback does the task+ in the right worktree via absolute paths, which loses only the implicit+ default cwd — not any capability.+- `wt switch --create` is not idempotent. If that ever changes upstream+ (enter-if-exists), step 2's existing-branch retry collapses to nothing.