Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(plugin): ship skills to Codex installs via a generated real-file mirror (#3440)
Maximilian Roos36ba57bdca4b
diff --git a/CLAUDE.md b/CLAUDE.mdindex 47f08b194..4140d46ed 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -43,13 +43,13 @@ Load relevant skills before starting; reload when scope changes mid-session. Pro## Documentation-Behavior changes require doc updates. `src/cli/mod.rs` (`after_long_help` plus clap attributes) is the PRIMARY SOURCE for command pages; never hand-edit the generated mirrors under `docs/content/` or `skills/worktrunk/reference/`. Ask: "does `--help` still describe what the code does?" After any doc change run `cargo test --test integration test_docs_are_in_sync`; editing help text (`after_long_help`, `about`, arg docs) also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept -- --test integration "test_help"` (the pre-merge hook runs both). Sync taxonomy, help-text authoring (three render contexts, link text, config-TOML blocks): `docs/CLAUDE.md`.+Behavior changes require doc updates. `src/cli/mod.rs` (`after_long_help` plus clap attributes) is the PRIMARY SOURCE for command pages; never hand-edit the generated mirrors under `docs/content/`, `skills/worktrunk/reference/`, or `plugins/worktrunk/skills/`. Ask: "does `--help` still describe what the code does?" After any doc change run `cargo test --test integration test_docs_are_in_sync`; editing help text (`after_long_help`, `about`, arg docs) also changes the rendered `--help` snapshots, which that test leaves untouched — regenerate them with `cargo insta test --accept -- --test integration "test_help"` (the pre-merge hook runs both). Sync taxonomy, help-text authoring (three render contexts, link text, config-TOML blocks): `docs/CLAUDE.md`.Design proposals live in `design/` and are review-only: open a PR to discuss, then close it without merging. They guide implementation PRs but don't land on `main`.## Plugin Layout-Per-tool layout and path resolution (Claude/Codex/Gemini), the convention-only Claude manifest, the Codex inline-hooks rationale, the accepted `wt-switch-create` tradeoff, and `test_plugin_layout_is_consolidated`: `plugins/worktrunk/CLAUDE.md`.+Per-tool layout and path resolution (Claude/Codex/Gemini), the convention-only Claude manifest, the Codex inline-hooks rationale, the generated plugin-skills mirror, the accepted `wt-switch-create` tradeoff, and `test_plugin_layout_is_consolidated`: `plugins/worktrunk/CLAUDE.md`.## Data Safetydiff --git a/plugins/worktrunk/.codex-plugin/plugin.json b/plugins/worktrunk/.codex-plugin/plugin.jsonindex 555820d1e..300eb4fab 100644--- a/plugins/worktrunk/.codex-plugin/plugin.json+++ b/plugins/worktrunk/.codex-plugin/plugin.json@@ -44,7 +44,6 @@]}},- "skills": "./skills/","interface": {"displayName": "Worktrunk","shortDescription": "Git worktree workflows for parallel Codex sessions.",diff --git a/plugins/worktrunk/CLAUDE.md b/plugins/worktrunk/CLAUDE.mdindex 41556e803..18b8ff59f 100644--- a/plugins/worktrunk/CLAUDE.md+++ b/plugins/worktrunk/CLAUDE.md@@ -14,7 +14,7 @@ worktrunk/ ← repo root = marketplace root├── .agents/plugins/marketplace.json← Codex pointer (source → ./plugins/worktrunk)├── gemini-extension.json ← Gemini manifest (extensionPath = repo root)├── hooks/hooks.json ← Gemini activity hooks (call the wt.sh below)-├── skills -> (this dir) ← Gemini reads ${extensionPath}/skills = repo-root skills/+├── skills/ ← real dir; Gemini reads ${extensionPath}/skills directly└── plugins/worktrunk/ ← plugin root (Claude + Codex resolve source here)├── .claude-plugin/plugin.json ← Claude manifest (metadata only — NO `hooks`│ or `skills` keys; components load by@@ -28,8 +28,10 @@ worktrunk/ ← repo root = marketplace root│ $CLAUDE_PLUGIN_ROOT, Codex via $PLUGIN_ROOT,│ Gemini via│ ${extensionPath}/plugins/worktrunk/hooks/wt.sh- ├── skills -> ../../skills ← symlink; single-sources skills across all- │ tools and the docs auto-sync+ ├── skills/ ← generated real-file mirror of repo-root+ │ skills/ (test_docs_are_in_sync; never+ │ hand-edit) — real files because Codex's+ │ installer drops symlinks, see below├── CLAUDE.md / README.md└── (Codex activity hooks live *inline* in .codex-plugin/plugin.json's`hooks` key — see Known Limitations below)@@ -53,25 +55,61 @@ Path resolution differs by tool, all verified end-to-end against the real CLIs:conventional path is dead config that can only mask a mislocated file.- Skills are auto-discovered by scanning `skills/` for `<dir>/SKILL.md`; a`skills` manifest array only *adds* directories to that scan, so listing- the defaults is redundant. The installer dereferences the `skills` symlink- into a real directory in the install cache.+ the defaults is redundant.`$CLAUDE_PLUGIN_ROOT` is the plugin root.-- **Codex**: `.agents/plugins/marketplace.json` `source` object- `{ "source": "local", "path": "./plugins/worktrunk" }`. Codex reads- `plugins/worktrunk/.codex-plugin/plugin.json`. `skills: "./skills/"` resolves- through the same symlink.+- **Codex** (codex-cli 0.144.1): `.agents/plugins/marketplace.json` `source`+ object `{ "source": "local", "path": "./plugins/worktrunk" }`. Codex reads+ `plugins/worktrunk/.codex-plugin/plugin.json`. Skills load by convention —+ with no `skills` manifest key, Codex scans `<plugin-root>/skills/`; an+ explicit `"skills": "./skills/"` names the same directory, so the manifest+ carries no `skills` key. The scanned tree is the real-file mirror ("Plugin+ skills are a generated mirror" below).- **Gemini**: `gemini-extension.json` at the repo root; `${extensionPath}` isthe repo root, so `${extensionPath}/skills/` is the repo-root `skills/`directly and `hooks/hooks.json` (repo root) calls the canonical shim at`${extensionPath}/plugins/worktrunk/hooks/wt.sh`. No symlink or copy.-All three tools pick up the whole `skills/` directory (Claude and Codex through-the symlink, Gemini directly), so a new repo-root skill ships everywhere with-no manifest change — provided its directory contains a `SKILL.md`-(`test_plugin_layout_is_consolidated` enforces that; a directory without one is-silently ignored). Claude-only skills reach the other tools too (accepted-tradeoff — see Known Limitations below).+All three tools pick up the whole `skills/` set — Gemini reads the repo-root+directory, Claude and Codex ship the plugin mirror — so a new repo-root skill+ships everywhere once `test_docs_are_in_sync` regenerates the mirror, provided+its directory contains a `SKILL.md` (`test_plugin_layout_is_consolidated`+enforces that; a directory without one is silently ignored). Claude-only+skills reach the other tools too (accepted tradeoff — see Known Limitations+below).++### Plugin skills are a generated mirror++`plugins/worktrunk/skills/` is a real-file mirror of the authored repo-root+`skills/`, regenerated — symlinks dereferenced, stale files deleted — by the+`sync_plugin_skills_mirror` stage of `test_docs_are_in_sync`; never hand-edit+it. Repo-root `skills/` stays the authored home: Gemini reads it directly and+the docs sync writes into it.++The mirror holds real files because of how the plugin ships, verified+end-to-end against codex-cli 0.144.1 (scratch marketplaces through+`codex plugin marketplace add` + `codex plugin add`, skill inventory read with+`codex debug prompt-input`):++- `codex plugin add` copies the plugin into+ `$CODEX_HOME/plugins/cache/<marketplace>/<plugin>/<version>` with a copier+ that handles only regular files and directories, silently skipping symlink+ entries (`copy_dir_recursive` in `codex-rs/core-plugins/src/store.rs`), and+ sessions load from that cache copy. A symlink anywhere in the tree — a+ top-level `skills` link or a nested one like `reference/README.md` — ships+ no content. No manifest value can bridge it: manifest paths must stay within+ the plugin root (`..` and absolute paths are rejected,+ `resolve_manifest_path` in `codex-rs/core-plugins/src/manifest.rs`).+- Codex's convention scan (`default_skill_roots`, the empty-`skills` branch of+ `plugin_skill_roots` in `codex-rs/core-plugins/src/loader.rs`) reads the+ mirror like any directory.+- Claude's installer dereferences symlinks, so a symlinked `skills/` worked+ for Claude; the mirror serves it identically. A symlink also materializes as+ a plain text file on Windows checkouts, which shipped no skills from a+ Windows clone to Claude or Codex.++`test_plugin_layout_is_consolidated` pins the no-symlinks invariant;+`test_docs_are_in_sync` pins content equality with repo-root `skills/`.## Known Limitations@@ -105,4 +143,4 @@ The events (Codex's `HookEventsToml` vocabulary, verified against `codex-rs/conf### 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 (`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.+Codex's mirrored `skills/` and Gemini's `${extensionPath}/skills/` both carry the entire skill set, 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 authored `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/skills b/plugins/worktrunk/skillsdeleted file mode 120000index 5dcab58e1..000000000--- a/plugins/worktrunk/skills+++ /dev/null@@ -1 +0,0 @@-../../skills\ No newline at end of filediff --git a/plugins/worktrunk/skills/worktrunk/SKILL.md b/plugins/worktrunk/skills/worktrunk/SKILL.mdnew file mode 100644index 000000000..ab68bcf99--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/SKILL.md@@ -0,0 +1,338 @@+---+name: worktrunk+description: Guidance for Worktrunk (the `wt` CLI) — git worktree management, hooks, and config. Load when 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.+license: MIT OR Apache-2.0+compatibility: Requires the `wt` CLI (https://worktrunk.dev)+---++# Worktrunk++Help users work with Worktrunk, a CLI tool for managing git worktrees.++## Available Documentation++Reference files are synced from [worktrunk.dev](https://worktrunk.dev) documentation:++- **reference/config.md**: User and project configuration (LLM, hooks, command defaults)+- **reference/hook.md**: Hook types, timing, and execution order+- **reference/switch.md**, **merge.md**, **list.md**, etc.: Command documentation+- **reference/extending.md**: Aliases, multi-step pipelines, custom subcommands, and template-expansion gotchas (two-pass `{% raw %}` deferral, for-each recipes)+- **reference/llm-commits.md**: LLM commit message generation+- **reference/tips-patterns.md**: Practical recipes — aliases, per-branch variables, dev server per worktree, parallel agent patterns+- **reference/shell-integration.md**: Shell integration debugging+- **reference/troubleshooting.md**: Troubleshooting for LLM and hooks (Claude-specific)++For command-specific options, run `wt <command> --help`. For configuration, follow the workflows below.++## Two Types of Configuration++Worktrunk uses two separate config files with different scopes and behaviors:++### User Config (`~/.config/worktrunk/config.toml`)+- **Scope**: Personal preferences for the individual developer+- **Location**: `~/.config/worktrunk/config.toml` (never checked into git)+- **Contains**: LLM integration, worktree path templates, command settings, user hooks, approved commands+- **Permission model**: Always propose changes and get consent before editing+- **See**: `reference/config.md` for detailed guidance++### Project Config (`.config/wt.toml`)+- **Scope**: Team-wide automation shared by all developers+- **Location**: `<repo>/.config/wt.toml` (checked into git)+- **Contains**: Hooks for worktree lifecycle (pre-start, pre-merge, etc.)+- **Permission model**: Proactive (create directly, changes are reversible via git)+- **See**: `reference/hook.md` for detailed guidance++## Determining Which Config to Use++When a user asks for configuration help, determine which type based on:++**User config indicators**:+- "set up LLM" or "configure commit generation"+- "change where worktrees are created"+- "customize commit message templates"+- Affects only their environment++**Project config indicators**:+- "set up hooks for this project"+- "automate npm install"+- "run tests before merge"+- Affects the entire team++**Both configs may be needed**: For example, setting up commit message generation requires user config, but automating quality checks requires project config.++## Core Workflows++### Setting Up Commit Message Generation (User Config)++Most common request. See `reference/llm-commits.md` for supported tools and exact command syntax.++1. **Detect available tools**+ ```bash+ which claude codex llm aichat 2>/dev/null+ ```++2. **If none installed, recommend Claude Code** (already available in Claude Code sessions)++3. **Propose config change** — Get the exact command from `reference/llm-commits.md`+ ```toml+ [commit.generation]+ command = "..." # see reference/llm-commits.md for tool-specific commands+ ```+ Ask: "Should I add this to your config?"++4. **After approval, apply**+ - Check if config exists: `wt config show`+ - If not, guide through `wt config create`+ - Read, modify, write preserving structure++5. **Suggest testing**+ ```bash+ wt step commit --show-prompt | head # verify prompt builds+ wt merge # in a repo with uncommitted changes+ ```++### Setting Up Project Hooks (Project Config)++Common request for workflow automation. Follow discovery process:++1. **Detect project type**+ ```bash+ ls package.json Cargo.toml pyproject.toml+ ```++2. **Identify available commands**+ - For npm: Read `package.json` scripts+ - For Rust: Common cargo commands+ - For Python: Check pyproject.toml++3. **Design appropriate hooks** (10 hook types: 5 events × pre/post — see `reference/hook.md`)+ - Dependencies (fast, must complete) → `pre-start`+ - Tests/linting (must pass) → `pre-commit` or `pre-merge`+ - Long builds, dev servers → `post-start`+ - Setup before branch resolution → `pre-switch`+ - Terminal/IDE updates → `post-switch`+ - After-commit triggers (CI, notifications) → `post-commit`+ - Deployment → `post-merge`+ - Cleanup before removal → `pre-remove`+ - Cleanup after removal (stop servers, remove containers) → `post-remove`++4. **Validate commands work**+ ```bash+ npm run lint # verify exists+ which cargo # verify tool exists+ ```++5. **Create `.config/wt.toml`**+ ```toml+ # Install dependencies when creating worktrees+ pre-start = "npm install"++ # Validate code quality before committing+ [pre-commit]+ lint = "npm run lint"+ typecheck = "npm run typecheck"++ # Run tests before merging+ pre-merge = "npm test"+ ```++6. **Add comments explaining choices**++7. **Suggest testing**+ ```bash+ wt switch --create test-hooks+ ```++**See `reference/hook.md` for complete details.**++### Adding Hooks to Existing Config++When users want to add automation to an existing project:++1. **Read existing config**: `cat .config/wt.toml`++2. **Determine hook type** - When should this run? (10 types: 5 events × pre/post)+ - Creating worktree (blocking) → `pre-start`+ - Creating worktree (background) → `post-start`+ - Before/after a switch → `pre-switch` / `post-switch`+ - Before committing → `pre-commit`+ - After committing (CI, notifications) → `post-commit`+ - Before merging → `pre-merge`+ - After merging → `post-merge`+ - Before/after removal → `pre-remove` / `post-remove`++3. **Handle format conversion if needed**++ Single command to a pipeline of dependent steps:+ ```toml+ # Before+ pre-start = "npm install"++ # After (adding db:migrate, which needs install to finish first)+ [[pre-start]]+ install = "npm install"++ [[pre-start]]+ migrate = "npm run db:migrate"+ ```++ For independent commands, a named table runs them concurrently:+ ```toml+ [pre-start]+ install = "npm install"+ env = "cp .env.example .env"+ ```++4. **Preserve existing structure and comments**++### Validation Before Adding Commands++Before adding hooks, validate:++```bash+# Verify command exists+which npm+which cargo++# For npm, verify script exists+npm run lint --dry-run++# For shell commands, check syntax+bash -n -c "if [ true ]; then echo ok; fi"+```++**Dangerous patterns** — Warn users before creating hooks with:+- Destructive commands: `rm -rf`, `DROP TABLE`+- External dependencies: `curl http://...`+- Privilege escalation: `sudo`++## Permission Models++### User Config: Conservative+- **Never edit without consent** - Always show proposed change and wait for approval+- **Never install tools** - Provide commands for users to run themselves+- **Preserve structure** - Keep existing comments and organization+- **Validate first** - Ensure TOML is valid before writing++### Project Config: Proactive+- **Create directly** - Changes are versioned, easily reversible+- **Validate commands** - Check commands exist before adding+- **Explain choices** - Add comments documenting why hooks exist+- **Warn on danger** - Flag destructive operations before adding++## Common Tasks Reference++### User Config Tasks+- Set up commit message generation → `reference/llm-commits.md`+- Customize worktree paths → `reference/config.md#worktree-path-template`+- Custom commit templates → `reference/llm-commits.md#prompt-templates`+- Configure command defaults → `reference/config.md#command-config`+- Set up personal hooks → `reference/config.md#hooks`++### Project Config Tasks+- Set up hooks for new project → `reference/hook.md`+- Add hook to existing config → `reference/hook.md#hook-forms`+- Use template variables → `reference/hook.md#template-variables`+- Add dev server URL to list → `reference/config.md#dev-server-url`++### Aliases & Multi-Worktree Tasks+- Create a `wt` alias → `reference/extending.md#aliases`+- Run a command in every worktree → `reference/step.md#wt-step-for-each`+- Rebase every worktree (up-style) → `reference/extending.md#recipe-rebase-every-worktree-onto-its-upstream`+- Defer a template variable to a nested `wt` command → `reference/extending.md#deferring-expansion-to-a-nested-wt-command`++## Key Commands++```bash+# View all configuration+wt config show++# Create initial user config (LLM/commit setup: see reference/llm-commits.md)+wt config create++# Full config reference (subcommands, templates, env vars)+wt config --help+```++## Loading Additional Documentation++Load **reference files** for detailed configuration, hook specifications, and troubleshooting.++Find specific sections with grep:+```bash+grep -A 20 "## Setup" reference/llm-commits.md+grep -A 30 "### pre-start" reference/hook.md+grep -A 20 "## Warning Messages" reference/shell-integration.md+```++## Hook Approvals in Non-Interactive Sessions++Worktrunk never runs a project's hooks or aliases until the user has explicitly approved them. The commands in `.config/wt.toml` are arbitrary shell code shipped in a repository the user may have just cloned, so on first run Worktrunk shows each command and waits for the user to approve it — an untrusted `.config/wt.toml` cannot silently execute anything. Approvals are stored per-project in `~/.config/worktrunk/approvals.toml` and re-prompted whenever a command template changes, so a hook can't be swapped for a different command after it was approved.++Agents running `wt merge`, `wt switch`, or other commands that trigger hooks will hit an error like:++```+▲ cargo-difftest needs approval to execute 1 command:+○ post-merge install:+ cargo install --path .+✗ Cannot prompt for approval in non-interactive environment+↳ To skip prompts in CI/CD, add --yes; to pre-approve commands, run wt config approvals add+```++The resolution is for the user to make the trust decision themselves:++- **`wt config approvals add`** — interactive prompt where the user reviews each command before it is stored to `~/.config/worktrunk/approvals.toml`. Run once per project; the approval persists across invocations until the command template changes or the project moves. This is the path to recommend — the user reviews and consents to exactly the commands that will run.++**When invoked as an agent, stop and escalate to the user.** Approving a project's hooks is a security decision about whether this repository should be trusted to run arbitrary commands on the user's machine — that decision belongs to the user, not the agent. Tell the user to run `wt config approvals add` and let them review the commands. Do not run `--yes` on the user's behalf: it skips the approval gate for that invocation, so reaching for it to unblock a command defeats the protection. `--yes` exists for CI/CD pipelines that already control their own hook contents; it is not a shortcut for an interactive agent to silence an approval prompt.++## Advanced: Agent Handoffs++When the user requests spawning a worktree with an agent in a background session ("spawn a worktree for...", "hand off to another agent"), use the appropriate pattern for their terminal multiplexer. Substitute `<agent-cli>` with the CLI you are running as: `claude` for Claude Code, `'opencode run'` for OpenCode.++**tmux** (check `$TMUX` env var):+```bash+tmux new-session -d -s <branch-name> "wt switch --create <branch-name> -x <agent-cli> -- '<task description>'"+```++**Zellij** (check `$ZELLIJ` env var):+```bash+zellij run -- wt switch --create <branch-name> -x <agent-cli> -- '<task description>'+```++**Requirements** (all must be true):+- User explicitly requests spawning/handoff+- User is in a supported multiplexer (tmux or Zellij)+- The user's project instructions (`CLAUDE.md` or `AGENTS.md`) or an explicit prompt authorize this pattern++**Do not use this pattern** for normal worktree operations.++Example (tmux, Claude Code):+```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.'"+```++Example (Zellij, OpenCode):+```bash+zellij run -- wt switch --create fix-auth-bug -x 'opencode run' -- \+ 'The login session expires after 5 minutes. Find the session timeout config and extend it to 24 hours.'+```++### Parallel sub-Agents (single Claude Code session)++To spawn multiple sub-Agents that each work in their own worktree from one Claude Code session — no terminal multiplexer, no human in the other pane — pre-start each worktree from the parent and pass the path into the sub-Agent prompt:++```bash+wt switch --create <branch> --no-cd --no-hooks+```++Then call the `Agent` tool **without** `isolation: "worktree"`, naming the path in the prompt:++```+You are working in `/abs/path/to/worktrunk.<branch>` on branch `<branch>`.+All edits must stay in that worktree.+```++`--no-cd` skips the shell-integration cd script the parent can't consume; `--no-hooks` is appropriate when each sub-Agent will run its own build/test step (e.g. `cargo run -- hook pre-merge --yes`) and you don't need post-start setup repeated per worktree.++**Do not** use `Agent { isolation: "worktree" }` for this. Claude Code passes its internal agent ID as `name` to the `WorktreeCreate` hook, so `wt` creates the worktree as `worktrunk.agent-<id>` on a throwaway branch. If the sub-Agent then creates a feature branch on top, you end up with non-canonical paths, orphan branches, and post-start hooks fired against the wrong branch. Pre-creating with `wt switch --create` keeps path, branch, and hook target aligned.diff --git a/plugins/worktrunk/skills/worktrunk/reference/README.md b/plugins/worktrunk/skills/worktrunk/reference/README.mdnew file mode 100644index 000000000..710ad9879--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/README.md@@ -0,0 +1,248 @@+<!-- markdownlint-disable MD033 -->++<h1><img src="docs/static/logo.png" alt="Worktrunk logo" width="50" align="absmiddle"> Worktrunk</h1>++<!-- Crates.io badge below disabled while shields.io is rate-limited by crates.io+ (renders "CRATES.IO: INVALID"). Tracking: badges/shields#11879. Restore once fixed.+ [](https://crates.io/crates/worktrunk)+-->+[](https://worktrunk.dev)+[](https://opensource.org/licenses/MIT)+[](https://github.com/max-sixty/worktrunk/actions?query=branch%3Amain+workflow%3Aci)+[](https://codecov.io/gh/max-sixty/worktrunk)+[](https://github.com/max-sixty/worktrunk/stargazers)+[](https://github.com/max-sixty/tend)++> **July 2026**: Worktrunk was [released](https://x.com/max_sixty/status/2006077845391724739?s=20) at the start of the year, and has quickly become the most popular git worktree manager. It's built with love (there's no slop!). Please let me know any frictions at all; I'm intensely focused on continuing to make Worktrunk excellent, and the biggest help is folks posting problems they perceive.++Worktrunk is a CLI for git worktree management, designed for running AI agents in parallel.++Worktrunk's three core commands make worktrees as easy as branches. Plus, Worktrunk has a bunch of quality-of-life features to simplify working with many parallel changes, including hooks to automate local workflows.++A quick demo:++++> ### 📚 Full documentation at [worktrunk.dev](https://worktrunk.dev) 📚++<!-- ⚠️ AUTO-GENERATED from docs/content/worktrunk.md#context-git-worktrees..worktrunk-makes-git-worktrees-as-easy-as-branches — edit source to update -->++## Context: git worktrees++AI agents like Claude Code and Codex can handle longer tasks without+supervision, such that it's possible to manage 5-10+ in parallel. Git's native+worktree feature give each agent its own working directory, so they don't step+on each other's changes.++But the git worktree UX is clunky. Even a task as small as starting a new+worktree requires typing the branch name three times: `git worktree add -b feat+../repo.feat`, then `cd ../repo.feat`.++## Worktrunk makes git worktrees as easy as branches++Worktrees are addressed by branch name; paths are computed from a configurable template.++> Start with the core commands++**Core commands:**++<table class="cmd-compare">+ <thead>+ <tr>+ <th>Task</th>+ <th>Worktrunk</th>+ <th>Plain git</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Switch worktrees</td>+ <td><pre>wt switch feat</pre></td>+ <td><pre>cd ../repo.feat</pre></td>+ </tr>+ <tr>+ <td>Create + start Claude</td>+ <td><pre>wt switch -c -x claude feat</pre></td>+ <td><pre>git worktree add -b feat ../repo.feat && \+cd ../repo.feat && \+claude</pre></td>+ </tr>+ <tr>+ <td>Clean up</td>+ <td><pre>wt remove</pre></td>+ <td><pre>cd ../repo && \+git worktree remove ../repo.feat && \+git branch -d feat</pre></td>+ </tr>+ <tr>+ <td>List with status</td>+ <td><pre>wt list</pre></td>+ <td><pre>git worktree list</pre> (paths only)</td>+ </tr>+ </tbody>+</table>++> Expand into the more advanced commands as needed++**Workflow automation:**++- **[Hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge, etc+- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs+- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command+- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with live diff and log previews+- **[Copy build caches](https://worktrunk.dev/step/#wt-step-copy-ignored)** — skip cold starts by sharing `target/`, `node_modules/`, etc between worktrees+- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch+- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch+- **[Dev server per worktree](https://worktrunk.dev/tips-patterns/#dev-server-per-worktree)** — `hash_port` template filter gives each worktree a unique port+- **[Aliases](https://worktrunk.dev/extending/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt <name>` commands and branch-scoped state for hook templates+- ...and **[lots more](#next-steps)**++Multiple parallel agents, same simple commands:++++<!-- END AUTO-GENERATED -->++<!-- ⚠️ AUTO-GENERATED from docs/content/worktrunk.md#install..further-reading — edit source to update -->++## Install++**Homebrew (macOS & Linux):**++```bash+brew install worktrunk && wt config shell install+```++Shell integration allows commands to change directories.++**Cargo:**++```bash+cargo install worktrunk && wt config shell install+```++<details>+<summary><strong>Windows & other</strong></summary>++**Windows.** `wt` defaults to Windows Terminal's command, so Winget additionally installs Worktrunk as `git-wt` to avoid the conflict:++```bash+winget install max-sixty.worktrunk+git-wt config shell install+```++Alternatively, disable Windows Terminal's alias (Settings → Apps → Advanced app settings → App execution aliases → "Terminal"/"Terminal Preview") to use `wt` directly.++**Arch Linux:**++```bash+sudo pacman -S worktrunk && wt config shell install+```++**Conda / Pixi** (community-maintained [feedstock](https://github.com/conda-forge/worktrunk-feedstock)):++```bash+conda install -c conda-forge worktrunk && wt config shell install+```++Or with [Pixi](https://pixi.sh): `pixi global install worktrunk && wt config shell install`.++</details>++## Quick start++Create a worktree for a new feature:++```console+$ wt switch --create feature-auth+✓ Created branch feature-auth from main and worktree @ ~/repo.feature-auth++```++This creates a new branch and worktree, then switches to it. Do your work, then check all worktrees with [`wt list`](https://worktrunk.dev/list/):++```console+$ wt list+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age Message+@ feature-auth + ↑ +27 -8 ↑1 +31 4bc72dc9 2h Add authenticat…+^ main ^⇡ ⇡1 0e631add 1d Initial commit++○ Showing 2 worktrees, 1 with changes, 1 ahead, 1 column hidden++```++The `@` marks the current worktree. `+` means staged changes, `↑1` means 1 commit ahead of main, `⇡` means unpushed commits.++When done, either:++**PR workflow** — commit, push, open a PR, merge via GitHub/GitLab, then clean up:++```bash+wt step commit # commit staged changes+gh pr create # or glab mr create+wt remove # after PR is merged+```++**Local merge** — squash, rebase onto main, fast-forward merge, clean up:++```console+$ wt merge main+◎ Generating commit message and committing changes... (2 files, +53, no squashing needed)+ Add authentication module+✓ Committed changes @ a1b2c3d+◎ Merging 1 commit to main @ a1b2c3d (no rebase needed)+ * a1b2c3d Add authentication module+ auth.rs | 51 ++++++++++++++++++++++++++++++++++++++++++++++++++++ lib.rs | 2 +++ 2 files changed, 53 insertions(+)+✓ Merged to main (1 commit, 2 files, +53)+◎ Removing feature-auth worktree & branch in background (same commit as main, _)+○ Switched to worktree for main @ ~/repo++```++For parallel agents, create multiple worktrees and launch an agent in each:++```bash+wt switch -x claude -c feature-a -- 'Add user authentication'+wt switch -x claude -c feature-b -- 'Fix the pagination bug'+wt switch -x claude -c feature-c -- 'Write tests for the API'+```++The `-x` flag runs a command after switching; arguments after `--` are passed to it. Configure [post-start hooks](https://worktrunk.dev/hook/#hook-types) to automate setup (install deps, start dev servers).++## Next steps++- Learn the core commands: [`wt switch`](https://worktrunk.dev/switch/), [`wt list`](https://worktrunk.dev/list/), [`wt merge`](https://worktrunk.dev/merge/), [`wt remove`](https://worktrunk.dev/remove/)+- Set up [hooks](https://worktrunk.dev/hook/) for automated setup+- Explore [LLM commit messages](https://worktrunk.dev/llm-commits/), [interactive+ picker](https://worktrunk.dev/switch/#interactive-picker), [Claude Code integration](https://worktrunk.dev/claude-code/), [CI+ status & PR links](https://worktrunk.dev/list/#ci-status)+- Browse [tips & patterns](https://worktrunk.dev/tips-patterns/) for recipes: aliases, dev servers, databases, agent handoffs, and more+- [Extending Worktrunk](https://worktrunk.dev/extending/) — customize workflows with hooks & aliases+- Run `wt --help` or `wt <command> --help` for quick CLI reference++## Further reading++- [Claude Code: Best practices for agentic coding](https://www.anthropic.com/engineering/claude-code-best-practices) — Anthropic's official guide, including the worktree pattern+- [Shipping faster with Claude Code and Git Worktrees](https://incident.io/blog/shipping-faster-with-claude-code-and-git-worktrees) — incident.io's workflow for parallel agents+- [Git worktree pattern discussion](https://github.com/anthropics/claude-code/issues/1052) — Community discussion in the Claude Code repo+- [@DevOpsToolbox's video on Worktrunk](https://youtu.be/WBQiqr6LevQ?t=345)+- [git-worktree documentation](https://git-scm.com/docs/git-worktree) — Official git reference++<!-- END AUTO-GENERATED -->++## Contributing++- ⭐ Star the repo+- Tell a friend about Worktrunk+- [Open an issue](https://github.com/max-sixty/worktrunk/issues/new?title=&body=%23%23%20Description%0A%0A%3C!--%20Describe%20the%20bug%20or%20feature%20request%20--%3E%0A%0A%23%23%20Context%0A%0A%3C!--%20Any%20relevant%20context%3A%20your%20workflow%2C%20what%20you%20were%20trying%20to%20do%2C%20etc.%20--%3E) — feedback, feature requests, even a small friction or imperfect user message, or [a worktree pain not yet solved](https://github.com/max-sixty/worktrunk/issues/new?title=Worktree%20friction%3A%20&body=%23%23%20The%20friction%0A%0A%3C!--%20What%20worktree-related%20task%20is%20still%20painful%3F%20--%3E%0A%0A%23%23%20Current%20workaround%0A%0A%3C!--%20How%20do%20you%20handle%20this%20today%3F%20--%3E%0A%0A%23%23%20Ideal%20solution%0A%0A%3C!--%20What%20would%20make%20this%20easier%3F%20--%3E)+- Share: [X](https://twitter.com/intent/tweet?text=Worktrunk%20%E2%80%94%20CLI%20for%20git%20worktree%20management&url=https%3A%2F%2Fworktrunk.dev) · [Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fworktrunk.dev&title=Worktrunk%20%E2%80%94%20CLI%20for%20git%20worktree%20management) · [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fworktrunk.dev)++> ### 📚 Full documentation at [worktrunk.dev](https://worktrunk.dev) 📚++### Star history++<a href="https://star-history.com/#max-sixty/worktrunk&Date">+ <img src="https://api.star-history.com/svg?repos=max-sixty/worktrunk&type=Date" width="500" alt="Star History Chart">+</a>diff --git a/plugins/worktrunk/skills/worktrunk/reference/claude-code.md b/plugins/worktrunk/skills/worktrunk/reference/claude-code.mdnew file mode 100644index 000000000..955ad72a9--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/claude-code.md@@ -0,0 +1,125 @@+# Agent Integration++Worktrunk ships a plugin for each supported agent CLI. What a plugin provides depends on the hooks that CLI exposes:++| Capability | Claude Code | Codex | OpenCode | Gemini CLI |+|---|:-:|:-:|:-:|:-:|+| Configuration skill | ✓ | ✓ | | ✓ |+| Activity tracking (🤖/💬 in `wt list`) | ✓ | ✓ | ✓ | ✓ |+| 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 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 tracks activity through its own turn-end (`Stop`) hook, but has no session-exit event, so a marker persists after a Codex session ends until the next session or a manual `wt config state marker clear`.++## Installation++### Claude Code++```bash+wt config plugins claude install+```++Manual equivalent:++```bash+claude plugin marketplace add max-sixty/worktrunk+claude plugin install worktrunk@worktrunk+```++### Codex++```bash+wt config plugins codex install+```++This configures the Worktrunk marketplace in Codex. Then run `/plugins` in Codex and install Worktrunk from the marketplace. Manual equivalent:++```bash+codex plugin marketplace add max-sixty/worktrunk+```++To remove the marketplace entry, run `wt config plugins codex uninstall`. Already-installed plugins are left unchanged.++### OpenCode++```bash+wt config plugins opencode install+```++This writes the activity-tracking plugin to OpenCode's global plugins directory, `~/.config/opencode/plugins/worktrunk.ts` (honoring `$OPENCODE_CONFIG_DIR` and `$XDG_CONFIG_HOME`). `wt config plugins opencode uninstall` removes it.++### Gemini CLI++```bash+gemini extensions install https://github.com/max-sixty/worktrunk+```++Gemini loads the extension natively from the repository, so there is no `wt` wrapper. `gemini extensions uninstall worktrunk` removes it.++## Configuration skill++With the `/worktrunk` skill, the agent can help with:++- Setting up LLM-generated commit messages+- Adding project hooks (pre-start, pre-merge, pre-commit)+- Configuring worktree path templates+- Fixing shell integration issues++Claude Code is designed to load the skill automatically when it detects worktrunk-related questions.++## Activity tracking++The Claude Code, Codex, OpenCode, and Gemini plugins track agent sessions with status markers in `wt list`:++```bash+$ wt list+ <b>Branch</b> <b>Status</b> <b>HEAD±</b> <b>main↕</b> <b>main…±</b> <b>Remote⇅</b> <b>Path</b> <b>Commit</b> <b>Age</b> <b>Message</b>+@ main <span class=d>^</span><span class=d>⇡</span> <span class=g>⇡1</span> . <span class=d>33323bc1</span> <span class=d>1d</span> <span class=d>Initial commit</span>++ feature-api <span class=d>↑</span> 🤖 <span class=g>↑1</span> <span class=g>+1</span> ../repo.feature-api <span class=d>70343f03</span> <span class=d>1d</span> <span class=d>Add REST API endpoints</span>++ review-ui <span class=c>?</span> <span class=d>↑</span> 💬 <span class=g>↑1</span> <span class=g>+1</span> ../repo.review-ui <span class=d>a585d6ed</span> <span class=d>1d</span> <span class=d>Add dashboard component</span>++ wip-docs <span class=c>?</span> <span class=d>–</span> ../repo.wip-docs <span class=d>33323bc1</span> <span class=d>1d</span> <span class=d>Initial commit</span>++<span class=d>○</span> <span class=d>Showing 4 worktrees, 2 with changes, 2 ahead</span>+```++- 🤖 — agent is working+- 💬 — agent is waiting or idle++The Claude Code, OpenCode, and Gemini plugins clear the marker when a session ends. A stale marker can remain if the agent process is killed before its session-end hook runs. Codex exposes no session-exit event, so its marker always persists after a session ends. In every case, `wt config state marker clear` removes a marker manually.++### Manual status markers++Set status markers manually for any workflow:++```bash+$ wt config state marker set "🚧" # Current branch+$ wt config state marker set "✅" --branch feature # Specific branch+$ git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Direct+```++## Worktree isolation (Claude Code only)++Claude Code agents can run in isolated worktrees (`isolation: "worktree"`). By default, Claude Code creates these with `git worktree add`. The plugin's `WorktreeCreate` and `WorktreeRemove` hooks route this through `wt switch --create` and `wt remove` instead, so worktrees created by agents get worktrunk's naming conventions, hooks, and lifecycle management.++## `/wt-switch-create` command (Claude Code only)++`/wt-switch-create [<branch>] [<repo>] [-- <task>]` starts a task in a fresh worktree without leaving the session: it creates the worktree, switches into it, and runs the task (all arguments optional). The worktree persists like any other; merge or remove it with `wt merge` / `wt remove`.++## Statusline (Claude Code only)++`wt list statusline --format=claude-code` outputs a single-line status for the Claude Code statusline. When the CI status cache is stale, this fetches from the network — typically 1–2 seconds — making it suitable for async statuslines but too slow for synchronous shell prompts. If a faster version would be helpful, please [open an issue](https://github.com/max-sixty/worktrunk/issues).++<code>~/w/myproject.feature-auth !🤖 @<span style='color:#0a0'>+42</span> <span style='color:#a00'>-8</span> <span style='color:#0a0'>↑3</span> <span style='color:#0a0'>⇡1</span> <span style='color:#0a0'>#3035</span> Opus 🌔 65% <span style='color:#a70'>1.4×(10am–3pm)</span></code>++When Claude Code provides context window usage via stdin JSON, a moon phase gauge appears (🌕→🌑 as context fills). A `<n>×(<window>)` segment appears when Claude's 5-hour or weekly rate limit is on track to be hit before reset — `1.4×(10am–3pm)` reads as 1.4× the pace that would exactly fill that window. Its colour deepens with severity — dim, then dim-yellow, then yellow — as more of the window would be spent locked out at the cap, so a fast pace that would only tip over near the reset stays dim. Above 90% used it shows usage instead of pace — `93%(10am–3pm)` — near the cap, how much is left matters more than how fast it's going.++Add to `~/.claude/settings.json`:++```json+{+ "statusLine": {+ "type": "command",+ "command": "wt list statusline --format=claude-code"+ }+}+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/code-signing.md b/plugins/worktrunk/skills/worktrunk/reference/code-signing.mdnew file mode 100644index 000000000..b707521a0--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/code-signing.md@@ -0,0 +1,52 @@+# Code Signing Policy++This page is Worktrunk's **code signing policy**. It describes what gets signed, which certificate is used, how the signing pipeline works, and who authorizes each release. It exists both to document the process for users and to satisfy the transparency requirements of the [SignPath Foundation](https://signpath.org/) open-source code signing program.++## Why signing matters++Worktrunk's Windows binaries (`wt.exe` and `git-wt.exe`) are small, native executables. Microsoft Defender's machine-learning heuristics routinely flag unsigned native executables of this shape as generic threats (for example `Trojan:Win32/Wacatac.B!ml`) — a false positive driven by the *absence of a trusted signature*, not by anything in the code. A valid [Authenticode](https://learn.microsoft.com/en-us/windows-hardware/drivers/install/authenticode) signature gives Defender's cloud something signed to trust, which is what stops that class of false positive. Signing the Windows artifacts is the durable fix.++The macOS and Linux release artifacts, the crates.io source distribution, and `cargo install` builds are unaffected by this policy — `cargo install` compiles locally from source and never downloads a pre-built artifact.++## Signing certificate++> Free code signing provided by [SignPath.io](https://signpath.io/), certificate by [SignPath Foundation](https://signpath.org/).++The certificate's private key is generated and held on SignPath's Hardware Security Module (HSM); no maintainer ever possesses the private key. Signing happens only through SignPath's service, invoked from Worktrunk's release pipeline.++## What is signed++- `wt.exe` and `git-wt.exe` — the Windows binaries shipped in the `x86_64-pc-windows-msvc` release archive on each [GitHub Release](https://github.com/max-sixty/worktrunk/releases) and distributed via [winget](https://github.com/microsoft/winget-pkgs) (`winget install max-sixty.worktrunk`). `git-wt.exe` is the same program built as a git subcommand.++Nothing else is signed under this policy. Signed artifacts contain only code built from this repository; any bundled third-party libraries are used unmodified.++## Build and signing pipeline++1. Every release is triggered by pushing a version tag to [`max-sixty/worktrunk`](https://github.com/max-sixty/worktrunk). No release is built from any other source.+2. The [`release` workflow](https://github.com/max-sixty/worktrunk/blob/main/.github/workflows/release.yaml) builds the platform binaries with [cargo-dist](https://axodotdev.github.io/cargo-dist/) on GitHub-hosted runners, from the tagged commit only.+3. The Windows binary is submitted to SignPath for signing via the [SignPath GitHub Action](https://github.com/SignPath/github-action-submit-signing-request). The signed binary is returned to the workflow and published in the release archive.+4. The build is reproducible from public source: the workflow, the toolchain pin ([`rust-toolchain.toml`](https://github.com/max-sixty/worktrunk/blob/main/rust-toolchain.toml)), and the release configuration ([`dist-workspace.toml`](https://github.com/max-sixty/worktrunk/blob/main/dist-workspace.toml)) are all tracked in this repository.++## Project roles++Worktrunk follows SignPath's team model:++| Role | Responsibility | Who |+|------|----------------|-----|+| **Author** | Trusted developer who commits and tags releases | [@max-sixty](https://github.com/max-sixty) |+| **Reviewer** | Reviews contributions from outside the trusted set before they can be released | [@max-sixty](https://github.com/max-sixty) |+| **Approver** | Authorizes each signing request for a release | [@max-sixty](https://github.com/max-sixty) |++All maintainers with signing authority use multi-factor authentication on their GitHub and SignPath accounts.++## Release approval++Every signing request requires **manual approval** by an Approver before the certificate is applied — signing is never fully automated. A release is signed only after the Approver has confirmed the artifact was built from the tagged commit in this repository.++## Privacy++Worktrunk is a local-first command-line tool. It performs no telemetry, collects no analytics, and transmits no user data. Network access happens only when a command the user ran needs it (for example, fetching CI status for `wt list --full`); the [FAQ](https://worktrunk.dev/faq/) and inline documentation describe exactly when. The signed binaries add no data collection of any kind.++## Reporting a problem++If you believe a signed Worktrunk binary has been tampered with, or you receive an antivirus detection on an official release artifact, please [open an issue](https://github.com/max-sixty/worktrunk/issues). For a suspected Defender false positive, you can also report the file to Microsoft through the [Windows Defender submission portal](https://www.microsoft.com/en-us/wdsi/filesubmission) (as *"I believe this file is safe"*), which corrects the cloud definition for every user.diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdnew file mode 100644index 000000000..09048e09b--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -0,0 +1,1468 @@+# wt config++Manage user & project configs. Includes shell integration, hooks, and saved state.++## Examples++Install shell integration (required for directory switching):++```bash+$ wt config shell install+```++Create user config file with documented examples:++```bash+$ wt config create+```++Create project config file (`.config/wt.toml`) for hooks:++```bash+$ wt config create --project+```++Show current configuration and file locations:++```bash+$ wt config show+```++## Configuration files++| File | Location | Contains | Committed & shared |+|------|----------|----------|--------------------|+| **User config** | `~/.config/worktrunk/config.toml` | Worktree path template, LLM commit configs, etc | ✗ |+| **Project config** | `.config/wt.toml` | Project hooks, dev server URL | ✓ |++Organizations can deploy a system-wide config file for shared defaults — run `wt config show` for the platform-specific location.++**User config** — personal preferences:++```toml+# ~/.config/worktrunk/config.toml+worktree-path = ".worktrees/{{ branch | sanitize }}"++[commit.generation]+command = "MAX_THINKING_TOKENS=0 claude -p --no-session-persistence --model=haiku --tools='' --safe-mode --setting-sources='user' --system-prompt=''"+```++**Project config** — shared team settings:++```toml+# .config/wt.toml+[pre-start]+deps = "npm ci"++[pre-merge]+test = "npm test"+```++<!-- USER_CONFIG_START -->+# User Configuration++Create with `wt config create`. Values shown are defaults unless noted otherwise.++Location:++- macOS/Linux: `~/.config/worktrunk/config.toml` (or `$XDG_CONFIG_HOME` if set)+- Windows: `%APPDATA%\worktrunk\config.toml`++## Worktree path template++Controls where new worktrees are created.++**Available template variables:**++- `{{ repo_path }}` — absolute path to the repository root (e.g., `/Users/me/code/myproject`. Or for bare repos, the bare directory itself)+- `{{ repo }}` — repository directory name (e.g., `myproject`)+- `{{ owner }}` — primary remote owner path (may include subgroups like `group/subgroup`)+- `{{ branch }}` — raw branch name (e.g., `feature/auth`)+- `{{ branch | sanitize }}` — filesystem-safe: `/` and `\` become `-` (e.g., `feature-auth`)+- `{{ branch | sanitize_db }}` — database-safe: lowercase, underscores, hash suffix (e.g., `feature_auth_x7k`)+- `{{ branch | codename(2) }}` — deterministic friendly name from a ~1.26M-combo pool (e.g., `malleable-opah`)++This is a smaller set than [the variables hooks and aliases get](https://worktrunk.dev/hook/#template-variables).++**Examples** for repo at `~/code/myproject`, branch `feature/auth`:++Default — sibling directory (`~/code/myproject.feature-auth`):++```toml+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | sanitize }}"+```++Inside the repository (`~/code/myproject/.worktrees/feature-auth`):++```toml+worktree-path = "{{ repo_path }}/.worktrees/{{ branch | sanitize }}"+```++Friendly branch-derived names (`~/code/myproject.malleable-opah`):++```toml+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"+```++Friendly names with branch identity in a parent directory (`~/code/worktrees/feature-auth/malleable-opah`):++```toml+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"+```++Centralized worktrees directory (`~/worktrees/myproject/feature-auth`):++```toml+worktree-path = "~/worktrees/{{ repo }}/{{ branch | sanitize }}"+```++By remote owner path (`~/development/max-sixty/myproject/feature/auth`):++```toml+worktree-path = "~/development/{{ owner }}/{{ repo }}/{{ branch }}"+```++Bare repository (`~/code/myproject/feature-auth`):++```toml+worktree-path = "{{ repo_path }}/../{{ branch | sanitize }}"+```++`~` expands to the home directory. Relative paths resolve from `repo_path`.++## LLM commit messages++Generate commit messages automatically during merge. Requires an external CLI tool.++### Claude Code++```toml+[commit.generation]+command = "MAX_THINKING_TOKENS=0 claude -p --no-session-persistence --model=haiku --tools='' --safe-mode --setting-sources='user' --system-prompt=''"+```++### Codex++```toml+[commit.generation]+command = "codex exec -m gpt-5.6-luna -c model_reasoning_effort='low' -c system_prompt='' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"+```++### OpenCode++```toml+[commit.generation]+command = "opencode run -m anthropic/claude-haiku-4.5 --variant fast"+```++### llm++```toml+[commit.generation]+command = "llm -m claude-haiku-4.5"+```++### aichat++```toml+[commit.generation]+command = "aichat -m claude:claude-haiku-4.5"+```++See [LLM commits docs](https://worktrunk.dev/llm-commits/) for setup and [Custom prompt templates](#custom-prompt-templates) for template customization.++## Command config++### List++Persistent flag values for `wt list`. Override on command line as needed.++```toml+[list]+summary = false # Enable LLM branch summaries (requires [commit.generation])++full = false # Show CI status and LLM summaries (--full)+branches = false # Include branches without worktrees (--branches)+remotes = false # Include remote-only branches (--remotes)++json-schema = 2 # JSON output schema: 2 (envelope) or 1 (bare array, the current default); unset emits 1 with a warning++columns = ["branch", "status", "ci", "path"] # Columns to show, in order — built-ins or custom headers (omit for the default set)++task-timeout-ms = 0 # Kill individual git commands after N ms; 0 disables+timeout-ms = 0 # Wall-clock budget for the entire collect phase; 0 disables+```++`columns` selects and orders the columns to render; omit it for the default set.+It is meant to drive a per-invocation [alias](https://worktrunk.dev/extending/#aliases)+(`wt --config-set 'list.columns=[…]' list`), giving a named view without+disturbing the default `wt list`. A static setting works but pins one layout+over a table that otherwise adapts to `--full` and terminal width.++Valid built-in names:++- `branch` — The branch name+- `status` — Git status symbols, plus any user-defined status+- `working-diff` — Uncommitted line changes against `HEAD` (header `HEAD±`)+- `ahead-behind` — Commits ahead of and behind the default branch (header `main↕`)+- `branch-diff` — Line changes against the default branch (header `main…±`)+- `summary` — An LLM-generated summary of the branch+- `upstream` — Commits ahead of and behind the upstream tracking branch (header `Remote⇅`)+- `ci` — CI status of the head commit+- `path` — The worktree's path+- `url` — Dev-server URL from the `[list] url` template+- `commit` — The head commit's short hash+- `age` — Time since the last commit+- `message` — The head commit's subject++A selection mixes built-ins with [custom columns](#custom-columns), each named+by its `[list.custom-columns]` header (`columns = ["branch", "Ticket", "ci"]`),+and is exhaustive: only the listed columns render. Omit `columns` to keep the+default set, where custom columns append automatically. A built-in name wins a+header collision; the gutter type indicator always shows.++Listing a column forces it on, space permitting: `ci` shows without `--full`,+since `--full` only bundles columns into the default table rather than gating a+named one. A column whose data source is missing still stays hidden — `summary`+needs an LLM command (`[commit.generation]`), `url` needs a `[list] url`+template — since listing can't supply the data.++The selection drives the table and the `wt switch` picker. `wt list --format+json` always emits every field, but a listed gated column (`ci`, `summary`)+still forces its data collection on, so the JSON carries the same data the+table shows.++#### Custom columns [experimental]++Custom columns add per-branch context to the `wt list` table. Each+`[list.custom-columns]` entry is a column: the key is the header, the template+renders each row's cell.++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}" # Required; the result is the cell text+width = 20 # Optional max display width (default: 40)+priority = 9 # Optional drop order when the terminal narrows;+ # lower = kept longer (default: 9, the URL band)+```++Templates may reference `{{ branch }}`, `{{ worktree_path }}`,+`{{ worktree_name }}` (empty for branch-only rows), and two per-branch+namespaces:++- `{{ vars.* }}` — values stored with+ [`wt config state vars set`](https://worktrunk.dev/config/#wt-config-state-vars).+- `{{ git.branch.* }}` — the branch's own git config under `branch.<name>.*`,+ read straight from `git config` (e.g. `{{ git.branch.jira }}` for a key you+ set yourself, or the git-native `description`). Git lowercases config variable+ names, so `branch.<name>.nvciShelf` reads as `{{ git.branch.nvcishelf }}`.++All standard filters work (`sanitize`, `hash_port`, `codename`, …). A row+where the template renders empty (e.g. a branch without the key) shows an+empty cell; a column that is empty for every row is dropped from the table.+`wt list --format json` includes the rendered values under `columns`.++A `Jira` column reading a key kept in git config, and a `Summary` column+showing just the first line of the git-native branch description:++```toml+[list.custom-columns.Jira]+template = "{{ git.branch.jira }}"++[list.custom-columns.Summary]+template = "{{ git.branch.description | lines | first }}"+```++### Commit++Shared by `wt step commit`, `wt step squash`, and `wt merge`.++```toml+[commit]+stage = "all" # What to stage before commit: "all", "tracked", or "none"+```++### Merge++Most flags are on by default. Set to false to change default behavior.++```toml+[merge]+squash = true # Squash commits into one (--no-squash to preserve history)+commit = true # Commit uncommitted changes first (--no-commit to skip)+rebase = true # Rebase onto target before merge (--no-rebase to skip)+remove = true # Remove worktree after merge (--no-remove to keep)+verify = true # Run project hooks (--no-hooks to skip)+ff = true # Fast-forward merge (--no-ff to create a merge commit instead)+```++### Remove++Persistent flag values for `wt remove`. Override on command line as needed.++```toml+[remove]+delete-branch = true # Delete branch after removal (--no-delete-branch to keep)+```++### Switch++```toml+[switch]+cd = true # Change directory after switching (--no-cd to skip)++[switch.picker]+pager = "delta --paging=never" # Example: override git's core.pager for diff preview+```++### Step++```toml+[step.copy-ignored]+exclude = [] # Additional excludes (e.g., [".cache/", ".turbo/"])+```++Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/`, `.pijul/`, `.sl/`, `.svn/`) and tool-state directories (`.conductor/`, `.entire/`, `.worktrees/`). User config and project config exclusions are combined.++### Aliases++Command templates that run as `wt <name>`. See the [Extending Worktrunk guide](https://worktrunk.dev/extending/#aliases) for usage and flags.++```toml+[aliases]+greet = "echo Hello from {{ branch }}"+url = "echo http://localhost:{{ branch | hash_port }}"+```++Aliases defined here apply to all projects. For project-specific aliases, use the [project config](https://worktrunk.dev/config/#project-configuration) `[aliases]` section instead.++### User project-specific settings++User config can include a `[projects]` table for project-specific settings — worktree layout, setting overrides, anything else — separate from the [project config](https://worktrunk.dev/config/#project-configuration) shared with teammates.++Entries are keyed by project identifier — `<host>/<owner>/<repo>` derived from the primary remote URL (no `.git` suffix), or the canonical repo path when there is no remote. Run `wt config show` inside the repo to see the identifier for the current project; it appears in the `PROJECT CONFIG` section as `Identifier: …`.++Scalar values (like `worktree-path`) replace the global value; everything else (hooks, aliases, etc.) appends, global first.++```toml+[projects."github.com/user/repo"]+worktree-path = ".worktrees/{{ branch | sanitize }}"+list.full = true+merge.squash = false+remove.delete-branch = false+pre-start.env = "cp .env.example .env"+step.copy-ignored.exclude = [".repo-local-cache/"]+aliases.deploy = "make deploy BRANCH={{ branch }}"+```++Hooks support all three [hook forms](https://worktrunk.dev/hook/#hook-forms). A table runs multiple commands concurrently; an array-of-tables pipeline runs steps in sequence. The dotted-key examples below are equivalent to the table forms — TOML treats `projects."github.com/user/repo".post-start.server = "..."` and a `[projects."github.com/user/repo".post-start]` table the same way:++```toml+# Single command+[projects."github.com/user/repo"]+post-start = "mise trust"++# Multiple commands, running concurrently+[projects."github.com/user/repo".post-start]+mise = "mise trust"+server = "npm run dev"++# Pipeline: steps run in sequence+[[projects."github.com/user/repo".post-start]]+install = "npm ci"++[[projects."github.com/user/repo".post-start]]+build = "npm run build"+server = "npm run dev"+```++### Custom prompt templates++Templates use [minijinja](https://docs.rs/minijinja/) syntax.++#### Commit template++Available variables:++- `{{ git_diff }}`, `{{ git_diff_stat }}` — diff content+- `{{ branch }}`, `{{ repo }}` — context+- `{{ recent_commits }}` — recent commit messages+- `{{ user_guidance }}`, `{{ project_guidance }}` — rendered append fragments (see [Appending to the prompt](https://worktrunk.dev/config/#appending-to-the-prompt))++Default template:++<!-- DEFAULT_TEMPLATE_START -->+```toml+[commit.generation]+template = """+<task>Write a commit message for the staged changes below.</task>++<format>+- Subject line under 50 chars+- For material changes, add a blank line then a body paragraph explaining the change+- Output only the commit message, no quotes or code blocks+</format>++<style>+- Imperative mood: "Add feature" not "Added feature"+- Match recent commit style (conventional commits if used)+- Describe the change, not the intent or benefit+</style>+{% if user_guidance %}+<user-guidance>+{{ user_guidance }}+</user-guidance>+{% endif %}{% if project_guidance %}+<project-guidance>+{{ project_guidance }}+</project-guidance>+{% endif %}+<diffstat>+{{ git_diff_stat }}+</diffstat>++<diff>+{{ git_diff }}+</diff>++<context>+Branch: {{ branch }}+{% if recent_commits %}<recent_commits>+{% for commit in recent_commits %}- {{ commit }}+{% endfor %}</recent_commits>{% endif %}+</context>++"""+```+<!-- DEFAULT_TEMPLATE_END -->++#### Squash template++Available variables (in addition to commit template variables):++- `{{ commit_details }}` — list of commits being squashed; each renders as its subject and exposes `.subject` / `.body`+- `{{ target_branch }}` — merge target branch++Default template:++<!-- DEFAULT_SQUASH_TEMPLATE_START -->+```toml+[commit.generation]+squash-template = """+<task>Write a commit message for the combined effect of these commits.</task>++<format>+- Subject line under 50 chars+- For material changes, add a blank line then a body paragraph explaining the change+- Output only the commit message, no quotes or code blocks+</format>++<style>+- Imperative mood: "Add feature" not "Added feature"+- Match the style of commits being squashed (conventional commits if used)+- Describe the change, not the intent or benefit+</style>+{% if user_guidance %}+<user-guidance>+{{ user_guidance }}+</user-guidance>+{% endif %}{% if project_guidance %}+<project-guidance>+{{ project_guidance }}+</project-guidance>+{% endif %}+<commits branch="{{ branch }}" target="{{ target_branch }}">+{% for detail in commit_details %}- {{ detail.subject }}+{% endfor %}</commits>++<diffstat>+{{ git_diff_stat }}+</diffstat>++<diff>+{{ git_diff }}+</diff>++"""+```+<!-- DEFAULT_SQUASH_TEMPLATE_END -->++#### Appending to the prompt [experimental]++`template-append` adds to the prompt instead of replacing it. The value is rendered as its own minijinja template (same variables) and injected into the default templates' `{{ user_guidance }}` slot — a `<user-guidance>` block right after `<style>`. It applies to both commit and squash. Use it for personal preferences without restating the whole template:++```toml+[commit.generation]+template-append = """+- Explain the rationale in the body, not just the change+"""+```++The [project config](https://worktrunk.dev/config/#project-configuration) has a `template-append` of its own; it renders into a separate `<project-guidance>` block right after `<user-guidance>`.++## Hooks++See [`wt hook`](https://worktrunk.dev/hook/) for hook types, execution order, template variables, and examples. User hooks apply to all projects; [project hooks](https://worktrunk.dev/config/#project-configuration) apply only to that repository.+<!-- USER_CONFIG_END -->+<!-- PROJECT_CONFIG_START -->+# Project Configuration++Project configuration lets teams share repository-specific settings — hooks, dev server URLs, and other defaults. The file lives in `.config/wt.toml` and is typically checked into version control.++To create a starter file with commented-out examples, run `wt config create --project`.++## Hooks++Project hooks apply to this repository only. See [`wt hook`](https://worktrunk.dev/hook/) for hook types, execution order, and examples.++```toml+pre-start = "npm ci"+post-start = "npm run dev"+pre-merge = "npm test"+```++## Dev server URL++URL column in `wt list` (dimmed when port not listening):++```toml+[list]+url = "http://localhost:{{ branch | hash_port }}"+```++## Forge platform++Name the forge explicitly for SSH aliases or self-hosted instances, where it can't be detected from the remote URL:++```toml+[forge]+platform = "github" # or "gitlab", "gitea" (experimental), "azure-devops" (experimental)+hostname = "github.example.com" # Example: API host (GHE / self-hosted GitLab)+```++## Commit-message append [experimental]++Project-wide commit-message conventions appended to the LLM commit and squash prompts inside a `<project-guidance>` block, after the main template's `<style>` section (and after any user `<user-guidance>`). Rendered as a [minijinja](https://docs.rs/minijinja/) template with the same variables as the main commit template (`{{ branch }}`, `{{ git_diff }}`, etc.), so it can reference them directly. The first time the fragment changes, `wt` prompts the user to approve it — the same one-shot gate as project-defined hooks.++```toml+[commit.generation]+template-append = """+- Use conventional commits (feat:, fix:, docs:, …)+- Reference the relevant issue ID in the body+"""+```++Only `template-append` is honored from the project file. The LLM command and the main prompt template stay in [user config](https://worktrunk.dev/config/) — they describe per-developer environment (which CLI is installed, which agent the developer prefers). User config has a `[commit.generation] template-append` of its own; it renders into a separate `<user-guidance>` block immediately before this one.++## Copy-ignored excludes++Additional excludes for `wt step copy-ignored`:++```toml+[step.copy-ignored]+exclude = [".cache/", ".turbo/"]+```++Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/`, `.pijul/`, `.sl/`, `.svn/`) and tool-state directories (`.conductor/`, `.entire/`, `.worktrees/`). User config and project config exclusions are combined.++## Aliases++Command templates that run as `wt <name>`. See the [Extending Worktrunk guide](https://worktrunk.dev/extending/#aliases) for usage and flags.++```toml+[aliases]+deploy = "make deploy BRANCH={{ branch }}"+url = "echo http://localhost:{{ branch | hash_port }}"+```++Aliases defined here are shared with teammates. For personal aliases, use the [user config](https://worktrunk.dev/config/#aliases) `[aliases]` section instead.+<!-- PROJECT_CONFIG_END -->++# Shell Integration++Worktrunk needs shell integration to change directories when switching worktrees. Install with:++```bash+$ wt config shell install+```++For manual setup, see `wt config shell init --help`.++Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.++### First-run prompts++On first run without shell integration, Worktrunk offers to install it. On first commit without LLM configuration, it offers to configure a detected tool (`claude`, `codex`). Declining sets `skip-shell-integration-prompt` or `skip-commit-generation-prompt` automatically.++# Other++## Environment variables++All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.++### Naming convention++Config keys use kebab-case (`worktree-path`), while env vars use SCREAMING_SNAKE_CASE (`WORKTRUNK_WORKTREE_PATH`). The conversion happens automatically.++For nested config sections, use double underscores to separate levels:++| Config | Environment Variable |+|--------|---------------------|+| `worktree-path` | `WORKTRUNK_WORKTREE_PATH` |+| `commit.generation.command` | `WORKTRUNK_COMMIT__GENERATION__COMMAND` |+| `commit.stage` | `WORKTRUNK_COMMIT__STAGE` |++### Example: CI/testing override++Override the LLM command in CI to use a mock:++```bash+$ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge+```++### Other environment variables++| Variable | Purpose |+|----------|---------|+| `WORKTRUNK_BIN` | Override binary path for shell wrappers; useful for testing dev builds |+| `WORKTRUNK_CONFIG_PATH` | Override user config file location |+| `WORKTRUNK_SYSTEM_CONFIG_PATH` | Override system config file location |+| `WORKTRUNK_PROJECT_CONFIG_PATH` | Override project config file location (defaults to `.config/wt.toml`) |+| `XDG_CONFIG_DIRS` | Colon-separated system config directories (default: `/etc/xdg`) |+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Internal: set by shell wrappers. wt writes a raw path; the wrapper `cd`s to it |+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file |+| `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |+| `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. |+| `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach |+| `RUST_LOG` | Logging directive (e.g. `worktrunk=debug`); overrides the verbosity baseline for what reaches stderr |+| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |+| `CLICOLOR_FORCE` | Force colored output even when not a TTY |++## Inline config overrides (`--config-set`)++`--config-set <toml>` overrides any user config key for a single invocation, with higher priority than both config files and `WORKTRUNK_` env vars. The value is a TOML fragment, so arrays and tables work directly; the flag is global (works before or after the subcommand), repeatable, and a later `--config-set` replaces an earlier one for the same key.++```bash+$ wt --config-set list.full=true list+$ wt step copy-ignored --config-set 'step.copy-ignored.exclude=["target", "dist"]'+```++This composes with aliases — an alias body can invoke `wt --config-set … <command>` to render a named view without changing the saved config.++## Command reference++```+wt config - Manage user & project configs++Includes shell integration, hooks, and saved state.++Usage: wt config [OPTIONS] <COMMAND>++Commands:+ shell Shell integration setup+ create Create configuration file+ show Show configuration files & locations+ update Update deprecated config settings+ approvals Manage command approvals+ alias Inspect and preview aliases+ plugins Plugin management+ state Manage internal data and cache++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++# Subcommands++## wt config show++Show configuration files & locations.++Shows location and contents of user config (`~/.config/worktrunk/config.toml`)+and project config (`.config/wt.toml`). Also shows system config if present.++If a config file doesn't exist, shows defaults that would be used.++### Full diagnostics++Use `--full` to run diagnostic checks:++```bash+$ wt config show --full+```++This tests:+- **CI tool status** — Whether `gh` (GitHub) or `glab` (GitLab) is installed and authenticated+- **Commit generation** — Whether the LLM command can generate commit messages+- **Version check** — Whether a newer version is available on GitHub++### Command reference++```+wt config show - Show configuration files & locations++Usage: wt config show [OPTIONS]++Options:+ --full+ Run diagnostic checks (CI tools, commit generation, version)++ -h, --help+ Print help (see a summary with '-h')++Output:+ --format <FORMAT>+ Output format++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config approvals++Manage command approvals.++Project hooks and project aliases prompt for approval on first run to prevent untrusted projects from running arbitrary commands. Approvals from both flows are stored together.++### Examples++List commands and their approval status for current project:+```bash+$ wt config approvals list+```++Pre-approve all hook and alias commands for current project:+```bash+$ wt config approvals add+```++Clear approvals for current project:+```bash+$ wt config approvals clear+```++Clear only approvals for commands no longer in the project config:+```bash+$ wt config approvals clear --stale+```++Clear global approvals:+```bash+$ wt config approvals clear --global+```++### How approvals work++Approved commands are saved to `~/.config/worktrunk/approvals.toml`. Re-approval is required when the command template changes or the project moves. Use `--yes` to bypass prompts in CI.++### Command reference++```+wt config approvals - Manage command approvals++Usage: wt config approvals [OPTIONS] <COMMAND>++Commands:+ list List project commands and their approval status+ add Store approvals in approvals.toml+ clear Clear approved commands from approvals.toml++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config alias++Inspect and preview aliases.++Aliases are command templates configured in user (`~/.config/worktrunk/config.toml`) or project (`.config/wt.toml`) config and run as `wt <name>`. See the [Extending Worktrunk guide](https://worktrunk.dev/extending/#aliases) for the configuration format.++### Examples++Show every configured alias's template:+```bash+$ wt config alias show+```++Show the template for `deploy`:+```bash+$ wt config alias show deploy+```++Preview an invocation without running it:+```bash+$ wt config alias dry-run deploy+$ wt config alias dry-run deploy -- --env=staging+```++### Command reference++```+wt config alias - Inspect and preview aliases++Usage: wt config alias [OPTIONS] <COMMAND>++Commands:+ show Show an alias's template, or all aliases' templates+ dry-run Preview an alias invocation with template expansion++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state++Manage internal data and cache.++State is stored in `.git/` (config entries and log files), separate from configuration files.++### Keys++- **cache**: [Regenerable caches — CI status, summaries, git commands, hints, and the `wt switch -` target](https://worktrunk.dev/config/#wt-config-state-cache)+- **default-branch**: [The repository's default branch (`main`, `master`, etc.)](https://worktrunk.dev/config/#wt-config-state-default-branch)+- **marker**: [Custom status marker for a branch (shown in `wt list`)](https://worktrunk.dev/config/#wt-config-state-marker)+- **vars**: [experimental] [Custom variables per branch](https://worktrunk.dev/config/#wt-config-state-vars)+- **logs**: [Operation and debug logs](https://worktrunk.dev/config/#wt-config-state-logs)++### Examples++Get the default branch:+```bash+$ wt config state default-branch+```++Set the default branch manually:+```bash+$ wt config state default-branch set main+```++Set a marker for current branch:+```bash+$ wt config state marker set 🚧+```++Store arbitrary data:+```bash+$ wt config state vars set env=staging+```++Drop the regenerable caches:+```bash+$ wt config state cache clear+```++Show all stored state:+```bash+$ wt config state get+```++Clear all stored state:+```bash+$ wt config state clear+```++### Command reference++```+wt config state - Manage internal data and cache++Usage: wt config state [OPTIONS] <COMMAND>++Commands:+ get Get all stored state+ clear Clear all stored state+ cache Regenerable caches+ default-branch Default branch detection and override+ logs Operation and debug logs+ marker Branch markers+ vars [experimental] Custom variables per branch++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state cache++Regenerable caches.++View or drop worktrunk's regenerable caches in one place. Everything here is rebuilt on demand — clearing only forces recomputation, never data loss.++### What's cached++- **CI status** — GitHub/GitLab CI per branch (30–60s TTL), shown in [`wt list`](https://worktrunk.dev/list/#ci-status), plus the largest PR/MR number seen (sizes the CI column)+- **Summaries** — LLM-generated branch summaries (`wt list --full`, `wt switch` preview)+- **Git commands** — SHA-keyed disk caches: merge-tree, ancestry, diff-stats, and `wt switch` preview renders+- **Hints** — one-time hints already shown in this repo+- **Previous branch** — the `wt switch -` target, re-recorded on the next switch++`cache clear` drops all of the above with no prompt. It re-shows one-time hints and forgets the `wt switch -` target until the next switch — both repopulate on their own.++Without a subcommand, runs `get`.++### Examples++Show cache contents:+```bash+$ wt config state cache+```++Drop all caches:+```bash+$ wt config state cache clear+```++### Command reference++```+wt config state cache - Regenerable caches++Usage: wt config state cache [OPTIONS] [COMMAND]++Commands:+ get Show cache contents+ clear Drop all caches++Options:+ -h, --help+ Print help (see a summary with '-h')++Output:+ --format <FORMAT>+ Output format (text, json) [default: text]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state default-branch++Default branch detection and override.++Useful in scripts to avoid hardcoding `main` or `master`:++```bash+$ git rebase $(wt config state default-branch)+```++In a hook or alias template, prefer the `{{ default_branch }}` [template variable](https://worktrunk.dev/hook/#template-variables); `$(wt config state default-branch)` is for plain shell scripts.++Without a subcommand, runs `get`. Use `set` to override, or `clear` then `get` to re-detect.++`default-branch get` resolves the value and caches it on a miss; the aggregate `wt config state get` only reports the cache (read-only), so it can show `(none)` until something populates it.++### Detection++Worktrunk detects the default branch automatically:++1. **Worktrunk cache** — Checks `git config worktrunk.default-branch`+2. **Git cache** — Detects primary remote and checks its HEAD (e.g., `origin/HEAD`)+3. **Remote query** — If not cached, queries `git ls-remote` — typically 100ms–2s+4. **Local inference** — If no remote, infers from local branches++Once detected, the result is cached in `worktrunk.default-branch` for fast access.++The local inference fallback uses these heuristics in order:+- If only one local branch exists, uses it+- For bare repos or empty repos, checks `symbolic-ref HEAD`+- Checks `git config init.defaultBranch`+- Looks for common names: `main`, `master`, `develop`, `trunk`++If none of these match, detection fails; set it explicitly with `wt config state default-branch set BRANCH`.++### Command reference++```+wt config state default-branch - Default branch detection and override++Usage: wt config state default-branch [OPTIONS] [COMMAND]++Commands:+ get Get the default branch+ set Set the default branch+ clear Clear the default branch cache++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state logs++Operation and debug logs.++View and manage log files — hook output, command audit trail, and debug diagnostics.++### What's logged++Three kinds of logs live in `.git/wt/logs/`:++#### Command log (`commands.jsonl`)++All hook executions and LLM commands are recorded automatically — one JSON object per line. Rotates to `commands.jsonl.old` at 1MB (~2MB total). Fields:++| Field | Description |+|-------|-------------|+| `ts` | ISO 8601 timestamp |+| `wt` | The `wt` command that triggered this (e.g., `wt hook pre-merge --yes`) |+| `label` | What ran (e.g., `pre-merge user:lint`, `commit.generation`) |+| `cmd` | Shell command executed |+| `exit` | Exit code (`null` for background commands) |+| `dur_ms` | Duration in milliseconds (`null` for background commands) |++The command log appends entries and is not branch-specific — it records all activity across all worktrees.++#### Hook output logs++Hook output lives in per-branch subtrees under `.git/wt/logs/{branch}/`:++| Operation | Log path |+|-----------|----------|+| Background hooks | `{branch}/{source}/{hook-type}/{name}.log` |+| Background removal | `{branch}/internal/remove.log` |++All `post-*` hooks (post-start, post-switch, post-commit, post-merge) run in the background and produce log files. Source is `user` or `project`. Branch and hook names are sanitized for filesystem safety (invalid characters → `-`; short collision-avoidance hash appended). Same operation on same branch overwrites the previous log. Removing a branch clears its subtree; orphans from deleted branches can be swept with `wt config state logs clear`.++#### Diagnostic files++| File | Created when |+|------|-------------|+| `trace.log` | Running with `-vv` |+| `trace.jsonl` | Running with `-vv` |+| `subprocess.log` | Running with `-vv` |+| `diagnostic.md` | Running with `-vv` |++`trace.log` is the human-readable trace at `-vv` — each command's start (`$ …`) and completion (`✓`/`✗ … 12.3ms`), in-process spans, milestones, and bounded subprocess previews. `trace.jsonl` is the same event stream as one JSON object per line, for machines (`jq`, chrome://tracing); `wt config state logs profile` reads it to summarize a performance report (where time went, parallelism, redundant commands). `subprocess.log` holds the raw uncapped subprocess stdout/stderr bodies. `diagnostic.md` is a markdown bug-report bundle that leads with that same performance profile and inlines `trace.log`; `wt` prints a `gh gist create` command pointing at it. All four are overwritten on each `-vv` run.++### Location++All logs are stored in `.git/wt/logs/` (in the main worktree's git directory). All worktrees write to the same directory. Top-level files are shared logs (command audit + diagnostics); top-level directories are per-branch log trees.++### Structured output++`wt config state logs --format=json` emits three arrays — `command_log`, `hook_output`, `diagnostic`. Each entry carries a `file` (relative), `path` (absolute), `size`, and `modified_at` (unix seconds). Hook-output entries additionally expose `branch`, `source` (`user` / `project` / `internal`), `hook_type` (the `post-*` kind, or `null` for internal ops), and `name`. Filter with `jq` to pick out a specific entry.++### Examples++List all log files:+```bash+$ wt config state logs+```++Query the command log:+```bash+$ tail -5 .git/wt/logs/commands.jsonl | jq .+```++Path to one hook log (e.g. the `post-start` `server` hook for the current branch):+```bash+$ wt config state logs --format=json | jq -r '.hook_output[] | select(.source == "user" and .hook_type == "post-start" and (.name | startswith("server"))) | .path'+```++Logs for a specific branch:+```bash+$ wt config state logs --format=json | jq '.hook_output[] | select(.branch | startswith("feature"))'+```++Clear all logs:+```bash+$ wt config state logs clear+```++### Command reference++```+wt config state logs - Operation and debug logs++Usage: wt config state logs [OPTIONS] [COMMAND]++Commands:+ get List all log file paths+ profile Performance profile from a trace+ clear Clear all log files++Options:+ -h, --help+ Print help (see a summary with '-h')++Output:+ --format <FORMAT>+ Output format (text, json) [default: text]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state ci-status++CI status cache.++**Deprecated** — the CI status cache is now part of [`wt config state cache`](https://worktrunk.dev/config/#wt-config-state-cache). This subcommand still works but prints a deprecation notice.++Caches GitHub/GitLab CI status for display in [`wt list`](https://worktrunk.dev/list/#ci-status).++Requires `gh` (GitHub) or `glab` (GitLab) CLI, authenticated. Platform auto-detects from the remote URL; set `forge.platform = "github"` (or `"gitlab"`) in `.config/wt.toml` for SSH host aliases or self-hosted instances. For GitHub Enterprise or self-hosted GitLab, also set `forge.hostname`.++Checks open PRs/MRs first, then branch pipelines for branches with upstream. Local-only branches (no remote tracking) show blank.++Results cache for 30-60 seconds. Indicators dim when local changes haven't been pushed.++### Status values++| Status | Meaning |+|--------|---------|+| `passed` | All checks passed |+| `running` | Checks in progress |+| `failed` | Checks failed |+| `conflicts` | PR has merge conflicts |+| `no-ci` | No checks configured |+| `error` | Fetch error (rate limit, network, auth) |++See [`wt list` CI status](https://worktrunk.dev/list/#ci-status) for display symbols and colors.++Without a subcommand, runs `get` for the current branch. Use `clear` to reset cache for a branch or `clear --all` to reset all.++### Command reference++```+wt config state ci-status - CI status cache++Usage: wt config state ci-status [OPTIONS] [COMMAND]++Commands:+ get Get CI status for a branch+ clear Clear CI status cache++Options:+ -h, --help+ Print help (see a summary with '-h')++Output:+ --format <FORMAT>+ Output format (text, json) [default: text]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state marker++Branch markers.++Custom status text or emoji shown in the `wt list` Status column.++### Display++Markers appear at the end of the Status column, after git symbols:++```+$ wt list+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age Message+@ main ^⇡ ⇡1 33323bc1 1d Initial commit++ feature-api ↑ 🤖 ↑1 +1 70343f03 1d Add REST API end…++ review-ui ? ↑ 💬 ↑1 +1 a585d6ed 1d Add dashboard co…++ wip-docs ? – 33323bc1 1d Initial commit++○ Showing 4 worktrees, 2 with changes, 2 ahead, 1 column hidden+```++### Use cases++- **Work status** — `🚧` WIP, `✅` ready for review, `🔥` urgent+- **Agent tracking** — The [Claude Code](https://worktrunk.dev/claude-code/) plugin sets markers automatically+- **Notes** — Any short text: `"blocked"`, `"needs tests"`++### Storage++Stored in git config as `worktrunk.state.<branch>.marker`. Set directly with:++```bash+$ git config worktrunk.state.feature.marker '{"marker":"🚧","set_at":0}'+```++Without a subcommand, runs `get` for the current branch. For `--branch`, use `get --branch=NAME`.++### Command reference++```+wt config state marker - Branch markers++Usage: wt config state marker [OPTIONS] [COMMAND]++Commands:+ get Get marker for a branch+ set Set marker for a branch+ clear Clear marker for a branch++Options:+ -h, --help+ Print help (see a summary with '-h')++Output:+ --format <FORMAT>+ Output format (text, json) [default: text]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt config state vars++[experimental]++Custom variables per branch.++Store custom variables per branch. Values are stored as-is — plain strings or JSON.++### Examples++Set and get values:+```bash+$ wt config state vars set env=staging+$ wt config state vars get env+```++Store JSON:+```bash+$ wt config state vars set config='{"port": 3000, "debug": true}'+```++List all keys:+```bash+$ wt config state vars list+```++Operate on a different branch:+```bash+$ wt config state vars set env=production --branch=main+```++### Template access++Variables are available in [hook templates](https://worktrunk.dev/hook/#template-variables) as `{{ vars.<key> }}`. Use the `default` filter for keys that may not be set:++```toml+[post-start]+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.port | default('3000') }}"+```++JSON object and array values support dot access:++```bash+$ wt config state vars set config='{"port": 3000, "debug": true}'+```+```toml+[post-start]+dev = "npm start -- --port {{ vars.config.port }}"+```++### Storage format++Stored in git config as `worktrunk.state.<branch>.vars.<key>`. Keys must contain only letters, digits and hyphens — dots conflict with git config's section separator, underscores with its variable name format.++### Command reference++```+wt config state vars - [experimental] Custom variables per branch++Usage: wt config state vars [OPTIONS] <COMMAND>++Commands:+ get Get a value+ list List all keys+ set Set a value+ clear Clear a key or all keys++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/extending.md b/plugins/worktrunk/skills/worktrunk/reference/extending.mdnew file mode 100644index 000000000..091080eed--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/extending.md@@ -0,0 +1,239 @@+# Extending Worktrunk++Worktrunk has three extension mechanisms.++**[Hooks](#hooks)** are shell commands that run automatically at lifecycle events (switching, starting, committing, merging, removing). Defined in TOML.++**[Aliases](#aliases)** are reusable shell commands invoked as `wt <name>`. Defined in TOML.++**[Custom subcommands](#custom-subcommands)** are standalone executables invoked as `wt <name>`. Drop `wt-foo` on `PATH` and it becomes `wt foo`.++| | Hooks | Aliases | Custom subcommands |+|---|---|---|---|+| **Trigger** | Automatic (lifecycle events) | Manual (`wt <name>`) | Manual (`wt <name>`) |+| **Defined in** | TOML config | TOML config | Any executable on `PATH` |+| **Template variables** | Yes | Yes | No |+| **Shareable via repo** | `.config/wt.toml` | `.config/wt.toml` | Distribute the binary |+| **Language** | Shell commands | Shell commands | Any |++Hooks and aliases live in the same TOML config and share the [template engine](https://worktrunk.dev/hook/#template-variables). User config is trusted; project config requires approval on first run. When both define the same name, both run (user first).++## Hooks++Ten hooks cover five lifecycle events:++| Event | `pre-` (blocking) | `post-` (background) |+|-------|-------------------|---------------------|+| **switch** | `pre-switch` | `post-switch` |+| **start** | `pre-start` | `post-start` |+| **commit** | `pre-commit` | `post-commit` |+| **merge** | `pre-merge` | `post-merge` |+| **remove** | `pre-remove` | `post-remove` |++`pre-*` hooks block: failure aborts the operation. `post-*` hooks run in the background.++```toml+[pre-start]+deps = "npm ci"++[post-start]+server = "npm run dev -- --port {{ branch | hash_port }}"++[pre-merge]+test = "npm test"+```++See [`wt hook`](https://worktrunk.dev/hook/) for the full reference and built-in recipes (dev server per worktree, database per worktree, progressive validation). [Tips & Patterns](https://worktrunk.dev/tips-patterns/) has more.++## Aliases++Aliases are configured under `[aliases]`:++```toml+[aliases]+deploy = "fly deploy --config=fly.{{ env }}.toml --app=myapp-{{ branch }}"+open = "open http://localhost:{{ branch | hash_port }}"+since-main = "git log --oneline {{ default_branch }}..HEAD"+```++```bash+wt deploy --env=staging+wt open+```++`wt <name>` resolves to a built-in first, then an alias, then a [custom subcommand](#custom-subcommands).++### Templates++Aliases use the same [template engine as hooks](https://worktrunk.dev/hook/#template-variables): variables, [filters](https://worktrunk.dev/hook/#worktrunk-filters), [functions](https://worktrunk.dev/hook/#worktrunk-functions), and [`--KEY=VALUE` smart routing](https://worktrunk.dev/hook/#passing-values) (bind if the template references `KEY`, else forward to `{{ args }}`). For example, `wt deploy --env=staging` sets `{{ env }}`.++Alias templates add `{{ args }}` for positional CLI arguments. Operation-context variables (`target`, `base`, `pr_number`) aren't auto-populated, but can still be bound with `--KEY=VALUE`.++### Positional arguments++`{{ args }}` renders as a space-joined, shell-escaped string, ready to splice into a command:++```toml+[aliases]+s = "wt switch {{ args }}"+```++```bash+wt s some-branch+wt s feature/api+wt s 'has a space'+```++For indexing (`{{ args[0] }}`), looping, and counting, see [Passing values](https://worktrunk.dev/hook/#passing-values).++Tokens after `--` forward unconditionally, bypassing any binding. Writing `wt deploy -- --branch=foo` forwards the literal `--branch=foo` to `{{ args }}` even though the template references `{{ branch }}`.++An alias that forwards `{{ args }}` to a `wt` command — like `co = "wt switch {{ args }}"` or `cm = "wt step commit {{ args }}"` — inherits that command's argument and flag completion, so `wt co <Tab>` completes branches the same way `wt switch <Tab>` does.++### Inspecting and previewing++- `wt config alias show <name>` prints the template.+- `wt config alias dry-run <name> [-- args...]` prints the rendered command.++```bash+wt config alias show deploy+wt config alias dry-run deploy+wt config alias dry-run deploy -- --env=staging+```++### Multi-step pipelines++`[[aliases.NAME]]` defines a pipeline using the [same `[[block]]` semantics as hooks](https://worktrunk.dev/hook/#hook-forms): blocks run in order, keys within a block run concurrently, and a step failure aborts the remainder.++```toml+[[aliases.release]]+test = "cargo test"++[[aliases.release]]+build = "cargo build --release"+package = "cargo package --no-verify"++[[aliases.release]]+publish = "cargo publish {{ args }}"+```++Every step sees the same `{{ args }}` and bound variables. `wt release -- --dry-run` forwards `--dry-run` to `publish` without affecting earlier steps.++### Changing directory++`wt switch`, `wt merge` (when it leaves the removed source), and `wt remove` of the current worktree change the parent shell's directory even when invoked from an alias; the Worktrunk shell integration propagates the change through. Other shell state doesn't persist: the alias runs in a subshell, so `cd`, `export`, and similar commands only affect that subshell.++### Deferring expansion to a nested `wt` command++A `wt step for-each` alias that prints the same branch in every worktree is rendering `{{ branch }}` too early. An alias body renders once at dispatch, in the invoking worktree, so a bare `{{ branch }}` is baked to that worktree's branch before for-each iterates. (`wt config alias dry-run <name>` shows the rendered body, with the value already baked in.)++`{% raw %}…{% endraw %}` defers the variable: it survives the dispatch render as a literal `{{ branch }}`, and for-each expands it per worktree. One catch for `for-each`: the deferred `{{ branch }}` has spaces, so the alias body's `sh -c` splits it into `{{`, `branch`, `}}` before for-each sees it (`Failed to expand for-each argument: syntax error`). Give for-each its own `sh -c '…'` to keep the value one token:++```toml+[aliases]+show-branches = "wt step for-each -- sh -c 'echo {% raw %}{{ branch }}{% endraw %}'"+```++`wt show-branches` prints each worktree's own branch.++`wt switch --execute` defers the same way, without the extra wrapper: its `--execute '…'` argument is already a single quoted string, so only `{% raw %}` is needed. Here `{{ worktree_path }}` expands against the worktree being created, not the one the alias ran from:++```toml+[aliases]+echo-target = "wt switch {{ args }} --no-cd --execute 'echo {% raw %}{{ worktree_path }}{% endraw %}'"+```++A repo-level variable like `{{ default_branch }}` needs no deferral: it is identical in every worktree, so a bare `{{ default_branch }}` is already correct everywhere.++### Recipe: rebase every worktree onto its upstream++```toml+[aliases]+up = '''+git fetch --all --prune && wt step for-each -- sh -c '+ git rev-parse --verify -q @{u} >/dev/null || exit 0+ g=$(git rev-parse --git-dir)+ test -d "$g/rebase-merge" -o -d "$g/rebase-apply" && exit 0+ git update-index --refresh -q >/dev/null || true+ git rebase @{u} --no-autostash || git rebase --abort+''''+```++`wt up` fetches all remotes, then iterates every worktree: skip if no upstream, skip if mid-rebase, refresh the index to drop stale stat entries, then rebase and auto-abort on conflict. It rebases onto git-native `@{u}` rather than a `{{ … }}` template, so git resolves each worktree's own upstream and there is nothing to defer.++### Recipe: move or copy in-progress changes to a new worktree++`wt switch --create` lands you in a clean worktree. To carry staged, unstaged, and untracked changes along, pair it with `git stash`:++```toml+# .config/wt.toml+[aliases]+move-changes = '''+if git diff --quiet HEAD && test -z "$(git ls-files --others --exclude-standard)"; then+ wt switch --create {{ to }} --execute="{{ args }}"+else+ git stash push --include-untracked --quiet+ wt switch --create {{ to }} --execute="git stash pop --index; {{ args }}"+fi+'''+```++Run with `wt move-changes --to=feature-xyz`. The guard skips the stash when nothing is in flight; otherwise `git stash push` captures everything and `--execute` pops it in the new worktree with the staged/unstaged split intact. Anything after `--` runs in the new worktree after pop. For example, `wt move-changes --to=feature-xyz -- claude` opens Claude there.++To copy instead of move, add `git stash apply --index --quiet` right after the push.++### Recipe: tail a specific hook log++`wt config state logs --format=json` emits structured entries (`branch`, `source`, `hook_type`, `name`, `path`). Pipe through `jq` to resolve one entry, then wrap in an alias for quick access:++```toml+[aliases]+hook-log = '''+tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sanitize_hash }}" --arg kind "{{ kind }}" '+ .hook_output[]+ | select(.branch == "{{ branch | sanitize_hash }}" and .hook_type == $kind and .name == $name)+ | .path+' | head -1)"+'''+```++Run with `wt hook-log --kind=post-start --name=server` to tail the log for the `server` hook on the current branch. `--kind` picks the hook type; the branch is pulled from the current worktree via `{{ branch }}`. `sanitize_hash` rewrites `branch` and `name` to filesystem-safe forms with a hash suffix that keeps distinct originals unique (the same transformation Worktrunk applies on disk), so the alias resolves the right log even when either contains characters like `/`.++## Custom subcommands++[experimental]++Any executable named `wt-<name>` on `PATH` becomes available as `wt <name>`, the same pattern git uses for `git-foo`. Built-in commands and [aliases](#aliases) take precedence.++```bash+wt sync origin # runs: wt-sync origin+wt -C /tmp/repo sync # -C is forwarded as the child's working directory+```++Arguments pass through verbatim, stdio is inherited, and the child's exit code propagates unchanged.++### Examples++- [`worktrunk-sync`](https://github.com/pablospe/worktrunk-sync): rebases stacked worktree branches in the dependency order inferred from git history. Install with `cargo install worktrunk-sync`, then run as `wt sync`.++## Reference: hooks vs. aliases++Aside from the differences below, hooks and aliases behave the same.++<details>+<summary>Interface differences</summary>++| Axis | Hooks | Aliases |+|------|-------|---------|+| Invocation | `wt hook <type> [args...]` (nested under the `hook` built-in) | `wt <name> [args...]` (top-level) |+| Bare positionals | Filter names (`wt hook pre-merge test build` runs only `test` and `build`) | Forwarded to `{{ args }}` |+| Reach `{{ args }}` from positionals | Must use `--` (`wt hook pre-merge -- extra`) | Any bare positional lands there |+| Approval skip flag | Post-subcommand `--yes` / `-y` supported (`wt hook pre-merge --yes`) | Only the global form (`wt -y <alias>`); post-alias `--yes` falls through to `{{ args }}` |+| Source discrimination | `user:` / `project:` / `user:name` / `project:name` filter syntax | Run user first, then project; no filter syntax |+| Force-bind escape | `--var KEY=VALUE` (deprecated in favor of `--KEY=VALUE`, but still force-binds) | None; smart routing is the only path |+| `--help` | `wt hook --help` lists hook types; `wt hook <type> --help` shows flags and arguments for that type | The template body is the documentation: `wt <alias> --help` redirects to `wt config alias show` / `dry-run`. `wt --help` and `wt step --help` list configured aliases alongside built-in commands |+| Inspection | `wt hook show [type] [--expanded]` | `wt config alias show <name>` / `wt config alias dry-run <name>` |+| Stdin | All template variables as JSON (parse with `json.load(sys.stdin)`) | Inherits parent stdin (pipes pass through; interactive TUIs like `wt switch` keep the tty) |+| Template-context extras | `hook_type`, `hook_name`, per-type operation vars (`base`, `target`, `pr_number`, …) | `args` on top of the shared base variables |++</details>diff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdnew file mode 100644index 000000000..070caf402--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -0,0 +1,302 @@+# FAQ++## How does Worktrunk compare to alternatives?++### vs. branch switching++Branch switching uses one directory: uncommitted changes from one agent get mixed with the next agent's work, or block switching entirely. Worktrees give each agent its own directory with independent files and index.++### vs. Plain `git worktree`++Git's built-in worktree commands work but require manual lifecycle management:++```bash+# Plain git worktree workflow+$ git worktree add -b feature-branch ../myapp-feature main+$ cd ../myapp-feature+# ...work, commit, push...+$ cd ../myapp+$ git merge feature-branch+$ git worktree remove ../myapp-feature+$ git branch -d feature-branch+```++Worktrunk automates the full lifecycle:++```bash+$ wt switch --create feature-branch # Creates worktree, runs setup hooks+# ...work...+$ wt merge # Merges into default branch, cleans up+```++No cd back to main — `wt merge` runs from the feature worktree and merges into the target, like GitHub's merge button.++What `git worktree` doesn't provide:++- Consistent directory naming and cleanup validation+- Project-specific automation (install dependencies, start services)+- Unified status across all worktrees (commits, CI, conflicts, changes)++### vs. git-machete / git-town++Different scopes:++- **git-machete**: Branch stack management in a single directory+- **git-town**: Git workflow automation in a single directory+- **worktrunk**: Multi-worktree management with hooks and status aggregation++These tools can be used together—run git-machete or git-town inside individual worktrees.++### vs. Git TUIs (lazygit, gh-dash, etc.)++Git TUIs operate on a single repository. Worktrunk manages multiple worktrees, runs automation hooks, and aggregates status across branches. TUIs work inside each worktree directory.++## Does Worktrunk support stacked branches?++Not natively — stacked-branch workflows are a large design space, so Worktrunk treats them as an extension rather than a built-in. [`worktrunk-sync`](https://github.com/pablospe/worktrunk-sync) is a community tool that auto-detects the branch dependency tree from git history and rebases each branch onto its parent in topological order. Install with `cargo install worktrunk-sync` and run as `wt sync` (via [custom subcommands](https://worktrunk.dev/extending/#custom-subcommands)).++## How do I move uncommitted changes to a new worktree?++Stash the changes, create the worktree, then pop:++```bash+$ git stash push -u # -u also stashes untracked files+$ wt switch --create feature # new branch off the default branch+$ git stash pop # changes reappear in the new worktree+```++The stash lives in the shared `.git` directory, so it's reachable from the new worktree. The original branch is left clean.++`wt switch --create` bases the new branch on the default branch. To base it on the current commit instead, pass `--base=@` (needed when the current branch has commits beyond the default branch).++## There's an issue with my shell setup++If shell integration isn't working (auto-cd not happening, completions missing, `wt` not found as a function), the fastest path to a fix is using Claude Code with the Worktrunk plugin:++1. Install the [Worktrunk plugin](https://worktrunk.dev/claude-code/) in Claude Code+2. Ask Claude to debug the Worktrunk shell integration++Claude will run `wt config show`, inspect the shell config files, and identify the issue.++If Claude can't fix it, please [open an issue](https://github.com/max-sixty/worktrunk/issues/new?title=Shell%20setup%20issue&body=%23%23%20Shell%20and%20OS%0A%0A-%20Shell%3A%20%0A-%20OS%3A%20%0A%0A%23%23%20Output%20of%20%60wt%20config%20show%60%0A%0A%60%60%60%0A%0A%60%60%60%0A%0A%23%23%20What%20Claude%20found%20%28if%20available%29%0A%0A) with the output of `wt config show`, the shell (bash/zsh/fish), and OS. (And even if it fixes the problem, feel free to open an issue: non-standard success cases are useful for ensuring Worktrunk is easy to set up for others.)++## What does `-v` / `-vv` do?++Three verbosity levels. Each is a superset of the previous one.++| Level | Stderr | Files (`.git/wt/logs/`) | Use case |+|-------|--------|-------------------------|----------|+| (none) | Warnings only | — | Normal use |+| `-v` | + Info: hook output, alias template variable resolution | — | Debugging hooks/aliases |+| `-vv` | Same as `-v` | + `trace.log`, `trace.jsonl`, `subprocess.log`, `diagnostic.md` | Filing a bug |++At `-vv`, debug-level records (command lines, in-process spans, bounded subprocess preview) route to `trace.log` instead of stderr — so the terminal stays readable while the deep trace lands on disk. A one-line pointer on stderr shows where the files went.++The `-vv` files have distinct audiences:++- **`trace.log`** — the human trace (bounded ~1K lines, gistable): each command's start (`$ git status`) and finish (`✓ git status [wt] 12.3ms`, `✗` on failure), spans, and milestones.+- **`trace.jsonl`** — the same records as one JSON object per line, for machines (`jq`, chrome://tracing). `wt config state logs profile` reads it.+- **`subprocess.log`** — raw uncapped stdout/stderr of every subprocess `wt` spawns (multi-MB possible, e.g. full `git log -p` output). The deep-dive escape hatch.+- **`diagnostic.md`** — markdown bug-report bundle that leads with the performance report (subprocess time by command type, slowest calls, repeated calls — the same rendering `wt config state logs profile` produces from `trace.jsonl`) and inlines `trace.log`. `wt` prints a `gh gist create` command pointing at it.++`RUST_LOG` overrides the flag baseline when set (`RUST_LOG=debug wt -v` lifts `-v` to debug-on-stderr).++The flags only reach a command you type; shell completion runs as its own process with nowhere to pass one. Set `WORKTRUNK_VERBOSE=0|1|2` to apply the level to *every* invocation, completion included — it's the env-var equivalent of `-v`/`-vv`, so level 2 writes the same `trace.log`/`trace.jsonl`/`subprocess.log`/`diagnostic.md` files. An explicit `-v`/`-vv` on a command raises the level further but never lowers this baseline. To profile a slow tab-completion, run it the way your shell does — e.g. `WORKTRUNK_VERBOSE=2 COMPLETE=fish wt -- wt switch ''` — then render the result with `wt config state logs profile`.++## What files does Worktrunk create?++### 1. Worktree directories++Created by `wt switch <branch>` when switching to a branch that doesn't have a worktree. Use `wt switch --create <branch>` to create a new branch. Default location is `../<repo>.<branch>` (sibling to main repo), configurable via `worktree-path` in user config.++**To remove:** `wt remove <branch>` removes the worktree directory and deletes the branch.++### 2. Config files++| File | Created by | Purpose |+|------|------------|---------|+| `~/.config/worktrunk/config.toml` | `wt config create` | User preferences |+| `~/.config/worktrunk/approvals.toml` | Approving project commands | Approved hook and alias commands |+| `.config/wt.toml` | `wt config create --project` | Project hooks (checked into repo) |++User config location: `$XDG_CONFIG_HOME/worktrunk/` (or `~/.config/worktrunk/`) on Linux/macOS, `%APPDATA%\worktrunk\` on Windows.++**To remove:** Delete directly. User config: `rm ~/.config/worktrunk/config.toml`. Project config: `rm .config/wt.toml` (and commit).++### 3. Shell integration++Created by `wt config shell install`:++- **Bash**: adds line to `~/.bashrc`+- **Zsh**: adds line to `~/.zshrc` (or `$ZDOTDIR/.zshrc`)+- **Fish**: creates `~/.config/fish/functions/wt.fish` and `~/.config/fish/completions/wt.fish`+- **Nushell** [experimental]: creates `wt.nu` in Nushell's user vendor-autoload directory — the last entry of `$nu.vendor-autoload-dirs`, under `$nu.data-dir` (typically `~/.local/share/nushell/vendor/autoload` on Linux, `~/Library/Application Support/nushell/vendor/autoload` on macOS)+- **PowerShell** (Windows): creates both profile files if they don't exist:+ - `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+)+ - `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)++**PowerShell detection on Windows:** When running from cmd.exe or PowerShell, both PowerShell profile files are created automatically. When running from Git Bash or MSYS2, PowerShell is skipped (use `wt config shell install powershell` to create the profiles explicitly).++**To remove:** `wt config shell uninstall`.++### 4. Metadata in `.git/` (automatic)++Worktrunk stores small amounts of cache and log data in the repository's `.git/` directory:++| Location | Purpose | Created by |+|----------|---------|------------|+| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, the largest PR/MR number seen (sizes the `wt list` CI column), and git command results (merge-tree, integration probes, diff stats, ancestry checks, ahead/behind counts, merge bases) | `wt list`, `wt merge`, `wt remove` |+| `.git/wt/cache/summary/{branch}/{hash}.json` | Cached LLM branch summaries, content-addressed by diff hash | `wt list --full`, `wt switch` (when `[list] summary = true`) |+| `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` |+| `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands |+| `.git/wt/logs/trace.log` | Human debug trace for issue reporting | Running with `-vv` |+| `.git/wt/logs/trace.jsonl` | Machine trace (one JSON object per record) | Running with `-vv` |+| `.git/wt/logs/subprocess.log` | Raw uncapped subprocess stdout/stderr (may be multi-MB) | Running with `-vv` |+| `.git/wt/logs/diagnostic.md` | Diagnostic report for issue reporting (leads with the performance profile) | Running with `-vv` |+| `.git/wt/trash/<name>-<timestamp>` | Staged worktree contents pending background deletion | `wt remove` |++None of this is tracked by git or pushed to remotes.++**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.++### What Worktrunk does NOT create++- No files outside `.git/`, config directories, or worktree directories+- No global git hooks+- No modifications to `~/.gitconfig`+- No long-running background processes or daemons++## What can Worktrunk delete?++Worktrunk can delete **worktrees** and **branches**. Both have safeguards.++### Worktree removal++`wt remove` mirrors `git worktree remove`: it refuses to remove worktrees with uncommitted changes (staged, modified, or untracked files). The `--force` flag removes the worktree anyway, discarding all of those changes.++For worktrees containing precious ignored data (databases, caches, large assets), use `git worktree lock`:++```bash+git worktree lock ../myproject.feature --reason "Contains local database"+```++Locked worktrees show `⊞` in `wt list`. Neither `git worktree remove` nor `wt remove` (even with `--force`) will delete them. Unlock with `git worktree unlock`.++### Branch deletion++By default, `wt remove` only deletes branches whose content is already in the default branch. Branches showing `_` (same commit) or `⊂` (integrated) in `wt list` are safe to delete.++For the full algorithm, see [Branch cleanup](https://worktrunk.dev/remove/#branch-cleanup) — it handles squash-merge and rebase workflows where commit history differs but file changes match.++Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.++### Other cleanup++- `wt remove` — in addition to the target worktree, runs a background internal sweep: deletes `.git/wt/trash/` entries older than 24 hours (eventual cleanup for directories orphaned when a previous background removal was interrupted), and terminates (`SIGTERM` then `SIGKILL`) `git fsmonitor--daemon` processes whose worktree no longer exists+- `wt remove` — terminates the removed worktree's `git fsmonitor--daemon` process. Git starts this per-worktree filesystem-watch daemon when `core.fsmonitor=true`; once its worktree is gone it would leak. Removal sends `git fsmonitor--daemon stop`, then resolves that daemon's PID from its IPC socket and force-terminates it (SIGTERM, then SIGKILL) if it didn't exit. The signal only ever targets the daemon whose socket resolves to the worktree being removed.+- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)+- `wt config shell install` — when migrating an integration to a new location, removes the worktrunk-managed file left at the old one: fish `conf.d/wt.fish` (now `functions/wt.fish`) and nushell wrappers stranded under `<config-dir>/vendor/autoload` (now `<data-dir>/vendor/autoload`)+- `wt config shell uninstall` — removes shell integration from rc files++See [What files does Worktrunk create?](#what-files-does-worktrunk-create) for details.++## What commands does Worktrunk execute?++Worktrunk runs `git` commands internally and optionally runs `gh` (GitHub) or `glab` (GitLab) for CI status. Beyond that, user-defined commands execute in four contexts:++1. **User hooks** (`~/.config/worktrunk/config.toml`) — Personal automation for all repositories+2. **Project hooks** (`.config/wt.toml`) — Repository-specific automation+3. **LLM commands** (`~/.config/worktrunk/config.toml`) — Commit message generation and [branch summaries](https://worktrunk.dev/llm-commits/#branch-summaries)+4. **--execute flag** — Explicitly provided commands++User hooks and user aliases don't require approval (you defined them). Commands from project hooks and project aliases require approval on first run. Approved commands are saved to the approvals file (`approvals.toml`). If a command changes, Worktrunk requires new approval.++### Example approval prompt++▲ repo needs approval to execute 3 commands:++○ pre-start install:+ npm ci+○ pre-start build:+ cargo build --release+○ pre-start env:+ echo 'PORT={{ branch | hash_port }}' > .env.local++❯ Allow and remember? [y/N]++Use `--yes` to bypass prompts (useful for CI/automation).++### Command log++All hook executions and LLM commands are recorded in `.git/wt/logs/commands.jsonl` — one JSON object per line. Fields: `ts` (timestamp), `wt` (the wt command that triggered it), `label` (what ran, e.g., `pre-merge user:lint`), `cmd` (shell command), `exit` (exit code, `null` for background), `dur_ms` (duration, `null` for background). The file rotates to `commands.jsonl.old` at 1MB, bounding storage to ~2MB.++View the log with `wt config state logs get`, or query directly:++```bash+# Recent commands+$ tail -5 .git/wt/logs/commands.jsonl | jq .++# Failed commands+$ jq 'select(.exit != 0 and .exit != null)' .git/wt/logs/commands.jsonl+```++Clear with `wt config state logs clear`.++## Does Worktrunk work on Windows?++Yes. Core commands, shell integration, and tab completion work in both Git Bash and PowerShell. See [installation](https://worktrunk.dev/worktrunk/#install) for setup details, including avoiding the Windows Terminal `wt` conflict.++**Git for Windows required** — Hooks use bash syntax and execute via Git Bash, so [Git for Windows](https://gitforwindows.org/) must be installed even when PowerShell is the interactive shell.++The `wt switch` interactive picker runs on Windows too, on [skim](https://github.com/skim-rs/skim)'s crossterm backend.++## How does Worktrunk determine the default branch?++Worktrunk checks the local git cache first, queries the remote if needed, and falls back to local inference when no remote exists.++If the remote's default branch has changed (e.g., renamed from master to main), clear the cache with `wt config state default-branch clear`.++For full details on the detection mechanism, see `wt config state default-branch --help`.++## My `for-each` or `--execute` alias prints the same value in every worktree++An alias body renders once at dispatch, in the invoking worktree's context, so a per-worktree variable like `{{ branch }}` is baked to that one worktree's value before the nested `wt` command iterates. Every worktree then sees the same value.++Confirm it with `wt config alias dry-run <name>`: if the value is already substituted (e.g. `… echo branch=main`), it was baked at dispatch.++To defer a variable to the nested command, wrap it as `{% raw %}{{ branch }}{% endraw %}`; for `wt step for-each`, also keep it inside a quoted `sh -c '…'` so the alias's shell doesn't word-split it. See [deferring expansion in an alias](https://worktrunk.dev/extending/#deferring-expansion-to-a-nested-wt-command). A repo-level variable like `{{ default_branch }}` is unaffected — it is identical in every worktree.++## Installation fails with C compilation errors++Errors related to tree-sitter or C compilation (C99 mode, `le16toh` undefined) can be avoided by installing without syntax highlighting:++```bash+cargo install worktrunk --no-default-features --features cli+```++This disables bash syntax highlighting in command output but keeps all core functionality. The syntax highlighting feature requires C99 compiler support and can fail on older systems or minimal Docker images.++## Running tests (for contributors)++### Quick tests++```bash+cargo test+```++### Full integration tests++Shell integration tests require bash, zsh, fish, and nushell:++```bash+cargo test --test integration --features shell-integration-tests+```++## How can I contribute?++- Star the repo+- Try it out and [open an issue](https://github.com/max-sixty/worktrunk/issues) with feedback — even small annoyances+- What worktree friction does Worktrunk not yet solve? [Tell us](https://github.com/max-sixty/worktrunk/issues)+- Send to a friend+- Post about it on [X](https://twitter.com/intent/tweet?text=Worktrunk%20%E2%80%94%20CLI%20for%20git%20worktree%20management&url=https%3A%2F%2Fworktrunk.dev), [Reddit](https://www.reddit.com/submit?url=https%3A%2F%2Fworktrunk.dev&title=Worktrunk%20%E2%80%94%20CLI%20for%20git%20worktree%20management), or [LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fworktrunk.dev)diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.mdnew file mode 100644index 000000000..049b7c850--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md@@ -0,0 +1,377 @@+# wt hook++Run configured hooks.++Hooks are shell commands that run at key points in the worktree lifecycle — automatically during `wt switch`, `wt merge`, & `wt remove`, or on demand via `wt hook <type>`. Both user and project hooks are supported.++# Hook Types++| Event | `pre-` — blocking | `post-` — background |+|-------|-------------------|---------------------|+| **switch** | `pre-switch` | `post-switch` |+| **create** | `pre-start` | `post-start` |+| **commit** | `pre-commit` | `post-commit` |+| **merge** | `pre-merge` | `post-merge` |+| **remove** | `pre-remove` | `post-remove` |++`pre-*` hooks block — failure aborts the operation. `post-*` hooks run in the background with output logged (use [`wt config state logs`](https://worktrunk.dev/config/#wt-config-state-logs) to find and manage log files). Use `-v` to see the template variables for background hooks; `wt hook <type> --dry-run` previews the commands.++The most common creation hook is `post-start` — it runs background tasks (dev servers, file copying, builds) without blocking worktree creation. Prefer `post-start` over `pre-start` unless a later step needs the work completed first.++| Hook | Purpose |+|------|---------|+| `pre-switch` | Runs before branch resolution or worktree creation. `{{ branch }}` is the destination as typed (before resolution) |+| `post-switch` | Triggers on all switch results: creating, switching to existing, or staying on current |+| `pre-start` | Runs once when a new worktree is created, blocking `post-start`/`--execute` until complete: dependency install, env file generation |+| `post-start` | Runs once when a new worktree is created, in the background: dev servers, long builds, file watchers, copying caches |+| `pre-commit` | Formatters, linters, type checking — runs during `wt merge` before the squash commit |+| `post-commit` | CI triggers, notifications, background linting |+| `pre-merge` | Tests, security scans, build verification — runs after rebase, before merge to target |+| `post-merge` | Deployment, notifications, installing updated binaries. Runs in the target branch worktree if it exists, otherwise the primary worktree |+| `pre-remove` | Cleanup before worktree deletion: saving test artifacts, backing up state. Runs in the worktree being removed |+| `post-remove` | Stopping dev servers, removing containers, notifying external systems. Template variables reference the removed worktree |++During `wt merge`, hooks run in this order: pre-commit → post-commit → pre-merge → pre-remove → post-remove + post-merge. See [`wt merge`](https://worktrunk.dev/merge/#pipeline) for the complete pipeline.++# Security++Project commands require approval on first run:++```+▲ repo needs approval to execute 3 commands:++○ pre-start install:+ npm ci+○ pre-start build:+ cargo build --release+○ pre-start env:+ echo 'PORT={{ branch | hash_port }}' > .env.local++❯ Allow and remember? [y/N]+```++- Approvals are saved to `~/.config/worktrunk/approvals.toml`+- If a command changes, new approval is required+- Declining skips every project command for that operation — including any already approved — and continues without them; saved approvals are unaffected+- Use `--yes` to bypass prompts — useful for CI and automation+- Use `--no-hooks` to skip hooks++Manage approvals with `wt config approvals add` and `wt config approvals clear`.++# Configuration++Hooks can be defined in project config (`.config/wt.toml`) or user config (`~/.config/worktrunk/config.toml`). Both use the same format. The project config is read from the worktree the command ran in.++## Hook forms++Hooks take one of three forms, determined by their TOML shape.++A string is a single command:++```toml+pre-start = "npm install"+```++A table is multiple commands that run concurrently:++```toml+[post-start]+server = "npm run dev"+watch = "npm run watch"+```++A pipeline is a sequence of `[[hook]]` blocks run in order. Each block is one step; multiple keys within a block run concurrently. A failing step aborts the rest of the pipeline:++```toml+[[post-start]]+install = "npm ci"++[[post-start]]+build = "npm run build"+server = "npm run dev"+```++Here `install` runs first, then `build` and `server` run together.++Templates are syntax-checked before the pipeline starts and rendered as each step runs, so a step can store [per-branch vars](https://worktrunk.dev/config/#wt-config-state-vars) that later steps read via `{{ vars.<key> }}`.++Most hooks don't need `[[hook]]` blocks. Reach for them when there's a dependency chain — typically setup that must complete before later steps, like installing dependencies before running a build and dev server concurrently.++## Project vs user hooks++| Aspect | Project hooks | User hooks |+|--------|--------------|------------|+| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |+| Scope | Single repository | All repositories (or [per-project](https://worktrunk.dev/config/#user-project-specific-settings)) |+| Approval | Required | Not required |+| Execution order | After user hooks | First |++Skip all hooks with `--no-hooks`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.++## Template variables++Hooks can use template variables that expand at runtime:++| Kind | Variable | Description |+|------|----------|-------------|+| active | `{{ branch }}` | Branch name |+| | `{{ worktree_path }}` | Worktree path |+| | `{{ worktree_name }}` | Worktree directory name |+| | `{{ commit }}` | Branch HEAD SHA |+| | `{{ short_commit }}` | Branch HEAD SHA, abbreviated per `core.abbrev` |+| | `{{ upstream }}` | Branch upstream (if tracking a remote) |+| operation | `{{ base }}` | Base branch name (switch/create only) |+| | `{{ base_worktree_path }}` | Base worktree path |+| | `{{ target }}` | Target branch name |+| | `{{ target_worktree_path }}` | Target worktree path (when target has a worktree) |+| | `{{ pr_number }}` | PR/MR number (post-switch, pre-start, post-start; when creating via `pr:N` / `mr:N`) |+| | `{{ pr_url }}` | PR/MR web URL (post-switch, pre-start, post-start; when creating via `pr:N` / `mr:N`) |+| repo | `{{ repo }}` | Repository directory name |+| | `{{ repo_path }}` | Absolute path to repository root |+| | `{{ owner }}` | Primary remote owner path (may include subgroups) |+| | `{{ primary_worktree_path }}` | Primary worktree path |+| | `{{ default_branch }}` | Default branch name |+| | `{{ remote }}` | Primary remote name |+| | `{{ remote_url }}` | Remote URL |+| exec | `{{ cwd }}` | Directory where the hook command runs |+| | `{{ hook_type }}` | Hook type being run (e.g. `pre-start`, `pre-merge`) |+| | `{{ hook_name }}` | Hook command name (if named) |+| | `{{ args }}` | Tokens forwarded from the CLI — see [Running Hooks Manually](#running-hooks-manually) |+| user | `{{ vars.<key> }}` | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) |++The `repo` variables (`repo`, `repo_path`, `owner`, `primary_worktree_path`, `default_branch`, `remote`, `remote_url`) are constant across the whole repository — `default_branch` is the same in every worktree. The `active` variables (`branch`, `worktree_path`, `worktree_name`, `commit`, `short_commit`, `upstream`) vary per worktree.++Bare variables (`branch`, `worktree_path`, `commit`) refer to the branch the operation acts on: the destination for switch/create, the source for merge/remove. `base` and `target` give the other side:++| Operation | Bare vars | `base` | `target` |+|-----------|-----------|--------|----------|+| switch/create | destination | where you came from | = bare vars |+| commit (during merge/squash) | worktree being squashed | = bare vars | integration target |+| merge | feature being merged | = bare vars | merge target |+| remove | branch being removed | = bare vars | where you end up |++All hooks share the same perspective — `{{ branch | hash_port }}` produces the same port in `post-start` and `post-remove`.++`cwd` is the worktree root where the hook command runs. It equals `worktree_path` except in three cases:++- `pre-switch`: hook runs in the source worktree; `worktree_path` is the destination+- `post-remove`: the active worktree is gone, so the hook runs in the primary worktree+- `post-merge` with removal: the active worktree is gone, so the hook runs in the target worktree++Undefined variables error — use conditionals or defaults for optional behavior:++```toml+[pre-start]+# Rebase onto upstream if tracking a remote branch (e.g., wt switch --create feature origin/feature)+sync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"+```++Run any hook-firing command with `-v` to see the resolved variables for the actual invocation — each hook prints a `template variables:` block showing every in-scope variable and its value (`(unset)` for conditional vars that didn't populate, like `target_worktree_path` during `wt switch -`). Aliases do the same under `-v`: `wt -v <alias>` prints the alias's in-scope variables before the pipeline runs.++Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:++```toml+[post-start]+dev = "ENV={{ vars.env | default('development') }} npm start -- --port {{ vars.config.port | default('3000') }}"+```++## Worktrunk filters++Templates support Jinja2 filters for transforming values:++| Filter | Example | Description |+|--------|---------|-------------|+| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |+| `sanitize_db` | `{{ branch \| sanitize_db }}` | Database-safe identifier with hash suffix (`[a-z0-9_]`, max 48 chars) |+| `sanitize_hash` | `{{ branch \| sanitize_hash }}` | Filesystem-safe name with hash suffix for uniqueness |+| `hash` | `{{ branch \| hash }}` | 3-character base36 digest of the input |+| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |+| `dirname` | `{{ repo_path \| dirname }}` | Strip the last path component (`/a/b/c` → `/a/b`) |+| `basename` | `{{ repo_path \| basename }}` | Keep only the last path component (`/a/b/c` → `c`) |+| `codename(n)` | `{{ branch \| codename(2) }}` | Deterministic friendly words |++The `sanitize_db` filter produces database-safe identifiers — lowercase alphanumeric and underscores, no leading digits, with a 3-character hash suffix to avoid collisions and reserved words. The `sanitize_hash` filter produces a filesystem-safe name and appends a 3-character hash suffix when sanitization changed the input, so distinct originals never collide — already-safe names pass through unchanged. The `codename(n)` filter produces deterministic friendly names from an input string: `codename(1)` returns a noun, `codename(2)` returns `adjective-noun`, and higher counts add more adjectives. The pool is large (~1.26M combinations for `codename(2)`), so it usually stands alone as a worktree leaf:++```toml+# Friendly branch-derived worktree names, e.g. myproject.malleable-opah+worktree-path = "{{ repo_path }}/../{{ repo }}.{{ branch | codename(2) }}"+```++When you want both a friendly name and the original branch identity in the path, put the branch name in a parent directory:++```toml+worktree-path = "{{ repo_path }}/../worktrees/{{ branch | sanitize }}/{{ branch | codename(2) }}"+```++The `hash` filter is the bare 3-character base36 digest, useful for composing your own truncate-with-collision-avoidance recipes when an output budget is tight (e.g., Unix socket paths capped at 107 bytes):++```toml+# Truncated branch slug + hash: collisions remain disambiguated even when prefixes match+worktree-path = "/tmp/{{ (branch | sanitize)[:20] }}_{{ branch | sanitize | hash }}"+```++The `dirname` and `basename` filters traverse paths. They're useful for bare repos in a hidden directory like `myproject/.git`, where `{{ repo }}` resolves to `.git`:++```toml+# Place worktrees as siblings of the bare repo, named `<wrapper>.<branch>`+worktree-path = "{{ repo_path }}/../{{ repo_path | dirname | basename }}.{{ branch | sanitize }}"+```++The `hash_port` filter is useful for running dev servers on unique ports per worktree:++```toml+[post-start]+dev = "npm run dev -- --host {{ branch }}.localhost --port {{ branch | hash_port }}"+```++Hash any string, including concatenations:++```toml+# Unique port per repo+branch combination+dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"+```++Variables are shell-escaped automatically — quotes around `{{ ... }}` are unnecessary and can cause issues with special characters.++## Worktrunk functions++Templates also support functions for dynamic lookups:++| Function | Example | Description |+|----------|---------|-------------|+| `worktree_path_of_branch(branch)` | `{{ worktree_path_of_branch("main") }}` | Look up the path of a branch's worktree |++The `worktree_path_of_branch` function returns the filesystem path of a worktree given a branch name, or an empty string if no worktree exists for that branch. This is useful for referencing files in other worktrees:++```toml+[pre-start]+# Copy config from main worktree+setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path }}"+```++## JSON context++Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express:++```toml+[pre-start]+setup = "python3 scripts/pre-start-setup.py"+```++```python+import json, sys, subprocess+ctx = json.load(sys.stdin)+if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+ subprocess.run(['make', 'seed-db'])+```++## Copying untracked files++One specific command worth calling out: [`wt step copy-ignored`](https://worktrunk.dev/step/#wt-step-copy-ignored). Git worktrees share the repository but not untracked files, and this copies gitignored files between worktrees:++```toml+[post-start]+copy = "wt step copy-ignored"+```++# Running Hooks Manually++`wt hook <type>` runs hooks on demand — useful for testing during development, running in CI pipelines, or re-running after a failure.++```bash+$ wt hook pre-merge # Run all pre-merge hooks+$ wt hook pre-merge test # Run hooks named "test" from both sources+$ wt hook pre-merge test build # Run hooks named "test" and "build"+$ wt hook pre-merge user: # Run all user hooks+$ wt hook pre-merge project: # Run all project hooks+$ wt hook pre-merge user:test # Run only user's "test" hook+$ wt hook pre-merge --yes # Skip approval prompts (for CI)+$ wt hook pre-start --branch=feature/test # Override a template variable+$ wt hook pre-merge -- --extra args # Forward tokens into {{ args }}+```++The `user:` and `project:` prefixes filter by source. Use `user:` or `project:` alone to run all hooks from that source, or `user:name` / `project:name` to run a specific hook.++```+$ wt hook pre-merge+◎ Running pre-merge project:test+ cargo test+ Finished test [unoptimized + debuginfo] target(s) in 0.12s+ Running unittests src/lib.rs (target/debug/deps/worktrunk-abc123)++running 18 tests+test auth::tests::test_jwt_decode ... ok+test auth::tests::test_jwt_encode ... ok+test auth::tests::test_token_refresh ... ok+test auth::tests::test_token_validation ... ok++test result: ok. 18 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.08s+◎ Running pre-merge project:lint+ cargo clippy+ Checking worktrunk v0.1.0+ Finished dev [unoptimized + debuginfo] target(s) in 1.23s+```++```bash+$ wt hook post-start+◎ Running post-start: project @ ~/acme+```++## Passing values++`--KEY=VALUE` binds `KEY` whenever `{{ KEY }}` appears in any command of the hook — the same smart-routing rule `wt <alias>` uses. Built-in variables can be overridden: `--branch=foo` sets `{{ branch }}` inside hook templates (the worktree's actual branch doesn't move). Hyphens in keys become underscores: `--my-var=x` sets `{{ my_var }}`.++Any `--KEY=VALUE` whose key isn't referenced by a hook template forwards into `{{ args }}` as a literal `--KEY=VALUE` token. Tokens after `--` also forward into `{{ args }}` verbatim. `{{ args }}` renders as a space-joined, shell-escaped string; index with `{{ args[0] }}`, loop with `{% for a in args %}…{% endfor %}`, count with `{{ args | length }}`.++The long form `--var KEY=VALUE` is deprecated but still supported. It force-binds regardless of whether any hook template references `KEY` — useful when a template only references the key conditionally (e.g. `{% if override %}…{% endif %}`).++# Recipes++- [Eliminate cold starts](https://worktrunk.dev/tips-patterns/#eliminate-cold-starts): `wt step copy-ignored` in `post-start` shares build caches and dependencies; use a `[[post-start]]` pipeline when a later hook depends on the copy+- [Dev server per worktree](https://worktrunk.dev/tips-patterns/#dev-server-per-worktree): `wt step tether` in `post-start` runs the dev server and kills its whole process group when the worktree is removed, with optional subdomain routing+- [Database per worktree](https://worktrunk.dev/tips-patterns/#database-per-worktree): a `post-start` pipeline stores container name, port, and connection string as [per-branch vars](https://worktrunk.dev/config/#wt-config-state-vars) that later hooks reference+- [Progressive validation](https://worktrunk.dev/tips-patterns/#progressive-validation): quick lint/typecheck in `pre-commit`, expensive tests and builds in `pre-merge`+- [Target-specific hooks](https://worktrunk.dev/tips-patterns/#target-specific-hooks): branch on `{{ target }}` in `post-merge` for per-environment deploys++## Command reference++```+wt hook - Run configured hooks++Usage: wt hook [OPTIONS] <COMMAND>++Commands:+ show Show configured hooks+ pre-switch Run pre-switch hooks+ post-switch Run post-switch hooks+ pre-start Run pre-start hooks+ post-start Run post-start hooks+ pre-commit Run pre-commit hooks+ post-commit Run post-commit hooks+ pre-merge Run pre-merge hooks+ post-merge Run post-merge hooks+ pre-remove Run pre-remove hooks+ post-remove Run post-remove hooks++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/list.md b/plugins/worktrunk/skills/worktrunk/reference/list.mdnew file mode 100644index 000000000..8b98ea209--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/list.md@@ -0,0 +1,506 @@+# wt list++List worktrees and their status.++Shows uncommitted changes, divergence from the default branch and remote, and optional CI status and LLM summaries.++The table renders progressively: branch names, paths, and commit hashes appear immediately, then status, divergence, and other columns fill in as background git operations complete.++## Full mode++`--full` adds the two columns that reach off-machine: [CI status](#ci-status) (GitHub/GitLab pipeline pass/fail, over the network) and [LLM-generated summaries](#llm-summaries) of each branch's changes. The `main…±` line diffs are local git, so they show by default.++## Examples++List all worktrees:++```+$ wt list+ Branch Status HEAD± main↕ main…± Remote⇅ Commit Age Message+@ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 ⇡3 6814f02a 30m Add API tests+^ main ^⇅ ⇡1 ⇣1 41ee0834 4d Merge fix-auth:…++ fix-auth ↕| ↑2 ↓1 +25 -11 | b772e68b 5h Add secure token…++ fix-typos _| | 41ee0834 4d Merge fix-auth:…++○ Showing 4 worktrees, 1 with changes, 2 ahead, 1 column hidden+```++Include CI status and LLM summaries:++```+$ wt list --full+ Branch Status HEAD± main↕ main…± Summary Remote⇅ CI Commit+@ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST architecture with middleware ⇡3 #412 6814f02a+^ main ^⇅ ⇡1 ⇣1 # 41ee0834++ fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with constant-time token validation | #408 b772e68b++ fix-typos _| | #410 41ee0834++○ Showing 4 worktrees, 1 with changes, 2 ahead, 3 columns hidden+```++Include branches that don't have worktrees:++```+$ wt list --branches --full+ Branch Status HEAD± main↕ main…± Summary Remote⇅ CI Commit+@ feature-api + ↕⇡ +54 -5 ↑4 ↓1 +234 -24 Refactor API to REST architecture with middleware ⇡3 #412 6814f02a+^ main ^⇅ ⇡1 ⇣1 # 41ee0834++ fix-auth ↕| ↑2 ↓1 +25 -11 Harden auth with constant-time token validation | #408 b772e68b++ fix-typos _| | #410 41ee0834+/ exp /↕ ↑2 ↓1 +137 Explore GraphQL schema and resolvers 96379229+/ wip /↕ ↑1 ↓1 +33 Start API documentation b40716dc++○ Showing 4 worktrees, 2 branches, 1 with changes, 4 ahead, 3 columns hidden+```++Output as JSON for scripting:++```bash+$ wt list --format=json+```++## Columns++| Column | Shows |+|--------|-------|+| Branch | Branch name |+| Status | Compact symbols (see below) |+| HEAD± | Uncommitted changes: +added -deleted lines |+| main↕ | Commits ahead/behind default branch |+| main…± | Line diffs since the merge-base (three-dot) with the default branch |+| Summary | LLM-generated branch summary; requires `--full`, `summary = true`, and [`commit.generation`](https://worktrunk.dev/config/#commit) [experimental] |+| Remote⇅ | Commits ahead/behind tracking branch |+| CI | PR/MR number colored by pipeline status; `--full` only |+| Path | Worktree directory |+| URL | Dev server URL from project config; dimmed if port is not listening |+| *(custom)* | User-defined [custom columns](#custom-columns) from `[list.custom-columns]` user config [experimental] |+| Commit | Short hash (8 chars) |+| Age | Time since last commit |+| Message | Last commit message (truncated) |++The `main` header label is used regardless of the default branch's actual name.++`main↕` and `main…±` measure against the default branch's upstream tip when the local copy lags it — so in a fork whose local `main` trails `origin/main`, a branch reads as ahead of the real mainline, not of a stale local checkout. The `↑`/`↓`/`↕` Status symbols derive from these counts, so they track the upstream tip too.++### Gutter++The leftmost column marks each row by physical presence, from most present to least:++| Symbol | Meaning |+|--------|---------|+| `@` | Current worktree |+| `^` | Primary worktree (the repo's home worktree) |+| `+` | Other worktree |+| `/` | Local branch without a worktree (`--branches`) |+| `\|` | Remote branch, not present locally until fetched (`--remotes`) |++### CI status++The CI column shows the branch's open PR/MR — `#3035` on GitHub, Gitea, and Azure DevOps, `!3035` on GitLab — colored by pipeline status, or a bare `#` when no number is available (e.g. branch workflows without a PR/MR). One color folds two JSON fields: green/blue/red/yellow/gray are `ci.status`; magenta/cyan are `ci.review_state`. The `Value` column is the matching JSON string from `--format=json`:++| Indicator | Value | Meaning |+|-----------|-------|---------|+| `#` green | `"passed"` | All checks passed |+| `#` blue | `"running"` | Checks in progress |+| `#` red | `"failed"` | One or more checks failed |+| `#` yellow | `"conflicts"` | Merge conflicts with the target branch |+| `#` gray | `"no-ci"` | No PR/MR, or no checks configured |+| `⚠` yellow | `"error"` | CI status could not be fetched (rate limit, network, etc.) |+| `#` magenta | `"changes_requested"` | A reviewer requested changes |+| `#` cyan | `"pending"` | A review is required (e.g. branch protection) but not yet given |+| (blank) | `ci` absent | No upstream, or no PR/MR and no branch workflow |++The two remaining `ci.review_state` values have no indicator of their own: `"draft"` only dims the cell and `"approved"` leaves the color unchanged.++Color precedence resolves the fold: changes-requested (magenta) outranks running checks — waiting can't clear it — while an outstanding required review (cyan) only recolors an otherwise green or quiet branch. Cool colors mean waiting, warm colors mean act. An approved PR, or one with no review signal at all (no required reviewers and no reviews), keeps its plain `ci.status` color — `ci.review_state` is then `"approved"` or absent, respectively. GitLab MR data carries only `"pending"` and `"draft"` — no approved or changes-requested signal.++CI cells are clickable links to the PR or pipeline page, and appear dimmed for a draft PR/MR (`"draft"`) or when unpushed local changes make the status stale (`ci.stale`). PRs/MRs are checked first, then branch workflows/pipelines for branches with an upstream. Local-only branches show blank; remote-only branches — visible with `--remotes` — get CI status detection. Results are cached for 30-60 seconds; use `wt config state` to view or clear.++### LLM summaries [experimental]++Reuses the [`commit.generation`](https://worktrunk.dev/config/#commit) command — the same LLM that generates commit messages. Enable with `summary = true` in `[list]` config; requires `--full`. Results are cached until the branch's diff changes.++### Custom columns [experimental]++Each `[list.custom-columns]` entry in user config adds a column: the key is the header, the template renders each row's cell. Templates read two per-branch namespaces — `{{ vars.* }}`, stored with [`wt config state vars set`](https://worktrunk.dev/config/#wt-config-state-vars), and `{{ git.branch.* }}`, the branch's own git config under `branch.<name>.*` (a `jira` key you set yourself, or the git-native `description`) — useful for tracking what each of many (often agent-driven) branches is for:++```toml+[list.custom-columns.Ticket]+template = "{{ vars.ticket }}"+```++A column that renders empty for every row is dropped from the table. Templates, widths, and drop priority: [custom columns config](https://worktrunk.dev/config/#custom-columns).++## Status symbols++The Status column packs several subcolumns, left to right, each mapping to a field in `--format=json`. Working-tree flags are independent and co-occur — any combination shows at once. The other subcolumns are mutually exclusive: each shows a single symbol, the highest-priority state in top-to-bottom table order, and is blank when nothing applies.++### Working tree++Independent flags from `git status`; several can show at once (e.g. `+!?`). Each maps to a boolean in the `working_tree` object:++| Symbol | working_tree | Meaning |+|--------|--------------|---------|+| `+` | `staged` | Staged files |+| `!` | `modified` | Modified files (unstaged) |+| `?` | `untracked` | Untracked files |++`working_tree` also reports `renamed` and `deleted`, which have no dedicated symbol in the column.++### Worktree++An in-progress git operation, a worktree-location attribute, or a branch with no worktree. One symbol shows, highest priority first (`✘ > ⤴ > ⤵ > ⊟ > ⊞ > ⚑ > /`):++| Symbol | JSON | Meaning |+|--------|------|---------|+| `✘` | `operation_state` `"conflicts"` | Merge conflicts |+| `⤴` | `operation_state` `"rebase"` | Rebase in progress |+| `⤵` | `operation_state` `"merge"` | Merge in progress |+| `⊟` | `worktree.state` `"prunable"` | Prunable (worktree directory missing) |+| `⊞` | `worktree.state` `"locked"` | Locked worktree |+| `⚑` | `worktree.state` `"branch_worktree_mismatch"` | Branch name doesn't match the worktree path |+| `/` | `kind` `"branch"` | Branch without a worktree (no `worktree` object) |++### Default branch++The single highest-priority state describing the branch's relation to the default branch; blank when none applies (a normal up-to-date branch). Each symbol is one `main_state` value:++| Symbol | main_state | Meaning |+|--------|------------|---------|+| `^` | `"is_main"` | The main worktree (the repo's home worktree) |+| `∅` | `"orphan"` | No common ancestor with the default branch |+| `_` | `"empty"` | Same commit as the default branch, working tree clean — safe to remove; row dimmed |+| `⊂` | `"integrated"` | Content [integrated](https://worktrunk.dev/remove/#branch-cleanup) into the default branch or merge target via different history; the matching check is in `integration_reason`; row dimmed |+| `✗` | `"would_conflict"` | Merging into the default branch would conflict (simulated with `git merge-tree`) and the branch isn't already integrated; with `--full`, the check includes uncommitted changes |+| `–` | `"same_commit"` | Same commit as the default branch, but with uncommitted changes |+| `↕` | `"diverged"` | Both ahead of and behind the default branch |+| `↑` | `"ahead"` | Has commits the default branch doesn't |+| `↓` | `"behind"` | Missing commits the default branch has |++Rows are dimmed when [safe to delete](https://worktrunk.dev/remove/#branch-cleanup) — `_` (`"empty"`) or `⊂` (`"integrated"`).++### Remote++Relation to the tracking branch, derived from the `remote.ahead` / `remote.behind` counts; blank when there is no upstream:++| Symbol | remote | Meaning |+|--------|--------|---------|+| `\|` | `ahead` 0, `behind` 0 | In sync with remote |+| `⇡` | `ahead` > 0 | Ahead of remote |+| `⇣` | `behind` > 0 | Behind remote |+| `⇅` | `ahead` > 0, `behind` > 0 | Diverged from remote |++### Placeholder symbols++These appear across all columns while the table is loading:++| Symbol | Meaning |+|--------|---------|+| `·` | Data is loading, or collection timed out / branch too stale |++---++## JSON output++`--format=json` emits structured data in one of two schemas while the format+migrates: `[list] json-schema = 2` selects the envelope format below, `= 1`+the original bare-array format. Unset emits schema 1 with a warning+(`wt config update` adopts `= 2`); a future release flips the default to+schema 2 and later removes schema 1.++### Schema 2++One envelope object. Items carry independent facts; rendered strings+(including the collapsed Status value) live under `display`:++```json+{+ "schema": 2,+ "repo": {+ "default_branch": "main",+ "forge": {"url": "https://github.com/org/repo", "provider": "github",+ "host": "github.com", "owner": "org", "name": "repo", "remote": "origin"}+ },+ "collected": {"ci": false, "summary": false},+ "items": [+ {+ "branch": "feature",+ "head": {"sha": "05a4a45d…", "short_sha": "05a4a45", "subject": "Add login page",+ "committed_at": "2025-01-01T08:00:00Z"},+ "worktree": {"path": "/home/user/repo.feature", "main": false, "current": true,+ "previous": false, "detached": false, "branch_mismatch": false,+ "changes": {"staged": false, "modified": true, "untracked": false,+ "renamed": false, "deleted": false, "conflicted": false,+ "diff": {"added": 10, "deleted": 2}}},+ "default_branch": {"ahead": 3, "behind": 1, "diff": {"added": 50, "deleted": 20},+ "orphan": false, "integration": null, "merge_conflicts": false},+ "upstream": {"remote": "origin", "branch": "feature", "ahead": 0, "behind": 2},+ "display": {"state": "diverged", "symbols": "!↕", "statusline": "feature …"}+ }+ ]+}+```++How "no value" reads:++- **Absent** — nothing to report: not applicable (`worktree` on a branch-only+ row), not requested this run (the envelope's `collected` records what was),+ or determined-empty (no PR, no lock, not integrated).+- **`null`** — requested but not determined: a task timed out, the branch was+ too stale for the expensive checks, or a forge fetch failed. This is the+ JSON form of the table's `·` placeholder.++jq treats absent and `null` identically in path expressions, so filters need+no null checks; `has()` distinguishes the two when it matters.++Item fields:++| Field | Description |+|-------|-------------|+| `branch` | Branch name; null for a detached-HEAD worktree. Remote rows carry the bare name with the remote in `remote` |+| `remote` | Remote name, present only on remote-only branch rows |+| `head` | `{sha, short_sha, subject, committed_at}`; null for unborn branches. `committed_at` is RFC 3339 UTC |+| `worktree` | `{path, main, current, previous, detached, locked, prunable, branch_mismatch, operation, changes}`; absent on branch-only rows. `locked`/`prunable` are `{reason}` objects and can co-occur; `operation` is `"rebase"` or `"merge"`; `changes` holds the five working-tree flags plus `conflicted` and `diff {added, deleted}` |+| `default_branch` | Relation to the default branch: `{ahead, behind, diff, orphan, integration, merge_conflicts}`; absent on the default branch itself. `integration.reason` is one of `same_commit`, `ancestor`, `no_added_changes`, `trees_match`, `merge_adds_nothing`, `patch_id_match`; a dirty tree skips the checks, leaving `integration` null |+| `upstream` | Tracking branch: `{remote, branch, ahead, behind}`; absent when none is configured |+| `pr` | Open PR/MR: `{number, url, review, mergeable, repo}`; collected with `--full` or a listed `ci` column. `review` uses the schema 1 `ci.review_state` vocabulary; `mergeable` is false when the forge reports conflicts, null otherwise |+| `checks` | CI pipeline: `{status, source, stale}`; `status` is `passed`, `running`, or `failed` — null when a conflicts report masks it |+| `dev_server` | `{url, listening}` from the project's `list.url` template |+| `summary` | LLM branch summary (requires `[list] summary = true`) |+| `vars` | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) |+| `display` | Rendered strings: `state` (schema 1's `main_state` vocabulary), `symbols`, `statusline` (with ANSI colors), `columns` (custom-column cells keyed by header) |++Schema 1 names map directly: `commit` → `head`, `working_tree` →+`worktree.changes`, `main` + `main_state` → `default_branch` ++`display.state`, `remote` → `upstream`, `ci` → `pr` + `checks`, `url` ++`url_active` → `dev_server`, `statusline`/`symbols`/`columns` → `display.*`,+and the per-item `repo` moves to the envelope's `repo.forge`.++```bash+# Current worktree path (for scripts)+$ wt list --format=json | jq -r '.items[] | select(.worktree.current) | .worktree.path'++# Branches with uncommitted changes+$ wt list --format=json | jq '.items[] | select(.worktree.changes.modified)'++# Integrated branches (safe to remove)+$ wt list --format=json | jq '.items[] | select(.display.state == "integrated" or .display.state == "empty") | .branch'++# Worktrees ahead of upstream (needs pushing)+$ wt list --format=json | jq '.items[] | select(.upstream.ahead > 0) | .branch'+```++### Schema 1++The original bare-array format, and the default while unset:++```bash+# Current worktree path (for scripts)+$ wt list --format=json | jq -r '.[] | select(.is_current) | .path'++# Branches with uncommitted changes+$ wt list --format=json | jq '.[] | select(.working_tree.modified)'++# Worktrees with merge conflicts+$ wt list --format=json | jq '.[] | select(.operation_state == "conflicts")'++# Branches ahead of main (needs merging)+$ wt list --format=json | jq '.[] | select(.main.ahead > 0) | .branch'++# Integrated branches (safe to remove)+$ wt list --format=json | jq '.[] | select(.main_state == "integrated" or .main_state == "empty") | .branch'++# Branches without worktrees+$ wt list --format=json --branches | jq '.[] | select(.kind == "branch") | .branch'++# Worktrees ahead of remote (needs pushing)+$ wt list --format=json | jq '.[] | select(.remote.ahead > 0) | {branch, ahead: .remote.ahead}'++# Stale CI (local changes not reflected in CI)+$ wt list --format=json --full | jq '.[] | select(.ci.stale) | .branch'+```++**Fields:**++| Field | Type | Description |+|-------|------|-------------|+| `branch` | string/null | Branch name (null for detached HEAD) |+| `path` | string | Worktree path (absent for branches without worktrees) |+| `kind` | string | `"worktree"` or `"branch"` |+| `commit` | object | Commit info (see below) |+| `working_tree` | object | Working tree state (see below) |+| `main_state` | string | Relation to the default branch (see below) |+| `integration_reason` | string | Why branch is integrated (see below) |+| `operation_state` | string | `"conflicts"`, `"rebase"`, or `"merge"` (see [Worktree](#worktree)); absent when clean |+| `main` | object | Relationship to the default branch (see below); absent when is_main |+| `remote` | object | Tracking branch info (see below); absent when no tracking |+| `worktree` | object | Worktree metadata (see below) |+| `is_main` | boolean | Is the main worktree |+| `is_current` | boolean | Is the current worktree |+| `is_previous` | boolean | Previous worktree from wt switch |+| `ci` | object | CI status (see below); `--full` only, then absent when no PR/MR or branch workflow |+| `repo_url` | string | Repository web URL derived from the primary remote; absent when the remote URL cannot be parsed |+| `repo` | object | Structured repository metadata (see below); includes `remote` |+| `url` | string | Dev server URL from project config; absent when not configured |+| `url_active` | boolean | Whether the URL's port is listening; absent when not configured |+| `summary` | string | LLM-generated branch summary; `--full` only, then absent when not configured or no summary |+| `statusline` | string | Pre-formatted status with ANSI colors |+| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |+| `vars` | object | Per-branch variables from [`wt config state vars`](https://worktrunk.dev/config/#wt-config-state-vars) (absent when empty) |+| `columns` | object | Rendered [custom column](#custom-columns) values keyed by header; empty cells omitted (absent when none configured) |++### Commit object++| Field | Type | Description |+|-------|------|-------------|+| `sha` | string | Full commit SHA (40 chars) |+| `short_sha` | string | Short commit SHA, abbreviated per `core.abbrev` (auto-extends for ambiguous prefixes) |+| `message` | string | Commit message (first line) |+| `timestamp` | number | Unix timestamp |++### working_tree object++The five change flags map to the [Working tree](#working-tree) symbols (`renamed` and `deleted` have none of their own):++| Field | Type | Description |+|-------|------|-------------|+| `staged` | boolean | Has staged files |+| `modified` | boolean | Has modified files (unstaged) |+| `untracked` | boolean | Has untracked files |+| `renamed` | boolean | Has renamed files |+| `deleted` | boolean | Has deleted files |+| `diff` | object | Lines changed vs HEAD: `{added, deleted}` |++### main object++| Field | Type | Description |+|-------|------|-------------|+| `ahead` | number | Commits ahead of the default branch |+| `behind` | number | Commits behind the default branch |+| `diff` | object | Lines changed vs the default branch: `{added, deleted}` |++### remote object++`ahead` / `behind` drive the [Remote](#remote) divergence symbol:++| Field | Type | Description |+|-------|------|-------------|+| `name` | string | Remote name (e.g., `"origin"`) |+| `branch` | string | Remote branch name |+| `ahead` | number | Commits ahead of remote |+| `behind` | number | Commits behind remote |++### worktree object++Present only for worktree-kind items. `state` is the worktree-location attribute — see [Worktree](#worktree) for its symbols:++| Field | Type | Description |+|-------|------|-------------|+| `state` | string | `"branch_worktree_mismatch"`, `"prunable"`, or `"locked"` (absent when normal) |+| `reason` | string | Reason for locked/prunable state |+| `detached` | boolean | HEAD is detached |++### ci object++| Field | Type | Description |+|-------|------|-------------|+| `status` | string | CI status (see below) |+| `source` | string | `"pr"` (PR/MR) or `"branch"` (branch workflow) |+| `number` | integer | PR/MR number; absent for branch workflows |+| `stale` | boolean | Local HEAD differs from remote (unpushed changes) |+| `url` | string | URL to the PR/MR page |+| `repo_url` | string | Web URL of the repo the PR/MR targets (the upstream for fork PRs); absent when `url` is absent or unrecognized |+| `repo` | object | Structured metadata for the repository the PR/MR targets; never includes `remote` |+| `review_state` | string | Review state (see below); absent when the forge reports no review signal |++### repo object++Top-level `repo` describes the local checkout's repository as derived from the primary remote. `ci.repo` describes the repository targeted by the PR/MR URL in `ci.url` (for fork PRs, this is the upstream target). Existing `repo_url` and `ci.repo_url` fields remain available and carry the same URL as `repo.url` / `ci.repo.url`.++| Field | Type | Description |+|-------|------|-------------|+| `url` | string | Repository web URL |+| `provider` | string | `"github"`, `"gitlab"`, `"gitea"`, `"azure-devops"`, or `"unknown"` |+| `host` | string | Repository web host |+| `owner` | string | Owner, organization, or namespace path |+| `name` | string | Repository name |+| `project` | string | Azure DevOps project name; absent for other providers |+| `remote` | string | Local remote name used for top-level repo metadata; absent from `ci.repo` |++### main_state values++The single highest-priority state describing the branch's relation to the default branch; absent when none applies (a normal up-to-date branch). Each value is one Default-branch symbol — see [Default branch](#default-branch) for the symbol and the full meaning of each value (`"is_main"`, `"orphan"`, `"empty"`, `"integrated"`, `"would_conflict"`, `"same_commit"`, `"diverged"`, `"ahead"`, `"behind"`).++### integration_reason values++Set only when `main_state == "integrated"` (the `⊂` symbol), recording which check matched. Checks run cheapest-first and the first match wins. JSON-only — every reason renders as the same `⊂`:++| Value | Meaning |+|-------|---------|+| `"ancestor"` | Branch HEAD is an ancestor of the default branch, which has moved past it |+| `"no-added-changes"` | The three-dot diff (`main...branch`) is empty — no file changes beyond the merge-base |+| `"trees-match"` | Different history, but the branch's tree is identical to the default branch's |+| `"merge-adds-nothing"` | The branch has changes, but merging them leaves the default branch's tree unchanged (e.g. a squash merge where the target advanced on other files) |+| `"patch-id-match"` | The branch's squashed diff matches a single commit on the default branch (e.g. a GitHub/GitLab squash merge) |++### ci.status and ci.review_state values++The [CI status](#ci-status) section above is the single source for both fields: the table maps each colored value, and the notes below it cover `"draft"` and `"approved"`. `ci.status` is one of `"passed"`, `"running"`, `"failed"`, `"conflicts"`, `"no-ci"`, `"error"`; `ci.review_state` is one of `"changes_requested"`, `"pending"`, `"draft"`, `"approved"`, absent when the forge reports no review signal. The vocabulary matches Claude Code's statusline `pr.review_state` field.++Missing a field that would be generally useful? Open an issue at https://github.com/max-sixty/worktrunk.++## Command reference++```+wt list - List worktrees and their status++Usage: wt list [OPTIONS]+ wt list <COMMAND>++Commands:+ statusline Single-line status for shell prompts++Options:+ --format <FORMAT>+ Output format++ [default: table]+ [possible values: table, json]++ --branches+ Include branches without worktrees++ --remotes+ Include remote branches++ --full+ Show CI status and LLM summaries++ --progressive+ Show fast info immediately, update with slow info++ Displays local data (branches, paths, status) first, then updates with remote data (CI,+ upstream) as it arrives. Use --no-progressive to force buffered rendering. Auto-enabled+ for TTY.++ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/llm-commits.md b/plugins/worktrunk/skills/worktrunk/reference/llm-commits.mdnew file mode 100644index 000000000..1a5d6dda0--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/llm-commits.md@@ -0,0 +1,199 @@+# LLM Commit Messages++Worktrunk generates commit messages by building a templated prompt and piping it to an external command. This integrates with `wt merge`, `wt step commit`, and `wt step squash`.++## Setup++Any command that reads a prompt from stdin and outputs a commit message works. Add to `~/.config/worktrunk/config.toml`:++### Claude Code++```toml+[commit.generation]+command = "MAX_THINKING_TOKENS=0 claude -p --no-session-persistence --model=haiku --tools='' --safe-mode --setting-sources='user' --system-prompt=''"+```++`--no-session-persistence` prevents the commit conversation from polluting `claude --continue`. `--safe-mode` keeps the run hermetic — no hooks, plugins, MCP, skills, or CLAUDE.md — while leaving authentication working normally, so setups that authenticate via `apiKeyHelper` (not just OAuth or `ANTHROPIC_API_KEY`) still get a key. `--setting-sources='user'` scopes settings to your user config so a project `.claude/settings.json` can't override auth. The remaining flags disable tools, system prompt, and thinking for fast text-only output. `--safe-mode` requires Claude Code ≥ 2.1.169. See [Claude Code docs](https://code.claude.com/docs/en/setup) for installation.++### Codex++```toml+[commit.generation]+command = "codex exec -m gpt-5.6-luna -c model_reasoning_effort='low' -c system_prompt='' --sandbox=read-only --json - | jq -sr '[.[] | select(.item.type? == \"agent_message\")] | last.item.text'"+```++Uses the fast mini model with low reasoning effort and an empty system prompt for faster output. Requires `jq` for JSON parsing. See [Codex CLI docs](https://developers.openai.com/codex/cli/).++### Other tools++```toml+# opencode — use a fast model variant+command = "opencode run -m anthropic/claude-haiku-4.5 --variant fast"++# llm+command = "llm -m claude-haiku-4.5"++# aichat+command = "aichat -m claude:claude-haiku-4.5"+```++## Usage++These examples assume a feature worktree with changes to commit.++### wt merge++Squashes all changes (uncommitted + existing commits) into one commit with an LLM-generated message, then merges to the default branch:++```bash+$ wt merge+<span class=c>◎</span> <span class=c>Squashing 3 commits into a single commit <span style='color:var(--bright-black,#555)'>(5 files, <span class=g>+16</span></span></span><span style='color:var(--bright-black,#555)'>)</span>...+<span class=c>◎</span> <span class=c>Generating squash commit message...</span>+<span style='background:var(--bright-white,#fff)'> </span> <b>feat(auth): Implement JWT authentication system</b>+<span style='background:var(--bright-white,#fff)'> </span>+<span style='background:var(--bright-white,#fff)'> </span> Add comprehensive JWT token handling including validation, refresh+<span style='background:var(--bright-white,#fff)'> </span> logic, and authentication tests.+<span class=g>✓</span> <span class=g>Squashed @ a1b2c3d</span>+<span class=c>◎</span> <span class=c>Merging 1 commit to <b>main</b> @ <span class=d>a1b2c3d</span> (no rebase needed)</span>+<span style='background:var(--bright-white,#fff)'> </span> * <span style='color:var(--yellow,#a60)'>a1b2c3d</span> feat(auth): Implement JWT authentication system+<span style='background:var(--bright-white,#fff)'> </span> auth.rs | 2 <span class=g>++</span>+<span style='background:var(--bright-white,#fff)'> </span> auth_test.rs | 2 <span class=g>++</span>+<span style='background:var(--bright-white,#fff)'> </span> integration_test.rs | 6 <span class=g>++++++</span>+<span style='background:var(--bright-white,#fff)'> </span> jwt.rs | 3 <span class=g>+++</span>+<span style='background:var(--bright-white,#fff)'> </span> jwt_test.rs | 3 <span class=g>+++</span>+<span style='background:var(--bright-white,#fff)'> </span> 5 files changed, 16 insertions(+)+<span class=g>✓</span> <span class=g>Merged to <b>main</b> <span style='color:var(--bright-black,#555)'>(1 commit, 5 files, <span class=g>+16</span></span></span><span style='color:var(--bright-black,#555)'>)</span>+<span class=c>◎</span> <span class=c>Removing <b>feature</b> worktree & branch in background (same commit as <b>main</b>,</span> <span class=d>_</span><span class=c>)</span>+<span class=d>○</span> Switched to worktree for <b>main</b> @ <b>~/repo</b>+```++### wt step commit++Stages and commits with LLM-generated message:++```bash+$ wt step commit+<span class=c>◎</span> <span class=c>Generating commit message and committing changes... <span style='color:var(--bright-black,#555)'>(2 files, <span class=g>+26</span></span></span><span style='color:var(--bright-black,#555)'>)</span>+<span style='background:var(--bright-white,#fff)'> </span> <b>feat(validation): add input validation utilities</b>+<span class=g>✓</span> <span class=g>Committed changes @ <span class=d>a1b2c3d</span></span>+```++### wt step squash++Squashes branch commits into one with LLM-generated message:++```bash+$ wt step squash+<span class=c>◎</span> <span class=c>Squashing 3 commits into a single commit <span style='color:var(--bright-black,#555)'>(5 files, <span class=g>+16</span></span></span><span style='color:var(--bright-black,#555)'>)</span>...+<span class=c>◎</span> <span class=c>Generating squash commit message...</span>+<span style='background:var(--bright-white,#fff)'> </span> <b>feat(auth): Implement JWT authentication system</b>+<span style='background:var(--bright-white,#fff)'> </span>+<span style='background:var(--bright-white,#fff)'> </span> Add comprehensive JWT token handling including validation, refresh+<span style='background:var(--bright-white,#fff)'> </span> logic, and authentication tests.+<span class=g>✓</span> <span class=g>Squashed @ a1b2c3d</span>+```++See [`wt merge`](https://worktrunk.dev/merge/) and [`wt step`](https://worktrunk.dev/step/) for full documentation.++## Branch summaries++[experimental]++With `summary = true` and a `[commit.generation] command` configured, Worktrunk generates LLM branch summaries — one-line descriptions of each branch's changes since the default branch.++Summaries appear in:++- **`wt switch`** [interactive picker](https://worktrunk.dev/switch/#interactive-picker) — preview tab 5+- **`wt list --full`** — the Summary column (see [`wt list`](https://worktrunk.dev/list/#llm-summaries))++Enable in user config:++```toml+[list]+summary = true+```++Summaries are cached and regenerated only when the diff changes.++## Prompt templates++Worktrunk uses [minijinja](https://docs.rs/minijinja/) templates (Jinja2-like syntax) to build prompts.++### Custom templates++Override the defaults with inline templates:++```toml+[commit.generation]+command = "llm -m claude-haiku-4.5"++template = """+Write a commit message for this diff. One line, under 50 chars.++Branch: {{ branch }}+Diff:+{{ git_diff }}+"""++squash-template = """+Combine these {{ commit_details | length }} commits into one message:+{% for c in commit_details %}+- {{ c.subject }}+{% endfor %}++Diff:+{{ git_diff }}+"""+```++### Template variables++| Variable | Description |+|----------|-------------|+| `{{ git_diff }}` | The diff (staged changes or combined diff for squash) |+| `{{ git_diff_stat }}` | Diff statistics (files changed, insertions, deletions) |+| `{{ branch }}` | Current branch name |+| `{{ repo }}` | Repository name |+| `{{ recent_commits }}` | Recent commit subjects (for style reference) |+| `{{ commit_details }}` | Commits being squashed (squash template only); each renders as its subject and exposes `.subject` / `.body` |+| `{{ target_branch }}` | Merge target branch (squash template only) |+| `{{ user_guidance }}` | Rendered user `template-append` fragment (see below) |+| `{{ project_guidance }}` | Rendered project `template-append` fragment (see below) |++### Template syntax++Templates use [minijinja](https://docs.rs/minijinja/latest/minijinja/syntax/index.html), which supports:++- **Variables**: `{{ branch }}`, `{{ repo | upper }}`+- **Filters**: `{{ commit_details | length }}`, `{{ repo | upper }}`+- **Conditionals**: `{% if recent_commits %}...{% endif %}`+- **Loops**: `{% for c in commit_details %}{{ c.subject }}{% endfor %}`+- **Loop variables**: `{{ loop.index }}`, `{{ loop.length }}`+- **Whitespace control**: `{%- ... -%}` strips surrounding whitespace++See `wt config create --help` for the full default templates.++## Appending to the prompt++[experimental]++`template-append` adds to the commit and squash prompts instead of replacing them. It lives in both user config (personal preferences) and project config (`.config/wt.toml`, shared so every teammate's LLM sees the same style guide). Each fragment is itself a [minijinja](https://docs.rs/minijinja/) template — Worktrunk renders it with the same variables as the main template (`{{ branch }}`, `{{ git_diff }}`, …), then appends the result after `<style>`. The user fragment renders into a `<user-guidance>` block and the project fragment into a `<project-guidance>` block, so the LLM can tell personal preference from shared convention:++```toml+# .config/wt.toml+[commit.generation]+template-append = """+- Use conventional commits (feat:, fix:, docs:, …)+- Reference the related issue ID in the body+"""+```++When both the user and project set `template-append`, the `<user-guidance>` block comes first, then `<project-guidance>`.++The user fragment needs no approval — it's the developer's own config. For the project fragment, the first time the rendered text is sent to the LLM, Worktrunk shows the raw fragment in an approval prompt — the same one-shot gate as project-defined hooks. Subsequent commits don't re-prompt unless the fragment changes. Declining is non-fatal: the LLM runs with just the user fragment (if any).++Custom user templates that don't reference `{{ user_guidance }}` / `{{ project_guidance }}` opt out of the appended blocks — the rendered values are injected only where the template places them.++## Fallback behavior++When no LLM is configured, worktrunk generates deterministic messages based on changed filenames (e.g., "Changes to auth.rs & config.rs").diff --git a/plugins/worktrunk/skills/worktrunk/reference/merge.md b/plugins/worktrunk/skills/worktrunk/reference/merge.mdnew file mode 100644index 000000000..e114fb1e9--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/merge.md@@ -0,0 +1,156 @@+# wt merge++Merge current branch into the target branch. Squash & rebase, fast-forward the target branch, remove the worktree.++Unlike `git merge`, this merges the current branch into the target branch — not the target into current. Similar to clicking "Merge pull request" on GitHub, but locally. The target defaults to the default branch.++## Examples++Merge to the default branch:++```+$ wt merge+◎ Running pre-merge project:test+ cargo nextest run+ Finished `test` profile [unoptimized + debuginfo] target(s) in 0.02s+ Summary [ 0.002s] 2 tests run: 2 passed, 0 skipped+◎ Merging 1 commit to main @ a1b2c3d (no commit/squash/rebase needed)+ * a1b2c3d feat: add hook registration+ hook.rs | 31 ++++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+)+✓ Merged to main (1 commit, 1 file, +31)+◎ Removing hooks worktree & branch in background (same commit as main, _)+○ Switched to worktree for main @ ~/repo+```++Merge to a different branch:++```bash+$ wt merge develop+```++Keep the worktree after merging:++```bash+$ wt merge --no-remove+```++Preserve commit history (no squash):++```bash+$ wt merge --no-squash+```++Create a merge commit — semi-linear history:++```bash+$ wt merge --no-ff+```++Skip committing/squashing (rebase still runs unless --no-rebase):++```bash+$ wt merge --no-commit+```++## Pipeline++`wt merge` runs these steps:++1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.+2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.+7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.+8. **Post-remove + post-merge hooks** — Run in background after cleanup.++Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.++## Local CI++For personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.++Historically, ensuring tests ran before merging was difficult to enforce locally. Remote CI was valuable for the process as much as the checks: it guaranteed validation happened. `wt merge` brings that guarantee local.++The full workflow: start an agent (one of many) on a task, work elsewhere, return when it's ready. Review the diff, run `wt merge`, move on. Pre-merge hooks validate before merging — if they pass, the branch goes to the default branch and the worktree cleans up.++```toml+[[pre-merge]]+test = "cargo test"+lint = "cargo clippy"+```++## Command reference++```+wt merge - Merge current branch into the target branch++Squash & rebase, fast-forward the target branch, remove the worktree.++Usage: wt merge [OPTIONS] [TARGET]++Arguments:+ [TARGET]+ Target branch++ Defaults to default branch.++Options:+ --no-squash+ Skip commit squashing++ --no-commit+ Skip commit and squash++ --no-rebase+ Skip rebase (fail if not already rebased)++ --no-remove+ Keep worktree after merge++ --no-ff+ Create a merge commit (no fast-forward)++ --stage <STAGE>+ What to stage before committing [default: all]++ Possible values:+ - all: Stage everything: untracked files + unstaged tracked changes+ - tracked: Stage tracked changes only (like git add -u)+ - none: Stage nothing, commit only what's already in the index++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --no-hooks+ Skip hooks++ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after merge completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/remove.md b/plugins/worktrunk/skills/worktrunk/reference/remove.mdnew file mode 100644index 000000000..c5c9e4881--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/remove.md@@ -0,0 +1,175 @@+# wt remove++Remove worktree; delete branch if merged. Defaults to the current worktree.++## Examples++Remove current worktree:++```+$ wt remove+◎ Running pre-remove project:cleanup+ flyctl scale count 0+Scaling app to 0 machines+◎ Removing api worktree & branch in background (same commit as main, _)+○ Switched to worktree for main @ ~/repo+```++Remove specific worktrees / branches:++```bash+$ wt remove feature-branch+$ wt remove old-feature another-branch+```++Keep the branch:++```bash+$ wt remove --no-delete-branch feature-branch+```++Force-delete an unmerged branch:++```bash+$ wt remove -D experimental+```++## Branch cleanup++By default, branches are deleted when they would add no changes to the default branch if merged. This works with both unchanged git histories, and squash-merge or rebase workflows where commit history differs but file changes match.++Worktrunk checks six conditions (in order of cost):++1. **Same commit** — Branch HEAD equals the default branch. Shows `_` in `wt list`.+2. **Ancestor** — Branch is in target's history (fast-forward or rebase case). Shows `⊂`.+3. **No added changes** — Three-dot diff (`target...branch`) is empty. Shows `⊂`.+4. **Trees match** — Branch tree SHA equals target tree SHA. Shows `⊂`.+5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced with changes to different files. Shows `⊂`.+6. **Patch-id match** — Branch's entire diff matches a single squash-merge commit on target. Fallback for when the simulated merge conflicts because target later modified the same files the branch touched. Shows `⊂`.++The default-branch walk is capped so a single check stays fast; a squash merge with hundreds of commits landed since the merge point falls outside the cap and needs `-D` to remove.++The 'same commit' check uses the local default branch; for other checks, 'target' means the default branch, or its upstream (e.g., `origin/main`) when strictly ahead.++Branches matching these conditions and with empty working trees are dimmed in `wt list` as safe to delete.++## Force flags++Worktrunk has two force flags for different situations:++| Flag | Scope | When to use |+|------|-------|-------------|+| `--force` (`-f`) | Worktree | Worktree has uncommitted changes |+| `--force-delete` (`-D`) | Branch | Branch has unmerged commits |++```bash+$ wt remove feature --force # Remove dirty worktree+$ wt remove feature -D # Delete unmerged branch+$ wt remove feature --force -D # Both+```++Use `--no-delete-branch` to keep the branch regardless of merge status.++## Background removal++Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}/internal/remove.log`. Use `--foreground` to run in the foreground.++After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).++## Reaping processes [experimental]++`--reap` terminates processes left running in the worktree before it is removed — a `post-start` dev server, a file watcher, a language server — freeing the ports and file handles they hold. Processes are discovered by working directory: any process whose current directory is at or under the worktree path (`SIGTERM`, then `SIGKILL` for survivors).++```bash+$ wt remove --reap feature+◎ Reaping 2 processes under feature worktree+ ┃ 51234 node+ ┃ 51240 esbuild+✓ Reaped 2 processes+◎ Removing feature worktree & branch in background (same commit as main, _)+```++To avoid killing work the user did not mean to kill, two guards keep `--reap` conservative:++- **Interactive processes are spared.** A process holding a controlling terminal — an interactive shell, or a terminal editor such as `vim` with unsaved buffers — is never reaped. Only detached processes remain candidates.+- **Discovery is by working directory only.** A process that started in the worktree and later changed directory, or a daemon that reparented to `init`, no longer reports a directory under the worktree and is not found. To reliably reap those, launch them with [`wt step tether`](https://worktrunk.dev/step/#wt-step-tether), which kills the whole process group when the worktree is removed.++Reaping runs before the worktree directory is touched, so it is independent of foreground/background removal and the `--force` flag. Unix only; on Windows `--reap` is rejected.++## Hooks++`pre-remove` hooks run before the worktree is deleted (with access to worktree files). `post-remove` hooks run after removal. See [`wt hook`](https://worktrunk.dev/hook/) for configuration.++## Detached HEAD worktrees++Detached worktrees have no branch name. Pass the worktree path instead: `wt remove /path/to/worktree`.++## Command reference++```+wt remove - Remove worktree; delete branch if merged++Defaults to the current worktree.++Usage: wt remove [OPTIONS] [BRANCHES]...++Arguments:+ [BRANCHES]...+ Branch name or worktree path [default: current]++Options:+ --no-delete-branch+ Keep branch after removal++ -D, --force-delete+ Delete unmerged branches++ --foreground+ Run removal in foreground (block until complete)++ --reap+ Kill processes started in the worktree [experimental]++ Before removal, terminate processes whose working directory is under the worktree — dev+ servers, watchers, language servers. Processes holding a controlling terminal (interactive+ shells, terminal editors) are left alone. Unix only.++ -f, --force+ Force worktree removal++ Remove a dirty worktree, including staged, modified, and untracked files. Without this+ flag, removal fails if the worktree has any uncommitted changes.++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --no-hooks+ Skip hooks++ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after removal completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.mdnew file mode 100644index 000000000..570b83da4--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md@@ -0,0 +1,261 @@+# Shell Integration Reference++How Worktrunk's shell integration works and how to debug issues.++## Why Shell Integration Exists++Subprocesses cannot change the parent shell's current directory. When+`wt switch feature` runs, the `wt` binary runs as a child process and cannot+`cd` the terminal.++Worktrunk solves this with **split directive file passing**:++1. Shell wrapper creates two temp files via `mktemp` (one for cd, one for exec)+2. Shell sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`+3. `wt` binary writes a raw path to the CD file (no shell escaping needed)+4. `wt` writes shell commands to the EXEC file (only for `--execute`)+5. Shell reads the CD file with `cd -- "$(< file)"` — no shell parsing+6. Shell sources the EXEC file if non-empty+7. Shell removes both temp files++The split design eliminates shell injection from cd directives — the CD file+holds a raw path that is never parsed as shell.++## Installation++```bash+# Auto-install for all shells (bash, zsh, fish, nushell (experimental), PowerShell)+wt config shell install++# Or manual installation - add to the shell config:+# bash (~/.bashrc):+eval "$(wt config shell init bash)"++# zsh (~/.zshrc):+eval "$(wt config shell init zsh)"++# fish (~/.config/fish/config.fish):+wt config shell init fish | source++# nushell (experimental) — save to vendor autoload directory:+wt config shell init nu | save -f ($nu.vendor-autoload-dirs | last | path join wt.nu)++# PowerShell ($PROFILE):+Invoke-Expression (& wt config shell init powershell | Out-String)+```++## Checking Status++```bash+# Show shell integration status+wt config show+```++The RUNTIME section shows whether shell integration is active for the current+session.++## Warning Messages++When shell integration isn't working, `wt switch` shows warnings explaining why.++### "shell integration not installed"++**Meaning**: The shell config file doesn't have the `eval "$(wt config shell init ...)"` line.++**Fix**: Run `wt config shell install` or add the line manually.++### "shell requires restart"++**Meaning**: Shell integration is configured, but the current shell session was+started before installation. The shell function isn't loaded yet.++**Fix**: Start a new terminal or run `source ~/.bashrc` (or equivalent).++### "ran ./path/to/wt; shell integration wraps wt"++**Meaning**: The binary was invoked with an explicit path (like `./target/debug/wt`+or `/usr/local/bin/wt`) instead of just `wt`. The shell wrapper only intercepts+the bare command `wt`.++**Fix**: Use `wt` without a path. For testing dev builds, set `WORKTRUNK_BIN`:+```bash+export WORKTRUNK_BIN=./target/debug/wt+wt switch feature # Now uses the dev build with shell integration+```++### "ran git wt; running through git prevents cd"++**Meaning**: `git wt` (git alias) was used instead of `wt`. Git runs worktrunk as+a subprocess, bypassing the shell wrapper.++**Fix**: Use `wt` directly instead of `git wt` when directory switching is needed.++### "Alias bypasses shell integration"++**Meaning**: An alias like `alias gwt="/usr/bin/wt"` or `alias gwt="wt.exe"`+points directly to the binary instead of the shell function.++When shell integration is installed, it creates a shell function named `wt` (or+`git-wt`). If the alias points to the binary path, it bypasses this function+and shell integration won't work.++**Examples that bypass** (won't auto-cd):+```bash+alias gwt="/usr/bin/wt"+alias gwt="wt.exe"+alias wt="/path/to/wt"+```++**Fix**: Change the alias to point to the function name instead of the binary:+```bash+alias gwt="wt" # Good - uses the shell function+alias gwt="git-wt" # Good - uses the shell function+```++`wt config show` detects these problematic aliases and shows a warning with the+suggested fix.++## How the Shell Wrapper Works++The shell wrapper (installed by `wt config shell install`) defines a shell+function that:++1. Creates two temp files (cd and exec)+2. Sets `WORKTRUNK_DIRECTIVE_CD_FILE` and `WORKTRUNK_DIRECTIVE_EXEC_FILE`+3. Runs the real `wt` binary+4. Reads the CD file with `cd -- "$(< file)"` (raw path, no shell parsing)+5. Sources the EXEC file if non-empty (for `--execute` payloads)+6. Cleans up both temp files++Simplified example (actual wrapper handles completions and edge cases):+```bash+wt() {+ local cd_file exec_file exit_code=0+ cd_file="$(mktemp)"+ exec_file="$(mktemp)"++ WORKTRUNK_DIRECTIVE_CD_FILE="$cd_file" WORKTRUNK_DIRECTIVE_EXEC_FILE="$exec_file" \+ command wt "$@" || exit_code=$?++ if [[ -s "$cd_file" ]]; then+ cd -- "$(<"$cd_file")"+ fi+ if [[ -s "$exec_file" ]]; then+ source "$exec_file"+ fi++ rm -f "$cd_file" "$exec_file"+ return "$exit_code"+}+```++## Debugging Checklist++### 1. Check if wrapper is installed++```bash+# Should show shell function, not binary path+type wt++# Expected output (bash/zsh):+# wt is a function+# wt () { ... }++# If it shows a path like /usr/local/bin/wt, wrapper isn't loaded+```++### 1b. Check if wrapper is installed (PowerShell)++```powershell+# PowerShell: should show Function, not just Application+Get-Command wt -All++# Expected output when wrapper is loaded:+# CommandType Name Source+# ----------- ---- ------+# Function wt+# Application wt C:\Users\...\wt.exe++# If only Application appears, wrapper isn't loaded (restart shell)+# If Function appears but integration is still "not active", check the body:+(Get-Command wt -CommandType Function).ScriptBlock | Select-String WORKTRUNK+```++### 2. Check shell config file++```bash+# bash+grep -n "wt config shell init" ~/.bashrc++# zsh+grep -n "wt config shell init" ~/.zshrc++# fish+grep -n "wt config shell init" ~/.config/fish/config.fish+```++Should show the `eval` line with line number.++### 3. Check if directive files are set++```bash+# After running any wt command, these should be unset (temp files deleted)+echo $WORKTRUNK_DIRECTIVE_CD_FILE+echo $WORKTRUNK_DIRECTIVE_EXEC_FILE++# During wt execution, these would be set to temp file paths+```++### 4. Test directive files manually++```bash+# Create temp files and test+export WORKTRUNK_DIRECTIVE_CD_FILE=$(mktemp)+export WORKTRUNK_DIRECTIVE_EXEC_FILE=$(mktemp)+command wt switch feature+cat $WORKTRUNK_DIRECTIVE_CD_FILE # Should contain: /path/to/worktree (raw path)+cd -- "$(<$WORKTRUNK_DIRECTIVE_CD_FILE)" # Should cd you there+rm -f $WORKTRUNK_DIRECTIVE_CD_FILE $WORKTRUNK_DIRECTIVE_EXEC_FILE+```++## Common Issues++### Shell integration works in terminal but not in IDE terminal++IDE terminals may use different shell configs. Check:+- VS Code: Settings → Terminal → Integrated → Shell Args+- The IDE terminal might source a different profile++### Completions not working++Completions are installed alongside shell integration. If they're missing:++```bash+# Reinstall (forces regeneration)+wt config shell install++# For zsh, you may need compinit before the wt line:+autoload -Uz compinit && compinit+eval "$(wt config shell init zsh)"+```++### Windows Git Bash issues++Git Bash uses MSYS2, which automatically converts POSIX paths in environment+variables. The directive file path is handled correctly without manual conversion.++If you see path issues, ensure you're using a recent Git for Windows version.++## Environment Variables++| Variable | Purpose |+|----------|---------|+| `WORKTRUNK_DIRECTIVE_CD_FILE` | Set by shell wrapper; wt writes a raw path, wrapper `cd`s to it |+| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Set by shell wrapper; wt writes shell commands, wrapper sources the file |+| `WORKTRUNK_BIN` | Override binary path (for testing dev builds) |+| `WORKTRUNK_SHELL` | Set by the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |++## See Also++- `wt config shell --help` — Shell integration commands+- `wt config show` — View current configuration and statusdiff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdnew file mode 100644index 000000000..98772bfb3--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md@@ -0,0 +1,1107 @@+# wt step++Run individual operations. The building blocks of wt merge — commit, squash, rebase, push — plus standalone utilities.++## Examples++Commit with LLM-generated message:++```+$ wt step commit+◎ Generating commit message and committing changes... (2 files, +26)+ feat(validation): add input validation utilities+✓ Committed changes @ a1b2c3d+```++Manual merge workflow with review between steps:++```bash+$ wt step commit+$ wt step squash+$ wt step rebase+$ wt step push+```++## Operations++- [`commit`](#wt-step-commit) — Stage and commit with [LLM-generated message](https://worktrunk.dev/llm-commits/)+- [`squash`](#wt-step-squash) — Squash all branch commits into one with [LLM-generated message](https://worktrunk.dev/llm-commits/)+- `rebase` — Rebase onto target branch+- `push` — Fast-forward target to current branch+- [`diff`](#wt-step-diff) — Show all changes since branching (committed, staged, unstaged, untracked)+- [`copy-ignored`](#wt-step-copy-ignored) — Copy gitignored files between worktrees+- [`eval`](#wt-step-eval) — [experimental] Evaluate a template expression+- [`for-each`](#wt-step-for-each) — [experimental] Run a command in every worktree+- [`promote`](#wt-step-promote) — [experimental] Swap a branch into the main worktree+- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch+- [`relocate`](#wt-step-relocate) — [experimental] Move worktrees to expected paths+- [`tether`](#wt-step-tether) — [experimental] Run a command; kill its whole process tree when its worktree is removed+- [`<alias>`](https://worktrunk.dev/extending/#aliases) — Run a configured command alias++## Command reference++```+wt step - Run individual operations++The building blocks of wt merge — commit, squash, rebase, push — plus standalone utilities.++Usage: wt step [OPTIONS] <COMMAND>++Commands:+ commit Stage and commit with LLM-generated message+ squash Squash commits since branching+ rebase Rebase onto target+ push Fast-forward target to current branch+ diff Show all changes since branching+ copy-ignored Copy gitignored files to another worktree+ eval [experimental] Evaluate a template expression+ for-each [experimental] Run command in each worktree+ promote [experimental] Swap a branch into the main worktree+ prune [experimental] Remove worktrees merged into the default branch+ relocate [experimental] Move worktrees to expected paths+ tether [experimental] Run a command; kill its whole process tree when its worktree is+ removed++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++# Subcommands++## wt step commit++Stage and commit with LLM-generated message.++See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for configuration and prompt customization.++### Options++#### Staging++Controls what to stage before committing:++| Value | Behavior |+|-------|----------|+| `all` | Stage all changes including untracked files (default) |+| `tracked` | Stage only modified tracked files |+| `none` | Don't stage anything, commit only what's already staged |++```bash+$ wt step commit --stage=tracked+```++Configure the default in user config:++```toml+[commit]+stage = "tracked"+```++#### Dry run++Render the prompt, print the LLM command, generate the message, and exit without staging, running hooks, or committing:++```bash+$ wt step commit --dry-run+```++Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the commit is skipped.++### Command reference++```+wt step commit - Stage and commit with LLM-generated message++Usage: wt step commit [OPTIONS]++Options:+ -b, --branch <BRANCH>+ Branch to operate on (defaults to current worktree)++ --stage <STAGE>+ What to stage before committing [default: all]++ Possible values:+ - all: Stage everything: untracked files + unstaged tracked changes+ - tracked: Stage tracked changes only (like git add -u)+ - none: Stage nothing, commit only what's already in the index++ --dry-run+ Preview prompt, command, and generated message without committing++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --no-hooks+ Skip hooks++ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after the commit completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step squash++Squash commits since branching. Stages changes and generates message with LLM.++See [LLM-generated commit messages](https://worktrunk.dev/llm-commits/) for configuration and prompt customization.++### Options++#### Staging++Controls what to stage before squashing:++| Value | Behavior |+|-------|----------|+| `all` | Stage all changes including untracked files (default) |+| `tracked` | Stage only modified tracked files |+| `none` | Don't stage anything, squash only committed changes |++```bash+$ wt step squash --stage=none+```++Configure the default in user config:++```toml+[commit]+stage = "tracked"+```++#### Dry run++Render the prompt, print the LLM command, generate the squash message, and exit without resetting, running hooks, or committing:++```bash+$ wt step squash --dry-run+```++Three sections are printed: the rendered prompt, the shell command that would invoke the LLM, and the message returned. The LLM call still happens — only the squash and commit are skipped.++### Command reference++```+wt step squash - Squash commits since branching++Stages changes and generates message with LLM.++Usage: wt step squash [OPTIONS] [TARGET]++Arguments:+ [TARGET]+ Target branch++ Defaults to default branch.++Options:+ --stage <STAGE>+ What to stage before committing [default: all]++ Possible values:+ - all: Stage everything: untracked files + unstaged tracked changes+ - tracked: Stage tracked changes only (like git add -u)+ - none: Stage nothing, commit only what's already in the index++ --dry-run+ Preview prompt, command, and generated message without squashing++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --no-hooks+ Skip hooks++ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after the squash completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step diff++Show all changes since branching. Includes committed, staged, unstaged, and untracked files.++This is what `wt merge` would include — a single diff against the merge base.++### Operating on another worktree++`--branch` diffs another worktree's branch without leaving the current one:++```bash+$ wt step diff --branch feature+```++The branch must have a checked-out worktree.++### Extra git diff arguments++Arguments after `--` are forwarded to `git diff`:++```bash+$ wt step diff -- --stat+$ wt step diff -- --name-only+$ wt step diff -- -- '*.rs'+```++The diff is pipeable to tools like `delta`:++```bash+$ wt step diff | delta+```++### How it works++Equivalent to:++```bash+$ cp "$(git rev-parse --git-dir)/index" /tmp/idx+$ GIT_INDEX_FILE=/tmp/idx git add --intent-to-add .+$ GIT_INDEX_FILE=/tmp/idx git diff $(git merge-base HEAD $(wt config state default-branch))+```++`git diff` ignores untracked files. `git add --intent-to-add .` registers them in the index without staging their content, making them visible to `git diff`. This runs against a copy of the real index so the original is never modified.++### Command reference++```+wt step diff - Show all changes since branching++Includes committed, staged, unstaged, and untracked files.++Usage: wt step diff [OPTIONS] [TARGET] [-- <EXTRA_ARGS>...]++Arguments:+ [TARGET]+ Target branch++ Defaults to default branch.++ [EXTRA_ARGS]...+ Extra arguments forwarded to git diff++Options:+ -b, --branch <BRANCH>+ Branch to operate on (defaults to current worktree)++ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step copy-ignored++Copy gitignored files to another worktree. Eliminates cold starts by copying build caches and dependencies.++### Setup++Add to the project config:++```toml+# .config/wt.toml+[post-start]+copy = "wt step copy-ignored"+```++### What gets copied++All gitignored files are copied by default, except for built-in excluded directories: VCS metadata (`.bzr/`, `.hg/`, `.jj/`, `.pijul/`, `.sl/`, `.svn/`) and tool-state (`.conductor/`, `.entire/`, `.worktrees/`). Tracked files are never touched.++To limit what gets copied further, create `.worktreeinclude` with gitignore-style patterns. Files must be **both** gitignored **and** in `.worktreeinclude`:++```text+# .worktreeinclude+.env+node_modules/+target/+```++After `.worktreeinclude` selects entries, you can add more gitignore-style excludes in user config, per-project user overrides, or project config:++```toml+[step.copy-ignored]+exclude = [".cache/", ".turbo/"]+```++To copy nothing unless `.worktreeinclude` exists — matching Claude Code desktop, where the file is required — pass `--require-include`:++```bash+wt step copy-ignored --require-include+```++Without `.worktreeinclude`, the command is a no-op (it reports that nothing was copied and why). With the file present, only matching files copy as above. To apply this across every repository, put the flag in a user-config hook: `post-start = "wt step copy-ignored --require-include"`.++### Common patterns++| Type | Patterns |+|------|----------|+| Dependencies | `node_modules/`, `.venv/`, `target/`, `vendor/`, `Pods/` |+| Build caches | `.cache/`, `.next/`, `.parcel-cache/`, `.turbo/` |+| Generated assets | Images, ML models, binaries too large for git |+| Environment files | `.env` (if not generated per-worktree) |++### Features++- Uses copy-on-write (reflink) when available for space-efficient copies+- Handles nested `.gitignore` files, global excludes, and `.git/info/exclude`+- Skips existing files by default (safe to re-run)+- `--force` overwrites existing files in the destination+- Always skips built-in excluded directories — VCS metadata (`.bzr/`, `.hg/`, `.jj/`, `.pijul/`, `.sl/`, `.svn/`) and tool-state (`.conductor/`, `.entire/`, `.worktrees/`) — and nested worktrees++### Performance++Reflink copies share disk blocks until modified — no data is actually copied. For a 14GB `target/` directory:++| Command | Time |+|---------|------|+| `cp -R` (full copy) | 2m |+| `cp -Rc` / `wt step copy-ignored` | 20s |++Uses per-file reflink (like `cp -Rc`) — copy time scales with file count.++Use the `post-start` hook so the copy runs in the background. Use `pre-start` instead if subsequent hooks or `--execute` command need the copied files immediately.++### Background-hook priority (experimental)++When invoked from a background hook pipeline (`post-*` hooks), `wt step copy-ignored` self-lowers its CPU and I/O priority — `taskpolicy -b` on macOS, `nice -n 19` plus `ionice -c 3` on Linux — so it yields to interactive work. Foreground callers (`pre-*` hooks, direct interactive use) run at normal priority so the user isn't waiting on a throttled copy.++wt signals background-hook context by exporting `WORKTRUNK_FOREGROUND=-1` into every detached hook pipeline; `copy-ignored` inspects that variable on entry. The variable name is experimental and may change.++### Language-specific notes++#### Rust++The `target/` directory is huge (often 1-10GB). Copying with reflink cuts first build from ~68s to ~3s by reusing compiled dependencies.++#### Node.js++`node_modules/` is large but mostly static. If the project has no native dependencies, symlinks are even faster:++```toml+[pre-start]+deps = "ln -sf {{ primary_worktree_path }}/node_modules ."+```++#### Python++Virtual environments contain absolute paths and can't be copied. Use `uv sync` instead — it's fast enough that copying isn't worth it.++### Behavior vs Claude Code on desktop++The `.worktreeinclude` pattern is shared with [Claude Code on desktop](https://code.claude.com/docs/en/desktop), which copies matching files when creating worktrees. Differences:++- worktrunk copies all gitignored files by default; Claude Code requires `.worktreeinclude`. Pass `--require-include` to match Claude Code (copy nothing without `.worktreeinclude`)+- worktrunk uses copy-on-write for large directories like `target/` — potentially 30x faster on macOS, 6x on Linux+- worktrunk runs as a configurable hook in the worktree lifecycle++### Command reference++```+wt step copy-ignored - Copy gitignored files to another worktree++Eliminates cold starts by copying build caches and dependencies.++Usage: wt step copy-ignored [OPTIONS]++Options:+ --from <FROM>+ Source worktree branch++ Defaults to main worktree.++ --to <TO>+ Destination worktree branch++ Defaults to current worktree.++ --dry-run+ Show what would be copied++ --force+ Overwrite existing files in destination++ --require-include+ Require .worktreeinclude to copy anything++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after the copy completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step eval++[experimental]++Evaluate a template expression. Prints the result to stdout for use in scripts and shell substitutions.++All [hook template variables and filters](https://worktrunk.dev/hook/#template-variables) are available.++### Examples++Get the port for the current branch:++```bash+$ wt step eval '{{ branch | hash_port }}'+16066+```++Use in shell substitution:++```bash+$ curl http://localhost:$(wt step eval '{{ branch | hash_port }}')/health+```++Combine multiple values:++```bash+$ wt step eval '{{ branch | hash_port }},{{ ("supabase-api-" ~ branch) | hash_port }}'+16066,16739+```++Use conditionals and filters:++```bash+$ wt step eval '{{ branch | sanitize_db }}'+feature_auth_oauth2_a1b+```++List the available template variables with `-v` (alongside the expansion, on stderr):++```bash+$ wt step eval -v '{{ branch }}'+○ Available template variables+ branch = feature/auth-oauth2+ worktree_path = /home/user/projects/myapp-feature-auth-oauth2+○ eval source+ {{ branch }}+○ eval result+ feature/auth-oauth2++feature/auth-oauth2+```++Note: This command is experimental and may change in future versions.++### Command reference++```+wt step eval - [experimental] Evaluate a template expression++Prints the result to stdout for use in scripts and shell substitutions.++Usage: wt step eval [OPTIONS] <TEMPLATE>++Arguments:+ <TEMPLATE>+ Template expression to evaluate++Options:+ -h, --help+ Print help (see a summary with '-h')++Automation:+ --format <FORMAT>+ Output format++ JSON prints {name, template, result} to stdout instead of the bare result.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step for-each++[experimental]++Run command in each worktree. Executes sequentially with real-time output; continues past command failures.++A summary of successes and failures is shown at the end. A template-expansion error (a malformed `{{ … }}` argument) aborts the whole run; only command failures are tolerated and reported. Context JSON — a flat object of every template variable — is piped to stdin for scripts that need structured data.++### Arguments++Arguments after `--` are the program and its arguments — run directly, no shell.++```bash+$ wt step for-each -- git status --short+$ wt step for-each -- npm install+```++For pipes, redirects, variables, or globs, wrap in `sh -c`:++```bash+$ wt step for-each -- sh -c 'git status | wc -l'+$ wt step for-each -- sh -c 'echo $HOME && git pull'+```++### Template variables++Variables substitute into each argv element before exec. See [`wt hook` template variables](https://worktrunk.dev/hook/#template-variables) for the complete list and filters.++```bash+$ wt step for-each -- echo 'Branch: {{ branch }}'+```++Each element is expanded fresh in every worktree, so `{{ branch }}` is that worktree's branch. An alias wrapping for-each renders templates earlier, in the invoking worktree; [deferring expansion in an alias](https://worktrunk.dev/extending/#deferring-expansion-to-a-nested-wt-command) shows how to keep a variable per-worktree.++### Examples++Pull updates in worktrees with upstreams (skips others):++```bash+$ git fetch --prune && wt step for-each -- sh -c '[ "$(git rev-parse @{u} 2>/dev/null)" ] || exit 0; git pull --autostash'+```++Note: This command is experimental and may change in future versions.++### Command reference++```+wt step for-each - [experimental] Run command in each worktree++Executes sequentially with real-time output; continues past command failures.++Usage: wt step for-each [OPTIONS] -- <ARGS>...++Arguments:+ <ARGS>...+ Command template (see --help for all variables)++Options:+ --format <FORMAT>+ Output format++ [default: text]+ [possible values: text, json]++ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step promote++[experimental]++Swap a branch into the main worktree. Exchanges branches and gitignored files between two worktrees.++**Experimental.** Use promote for temporary testing when the main worktree has special significance (Docker Compose, IDE configs, heavy build artifacts anchored to project root), and hooks & tools aren't yet set up to run on arbitrary worktrees. The idiomatic Worktrunk workflow does not use `promote`; instead each worktree has a full environment. `promote` is the only Worktrunk command which changes a branch in an existing worktree.++### Example++```bash+# from ~/project (main worktree)+$ wt step promote feature+```++Before:++```+ Branch Path+@ main ~/project++ feature ~/project.feature+```++After:++```+ Branch Path+@ feature ~/project++ main ~/project.feature+```++To restore: `wt step promote main` from anywhere, or just `wt step promote` from the main worktree.++Without an argument, promotes the current branch — or restores the default branch if run from the main worktree.++### Requirements++- Both worktrees must be clean+- The branch must have an existing worktree++### Gitignored files++Gitignored files (build artifacts, `node_modules/`, `.env`) are swapped along with the branches so each worktree keeps the artifacts that belong to its branch. Files are discovered using the same mechanism as [`copy-ignored`](#wt-step-copy-ignored) and can be filtered with `.worktreeinclude`.++The swap uses `rename()` for each entry — fast regardless of entry size, since only filesystem metadata changes. If the worktree is on a different filesystem from `.git/`, it falls back to reflink copy.++### Command reference++```+wt step promote - [experimental] Swap a branch into the main worktree++Exchanges branches and gitignored files between two worktrees.++Usage: wt step promote [OPTIONS] [BRANCH]++Arguments:+ [BRANCH]+ Branch to promote to main worktree++ Defaults to current branch, or default branch from main worktree.++Options:+ -h, --help+ Print help (see a summary with '-h')++Automation:+ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after the promote completes. The mismatch warning+ still appears on stderr in JSON mode (safety signal).++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step prune++[experimental]++Remove worktrees merged into the default branch.++Bulk-removes worktrees and branches that are integrated into the default branch, using the same criteria as `wt remove`'s branch cleanup. Stale worktree entries are cleaned up too.++In `wt list`, candidates show `_` (same commit) or `⊂` (content integrated). Run `--dry-run` to preview. See `wt remove --help` for the full integration criteria.++Locked worktrees and the main worktree are always skipped. The current worktree is removed last, triggering cd to the primary worktree. Pre-remove and post-remove hooks run for each removal; a candidate whose hooks include an unapproved project command is skipped with `(approval required)` (pre-approve with `wt config approvals add`, or pass `--yes`).++### Min-age guard++Worktrees younger than `--min-age` (default: 1 day) are skipped. This prevents removing a worktree just created from the default branch — it looks "merged" because its branch points at the same commit.++```bash+$ wt step prune --min-age=0s # no age guard+$ wt step prune --min-age=2d # skip worktrees younger than 2 days+```++### Examples++Preview what would be removed:++```bash+$ wt step prune --dry-run+```++Remove all merged worktrees:++```bash+$ wt step prune+```++### Command reference++```+wt step prune - [experimental] Remove worktrees merged into the default branch++Usage: wt step prune [OPTIONS]++Options:+ --dry-run+ Show what would be removed++ --min-age <MIN_AGE>+ Skip worktrees younger than this++ [default: 1d]++ --foreground+ Run removal in foreground (block until complete)++ --format <FORMAT>+ Output format++ [default: text]+ [possible values: text, json]++ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step relocate++[experimental]++Move worktrees to expected paths. Relocates worktrees whose path doesn't match the worktree-path template.++### Examples++Preview what would be moved:++```bash+$ wt step relocate --dry-run+```++Move all mismatched worktrees:++```bash+$ wt step relocate+```++Auto-commit and clobber blockers (never fails):++```bash+$ wt step relocate --commit --clobber+```++Move specific worktrees:++```bash+$ wt step relocate feature bugfix+```++### Swap handling++When worktrees are at each other's expected locations (e.g., `alpha` at+`repo.beta` and `beta` at `repo.alpha`), relocate automatically resolves+this by using a temporary location.++### Clobbering++With `--clobber`, non-worktree paths at target locations are moved to+`<path>.bak.<timestamp>` before relocating. If that name is already taken,+the move counts up (`…-2`, `…-3`, …) until it finds a free name, so an+existing backup is never overwritten.++### Main worktree behavior++The main worktree can't be moved with `git worktree move`. Instead, relocate+switches it to the default branch and creates a new linked worktree at the+expected path. Untracked and gitignored files remain at the original location.++### Dirty worktrees++Linked worktrees relocate as-is — `git worktree move` carries uncommitted+changes along. Only the main worktree skips when dirty (its `git checkout`+refuses), unless `--commit` is passed.++### Skipped worktrees++- **Dirty main worktree** (without `--commit`) — use `--commit` to auto-commit first+- **Locked** — unlock with `git worktree unlock`+- **Target blocked** (without `--clobber`) — use `--clobber` to backup blocker+- **Detached HEAD** — no branch to compute expected path++Note: This command is experimental and may change in future versions.++### Command reference++```+wt step relocate - [experimental] Move worktrees to expected paths++Relocates worktrees whose path doesn't match the worktree-path template.++Usage: wt step relocate [OPTIONS] [BRANCHES]...++Arguments:+ [BRANCHES]...+ Worktrees to relocate (defaults to all mismatched)++Options:+ --dry-run+ Show what would be moved++ --commit+ Commit uncommitted changes before relocating++ --clobber+ Backup non-worktree paths at target locations++ Moves blocking paths to <path>.bak.<timestamp>. If that name is taken, counts up (…-2, …-3+ , …) to a free name.++ -h, --help+ Print help (see a summary with '-h')++Automation:+ --format <FORMAT>+ Output format++ JSON prints structured result to stdout after the relocate completes.++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```++## wt step tether++[experimental]++Run a command; kill its whole process tree when its worktree is removed. Teardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.++### Why++A `post-start` hook to start a long-lived process and a `pre-remove` hook to+stop it is usually enough. But `pre-remove` only runs when worktrunk removes+the worktree, so a `git worktree remove`, an `rm -rf`, or a crashed hook skips+it. Across enough worktree churn some process is bound to outlive its worktree,+and with no cleanup these leaks accumulate (on macOS they eventually saturate+`fseventsd`). `tether` removes the need for a `pre-remove`: it ties the+command's lifetime to the worktree and kills the whole process group once the+worktree is gone.++### Arguments++Arguments after `--` are the program and its arguments, run directly, no shell.++```bash+$ wt step tether -- npm run dev+```++For pipes, redirects, variables, or globs, wrap in `sh -c`:++```bash+$ wt step tether -- sh -c 'PORT=$P npm run dev | tee dev.log'+```++To run the command from a subdirectory, pass the global `-C` flag (teardown+still watches the worktree root, so a server launched with a relative `-C` is+torn down with the worktree):++```bash+$ wt step tether -C frontend -- npm run dev+```++### Examples++Run a dev server, torn down automatically when the worktree goes away:++```toml+# .config/wt.toml+[post-start]+server = "wt step tether -- npm run dev -- --port {{ branch | hash_port }}"+```++Note: This command is experimental and may change in future versions.++### Command reference++```+wt step tether - [experimental] Run a command; kill its whole process tree when its worktree is removed++Teardown is automatic and needs no pre-remove hook; the group gets SIGTERM then SIGKILL.++Usage: wt step tether [OPTIONS] -- <COMMAND>...++Arguments:+ <COMMAND>...+ Command to run (after --, run directly, no shell)++Options:+ -h, --help+ Print help (see a summary with '-h')++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/switch.md b/plugins/worktrunk/skills/worktrunk/reference/switch.mdnew file mode 100644index 000000000..c9520a63b--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/switch.md@@ -0,0 +1,246 @@+# wt switch++Switch to a worktree; create if needed.++Worktrees are addressed by branch name; paths are computed from a configurable template. Unlike `git switch`, this navigates between worktrees rather than changing branches in place.++## Examples++```bash+$ wt switch feature-auth # Switch to worktree+$ wt switch - # Previous worktree (like cd -)+$ wt switch --create new-feature # Create new branch and worktree+$ wt switch --create hotfix --base production+$ wt switch pr:123 # Switch to PR #123's branch+$ wt switch https://github.com/owner/repo/pull/123 # ...or paste the PR's URL+```++## Creating a branch++The `--create` flag creates a new branch from `--base` — the default branch unless specified. Without `--create`, the branch must already exist. Switching to a remote branch (e.g., `wt switch feature` when only `origin/feature` exists) creates a local tracking branch.++## Creating worktrees++If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one:++1. Runs [pre-switch hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete+2. Creates worktree at configured path+3. Switches to new directory+4. Runs [pre-start hooks](https://worktrunk.dev/hook/#hook-types), blocking until complete+5. Spawns [post-start](https://worktrunk.dev/hook/#hook-types) and [post-switch hooks](https://worktrunk.dev/hook/#hook-types) in the background++```bash+$ wt switch feature # Existing branch → creates worktree+$ wt switch --create feature # New branch and worktree+$ wt switch --create fix --base release # New branch from release+$ wt switch --create temp --no-hooks # Skip hooks+```++## Shortcuts++| Shortcut | Meaning |+|----------|---------|+| `^` | Default branch (`main`/`master`) |+| `@` | Current branch/worktree |+| `-` | Previous worktree (like `cd -`) |+| `pr:{N}` | GitHub PR #N's branch |+| `mr:{N}` | GitLab MR !N's branch |++```bash+$ wt switch - # Back to previous+$ wt switch ^ # Default branch worktree+$ wt switch --create fix --base=@ # Branch from current HEAD+$ wt switch --create fix --base=pr:123 # Branch from PR #123's head+$ wt switch pr:123 # PR #123's branch+$ wt switch mr:101 # MR !101's branch+```++Shortcuts also apply to `--base`. For a fork PR/MR, the head commit is fetched and used as the base SHA without creating a tracking branch.++## Interactive picker++When called without arguments, `wt switch` opens an interactive picker to browse and select worktrees with live preview. The candidate set widens with `--branches` (local branches without worktrees), `--remotes` (remote branches), and `--prs` (open PRs/MRs — see below).++The CI column shows each row's PR/MR CI and review status, the same as [`wt list --full`](https://worktrunk.dev/list/).++**Keybindings:**++| Key | Action |+|-----|--------|+| `↑`/`↓` | Navigate worktree list |+| (type) | Filter worktrees |+| `Enter` | Switch to selected worktree |+| `Alt-c` | Create new worktree named as entered text |+| `Alt-x` | Remove selected worktree/branch |+| `Alt-y` | Copy selected branch name to the clipboard |+| `Alt-o` | Open the selected row's PR/MR URL in the browser |+| `Alt-r` | Refresh the list (pick up worktrees created elsewhere) |+| `Esc` | Cancel |+| `Alt-1`–`Alt-7` | Jump to a preview tab |+| `Tab`/`Shift-Tab` | Cycle preview tabs forward/backward |+| `Alt-p` | Toggle preview panel |+| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |++`Alt-o` is a no-op on a row with no PR/MR (or whose status hasn't loaded yet).++`Alt-x` is a no-op on the current worktree (the `@` row) — removing the worktree in use would have to switch elsewhere first, so switch away and remove it from there.++Each row filters by its branch, path, and — when it has a PR/MR — the PR/MR's number, title, and author, the same fields whether the PR is checked out (a worktree row) or listed via `--prs`. Plain digits go to the filter, so a number can be typed directly and the preview tabs move to `Alt`.++Typing a gutter sigil filters by row kind: `+` narrows to linked worktrees and `@` to the current worktree. The other sigils don't filter cleanly — `^` and `|` are skim's prefix-anchor and OR query operators (so `^` matches every row and `|` none), and `/` matches most rows because every worktree path contains it.++**Preview tabs:**++1. **HEAD±** — Diff of uncommitted changes+2. **log** — Recent commits; commits already on the default branch have dimmed hashes+3. **main…±** — Diff of changes since the merge-base with the default branch+4. **remote⇅** — Ahead/behind diff vs upstream tracking branch+5. **summary** — LLM-generated branch summary; requires `[list] summary = true` and [`commit.generation`](https://worktrunk.dev/config/#commit)+6. **pr** — The selected row's PR/MR, for any row whose branch has one+7. **comments** — The PR/MR's comment thread, fetched from the forge on `--prs` rows++On narrow previews the tab bar compacts to digits — only the active tab keeps its label — so every `Alt-N` accelerator stays visible.++**Pager configuration:** The preview panel pipes diff output through git's pager. Override in user config:++```toml+[switch.picker]+pager = "delta --paging=never --width=$COLUMNS"+```++## Pull requests and merge requests++The `pr:<number>` / `mr:<number>` shortcut and the PR/MR's web URL both resolve to its branch. For same-repo PRs/MRs, worktrunk switches to the branch directly. For fork PRs/MRs, it fetches the ref (`refs/pull/N/head` or `refs/merge-requests/N/head`) and configures `pushRemote` to the fork URL.++```bash+$ wt switch pr:101 # GitHub PR #101+$ wt switch https://github.com/owner/repo/pull/101 # ...the same PR, by URL+$ wt switch mr:101 # GitLab MR !101+$ wt switch https://gitlab.com/owner/repo/-/merge_requests/101 # ...the same MR, by URL+$ wt switch --prs # Browse open PRs/MRs in the picker+```++Both work anywhere a branch is accepted, including `--base`. The `--create` flag cannot be used with a PR/MR reference since the branch already exists.++If the PR or MR is on a fork, the local branch uses its branch name directly, so `git push` works normally. A pre-existing local branch with that name tracking something else requires renaming first.++The `--prs` flag adds the repository's open PRs (GitHub) or MRs (GitLab) to the interactive picker — only the ones not already there: a PR whose branch is already shown (as a worktree, or a local or remote branch) isn't listed twice, so `--prs` only adds the rest and the two pickers differ solely by those extra rows. Each added row resolves to the same `pr:`/`mr:` shortcut, so selecting one fetches the ref and switches to its branch. A `--prs` row has no local worktree, so its `pr` and `comments` preview tabs load the PR/MR's metadata and comments from the forge in the background. The `log` tab uses a local `git log` — graph and merge-base dimming included — whenever the head commit is already in the object store (a same-repo PR off a fetched remote), falling back to a flat forge-fetched commit list otherwise.++Requires `gh` (GitHub), `glab` (GitLab), or an equivalent CLI installed and authenticated; see [forge platform](https://worktrunk.dev/config/#forge-platform) for Gitea, Azure DevOps, and other supported platforms.++## When wt switch fails++- **Branch doesn't exist** — Use `--create`, or check `wt list --branches`+- **Path occupied** — Another worktree is at the target path; switch to it or remove it+- **Stale directory** — Use `--clobber` to remove a non-worktree directory at the target path++To change which branch a worktree is on, use `git switch` inside that worktree.++## Command reference++```+wt switch - Switch to a worktree; create if needed++Usage: wt switch [OPTIONS] [BRANCH] [-- <EXECUTE_ARGS>...]++Arguments:+ [BRANCH]+ Branch name, shortcut, or PR/MR URL++ Opens interactive picker if omitted. Shortcuts: ^ (default branch), - (previous), @+ (current), pr:{N} (GitHub PR), mr:{N} (GitLab MR)++ [EXECUTE_ARGS]...+ Additional arguments for --execute command (after --)++ Arguments after -- are appended to the execute command. Each argument is expanded for+ templates, then POSIX shell-escaped.++Options:+ -c, --create+ Create a new branch++ -b, --base <BASE>+ Base branch++ Defaults to default branch. Supports the same shortcuts as the branch argument: ^, @, -,+ pr:{N}, mr:{N}.++ -x, --execute <EXECUTE>+ Command to run after switch++ Replaces the wt process with the command after switching, giving it full terminal control.+ Useful for launching editors, AI agents, or other interactive tools.++ Without a branch argument, the interactive picker opens and the command runs against the+ selected worktree — so wt switch -x claude picks a worktree, then launches Claude Code+ there.++ Supports hook template variables ({{ branch }}, {{ worktree_path }}, etc.) and filters. {{+ base }} and {{ base_worktree_path }} require --create.++ Especially useful with shell aliases:++ alias wsc='wt switch --create -x claude'+ wsc feature-branch -- 'Fix GH #322'++ Then wsc feature-branch creates the worktree and launches Claude Code. Arguments after --+ are passed to the command, so wsc feature -- 'Fix GH #322' runs claude 'Fix GH #322',+ starting Claude with a prompt.++ Template example: -x code -- '{{ worktree_path }}' opens VS Code at the worktree, -x tmux+ -- new -s '{{ branch | sanitize }}' starts a tmux session named after the branch.++ --clobber+ Remove stale paths at target++ --no-cd+ Skip directory change after switching++ Hooks still run normally. Useful when hooks handle navigation (e.g., tmux workflows) or+ for CI/automation. Use --cd to override.++ -h, --help+ Print help (see a summary with '-h')++Picker Options:+ --branches+ Include branches without worktrees++ --remotes+ Include remote branches++ --prs+ Include open PRs/MRs++Automation:+ --no-hooks+ Skip hooks++ --format <FORMAT>+ Output format++ JSON prints structured result to stdout. Designed for tool integration (e.g., Claude Code+ WorktreeCreate hooks).++ [default: text]+ [possible values: text, json]++Global Options:+ -C <path>+ Working directory for this command++ --config <path>+ User config file path++ --config-set <toml>+ Override config with inline TOML, e.g. --config-set list.full=true (repeatable)++ -v, --verbose...+ Verbose output (-v: info logs + hook/alias template variables on stderr; -vv: also debug+ logs and raw subprocess output written to .git/wt/logs/). Set WORKTRUNK_VERBOSE=0|1|2 to+ apply the same level everywhere — including shell completion, which no flag can reach++ -y, --yes+ Skip approval prompts+```diff --git a/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.mdnew file mode 100644index 000000000..80e0780dd--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/tips-patterns.md@@ -0,0 +1,527 @@+# Tips & Patterns++Practical recipes for common Worktrunk workflows.++## 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'`+```++## `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.++## 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:++```bash+$ wt list+ <b>Branch</b> <b>Status</b> <b>HEAD±</b> <b>main↕</b> <b>main…±</b> <b>Remote⇅</b> <b>URL</b> <b>Commit</b>+@ main <span class=c>?</span> <span class=d>^</span><span class=d>⇅</span> <span class=g>⇡1</span> <span class=d><span class=r>⇣1</span></span> <span class=d>http://localhost:12107</span> <span class=d>41ee0834</span>++ feature-api <span class=c>+</span> <span class=d>↕</span><span class=d>⇡</span> <span class=g>+54</span> <span class=r>-5</span> <span class=g>↑4</span> <span class=d><span class=r>↓1</span></span> <span class=g>+234</span> <span class=r>-24</span> <span class=g>⇡3</span> <span class=d>http://localhost:10703</span> <span class=d>6814f02a</span>++ fix-auth <span class=d>↕</span><span class=d>|</span> <span class=g>↑2</span> <span class=d><span class=r>↓1</span></span> <span class=g>+25</span> <span class=r>-11</span> <span class=d>|</span> <span class=d>http://localhost:16460</span> <span class=d>b772e68b</span>++ <span class=d>fix-typos</span> <span class=d>_</span><span class=d>|</span> <span class=d>|</span> <span class=d>http://localhost:14301</span> <span class=d>41ee0834</span>++<span class=d>○</span> <span class=d>Showing 4 worktrees, 2 with changes, 2 ahead, 3 columns hidden</span>+```++`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+[[post-start]]+set-vars = """+wt config state vars set \+ container='{{ repo }}-{{ branch | sanitize }}-postgres' \+ port='{{ ('db-' ~ branch) | hash_port }}' \+ 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+export MY_PACKAGES_PATH="$PWD/.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+[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 — without the `--execute` workaround. Each new worktree is a new path, so it needs its own one-time trust step (`direnv allow` / `mise trust`); worktrunk deliberately doesn't bypass that prompt, the same safety reasoning behind [disabling `--execute` in project alias and hook bodies](https://github.com/max-sixty/worktrunk/issues/2101).++## 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+[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+[[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.++## 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.++## Track agent status++Custom emoji markers show agent state in `wt list`. The [Claude Code](https://worktrunk.dev/claude-code/) plugin and [OpenCode plugin](https://github.com/max-sixty/worktrunk/tree/main/dev/opencode-plugin.ts) set these automatically:++```++ feature-api ↑ 🤖 ↑1 ./repo.feature-api++ review-ui ? ↑ 💬 ↑1 ./repo.review-ui+```++- `🤖` — Agent is working+- `💬` — Agent is waiting for input++Set status manually for any workflow:++```bash+wt config state marker set "🚧" # Current branch+wt config state marker set "✅" --branch feature # Specific branch+git config worktrunk.state.feature.marker '{"marker":"💬","set_at":0}' # Direct+```++See [Claude Code Integration](https://worktrunk.dev/claude-code/#installation) for plugin installation.++## 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 (tab 5).++```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.++## Reuse `default-branch`++Worktrunk maintains useful state. Default branch [detection](https://worktrunk.dev/config/#wt-config-state-default-branch), for instance, 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.++## Task runners in hooks++Reference Taskfile/Justfile/Makefile in hooks:++```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+[[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+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.++## 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=@+```++## Agent handoffs++Spawn a worktree with an agent CLI running in the background. Examples below use `claude`; for OpenCode, replace `claude` with `'opencode run'`.++**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+When I ask you to spawn parallel worktrees, use the agent handoff pattern+from the worktrunk skill.+```++## 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:++```bash+$ 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+"""+```++This precisely targets only the DerivedData for the removed worktree, leaving caches for other worktrees and the main repository intact.++## 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 }}` → 16460)+2. The hook starts Caddy if needed and registers a route using the same port: `feature-auth.myproject` → `localhost:16460`+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++## Monitor hook logs++Follow background hook output:++```bash+tail -f "$(wt config state logs get --hook=user:post-start:server)"+```++The `--hook` format is `source:hook-type:name` — e.g., `project:post-start:build` for project-defined hooks. Use `wt config state logs get` to list all available logs.++Create an alias for frequent use:++```bash+alias wtlog='f() { tail -f "$(wt config state logs get --hook="$1")"; }; f'+```++## 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+```++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+cd myproject/main+wt config create --project+```++Commit the file and it will appear in every worktree automatically.diff --git a/plugins/worktrunk/skills/worktrunk/reference/troubleshooting.md b/plugins/worktrunk/skills/worktrunk/reference/troubleshooting.mdnew file mode 100644index 000000000..6b30ab3b5--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/troubleshooting.md@@ -0,0 +1,165 @@+# Troubleshooting++Claude-specific troubleshooting guidance for common worktrunk issues.++## Commit Message Generation++### Command not found++Check if the configured tool is installed:++```bash+wt config show # shows the configured command+which claude # or: which codex, which llm, which aichat+```++If empty, install one of the supported tools. See [LLM commits docs](https://worktrunk.dev/llm-commits/) for setup instructions.++### Command returns an error++Test the configured command directly by piping a prompt to it. See `reference/llm-commits.md` for the exact command syntax for each tool.++```bash+echo "say hello" | <your-configured-command>+```++Common issues:+- **API key not set**: Each tool has its own auth mechanism+- **Model not available**: Check model name with the tool's help+- **Network issues**: Check internet connectivity++### Config not loading++1. View config path: `wt config show` shows location+2. Verify file exists: `ls -la ~/.config/worktrunk/config.toml`+3. Check TOML syntax: `cat ~/.config/worktrunk/config.toml`+4. Look for validation errors (path must be relative, not absolute)++### Template conflicts++Check for mutually exclusive options:+- `template` and `template-file` cannot both be set+- `squash-template` and `squash-template-file` cannot both be set++If a template file is used, verify it exists at the specified path.++## Hooks++### Hook not running++Check sequence:+1. Verify `.config/wt.toml` exists: `ls -la .config/wt.toml`+2. Check TOML syntax (use `wt hook show` to see parsed config)+3. Verify hook type spelling matches one of the ten types+4. Test command manually in the worktree++### Hook failing++Debug steps:+1. Run the command manually in the worktree to see errors+2. Check for missing dependencies (npm packages, system tools)+3. Verify template variables expand correctly with `wt hook show --expanded` (shows each command with its variables substituted)+4. For background hooks, check `.git/wt/logs/` for output++### Slow blocking hooks++Move long-running commands to background:++```toml+# Before — blocks for minutes+pre-start = "npm run build"++# After — fast setup, build in background+pre-start = "npm install"+post-start = "npm run build"+```++## Aliases++### Inspecting an alias++- `wt config alias show <name>` prints the raw template.+- `wt config alias dry-run <name> [-- args...]` prints the rendered command without running it.++### A `for-each` or `--execute` alias uses the same value in every worktree++The alias body renders once at dispatch, in the invoking worktree, so a per-worktree variable like `{{ branch }}` is baked before the nested `wt` command iterates. If `wt config alias dry-run <name>` shows a single substituted value (e.g. `… echo branch=main`), it was baked at that first pass. Defer it with `{% raw %}{{ branch }}{% endraw %}`, and for `for-each` keep it inside a quoted `sh -c '...'` so the alias's shell doesn't word-split it. Repo-level variables like `{{ default_branch }}` are unaffected — they are identical in every worktree. See `reference/extending.md#deferring-expansion-to-a-nested-wt-command`.++## List++### `wt list` times out after 120s++The timeout warning names the tasks that didn't finish:++```+wt list timed out after 120s (170 results received); blocked tasks:+ <branch>: working-tree-diff, working-tree-conflicts+```++Both tasks run `git status --porcelain` first. When the named worktree has `core.fsmonitor=true` and its `git fsmonitor--daemon` is wedged, `git status` blocks until the IPC attempt fails (several minutes), and the 120s drain deadline fires first.++Confirm by running `git status` in the affected worktree:++```bash+cd <worktree>+time git --no-optional-locks status --porcelain+# error: could not read IPC response → hung daemon+```++List running daemons with their IPC socket (identifies which worktree each serves):++```bash+for pid in $(pgrep -f 'git fsmonitor--daemon'); do+ sock=$(lsof -p $pid 2>/dev/null | grep 'fsmonitor--daemon.ipc' | awk '{print $NF}' | head -1)+ printf "%6d %s\n" "$pid" "$sock"+done+```++Sockets listed as bare `fsmonitor--daemon.ipc` (no resolved path) belong to deleted worktrees. `wt remove` reaps these as part of its internal sweep: after the primary removal output, it sends `SIGTERM` (then `SIGKILL` after a short bounded wait) to every `git fsmonitor--daemon` whose socket no longer resolves to a live worktree. That covers daemons orphaned by `wt remove` itself and by paths that bypass it (plain `git worktree remove`, manual `rm -rf`, or a crashed `wt`).++`wt remove` also force-terminates the removed worktree's own daemon as part of the synchronous teardown — it sends `git fsmonitor--daemon stop`, then resolves the daemon's PID from its IPC socket and SIGTERM/SIGKILLs it if it didn't exit. So removing a worktree never leaves a daemon behind, even one that has stopped answering its IPC.++The residual case both paths deliberately leave is a wedged daemon on a *live* worktree that is never removed: `git status` in that worktree blocks on the unresponsive IPC, but the daemon still serves a real worktree, so reaping it implicitly is out of scope. Terminate it manually: kill the daemon whose socket path matches the worktree, or `pkill -9 -f 'git fsmonitor--daemon'` and let the next `wt list` respawn the live ones. Disabling fsmonitor globally (`git config --global core.fsmonitor false`) avoids the class of problem entirely at the cost of some `git status` speed on large repos.++## PowerShell on Windows++### PowerShell profiles not created++On Windows, `wt config shell install` creates PowerShell profiles automatically when running from cmd.exe or PowerShell. It creates both:+- `Documents/PowerShell/Microsoft.PowerShell_profile.ps1` (PowerShell 7+/pwsh)+- `Documents/WindowsPowerShell/Microsoft.PowerShell_profile.ps1` (Windows PowerShell 5.1)++**If running from Git Bash or MSYS2**, PowerShell is skipped because the `SHELL` environment variable is set. To create PowerShell profiles explicitly:++```bash+wt config shell install powershell+```++### Wrong PowerShell variant configured++Both profile files are created when installing from a Windows-native shell. This ensures shell integration works regardless of which PowerShell variant the user opens later. The profile files are small and harmless if unused.++### Shell integration configured but not active++When `wt config show` shows the profile line is configured but shell integration+is "not active", ask the user to run these diagnostics in the same PowerShell+session:++1. `Get-Command git-wt -All` — shows whether the wrapper Function is loaded+ alongside the Application (exe). If only Application appears, the profile+ didn't define the function (restart shell, or profile load failed).++2. `(Get-Command git-wt -CommandType Function).ScriptBlock | Select-String+ WORKTRUNK` — verifies the wrapper function body sets+ `WORKTRUNK_DIRECTIVE_CD_FILE`. If this doesn't appear, the function is+ incomplete or corrupted.++3. `Get-Command git-wt -CommandType Application | Select-Object Source` — shows+ what the wrapper resolves as `$wtBin`. If empty, the wrapper can't find the+ binary and will fail silently.++### Detection logic++Worktrunk detects Windows-native shells (cmd/PowerShell) by checking if the `SHELL` environment variable is **not** set:+- `SHELL` not set → Windows-native shell → create both PowerShell profiles+- `SHELL` set (e.g., `/usr/bin/bash`) → Git Bash/MSYS2 → skip PowerShelldiff --git a/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md b/plugins/worktrunk/skills/worktrunk/reference/worktrunk.mdnew file mode 100644index 000000000..6af7745c5--- /dev/null+++ b/plugins/worktrunk/skills/worktrunk/reference/worktrunk.md@@ -0,0 +1,204 @@+# Worktrunk++Worktrunk is a CLI for git worktree management, designed for running AI agents+in parallel.++Worktrunk's three core commands make worktrees as easy as branches.+Plus, Worktrunk has a bunch of quality-of-life features to simplify working+with many parallel changes, including hooks to automate local workflows.++A quick demo:++## Context: git worktrees++AI agents like Claude Code and Codex can handle longer tasks without+supervision, such that it's possible to manage 5-10+ in parallel. Git's native+worktree feature give each agent its own working directory, so they don't step+on each other's changes.++But the git worktree UX is clunky. Even a task as small as starting a new+worktree requires typing the branch name three times: `git worktree add -b feat+../repo.feat`, then `cd ../repo.feat`.++## Worktrunk makes git worktrees as easy as branches++Worktrees are addressed by branch name; paths are computed from a configurable template.++> Start with the core commands++**Core commands:**++<table class="cmd-compare">+ <thead>+ <tr>+ <th>Task</th>+ <th>Worktrunk</th>+ <th>Plain git</th>+ </tr>+ </thead>+ <tbody>+ <tr>+ <td>Switch worktrees</td>+ <td>wt switch feat</td>+ <td>cd ../repo.feat</td>+ </tr>+ <tr>+ <td>Create + start Claude</td>+ <td>wt switch -c -x claude feat</td>+ <td>git worktree add -b feat ../repo.feat && \+cd ../repo.feat && \+claude</td>+ </tr>+ <tr>+ <td>Clean up</td>+ <td>wt remove</td>+ <td>cd ../repo && \+git worktree remove ../repo.feat && \+git branch -d feat</td>+ </tr>+ <tr>+ <td>List with status</td>+ <td>wt list</td>+ <td>git worktree list (paths only)</td>+ </tr>+ </tbody>+</table>++> Expand into the more advanced commands as needed++**Workflow automation:**++- **[Hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge, etc+- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs+- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command+- **[Interactive picker](https://worktrunk.dev/switch/#interactive-picker)** — browse worktrees with live diff and log previews+- **[Copy build caches](https://worktrunk.dev/step/#wt-step-copy-ignored)** — skip cold starts by sharing `target/`, `node_modules/`, etc between worktrees+- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch+- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch+- **[Dev server per worktree](https://worktrunk.dev/tips-patterns/#dev-server-per-worktree)** — `hash_port` template filter gives each worktree a unique port+- **[Aliases](https://worktrunk.dev/extending/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt <name>` commands and branch-scoped state for hook templates+- ...and **[lots more](#next-steps)**++Multiple parallel agents, same simple commands:++## Install++**Homebrew (macOS & Linux):**++```bash+brew install worktrunk && wt config shell install+```++Shell integration allows commands to change directories.++**Cargo:**++```bash+cargo install worktrunk && wt config shell install+```++<details>+<summary><strong>Windows & other</strong></summary>++**Windows.** `wt` defaults to Windows Terminal's command, so Winget additionally installs Worktrunk as `git-wt` to avoid the conflict:++```bash+winget install max-sixty.worktrunk+git-wt config shell install+```++Alternatively, disable Windows Terminal's alias (Settings → Apps → Advanced app settings → App execution aliases → "Terminal"/"Terminal Preview") to use `wt` directly.++**Arch Linux:**++```bash+sudo pacman -S worktrunk && wt config shell install+```++**Conda / Pixi** (community-maintained [feedstock](https://github.com/conda-forge/worktrunk-feedstock)):++```bash+conda install -c conda-forge worktrunk && wt config shell install+```++Or with [Pixi](https://pixi.sh): `pixi global install worktrunk && wt config shell install`.++</details>++## Quick start++Create a worktree for a new feature:++```bash+$ wt switch --create feature-auth+<span class=g>✓</span> <span class=g>Created branch <b>feature-auth</b> from <b>main</b> and worktree @ <b>~/repo.feature-auth</b></span>+```++This creates a new branch and worktree, then switches to it. Do your work, then check all worktrees with [`wt list`](https://worktrunk.dev/list/):++```bash+$ wt list+ <b>Branch</b> <b>Status</b> <b>HEAD±</b> <b>main↕</b> <b>main…±</b> <b>Remote⇅</b> <b>Commit</b> <b>Age</b> <b>Message</b>+@ feature-auth <span class=c>+</span> <span class=d>↑</span> <span class=g>+27</span> <span class=r>-8</span> <span class=g>↑1</span> <span class=g>+31</span> <span class=d>4bc72dc9</span> <span class=d>2h</span> <span class=d>Add authenticat…</span>+^ main <span class=d>^</span><span class=d>⇡</span> <span class=g>⇡1</span> <span class=d>0e631add</span> <span class=d>1d</span> <span class=d>Initial commit</span>++<span class=d>○</span> <span class=d>Showing 2 worktrees, 1 with changes, 1 ahead, 1 column hidden</span>+```++The `@` marks the current worktree. `+` means staged changes, `↑1` means 1 commit ahead of main, `⇡` means unpushed commits.++When done, either:++**PR workflow** — commit, push, open a PR, merge via GitHub/GitLab, then clean up:++```bash+wt step commit # commit staged changes+gh pr create # or glab mr create+wt remove # after PR is merged+```++**Local merge** — squash, rebase onto main, fast-forward merge, clean up:++```bash+$ wt merge main+<span class=c>◎</span> <span class=c>Generating commit message and committing changes... <span style='color:var(--bright-black,#555)'>(2 files, <span class=g>+53</span></span></span>, no squashing needed<span style='color:var(--bright-black,#555)'>)</span>+<span style='background:var(--bright-white,#fff)'> </span> <b>Add authentication module</b>+<span class=g>✓</span> <span class=g>Committed changes @ <span class=d>a1b2c3d</span></span>+<span class=c>◎</span> <span class=c>Merging 1 commit to <b>main</b> @ <span class=d>a1b2c3d</span> (no rebase needed)</span>+<span style='background:var(--bright-white,#fff)'> </span> * <span style='color:var(--yellow,#a60)'>a1b2c3d</span> Add authentication module+<span style='background:var(--bright-white,#fff)'> </span> auth.rs | 51 <span class=g>+++++++++++++++++++++++++++++++++++++++++++++++++++</span>+<span style='background:var(--bright-white,#fff)'> </span> lib.rs | 2 <span class=g>++</span>+<span style='background:var(--bright-white,#fff)'> </span> 2 files changed, 53 insertions(+)+<span class=g>✓</span> <span class=g>Merged to <b>main</b> <span style='color:var(--bright-black,#555)'>(1 commit, 2 files, <span class=g>+53</span></span></span><span style='color:var(--bright-black,#555)'>)</span>+<span class=c>◎</span> <span class=c>Removing <b>feature-auth</b> worktree & branch in background (same commit as <b>main</b>,</span> <span class=d>_</span><span class=c>)</span>+<span class=d>○</span> Switched to worktree for <b>main</b> @ <b>~/repo</b>+```++For parallel agents, create multiple worktrees and launch an agent in each:++```bash+wt switch -x claude -c feature-a -- 'Add user authentication'+wt switch -x claude -c feature-b -- 'Fix the pagination bug'+wt switch -x claude -c feature-c -- 'Write tests for the API'+```++The `-x` flag runs a command after switching; arguments after `--` are passed to it. Configure [post-start hooks](https://worktrunk.dev/hook/#hook-types) to automate setup (install deps, start dev servers).++## Next steps++- Learn the core commands: [`wt switch`](https://worktrunk.dev/switch/), [`wt list`](https://worktrunk.dev/list/), [`wt merge`](https://worktrunk.dev/merge/), [`wt remove`](https://worktrunk.dev/remove/)+- Set up [hooks](https://worktrunk.dev/hook/) for automated setup+- Explore [LLM commit messages](https://worktrunk.dev/llm-commits/), [interactive+ picker](https://worktrunk.dev/switch/#interactive-picker), [Claude Code integration](https://worktrunk.dev/claude-code/), [CI+ status & PR links](https://worktrunk.dev/list/#ci-status)+- Browse [tips & patterns](https://worktrunk.dev/tips-patterns/) for recipes: aliases, dev servers, databases, agent handoffs, and more+- [Extending Worktrunk](https://worktrunk.dev/extending/) — customize workflows with hooks & aliases+- Run `wt --help` or `wt <command> --help` for quick CLI reference++## Further reading++- [Claude Code: Best practices for agentic coding](https://www.anthropic.com/engineering/claude-code-best-practices) — Anthropic's official guide, including the worktree pattern+- [Shipping faster with Claude Code and Git Worktrees](https://incident.io/blog/shipping-faster-with-claude-code-and-git-worktrees) — incident.io's workflow for parallel agents+- [Git worktree pattern discussion](https://github.com/anthropics/claude-code/issues/1052) — Community discussion in the Claude Code repo+- [@DevOpsToolbox's video on Worktrunk](https://youtu.be/WBQiqr6LevQ?t=345)+- [git-worktree documentation](https://git-scm.com/docs/git-worktree) — Official git referencediff --git a/plugins/worktrunk/skills/wt-switch-create/SKILL.md b/plugins/worktrunk/skills/wt-switch-create/SKILL.mdnew file mode 100644index 000000000..87828bcfc--- /dev/null+++ b/plugins/worktrunk/skills/wt-switch-create/SKILL.md@@ -0,0 +1,106 @@+---+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.+argument-hint: "[<branch>] [<repo>] [-- <task>]"+license: MIT OR Apache-2.0+compatibility: Requires the `wt` CLI (https://worktrunk.dev)+---++Arguments: `$ARGUMENTS`. Grammar: `[<branch>] [<repo>] [-- <task>]`.++- **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 the+ session's current one.+- **task** — optional; what to do inside the new worktree. No task means enter+ the worktree and wait.++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++Steps 1–3 run on every invocation, before any other work. The invocation is+itself the explicit request to create the worktree; a research or read-only+task gets one all the same.++<!-- Maintainers: rationale.md (same directory) covers the harness rules and+design 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+ consistent with existing worktree names, 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>` for this repo):++ ```+ 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`: if the user named+ the branch, rerun without `--create` (it enters the branch, creating its+ worktree if missing); if step 1 picked the name, pick another and rerun. Any+ other failure (not a git repo, invalid name): report it and stop.++ Mid-session, carry uncommitted work across: `git stash push -u` before+ creating the worktree, then `git -C <path> stash pop` after (the stash is+ shared across worktrees).++3. **Enter the worktree, then do the task.** Call+ `EnterWorktree({path: "<path from the JSON>"})`.++ - **Accepted** → the session is re-rooted in the worktree. Do the task (or,+ with no task text, confirm it's ready and wait).+ - **Rejected** → graceful, and nothing is created. `EnterWorktree`+ re-roots only into a worktree the session is permitted to enter, and that+ permitted set is fixed by two factors: the repo your cwd resolves to, and+ the session's state. Each rejection is just that set coming up empty or+ without the target: no repo resolves (cwd is outside any git repo, e.g. a+ non-git parent such as `~/workspace` that only holds repos, as in a+ background job), which fails with `the current directory is not in a git+ repository`; the target belongs to a different repo than the one resolved;+ or the session is already rooted in a worktree (or is a pinned agent), a+ state that narrows the set to the resolved repo's `.claude/worktrees/` and+ so excludes even a same-repo `wt` sibling. All reduce to the same recovery+ test: whether you can `cd` into the worktree, which works when it's inside+ an allowed directory (a `permissions.additionalDirectories` entry such as+ `~/workspace`). So `cd <path>` and read the result:+ - no `Shell cwd was reset` notice → it stuck; the worktree is reachable.+ Work there, but a bare `cd` is not a tracked re-root, so the cwd can+ revert to the session's launch worktree across turns (and in spawned+ subagents); pin commands with `git -C <path>` / `wt -C <path>` rather+ than trusting the `cd` to persist.+ - `Shell cwd was reset` → not reachable. Stop and ask the user to make it+ reachable: add the repo, or a parent like `~/workspace`, to+ `permissions.additionalDirectories` (durable, every session), or run+ `/add-dir <path>` (this session). Then continue. Don't grind through+ absolute paths with `cd` resetting on every command.++## Cleanup++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>`.++## Scope++The command's mandate is ONE worktree (in the named repo, if one was given)+and the requested task inside it. Commits, pushes, and merges still each+require explicit user permission.diff --git a/plugins/worktrunk/skills/wt-switch-create/rationale.md b/plugins/worktrunk/skills/wt-switch-create/rationale.mdnew file mode 100644index 000000000..3dbb2ebb4--- /dev/null+++ b/plugins/worktrunk/skills/wt-switch-create/rationale.md@@ -0,0 +1,226 @@+# wt-switch-create design rationale++Why the skill is create-then-reach: create the worktree with `wt`, enter it with+`EnterWorktree`, and when entry is rejected, work in it if it's reachable or+escalate to the user to make it reachable. Not+the guard-heavy multi-route flow it replaced, and not the silent absolute-paths+fallback that read as a failure.++Every claim here was verified against primary sources (2026-06-11 to+2026-06-17): Claude Code 2.1.173, with the path-entry and working-directory+logic re-confirmed live and against the 2.1.177 binary, plus 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. Binary symbol names are+deliberately omitted — they re-minify every build.++## The design++1. Create the worktree with `wt -C <repo> switch --create <branch> --no-cd+ --format=json` in Bash (omit `-C` for this repo). `wt` solves repo targeting+ (`-C` works from anywhere), existing-branch handling (rerun without+ `--create`), and machine-readable output (`.path` on stdout, status on+ stderr). Creating in another repo is fine; only *entering* the result is+ constrained.+2. Enter it with `EnterWorktree({path})` — the only way to re-root a Claude Code+ session, and it accepts only a worktree of the session's own repo.+3. On rejection, the session can still work there iff the path sits inside a+ directory it's allowed in (an+ `additionalDirectories` entry). A single `cd <path>` discovers which: it+ sticks when reachable, resets when not. Reachable → work in place.+ Unreachable → escalate, because the agent can't enlarge that set itself: ask+ the user to add the repo or a parent (e.g. `~/workspace`) to+ `additionalDirectories`, or `/add-dir <path>`. A one-line, set-once handback,+ not a silent degrade.++Two independent harness facts underlie this — re-root is repo-scoped, and `cd`+persistence is working-directory-membership-scoped — detailed below.++## Why creation is unconditional++The recurring failure: handed a research or read-only task, the model decided+it didn't need isolation and skipped creation. Two wordings fed that. Scope's+"authorizes" read as permission, inviting a should-I test (user-level rules+that gate worktree creation behind an explicit request answer it "no"); an+ordering-only lead ("steps 1–3 come first") doesn't bind a model that decided+the steps don't apply. So the lead makes the invocation the explicit request+itself, and Scope states bounds rather than permission. Don't reintroduce+either wording.++## 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 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++A session works wherever its cwd is. Two mechanisms move it, and they *compose*:+`cd` moves the cwd (and so which repo `EnterWorktree` sees); `EnterWorktree`+re-roots within the repo the cwd is in. All verified live and against the+2.1.177 binary.++### M1 — `cd` (shell cwd)++Moves the shell cwd; the statusline and tool-path relativization+(`Write(foo/bar.py)`) follow it.++- **Gate:** the path must sit inside a configured working directory — the+ session's base cwd plus every entry in `permissions.additionalDirectories`+ (settings.json), `--add-dir` (launch), or `/add-dir` (mid-session).+- Inside → `cd` persists across Bash calls. Outside → the harness snaps it back+ and appends `Shell cwd was reset to <original>` to the result.+- **Repo-blind:** it checks only the path's location against that set, never+ which git repo owns the path. A different repo's worktree under `/tmp` is+ reachable when `/tmp` is configured.+- Within a *single* Bash call, `cd X && cmd` always works; the reset happens+ only *between* calls. (Subagent threads reset between every call.)++### M2 — `EnterWorktree({path})` (re-root)++Formally re-roots: sets the session's worktree home (tracked for exit) and its+cwd.++- **Gate:** a worktree of **the repo the current cwd resolves to**, by session+ state:+ - **Plain / first-entry session** → any worktree *registered to that repo*+ (`git worktree list`), anywhere on disk.+ - **Already in a worktree-session, or a pinned agent** → only under that+ repo's `.claude/worktrees/`; rejects even same-repo siblings.+ - **cwd outside any git repo** → refuses entirely.+- Rejections are graceful and side-effect-free (nothing is created), verbatim:+ - registered-check: `Cannot enter worktree: <path> is not a registered+ worktree of <repo>. Run 'git -C <repo> worktree list' …`+ - managed-location: `Cannot enter worktree: <path> is not under+ <repo>/.claude/worktrees. Switching from this session is limited to+ worktrees managed by Claude Code …`+ - no repo: `Cannot enter an existing worktree: the current directory is not in+ a git repository.`++The repo is read from the cwd, so `EnterWorktree` never moves you to a different+repo on its own — it re-roots within whatever repo you're already standing in.+To re-root into *another* repo, `cd` into it first, then `EnterWorktree`.+Verified: from a worktrunk session, `cd` into a prql worktree under `/tmp`, then+`EnterWorktree` re-rooted within prql.++### How they compose++Whether you can work in — or re-root into — a repo reduces to whether your cwd+can be there, which is `cd`'s gate:++| Target | cwd reachable? | Result |+|---|---|---|+| Same repo (incl. its sibling worktrees) | always | `EnterWorktree` re-roots directly |+| Another repo under a configured dir (`~/workspace`, `/tmp`) | yes | `cd` in → working there; from a plain session, `EnterWorktree` re-roots within it too |+| Another repo outside every configured dir | no | unreachable — add it (or a parent) to `additionalDirectories`, or `/add-dir` |+| Outside any repo | n/a | no re-root possible |++`additionalDirectories` is the one master gate: once a repo, or a parent like+`~/workspace`, is in it, the session can `cd` into that repo's worktrees and both+work there and re-root within them. This is load-bearing for the same-repo path+too: a sibling worktree is registered to the repo, so `EnterWorktree` from a+plain session re-roots into the sibling `wt` creates. The agent **cannot**+enlarge that set itself (`/add-dir` is user-typed; the only automatic add is a+narrow symlink-resolving-to-the-same-cwd fixup), so a repo reachable by neither+the cwd nor config is a genuine handback to the user.++### Why `--no-cd`++The Bash tool is not a bare shell: Claude Code replays the user's shell startup+from a snapshot, so a user who installed wt shell integration runs the `wt`+wrapper function inside the tool. wt then runs with integration active, and a+plain `wt switch` hands the wrapper a cd directive that moves the tool's cwd — a+second, untracked re-root racing `EnterWorktree`. `--no-cd` skips the directive,+so `EnterWorktree` stays the single re-root. Verified: without `--no-cd`,+`wt switch <branch>` moved the session and the new cwd persisted to the next+Bash call. Where the user never installed integration (a fresh shell, CI) the+wrapper is absent and wt cannot cd regardless, so `--no-cd` is load-bearing on an+integrated machine and a no-op elsewhere. Don't drop it.++### Why not `EnterWorktree({name})` + the WorktreeCreate hook++A worktree could also be created by `EnterWorktree({name})`, which the worktrunk+plugin routes through its `WorktreeCreate` hook. 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; it can't make one in another repo, which `wt -C` does+ trivially in step 1.+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 escalate instead of grinding through absolute paths++The original incident worked a cross-repo task via absolute paths from a session+rooted elsewhere: every `cd` into the worktree reset, so each command needed an+absolute prefix, and the session never gained the worktree cwd. It produced+correct output but read as a failure. File tools (absolute paths) and `git -C`+are cwd-independent, so the work is *possible* that way — but it is friction the+user shouldn't absorb when the fix is one line of config.++So when the worktree is unreachable, the skill escalates with the concrete fix+rather than degrading silently. This is not a predictive guard: the skill+doesn't refuse to create cross-repo and doesn't guess reachability. It creates,+attempts entry, and lets a single `cd` reveal reachability — the escalation+fires only on an actual reset. Cheap to attempt, and the handback is actionable+and durable (a `~/workspace` entry, set once, covers every future cross-repo+task).++## 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)++- `EnterWorktree` re-roots only within the repo the cwd is in, and the cwd can't+ `cd` outside the session's `additionalDirectories` (Claude Code restrictions,+ not skill gaps). So another repo is reachable only when it, or a parent like+ `~/workspace`, is in `additionalDirectories` — then the session `cd`s in and+ works there (and, from a plain session, can re-root within it). Otherwise the+ skill escalates for a one-line config add rather than degrading to+ absolute-paths mode. The agent can't enlarge the set itself (`/add-dir` is+ user-typed), so this handback is irreducible — but set once, it is permanent.+- A pinned or already-in-worktree session can't even re-enter a *same-repo*+ sibling worktree (the stricter `.claude/worktrees/` check); it lands in the+ same reachability test and the same escalation.+- `wt switch --create` is not idempotent. If that ever changes upstream+ (enter-if-exists), step 2's existing-branch retry collapses to nothing.diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rsindex 5ac5122f2..002a2d63e 100644--- a/tests/integration_tests/config_show.rs+++ b/tests/integration_tests/config_show.rs@@ -3888,10 +3888,20 @@ fn test_codex_plugin_metadata_is_valid_json() {.unwrap();assert_eq!(plugin["name"], "worktrunk");- assert_eq!(plugin["skills"], "./skills/");+ // No `skills` key: Codex scans <plugin-root>/skills/ by convention when+ // the manifest omits it, and an explicit "./skills/" names the same+ // directory (verified against codex-cli 0.144.1). The scanned tree is the+ // real-file mirror of repo-root skills/ — `codex plugin add` copies the+ // plugin into its cache with a copier that drops symlink entries, which+ // is why the mirror exists. See CLAUDE.md → "Plugin skills are a+ // generated mirror".+ assert!(+ plugin.get("skills").is_none(),+ "the Codex manifest must not carry a `skills` key — Codex scans skills/ by convention"+ );// Metadata must not drift back toward the Claude plugin: the Codex plugin- // ships only the configuration skill, and its URLs are the canonical site- // (not the `/claude-code/` doc slug).+ // is scoped to configuration guidance (no activity-tracking claims), and+ // its URLs are the canonical site (not the `/claude-code/` doc slug).for key in ["description", "homepage"] {let val = plugin[key].as_str().unwrap();assert!(@@ -3981,10 +3991,14 @@ fn test_codex_plugin_metadata_is_valid_json() {/// against the real CLIs: Claude (claude-cli 2.1.207) reads the manifest at/// `<plugin-root>/.claude-plugin/plugin.json` — the only location `claude/// plugin validate` accepts — and discovers components by convention: hooks-/// at `hooks/hooks.json`, skills by scanning `skills/*/SKILL.md` (the-/// installer dereferences the `skills` symlink into a real directory in the-/// install cache). A marketplace install of exactly this shape loads the-/// skills and fires the hooks with no component keys in the manifest. Gemini+/// at `hooks/hooks.json`, skills by scanning `skills/*/SKILL.md`. A+/// marketplace install of exactly this shape loads the skills and fires the+/// hooks with no component keys in the manifest. Codex (codex-cli 0.144.1)+/// also scans `skills/` by convention when the manifest omits the key, but+/// its installer's cache copy drops symlink entries — which is why the+/// plugin's `skills/` is a real-file mirror of the repo-root `skills/`,+/// generated by `test_docs_are_in_sync` (see plugins/worktrunk/CLAUDE.md+/// → "Plugin skills are a generated mirror"). Gemini/// (gemini-cli 0.42) resolves the extension at the repo root, so/// `${extensionPath}/skills/` is the real single-sourced repo-root `skills/`/// and its hooks call the canonical@@ -4106,22 +4120,40 @@ fn test_plugin_layout_is_consolidated() {"no bundled Gemini wt.sh — hooks reference the canonical worktrunk shim");- // Claude auto-discovers skills by scanning skills/ for <dir>/SKILL.md, so- // the invariants are structural: the plugin's skills/ is the symlink that- // single-sources the repo-root skills/ (checked on unix only — a Windows- // checkout without core.symlinks materializes it as a plain file), and- // every repo-root skill dir carries a SKILL.md, since the scan silently- // ignores a directory without one.- if cfg!(unix) {- let skills_link = root.join("plugins/worktrunk/skills");- assert!(- skills_link.is_symlink()- && dunce::canonicalize(&skills_link).unwrap()- == dunce::canonicalize(root.join("skills")).unwrap(),- "plugins/worktrunk/skills must be the symlink single-sourcing the \- repo-root skills/"- );+ // Claude and Codex auto-discover skills by scanning the plugin root's+ // skills/ for <dir>/SKILL.md. That tree is a real-file mirror of the+ // authored repo-root skills/, generated by test_docs_are_in_sync+ // (sync_plugin_skills_mirror): Codex's plugin installer copies the plugin+ // root with a copier that silently skips symlink entries, so a symlink+ // anywhere in the tree — the old top-level `skills -> ../../skills` or a+ // nested reference link — ships no content to Codex installs, and a+ // symlink also materializes as a plain text file on Windows checkouts.+ // Claude's installer dereferences symlinks, so real files serve it+ // equally. The invariant here is structural: regular files all the way+ // down.+ let plugin_skills = root.join("plugins/worktrunk/skills");+ assert!(+ plugin_skills.is_dir() && !plugin_skills.is_symlink(),+ "plugins/worktrunk/skills must be a real directory (mirror of repo-root skills/); \+ Codex's installer drops symlinks"+ );+ let mut dirs = vec![plugin_skills];+ while let Some(dir) = dirs.pop() {+ for entry in fs::read_dir(&dir).unwrap() {+ let entry = entry.unwrap();+ assert!(+ !entry.path().is_symlink(),+ "{} is a symlink — the plugin skills mirror must hold only regular files \+ (Codex's installer silently drops symlinks)",+ entry.path().display()+ );+ if entry.file_type().unwrap().is_dir() {+ dirs.push(entry.path());+ }+ }}+ // Every repo-root skill dir carries a SKILL.md, since the convention scan+ // silently ignores a directory without one.for entry in fs::read_dir(root.join("skills")).unwrap() {let entry = entry.unwrap();if entry.file_type().unwrap().is_dir() {diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rsindex 5d8d8de29..28455d6c5 100644--- a/tests/integration_tests/readme_sync.rs+++ b/tests/integration_tests/readme_sync.rs@@ -24,8 +24,9 @@ use crate::common::wt_command;use ansi_str::AnsiStr;use ansi_to_html::convert as ansi_to_html;use regex::Regex;+use std::collections::BTreeMap;use std::fs;-use std::path::Path;+use std::path::{Path, PathBuf};use std::sync::LazyLock;use worktrunk::docs::{MARKER_CLOSE, MARKER_OPEN_PREFIX};@@ -2204,6 +2205,87 @@ fn finalize_skill_content(content: &str) -> String {.join("\n")}+/// Mirror the repo-root `skills/` tree into `plugins/worktrunk/skills/` as+/// regular files, dereferencing symlinks, and delete mirror files whose+/// source is gone.+///+/// The mirror is what Claude and Codex installs ship. It must hold real files+/// only: Codex's plugin installer copies the plugin root with a copier that+/// silently skips symlink entries (`copy_dir_recursive` in codex-rs+/// core-plugins), so a symlink anywhere in the tree — a `skills` link at the+/// top or a nested one like `reference/README.md` — ships no content, and a+/// symlink also materializes as a plain text file on Windows checkouts.+/// Repo-root `skills/` stays the authored home: Gemini reads it directly, and+/// the earlier sync stages write into it.+fn sync_plugin_skills_mirror(project_root: &Path) -> (Vec<String>, Vec<String>) {+ let mut errors = Vec::new();+ let mut updated_files = Vec::new();++ let source_root = project_root.join("skills");+ let mirror_root = project_root.join("plugins/worktrunk/skills");++ // `is_dir` and `read` follow symlinks, so linked source content lands in+ // the collected map — and therefore in the mirror — as regular file bytes.+ fn collect_files(+ root: &Path,+ dir: &Path,+ files: &mut BTreeMap<PathBuf, Vec<u8>>,+ ) -> std::io::Result<()> {+ for entry in fs::read_dir(dir)? {+ let path = entry?.path();+ if path.is_dir() {+ collect_files(root, &path, files)?;+ } else {+ let rel = path.strip_prefix(root).unwrap().to_path_buf();+ files.insert(rel, fs::read(&path)?);+ }+ }+ Ok(())+ }++ let mut source_files = BTreeMap::new();+ if let Err(e) = collect_files(&source_root, &source_root, &mut source_files) {+ errors.push(format!("walk {}: {e}", source_root.display()));+ return (errors, updated_files);+ }+ let mut mirror_files = BTreeMap::new();+ if mirror_root.exists()+ && let Err(e) = collect_files(&mirror_root, &mirror_root, &mut mirror_files)+ {+ errors.push(format!("walk {}: {e}", mirror_root.display()));+ return (errors, updated_files);+ }++ for (rel, content) in &source_files {+ if mirror_files+ .get(rel)+ .is_none_or(|mirrored| mirrored != content)+ {+ let dst = mirror_root.join(rel);+ if let Some(parent) = dst.parent() {+ fs::create_dir_all(parent)+ .unwrap_or_else(|e| panic!("Failed to create {}: {}", parent.display(), e));+ }+ fs::write(&dst, content)+ .unwrap_or_else(|e| panic!("Failed to write {}: {}", dst.display(), e));+ updated_files.push(format!("plugins/worktrunk/skills/{}", rel.display()));+ }+ }+ for rel in mirror_files.keys() {+ if !source_files.contains_key(rel) {+ let stale = mirror_root.join(rel);+ fs::remove_file(&stale)+ .unwrap_or_else(|e| panic!("Failed to remove {}: {}", stale.display(), e));+ updated_files.push(format!(+ "plugins/worktrunk/skills/{} (removed)",+ rel.display()+ ));+ }+ }++ (errors, updated_files)+}+/// Sync .well-known/agent-skills/ index.json and verify symlink.////// The skill files are served via a symlink:@@ -2615,6 +2697,11 @@ fn test_docs_are_in_sync() {let (skill_errors, skill_files) = sync_skill_files(project_root);tag("skill files", skill_errors, skill_files);+ // Step 3b: Mirror the now-fresh skills/ into plugins/worktrunk/skills/+ // (real files for the plugin payload — Codex's installer drops symlinks)+ let (mirror_errors, mirror_files) = sync_plugin_skills_mirror(project_root);+ tag("plugin skills mirror", mirror_errors, mirror_files);+// Step 4: Sync .well-known/agent-skills/ (skills/ → docs/static/)let (well_known_errors, well_known_files) = sync_well_known_skills(project_root);tag(".well-known", well_known_errors, well_known_files);