aidenlx/zotlit / .agents/skills/worktrunk
worktrunk
VerifiedGuidance for Worktrunk (the `wt` CLI) — git worktree management, hooks, and config. Load when working out which worktree a `wt` command will act on, or reaching for the global `-C <path>` to target one; editing .config/wt.toml or ~/.config/worktrunk/config.toml; adding, modifying, or debugging hooks (post-merge, post-start, pre-commit, pre-merge, post-switch, etc.); configuring commit message generation or command aliases; or troubleshooting wt behavior. Also answers general worktrunk/wt questions.
| File | Kind | Size |
|---|---|---|
| SKILL.md | skill md | 11.2 KB |
| reference/claude-code.md | markdown | 7.0 KB |
| reference/code-signing.md | markdown | 4.9 KB |
| reference/config.md | markdown | 49.9 KB |
| reference/extending.md | markdown | 12.0 KB |
| reference/faq.md | markdown | 20.4 KB |
| reference/hook.md | markdown | 20.4 KB |
| reference/list.md | markdown | 30.6 KB |
| reference/llm-commits.md | markdown | 8.2 KB |
| reference/merge.md | markdown | 7.0 KB |
| reference/remove.md | markdown | 7.4 KB |
| reference/shell-integration.md | markdown | 8.3 KB |
| reference/step.md | markdown | 30.8 KB |
| reference/switch.md | markdown | 13.3 KB |
| reference/tips-patterns.md | markdown | 20.5 KB |
| reference/troubleshooting.md | markdown | 6.4 KB |
| reference/worktrunk.md | markdown | 8.1 KB |
reference/tips-patterns.md
View on GitHub# Tips & Patterns
Practical recipes for common Worktrunk workflows.
## Setup and layout
### Shell alias for new worktree + agent
Create a worktree and launch Claude in one command:
```bash
alias wsc='wt switch --create --execute=claude'
wsc new-feature # Creates worktree, runs hooks, launches Claude
wsc feature -- 'Fix GH #322' # Runs `claude 'Fix GH #322'`
```
### Shortcuts
Special arguments work across all commands—see [`wt switch`](https://worktrunk.dev/switch/#shortcuts) for the full list.
```bash
wt switch --create hotfix --base=@ # Branch from current HEAD
wt switch - # Switch to previous worktree
wt remove @ # Remove current worktree
```
### Stacked branches
Branch from current HEAD instead of the default branch:
```bash
wt switch --create feature-part2 --base=@
```
### Reuse `default-branch`
Default branch [detection](https://worktrunk.dev/config/#wt-config-state-default-branch) means scripts work on any repo — no need to hardcode `main` or `master`:
```bash
git rebase $(wt config state default-branch)
```
In hooks and aliases, the same value is the `{{ default_branch }}` [template variable](https://worktrunk.dev/hook/#template-variables); reserve this command for plain shell scripts.
### Override `default-branch` for one clone
When the integration branch differs from the remote's `HEAD`, set a [clone-local override](https://worktrunk.dev/config/#wt-config-state-default-branch):
```bash
wt config state default-branch set integration
```
### Bare repository layout
A [bare repository](https://git-scm.com/docs/gitrepository-layout) has no working tree, so all branches — including the default — are [linked worktrees](https://git-scm.com/docs/git-worktree) at equal paths. No branch gets special treatment.
Cloning a bare repo into `<project>/.git` puts all worktrees under one directory:
```bash
git clone --bare <url> myproject/.git
cd myproject
git config remote.origin.fetch '+refs/heads/*:refs/remotes/origin/*'
git fetch origin
git remote set-head origin --auto
```
The fetch refspec creates remote-tracking branches such as `origin/main`; `git remote set-head` records the remote's default branch.
With `worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"`, worktrees become subdirectories of `myproject/`:
```
myproject/
├── .git/ # bare repository
├── main/ # default branch worktree
├── feature/ # feature branch worktree
└── bugfix/ # bugfix branch worktree
```
#### Configure the worktree path
On first `wt switch` in a bare repo at a hidden path (`.git`, `.bare`), worktrunk detects that the default template would produce broken paths like `myproject/.git.main` and offers a fix:
```
▲ Bare repo at myproject/.git — worktrees will be at myproject/.git.main
◎ Configure worktree-path to place worktrees at myproject/main? [y/N/?]
```
Accepting writes a project-scoped entry to user config:
```toml
# ~/.config/worktrunk/config.toml
[projects."github.com/myorg/myrepo"]
worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"
```
Run `wt config show` from inside any worktree to find the project identifier (`Identifier: …` in the PROJECT CONFIG section). Set it globally with `worktree-path = "..."` at the top level if this layout is preferred for all bare repos.
#### Create the first worktree
```bash
wt switch main
```
For a freshly cloned bare repo the default branch already exists, so `wt switch main` (without `--create`) is enough. Use `wt switch --create <branch>` for new branches.
Now `wt switch --create feature` creates `myproject/feature/`.
#### Set up the project config
The project config (`.config/wt.toml`) must live inside a worktree — the bare `.git` directory has no tracked files. Once the first worktree exists, create it from there:
```bash
wt switch main
wt config create --project
```
Commit the file and it will appear in every worktree automatically.
## Aliases and hooks
### `wt` aliases
Compose with template filters and [vars](https://worktrunk.dev/tips-patterns/#per-branch-variables):
```toml
# .config/wt.toml
[aliases]
# Open this worktree's dev server
open = "open http://localhost:{{ branch | hash_port }}"
# Test with branch-specific features from vars
test = "cargo test --features {{ vars.features | default('default') }}"
# Switch via the interactive picker, print the chosen branch
pick = "wt switch --format=json | jq -r '.branch'"
```
See [Aliases](https://worktrunk.dev/extending/#aliases) for scoping, approval, and reference.
### Per-branch variables
`wt config state vars` holds state per branch, accessible from templates (`{{ vars.key }}`) and the CLI. Some uses:
- **Coordinate state across pipeline steps** — see [Database per worktree](https://worktrunk.dev/tips-patterns/#database-per-worktree) below for a full recipe
- **Stick a branch to an environment** — `wt config state vars set env=staging`, then `{{ vars.env | default('dev') }}` in hooks
- **Parametrize aliases per branch** — see [`wt` aliases above](https://worktrunk.dev/tips-patterns/#wt-aliases)
See [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) for storage format, JSON support, and reference.
### Task runners in hooks
Reference Taskfile/Justfile/Makefile in hooks:
```toml
# .config/wt.toml
[pre-start]
"setup" = "task install"
[pre-merge]
"validate" = "just test lint"
```
### Progressive validation
Split checks across hook types — quick feedback before each commit, expensive suites before merge:
```toml
# .config/wt.toml
[[pre-commit]]
lint = "npm run lint"
typecheck = "npm run typecheck"
[[pre-merge]]
test = "npm test"
build = "npm run build"
```
`pre-commit` runs during `wt merge`, before the squash commit; `pre-merge` runs once per merge after the rebase, so it's the right place for the slow tests.
### Target-specific hooks
Branch on `{{ target }}` to vary behavior per merge destination — for example, deploying to production from `main` and staging from a release branch:
```toml
# .config/wt.toml
post-merge = """
if [ {{ target }} = main ]; then
npm run deploy:production
elif [ {{ target }} = staging ]; then
npm run deploy:staging
fi
"""
```
`{{ target }}` is the branch being merged into. `post-merge` runs in the target's worktree (or the primary worktree if target has none), so deploy commands see the merged code.
## Per-worktree services
### Dev server per worktree
Each worktree runs its own dev server on a deterministic port. The `hash_port` filter generates a stable port (10000-19999) from the branch name:
```toml
# .config/wt.toml
[post-start]
server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
[list]
url = "http://localhost:{{ branch | hash_port }}"
```
[`wt step tether`](https://worktrunk.dev/step/#wt-step-tether) runs the server in its own process group and tears the whole group down when the worktree is removed, so no `pre-remove` hook is needed. See the [`wt step tether`](https://worktrunk.dev/step/#wt-step-tether) docs for the full rationale and platform behavior.
The URL column in `wt list` shows each worktree's dev server:
```console
$ wt list
Branch Status HEAD± main↕ main…± Remote⇅ URL Commit
@ main ? ^⇅ +5 ⇡1 ⇣1 http://localhost:12107 41ee083
+ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 ⇡3 http://localhost:10703 6814f02
+ fix-auth ↕| ↑2 ↓1 +25 -11 | http://localhost:16460 b772e68
+ fix-typos _| | http://localhost:14301 41ee083
○ Showing 4 worktrees, 2 with changes, 2 ahead, hidden: Path, Age, Message
```
`fix-auth` always gets port 16460, on any machine. The URL dims if the server isn't running.
### Database per worktree
Each worktree can have its own isolated database. A pipeline sets up names and ports as [vars](https://worktrunk.dev/config/#wt-config-state-vars), then later steps and hooks reference them:
```toml
# .config/wt.toml
[[post-start]]
set-vars = """
wt config state vars set container='{{ repo }}-{{ branch | sanitize }}-postgres' &&
wt config state vars set port='{{ ('db-' ~ branch) | hash_port }}' &&
wt config state vars set db-url='postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ branch | sanitize_db }}'
"""
[[post-start]]
db = """
docker run -d --rm \
--name {{ vars.container }} \
-p {{ vars.port }}:5432 \
-e POSTGRES_DB={{ branch | sanitize_db }} \
-e POSTGRES_PASSWORD=dev \
postgres:16
"""
[pre-remove]
db-stop = "docker stop {{ vars.container }} 2>/dev/null || true"
```
The first pipeline step derives values from the branch and stores them as vars. The second step references `{{ vars.container }}` and `{{ vars.port }}` — templates render when each step runs, so the vars are already set. `pre-remove` reads the same vars to stop the container.
The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide. The `sanitize_db` filter produces database-safe identifiers (lowercase, underscores, no leading digits, with a short hash suffix).
The connection string is accessible anywhere — not just in hooks:
```bash
DATABASE_URL=$(wt config state vars get db-url) npm start
```
### Per-worktree env vars
To scope environment variables to a worktree — a tool's package path, a profile, an API endpoint — use a directory environment manager like [direnv](https://direnv.net) or [mise](https://mise.jdx.dev). Both hook the shell prompt, so they activate on the `cd` that `wt switch` already performs — no worktrunk configuration needed. Commit the config at the repo root and every worktree gets its own copy, with paths resolving relative to that worktree.
**direnv** — commit `.envrc` at the repo root:
```sh
# .envrc
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.
**mise** — commit `mise.toml` at the repo root:
```toml
# mise.toml
[env]
MY_PACKAGES_PATH = "{{ config_root }}/.packages"
```
`{{ config_root }}` is the project root mise resolves relative paths against ([env directives](https://mise.jdx.dev/environments/)) — the worktree root, not the primary worktree. mise also covers Windows / PowerShell, which direnv doesn't natively.
Both set real environment variables in the shell session, so every child process inherits them — hooks, build tools, subshells. Each new worktree is a new path, so it needs its own one-time trust step (`direnv allow` / `mise trust`).
### Eliminate cold starts
Use [`wt step copy-ignored`](https://worktrunk.dev/step/#wt-step-copy-ignored) to copy gitignored files (caches, dependencies, `.env`) between worktrees:
```toml
# .config/wt.toml
[post-start]
copy = "wt step copy-ignored"
```
When another hook depends on the copy — for example, copying `node_modules/` before `pnpm install` so the install reuses cached packages — sequence them with a `[[post-start]]` pipeline:
```toml
# .config/wt.toml
[[post-start]]
copy = "wt step copy-ignored"
[[post-start]]
install = "pnpm install"
```
Use `pre-start` instead when an `--execute` command needs the copied files immediately.
All gitignored files are copied by default. To limit what gets copied, create `.worktreeinclude` with patterns — files must be both gitignored and listed. See [`wt step copy-ignored`](https://worktrunk.dev/step/#wt-step-copy-ignored) for details.
### Subdomain routing with Caddy
<!-- Hand-tested 2026-03-07 -->
Clean URLs like `http://feature-auth.myproject.localhost` without port numbers. Useful for cookies, CORS, and matching production URL structure.
**Prerequisites:** [Caddy](https://caddyserver.com/docs/install) (`brew install caddy`)
```toml
# .config/wt.toml
[post-start]
server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"
proxy = """
curl -sf --max-time 0.5 http://localhost:2019/config/ || caddy start
curl -sf http://localhost:2019/config/apps/http/servers/wt || \
curl -sfX PUT http://localhost:2019/config/apps/http/servers/wt -H 'Content-Type: application/json' \
-d '{"listen":[":8080"],"automatic_https":{"disable":true},"routes":[]}'
curl -sf -X DELETE http://localhost:2019/id/wt:{{ repo }}:{{ branch | sanitize }} || true
curl -sfX PUT http://localhost:2019/config/apps/http/servers/wt/routes/0 -H 'Content-Type: application/json' \
-d '{"@id":"wt:{{ repo }}:{{ branch | sanitize }}","match":[{"host":["{{ branch | sanitize }}.{{ repo }}.localhost"]}],"handle":[{"handler":"reverse_proxy","upstreams":[{"dial":"127.0.0.1:{{ branch | hash_port }}"}]}]}'
"""
[pre-remove]
proxy = "curl -sf -X DELETE http://localhost:2019/id/wt:{{ repo }}:{{ branch | sanitize }} || true"
[list]
url = "http://{{ branch | sanitize }}.{{ repo }}.localhost:8080"
```
**How it works:**
1. `wt switch --create feature-auth` runs the `post-start` hook, starting the dev server on a deterministic port (`{{ branch | hash_port }}` → 18283)
2. The hook starts Caddy if needed and registers a route using the same port: `feature-auth.myproject` → `localhost:18283`
3. `*.localhost` resolves to `127.0.0.1` via the OS
4. Visiting `http://feature-auth.myproject.localhost:8080`: Caddy matches the subdomain and proxies to the dev server
### Tmux session per worktree
Each worktree gets its own tmux session with a multi-pane layout.
```toml
# .config/wt.toml
[pre-start]
tmux = """
S={{ branch | sanitize }}
W={{ worktree_path }}
tmux new-session -d -s "$S" -c "$W" -n dev
# Create 4-pane layout: shell | backend / claude | frontend
tmux split-window -h -t "$S:dev" -c "$W"
tmux split-window -v -t "$S:dev.0" -c "$W"
tmux split-window -v -t "$S:dev.2" -c "$W"
# Start services in each pane
tmux send-keys -t "$S:dev.1" 'npm run backend' Enter
tmux send-keys -t "$S:dev.2" 'claude' Enter
tmux send-keys -t "$S:dev.3" 'npm run frontend' Enter
tmux select-pane -t "$S:dev.0"
echo "✓ Session '$S' — attach with: tmux attach -t $S"
"""
[pre-remove]
tmux = "tmux kill-session -t {{ branch | sanitize }} 2>/dev/null || true"
```
To create a worktree and immediately attach:
```console
$ wt switch --create feature -x tmux -- attach -t '{{ branch | sanitize }}'
```
### cmux workspace per worktree
Each worktree gets its own [cmux](https://cmux.com) workspace. Switching worktrees switches workspaces; removing a worktree closes its workspace. Configuration contributed by [@endigma](https://github.com/endigma) ([#2796](https://github.com/max-sixty/worktrunk/issues/2796)).
**Prerequisites:** [jq](https://jqlang.org) (`brew install jq`)
```toml
# ~/.config/worktrunk/config.toml
# cmux is the navigation primitive; don't also cd the invoking shell.
[switch]
cd = false
[pre-start]
cmux = "cmux new-workspace --name {{ repo | sanitize }}/{{ branch | sanitize }} --cwd {{ worktree_path }} --focus true"
[pre-switch]
cmux = """
WS=$(cmux --json list-workspaces 2>/dev/null \\
| jq -r --arg t '{{ repo | sanitize }}/{{ branch | sanitize }}' \\
'.workspaces[] | select(.title == $t) | .ref' | head -1)
[ -n "$WS" ] && cmux select-workspace --workspace "$WS" || true
"""
[pre-remove]
cmux = """
WS=$(cmux --json list-workspaces 2>/dev/null \\
| jq -r --arg t '{{ repo | sanitize }}/{{ branch | sanitize }}' \\
'.workspaces[] | select(.title == $t) | .ref' | head -1)
[ -n "$WS" ] && cmux close-workspace --workspace "$WS" || true
"""
```
**Why `pre-*` instead of `post-*`?** cmux restricts socket access to processes spawned inside a cmux terminal. `post-*` hooks run as detached background processes, breaking the process ancestry chain. `pre-*` hooks run in the foreground and inherit the terminal's process lineage.
### Xcode DerivedData cleanup
Clean up Xcode's DerivedData when removing a worktree. Each DerivedData directory contains an `info.plist` recording its project path — grep for the worktree path to find and remove the matching build cache:
```toml
# ~/.config/worktrunk/config.toml
[post-remove]
clean-derived = """
grep -Fl {{ worktree_path }} \
~/Library/Developer/Xcode/DerivedData/*/info.plist 2>/dev/null \
| while read plist; do
derived_dir=$(dirname "$plist")
rm -rf "$derived_dir"
echo "Cleaned DerivedData: $derived_dir"
done
"""
```
## Working with agents
### Track agent status
The agent plugins mark each worktree 🤖 (working) or 💬 (waiting) in `wt list`, and `wt config state marker set` sets a marker by hand for any other workflow. See [Activity tracking](https://worktrunk.dev/claude-code/#activity-tracking).
### Agent handoffs
Spawn a worktree with an agent CLI running in the background. `-x` names the program to run and everything after `--` is passed to it, so OpenCode's subcommand goes after the `--`: `-x opencode -- run '<task>'`.
**tmux** (new detached session):
```bash
tmux new-session -d -s fix-auth-bug "wt switch --create fix-auth-bug -x claude -- \
'The login session expires after 5 minutes. Find the session timeout config and extend it to 24 hours.'"
```
**Zellij** (new pane in current session):
```bash
zellij run -- wt switch --create fix-auth-bug -x claude -- \
'The login session expires after 5 minutes. Find the session timeout config and extend it to 24 hours.'
```
This lets one agent session hand off work to another that runs in the background. Hooks run inside the multiplexer session/pane.
The [worktrunk skill](https://worktrunk.dev/claude-code/) includes guidance for Claude Code (and other agent CLIs that load it) to execute this pattern. To enable it, request it explicitly ("spawn a parallel worktree for...") or add to your project instructions (`CLAUDE.md` or `AGENTS.md`):
```markdown title="AGENTS.md"
When I ask you to spawn parallel worktrees, use the agent handoff pattern
from the worktrunk skill.
```
## Status, commits, and logs
### Monitor CI across branches
```bash
wt list --full --branches
```
Shows PR/CI status for all branches, including those without worktrees. CI indicators are clickable links to the PR page.
### LLM branch summaries
With `summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit) configured, `wt list --full` shows an LLM-generated one-line summary for each branch. The same summaries appear in the [`wt switch` picker](https://worktrunk.dev/switch/#interactive-picker)'s `summary` tab.
```toml
# ~/.config/worktrunk/config.toml
[list]
summary = true
```
See [LLM Commits](https://worktrunk.dev/llm-commits/#branch-summaries) for details.
### JSON API
```bash
wt list --format=json
```
Structured output for dashboards, statuslines, and scripts. See [`wt list`](https://worktrunk.dev/list/) for query examples.
### Manual commit messages
The `commit.generation.command` receives the rendered prompt on stdin and returns the commit message on stdout. To write commit messages by hand instead of using an LLM, point it at `$EDITOR`:
```toml
# ~/.config/worktrunk/config.toml
[commit.generation]
command = '''f=$(mktemp); printf '\n\n' > "$f"; sed 's/^/# /' >> "$f"; ${EDITOR:-vi} "$f" < /dev/tty > /dev/tty; grep -v '^#' "$f"'''
```
This comments out the rendered prompt (diff, branch name, stats) with `#` prefixes, opens your editor, and strips comment lines on save. A couple of blank lines at the top give you space to type; the prompt context is visible below for reference.
To keep the LLM as default but use the editor for a specific merge, add a [worktrunk alias](https://worktrunk.dev/extending/#aliases):
```toml
# ~/.config/worktrunk/config.toml
[aliases]
mc = '''WORKTRUNK_COMMIT__GENERATION__COMMAND='f=$(mktemp); printf "\n\n" > "$f"; sed "s/^/# /" >> "$f"; ${EDITOR:-vi} "$f" < /dev/tty > /dev/tty; grep -v "^#" "$f"' wt merge'''
```
Then `wt mc` opens an editor for the commit message while plain `wt merge` continues to use the LLM.
### Monitor hook logs
Follow background hook output:
```bash
tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", "server"]) | .path')"
```
Each `hook_output` entry carries `branch`, `source` (`user`, `project`, or `internal`), `hook_type`, `name`, and `path` — adjust the `select` to pick a different hook or branch. Run `wt config state logs` to list all available logs.
Create a shell function for frequent use (`wtlog server`):
```bash
wtlog() {
tail -f "$(wt config state logs --format=json | jq -r --arg branch "$(git branch --show-current)" --arg name "$1" '.hook_output[] | select([.branch, .source, .hook_type, .name] == [$branch, "user", "post-start", $name]) | .path')"
}
```
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| receiving-code-reviewobra/superpowersUse when receiving code review feedback, before implementing suggestions, especially if feedback seems unclear or technically questionable - requires technical rigor and verification, not performative agreement or blind implementation | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| requesting-code-reviewobra/superpowersUse when completing tasks, implementing major features, or before merging to verify work meets requirements | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| using-git-worktreesobra/superpowersUse when starting feature work that needs isolation from current workspace or before executing implementation plans - ensures an isolated workspace exists via native tools or git worktree fallback | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| verification-before-completionobra/superpowersUse when about to claim work is complete, fixed, or passing, before committing or creating PRs - requires running verification commands and confirming output before making any success claims; evidence before assertions always | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |