Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: reorder CLI commands by usage frequency (#434)
Maximilian Roosd4be5ee197ef
diff --git a/src/cli.rs b/src/cli.rsindex b5f2e3c6c..86c862ea4 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -1247,1435 +1247,1434 @@ pub enum ListSubcommand {#[derive(Subcommand)]pub enum Commands {- /// Manage configuration and shell integration+ /// Switch to a worktree#[command(- about = "Manage configuration and shell integration",- after_long_help = r#"Manages configuration, shell integration, and runtime settings.--Worktrunk uses two configuration files:+ after_long_help = r#"Change directory to a worktree, creating one if needed.+<!-- demo: wt-switch.gif 1600x900 -->-| File | Location | Purpose |-|------|----------|---------|-| **User config** | `~/.config/worktrunk/config.toml` | Personal settings, command defaults, approved project commands |-| **Project config** | `.config/wt.toml` | Lifecycle hooks, checked into version control |+Worktrees are addressed by branch name; paths are computed from a template. Unlike `git switch`, this navigates between worktrees rather than changing branches in place.## Examples-Install shell integration (required for directory switching):-```console-wt config shell install+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```-Create user config file with documented examples:+## Creating a branch-```console-wt config create-```+The `--create` flag creates a new branch from the `--base` branch (defaults to default branch). Without `--create`, the branch must already exist.-Create project config file (`.config/wt.toml`) for hooks:+## Creating worktrees-```console-wt config create --project-```+If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one, running [hooks](@/hook.md).-Show current configuration and file locations:+When creating a worktree, worktrunk:++1. Creates worktree at configured path+2. Switches to new directory+3. Runs [post-create hooks](@/hook.md#post-create) (blocking)+4. Spawns [post-start hooks](@/hook.md#post-start) (background)```console-wt config show+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-verify # Skip hooks```-## User config--The user config stores personal preferences that apply across all repositories. Create it with `wt config create` and view with `wt config show`.+## Shortcuts-### Worktree path template+| Shortcut | Meaning |+|----------|---------|+| `^` | Default branch (main/master) |+| `@` | Current branch/worktree |+| `-` | Previous worktree (like `cd -`) |-Controls where new worktrees are created. The template is relative to the repository root.+```console+wt switch - # Back to previous+wt switch ^ # Default branch worktree+wt switch --create fix --base=@ # Branch from current HEAD+```-**Available variables:**-- `{{ repo }}` — repository directory name-- `{{ branch }}` — raw branch name (e.g., `feature/auth`)-- `{{ branch | sanitize }}` — branch name with `/` and `\` replaced by `-`+## When wt switch fails-**Examples** for a repo at `~/code/myproject` creating branch `feature/login`:+- **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-```toml-# Default — siblings in parent directory-# Creates: ~/code/myproject.feature-login-worktree-path = "../{{ repo }}.{{ branch | sanitize }}"+To change which branch a worktree is on, use `git switch` inside that worktree.-# Inside the repository-# Creates: ~/code/myproject/.worktrees/feature-login-worktree-path = ".worktrees/{{ branch | sanitize }}"+## See also-# Namespaced (useful when multiple repos share a parent directory)-# Creates: ~/code/worktrees/myproject/feature-login-worktree-path = "../worktrees/{{ repo }}/{{ branch | sanitize }}"+- [wt select](@/select.md) — Interactive worktree selection+- [wt list](@/list.md) — View all worktrees+- [wt remove](@/remove.md) — Delete worktrees when done+- [wt merge](@/merge.md) — Integrate changes back to the default branch+"#+ )]+ Switch {+ /// Branch name+ ///+ /// Shortcuts: '^' (default branch), '-' (previous), '@' (current)+ #[arg(add = crate::completion::worktree_branch_completer())]+ branch: String,-# Nested bare repo (git clone --bare <url> project/.git)-# Creates: ~/code/project/feature-login (sibling to .git)-worktree-path = "../{{ branch | sanitize }}"-```+ /// Create a new branch+ #[arg(short = 'c', long)]+ create: bool,-### Command settings+ /// Base branch+ ///+ /// Defaults to default branch.+ #[arg(short = 'b', long, add = crate::completion::branch_value_completer())]+ base: Option<String>,-Set persistent flag values for commands. These apply unless explicitly overridden on the command line.+ /// 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.+ ///+ /// Especially useful with shell aliases:+ ///+ /// ```sh+ /// 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.+ #[arg(short = 'x', long)]+ execute: Option<String>,-**`wt list`:**+ /// Additional arguments for --execute command (after --)+ ///+ /// Arguments after `--` are appended to the execute command.+ /// Each argument is POSIX shell-escaped before appending.+ #[arg(last = true, requires = "execute")]+ execute_args: Vec<String>,-```toml-[list]-# All off by default-full = true # --full-branches = true # --branches-remotes = true # --remotes-```+ /// Skip approval prompts+ #[arg(short, long)]+ yes: bool,-**`wt step commit` and `wt merge` staging:**+ /// Remove stale paths at target+ #[arg(long)]+ clobber: bool,-```toml-[commit]-stage = "all" # "all" (default), "tracked", or "none"-```+ /// Skip hooks+ #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]+ verify: bool,+ },-**`wt merge`:**+ /// List worktrees and their status+ #[command(+ after_long_help = r#"Show all worktrees with their status. The table includes uncommitted changes, divergence from the default branch and remote, and optional CI status.+<!-- demo: wt-list.gif 1600x900 -->-```toml-[merge]-# These flags are on by default; set to false to disable-squash = false # Preserve individual commits (--no-squash)-commit = false # Skip committing uncommitted changes (also disables squash)-rebase = false # Skip rebase (fails if not already rebased)-remove = false # Keep worktree after merge (--no-remove)-verify = false # Skip hooks (--no-verify)-```+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. With `--full`, CI status fetches from the network — the table displays instantly and CI fills in as results arrive.-### LLM commit messages+## Examples-Configure automatic commit message generation. Requires an external tool like [llm](https://llm.datasette.io/):+List all worktrees:-```toml-[commit-generation]-command = "llm"-args = ["-m", "claude-haiku-4.5"]+<!-- wt list -->+```console+$ wt list```-See [LLM Commit Messages](@/llm-commits.md) for setup details and template customization.--### Approved commands--When project hooks run for the first time, Worktrunk prompts for approval. Approved commands are saved here automatically:+Include CI status and line diffs:-```toml-[projects."my-project"]-approved-commands = ["npm ci", "npm test"]+<!-- wt list --full -->+```console+$ wt list --full```-Manage approvals with `wt hook approvals add` to review and pre-approve commands, and `wt hook approvals clear` to reset (add `--global` to clear all projects).--### User hooks+Include branches that don't have worktrees:-Personal hooks that run for all repositories. Use the same syntax as project hooks:+<!-- wt list --branches --full -->+```console+$ wt list --branches --full+```-```toml-[post-create]-setup = "echo 'Setting up worktree...'"+Output as JSON for scripting:-[pre-merge]-notify = "notify-send 'Merging {{ branch }}'"+```console+$ wt list --format=json```-User hooks run before project hooks and don't require approval. Skip with `--no-verify`.--See [wt hook](@/hook.md#user-hooks) for complete documentation.+## Columns-## Project config+| 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 with the default branch (`--full`) |+| Path | Worktree directory |+| Remote⇅ | Commits ahead/behind tracking branch |+| URL | Dev server URL from project config (dimmed if port not listening) |+| CI | Pipeline status (`--full`) |+| Commit | Short hash (8 chars) |+| Age | Time since last commit |+| Message | Last commit message (truncated) |-The project config defines lifecycle hooks and project-specific settings. This file is checked into version control and shared across the team.+Note: `main↕` and `main…±` refer to the default branch (header label stays `main` for compactness). `main…±` uses a merge-base (three-dot) diff.-Create `.config/wt.toml` in the repository root:+### CI status-```toml-[post-create]-install = "npm ci"+The CI column shows GitHub/GitLab pipeline status:-[pre-merge]-test = "npm test"-lint = "npm run lint"-```+| Indicator | Meaning |+|-----------|---------|+| `●` green | All checks passed |+| `●` blue | Checks running |+| `●` red | Checks failed |+| `●` yellow | Merge conflicts with base |+| `●` gray | No checks configured |+| `⚠` yellow | Fetch error (rate limit, network) |+| (blank) | No upstream or no PR/MR |-See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).+CI indicators are clickable links to the PR or pipeline page. Any CI dot appears dimmed when there are unpushed local changes (stale status). PRs/MRs are checked first, then branch workflows/pipelines for branches with an upstream. Local-only branches show blank. Results are cached for 30-60 seconds; use `wt config state` to view or clear.-### Dev server URL+## Status symbols-The `[list]` section adds a URL column to `wt list`:+The Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):-```toml-[list]-url = "http://localhost:{{ branch | hash_port }}"-```+| Subcolumn | Symbol | Meaning |+|-----------|--------|---------|+| Working tree (1) | `+` | Staged files |+| Working tree (2) | `!` | Modified files (unstaged) |+| Working tree (3) | `?` | Untracked files |+| Worktree | `✘` | Merge conflicts |+| | `⤴` | Rebase in progress |+| | `⤵` | Merge in progress |+| | `/` | Branch without worktree |+| | `⚑` | Branch-worktree mismatch (branch name doesn't match worktree path) |+| | `⊟` | Prunable (directory missing) |+| | `⊞` | Locked worktree |+| Default branch | `^` | Is the default branch |+| | `✗` | Would conflict if merged to the default branch (with `--full`, includes uncommitted changes) |+| | `_` | Same commit as the default branch, clean |+| | `–` | Same commit as the default branch, uncommitted changes |+| | `⊂` | Content [integrated](@/remove.md#branch-cleanup) into the default branch or target |+| | `↕` | Diverged from the default branch |+| | `↑` | Ahead of the default branch |+| | `↓` | Behind the default branch |+| Remote | `\|` | In sync with remote |+| | `⇅` | Diverged from remote |+| | `⇡` | Ahead of remote |+| | `⇣` | Behind remote |-URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).+Rows are dimmed when [safe to delete](@/remove.md#branch-cleanup) (`_` same commit with clean working tree or `⊂` content integrated).-## Shell integration+## JSON output-Worktrunk needs shell integration to change directories when switching worktrees. Install with:+Query structured data with `--format=json`:```console-wt config shell install-```+# Worktrees with merge conflicts+wt list --format=json | jq '.[] | select(.operation_state == "conflicts")'-Or manually add to the shell config:+# Uncommitted changes+wt list --format=json | jq '.[] | select(.working_tree.modified)'-```console-# For bash: add to ~/.bashrc-eval "$(wt config shell init bash)"+# Current worktree+wt list --format=json | jq '.[] | select(.is_current)'-# For zsh: add to ~/.zshrc-eval "$(wt config shell init zsh)"+# Branches ahead of the default branch+wt list --format=json | jq '.[] | select(.main.ahead > 0)'-# For fish: add to ~/.config/fish/config.fish-wt config shell init fish | source+# Integrated branches (ready to clean up)+wt list --format=json | jq '.[] | select(.main_state == "integrated" or .main_state == "empty")'```-Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.+**Fields:**-## Environment variables+| 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"` (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, absent when no CI) |+| `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) |+| `statusline` | string | Pre-formatted status with ANSI colors |+| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |-All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.+### commit object-### Naming convention+| Field | Type | Description |+|-------|------|-------------|+| `sha` | string | Full commit SHA (40 chars) |+| `short_sha` | string | Short commit SHA (7 chars) |+| `message` | string | Commit message (first line) |+| `timestamp` | number | Unix timestamp |-Config keys use kebab-case (`worktree-path`), while env vars use SCREAMING_SNAKE_CASE (`WORKTRUNK_WORKTREE_PATH`). The conversion happens automatically.+### working_tree object-For nested config sections, use double underscores to separate levels:+| 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}` |+| `diff_vs_main` | object | Lines changed vs the default branch: `{added, deleted}` |-| Config | Environment Variable |-|--------|---------------------|-| `worktree-path` | `WORKTRUNK_WORKTREE_PATH` |-| `commit-generation.command` | `WORKTRUNK_COMMIT_GENERATION__COMMAND` |-| `commit-generation.args` | `WORKTRUNK_COMMIT_GENERATION__ARGS` |+### main object-Note the single underscore after `WORKTRUNK` and double underscores between nested keys.+| 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}` |-### Array values+### remote object-Array config values like `args = ["-m", "claude-haiku"]` can be specified as a single string in environment variables:+| 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 |-```console-export WORKTRUNK_COMMIT_GENERATION__ARGS="-m claude-haiku"-```+### worktree object-### Example: CI/testing override+| Field | Type | Description |+|-------|------|-------------|+| `state` | string | `"branch_worktree_mismatch"`, `"prunable"`, `"locked"` (absent when normal) |+| `reason` | string | Reason for locked/prunable state |+| `detached` | boolean | HEAD is detached |-Override the LLM command in CI to use a mock:+### ci object-```console-WORKTRUNK_COMMIT_GENERATION__COMMAND=echo \-WORKTRUNK_COMMIT_GENERATION__ARGS="test: automated commit" \- wt merge-```+| Field | Type | Description |+|-------|------|-------------|+| `status` | string | CI status (see below) |+| `source` | string | `"pr"` (PR/MR) or `"branch"` (branch workflow) |+| `stale` | boolean | Local HEAD differs from remote (unpushed changes) |+| `url` | string | URL to the PR/MR page |-### Other environment variables+### main_state values-| Variable | Purpose |-|----------|---------|-| `WORKTRUNK_BIN` | Override binary path for shell wrappers (useful for testing dev builds) |-| `WORKTRUNK_CONFIG_PATH` | Override user config file location |-| `WORKTRUNK_DIRECTIVE_FILE` | Internal: set by shell wrappers to enable directory changes |-| `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 resource limits. |-| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |-| `CLICOLOR_FORCE` | Force colored output even when not a TTY |+These values describe relation to the default branch.-<!-- subdoc: create -->+`"is_main"` `"would_conflict"` `"empty"` `"same_commit"` `"integrated"` `"diverged"` `"ahead"` `"behind"`-<!-- subdoc: show -->+### integration_reason values-<!-- subdoc: state -->+When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"`++### ci.status values++`"passed"` `"running"` `"failed"` `"conflicts"` `"no-ci"` `"error"`++Missing a field that would be generally useful? Open an issue at https://github.com/max-sixty/worktrunk.++## See also++- [wt select](@/select.md) — Interactive worktree picker with live preview"#)]- Config {+ // TODO: `args_conflicts_with_subcommands` causes confusing errors for unknown+ // subcommands ("cannot be used with --branches") instead of "unknown subcommand".+ // Could fix with external_subcommand + post-parse validation, but not worth the+ // code. The `statusline` subcommand may move elsewhere anyway.+ #[command(args_conflicts_with_subcommands = true)]+ List {#[command(subcommand)]- action: ConfigCommand,+ subcommand: Option<ListSubcommand>,++ /// Output format (table, json)+ #[arg(long, value_enum, default_value = "table", hide_possible_values = true)]+ format: OutputFormat,++ /// Include branches without worktrees+ #[arg(long)]+ branches: bool,++ /// Include remote branches+ #[arg(long)]+ remotes: bool,++ /// Include CI status and diff analysis (slower)+ #[arg(long)]+ full: bool,++ /// 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. Auto-enabled for TTY.+ #[arg(long, overrides_with = "no_progressive")]+ progressive: bool,++ /// Force buffered rendering+ #[arg(long = "no-progressive", overrides_with = "progressive", hide = true)]+ no_progressive: bool,},- /// Run individual operations+ /// Remove worktree; delete branch if merged#[command(- name = "step",- after_long_help = r#"Run individual git workflow operations: commits, squashes, rebases, and pushes.+ after_long_help = r#"Removes worktrees and their branches (if merged), returning to the main worktree. Defaults to removing the current worktree.## Examples-Commit with LLM-generated message:+Remove current worktree:```console-wt step commit+wt remove```-Manual merge workflow with review between steps:+Remove specific worktrees:```console-wt step commit-wt step squash-# Review the squashed commit-wt step rebase-wt step push+wt remove feature-branch+wt remove old-feature another-branch```-## Operations+Keep the branch:-- `commit` — Stage and commit with [LLM-generated message](@/llm-commits.md)-- `squash` — Squash all branch commits into one with [LLM-generated message](@/llm-commits.md)-- `rebase` — Rebase onto target branch-- `push` — Fast-forward target to current branch-- `for-each` — [experimental] Run a command in every worktree+```console+wt remove --no-delete-branch feature-branch+```-## See also+Force-delete an unmerged branch:-- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically-- [wt hook](@/hook.md) — Run configured hooks+```console+wt remove -D experimental+```-<!-- subdoc: for-each -->-"#- )]- Step {- #[command(subcommand)]- action: StepCommand,- },+## Branch cleanup- /// Run configured hooks- #[command(- name = "hook",- after_long_help = r#"Shell commands that run at key points in the worktree lifecycle.+By default, branches are deleted when merging them would add nothing. This works with squash-merge and rebase workflows where commit history differs but file changes match.-Hooks run automatically during `wt switch`, `wt merge`, & `wt remove`. `wt hook <type>` runs them on demand. Both user hooks (from `~/.config/worktrunk/config.toml`) and project hooks (from `.config/wt.toml`) are supported.--## Hook types+Worktrunk checks five conditions (in order of cost):-| Hook | When | Blocking | Fail-fast |-|------|------|----------|-----------|-| `post-create` | After worktree created | Yes | No |-| `post-start` | After worktree created | No (background) | No |-| `post-switch` | After every switch | No (background) | No |-| `pre-commit` | Before commit during merge | Yes | Yes |-| `pre-merge` | Before merging to target | Yes | Yes |-| `post-merge` | After successful merge | Yes | No |-| `pre-remove` | Before worktree removed | Yes | Yes |+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. Shows `⊂`.-**Blocking**: Command waits for hook to complete before continuing.-**Fail-fast**: First failure aborts the operation.+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.-### post-create+Branches showing `_` or `⊂` are dimmed as safe to delete.-Runs after worktree creation, **blocks until complete**. The worktree switch doesn't finish until these commands succeed.+Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.-**Use cases**: Installing dependencies, database migrations, copying environment files.+## Background removal-```toml-[post-create]-install = "npm ci"-migrate = "npm run db:migrate"-env = "cp .env.example .env"-```+Removal runs in the background by default (returns immediately). Logs are written to `.git/wt-logs/{branch}-remove.log`. Use `--no-background` to run in the foreground.-### post-start+## Shortcuts-Runs after worktree creation, **in background**. The worktree switch completes immediately; these run in parallel.+`@` (current), `-` (previous), `^` (default branch). See [wt switch](@/switch.md#shortcuts).-**Use cases**: Long builds, dev servers, file watchers, downloading large assets.+## See also-```toml-[post-start]-build = "npm run build"-server = "npm run dev"-```+- [wt merge](@/merge.md) — Remove worktree after merging+- [wt list](@/list.md) — View all worktrees+"#+ )]+ Remove {+ /// Branch name [default: current]+ #[arg(add = crate::completion::local_branches_completer())]+ branches: Vec<String>,-Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log` (source is `user` or `project`).+ /// Keep branch after removal+ #[arg(long = "no-delete-branch", action = clap::ArgAction::SetFalse, default_value_t = true)]+ delete_branch: bool,-### post-switch+ /// Delete unmerged branches+ #[arg(short = 'D', long = "force-delete")]+ force_delete: bool,-Runs after **every** switch operation, **in background**. Triggers on all switch results: creating new worktrees, switching to existing ones, or switching to the current worktree.+ /// Run removal in foreground+ #[arg(long = "no-background", action = clap::ArgAction::SetFalse, default_value_t = true)]+ background: bool,-**Use cases**: Renaming terminal tabs, updating tmux window names, IDE notifications.+ /// Skip hooks+ #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]+ verify: bool,-```toml-post-switch = "echo 'Switched to {{ branch }}'"-```+ /// Skip approval prompts+ #[arg(short, long)]+ yes: bool,-Output logged to `.git/wt-logs/{branch}-{source}-post-switch-{name}.log` (source is `user` or `project`).+ /// Force worktree removal+ ///+ /// Remove worktrees even if they contain untracked files (like build+ /// artifacts). Without this flag, removal fails if untracked files exist.+ #[arg(short, long)]+ force: bool,+ },-### pre-commit+ /// Merge worktree into target branch+ ///+ /// Squash & rebase, fast-forward target, remove the worktree.+ #[command(+ after_long_help = r#"Merge the current branch into the default branch — like clicking "Merge pull request" on GitHub.+<!-- demo: wt-merge.gif 1600x900 -->-Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.+## Examples-**Use cases**: Formatters, linters, type checking.+Merge to the default branch:-```toml-[pre-commit]-format = "cargo fmt -- --check"-lint = "cargo clippy -- -D warnings"+```console+wt merge```-### pre-merge+Merge to a different branch:-Runs before merging to target branch, **fail-fast**. All commands must exit 0 for the merge to proceed.+```console+wt merge develop+```-**Use cases**: Tests, security scans, build verification.+Keep the worktree after merging:-```toml-[pre-merge]-test = "cargo test"-build = "cargo build --release"+```console+wt merge --no-remove```-### post-merge+Preserve commit history (no squash):-Runs after successful merge in the **worktree for the target branch** if it exists, otherwise the **main worktree**, **best-effort**. Failures are logged but don't abort.+```console+wt merge --no-squash+```-**Use cases**: Deployment, notifications, installing updated binaries.+Skip committing/squashing (rebase still runs unless --no-rebase):-```toml-post-merge = "cargo install --path ."+```console+wt merge --no-commit```-### pre-remove--Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit 0 for removal to proceed.+## Pipeline-**Use cases**: Cleanup tasks, saving state, notifying external systems.+`wt merge` runs these steps:-```toml-[pre-remove]-cleanup = "rm -rf /tmp/cache/{{ branch }}"-```+1. **Squash** — Stages uncommitted changes, then 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`, uncommitted changes become a separate commit and individual commits are preserved.+2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [wt hook](@/hook.md).+4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.+5. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.+6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the main worktree, the worktree is preserved.+7. **Post-merge hooks** — Hooks run after cleanup. Failures are logged but don't abort.-### Timing during merge+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`. Requires a clean working tree.-- **pre-commit** — After staging, before squash commit-- **pre-merge** — After rebase, before merge to target-- **pre-remove** — Before removing worktree during cleanup-- **post-merge** — After cleanup completes+## Local CI-See [wt merge](@/merge.md#pipeline) for the complete pipeline.+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.-## Configuration+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.-Hooks are defined in `.config/wt.toml`. They can be a single command or multiple named commands:+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-# Single command (string)-post-create = "npm install"--# Multiple commands (table) — run sequentially in declaration order[pre-merge]test = "cargo test"-build = "cargo build --release"+lint = "cargo clippy"```-### Template variables+## See also-Hooks can use template variables that expand at runtime:+- [wt step](@/step.md) — Run individual operations (commit, squash, rebase, push)+- [wt remove](@/remove.md) — Remove worktrees without merging+- [wt switch](@/switch.md) — Navigate to other worktrees+"#+ )]+ Merge {+ /// Target branch+ ///+ /// Defaults to default branch.+ #[arg(add = crate::completion::branch_value_completer())]+ target: Option<String>,-| Variable | Example | Description |-|----------|---------|-------------|-| `{{ repo }}` | myproject | Repository directory name |-| `{{ repo_path }}` | /path/to/myproject | Absolute path to repository root |-| `{{ branch }}` | feature/auth | Branch name |-| `{{ worktree_name }}` | myproject.feature-auth | Worktree directory name |-| `{{ worktree_path }}` | /path/to/myproject.feature-auth | Absolute worktree path |-| `{{ main_worktree_path }}` | /path/to/myproject | Default branch worktree |-| `{{ default_branch }}` | main | Default branch name |-| `{{ commit }}` | a1b2c3d4e5f6... | Full HEAD commit SHA |-| `{{ short_commit }}` | a1b2c3d | Short HEAD commit SHA |-| `{{ remote }}` | origin | Primary remote name |-| `{{ remote_url }}` | [email protected]:user/repo.git | Remote URL |-| `{{ upstream }}` | origin/feature | Upstream tracking branch |-| `{{ target }}` | main | Target branch (merge hooks only) |+ /// Force commit squashing+ #[arg(long, overrides_with = "no_squash", hide = true)]+ squash: bool,-See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.+ /// Skip commit squashing+ #[arg(long = "no-squash", overrides_with = "squash")]+ no_squash: bool,-**Deprecated:** `repo_root` (use `repo_path`), `worktree` (use `worktree_path`), `main_worktree` (use `repo`). These still work but emit warnings.+ /// Force commit and squash+ #[arg(long, overrides_with = "no_commit", hide = true)]+ commit: bool,-### Filters+ /// Skip commit and squash+ #[arg(long = "no-commit", overrides_with = "commit")]+ no_commit: bool,-Templates support Jinja2 filters for transforming values:+ /// Force rebasing onto target+ #[arg(long, overrides_with = "no_rebase", hide = true)]+ rebase: bool,-| Filter | Example | Description |-|--------|---------|-------------|-| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |-| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |+ /// Skip rebase (fail if not already rebased)+ #[arg(long = "no-rebase", overrides_with = "rebase")]+ no_rebase: bool,-The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:+ /// Force worktree removal after merge+ #[arg(long, overrides_with = "no_remove", hide = true)]+ remove: bool,-```toml-[post-start]-dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"-```+ /// Keep worktree after merge+ #[arg(long = "no-remove", overrides_with = "remove")]+ no_remove: bool,-Hash any string, including concatenations:+ /// Force running hooks+ #[arg(long, overrides_with = "no_verify", hide = true)]+ verify: bool,-```toml-# Unique port per repo+branch combination-dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"-```+ /// Skip hooks+ #[arg(long = "no-verify", overrides_with = "verify")]+ no_verify: bool,-### JSON context+ /// Skip approval prompts+ #[arg(short, long)]+ yes: bool,-Hooks also receive context as JSON on stdin, enabling hooks in any language:+ /// What to stage before committing [default: all]+ #[arg(long)]+ stage: Option<crate::commands::commit::StageMode>,+ },+ /// Interactive worktree selector+ ///+ /// Browse and switch worktrees with live preview.+ #[cfg_attr(not(unix), command(hide = true))]+ #[command(+ after_long_help = r#"Interactive worktree picker with live preview. Navigate worktrees with keyboard shortcuts and press Enter to switch.+<!-- demo: wt-select.gif 1600x800 -->-```python-import json, sys-ctx = json.load(sys.stdin)-print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")-```+## Examples-The JSON includes all template variables plus `hook_type` and `hook_name`.+Open the selector:-## Designing effective hooks+```console+wt select+```-### post-create vs post-start+## Preview tabs-Both run when creating a worktree. The difference:+Toggle between views with number keys:-| Hook | Execution | Best for |-|------|-----------|----------|-| `post-create` | Blocks until complete | Tasks the developer needs before working (dependency install) |-| `post-start` | Background, parallel | Long-running tasks that can finish while you work |+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-Many tasks work well in `post-start` — they'll likely be ready by the time you need them, especially when the fallback is recompiling. If unsure, prefer `post-start` for faster worktree creation.+## Keybindings-### Copying untracked files+| Key | Action |+|-----|--------|+| `↑`/`↓` | Navigate worktree list |+| `Enter` | Switch to selected worktree |+| `Esc` | Cancel |+| (type) | Filter worktrees |+| `1`/`2`/`3` | Switch preview tab |+| `Alt-p` | Toggle preview panel |+| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |-Git worktrees share the repository but not untracked files. Common files to copy or link:+Branches without worktrees are included — selecting one creates a worktree. (`wt list` requires `--branches` to show them.)-- **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)+## See also-Three strategies:+- [wt list](@/list.md) — Static table view with all worktree metadata+- [wt switch](@/switch.md) — Direct switching to a known target branch+"#+ )]+ Select,-| Strategy | Speed | Disk | State |-|----------|-------|------|-------|-| **Symlink** | Instant | Shared | Shared (changes affect all worktrees) |-| **Copy** | Slow | Full duplicate | Isolated |-| **Copy-on-write** | Instant | Shared until modified | Isolated |+ /// Run individual operations+ #[command(+ name = "step",+ after_long_help = r#"Run individual git workflow operations: commits, squashes, rebases, and pushes.-### Copy-on-write for disk efficiency+## Examples-Copy-on-write (CoW) creates instant clones that share disk space until modified. Perfect for large directories.+Commit with LLM-generated message:-| OS | Filesystem | Command |-|----|------------|---------|-| macOS | APFS | `cp -c` |-| Linux | Btrfs, XFS | `cp --reflink=auto` |-| Windows | ReFS | No shell equivalent (requires API) |+```console+wt step commit+```-Cross-platform pattern that auto-detects and falls back gracefully:+Manual merge workflow with review between steps:-```toml-[post-create]-deps = """-if cp -c /dev/null /dev/null 2>/dev/null; then- cp -c -r {{ main_worktree_path }}/node_modules .-elif cp --reflink=auto /dev/null /dev/null 2>/dev/null; then- cp --reflink=auto -r {{ main_worktree_path }}/node_modules .-else- cp -r {{ main_worktree_path }}/node_modules .-fi-"""+```console+wt step commit+wt step squash+# Review the squashed commit+wt step rebase+wt step push```-### Dev servers+## Operations-Run a dev server per worktree on a deterministic port using `hash_port`:+- `commit` — Stage and commit with [LLM-generated message](@/llm-commits.md)+- `squash` — Squash all branch commits into one with [LLM-generated message](@/llm-commits.md)+- `rebase` — Rebase onto target branch+- `push` — Fast-forward target to current branch+- `for-each` — [experimental] Run a command in every worktree-```toml-[post-start]-server = "npm run dev -- --port {{ branch | hash_port }}"-```+## See also-The port is stable across machines and restarts — `feature-api` always gets the same port. Show it in `wt list`:+- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically+- [wt hook](@/hook.md) — Run configured hooks-```toml-[list]-url = "http://localhost:{{ branch | hash_port }}"-```+<!-- subdoc: for-each -->+"#+ )]+ Step {+ #[command(subcommand)]+ action: StepCommand,+ },-For subdomain-based routing (useful for cookies/CORS), use `lvh.me` which resolves to 127.0.0.1:+ /// Run configured hooks+ #[command(+ name = "hook",+ after_long_help = r#"Shell commands that run at key points in the worktree lifecycle.-```toml-[post-start]-server = "npm run dev -- --host {{ branch | sanitize }}.lvh.me --port {{ branch | hash_port }}"-```+Hooks run automatically during `wt switch`, `wt merge`, & `wt remove`. `wt hook <type>` runs them on demand. Both user hooks (from `~/.config/worktrunk/config.toml`) and project hooks (from `.config/wt.toml`) are supported.-### Databases+## Hook types-Each worktree can have its own database. Docker containers get unique names and ports:+| Hook | When | Blocking | Fail-fast |+|------|------|----------|-----------|+| `post-create` | After worktree created | Yes | No |+| `post-start` | After worktree created | No (background) | No |+| `post-switch` | After every switch | No (background) | No |+| `pre-commit` | Before commit during merge | Yes | Yes |+| `pre-merge` | Before merging to target | Yes | Yes |+| `post-merge` | After successful merge | Yes | No |+| `pre-remove` | Before worktree removed | Yes | Yes |-```toml-[post-start]-db = """-docker run -d --rm \- --name {{ repo }}-{{ branch | sanitize }}-postgres \- -p {{ ('db-' ~ branch) | hash_port }}:5432 \- -e POSTGRES_DB={{ repo }} \- -e POSTGRES_PASSWORD=dev \- postgres:16-"""+**Blocking**: Command waits for hook to complete before continuing.+**Fail-fast**: First failure aborts the operation.-[pre-remove]-db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"-```+### post-create-The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.-Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.+Runs after worktree creation, **blocks until complete**. The worktree switch doesn't finish until these commands succeed.-Generate `.env.local` with the connection string:+**Use cases**: Installing dependencies, database migrations, copying environment files.```toml[post-create]-env = """-cat > .env.local << EOF-DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}-DEV_PORT={{ branch | hash_port }}-EOF-"""+install = "npm ci"+migrate = "npm run db:migrate"+env = "cp .env.example .env"```-## Security+### post-start-Project commands require approval on first run:+Runs after worktree creation, **in background**. The worktree switch completes immediately; these run in parallel.++**Use cases**: Long builds, dev servers, file watchers, downloading large assets.+```toml+[post-start]+build = "npm run build"+server = "npm run dev"```-▲ repo needs approval to execute 3 commands:-○ post-create install:- echo 'Installing dependencies...'+Output logged to `.git/wt-logs/{branch}-{source}-post-start-{name}.log` (source is `user` or `project`).-❯ Allow and remember? [y/N]+### post-switch++Runs after **every** switch operation, **in background**. Triggers on all switch results: creating new worktrees, switching to existing ones, or switching to the current worktree.++**Use cases**: Renaming terminal tabs, updating tmux window names, IDE notifications.++```toml+post-switch = "echo 'Switched to {{ branch }}'"```-- Approvals are saved to user config (`~/.config/worktrunk/config.toml`)-- If a command changes, new approval is required-- Use `--yes` to bypass prompts (useful for CI/automation)-- Use `--no-verify` to skip hooks+Output logged to `.git/wt-logs/{branch}-{source}-post-switch-{name}.log` (source is `user` or `project`).-Manage approvals with `wt hook approvals add` and `wt hook approvals clear`.+### pre-commit-## User hooks+Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.-Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval.+**Use cases**: Formatters, linters, type checking.```toml-# ~/.config/worktrunk/config.toml-[post-create]-setup = "echo 'Setting up worktree...'"+[pre-commit]+format = "cargo fmt -- --check"+lint = "cargo clippy -- -D warnings"+```++### pre-merge+Runs before merging to target branch, **fail-fast**. All commands must exit 0 for the merge to proceed.++**Use cases**: Tests, security scans, build verification.++```toml[pre-merge]-notify = "notify-send 'Merging {{ branch }}'"+test = "cargo test"+build = "cargo build --release"```-User hooks support the same hook types and template variables as project hooks.+### post-merge-**Key differences from project hooks:**+Runs after successful merge in the **worktree for the target branch** if it exists, otherwise the **main worktree**, **best-effort**. Failures are logged but don't abort.-| Aspect | Project hooks | User hooks |-|--------|--------------|------------|-| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |-| Scope | Single repository | All repositories |-| Approval | Required | Not required |-| Execution order | After user hooks | Before project hooks |+**Use cases**: Deployment, notifications, installing updated binaries.-Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.+```toml+post-merge = "cargo install --path ."+```-**Use cases:**-- Personal notifications or logging-- Editor/IDE integration-- Repository-agnostic setup tasks-- Filtering by repository using JSON context+### pre-remove-**Filtering by repository:**+Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit 0 for removal to proceed.-User hooks receive JSON context on stdin, enabling repository-specific behavior:+**Use cases**: Cleanup tasks, saving state, notifying external systems.```toml-# ~/.config/worktrunk/config.toml-[post-create]-gitlab-setup = """-python3 -c '-import json, sys, subprocess-ctx = json.load(sys.stdin)-if "gitlab" in ctx.get("remote", ""):- subprocess.run(["glab", "mr", "create", "--fill"])-'-"""+[pre-remove]+cleanup = "rm -rf /tmp/cache/{{ branch }}"```-## Running hooks manually+### Timing during merge-`wt hook <type>` runs hooks on demand — useful for testing during development, running in CI pipelines, or re-running after a failure.--```console-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 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 project:test # Run only project's "test" hook-wt hook pre-merge --yes # Skip approval prompts (for CI)-```--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.--## Language-specific tips+- **pre-commit** — After staging, before squash commit+- **pre-merge** — After rebase, before merge to target+- **pre-remove** — Before removing worktree during cleanup+- **post-merge** — After cleanup completes-Each ecosystem has quirks that affect hook design. Contributions welcome for languages not listed.+See [wt merge](@/merge.md#pipeline) for the complete pipeline.-### Rust+## Configuration-The `target/` directory is huge (often 1-10GB) and benefits most from CoW. Worktrunk's own config seeds compiled dependencies:+Hooks are defined in `.config/wt.toml`. They can be a single command or multiple named commands:```toml-[post-start]-deps = """-[ -d {{ main_worktree_path }}/target/debug/deps ] && [ ! -e target ] &&-mkdir -p target/debug/deps &&-cp -c {{ main_worktree_path }}/target/debug/deps/*.rlib {{ main_worktree_path }}/target/debug/deps/*.rmeta target/debug/deps/ &&-cp -cR {{ main_worktree_path }}/target/debug/.fingerprint {{ main_worktree_path }}/target/debug/build target/debug/-"""+# Single command (string)+post-create = "npm install"++# Multiple commands (table) — run sequentially in declaration order+[pre-merge]+test = "cargo test"+build = "cargo build --release"```-This cuts first build from ~68s to ~3s by reusing compiled dependencies. The check `[ ! -e target ]` skips if target already exists.+### Template variables-### Python+Hooks can use template variables that expand at runtime:-Virtual environments contain absolute paths and can't be copied between directories. Use `uv sync` to recreate — it's fast enough that copying isn't worth it:+| Variable | Example | Description |+|----------|---------|-------------|+| `{{ repo }}` | myproject | Repository directory name |+| `{{ repo_path }}` | /path/to/myproject | Absolute path to repository root |+| `{{ branch }}` | feature/auth | Branch name |+| `{{ worktree_name }}` | myproject.feature-auth | Worktree directory name |+| `{{ worktree_path }}` | /path/to/myproject.feature-auth | Absolute worktree path |+| `{{ main_worktree_path }}` | /path/to/myproject | Default branch worktree |+| `{{ default_branch }}` | main | Default branch name |+| `{{ commit }}` | a1b2c3d4e5f6... | Full HEAD commit SHA |+| `{{ short_commit }}` | a1b2c3d | Short HEAD commit SHA |+| `{{ remote }}` | origin | Primary remote name |+| `{{ remote_url }}` | [email protected]:user/repo.git | Remote URL |+| `{{ upstream }}` | origin/feature | Upstream tracking branch |+| `{{ target }}` | main | Target branch (merge hooks only) |-```toml-[post-create]-install = "uv sync"-```+See [Designing effective hooks](#designing-effective-hooks) for `main_worktree_path` patterns.-For pip-based projects without uv:+**Deprecated:** `repo_root` (use `repo_path`), `worktree` (use `worktree_path`), `main_worktree` (use `repo`). These still work but emit warnings.-```toml-[post-create]-venv = "python -m venv .venv && .venv/bin/pip install -r requirements.txt"-```+### Filters-### Node.js+Templates support Jinja2 filters for transforming values:-`node_modules/` is large but mostly static. CoW works well:+| Filter | Example | Description |+|--------|---------|-------------|+| `sanitize` | `{{ branch \| sanitize }}` | Replace `/` and `\` with `-` |+| `hash_port` | `{{ branch \| hash_port }}` | Hash to port 10000-19999 |++The `sanitize` filter makes branch names safe for filesystem paths. The `hash_port` filter is useful for running dev servers on unique ports per worktree:```toml-[post-create]-deps = "cp -c -r {{ main_worktree_path }}/node_modules . 2>/dev/null || npm ci"+[post-start]+dev = "npm run dev -- --host {{ branch }}.lvh.me --port {{ branch | hash_port }}"```-If the project has no native dependencies, symlinks are even faster:+Hash any string, including concatenations:```toml-[post-create]-deps = "ln -sf {{ main_worktree_path }}/node_modules ."+# Unique port per repo+branch combination+dev = "npm run dev --port {{ (repo ~ '-' ~ branch) | hash_port }}"```-### Hook flow patterns--**Progressive validation** — Quick checks before commit, thorough validation before merge:+### JSON context-```toml-[pre-commit]-lint = "npm run lint"-typecheck = "npm run typecheck"+Hooks also receive context as JSON on stdin, enabling hooks in any language:-[pre-merge]-test = "npm test"-build = "npm run build"+```python+import json, sys+ctx = json.load(sys.stdin)+print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")```-**Target-specific behavior** — Different actions for production vs staging:--```toml-post-merge = """-if [ "{{ target }}" = "main" ]; then- npm run deploy:production-elif [ "{{ target }}" = "staging" ]; then- npm run deploy:staging-fi-"""-```+The JSON includes all template variables plus `hook_type` and `hook_name`.-## See also+## Designing effective hooks-- [wt merge](@/merge.md) — Runs hooks automatically during merge-- [wt switch](@/switch.md) — Runs post-create/post-start hooks on `--create`-- [wt config](@/config.md) — Manage hook approvals+### post-create vs post-start-<!-- subdoc: approvals -->-"#- )]- Hook {- #[command(subcommand)]- action: HookCommand,- },+Both run when creating a worktree. The difference:- /// Interactive worktree selector- ///- /// Browse and switch worktrees with live preview.- #[cfg_attr(not(unix), command(hide = true))]- #[command(- after_long_help = r#"Interactive worktree picker with live preview. Navigate worktrees with keyboard shortcuts and press Enter to switch.-<!-- demo: wt-select.gif 1600x800 -->+| Hook | Execution | Best for |+|------|-----------|----------|+| `post-create` | Blocks until complete | Tasks the developer needs before working (dependency install) |+| `post-start` | Background, parallel | Long-running tasks that can finish while you work |-## Examples+Many tasks work well in `post-start` — they'll likely be ready by the time you need them, especially when the fallback is recompiling. If unsure, prefer `post-start` for faster worktree creation.-Open the selector:+### Copying untracked files-```console-wt select-```+Git worktrees share the repository but not untracked files. Common files to copy or link:-## Preview tabs+- **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)-Toggle between views with number keys:+Three strategies:-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+| Strategy | Speed | Disk | State |+|----------|-------|------|-------|+| **Symlink** | Instant | Shared | Shared (changes affect all worktrees) |+| **Copy** | Slow | Full duplicate | Isolated |+| **Copy-on-write** | Instant | Shared until modified | Isolated |-## Keybindings+### Copy-on-write for disk efficiency-| Key | Action |-|-----|--------|-| `↑`/`↓` | Navigate worktree list |-| `Enter` | Switch to selected worktree |-| `Esc` | Cancel |-| (type) | Filter worktrees |-| `1`/`2`/`3` | Switch preview tab |-| `Alt-p` | Toggle preview panel |-| `Ctrl-u`/`Ctrl-d` | Scroll preview up/down |+Copy-on-write (CoW) creates instant clones that share disk space until modified. Perfect for large directories.-Branches without worktrees are included — selecting one creates a worktree. (`wt list` requires `--branches` to show them.)+| OS | Filesystem | Command |+|----|------------|---------|+| macOS | APFS | `cp -c` |+| Linux | Btrfs, XFS | `cp --reflink=auto` |+| Windows | ReFS | No shell equivalent (requires API) |-## See also+Cross-platform pattern that auto-detects and falls back gracefully:-- [wt list](@/list.md) — Static table view with all worktree metadata-- [wt switch](@/switch.md) — Direct switching to a known target branch-"#- )]- Select,+```toml+[post-create]+deps = """+if cp -c /dev/null /dev/null 2>/dev/null; then+ cp -c -r {{ main_worktree_path }}/node_modules .+elif cp --reflink=auto /dev/null /dev/null 2>/dev/null; then+ cp --reflink=auto -r {{ main_worktree_path }}/node_modules .+else+ cp -r {{ main_worktree_path }}/node_modules .+fi+"""+```- /// List worktrees and their status- #[command(- after_long_help = r#"Show all worktrees with their status. The table includes uncommitted changes, divergence from the default branch and remote, and optional CI status.-<!-- demo: wt-list.gif 1600x900 -->+### Dev servers-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. With `--full`, CI status fetches from the network — the table displays instantly and CI fills in as results arrive.+Run a dev server per worktree on a deterministic port using `hash_port`:-## Examples+```toml+[post-start]+server = "npm run dev -- --port {{ branch | hash_port }}"+```-List all worktrees:+The port is stable across machines and restarts — `feature-api` always gets the same port. Show it in `wt list`:-<!-- wt list -->-```console-$ wt list+```toml+[list]+url = "http://localhost:{{ branch | hash_port }}"```-Include CI status and line diffs:+For subdomain-based routing (useful for cookies/CORS), use `lvh.me` which resolves to 127.0.0.1:-<!-- wt list --full -->-```console-$ wt list --full+```toml+[post-start]+server = "npm run dev -- --host {{ branch | sanitize }}.lvh.me --port {{ branch | hash_port }}"```-Include branches that don't have worktrees:+### Databases-<!-- wt list --branches --full -->-```console-$ wt list --branches --full-```+Each worktree can have its own database. Docker containers get unique names and ports:-Output as JSON for scripting:+```toml+[post-start]+db = """+docker run -d --rm \+ --name {{ repo }}-{{ branch | sanitize }}-postgres \+ -p {{ ('db-' ~ branch) | hash_port }}:5432 \+ -e POSTGRES_DB={{ repo }} \+ -e POSTGRES_PASSWORD=dev \+ postgres:16+"""-```console-$ wt list --format=json+[pre-remove]+db-stop = "docker stop {{ repo }}-{{ branch | sanitize }}-postgres 2>/dev/null || true"```-## Columns+The `('db-' ~ branch)` concatenation hashes differently than plain `branch`, so database and dev server ports don't collide.+Jinja2's operator precedence has pipe `|` with higher precedence than concatenation `~`, meaning expressions need parentheses to filter concatenated values.-| 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 with the default branch (`--full`) |-| Path | Worktree directory |-| Remote⇅ | Commits ahead/behind tracking branch |-| URL | Dev server URL from project config (dimmed if port not listening) |-| CI | Pipeline status (`--full`) |-| Commit | Short hash (8 chars) |-| Age | Time since last commit |-| Message | Last commit message (truncated) |--Note: `main↕` and `main…±` refer to the default branch (header label stays `main` for compactness). `main…±` uses a merge-base (three-dot) diff.--### CI status--The CI column shows GitHub/GitLab pipeline status:--| Indicator | Meaning |-|-----------|---------|-| `●` green | All checks passed |-| `●` blue | Checks running |-| `●` red | Checks failed |-| `●` yellow | Merge conflicts with base |-| `●` gray | No checks configured |-| `⚠` yellow | Fetch error (rate limit, network) |-| (blank) | No upstream or no PR/MR |+Generate `.env.local` with the connection string:-CI indicators are clickable links to the PR or pipeline page. Any CI dot appears dimmed when there are unpushed local changes (stale status). PRs/MRs are checked first, then branch workflows/pipelines for branches with an upstream. Local-only branches show blank. Results are cached for 30-60 seconds; use `wt config state` to view or clear.+```toml+[post-create]+env = """+cat > .env.local << EOF+DATABASE_URL=postgres://postgres:dev@localhost:{{ ('db-' ~ branch) | hash_port }}/{{ repo }}+DEV_PORT={{ branch | hash_port }}+EOF+"""+```-## Status symbols+## Security-The Status column has multiple subcolumns. Within each, only the first matching symbol is shown (listed in priority order):+Project commands require approval on first run:-| Subcolumn | Symbol | Meaning |-|-----------|--------|---------|-| Working tree (1) | `+` | Staged files |-| Working tree (2) | `!` | Modified files (unstaged) |-| Working tree (3) | `?` | Untracked files |-| Worktree | `✘` | Merge conflicts |-| | `⤴` | Rebase in progress |-| | `⤵` | Merge in progress |-| | `/` | Branch without worktree |-| | `⚑` | Branch-worktree mismatch (branch name doesn't match worktree path) |-| | `⊟` | Prunable (directory missing) |-| | `⊞` | Locked worktree |-| Default branch | `^` | Is the default branch |-| | `✗` | Would conflict if merged to the default branch (with `--full`, includes uncommitted changes) |-| | `_` | Same commit as the default branch, clean |-| | `–` | Same commit as the default branch, uncommitted changes |-| | `⊂` | Content [integrated](@/remove.md#branch-cleanup) into the default branch or target |-| | `↕` | Diverged from the default branch |-| | `↑` | Ahead of the default branch |-| | `↓` | Behind the default branch |-| Remote | `\|` | In sync with remote |-| | `⇅` | Diverged from remote |-| | `⇡` | Ahead of remote |-| | `⇣` | Behind remote |+```+▲ repo needs approval to execute 3 commands:-Rows are dimmed when [safe to delete](@/remove.md#branch-cleanup) (`_` same commit with clean working tree or `⊂` content integrated).+○ post-create install:+ echo 'Installing dependencies...'-## JSON output+❯ Allow and remember? [y/N]+```-Query structured data with `--format=json`:+- Approvals are saved to user config (`~/.config/worktrunk/config.toml`)+- If a command changes, new approval is required+- Use `--yes` to bypass prompts (useful for CI/automation)+- Use `--no-verify` to skip hooks-```console-# Worktrees with merge conflicts-wt list --format=json | jq '.[] | select(.operation_state == "conflicts")'+Manage approvals with `wt hook approvals add` and `wt hook approvals clear`.-# Uncommitted changes-wt list --format=json | jq '.[] | select(.working_tree.modified)'+## User hooks-# Current worktree-wt list --format=json | jq '.[] | select(.is_current)'+Define hooks in `~/.config/worktrunk/config.toml` to run for all repositories. User hooks run before project hooks and don't require approval.-# Branches ahead of the default branch-wt list --format=json | jq '.[] | select(.main.ahead > 0)'+```toml+# ~/.config/worktrunk/config.toml+[post-create]+setup = "echo 'Setting up worktree...'"-# Integrated branches (ready to clean up)-wt list --format=json | jq '.[] | select(.main_state == "integrated" or .main_state == "empty")'+[pre-merge]+notify = "notify-send 'Merging {{ branch }}'"```-**Fields:**+User hooks support the same hook types and template variables as project hooks.-| 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"` (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, absent when no CI) |-| `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) |-| `statusline` | string | Pre-formatted status with ANSI colors |-| `symbols` | string | Raw status symbols without colors (e.g., `"!?↓"`) |+**Key differences from project hooks:**-### commit object+| Aspect | Project hooks | User hooks |+|--------|--------------|------------|+| Location | `.config/wt.toml` | `~/.config/worktrunk/config.toml` |+| Scope | Single repository | All repositories |+| Approval | Required | Not required |+| Execution order | After user hooks | Before project hooks |-| Field | Type | Description |-|-------|------|-------------|-| `sha` | string | Full commit SHA (40 chars) |-| `short_sha` | string | Short commit SHA (7 chars) |-| `message` | string | Commit message (first line) |-| `timestamp` | number | Unix timestamp |+Skip hooks with `--no-verify`. To run a specific hook when user and project both define the same name, use `user:name` or `project:name` syntax.-### working_tree object+**Use cases:**+- Personal notifications or logging+- Editor/IDE integration+- Repository-agnostic setup tasks+- Filtering by repository using JSON context-| 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}` |-| `diff_vs_main` | object | Lines changed vs the default branch: `{added, deleted}` |+**Filtering by repository:**-### main object+User hooks receive JSON context on stdin, enabling repository-specific behavior:-| 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}` |+```toml+# ~/.config/worktrunk/config.toml+[post-create]+gitlab-setup = """+python3 -c '+import json, sys, subprocess+ctx = json.load(sys.stdin)+if "gitlab" in ctx.get("remote", ""):+ subprocess.run(["glab", "mr", "create", "--fill"])+'+"""+```-### remote object+## Running hooks manually-| 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 |+`wt hook <type>` runs hooks on demand — useful for testing during development, running in CI pipelines, or re-running after a failure.-### worktree object+```console+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 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 project:test # Run only project's "test" hook+wt hook pre-merge --yes # Skip approval prompts (for CI)+```-| Field | Type | Description |-|-------|------|-------------|-| `state` | string | `"branch_worktree_mismatch"`, `"prunable"`, `"locked"` (absent when normal) |-| `reason` | string | Reason for locked/prunable state |-| `detached` | boolean | HEAD is detached |+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.-### ci object+## Language-specific tips-| Field | Type | Description |-|-------|------|-------------|-| `status` | string | CI status (see below) |-| `source` | string | `"pr"` (PR/MR) or `"branch"` (branch workflow) |-| `stale` | boolean | Local HEAD differs from remote (unpushed changes) |-| `url` | string | URL to the PR/MR page |+Each ecosystem has quirks that affect hook design. Contributions welcome for languages not listed.-### main_state values+### Rust-These values describe relation to the default branch.+The `target/` directory is huge (often 1-10GB) and benefits most from CoW. Worktrunk's own config seeds compiled dependencies:-`"is_main"` `"would_conflict"` `"empty"` `"same_commit"` `"integrated"` `"diverged"` `"ahead"` `"behind"`+```toml+[post-start]+deps = """+[ -d {{ main_worktree_path }}/target/debug/deps ] && [ ! -e target ] &&+mkdir -p target/debug/deps &&+cp -c {{ main_worktree_path }}/target/debug/deps/*.rlib {{ main_worktree_path }}/target/debug/deps/*.rmeta target/debug/deps/ &&+cp -cR {{ main_worktree_path }}/target/debug/.fingerprint {{ main_worktree_path }}/target/debug/build target/debug/+"""+```-### integration_reason values+This cuts first build from ~68s to ~3s by reusing compiled dependencies. The check `[ ! -e target ]` skips if target already exists.-When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"`+### Python-### ci.status values+Virtual environments contain absolute paths and can't be copied between directories. Use `uv sync` to recreate — it's fast enough that copying isn't worth it:-`"passed"` `"running"` `"failed"` `"conflicts"` `"no-ci"` `"error"`+```toml+[post-create]+install = "uv sync"+```-Missing a field that would be generally useful? Open an issue at https://github.com/max-sixty/worktrunk.+For pip-based projects without uv:-## See also+```toml+[post-create]+venv = "python -m venv .venv && .venv/bin/pip install -r requirements.txt"+```-- [wt select](@/select.md) — Interactive worktree picker with live preview-"#- )]- // TODO: `args_conflicts_with_subcommands` causes confusing errors for unknown- // subcommands ("cannot be used with --branches") instead of "unknown subcommand".- // Could fix with external_subcommand + post-parse validation, but not worth the- // code. The `statusline` subcommand may move elsewhere anyway.- #[command(args_conflicts_with_subcommands = true)]- List {- #[command(subcommand)]- subcommand: Option<ListSubcommand>,+### Node.js- /// Output format (table, json)- #[arg(long, value_enum, default_value = "table", hide_possible_values = true)]- format: OutputFormat,+`node_modules/` is large but mostly static. CoW works well:- /// Include branches without worktrees- #[arg(long)]- branches: bool,+```toml+[post-create]+deps = "cp -c -r {{ main_worktree_path }}/node_modules . 2>/dev/null || npm ci"+```- /// Include remote branches- #[arg(long)]- remotes: bool,+If the project has no native dependencies, symlinks are even faster:- /// Include CI status and diff analysis (slower)- #[arg(long)]- full: bool,+```toml+[post-create]+deps = "ln -sf {{ main_worktree_path }}/node_modules ."+```- /// 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. Auto-enabled for TTY.- #[arg(long, overrides_with = "no_progressive")]- progressive: bool,+### Hook flow patterns- /// Force buffered rendering- #[arg(long = "no-progressive", overrides_with = "progressive", hide = true)]- no_progressive: bool,- },+**Progressive validation** — Quick checks before commit, thorough validation before merge:- /// Switch to a worktree- #[command(- after_long_help = r#"Change directory to a worktree, creating one if needed.-<!-- demo: wt-switch.gif 1600x900 -->+```toml+[pre-commit]+lint = "npm run lint"+typecheck = "npm run typecheck"-Worktrees are addressed by branch name; paths are computed from a template. Unlike `git switch`, this navigates between worktrees rather than changing branches in place.+[pre-merge]+test = "npm test"+build = "npm run build"+```-## Examples+**Target-specific behavior** — Different actions for production vs staging:-```console-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+```toml+post-merge = """+if [ "{{ target }}" = "main" ]; then+ npm run deploy:production+elif [ "{{ target }}" = "staging" ]; then+ npm run deploy:staging+fi+"""```-## Creating a branch+## See also-The `--create` flag creates a new branch from the `--base` branch (defaults to default branch). Without `--create`, the branch must already exist.+- [wt merge](@/merge.md) — Runs hooks automatically during merge+- [wt switch](@/switch.md) — Runs post-create/post-start hooks on `--create`+- [wt config](@/config.md) — Manage hook approvals-## Creating worktrees+<!-- subdoc: approvals -->+"#+ )]+ Hook {+ #[command(subcommand)]+ action: HookCommand,+ },-If the branch already has a worktree, `wt switch` changes directories to it. Otherwise, it creates one, running [hooks](@/hook.md).+ /// Manage configuration and shell integration+ #[command(+ about = "Manage configuration and shell integration",+ after_long_help = r#"Manages configuration, shell integration, and runtime settings.-When creating a worktree, worktrunk:+Worktrunk uses two configuration files:-1. Creates worktree at configured path-2. Switches to new directory-3. Runs [post-create hooks](@/hook.md#post-create) (blocking)-4. Spawns [post-start hooks](@/hook.md#post-start) (background)+| File | Location | Purpose |+|------|----------|---------|+| **User config** | `~/.config/worktrunk/config.toml` | Personal settings, command defaults, approved project commands |+| **Project config** | `.config/wt.toml` | Lifecycle hooks, checked into version control |++## Examples++Install shell integration (required for directory switching):```console-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-verify # Skip hooks+wt config shell install```-## Shortcuts--| Shortcut | Meaning |-|----------|---------|-| `^` | Default branch (main/master) |-| `@` | Current branch/worktree |-| `-` | Previous worktree (like `cd -`) |+Create user config file with documented examples:```console-wt switch - # Back to previous-wt switch ^ # Default branch worktree-wt switch --create fix --base=@ # Branch from current HEAD+wt config create```-## When wt switch fails+Create project config file (`.config/wt.toml`) for hooks:-- **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+```console+wt config create --project+```-To change which branch a worktree is on, use `git switch` inside that worktree.+Show current configuration and file locations:-## See also+```console+wt config show+```-- [wt select](@/select.md) — Interactive worktree selection-- [wt list](@/list.md) — View all worktrees-- [wt remove](@/remove.md) — Delete worktrees when done-- [wt merge](@/merge.md) — Integrate changes back to the default branch-"#- )]- Switch {- /// Branch name- ///- /// Shortcuts: '^' (default branch), '-' (previous), '@' (current)- #[arg(add = crate::completion::worktree_branch_completer())]- branch: String,+## User config- /// Create a new branch- #[arg(short = 'c', long)]- create: bool,+The user config stores personal preferences that apply across all repositories. Create it with `wt config create` and view with `wt config show`.- /// Base branch- ///- /// Defaults to default branch.- #[arg(short = 'b', long, add = crate::completion::branch_value_completer())]- base: Option<String>,+### Worktree path template- /// 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.- ///- /// Especially useful with shell aliases:- ///- /// ```sh- /// 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.- #[arg(short = 'x', long)]- execute: Option<String>,+Controls where new worktrees are created. The template is relative to the repository root.- /// Additional arguments for --execute command (after --)- ///- /// Arguments after `--` are appended to the execute command.- /// Each argument is POSIX shell-escaped before appending.- #[arg(last = true, requires = "execute")]- execute_args: Vec<String>,+**Available variables:**+- `{{ repo }}` — repository directory name+- `{{ branch }}` — raw branch name (e.g., `feature/auth`)+- `{{ branch | sanitize }}` — branch name with `/` and `\` replaced by `-`- /// Skip approval prompts- #[arg(short, long)]- yes: bool,+**Examples** for a repo at `~/code/myproject` creating branch `feature/login`:- /// Remove stale paths at target- #[arg(long)]- clobber: bool,+```toml+# Default — siblings in parent directory+# Creates: ~/code/myproject.feature-login+worktree-path = "../{{ repo }}.{{ branch | sanitize }}"- /// Skip hooks- #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]- verify: bool,- },+# Inside the repository+# Creates: ~/code/myproject/.worktrees/feature-login+worktree-path = ".worktrees/{{ branch | sanitize }}"- /// Remove worktree; delete branch if merged- #[command(- after_long_help = r#"Removes worktrees and their branches (if merged), returning to the main worktree. Defaults to removing the current worktree.+# Namespaced (useful when multiple repos share a parent directory)+# Creates: ~/code/worktrees/myproject/feature-login+worktree-path = "../worktrees/{{ repo }}/{{ branch | sanitize }}"-## Examples+# Nested bare repo (git clone --bare <url> project/.git)+# Creates: ~/code/project/feature-login (sibling to .git)+worktree-path = "../{{ branch | sanitize }}"+```-Remove current worktree:+### Command settings-```console-wt remove-```+Set persistent flag values for commands. These apply unless explicitly overridden on the command line.-Remove specific worktrees:+**`wt list`:**-```console-wt remove feature-branch-wt remove old-feature another-branch+```toml+[list]+# All off by default+full = true # --full+branches = true # --branches+remotes = true # --remotes```-Keep the branch:+**`wt step commit` and `wt merge` staging:**-```console-wt remove --no-delete-branch feature-branch+```toml+[commit]+stage = "all" # "all" (default), "tracked", or "none"```-Force-delete an unmerged branch:+**`wt merge`:**-```console-wt remove -D experimental+```toml+[merge]+# These flags are on by default; set to false to disable+squash = false # Preserve individual commits (--no-squash)+commit = false # Skip committing uncommitted changes (also disables squash)+rebase = false # Skip rebase (fails if not already rebased)+remove = false # Keep worktree after merge (--no-remove)+verify = false # Skip hooks (--no-verify)```-## Branch cleanup+### LLM commit messages-By default, branches are deleted when merging them would add nothing. This works with squash-merge and rebase workflows where commit history differs but file changes match.+Configure automatic commit message generation. Requires an external tool like [llm](https://llm.datasette.io/):-Worktrunk checks five conditions (in order of cost):+```toml+[commit-generation]+command = "llm"+args = ["-m", "claude-haiku-4.5"]+```-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. Shows `⊂`.+See [LLM Commit Messages](@/llm-commits.md) for setup details and template customization.-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.+### Approved commands-Branches showing `_` or `⊂` are dimmed as safe to delete.+When project hooks run for the first time, Worktrunk prompts for approval. Approved commands are saved here automatically:-Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch` to keep the branch regardless of status.+```toml+[projects."my-project"]+approved-commands = ["npm ci", "npm test"]+```-## Background removal+Manage approvals with `wt hook approvals add` to review and pre-approve commands, and `wt hook approvals clear` to reset (add `--global` to clear all projects).-Removal runs in the background by default (returns immediately). Logs are written to `.git/wt-logs/{branch}-remove.log`. Use `--no-background` to run in the foreground.+### User hooks-## Shortcuts+Personal hooks that run for all repositories. Use the same syntax as project hooks:-`@` (current), `-` (previous), `^` (default branch). See [wt switch](@/switch.md#shortcuts).+```toml+[post-create]+setup = "echo 'Setting up worktree...'"-## See also+[pre-merge]+notify = "notify-send 'Merging {{ branch }}'"+```-- [wt merge](@/merge.md) — Remove worktree after merging-- [wt list](@/list.md) — View all worktrees-"#- )]- Remove {- /// Branch name [default: current]- #[arg(add = crate::completion::local_branches_completer())]- branches: Vec<String>,+User hooks run before project hooks and don't require approval. Skip with `--no-verify`.- /// Keep branch after removal- #[arg(long = "no-delete-branch", action = clap::ArgAction::SetFalse, default_value_t = true)]- delete_branch: bool,+See [wt hook](@/hook.md#user-hooks) for complete documentation.- /// Delete unmerged branches- #[arg(short = 'D', long = "force-delete")]- force_delete: bool,+## Project config- /// Run removal in foreground- #[arg(long = "no-background", action = clap::ArgAction::SetFalse, default_value_t = true)]- background: bool,+The project config defines lifecycle hooks and project-specific settings. This file is checked into version control and shared across the team.- /// Skip hooks- #[arg(long = "no-verify", action = clap::ArgAction::SetFalse, default_value_t = true)]- verify: bool,+Create `.config/wt.toml` in the repository root:- /// Skip approval prompts- #[arg(short, long)]- yes: bool,+```toml+[post-create]+install = "npm ci"- /// Force worktree removal- ///- /// Remove worktrees even if they contain untracked files (like build- /// artifacts). Without this flag, removal fails if untracked files exist.- #[arg(short, long)]- force: bool,- },+[pre-merge]+test = "npm test"+lint = "npm run lint"+```- /// Merge worktree into target branch- ///- /// Squash & rebase, fast-forward target, remove the worktree.- #[command(- after_long_help = r#"Merge the current branch into the default branch — like clicking "Merge pull request" on GitHub.-<!-- demo: wt-merge.gif 1600x900 -->+See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).-## Examples+### Dev server URL-Merge to the default branch:+The `[list]` section adds a URL column to `wt list`:-```console-wt merge+```toml+[list]+url = "http://localhost:{{ branch | hash_port }}"```-Merge to a different branch:+URLs are dimmed when the port isn't listening. The template supports `{{ branch }}` with filters `hash_port` (port 10000-19999) and `sanitize` (filesystem-safe).-```console-wt merge develop-```+## Shell integration-Keep the worktree after merging:+Worktrunk needs shell integration to change directories when switching worktrees. Install with:```console-wt merge --no-remove+wt config shell install```-Preserve commit history (no squash):+Or manually add to the shell config:```console-wt merge --no-squash-```+# For bash: add to ~/.bashrc+eval "$(wt config shell init bash)"-Skip committing/squashing (rebase still runs unless --no-rebase):+# For zsh: add to ~/.zshrc+eval "$(wt config shell init zsh)"-```console-wt merge --no-commit+# For fish: add to ~/.config/fish/config.fish+wt config shell init fish | source```-## Pipeline--`wt merge` runs these steps:--1. **Squash** — Stages uncommitted changes, then 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`, uncommitted changes become a separate commit and individual commits are preserved.-2. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.-3. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [wt hook](@/hook.md).-4. **Merge** — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.-5. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.-6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the main worktree, the worktree is preserved.-7. **Post-merge hooks** — Hooks run after cleanup. Failures are logged but don't abort.--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`. Requires a clean working tree.--## Local CI+Without shell integration, `wt switch` prints the target directory but cannot `cd` into it.-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.+## Environment variables-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.+All user config options can be overridden with environment variables using the `WORKTRUNK_` prefix.-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.+### Naming convention-```toml-[pre-merge]-test = "cargo test"-lint = "cargo clippy"-```+Config keys use kebab-case (`worktree-path`), while env vars use SCREAMING_SNAKE_CASE (`WORKTRUNK_WORKTREE_PATH`). The conversion happens automatically.-## See also+For nested config sections, use double underscores to separate levels:-- [wt step](@/step.md) — Run individual operations (commit, squash, rebase, push)-- [wt remove](@/remove.md) — Remove worktrees without merging-- [wt switch](@/switch.md) — Navigate to other worktrees-"#- )]- Merge {- /// Target branch- ///- /// Defaults to default branch.- #[arg(add = crate::completion::branch_value_completer())]- target: Option<String>,+| Config | Environment Variable |+|--------|---------------------|+| `worktree-path` | `WORKTRUNK_WORKTREE_PATH` |+| `commit-generation.command` | `WORKTRUNK_COMMIT_GENERATION__COMMAND` |+| `commit-generation.args` | `WORKTRUNK_COMMIT_GENERATION__ARGS` |- /// Force commit squashing- #[arg(long, overrides_with = "no_squash", hide = true)]- squash: bool,+Note the single underscore after `WORKTRUNK` and double underscores between nested keys.- /// Skip commit squashing- #[arg(long = "no-squash", overrides_with = "squash")]- no_squash: bool,+### Array values- /// Force commit and squash- #[arg(long, overrides_with = "no_commit", hide = true)]- commit: bool,+Array config values like `args = ["-m", "claude-haiku"]` can be specified as a single string in environment variables:- /// Skip commit and squash- #[arg(long = "no-commit", overrides_with = "commit")]- no_commit: bool,+```console+export WORKTRUNK_COMMIT_GENERATION__ARGS="-m claude-haiku"+```- /// Force rebasing onto target- #[arg(long, overrides_with = "no_rebase", hide = true)]- rebase: bool,+### Example: CI/testing override- /// Skip rebase (fail if not already rebased)- #[arg(long = "no-rebase", overrides_with = "rebase")]- no_rebase: bool,+Override the LLM command in CI to use a mock:- /// Force worktree removal after merge- #[arg(long, overrides_with = "no_remove", hide = true)]- remove: bool,+```console+WORKTRUNK_COMMIT_GENERATION__COMMAND=echo \+WORKTRUNK_COMMIT_GENERATION__ARGS="test: automated commit" \+ wt merge+```- /// Keep worktree after merge- #[arg(long = "no-remove", overrides_with = "remove")]- no_remove: bool,+### Other environment variables- /// Force running hooks- #[arg(long, overrides_with = "no_verify", hide = true)]- verify: bool,+| Variable | Purpose |+|----------|---------|+| `WORKTRUNK_BIN` | Override binary path for shell wrappers (useful for testing dev builds) |+| `WORKTRUNK_CONFIG_PATH` | Override user config file location |+| `WORKTRUNK_DIRECTIVE_FILE` | Internal: set by shell wrappers to enable directory changes |+| `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 resource limits. |+| `NO_COLOR` | Disable colored output ([standard](https://no-color.org/)) |+| `CLICOLOR_FORCE` | Force colored output even when not a TTY |- /// Skip hooks- #[arg(long = "no-verify", overrides_with = "verify")]- no_verify: bool,+<!-- subdoc: create -->- /// Skip approval prompts- #[arg(short, long)]- yes: bool,+<!-- subdoc: show -->- /// What to stage before committing [default: all]- #[arg(long)]- stage: Option<crate::commands::commit::StageMode>,+<!-- subdoc: state -->+"#+ )]+ Config {+ #[command(subcommand)]+ action: ConfigCommand,},}diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__bash_completion_subcommands.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__bash_completion_subcommands.snapindex 7ca2d2d17..9d8e54ba1 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__bash_completion_subcommands.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__bash_completion_subcommands.snap@@ -2,11 +2,11 @@source: tests/integration_tests/shell_wrapper.rsexpression: "String::from_utf8_lossy(&output.stdout)"----config-step-hook-select-listswitch+listremovemerge+select+step+hook+configdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__fish_completion_subcommands.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__fish_completion_subcommands.snapindex db1a7d92d..488382e79 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__fish_completion_subcommands.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__fish_completion_subcommands.snap@@ -2,11 +2,11 @@source: tests/integration_tests/shell_wrapper.rsexpression: completions----config-step-hook-select-listswitch+listremovemerge+select+step+hook+configdiff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__zsh_completion_subcommands.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__zsh_completion_subcommands.snapindex 7ca2d2d17..9d8e54ba1 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__zsh_completion_subcommands.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__zsh_completion_subcommands.snap@@ -2,11 +2,11 @@source: tests/integration_tests/shell_wrapper.rsexpression: "String::from_utf8_lossy(&output.stdout)"----config-step-hook-select-listswitch+listremovemerge+select+step+hook+configdiff --git a/tests/snapshots/integration__integration_tests__help__help_md_root.snap b/tests/snapshots/integration__integration_tests__help__help_md_root.snapindex b35eb3905..dc97deb5d 100644--- a/tests/snapshots/integration__integration_tests__help__help_md_root.snap+++ b/tests/snapshots/integration__integration_tests__help__help_md_root.snap@@ -22,14 +22,14 @@ wt - Git worktree management for parallel AI agent workflowsUsage: wt [OPTIONS] [COMMAND]Commands:- config Manage configuration and shell integration- step Run individual operations- hook Run configured hooks- select Interactive worktree selector- list List worktrees and their statusswitch Switch to a worktree+ list List worktrees and their statusremove Remove worktree; delete branch if mergedmerge Merge worktree into target branch+ select Interactive worktree selector+ step Run individual operations+ hook Run configured hooks+ config Manage configuration and shell integrationOptions:-h, --helpdiff --git a/tests/snapshots/integration__integration_tests__help__help_no_args.snap b/tests/snapshots/integration__integration_tests__help__help_no_args.snapindex 6b9cdf469..72c5b03d2 100644--- a/tests/snapshots/integration__integration_tests__help__help_no_args.snap+++ b/tests/snapshots/integration__integration_tests__help__help_no_args.snap@@ -23,14 +23,14 @@ wt - Git worktree management for parallel AI agent workflowsUsage: [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][1m[32mCommands:- [1m[36mconfig[0m Manage configuration and shell integration- [1m[36mstep[0m Run individual operations- [1m[36mhook[0m Run configured hooks- [1m[36mselect[0m Interactive worktree selector- [1m[36mlist[0m List worktrees and their status[1m[36mswitch[0m Switch to a worktree+ [1m[36mlist[0m List worktrees and their status[1m[36mremove[0m Remove worktree; delete branch if merged[1m[36mmerge[0m Merge worktree into target branch+ [1m[36mselect[0m Interactive worktree selector+ [1m[36mstep[0m Run individual operations+ [1m[36mhook[0m Run configured hooks+ [1m[36mconfig[0m Manage configuration and shell integration[1m[32mOptions:[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')diff --git a/tests/snapshots/integration__integration_tests__help__help_root_long.snap b/tests/snapshots/integration__integration_tests__help__help_root_long.snapindex bbd0818a6..669894b09 100644--- a/tests/snapshots/integration__integration_tests__help__help_root_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_root_long.snap@@ -24,14 +24,14 @@ wt - Git worktree management for parallel AI agent workflowsUsage: [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][1m[32mCommands:- [1m[36mconfig[0m Manage configuration and shell integration- [1m[36mstep[0m Run individual operations- [1m[36mhook[0m Run configured hooks- [1m[36mselect[0m Interactive worktree selector- [1m[36mlist[0m List worktrees and their status[1m[36mswitch[0m Switch to a worktree+ [1m[36mlist[0m List worktrees and their status[1m[36mremove[0m Remove worktree; delete branch if merged[1m[36mmerge[0m Merge worktree into target branch+ [1m[36mselect[0m Interactive worktree selector+ [1m[36mstep[0m Run individual operations+ [1m[36mhook[0m Run configured hooks+ [1m[36mconfig[0m Manage configuration and shell integration[1m[32mOptions:[1m[36m-h[0m, [1m[36m--helpdiff --git a/tests/snapshots/integration__integration_tests__help__help_root_short.snap b/tests/snapshots/integration__integration_tests__help__help_root_short.snapindex 1c79e575d..652176677 100644--- a/tests/snapshots/integration__integration_tests__help__help_root_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_root_short.snap@@ -24,14 +24,14 @@ wt - Git worktree management for parallel AI agent workflowsUsage: [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND][1m[32mCommands:- [1m[36mconfig[0m Manage configuration and shell integration- [1m[36mstep[0m Run individual operations- [1m[36mhook[0m Run configured hooks- [1m[36mselect[0m Interactive worktree selector- [1m[36mlist[0m List worktrees and their status[1m[36mswitch[0m Switch to a worktree+ [1m[36mlist[0m List worktrees and their status[1m[36mremove[0m Remove worktree; delete branch if merged[1m[36mmerge[0m Merge worktree into target branch+ [1m[36mselect[0m Interactive worktree selector+ [1m[36mstep[0m Run individual operations+ [1m[36mhook[0m Run configured hooks+ [1m[36mconfig[0m Manage configuration and shell integration[1m[32mOptions:[1m[36m-h[0m, [1m[36m--help[0m Print help (see more with '--help')