Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Add wt hook command for running lifecycle hooks (#113)

Maximilian Roosa89047816ea4
diff --git a/.config/lychee.toml b/.config/lychee.toml
index 9ca327073..307d9ee75 100644
--- a/.config/lychee.toml
+++ b/.config/lychee.toml
@@ -53,6 +53,8 @@ exclude = [
"127\\.0\\.0\\.1",
"localhost",
+ # TODO: Remove after first deployment - new page from hooks.md → hook.md consolidation
+ "https://worktrunk\\.dev/hook/",
]
# Root directory for resolving root-relative paths like /assets/wt-demo.gif
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index 7820f68b3..ec834ed2e 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -29,13 +29,14 @@ repos:
- repo: https://github.com/lycheeverse/lychee
rev: lychee-v0.22.0
hooks:
- # Fast PR mode - only check worktrunk domains (internal links validated by zola check)
+ # PR mode - check links using .config/lychee.toml exclusions
+ # TODO: Consider re-adding `--include=^https://(github\.com/max-sixty/worktrunk|worktrunk\.dev)`
+ # once /hook/ page is deployed (currently excluded in lychee.toml to allow landing page merge)
- id: lychee
name: lychee (PR mode)
types: [markdown]
args:
- --config=.config/lychee.toml
- - --include=^https://(github\.com/max-sixty/worktrunk|worktrunk\.dev)
# Comprehensive mode - check all links with full config
# Run manually: pre-commit run --hook-stage manual lychee-all --all-files
- id: lychee
diff --git a/CLAUDE.md b/CLAUDE.md
index 205c10a91..01a6b5ce6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -55,7 +55,7 @@ cargo test --test integration
cargo test --test integration --features shell-integration-tests
# Run all tests via pre-merge hook (recommended before committing)
-cargo run -- step pre-merge --force
+cargo run -- hook pre-merge --force
```
The pre-merge hook runs the full test suite and is the recommended way to verify changes before committing.
diff --git a/README.md b/README.md
index e546644f1..8eb5fa7f3 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ Worktrunk makes worktrees easy to use — branch-based navigation, unified statu
**Workflow automation:**
-- **[Lifecycle hooks](https://worktrunk.dev/hooks/)** — run commands on create, pre-merge, post-merge
+- **[Lifecycle hooks](https://worktrunk.dev/hook/)** — run commands on create, pre-merge, post-merge
- **[LLM commit messages](https://worktrunk.dev/llm-commits/)** — generate commit messages from diffs via [llm](https://llm.datasette.io/)
- **[Merge workflow](https://worktrunk.dev/merge/)** — squash, rebase, merge, clean up in one command
- ...and lots more.
@@ -125,7 +125,7 @@ $ wt config shell install
## Next steps
- Learn the core commands: [wt switch](https://worktrunk.dev/switch/), [wt list](https://worktrunk.dev/list/), [wt merge](https://worktrunk.dev/merge/), [wt remove](https://worktrunk.dev/remove/)
-- Set up [project hooks](https://worktrunk.dev/hooks/) for automated setup
+- Set up [project hooks](https://worktrunk.dev/hook/) for automated setup
- Explore [LLM commit messages](https://worktrunk.dev/llm-commits/), [fzf-like picker](https://worktrunk.dev/select/), [Claude Code integration](https://worktrunk.dev/claude-code/)
- Run `wt --help` or `wt <command> --help` for quick CLI reference
diff --git a/docs/content/config.md b/docs/content/config.md
index d139deeaf..edf8342d0 100644
--- a/docs/content/config.md
+++ b/docs/content/config.md
@@ -144,7 +144,7 @@ test = "npm test"
lint = "npm run lint"
```
-See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hooks.md#json-context).
+See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).
## Shell integration
diff --git a/docs/content/hook.md b/docs/content/hook.md
new file mode 100644
index 000000000..a508e7c5c
--- /dev/null
+++ b/docs/content/hook.md
@@ -0,0 +1,363 @@
++++
+title = "wt hook"
+weight = 50
+
+[extra]
+group = "Commands"
++++
+
+<!-- ⚠️ AUTO-GENERATED from `wt hook --help-page` — edit src/cli.rs to update -->
+
+Run project-defined lifecycle hooks from `.config/wt.toml`.
+
+Hooks are commands that run automatically during worktree operations (`wt switch --create`, `wt merge`, `wt remove`). Use `wt hook` to run them manually for testing or CI.
+
+## Examples
+
+Run pre-merge hooks (for testing):
+
+```bash
+wt hook pre-merge
+```
+
+Run in CI (skip approval prompts):
+
+```bash
+wt hook pre-merge --force
+```
+
+## Hook types
+
+| Hook | When | Blocking | Fail-fast | Execution |
+|------|------|----------|-----------|-----------|
+| `post-create` | After worktree created | Yes | No | Sequential |
+| `post-start` | After worktree created | No | No | Parallel (background) |
+| `pre-commit` | Before commit during merge | Yes | Yes | Sequential |
+| `pre-merge` | Before merging to target | Yes | Yes | Sequential |
+| `post-merge` | After successful merge | Yes | No | Sequential |
+| `pre-remove` | Before worktree removed | Yes | Yes | Sequential |
+
+**Blocking**: Command waits for hook to complete before continuing.
+**Fail-fast**: First failure aborts the operation.
+
+## Configuration formats
+
+Hooks can be a single command or multiple named commands in `.config/wt.toml`:
+
+**Single command (string):**
+
+```toml
+post-create = "npm install"
+```
+
+**Multiple commands (table):**
+
+```toml
+[post-create]
+install = "npm install"
+build = "npm run build"
+```
+
+Named commands run sequentially in declaration order and appear in output with their labels.
+
+## Template variables
+
+Hooks can use template variables that expand at runtime.
+
+**All hooks:**
+
+| Variable | Example | Description |
+|----------|---------|-------------|
+| `{{ repo }}` | my-project | Repository name |
+| `{{ branch }}` | feature-foo | Branch name |
+| `{{ worktree }}` | /path/to/worktree | Absolute worktree path |
+| `{{ worktree_name }}` | my-project.feature-foo | Worktree directory name |
+| `{{ repo_root }}` | /path/to/main | Repository root path |
+| `{{ default_branch }}` | main | Default branch name |
+| `{{ commit }}` | a1b2c3d4e5f6... | Full HEAD commit SHA |
+| `{{ short_commit }}` | a1b2c3d | Short HEAD commit SHA |
+| `{{ remote }}` | origin | Primary remote name |
+| `{{ upstream }}` | origin/feature | Upstream tracking branch |
+
+**Merge hooks** (`pre-commit`, `pre-merge`, `post-merge`):
+
+| Variable | Example | Description |
+|----------|---------|-------------|
+| `{{ target }}` | main | Target branch for merge |
+
+## Hook details
+
+### post-create
+
+Runs after worktree creation, **blocks until complete**. The worktree switch doesn't finish until these commands succeed.
+
+**Use cases**: Installing dependencies, database migrations, copying environment files.
+
+```toml
+[post-create]
+install = "npm ci"
+migrate = "npm run db:migrate"
+env = "cp .env.example .env"
+```
+
+### post-start
+
+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"
+```
+
+Output logged to `.git/wt-logs/{branch}-post-start-{name}.log`.
+
+### pre-commit
+
+Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.
+
+**Use cases**: Formatters, linters, type checking.
+
+```toml
+[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]
+test = "cargo test"
+build = "cargo build --release"
+```
+
+### post-merge
+
+Runs after successful merge in the **main worktree**, **best-effort**. Failures are logged but don't abort.
+
+**Use cases**: Deployment, notifications, installing updated binaries.
+
+```toml
+post-merge = "cargo install --path ."
+```
+
+### pre-remove
+
+Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit 0 for removal to proceed.
+
+**Use cases**: Cleanup tasks, saving state, notifying external systems.
+
+```toml
+[pre-remove]
+cleanup = "rm -rf /tmp/cache/{{ branch }}"
+```
+
+## When hooks run during merge
+
+- **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
+
+See [wt merge](@/merge.md#pipeline) for the complete pipeline.
+
+## Security & approval
+
+Project commands require approval on first run:
+
+```
+🟡 repo needs approval to execute 3 commands:
+
+⚪ post-create install:
+ echo 'Installing dependencies...'
+
+❓ Allow and remember? [y/N]
+```
+
+- Approvals are saved to user config (`~/.config/worktrunk/config.toml`)
+- If a command changes, new approval is required
+- Use `--force` to bypass prompts (useful for CI/automation)
+
+Manage approvals with `wt config approvals add` and `wt config approvals clear`.
+
+## Skipping hooks
+
+Use `--no-verify` to skip all project hooks:
+
+```bash
+wt switch --create temp --no-verify # Skip post-create and post-start
+wt merge --no-verify # Skip pre-commit, pre-merge, post-merge
+wt remove feature --no-verify # Skip pre-remove
+```
+
+## Logging
+
+Background operations log to `.git/wt-logs/` in the main worktree:
+
+| Operation | Log file |
+|-----------|----------|
+| post-start | `{branch}-post-start-{name}.log` |
+| Background removal | `{branch}-remove.log` |
+
+## Example configurations
+
+### Node.js / TypeScript
+
+```toml
+[post-create]
+install = "npm ci"
+
+[post-start]
+dev = "npm run dev"
+
+[pre-commit]
+lint = "npm run lint"
+typecheck = "npm run typecheck"
+
+[pre-merge]
+test = "npm test"
+build = "npm run build"
+```
+
+### Rust
+
+```toml
+[post-create]
+build = "cargo build"
+
+[pre-commit]
+format = "cargo fmt -- --check"
+clippy = "cargo clippy -- -D warnings"
+
+[pre-merge]
+test = "cargo test"
+build = "cargo build --release"
+
+[post-merge]
+install = "cargo install --path ."
+```
+
+### Python (uv)
+
+```toml
+[post-create]
+install = "uv sync"
+
+[pre-commit]
+format = "uv run ruff format --check ."
+lint = "uv run ruff check ."
+
+[pre-merge]
+test = "uv run pytest"
+typecheck = "uv run mypy ."
+```
+
+### Monorepo
+
+```toml
+[post-create]
+frontend = "cd frontend && npm ci"
+backend = "cd backend && cargo build"
+
+[post-start]
+database = "docker-compose up -d postgres"
+
+[pre-merge]
+frontend-tests = "cd frontend && npm test"
+backend-tests = "cd backend && cargo test"
+```
+
+## Common patterns
+
+### Fast dependencies + slow build
+
+Install dependencies blocking, build in background:
+
+```toml
+post-create = "npm install"
+post-start = "npm run build"
+```
+
+### Progressive validation
+
+Quick checks before commit, thorough validation before merge:
+
+```toml
+[pre-commit]
+lint = "npm run lint"
+typecheck = "npm run typecheck"
+
+[pre-merge]
+test = "npm test"
+build = "npm run build"
+```
+
+### Target-specific behavior
+
+Different behavior based on merge target:
+
+```toml
+post-merge = """
+if [ "{{ target }}" = "main" ]; then
+ npm run deploy:production
+elif [ "{{ target }}" = "staging" ]; then
+ npm run deploy:staging
+fi
+"""
+```
+
+### Symlinks and caches
+
+Set up shared resources. The `{{ repo_root }}` variable points to the main worktree:
+
+```toml
+[post-create]
+cache = "ln -sf {{ repo_root }}/node_modules node_modules"
+env = "cp {{ repo_root }}/.env.local .env"
+```
+
+## See also
+
+- [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
+
+---
+
+## Command reference
+
+<!-- ⚠️ AUTO-GENERATED from `wt hook --help-page` — edit cli.rs to update -->
+
+```
+wt hook - Run project hooks
+Usage: wt hook [OPTIONS] <COMMAND>
+
+Commands:
+ post-create Run post-create hooks
+ post-start Run post-start hooks
+ pre-commit Run pre-commit hooks
+ pre-merge Run pre-merge hooks
+ post-merge Run post-merge hooks
+ pre-remove Run pre-remove hooks
+
+Options:
+ -h, --help
+ Print help (see a summary with '-h')
+
+Global Options:
+ -C <path>
+ Working directory for this command
+
+ --config <path>
+ User config file path
+
+ -v, --verbose
+ Show commands and debug info
+```
diff --git a/docs/content/hooks.md b/docs/content/hooks.md
deleted file mode 100644
index 3e099606d..000000000
--- a/docs/content/hooks.md
+++ /dev/null
@@ -1,446 +0,0 @@
-+++
-title = "Hooks"
-weight = 21
-
-[extra]
-group = "Reference"
-+++
-
-Hooks automate setup and validation at worktree lifecycle events. They're defined in `.config/wt.toml` (project config) and run automatically during `wt switch --create`, `wt merge`, and `wt remove`.
-
-## Hook types
-
-| Hook | When | Blocking? | Fail-Fast? | Execution |
-|------|------|-----------|------------|-----------|
-| **post-create** | After worktree created | Yes | No | Sequential |
-| **post-start** | After worktree created | No | No | Parallel (background) |
-| **pre-commit** | Before commit during merge | Yes | Yes | Sequential |
-| **pre-merge** | Before merging to target | Yes | Yes | Sequential |
-| **post-merge** | After successful merge | Yes | No | Sequential |
-| **pre-remove** | Before worktree removed | Yes | Yes | Sequential |
-
-**Blocking**: Command waits for hook to complete before continuing.
-**Fail-fast**: First failure aborts the operation.
-
-## Configuration formats
-
-Hooks can be a single command or multiple named commands. All hooks support both formats in `.config/wt.toml`:
-
-### Single command (string)
-
-```toml
-post-create = "npm install"
-```
-
-### Multiple commands (table)
-
-```toml
-[post-create]
-install = "npm install"
-build = "npm run build"
-```
-
-Named commands appear in output with their labels:
-
-<!-- ⚠️ AUTO-GENERATED-HTML from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_hooks_post_create.snap — edit source to update -->
-
-{% terminal() %}
-<span class="prompt">$</span> <span class="cmd">wt switch --create feature-x</span>
-🔄 <span class=c>Running post-create <b>install</b>:</span>
-<span style='background:var(--bright-white,#fff)'> </span> <span class=d><span style='color:var(--blue,#00a)'>uv</span></span><span class=d> sync</span>
-
- Resolved 24 packages in 145ms
- Installed 24 packages in 1.2s
-✅ <span class=g>Created new worktree for <b>feature-x</b> from <b>main</b> at <b>../repo.feature-x</b></span>
-🔄 <span class=c>Running post-start <b>dev</b>:</span>
-<span style='background:var(--bright-white,#fff)'> </span> <span class=d><span style='color:var(--blue,#00a)'>uv</span></span><span class=d> run dev</span>
-{% end %}
-
-<!-- END AUTO-GENERATED -->
-
-## Template variables
-
-Hooks can use template variables that expand at runtime:
-
-### Basic variables (all hooks)
-
-- `{{ repo }}` — Repository name (e.g., "my-project")
-- `{{ branch }}` — Branch name (slashes replaced with dashes)
-- `{{ worktree }}` — Absolute path to the worktree
-- `{{ worktree_name }}` — Worktree directory name (e.g., "my-project.feature-foo")
-- `{{ repo_root }}` — Absolute path to the repository root
-- `{{ default_branch }}` — Default branch name (e.g., "main")
-
-### Git variables (all hooks)
-
-- `{{ commit }}` — Current HEAD commit SHA (full 40-character hash)
-- `{{ short_commit }}` — Current HEAD commit SHA (short 7-character hash)
-- `{{ remote }}` — Primary remote name (e.g., "origin")
-- `{{ upstream }}` — Upstream tracking branch (e.g., "origin/feature"), if configured
-
-### Merge variables (pre-commit, pre-merge, post-merge)
-
-- `{{ target }}` — Target branch for the merge (e.g., "main")
-
-```toml
-# Tag builds with commit hash
-post-create = "echo '{{ short_commit }}' > .version"
-
-# Reference merge target
-pre-merge = "echo 'Merging {{ branch }} into {{ target }}'"
-```
-
-## JSON context
-
-Hooks receive all context variables as JSON on stdin. This allows hooks written in any language to access worktree information.
-
-```toml
-# .config/wt.toml — paths are relative to the worktree root
-post-create = "./scripts/setup.py"
-```
-
-```python
-#!/usr/bin/env python3
-# scripts/setup.py
-import json, sys
-
-ctx = json.load(sys.stdin)
-print(f"Setting up {ctx['repo']} on branch {ctx['branch']}")
-print(f"Worktree: {ctx['worktree']}")
-print(f"Hook: {ctx['hook_type']} {ctx.get('hook_name', '(unnamed)')}")
-```
-
-The JSON contains all the same fields as template variables, plus hook metadata:
-
-```json
-{
- "repo": "my-project",
- "branch": "feature-foo",
- "worktree": "/path/to/my-project.feature-foo",
- "worktree_name": "my-project.feature-foo",
- "repo_root": "/path/to/my-project",
- "default_branch": "main",
- "commit": "abc123...",
- "short_commit": "abc123",
- "remote": "origin",
- "upstream": "origin/feature-foo",
- "target": "main",
- "hook_type": "post-create",
- "hook_name": "setup"
-}
-```
-
-Optional fields (`default_branch`, `commit`, `short_commit`, `remote`, `upstream`, `target`, `hook_name`) are only present when available.
-
-## Hook details
-
-### post-create
-
-Runs after worktree creation, **blocks until complete**. The worktree switch doesn't finish until these commands succeed.
-
-**Use cases**: Installing dependencies, database migrations, copying environment files — anything that must complete before work begins.
-
-```toml
-[post-create]
-install = "npm ci"
-migrate = "npm run db:migrate"
-env = "cp .env.example .env"
-```
-
-**Behavior**:
-- Commands run sequentially in declaration order
-- Failure shows error but doesn't abort (worktree already created)
-- User cannot work in worktree until complete
-
-### post-start
-
-Runs after worktree creation, **in background**. The worktree switch completes immediately; these run in parallel.
-
-**Use cases**: Long builds, dev servers, file watchers, downloading assets too large for git — anything slow that doesn't need to block.
-
-```toml
-[post-start]
-build = "npm run build"
-server = "npm run dev"
-assets = "./scripts/fetch-large-assets"
-```
-
-**Behavior**:
-- All commands start immediately in parallel
-- Output logged to `.git/wt-logs/{branch}-post-start-{name}.log`
-- Failures don't affect the user session
-
-### pre-commit
-
-Runs before committing during `wt merge`, **fail-fast**. All commands must exit with code 0 for the commit to proceed.
-
-**Use cases**: Formatters, linters, type checking — quick validation before commit.
-
-```toml
-[pre-commit]
-format = "cargo fmt -- --check"
-lint = "cargo clippy -- -D warnings"
-```
-
-**Behavior**:
-- Commands run sequentially
-- First failure aborts the commit
-- Runs for both squash and no-squash merge modes
-
-### pre-merge
-
-Runs before merging to target branch, **fail-fast**. All commands must exit with code 0 for the merge to proceed.
-
-**Use cases**: Tests, security scans, build verification — thorough validation before merge.
-
-```toml
-[pre-merge]
-test = "cargo test"
-build = "cargo build --release"
-```
-
-**Behavior**:
-- Commands run sequentially
-- First failure aborts the merge (commit remains)
-- Runs after commit succeeds, before merge
-
-### post-merge
-
-Runs after successful merge and cleanup, **best-effort**. The merge has already completed and the feature worktree has been removed, so failures are logged but don't abort.
-
-**Use cases**: Deployment, notifications, installing updated binaries — post-merge automation.
-
-```toml
-post-merge = "cargo install --path ."
-```
-
-**Behavior**:
-- Commands run sequentially in the **main worktree**
-- Runs after cleanup completes
-- Failures show errors but don't affect the completed merge
-
-### pre-remove
-
-Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit with code 0 for the removal to proceed.
-
-**Use cases**: Cleanup tasks, saving state, notifying external systems — validation before removal.
-
-```toml
-[pre-remove]
-cleanup = "rm -rf /tmp/cache/{{ branch }}"
-notify = "echo 'Removing {{ branch }}' >> ~/worktree-log.txt"
-```
-
-**Behavior**:
-- Commands run sequentially in the **worktree being removed**
-- First failure aborts the removal (worktree preserved)
-- Runs for both foreground and background removal modes
-- Does **not** run for branch-only removal (no worktree)
-- Use `--no-verify` to skip
-
-## When hooks run during merge
-
-- **pre-commit** — After staging, before squash commit
-- **pre-merge** — After rebase, before merge to target
-- **pre-remove** — Before removing worktree during cleanup (failures abort)
-- **post-merge** — After cleanup completes
-
-See [wt merge](@/merge.md#pipeline) for the complete pipeline.
-
-## Security & approval
-
-Project commands require approval on first run. When a project defines hooks, the first execution prompts for approval:
-
-<!-- ⚠️ AUTO-GENERATED from tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__readme_example_approval_prompt.snap — edit source to update -->
-
-```
-🟡 repo needs approval to execute 3 commands:
-
-⚪ post-create install:
- echo 'Installing dependencies...'
-
-⚪ post-create build:
- echo 'Building project...'
-
-⚪ post-create test:
- echo 'Running tests...'
-
-❓ Allow and remember? [y/N]
-```
-
-<!-- END AUTO-GENERATED -->
-
-**Approval behavior**:
-- Approvals are saved to user config (`~/.config/worktrunk/config.toml`)
-- If a command changes, new approval is required
-- Use `--force` to bypass prompts (useful for CI/automation)
-
-Manage approvals with `wt config approvals`:
-
-```bash
-wt config approvals list # Show all approvals
-wt config approvals clear <repo> # Remove approvals for a repo
-```
-
-## Skipping hooks
-
-Use `--no-verify` to skip all project hooks:
-
-```bash
-wt switch --create temp --no-verify # Skip post-create and post-start
-wt merge --no-verify # Skip pre-commit, pre-merge, post-merge
-wt remove feature --no-verify # Skip pre-remove
-```
-
-## Logging
-
-Background operations log to `.git/wt-logs/` in the main worktree:
-
-| Operation | Log file |
-|-----------|----------|
-| post-start | `{branch}-post-start-{name}.log` |
-| Background removal | `{branch}-remove.log` |
-
-Logs overwrite on repeated runs for the same branch/operation. Stale logs from deleted branches persist but are bounded by branch count.
-
-## Running hooks manually
-
-Use `wt step` to run individual hooks:
-
-```bash
-wt step post-create # Run post-create hooks
-wt step pre-merge # Run pre-merge hooks
-wt step post-merge # Run post-merge hooks
-wt step pre-remove # Run pre-remove hooks
-```
-
-## Example configurations
-
-### Node.js / TypeScript
-
-```toml
-[post-create]
-install = "npm ci"
-
-[post-start]
-dev = "npm run dev"
-
-[pre-commit]
-lint = "npm run lint"
-typecheck = "npm run typecheck"
-
-[pre-merge]
-test = "npm test"
-build = "npm run build"
-```
-
-### Rust
-
-```toml
-[post-create]
-build = "cargo build"
-
-[pre-commit]
-format = "cargo fmt -- --check"
-clippy = "cargo clippy -- -D warnings"
-
-[pre-merge]
-test = "cargo test"
-build = "cargo build --release"
-
-[post-merge]
-install = "cargo install --path ."
-```
-
-### Python (uv)
-
-```toml
-[post-create]
-install = "uv sync"
-
-[pre-commit]
-format = "uv run ruff format --check ."
-lint = "uv run ruff check ."
-
-[pre-merge]
-test = "uv run pytest"
-typecheck = "uv run mypy ."
-```
-
-### Python (pip/venv)
-
-```toml
-[post-create]
-venv = "python -m venv .venv"
-install = ".venv/bin/pip install -r requirements.txt"
-
-[pre-merge]
-format = ".venv/bin/black --check ."
-lint = ".venv/bin/ruff check ."
-test = ".venv/bin/pytest"
-```
-
-### Monorepo
-
-```toml
-[post-create]
-frontend = "cd frontend && npm ci"
-backend = "cd backend && cargo build"
-
-[post-start]
-database = "docker-compose up -d postgres"
-
-[pre-merge]
-frontend-tests = "cd frontend && npm test"
-backend-tests = "cd backend && cargo test"
-integration = "./scripts/integration-tests.sh"
-```
-
-## Common patterns
-
-### Fast dependencies + slow build
-
-Install dependencies blocking (must complete before work), build in background:
-
-```toml
-post-create = "npm install"
-post-start = "npm run build"
-```
-
-### Progressive validation
-
-Quick checks before commit, thorough validation before merge:
-
-```toml
-[pre-commit]
-lint = "npm run lint"
-typecheck = "npm run typecheck"
-
-[pre-merge]
-test = "npm test"
-build = "npm run build"
-```
-
-### Target-specific behavior
-
-Different behavior based on merge target:
-
-```toml
-post-merge = """
-if [ "{{ target }}" = "main" ]; then
- npm run deploy:production
-elif [ "{{ target }}" = "staging" ]; then
- npm run deploy:staging
-fi
-"""
-```
-
-### Symlinks and caches
-
-Set up shared resources that shouldn't be duplicated. The `{{ repo_root }}` variable points to the main worktree:
-
-```toml
-[post-create]
-cache = "ln -sf {{ repo_root }}/node_modules node_modules"
-env = "cp {{ repo_root }}/.env.local .env"
-```
diff --git a/docs/content/merge.md b/docs/content/merge.md
index 9313dd18f..30c91011a 100644
--- a/docs/content/merge.md
+++ b/docs/content/merge.md
@@ -50,7 +50,7 @@ wt merge --no-commit
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 are committed separately 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** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).
+3. **Pre-merge hooks** — Project commands 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** — Project commands run before removing worktree. Failures abort.
6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
diff --git a/docs/content/step.md b/docs/content/step.md
index 483eb14d6..fd42c0d3a 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -8,7 +8,7 @@ group = "Commands"
<!-- ⚠️ AUTO-GENERATED from `wt step --help-page` — edit src/cli.rs to update -->
-Run individual workflow operations: commits, squashes, rebases, pushes, and [hooks](@/hooks.md).
+Run individual git workflow operations: commits, squashes, rebases, and pushes.
## Examples
@@ -18,12 +18,6 @@ Commit with LLM-generated message:
wt step commit
```
-Run pre-merge hooks in CI:
-
-```bash
-wt step pre-merge --force
-```
-
Manual merge workflow with review between steps:
```bash
@@ -36,26 +30,15 @@ wt step push
## Operations
-**Git operations:**
-
- `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` — Push to target branch (default: main)
-**Hooks** — run project commands defined in [`.config/wt.toml`](@/hooks.md):
-
-- `post-create` — After worktree creation (blocking)
-- `post-start` — After worktree creation (background)
-- `pre-commit` — Before committing
-- `pre-merge` — Before pushing to target
-- `post-merge` — After merge cleanup
-
-Hooks receive context as JSON on stdin and support template variables.
-
## See also
- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically
+- [wt hook](@/hook.md) — Run project-defined lifecycle hooks
---
@@ -68,16 +51,10 @@ wt step - Run individual workflow operations
Usage: wt step [OPTIONS] <COMMAND>
Commands:
- commit Commit changes with LLM commit message
- squash Squash commits down to target
- push Push changes to local target branch
- rebase Rebase onto target
- post-create Run post-create hook
- post-start Run post-start hook
- pre-commit Run pre-commit hook
- pre-merge Run pre-merge hook
- post-merge Run post-merge hook
- pre-remove Run pre-remove hook
+ commit Commit changes with LLM commit message
+ squash Squash commits down to target
+ push Push changes to local target branch
+ rebase Rebase onto target
Options:
-h, --help
diff --git a/docs/content/switch.md b/docs/content/switch.md
index 8e368eb62..b5d50a58d 100644
--- a/docs/content/switch.md
+++ b/docs/content/switch.md
@@ -11,7 +11,7 @@ group = "Commands"
Two distinct operations:
- **Switch to existing worktree** — Changes directory, nothing else
-- **Create new worktree** (`--create`) — Creates branch and worktree, runs [hooks](@/hooks.md)
+- **Create new worktree** (`--create`) — Creates branch and worktree, runs [hooks](@/hook.md)
## Examples
@@ -30,9 +30,9 @@ With `--create`, worktrunk:
1. Creates branch from `--base` (defaults to default branch)
2. Creates worktree at configured path
-3. Runs [post-create hooks](@/hooks.md#post-create) (blocking)
+3. Runs [post-create hooks](@/hook.md#post-create) (blocking)
4. Switches to new directory
-5. Spawns [post-start hooks](@/hooks.md#post-start) (background)
+5. Spawns [post-start hooks](@/hook.md#post-start) (background)
```bash
wt switch --create api-refactor
diff --git a/docs/content/why-worktrunk.md b/docs/content/why-worktrunk.md
index 19c62e5e2..fc98f8214 100644
--- a/docs/content/why-worktrunk.md
+++ b/docs/content/why-worktrunk.md
@@ -35,7 +35,7 @@ Worktrunk makes worktrees easy to use — branch-based navigation, unified statu
**Workflow automation:**
-- **[Lifecycle hooks](@/hooks.md)** — run commands on create, pre-merge, post-merge
+- **[Lifecycle hooks](@/hook.md)** — run commands on create, pre-merge, post-merge
- **[LLM commit messages](@/llm-commits.md)** — generate commit messages from diffs via [llm](https://llm.datasette.io/)
- **[Merge workflow](@/merge.md)** — squash, rebase, merge, clean up in one command
- ...and lots more.
@@ -110,7 +110,7 @@ $ wt config shell install
## Next steps
- Learn the core commands: [wt switch](@/switch.md), [wt list](@/list.md), [wt merge](@/merge.md), [wt remove](@/remove.md)
-- Set up [project hooks](@/hooks.md) for automated setup
+- Set up [project hooks](@/hook.md) for automated setup
- Explore [LLM commit messages](@/llm-commits.md), [fzf-like picker](@/select.md), [Claude Code integration](@/claude-code.md)
- Run `wt --help` or `wt <command> --help` for quick CLI reference
diff --git a/src/cli.rs b/src/cli.rs
index 101e3f9e4..63aa1fbaa 100644
--- a/src/cli.rs
+++ b/src/cli.rs
@@ -611,8 +611,14 @@ pub enum StepCommand {
#[arg(add = crate::completion::branch_value_completer())]
target: Option<String>,
},
+}
- /// Run post-create hook
+/// Run project hooks
+#[derive(Subcommand)]
+pub enum HookCommand {
+ /// Run post-create hooks
+ ///
+ /// Executes blocking commands after worktree creation.
PostCreate {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -623,7 +629,9 @@ pub enum StepCommand {
force: bool,
},
- /// Run post-start hook
+ /// Run post-start hooks
+ ///
+ /// Executes background commands after worktree creation.
PostStart {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -634,7 +642,9 @@ pub enum StepCommand {
force: bool,
},
- /// Run pre-commit hook
+ /// Run pre-commit hooks
+ ///
+ /// Executes validation commands before committing.
PreCommit {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -645,7 +655,9 @@ pub enum StepCommand {
force: bool,
},
- /// Run pre-merge hook
+ /// Run pre-merge hooks
+ ///
+ /// Executes validation commands before merging.
PreMerge {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -656,7 +668,9 @@ pub enum StepCommand {
force: bool,
},
- /// Run post-merge hook
+ /// Run post-merge hooks
+ ///
+ /// Executes commands after successful merge.
PostMerge {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -667,7 +681,9 @@ pub enum StepCommand {
force: bool,
},
- /// Run pre-remove hook
+ /// Run pre-remove hooks
+ ///
+ /// Executes cleanup commands before worktree removal.
PreRemove {
/// Run only this command from hook config
#[arg(add = crate::completion::hook_command_name_completer())]
@@ -839,7 +855,7 @@ test = "npm test"
lint = "npm run lint"
```
-See [Hooks](@/hooks.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hooks.md#json-context).
+See [wt hook](@/hook.md) for complete documentation on hook types, execution order, template variables, and [JSON context](@/hook.md#json-context).
## Shell integration
@@ -917,7 +933,7 @@ WORKTRUNK_COMMIT_GENERATION__ARGS="test: automated commit" \
/// Run individual workflow operations
#[command(
name = "step",
- after_long_help = r#"Run individual workflow operations: commits, squashes, rebases, pushes, and [hooks](@/hooks.md).
+ after_long_help = r#"Run individual git workflow operations: commits, squashes, rebases, and pushes.
## Examples
@@ -927,12 +943,6 @@ Commit with LLM-generated message:
wt step commit
```
-Run pre-merge hooks in CI:
-
-```console
-wt step pre-merge --force
-```
-
Manual merge workflow with review between steps:
```console
@@ -945,26 +955,15 @@ wt step push
## Operations
-**Git operations:**
-
- `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` — Push to target branch (default: main)
-**Hooks** — run project commands defined in [`.config/wt.toml`](@/hooks.md):
-
-- `post-create` — After worktree creation (blocking)
-- `post-start` — After worktree creation (background)
-- `pre-commit` — Before committing
-- `pre-merge` — Before pushing to target
-- `post-merge` — After merge cleanup
-
-Hooks receive context as JSON on stdin and support template variables.
-
## See also
- [wt merge](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically
+- [wt hook](@/hook.md) — Run project-defined lifecycle hooks
"#
)]
Step {
@@ -972,6 +971,336 @@ Hooks receive context as JSON on stdin and support template variables.
action: StepCommand,
},
+ /// Run project hooks
+ #[command(
+ name = "hook",
+ after_long_help = r#"Run project-defined lifecycle hooks from `.config/wt.toml`.
+
+Hooks are commands that run automatically during worktree operations (`wt switch --create`, `wt merge`, `wt remove`). Use `wt hook` to run them manually for testing or CI.
+
+## Examples
+
+Run pre-merge hooks (for testing):
+
+```console
+wt hook pre-merge
+```
+
+Run in CI (skip approval prompts):
+
+```console
+wt hook pre-merge --force
+```
+
+## Hook types
+
+| Hook | When | Blocking | Fail-fast | Execution |
+|------|------|----------|-----------|-----------|
+| `post-create` | After worktree created | Yes | No | Sequential |
+| `post-start` | After worktree created | No | No | Parallel (background) |
+| `pre-commit` | Before commit during merge | Yes | Yes | Sequential |
+| `pre-merge` | Before merging to target | Yes | Yes | Sequential |
+| `post-merge` | After successful merge | Yes | No | Sequential |
+| `pre-remove` | Before worktree removed | Yes | Yes | Sequential |
+
+**Blocking**: Command waits for hook to complete before continuing.
+**Fail-fast**: First failure aborts the operation.
+
+## Configuration formats
+
+Hooks can be a single command or multiple named commands in `.config/wt.toml`:
+
+**Single command (string):**
+
+```toml
+post-create = "npm install"
+```
+
+**Multiple commands (table):**
+
+```toml
+[post-create]
+install = "npm install"
+build = "npm run build"
+```
+
+Named commands run sequentially in declaration order and appear in output with their labels.
+
+## Template variables
+
+Hooks can use template variables that expand at runtime.
+
+**All hooks:**
+
+| Variable | Example | Description |
+|----------|---------|-------------|
+| `{{ repo }}` | my-project | Repository name |
+| `{{ branch }}` | feature-foo | Branch name |
+| `{{ worktree }}` | /path/to/worktree | Absolute worktree path |
+| `{{ worktree_name }}` | my-project.feature-foo | Worktree directory name |
+| `{{ repo_root }}` | /path/to/main | Repository root path |
+| `{{ default_branch }}` | main | Default branch name |
+| `{{ commit }}` | a1b2c3d4e5f6... | Full HEAD commit SHA |
+| `{{ short_commit }}` | a1b2c3d | Short HEAD commit SHA |
+| `{{ remote }}` | origin | Primary remote name |
+| `{{ upstream }}` | origin/feature | Upstream tracking branch |
+
+**Merge hooks** (`pre-commit`, `pre-merge`, `post-merge`):
+
+| Variable | Example | Description |
+|----------|---------|-------------|
+| `{{ target }}` | main | Target branch for merge |
+
+## Hook details
+
+### post-create
+
+Runs after worktree creation, **blocks until complete**. The worktree switch doesn't finish until these commands succeed.
+
+**Use cases**: Installing dependencies, database migrations, copying environment files.
+
+```toml
+[post-create]
+install = "npm ci"
+migrate = "npm run db:migrate"
+env = "cp .env.example .env"
+```
+
+### post-start
+
+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"
+```
+
+Output logged to `.git/wt-logs/{branch}-post-start-{name}.log`.
+
+### pre-commit
+
+Runs before committing during `wt merge`, **fail-fast**. All commands must exit 0 for the commit to proceed.
+
+**Use cases**: Formatters, linters, type checking.
+
+```toml
+[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]
+test = "cargo test"
+build = "cargo build --release"
+```
+
+### post-merge
+
+Runs after successful merge in the **main worktree**, **best-effort**. Failures are logged but don't abort.
+
+**Use cases**: Deployment, notifications, installing updated binaries.
+
+```toml
+post-merge = "cargo install --path ."
+```
+
+### pre-remove
+
+Runs before worktree removal during `wt remove`, **fail-fast**. All commands must exit 0 for removal to proceed.
+
+**Use cases**: Cleanup tasks, saving state, notifying external systems.
+
+```toml
+[pre-remove]
+cleanup = "rm -rf /tmp/cache/{{ branch }}"
+```
+
+## When hooks run during merge
+
+- **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
+
+See [wt merge](@/merge.md#pipeline) for the complete pipeline.
+
+## Security & approval
+
+Project commands require approval on first run:
+
+```
+🟡 repo needs approval to execute 3 commands:
+
+⚪ post-create install:
+ echo 'Installing dependencies...'
+
+❓ Allow and remember? [y/N]
+```
+
+- Approvals are saved to user config (`~/.config/worktrunk/config.toml`)
+- If a command changes, new approval is required
+- Use `--force` to bypass prompts (useful for CI/automation)
+
+Manage approvals with `wt config approvals add` and `wt config approvals clear`.
+
+## Skipping hooks
+
+Use `--no-verify` to skip all project hooks:
+
+```console
+wt switch --create temp --no-verify # Skip post-create and post-start
+wt merge --no-verify # Skip pre-commit, pre-merge, post-merge
+wt remove feature --no-verify # Skip pre-remove
+```
+
+## Logging
+
+Background operations log to `.git/wt-logs/` in the main worktree:
+
+| Operation | Log file |
+|-----------|----------|
+| post-start | `{branch}-post-start-{name}.log` |
+| Background removal | `{branch}-remove.log` |
+
+## Example configurations
+
+### Node.js / TypeScript
+
+```toml
+[post-create]
+install = "npm ci"
+
+[post-start]
+dev = "npm run dev"
+
+[pre-commit]
+lint = "npm run lint"
+typecheck = "npm run typecheck"
+
+[pre-merge]
+test = "npm test"
+build = "npm run build"
+```
+
+### Rust
+
+```toml
+[post-create]
+build = "cargo build"
+
+[pre-commit]
+format = "cargo fmt -- --check"
+clippy = "cargo clippy -- -D warnings"
+
+[pre-merge]
+test = "cargo test"
+build = "cargo build --release"
+
+[post-merge]
+install = "cargo install --path ."
+```
+
+### Python (uv)
+
+```toml
+[post-create]
+install = "uv sync"
+
+[pre-commit]
+format = "uv run ruff format --check ."
+lint = "uv run ruff check ."
+
+[pre-merge]
+test = "uv run pytest"
+typecheck = "uv run mypy ."
+```
+
+### Monorepo
+
+```toml
+[post-create]
+frontend = "cd frontend && npm ci"
+backend = "cd backend && cargo build"
+
+[post-start]
+database = "docker-compose up -d postgres"
+
+[pre-merge]
+frontend-tests = "cd frontend && npm test"
+backend-tests = "cd backend && cargo test"
+```
+
+## Common patterns
+
+### Fast dependencies + slow build
+
+Install dependencies blocking, build in background:
+
+```toml
+post-create = "npm install"
+post-start = "npm run build"
+```
+
+### Progressive validation
+
+Quick checks before commit, thorough validation before merge:
+
+```toml
+[pre-commit]
+lint = "npm run lint"
+typecheck = "npm run typecheck"
+
+[pre-merge]
+test = "npm test"
+build = "npm run build"
+```
+
+### Target-specific behavior
+
+Different behavior based on merge target:
+
+```toml
+post-merge = """
+if [ "{{ target }}" = "main" ]; then
+ npm run deploy:production
+elif [ "{{ target }}" = "staging" ]; then
+ npm run deploy:staging
+fi
+"""
+```
+
+### Symlinks and caches
+
+Set up shared resources. The `{{ repo_root }}` variable points to the main worktree:
+
+```toml
+[post-create]
+cache = "ln -sf {{ repo_root }}/node_modules node_modules"
+env = "cp {{ repo_root }}/.env.local .env"
+```
+
+## See also
+
+- [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
+"#
+ )]
+ Hook {
+ #[command(subcommand)]
+ action: HookCommand,
+ },
+
/// Interactive worktree selector
///
/// Toggle preview tabs with 1/2/3 keys. Toggle preview visibility with alt-p.
@@ -1183,7 +1512,7 @@ wt list --format=json | jq '.[] | select(.status.main_divergence == "Ahead")'
#[command(after_long_help = r#"Two distinct operations:
- **Switch to existing worktree** — Changes directory, nothing else
-- **Create new worktree** (`--create`) — Creates branch and worktree, runs [hooks](@/hooks.md)
+- **Create new worktree** (`--create`) — Creates branch and worktree, runs [hooks](@/hook.md)
## Examples
@@ -1202,9 +1531,9 @@ With `--create`, worktrunk:
1. Creates branch from `--base` (defaults to default branch)
2. Creates worktree at configured path
-3. Runs [post-create hooks](@/hooks.md#post-create) (blocking)
+3. Runs [post-create hooks](@/hook.md#post-create) (blocking)
4. Switches to new directory
-5. Spawns [post-start hooks](@/hooks.md#post-start) (background)
+5. Spawns [post-start hooks](@/hook.md#post-start) (background)
```console
wt switch --create api-refactor
@@ -1400,7 +1729,7 @@ wt merge --no-commit
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 are committed separately 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** — Project commands run after rebase, before merge. Failures abort. See [Hooks](@/hooks.md).
+3. **Pre-merge hooks** — Project commands 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** — Project commands run before removing worktree. Failures abort.
6. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree.
diff --git a/src/commands/CLAUDE.md b/src/commands/CLAUDE.md
index 749ace275..a0a116952 100644
--- a/src/commands/CLAUDE.md
+++ b/src/commands/CLAUDE.md
@@ -104,7 +104,7 @@ Each command page should follow this order:
1. **Intro paragraph** — One or two sentences: what the command does and when to use it. Integrate key behavioral distinctions (e.g., "Switching to an existing worktree is just a directory change. With `--create`, hooks run.")
2. **Examples** — Common use cases with brief labels, immediately after intro
3. **Feature sections** — Deeper explanation of major features (e.g., "Creating worktrees", "Shortcuts")
-4. **Hooks** — Brief summary with link to `/hooks/` for details
+4. **Hooks** — Brief summary with link to `/hook/` for details
5. **Technical details** — Implementation details like argument resolution, pushed to the bottom
6. **Command reference** — Auto-generated from `--help-page`, always last
@@ -114,7 +114,7 @@ Each command page should follow this order:
- **Spaced em-dashes** — "instant — no stashing" not "instant—no stashing"
- **No second person** — Describe behavior, don't address the reader
- **Concrete examples** — Real commands, actual output, specific scenarios
-- **Link to dedicated pages** — Don't duplicate content from `/hooks/`, `/configuration/`, etc.
+- **Link to dedicated pages** — Don't duplicate content from `/hook/`, `/configuration/`, etc.
### What to Avoid
diff --git a/src/commands/standalone.rs b/src/commands/standalone.rs
index 6fa56fe72..bc3510b0c 100644
--- a/src/commands/standalone.rs
+++ b/src/commands/standalone.rs
@@ -15,7 +15,7 @@ use super::merge::{
use super::project_config::collect_commands_for_hooks;
use super::repository_ext::RepositoryCliExt;
-/// Handle `wt step hook` command
+/// Handle `wt hook` command
pub fn handle_standalone_run_hook(
hook_type: HookType,
force: bool,
diff --git a/src/completion.rs b/src/completion.rs
index 0414fac96..c20236a90 100644
--- a/src/completion.rs
+++ b/src/completion.rs
@@ -288,8 +288,10 @@ fn adjust_completion_command(cmd: Command) -> Command {
.mut_subcommand("rebase", |rebase| {
rebase.mut_arg("target", |arg| arg.last(true))
})
- // Hook subcommands - allow name after --force
- .mut_subcommand("post-create", |c| c.mut_arg("name", |arg| arg.last(true)))
+ })
+ .mut_subcommand("hook", |hook| {
+ // Hook subcommands - allow name after --force
+ hook.mut_subcommand("post-create", |c| c.mut_arg("name", |arg| arg.last(true)))
.mut_subcommand("post-start", |c| c.mut_arg("name", |arg| arg.last(true)))
.mut_subcommand("pre-commit", |c| c.mut_arg("name", |arg| arg.last(true)))
.mut_subcommand("pre-merge", |c| c.mut_arg("name", |arg| arg.last(true)))
diff --git a/src/main.rs b/src/main.rs
index b2e33237f..61250f01b 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -37,7 +37,7 @@ use commands::{
use output::{execute_user_command, handle_remove_output, handle_switch_output};
use cli::{
- ApprovalsCommand, CacheCommand, Cli, Commands, ConfigCommand, ConfigShellCommand,
+ ApprovalsCommand, CacheCommand, Cli, Commands, ConfigCommand, ConfigShellCommand, HookCommand,
ListSubcommand, StepCommand, VarCommand,
};
use worktrunk::HookType;
@@ -821,22 +821,24 @@ fn main() {
}
})
}
- StepCommand::PostCreate { name, force } => {
+ },
+ Commands::Hook { action } => match action {
+ HookCommand::PostCreate { name, force } => {
handle_standalone_run_hook(HookType::PostCreate, force, name.as_deref())
}
- StepCommand::PostStart { name, force } => {
+ HookCommand::PostStart { name, force } => {
handle_standalone_run_hook(HookType::PostStart, force, name.as_deref())
}
- StepCommand::PreCommit { name, force } => {
+ HookCommand::PreCommit { name, force } => {
handle_standalone_run_hook(HookType::PreCommit, force, name.as_deref())
}
- StepCommand::PreMerge { name, force } => {
+ HookCommand::PreMerge { name, force } => {
handle_standalone_run_hook(HookType::PreMerge, force, name.as_deref())
}
- StepCommand::PostMerge { name, force } => {
+ HookCommand::PostMerge { name, force } => {
handle_standalone_run_hook(HookType::PostMerge, force, name.as_deref())
}
- StepCommand::PreRemove { name, force } => {
+ HookCommand::PreRemove { name, force } => {
handle_standalone_run_hook(HookType::PreRemove, force, name.as_deref())
}
},
diff --git a/src/md_help.rs b/src/md_help.rs
index 37c5c074c..76e636a51 100644
--- a/src/md_help.rs
+++ b/src/md_help.rs
@@ -361,8 +361,8 @@ mod tests {
fn test_render_inline_formatting_strips_links() {
assert_eq!(render_inline_formatting("[text](url)"), "text");
assert_eq!(
- render_inline_formatting("See [Hooks](@/hooks.md) for details"),
- "See Hooks for details"
+ render_inline_formatting("See [wt hook](@/hook.md) for details"),
+ "See wt hook for details"
);
}
diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rs
index fac945c4a..a5cb67f42 100644
--- a/tests/integration_tests/approval_ui.rs
+++ b/tests/integration_tests/approval_ui.rs
@@ -241,7 +241,7 @@ test = "echo 'Running tests...'"
fn snapshot_run_hook(test_name: &str, repo: &TestRepo, hook_type: &str, approve: bool) {
let settings = setup_snapshot_settings(repo);
settings.bind(|| {
- let mut cmd = make_snapshot_cmd(repo, "step", &[hook_type], None);
+ let mut cmd = make_snapshot_cmd(repo, "hook", &[hook_type], None);
cmd.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped());
@@ -271,9 +271,9 @@ fn snapshot_run_hook(test_name: &str, repo: &TestRepo, hook_type: &str, approve:
});
}
-/// Test that `wt step pre-merge` requires approval (security boundary test)
+/// Test that `wt hook pre-merge` requires approval (security boundary test)
///
-/// This verifies the fix for the security issue where step hooks were bypassing approval.
+/// This verifies the fix for the security issue where hooks were bypassing approval.
/// Before the fix, pre-merge hooks ran with auto_trust=true, skipping approval prompts.
#[test]
fn test_run_hook_pre_merge_requires_approval() {
@@ -293,9 +293,9 @@ fn test_run_hook_pre_merge_requires_approval() {
);
}
-/// Test that `wt step post-merge` requires approval (security boundary test)
+/// Test that `wt hook post-merge` requires approval (security boundary test)
///
-/// This verifies the fix for the security issue where step hooks were bypassing approval.
+/// This verifies the fix for the security issue where hooks were bypassing approval.
/// Before the fix, post-merge hooks ran with auto_trust=true, skipping approval prompts.
#[test]
fn test_run_hook_post_merge_requires_approval() {
@@ -362,11 +362,11 @@ fn test_force_bypasses_tty_check() {
/// Test that `{{ target }}` is the current branch when running standalone
///
-/// When `wt step post-merge` runs standalone (not via `wt merge`), the `{{ target }}`
+/// When `wt hook post-merge` runs standalone (not via `wt merge`), the `{{ target }}`
/// variable should be the current branch, not always the default branch.
/// This allows hooks to behave correctly when testing from feature worktrees.
#[test]
-fn test_step_post_merge_target_is_current_branch() {
+fn test_hook_post_merge_target_is_current_branch() {
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -381,15 +381,15 @@ fn test_step_post_merge_target_is_current_branch() {
// Run the hook with --force to skip approval
let output = Command::new(env!("CARGO_BIN_EXE_wt"))
- .args(["step", "post-merge", "--force"])
+ .args(["hook", "post-merge", "--force"])
.current_dir(repo.root_path())
.env("NO_COLOR", "1")
.output()
- .expect("Failed to run wt step post-merge");
+ .expect("Failed to run wt hook post-merge");
assert!(
output.status.success(),
- "wt step post-merge failed: {}",
+ "wt hook post-merge failed: {}",
String::from_utf8_lossy(&output.stderr)
);
@@ -406,7 +406,7 @@ fn test_step_post_merge_target_is_current_branch() {
/// Test that `{{ target }}` is the current branch for pre-merge standalone
#[test]
-fn test_step_pre_merge_target_is_current_branch() {
+fn test_hook_pre_merge_target_is_current_branch() {
let repo = TestRepo::new();
repo.commit("Initial commit");
@@ -421,15 +421,15 @@ fn test_step_pre_merge_target_is_current_branch() {
// Run the hook with --force to skip approval
let output = Command::new(env!("CARGO_BIN_EXE_wt"))
- .args(["step", "pre-merge", "--force"])
+ .args(["hook", "pre-merge", "--force"])
.current_dir(repo.root_path())
.env("NO_COLOR", "1")
.output()
- .expect("Failed to run wt step pre-merge");
+ .expect("Failed to run wt hook pre-merge");
assert!(
output.status.success(),
- "wt step pre-merge failed: {}",
+ "wt hook pre-merge failed: {}",
String::from_utf8_lossy(&output.stderr)
);
@@ -462,15 +462,15 @@ build = "echo 'running build' > build.txt"
// Run only the "lint" command with --force to skip approval
let output = Command::new(env!("CARGO_BIN_EXE_wt"))
- .args(["step", "pre-merge", "lint", "--force"])
+ .args(["hook", "pre-merge", "lint", "--force"])
.current_dir(repo.root_path())
.env("NO_COLOR", "1")
.output()
- .expect("Failed to run wt step pre-merge lint");
+ .expect("Failed to run wt hook pre-merge lint");
assert!(
output.status.success(),
- "wt step pre-merge lint failed: {}",
+ "wt hook pre-merge lint failed: {}",
String::from_utf8_lossy(&output.stderr)
);
@@ -509,7 +509,7 @@ lint = "echo 'lint'"
settings.bind(|| {
let mut cmd = make_snapshot_cmd(
&repo,
- "step",
+ "hook",
&["pre-merge", "nonexistent", "--force"],
None,
);
@@ -530,7 +530,7 @@ fn test_step_hook_name_filter_on_unnamed_command() {
// Run with a name filter on a hook that has no named commands
let settings = setup_snapshot_settings(&repo);
settings.bind(|| {
- let mut cmd = make_snapshot_cmd(&repo, "step", &["pre-merge", "test", "--force"], None);
+ let mut cmd = make_snapshot_cmd(&repo, "hook", &["pre-merge", "test", "--force"], None);
assert_cmd_snapshot!("step_hook_name_filter_on_unnamed", cmd);
});
}
@@ -553,15 +553,15 @@ third = "echo 'third' >> output.txt"
// Run without name filter (all commands should run)
let output = Command::new(env!("CARGO_BIN_EXE_wt"))
- .args(["step", "pre-merge", "--force"])
+ .args(["hook", "pre-merge", "--force"])
.current_dir(repo.root_path())
.env("NO_COLOR", "1")
.output()
- .expect("Failed to run wt step pre-merge");
+ .expect("Failed to run wt hook pre-merge");
assert!(
output.status.success(),
- "wt step pre-merge failed: {}",
+ "wt hook pre-merge failed: {}",
String::from_utf8_lossy(&output.stderr)
);
diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rs
index d90aadd27..e83008a75 100644
--- a/tests/integration_tests/completion.rs
+++ b/tests/integration_tests/completion.rs
@@ -692,16 +692,33 @@ fn test_complete_step_subcommands() {
let temp = TestRepo::new();
temp.commit("initial");
- // Test 1: No input - shows all step subcommands
+ // Test: No input - shows all step subcommands (git operations only)
let output = temp.completion_cmd(&["wt", "step", ""]).output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
let subcommands = value_suggestions(&stdout);
- // Operations
+ // Git operations
assert!(subcommands.contains(&"commit"), "Missing commit");
assert!(subcommands.contains(&"squash"), "Missing squash");
assert!(subcommands.contains(&"push"), "Missing push");
assert!(subcommands.contains(&"rebase"), "Missing rebase");
+ assert_eq!(
+ subcommands.len(),
+ 4,
+ "Should have exactly 4 step subcommands (git operations)"
+ );
+}
+
+#[test]
+fn test_complete_hook_subcommands() {
+ let temp = TestRepo::new();
+ temp.commit("initial");
+
+ // Test 1: No input - shows all hook subcommands
+ let output = temp.completion_cmd(&["wt", "hook", ""]).output().unwrap();
+ assert!(output.status.success());
+ let stdout = String::from_utf8_lossy(&output.stdout);
+ let subcommands = value_suggestions(&stdout);
// Hook types
assert!(subcommands.contains(&"post-create"), "Missing post-create");
assert!(subcommands.contains(&"post-start"), "Missing post-start");
@@ -711,12 +728,12 @@ fn test_complete_step_subcommands() {
assert!(subcommands.contains(&"pre-remove"), "Missing pre-remove");
assert_eq!(
subcommands.len(),
- 10,
- "Should have exactly 10 step subcommands"
+ 6,
+ "Should have exactly 6 hook subcommands"
);
// Test 2: Partial input "po" - filters to post-* subcommands
- let output = temp.completion_cmd(&["wt", "step", "po"]).output().unwrap();
+ let output = temp.completion_cmd(&["wt", "hook", "po"]).output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8_lossy(&output.stdout);
let subcommands = value_suggestions(&stdout);
diff --git a/tests/integration_tests/readme_sync.rs b/tests/integration_tests/readme_sync.rs
index 4086aedb8..b0746b8df 100644
--- a/tests/integration_tests/readme_sync.rs
+++ b/tests/integration_tests/readme_sync.rs
@@ -1017,7 +1017,6 @@ fn test_docs_quickstart_examples_are_in_sync() {
// Process all docs files with AUTO-GENERATED-HTML markers
let doc_files = [
"docs/content/why-worktrunk.md",
- "docs/content/hooks.md",
"docs/content/claude-code.md",
];
@@ -1050,7 +1049,7 @@ fn test_docs_quickstart_examples_are_in_sync() {
/// Command pages generated via `wt <cmd> --help-page`
const COMMAND_PAGES: &[&str] = &[
- "switch", "list", "merge", "remove", "select", "config", "step",
+ "switch", "list", "merge", "remove", "select", "config", "step", "hook",
];
#[test]
diff --git a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap
index e99a9f780..3ad188b47 100644
--- a/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap
+++ b/tests/integration_tests/snapshots/integration__integration_tests__shell_wrapper__tests__source_flag_error_passthrough.snap
@@ -4,6 +4,8 @@ expression: output.normalized()
---
error: unrecognized subcommand 'foo'
+ tip: a similar subcommand exists: 'hook'
+
Usage: wt [OPTIONS] [COMMAND]
For more information, try '--help'.
diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
index 664471707..9357d7a94 100644
--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap
@@ -156,7 +156,7 @@ Create .config/wt.toml in the repository root:
test = "npm test"
lint = "npm run lint"
-See Hooks for complete documentation on hook types, execution order, template variables, and JSON context.
+See wt hook for complete documentation on hook types, execution order, template variables, and JSON context.
Shell integration
diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
index 4b1242471..c9291bf9f 100644
--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap
@@ -95,7 +95,7 @@ Skip git operations, only run hooks and push:
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 are committed separately 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 — Project commands run after rebase, before merge. Failures abort. See Hooks.
+3. Pre-merge hooks — Project commands run after rebase, before merge. Failures abort. See wt hook.
4. Merge — Fast-forward merge to the target branch. Non-fast-forward merges are rejected.
5. Pre-remove hooks — Project commands run before removing worktree. Failures abort.
6. Cleanup — Removes the worktree and branch. Use --no-remove to keep the worktree.
diff --git a/tests/snapshots/integration__integration_tests__help__help_no_args.snap b/tests/snapshots/integration__integration_tests__help__help_no_args.snap
index 78c69abff..7520a4fab 100644
--- a/tests/snapshots/integration__integration_tests__help__help_no_args.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_no_args.snap
@@ -21,6 +21,7 @@ Usage: wt [OPTIONS] [COMMAND]
Commands:
config Manage configuration and shell integration
step Run individual workflow operations
+ hook Run project hooks
select Interactive worktree selector
list List worktrees and optionally branches
switch Switch to a worktree
diff --git a/tests/snapshots/integration__integration_tests__help__help_root_long.snap b/tests/snapshots/integration__integration_tests__help__help_root_long.snap
index 63a54e71e..dc1d1cdac 100644
--- a/tests/snapshots/integration__integration_tests__help__help_root_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_root_long.snap
@@ -22,6 +22,7 @@ Usage: wt [OPTIONS] [COMMAND]
Commands:
config Manage configuration and shell integration
step Run individual workflow operations
+ hook Run project hooks
select Interactive worktree selector
list List worktrees and optionally branches
switch Switch to a worktree
diff --git a/tests/snapshots/integration__integration_tests__help__help_root_short.snap b/tests/snapshots/integration__integration_tests__help__help_root_short.snap
index 6ccd3d7d1..209a5e986 100644
--- a/tests/snapshots/integration__integration_tests__help__help_root_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_root_short.snap
@@ -22,6 +22,7 @@ Usage: wt [OPTIONS] [COMMAND]
Commands:
config Manage configuration and shell integration
step Run individual workflow operations
+ hook Run project hooks
select Interactive worktree selector
list List worktrees and optionally branches
switch Switch to a worktree
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
index d2899e287..b2bd24af0 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap
@@ -21,16 +21,10 @@ wt step - Run individual workflow operations
Usage: wt step [OPTIONS] <COMMAND>
Commands:
- commit Commit changes with LLM commit message
- squash Squash commits down to target
- push Push changes to local target branch
- rebase Rebase onto target
- post-create Run post-create hook
- post-start Run post-start hook
- pre-commit Run pre-commit hook
- pre-merge Run pre-merge hook
- post-merge Run post-merge hook
- pre-remove Run pre-remove hook
+ commit Commit changes with LLM commit message
+ squash Squash commits down to target
+ push Push changes to local target branch
+ rebase Rebase onto target
Options:
-h, --help
@@ -46,7 +40,7 @@ Usage: wt step [OPTIONS] <COMMAND>
-v, --verbose
Show commands and debug info
-Run individual workflow operations: commits, squashes, rebases, pushes, and hooks.
+Run individual git workflow operations: commits, squashes, rebases, and pushes.
Examples
@@ -54,10 +48,6 @@ Commit with LLM-generated message:
wt step commit
-Run pre-merge hooks in CI:
-
- wt step pre-merge --force
-
Manual merge workflow with review between steps:
wt step commit
@@ -68,23 +58,12 @@ Manual merge workflow with review between steps:
Operations
-Git operations:
-
- commit — Stage and commit with LLM-generated message
- squash — Squash all branch commits into one with LLM-generated message
- rebase — Rebase onto target branch
- push — Push to target branch (default: main)
-Hooks — run project commands defined in `.config/wt.toml`:
-
-- post-create — After worktree creation (blocking)
-- post-start — After worktree creation (background)
-- pre-commit — Before committing
-- pre-merge — Before pushing to target
-- post-merge — After merge cleanup
-
-Hooks receive context as JSON on stdin and support template variables.
-
See also
- wt merge — Runs commit → squash → rebase → hooks → push → cleanup automatically
+- wt hook — Run project-defined lifecycle hooks
diff --git a/tests/snapshots/integration__integration_tests__help__help_step_short.snap b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
index 730b2db10..0a29c08a3 100644
--- a/tests/snapshots/integration__integration_tests__help__help_step_short.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_step_short.snap
@@ -21,16 +21,10 @@ wt step - Run individual workflow operations
Usage: wt step [OPTIONS] <COMMAND>
Commands:
- commit Commit changes with LLM commit message
- squash Squash commits down to target
- push Push changes to local target branch
- rebase Rebase onto target
- post-create Run post-create hook
- post-start Run post-start hook
- pre-commit Run pre-commit hook
- pre-merge Run pre-merge hook
- post-merge Run post-merge hook
- pre-remove Run pre-remove hook
+ commit Commit changes with LLM commit message
+ squash Squash commits down to target
+ push Push changes to local target branch
+ rebase Rebase onto target
Options:
-h, --help Print help (see more with '--help')