Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(alias): dispatch aliases from top-level `wt <name>` (#2266)
Maximilian Roosa1be5645c488
diff --git a/README.md b/README.mdindex 4041ac70e..7b59830a0 100644--- a/README.md+++ b/README.md@@ -91,7 +91,7 @@ git branch -d feat</pre></td>- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch- **[Dev server per worktree](https://worktrunk.dev/hook/#dev-servers)** — `hash_port` template filter gives each worktree a unique port-- **[Aliases](https://worktrunk.dev/step/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt step <name>` commands and branch-scoped state for hook templates+- **[Aliases](https://worktrunk.dev/extending/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt <name>` commands and branch-scoped state for hook templates- ...and **[lots more](#next-steps)**A demo with some advanced features:diff --git a/dev/config.example.toml b/dev/config.example.tomlindex 2b7dd2e93..25a3ec075 100644--- a/dev/config.example.toml+++ b/dev/config.example.toml@@ -127,7 +127,7 @@## ### Aliases#-# Command templates that run with `wt step <name>`. See `wt step` aliases (https://worktrunk.dev/step/#aliases) for usage and flags.+# Command templates that run as `wt <name>`. See Aliases (https://worktrunk.dev/extending/#aliases) for usage and flags.## [aliases]# greet = "echo Hello from {{ branch }}"diff --git a/dev/wt.example.toml b/dev/wt.example.tomlindex 8f871281f..831b76357 100644--- a/dev/wt.example.toml+++ b/dev/wt.example.toml@@ -38,7 +38,7 @@## ## Aliases#-# Command templates that run with `wt step <name>`. See `wt step` aliases (https://worktrunk.dev/step/#aliases) for usage and flags.+# Command templates that run as `wt <name>`. See Aliases (https://worktrunk.dev/extending/#aliases) for usage and flags.## [aliases]# deploy = "make deploy BRANCH={{ branch }}"diff --git a/docs/content/config.md b/docs/content/config.mdindex d47e77cd2..ce6589e16 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -219,7 +219,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/### Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](@/step.md#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](@/extending.md#aliases) for usage and flags.```toml[aliases]@@ -396,7 +396,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/## Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](@/step.md#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](@/extending.md#aliases) for usage and flags.```toml[aliases]diff --git a/docs/content/extending.md b/docs/content/extending.mdindex 54b32184d..0eb1de8e5 100644--- a/docs/content/extending.md+++ b/docs/content/extending.md@@ -11,13 +11,13 @@ Worktrunk has three extension mechanisms.**[Hooks](#hooks)** run shell commands at lifecycle events — creating a worktree, merging, removing. They're configured in TOML and run automatically.-**[Aliases](#aliases)** define reusable commands invoked via `wt step <name>`. Same template variables as hooks, but triggered manually.+**[Aliases](#aliases)** define reusable commands invoked as `wt <name>`. Same template variables as hooks, but triggered manually.**[External subcommands](#external-subcommands)** are standalone executables. Drop `wt-foo` on `PATH` and it becomes `wt foo`. No configuration needed.| | Hooks | Aliases | External subcommands ||---|---|---|---|-| **Trigger** | Automatic (lifecycle events) | Manual (`wt step <name>`) | Manual (`wt <name>`) |+| **Trigger** | Automatic (lifecycle events) | Manual (`wt <name>`) | Manual (`wt <name>`) || **Defined in** | TOML config | TOML config | Any executable on `PATH` || **Template variables** | Yes | Yes | No || **Shareable via repo** | `.config/wt.toml` | `.config/wt.toml` | Distribute the binary |@@ -108,7 +108,9 @@ See [Tips & Patterns](@/tips-patterns.md) for more recipes: dev server per workt## Aliases-Aliases are custom commands invoked via `wt step <name>`. They share the same template variables and approval model as hooks.+<span class="badge-experimental"></span>++Aliases are custom commands invoked as `wt <name>`. They share the same template variables and approval model as hooks.```toml[aliases]@@ -116,7 +118,11 @@ deploy = "make deploy BRANCH={{ branch }}"open = "open http://localhost:{{ branch | hash_port }}"```-{{ terminal(cmd="wt step deploy|||wt step deploy --dry-run|||wt step deploy --env=staging") }}+{{ terminal(cmd="wt deploy|||wt deploy --dry-run|||wt deploy --env=staging") }}++`wt deploy` resolves `deploy` against configured aliases first, then falls through to a `wt-deploy` PATH binary if no alias matches. Built-in subcommands always take precedence — an alias named `list` or `switch` is unreachable.++Hyphens in variable names are canonicalized to underscores at parse time, so `--my-var=value` is referenced as `{{ my_var }}` in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of `{{ my-var }}` as subtraction.An `up` alias that fetches all remotes and rebases each worktree onto its upstream:@@ -131,9 +137,29 @@ git fetch --all --prune && wt step for-each -- '''''```-When both user and project config define the same alias name, both run — user first, then project. Project-config aliases require approval, same as project hooks.+### Multi-step pipelines++Multi-step aliases run commands in order using `[[aliases.NAME]]` blocks. Each block is one step; multiple keys within a block run concurrently.++```toml+[[aliases.release]]+test = "cargo test"++[[aliases.release]]+build = "cargo build --release"+package = "cargo package --no-verify"++[[aliases.release]]+publish = "cargo publish"+```++`test` runs first, then `build` and `package` run together, then `publish` runs last. A step failure aborts the remaining steps.-Alias names that collide with built-in step commands (`commit`, `squash`, `rebase`, etc.) are shadowed by the built-in.+### Sources and approval++When both user and project config define the same alias name, both run — user first, then project. Project-config aliases require approval on first run, same as project hooks. User-config aliases are trusted.++Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.### Recipe: move or copy in-progress changes to a new worktree@@ -152,11 +178,11 @@ fi'''```-Run with `wt step move-changes --to=feature-xyz`. The leading guard avoids touching a pre-existing stash when nothing is in flight; otherwise, `git stash push --include-untracked` captures everything, `wt switch --create` makes the new worktree, and `git stash pop --index` (via `--execute`) restores the changes there with the staged/unstaged split intact.+Run with `wt move-changes --to=feature-xyz`. The leading guard avoids touching a pre-existing stash when nothing is in flight; otherwise, `git stash push --include-untracked` captures everything, `wt switch --create` makes the new worktree, and `git stash pop --index` (via `--execute`) restores the changes there with the staged/unstaged split intact.To copy instead of move (source keeps its changes too), add `git stash apply --index --quiet` right after the push. For staged-only flows, swap the stash for `git diff --cached` written to a tempfile and applied with `git apply --index` in the new worktree — that handles files where staged and unstaged hunks overlap on the same lines, where `git stash --staged` falls short.-Because an inner `wt switch --create` inside an alias [propagates its `cd` to the parent shell](@/step.md#aliases), the alias drops you in the new worktree directly.+Because an inner `wt switch --create` inside an alias propagates its `cd` to the parent shell, the alias drops you in the new worktree directly.### Recipe: tail a specific hook log@@ -173,21 +199,19 @@ tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sani'''```-Run with `wt step hook-log --name=<hook-name>` (e.g., `wt step hook-log --name=server`) to tail the current worktree's `post-start` hook of that name. The `sanitize_hash` filter produces a filesystem-safe name with a hash suffix that keeps distinct originals unique — the same transformation Worktrunk applies on disk — so the alias resolves the right log even for branch and hook names containing characters like `/`.--See [`wt step` — Aliases](@/step.md#aliases) for the full reference.+Run with `wt hook-log --name=<hook-name>` (e.g., `wt hook-log --name=server`) to tail the current worktree's `post-start` hook of that name. The `sanitize_hash` filter produces a filesystem-safe name with a hash suffix that keeps distinct originals unique — the same transformation Worktrunk applies on disk — so the alias resolves the right log even for branch and hook names containing characters like `/`.## External subcommands<span class="badge-experimental"></span>-Any executable named `wt-<name>` on `PATH` becomes available as `wt <name>` — the same pattern git uses for `git-foo`. Built-in commands always take precedence.+Any executable named `wt-<name>` on `PATH` becomes available as `wt <name>` — the same pattern git uses for `git-foo`. Built-in commands and configured [aliases](#aliases) take precedence — `wt foo` resolves to the alias if `foo` is configured, otherwise to `wt-foo`.{{ terminal(cmd="wt sync origin # runs: wt-sync origin|||wt -C /tmp/repo sync # -C is forwarded as the child's working directory") }}Arguments pass through verbatim, stdio is inherited, and the child's exit code propagates unchanged. External subcommands don't have access to template variables.-If nothing matches — no built-in, no nested subcommand, no `wt-<name>` on `PATH` — wt prints a "not a wt command" error with a typo suggestion.+If nothing matches — no built-in, no alias, no `wt-<name>` on `PATH` — wt prints a "not a wt command" error with a typo suggestion.### Examplesdiff --git a/docs/content/step.md b/docs/content/step.mdindex 50b7ada52..fe8ee7a59 100644--- a/docs/content/step.md+++ b/docs/content/step.md@@ -34,12 +34,13 @@ Manual merge workflow with review between steps:- [`promote`](#wt-step-promote) — <span class="badge-experimental"></span> Swap a branch into the main worktree- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch- [`relocate`](#wt-step-relocate) — <span class="badge-experimental"></span> Move worktrees to expected paths-- [`<alias>`](#aliases) — <span class="badge-experimental"></span> Run a configured command alias+- [`<alias>`](@/extending.md#aliases) — <span class="badge-experimental"></span> Run a configured command alias (see [Aliases](@/extending.md#aliases))## See also- [`wt merge`](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically- [`wt hook`](@/hook.md) — Run configured hooks+- [Aliases](@/extending.md#aliases) — Custom command templates run as `wt <name>`## Command reference@@ -819,60 +820,4 @@ Usage: <b><span class=c>wt step relocate</span></b> <span class=c>[OPTIONS]</spa+ trace.log/output.log under .git/wt/logs/){% end %}-## Aliases--<span class="badge-experimental"></span>--Custom command templates configured in user config (`~/.config/worktrunk/config.toml`) or project config (`.config/wt.toml`). Aliases support the same [template variables](@/hook.md#template-variables) as hooks.--```toml-# .config/wt.toml-[aliases]-deploy = "make deploy BRANCH={{ branch }}"-port = "echo http://localhost:{{ branch | hash_port }}"-```--{{ terminal(cmd="wt step deploy # run the alias|||wt step deploy --dry-run # show expanded command|||wt step deploy --env=staging # pass template variable|||wt step deploy --var env=staging # equivalent long form|||wt step deploy --my-var=value # hyphens become underscores (__WT_OPEN2__ my_var __WT_CLOSE2__)|||wt step deploy --yes # skip approval prompt") }}--Hyphens in variable names are canonicalized to underscores at parse time, so `--my-var=value` is referenced as `{{ my_var }}` in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of `{{ my-var }}` as subtraction.--Multi-line aliases work too. This `up` alias fetches all remotes and rebases each worktree onto its upstream, skipping worktrees without a tracking branch or with a rebase already in progress:--```toml-# ~/.config/worktrunk/config.toml-[aliases]-up = '''-git fetch --all --prune && wt step for-each -- '- git rev-parse --verify -q @{u} >/dev/null || exit 0- g=$(git rev-parse --git-dir)- test -d "$g/rebase-merge" -o -d "$g/rebase-apply" && exit 0- git rebase @{u} --no-autostash || git rebase --abort-''''-```--{{ terminal(cmd="wt step up") }}--Multi-step aliases run commands in order using `[[aliases.NAME]]` blocks. Each block is one step; multiple keys within a block run concurrently.--```toml-# .config/wt.toml-[[aliases.release]]-test = "cargo test"--[[aliases.release]]-build = "cargo build --release"-package = "cargo package --no-verify"--[[aliases.release]]-publish = "cargo publish"-```--Here `test` runs first, then `build` and `package` run together, then `publish` runs last. A step failure aborts the remaining steps.--When defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](@/hook.md#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.--Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.--Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run.-<!-- END AUTO-GENERATED from `wt step --help-page` -->diff --git a/docs/content/tips-patterns.md b/docs/content/tips-patterns.mdindex 1352739d3..6c9218a51 100644--- a/docs/content/tips-patterns.md+++ b/docs/content/tips-patterns.md@@ -29,7 +29,7 @@ open = "open http://localhost:{{ branch | hash_port }}"test = "cargo test --features {{ vars.features | default('default') }}"```-See [`wt step` aliases](@/step.md#aliases) for scoping, approval, and reference.+See [Aliases](@/extending.md#aliases) for scoping, approval, and reference.## Per-branch variables@@ -148,7 +148,7 @@ command = '''f=$(mktemp); printf '\n\n' > "$f"; sed 's/^/# /' >> "$f"; ${EDITOR:This comments out the rendered prompt (diff, branch name, stats) with `#` prefixes, opens your editor, and strips comment lines on save. A couple of blank lines at the top give you space to type; the prompt context is visible below for reference.-To keep the LLM as default but use the editor for a specific merge, add a [worktrunk alias](@/step.md#aliases):+To keep the LLM as default but use the editor for a specific merge, add a [worktrunk alias](@/extending.md#aliases):```toml# ~/.config/worktrunk/config.toml@@ -156,7 +156,7 @@ To keep the LLM as default but use the editor for a specific merge, add a [worktmc = '''WORKTRUNK_COMMIT__GENERATION__COMMAND='f=$(mktemp); printf "\n\n" > "$f"; sed "s/^/# /" >> "$f"; ${EDITOR:-vi} "$f" < /dev/tty > /dev/tty; grep -v "^#" "$f"' wt merge'''```-Then `wt step mc` opens an editor for the commit message while plain `wt merge` continues to use the LLM.+Then `wt mc` opens an editor for the commit message while plain `wt merge` continues to use the LLM.## Track agent statusdiff --git a/docs/content/worktrunk.md b/docs/content/worktrunk.mdindex 81f3dcd20..e7273c1d9 100644--- a/docs/content/worktrunk.md+++ b/docs/content/worktrunk.md@@ -91,7 +91,7 @@ git branch -d feat{% end %}</td>- **[`wt list --full`](@/list.md#full-mode)** — [CI status](@/list.md#ci-status) and [AI-generated summaries](@/list.md#llm-summaries) per branch- **[PR checkout](@/switch.md#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch- **[Dev server per worktree](@/hook.md#dev-servers)** — `hash_port` template filter gives each worktree a unique port-- **[Aliases](@/step.md#aliases) & [per-branch variables](@/config.md#wt-config-state-vars)** — custom `wt step <name>` commands and branch-scoped state for hook templates+- **[Aliases](@/extending.md#aliases) & [per-branch variables](@/config.md#wt-config-state-vars)** — custom `wt <name>` commands and branch-scoped state for hook templates- ...and **[lots more](#next-steps)**A demo with some advanced features:diff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex fb85399e7..f04f69e12 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -218,7 +218,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/### Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](https://worktrunk.dev/step/#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](https://worktrunk.dev/extending/#aliases) for usage and flags.```toml[aliases]@@ -395,7 +395,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/## Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](https://worktrunk.dev/step/#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](https://worktrunk.dev/extending/#aliases) for usage and flags.```toml[aliases]diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.mdindex c243434ab..ea75db29e 100644--- a/skills/worktrunk/reference/extending.md+++ b/skills/worktrunk/reference/extending.md@@ -4,13 +4,13 @@ Worktrunk has three extension mechanisms.**[Hooks](#hooks)** run shell commands at lifecycle events — creating a worktree, merging, removing. They're configured in TOML and run automatically.-**[Aliases](#aliases)** define reusable commands invoked via `wt step <name>`. Same template variables as hooks, but triggered manually.+**[Aliases](#aliases)** define reusable commands invoked as `wt <name>`. Same template variables as hooks, but triggered manually.**[External subcommands](#external-subcommands)** are standalone executables. Drop `wt-foo` on `PATH` and it becomes `wt foo`. No configuration needed.| | Hooks | Aliases | External subcommands ||---|---|---|---|-| **Trigger** | Automatic (lifecycle events) | Manual (`wt step <name>`) | Manual (`wt <name>`) |+| **Trigger** | Automatic (lifecycle events) | Manual (`wt <name>`) | Manual (`wt <name>`) || **Defined in** | TOML config | TOML config | Any executable on `PATH` || **Template variables** | Yes | Yes | No || **Shareable via repo** | `.config/wt.toml` | `.config/wt.toml` | Distribute the binary |@@ -101,7 +101,9 @@ See [Tips & Patterns](https://worktrunk.dev/tips-patterns/) for more recipes: de## Aliases-Aliases are custom commands invoked via `wt step <name>`. They share the same template variables and approval model as hooks.+[experimental]++Aliases are custom commands invoked as `wt <name>`. They share the same template variables and approval model as hooks.```toml[aliases]@@ -110,11 +112,15 @@ open = "open http://localhost:{{ branch | hash_port }}"``````bash-wt step deploy-wt step deploy --dry-run-wt step deploy --env=staging+wt deploy+wt deploy --dry-run+wt deploy --env=staging```+`wt deploy` resolves `deploy` against configured aliases first, then falls through to a `wt-deploy` PATH binary if no alias matches. Built-in subcommands always take precedence — an alias named `list` or `switch` is unreachable.++Hyphens in variable names are canonicalized to underscores at parse time, so `--my-var=value` is referenced as `{{ my_var }}` in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of `{{ my-var }}` as subtraction.+An `up` alias that fetches all remotes and rebases each worktree onto its upstream:```toml@@ -128,9 +134,29 @@ git fetch --all --prune && wt step for-each -- '''''```-When both user and project config define the same alias name, both run — user first, then project. Project-config aliases require approval, same as project hooks.+### Multi-step pipelines++Multi-step aliases run commands in order using `[[aliases.NAME]]` blocks. Each block is one step; multiple keys within a block run concurrently.++```toml+[[aliases.release]]+test = "cargo test"++[[aliases.release]]+build = "cargo build --release"+package = "cargo package --no-verify"++[[aliases.release]]+publish = "cargo publish"+```++`test` runs first, then `build` and `package` run together, then `publish` runs last. A step failure aborts the remaining steps.-Alias names that collide with built-in step commands (`commit`, `squash`, `rebase`, etc.) are shadowed by the built-in.+### Sources and approval++When both user and project config define the same alias name, both run — user first, then project. Project-config aliases require approval on first run, same as project hooks. User-config aliases are trusted.++Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.### Recipe: move or copy in-progress changes to a new worktree@@ -149,11 +175,11 @@ fi'''```-Run with `wt step move-changes --to=feature-xyz`. The leading guard avoids touching a pre-existing stash when nothing is in flight; otherwise, `git stash push --include-untracked` captures everything, `wt switch --create` makes the new worktree, and `git stash pop --index` (via `--execute`) restores the changes there with the staged/unstaged split intact.+Run with `wt move-changes --to=feature-xyz`. The leading guard avoids touching a pre-existing stash when nothing is in flight; otherwise, `git stash push --include-untracked` captures everything, `wt switch --create` makes the new worktree, and `git stash pop --index` (via `--execute`) restores the changes there with the staged/unstaged split intact.To copy instead of move (source keeps its changes too), add `git stash apply --index --quiet` right after the push. For staged-only flows, swap the stash for `git diff --cached` written to a tempfile and applied with `git apply --index` in the new worktree — that handles files where staged and unstaged hunks overlap on the same lines, where `git stash --staged` falls short.-Because an inner `wt switch --create` inside an alias [propagates its `cd` to the parent shell](https://worktrunk.dev/step/#aliases), the alias drops you in the new worktree directly.+Because an inner `wt switch --create` inside an alias propagates its `cd` to the parent shell, the alias drops you in the new worktree directly.### Recipe: tail a specific hook log@@ -170,15 +196,13 @@ tail -f "$(wt config state logs --format=json | jq -r --arg name "{{ name | sani'''```-Run with `wt step hook-log --name=<hook-name>` (e.g., `wt step hook-log --name=server`) to tail the current worktree's `post-start` hook of that name. The `sanitize_hash` filter produces a filesystem-safe name with a hash suffix that keeps distinct originals unique — the same transformation Worktrunk applies on disk — so the alias resolves the right log even for branch and hook names containing characters like `/`.--See [`wt step` — Aliases](https://worktrunk.dev/step/#aliases) for the full reference.+Run with `wt hook-log --name=<hook-name>` (e.g., `wt hook-log --name=server`) to tail the current worktree's `post-start` hook of that name. The `sanitize_hash` filter produces a filesystem-safe name with a hash suffix that keeps distinct originals unique — the same transformation Worktrunk applies on disk — so the alias resolves the right log even for branch and hook names containing characters like `/`.## External subcommands[experimental]-Any executable named `wt-<name>` on `PATH` becomes available as `wt <name>` — the same pattern git uses for `git-foo`. Built-in commands always take precedence.+Any executable named `wt-<name>` on `PATH` becomes available as `wt <name>` — the same pattern git uses for `git-foo`. Built-in commands and configured [aliases](#aliases) take precedence — `wt foo` resolves to the alias if `foo` is configured, otherwise to `wt-foo`.```bashwt sync origin # runs: wt-sync origin@@ -187,7 +211,7 @@ wt -C /tmp/repo sync # -C is forwarded as the child's working directoryArguments pass through verbatim, stdio is inherited, and the child's exit code propagates unchanged. External subcommands don't have access to template variables.-If nothing matches — no built-in, no nested subcommand, no `wt-<name>` on `PATH` — wt prints a "not a wt command" error with a typo suggestion.+If nothing matches — no built-in, no alias, no `wt-<name>` on `PATH` — wt prints a "not a wt command" error with a typo suggestion.### Examplesdiff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex 2b2b68d2e..b47b4e3e2 100644--- a/skills/worktrunk/reference/step.md+++ b/skills/worktrunk/reference/step.md@@ -32,7 +32,7 @@ $ wt step push- [`promote`](#wt-step-promote) — [experimental] Swap a branch into the main worktree- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch- [`relocate`](#wt-step-relocate) — [experimental] Move worktrees to expected paths-- [`<alias>`](#aliases) — [experimental] Run a configured command alias+- [`<alias>`](https://worktrunk.dev/extending/#aliases) — [experimental] Run a configured command alias (see [Aliases](https://worktrunk.dev/extending/#aliases))## Command reference@@ -865,66 +865,3 @@ Global Options:Verbose output (-v: info logs + hook/template output; -vv: debug logs + diagnostic report+ trace.log/output.log under .git/wt/logs/)```--## Aliases [experimental]--Custom command templates configured in user config (`~/.config/worktrunk/config.toml`) or project config (`.config/wt.toml`). Aliases support the same [template variables](https://worktrunk.dev/hook/#template-variables) as hooks.--```toml-# .config/wt.toml-[aliases]-deploy = "make deploy BRANCH={{ branch }}"-port = "echo http://localhost:{{ branch | hash_port }}"-```--```bash-$ wt step deploy # run the alias-$ wt step deploy --dry-run # show expanded command-$ wt step deploy --env=staging # pass template variable-$ wt step deploy --var env=staging # equivalent long form-$ wt step deploy --my-var=value # hyphens become underscores ({{ my_var }})-$ wt step deploy --yes # skip approval prompt-```--Hyphens in variable names are canonicalized to underscores at parse time, so `--my-var=value` is referenced as `{{ my_var }}` in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of `{{ my-var }}` as subtraction.--Multi-line aliases work too. This `up` alias fetches all remotes and rebases each worktree onto its upstream, skipping worktrees without a tracking branch or with a rebase already in progress:--```toml-# ~/.config/worktrunk/config.toml-[aliases]-up = '''-git fetch --all --prune && wt step for-each -- '- git rev-parse --verify -q @{u} >/dev/null || exit 0- g=$(git rev-parse --git-dir)- test -d "$g/rebase-merge" -o -d "$g/rebase-apply" && exit 0- git rebase @{u} --no-autostash || git rebase --abort-''''-```--```bash-$ wt step up-```--Multi-step aliases run commands in order using `[[aliases.NAME]]` blocks. Each block is one step; multiple keys within a block run concurrently.--```toml-# .config/wt.toml-[[aliases.release]]-test = "cargo test"--[[aliases.release]]-build = "cargo build --release"-package = "cargo package --no-verify"--[[aliases.release]]-publish = "cargo publish"-```--Here `test` runs first, then `build` and `package` run together, then `publish` runs last. A step failure aborts the remaining steps.--When defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](https://worktrunk.dev/hook/#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.--Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.--Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run.diff --git a/skills/worktrunk/reference/tips-patterns.md b/skills/worktrunk/reference/tips-patterns.mdindex 15e31e998..7494e7b5e 100644--- a/skills/worktrunk/reference/tips-patterns.md+++ b/skills/worktrunk/reference/tips-patterns.md@@ -26,7 +26,7 @@ open = "open http://localhost:{{ branch | hash_port }}"test = "cargo test --features {{ vars.features | default('default') }}"```-See [`wt step` aliases](https://worktrunk.dev/step/#aliases) for scoping, approval, and reference.+See [Aliases](https://worktrunk.dev/extending/#aliases) for scoping, approval, and reference.## Per-branch variables@@ -143,7 +143,7 @@ command = '''f=$(mktemp); printf '\n\n' > "$f"; sed 's/^/# /' >> "$f"; ${EDITOR:This comments out the rendered prompt (diff, branch name, stats) with `#` prefixes, opens your editor, and strips comment lines on save. A couple of blank lines at the top give you space to type; the prompt context is visible below for reference.-To keep the LLM as default but use the editor for a specific merge, add a [worktrunk alias](https://worktrunk.dev/step/#aliases):+To keep the LLM as default but use the editor for a specific merge, add a [worktrunk alias](https://worktrunk.dev/extending/#aliases):```toml# ~/.config/worktrunk/config.toml@@ -151,7 +151,7 @@ To keep the LLM as default but use the editor for a specific merge, add a [worktmc = '''WORKTRUNK_COMMIT__GENERATION__COMMAND='f=$(mktemp); printf "\n\n" > "$f"; sed "s/^/# /" >> "$f"; ${EDITOR:-vi} "$f" < /dev/tty > /dev/tty; grep -v "^#" "$f"' wt merge'''```-Then `wt step mc` opens an editor for the commit message while plain `wt merge` continues to use the LLM.+Then `wt mc` opens an editor for the commit message while plain `wt merge` continues to use the LLM.## Track agent statusdiff --git a/skills/worktrunk/reference/worktrunk.md b/skills/worktrunk/reference/worktrunk.mdindex b0d4d0077..104f5d86d 100644--- a/skills/worktrunk/reference/worktrunk.md+++ b/skills/worktrunk/reference/worktrunk.md@@ -76,7 +76,7 @@ git branch -d feat</td>- **[`wt list --full`](https://worktrunk.dev/list/#full-mode)** — [CI status](https://worktrunk.dev/list/#ci-status) and [AI-generated summaries](https://worktrunk.dev/list/#llm-summaries) per branch- **[PR checkout](https://worktrunk.dev/switch/#pull-requests-and-merge-requests)** — `wt switch pr:123` to jump straight to a PR's branch- **[Dev server per worktree](https://worktrunk.dev/hook/#dev-servers)** — `hash_port` template filter gives each worktree a unique port-- **[Aliases](https://worktrunk.dev/step/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt step <name>` commands and branch-scoped state for hook templates+- **[Aliases](https://worktrunk.dev/extending/#aliases) & [per-branch variables](https://worktrunk.dev/config/#wt-config-state-vars)** — custom `wt <name>` commands and branch-scoped state for hook templates- ...and **[lots more](#next-steps)**A demo with some advanced features:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex f837adc2e..f77af8ade 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1121,13 +1121,13 @@ $ wt step push- [`promote`](#wt-step-promote) — [experimental] Swap a branch into the main worktree- [`prune`](#wt-step-prune) — Remove worktrees and branches merged into the default branch- [`relocate`](#wt-step-relocate) — [experimental] Move worktrees to expected paths-- [`<alias>`](#aliases) — [experimental] Run a configured command alias+- [`<alias>`](@/extending.md#aliases) — [experimental] Run a configured command alias (see [Aliases](@/extending.md#aliases))## See also- [`wt merge`](@/merge.md) — Runs commit → squash → rebase → hooks → push → cleanup automatically- [`wt hook`](@/hook.md) — Run configured hooks-+- [Aliases](@/extending.md#aliases) — Custom command templates run as `wt <name>`<!-- subdoc: commit --><!-- subdoc: squash --><!-- subdoc: diff -->@@ -1136,69 +1136,7 @@ $ wt step push<!-- subdoc: for-each --><!-- subdoc: promote --><!-- subdoc: prune -->-<!-- subdoc: relocate -->-## Aliases [experimental]--Custom command templates configured in user config (`~/.config/worktrunk/config.toml`) or project config (`.config/wt.toml`). Aliases support the same [template variables](@/hook.md#template-variables) as hooks.--```toml-# .config/wt.toml-[aliases]-deploy = "make deploy BRANCH={{ branch }}"-port = "echo http://localhost:{{ branch | hash_port }}"-```--```console-$ wt step deploy # run the alias-$ wt step deploy --dry-run # show expanded command-$ wt step deploy --env=staging # pass template variable-$ wt step deploy --var env=staging # equivalent long form-$ wt step deploy --my-var=value # hyphens become underscores ({{ my_var }})-$ wt step deploy --yes # skip approval prompt-```--Hyphens in variable names are canonicalized to underscores at parse time, so `--my-var=value` is referenced as `{{ my_var }}` in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of `{{ my-var }}` as subtraction.--Multi-line aliases work too. This `up` alias fetches all remotes and rebases each worktree onto its upstream, skipping worktrees without a tracking branch or with a rebase already in progress:--```toml-# ~/.config/worktrunk/config.toml-[aliases]-up = '''-git fetch --all --prune && wt step for-each -- '- git rev-parse --verify -q @{u} >/dev/null || exit 0- g=$(git rev-parse --git-dir)- test -d "$g/rebase-merge" -o -d "$g/rebase-apply" && exit 0- git rebase @{u} --no-autostash || git rebase --abort-''''-```--```console-$ wt step up-```--Multi-step aliases run commands in order using `[[aliases.NAME]]` blocks. Each block is one step; multiple keys within a block run concurrently.--```toml-# .config/wt.toml-[[aliases.release]]-test = "cargo test"--[[aliases.release]]-build = "cargo build --release"-package = "cargo package --no-verify"--[[aliases.release]]-publish = "cargo publish"-```--Here `test` runs first, then `build` and `package` run together, then `publish` runs last. A step failure aborts the remaining steps.--When defined in both user and project config, both run — user first, then project. Project-config aliases require [command approval](@/hook.md#wt-hook-approvals) on first run, same as project hooks. User-config aliases are trusted.--Inside an alias body, an inner `wt switch` (or `wt switch --create`) passes its `cd` through to the parent shell, so an alias wrapping `wt switch --create` lands the shell in the new worktree just like running it directly.--Alias names that match a built-in step command (`commit`, `squash`, etc.) are shadowed by the built-in and will never run."#+<!-- subdoc: relocate -->"#)]Step {#[command(subcommand)]@@ -1898,7 +1836,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/### Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](@/step.md#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](@/extending.md#aliases) for usage and flags.```toml[aliases]@@ -2075,7 +2013,7 @@ Built-in excludes always apply: VCS metadata directories (`.bzr/`, `.hg/`, `.jj/## Aliases-Command templates that run with `wt step <name>`. See [`wt step` aliases](@/step.md#aliases) for usage and flags.+Command templates that run as `wt <name>`. See [Aliases](@/extending.md#aliases) for usage and flags.```toml[aliases]diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 8c0f0553a..edefe9209 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -41,9 +41,7 @@ use worktrunk::config::{validate_template_syntax,};use worktrunk::git::Repository;-use worktrunk::styling::{- eprintln, format_bash_with_gutter, info_message, progress_message, warning_message,-};+use worktrunk::styling::{eprintln, format_bash_with_gutter, info_message, progress_message};use crate::commands::command_approval::approve_alias_commands;use crate::commands::command_executor::{@@ -54,7 +52,7 @@ use crate::commands::hooks::format_pipeline_summary_from_names;use crate::output::DirectivePassthrough;/// Built-in `wt step` subcommand names. Aliases with these names are-/// shadowed by the built-in and will never run.+/// reachable via `wt <name>` (top-level) but shadowed via `wt step <name>`.const BUILTIN_STEP_COMMANDS: &[&str] = &["commit","copy-ignored",@@ -69,6 +67,15 @@ const BUILTIN_STEP_COMMANDS: &[&str] = &["squash",];+/// Built-in top-level `wt` subcommand names — visible and hidden. Aliases+/// with these names are fully unreachable: clap matches the built-in before+/// alias dispatch sees the name, so `wt list` always runs the built-in even+/// if `[aliases] list = …` is configured. Kept in sync with `Cli` via+/// `test_top_level_builtins_match_clap`.+const TOP_LEVEL_BUILTINS: &[&str] = &[+ "config", "hook", "list", "merge", "remove", "select", "step", "switch",+];+/// Options parsed from the external subcommand args.#[derive(Debug)]pub struct AliasOptions {@@ -246,48 +253,57 @@ fn format_alias_announcement(name: &str, cmd_config: &CommandConfig) -> String {}}-/// Run a configured alias by name.-///-/// Looks up the alias in merged config (project config + user config),-/// expands each command template, and executes them in order. Project-config-/// aliases require command approval before execution.-pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {- let repo = Repository::current()?;- let user_config = UserConfig::load()?;+/// Load the merged alias map (user config + project config, in runtime order).+fn load_merged_aliases(+ repo: &Repository,+ user_config: &UserConfig,+ project_config: Option<&ProjectConfig>,+) -> BTreeMap<String, CommandConfig> {let project_id = repo.project_identifier().ok();- let project_config = ProjectConfig::load(&repo, true)?;-- // Merge aliases: user config first, then project config appends.- // Matches hook merge semantics — both sources run, project commands- // need approval regardless of whether user also defines the alias.let mut aliases = user_config.aliases(project_id.as_deref());- if let Some(pc) = project_config.as_ref() {+ if let Some(pc) = project_config {append_aliases(&mut aliases, &pc.aliases);}+ aliases+}- // Warn about aliases that shadow built-in step commands- let shadowed: Vec<_> = aliases- .keys()- .filter(|k| BUILTIN_STEP_COMMANDS.contains(&k.as_str()))- .collect();- if !shadowed.is_empty() {- let names = shadowed- .iter()- .map(|k| cformat!("<bold>{k}</>"))- .collect::<Vec<_>>()- .join(", ");- let (noun, verb) = if shadowed.len() == 1 {- ("Alias", "shadows a built-in step command")- } else {- ("Aliases", "shadow built-in step commands")- };- eprintln!(- "{}",- warning_message(format!("{noun} {names} {verb} and will never run"))- );+/// Try to run alias `name` with `rest` as its arg vector. Returns `Ok(None)`+/// when no alias by that name is configured — the caller can fall through to+/// other dispatch (e.g. `wt-<name>` PATH binary at the top level). Argument+/// parsing only runs after we've confirmed the alias is configured, so+/// non-alias `rest` (positional args meant for an external binary) doesn't+/// surface as a parse error.+///+/// Alias execution needs a git repository; without one this returns `Ok(None)`+/// so the caller falls through to PATH lookup. Config load errors propagate —+/// a broken `wt.toml` should fail loudly here just as it does for `wt list`,+/// rather than silently turning into an "unrecognized subcommand" once we+/// fall through to PATH lookup.+pub fn try_alias(name: String, rest: Vec<String>) -> anyhow::Result<Option<()>> {+ let Ok(repo) = Repository::current() else {+ return Ok(None);+ };+ let user_config = UserConfig::load()?;+ let project_config = ProjectConfig::load(&repo, true)?;+ let aliases = load_merged_aliases(&repo, &user_config, project_config.as_ref());+ if !aliases.contains_key(&name) {+ return Ok(None);}+ let mut alias_args = Vec::with_capacity(1 + rest.len());+ alias_args.push(name);+ alias_args.extend(rest);+ let opts = AliasOptions::parse(alias_args)?;+ run_alias(opts, repo, user_config, project_config, aliases).map(Some)+}- let Some(cmd_config) = aliases.get(&opts.name) else {+/// Run a configured alias from `wt step <name>`. Errors with a clap-style+/// "unrecognized subcommand" if the alias isn't configured.+pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {+ let repo = Repository::current()?;+ let user_config = UserConfig::load()?;+ let project_config = ProjectConfig::load(&repo, true)?;+ let aliases = load_merged_aliases(&repo, &user_config, project_config.as_ref());+ if !aliases.contains_key(&opts.name) {// Mirror clap's native `unrecognized subcommand` error so `wt step// <typo>` reads the same as `wt <typo>`. Aliases are fed into the// `SuggestedSubcommand` list so a typo like `wt step deplyo` still@@ -300,11 +316,46 @@ pub fn step_alias(opts: AliasOptions) -> anyhow::Result<()> {.map(|k| k.as_str()).collect();unknown_step_command_exit(&opts.name, &alias_names);+ }+ run_alias(opts, repo, user_config, project_config, aliases)+}++/// Return alias names for use as suggestions when a top-level subcommand is+/// not recognized. Best-effort — returns empty if config can't be loaded so+/// the suggestion list silently degrades to clap's built-in candidates.+pub fn alias_names_for_suggestions() -> Vec<String> {+ worktrunk::config::suppress_warnings();+ let Ok(repo) = Repository::current() else {+ return UserConfig::load()+ .map(|uc| uc.aliases(None).keys().cloned().collect())+ .unwrap_or_default();+ };+ let Ok(user_config) = UserConfig::load() else {+ return Vec::new();};+ let project_config = ProjectConfig::load(&repo, false).ok().flatten();+ load_merged_aliases(&repo, &user_config, project_config.as_ref())+ .keys()+ .cloned()+ .collect()+}++/// Execute `cmd_config` for `opts.name`. Caller must have already verified+/// `aliases.contains_key(&opts.name)`.+fn run_alias(+ opts: AliasOptions,+ repo: Repository,+ user_config: UserConfig,+ project_config: Option<ProjectConfig>,+ aliases: BTreeMap<String, CommandConfig>,+) -> anyhow::Result<()> {+ let cmd_config = aliases+ .get(&opts.name)+ .expect("caller verified alias is configured");// Check if this alias needs project-config approval (skip for --dry-run).// project_id is required for approval — re-derive with error propagation- // rather than using the .ok() from above.+ // rather than relying on `.ok()`.if !opts.dry_run&& let Some(project_commands) = alias_needs_approval(&opts.name, &project_config){@@ -443,15 +494,26 @@ enum AliasSource {Project,}-/// Splice the Aliases section into clap-rendered `wt step` help, if any-/// aliases are configured.+/// Which help page is being augmented. Controls the "shadowed by built-in"+/// annotation: at the top level, only top-level built-ins shadow an alias+/// (`wt list` blocks an alias named `list`). Under `wt step`, only step+/// built-ins shadow it (`wt step commit` blocks an alias named `commit` from+/// running via that path — but `wt commit` still runs the alias).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub(crate) enum HelpContext {+ TopLevel,+ Step,+}++/// Splice the Aliases section into clap-rendered help, if any aliases are+/// configured.///-/// Called from the help path in `help.rs` — which covers `wt step`-/// (via `arg_required_else_help`), `wt step -h`, and `wt step --help`,-/// all of which flow through clap's `DisplayHelp` error. Tolerates-/// running outside a repository: user-config aliases still list,-/// project-config aliases just get skipped.-pub(crate) fn augment_step_help(help: &str) -> String {+/// Called from the help path in `help.rs` — which covers `wt --help`,+/// `wt step --help`, and the bare `wt step` invocation (via+/// `arg_required_else_help`), all of which flow through clap's `DisplayHelp`+/// error. Tolerates running outside a repository: user-config aliases still+/// list, project-config aliases just get skipped.+pub(crate) fn augment_help(help: &str, context: HelpContext) -> String {// Help must not emit deprecation/unknown-field warnings or write `.new`// migration files as a side effect of rendering the alias list.worktrunk::config::suppress_warnings();@@ -467,7 +529,7 @@ pub(crate) fn augment_step_help(help: &str) -> String {// rendered output. The search prefix is derived from the same style// clap uses (our `help_styles().get_header()`), so if the header// styling changes both sides move together.- let aliases_section = render_aliases_section(&aliases);+ let aliases_section = render_aliases_section(&aliases, context);let options_heading = format!("{}Options:",crate::cli::help_styles().get_header().render()@@ -492,9 +554,21 @@ pub(crate) fn augment_step_help(help: &str) -> String {/// When a name is defined in both user and project config, two rows are/// shown (user first, then project, matching runtime order). Both rows/// carry a source marker so the reader can tell which pipeline is which.-fn render_aliases_section(entries: &[(String, CommandConfig, AliasSource)]) -> String {+///+/// `context` controls the "shadowed by built-in" annotation — see+/// [`HelpContext`].+fn render_aliases_section(+ entries: &[(String, CommandConfig, AliasSource)],+ context: HelpContext,+) -> String {use std::fmt::Write as _;+ let shadowed_names: &[&str] = match context {+ HelpContext::TopLevel => TOP_LEVEL_BUILTINS,+ HelpContext::Step => BUILTIN_STEP_COMMANDS,+ };+ let is_shadowed = |name: &str| shadowed_names.contains(&name);+// Names appearing in both sources need source markers to be distinguishable.let mut counts: BTreeMap<&str, usize> = BTreeMap::new();for (name, _, _) in entries {@@ -514,7 +588,7 @@ fn render_aliases_section(entries: &[(String, CommandConfig, AliasSource)]) -> Slet summary = format_alias_summary(cfg);// Shadowed-by-builtin is a warning (yellow) and takes precedence over// the source marker so the row doesn't pile up suffixes.- let suffix = if BUILTIN_STEP_COMMANDS.contains(&name.as_str()) {+ let suffix = if is_shadowed(name) {cformat!(" <yellow>(shadowed by built-in)</>")} else if counts.get(name.as_str()).copied().unwrap_or(0) > 1 {match source {@@ -1015,6 +1089,40 @@ cmd = [}}+ /// Verify TOP_LEVEL_BUILTINS stays in sync with the actual `Cli` enum.+ ///+ /// Hidden subcommands like `select` count — clap still matches them+ /// before falling through to alias dispatch, so they shadow aliases of+ /// the same name. Only `help` (clap-internal) and external subcommands+ /// are excluded.+ #[test]+ fn test_top_level_builtins_match_clap() {+ use crate::cli::Cli;+ use clap::CommandFactory;++ let app = Cli::command();+ let clap_names: Vec<&str> = app+ .get_subcommands()+ .map(|s| s.get_name())+ .filter(|n| *n != "help")+ .collect();++ for name in &clap_names {+ assert!(+ TOP_LEVEL_BUILTINS.contains(name),+ "Top-level subcommand '{name}' is missing from TOP_LEVEL_BUILTINS. \+ Add it so the help splice annotates aliases unreachable at the top level."+ );+ }+ for name in TOP_LEVEL_BUILTINS {+ assert!(+ clap_names.contains(name),+ "TOP_LEVEL_BUILTINS contains '{name}' but no such top-level subcommand exists. \+ Remove it from the list."+ );+ }+ }+#[test]fn test_format_alias_summary_single_command() {let cfg = cfg_from_toml(r#"cmd = "echo hello""#);@@ -1098,7 +1206,7 @@ test = "cargo test"// Caller passes pre-sorted entries; mirror that here.let mut sorted = entries;sorted.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));- let rendered = render_aliases_section(&sorted);+ let rendered = render_aliases_section(&sorted, HelpContext::Step);let rendered = rendered.ansi_strip();insta::assert_snapshot!(rendered, @r"Aliases:@@ -1108,4 +1216,39 @@ test = "cargo test"shared echo from-project (project)");}++ #[test]+ fn test_render_aliases_section_top_level_shadowing() {+ // Top-level shadowing: an alias named after a top-level built-in (e.g.+ // `list`) is unreachable from `wt list` because clap matches first.+ // Step-only built-in names (e.g. `commit`) are NOT shadowed at the top+ // level — `wt commit` runs the alias.+ let entries = vec![+ (+ "list".to_string(),+ cfg_from_toml(r#"cmd = "ls""#),+ AliasSource::User,+ ),+ (+ "commit".to_string(),+ cfg_from_toml(r#"cmd = "git commit""#),+ AliasSource::User,+ ),+ (+ "deploy".to_string(),+ cfg_from_toml(r#"cmd = "make deploy""#),+ AliasSource::User,+ ),+ ];+ let mut sorted = entries;+ sorted.sort_by(|a, b| a.0.cmp(&b.0).then(a.2.cmp(&b.2)));+ let rendered = render_aliases_section(&sorted, HelpContext::TopLevel);+ let rendered = rendered.ansi_strip();+ insta::assert_snapshot!(rendered, @r"+ Aliases:+ commit git commit+ deploy make deploy+ list ls (shadowed by built-in)+ ");+ }}diff --git a/src/commands/external.rs b/src/commands/external.rsindex e2e441156..456e13eba 100644--- a/src/commands/external.rs+++ b/src/commands/external.rs@@ -2,22 +2,25 @@//!//! When the user runs `wt foo` and `foo` is not a built-in subcommand, clap//! captures the invocation via the `Commands::External` variant. This module-//! looks for an executable named `wt-foo` on `PATH` and runs it with the-//! remaining arguments, mirroring how `git foo` finds `git-foo`.+//! resolves it in this order://!-//! Behaviour:-//!-//! 1. Resolve `wt-<name>` via `which`. If found, run it with the remaining-//! args, inheriting stdio, and propagate the exit code.-//! 2. If not found, synthesize clap's native `InvalidSubcommand` error and-//! route it through `enhance_and_exit_error` so the output matches what-//! clap would have produced without `external_subcommand` — same-//! formatting, suggestions, Usage line, and nested-subcommand tip (e.g.-//! `wt squash` → `perhaps wt step squash?`).+//! 1. **Alias**: if `foo` is configured as an alias in user/project config,+//! run it via the same path as `wt step foo`. User config wins over+//! `wt-<name>` PATH binaries — aliases are how users customize wt, so the+//! user's intent should take precedence.+//! 2. **PATH binary**: resolve `wt-<name>` via `which`. If found, run it with+//! the remaining args, inheriting stdio, and propagate the exit code.+//! Mirrors how `git foo` finds `git-foo`.+//! 3. Otherwise, synthesize clap's native `InvalidSubcommand` error (with+//! aliases included in the "did you mean" candidates) and route it through+//! `enhance_and_exit_error` so the output matches what clap would have+//! produced without `external_subcommand` — same formatting, suggestions,+//! Usage line, and nested-subcommand tip (e.g. `wt squash` →+//! `perhaps wt step squash?`).//!//! Built-in subcommands always take precedence — clap only dispatches//! `Commands::External` when no built-in matched, so there is no way for an-//! external `wt-switch` to shadow `wt switch`.+//! alias or external `wt-switch` to shadow `wt switch`.use std::ffi::OsString;use std::path::{Path, PathBuf};@@ -29,6 +32,7 @@ use strsim::jaro_winkler;use worktrunk::git::WorktrunkError;use crate::cli::build_command;+use crate::commands::{alias_names_for_suggestions, try_alias};use crate::enhance_and_exit_error;/// Handle a `Commands::External` invocation.@@ -63,24 +67,37 @@ pub(crate) fn handle_external_command(})?.to_owned();- // Try the PATH lookup first. If a `wt-<name>` binary exists, it takes- // precedence over clap's "unrecognized subcommand" error path — but *not*- // over built-ins, because clap only dispatches `External` when no built-in- // matched. Nested-subcommand hints (`wt squash` → `wt step squash`) are- // applied by `enhance_and_exit_error` when we fall through below, so a- // name that matches a nested subcommand still gets its tip even though- // we look at PATH first (nested names aren't expected to collide with- // real `wt-*` binaries, and if they do the on-PATH binary wins — same as- // git's behaviour).+ // Try alias dispatch first so user/project config wins over PATH binaries+ // of the same name. Built-ins still take precedence — clap only routes+ // to `Commands::External` when no built-in matched. The alias arg parser+ // requires UTF-8, but we only run it after confirming the name is a+ // configured alias, so non-UTF-8 args meant for an external binary don't+ // surface as alias parse errors.+ let alias_args: Option<Vec<String>> = rest+ .iter()+ .map(|a| a.to_str().map(|s| s.to_owned()))+ .collect();+ if let Some(alias_args) = alias_args+ && let Some(()) = try_alias(name.clone(), alias_args)?+ {+ return Ok(());+ }++ // Fall through to `wt-<name>` PATH binary. Nested-subcommand hints+ // (`wt squash` → `wt step squash`) are applied by `enhance_and_exit_error`+ // when we fall through below, so a name that matches a nested subcommand+ // still gets its tip even though we look at PATH before erroring (nested+ // names aren't expected to collide with real `wt-*` binaries, and if they+ // do the on-PATH binary wins — same as git's behaviour).let binary = format!("wt-{name}");if let Ok(path) = which::which(&binary) {return run_external(&path, &rest, working_dir.as_deref());}- // Not on PATH — emit clap's native `InvalidSubcommand` error. Routing- // through `enhance_and_exit_error` keeps the rendering consistent with- // every other clap error (same tip/Usage formatting) and layers the- // wt-specific nested-subcommand hint on top.+ // Not an alias and not on PATH — emit clap's native `InvalidSubcommand`+ // error. Routing through `enhance_and_exit_error` keeps the rendering+ // consistent with every other clap error (same tip/Usage formatting) and+ // layers the wt-specific nested-subcommand hint on top.enhance_and_exit_error(unrecognized_subcommand_error(&name));}@@ -90,6 +107,10 @@ pub(crate) fn handle_external_command(/// `SuggestedSubcommand`, and `Usage` context so clap's rich formatter/// produces its native output (the "tip:" line and "Usage:" block come from/// these context entries).+///+/// Configured aliases are mixed into the candidate pool so a typo like+/// `wt deplyo` produces `tip: ... 'deploy'` when `deploy` is user-defined,+/// matching the discovery surface of `wt --help`.fn unrecognized_subcommand_error(name: &str) -> clap::Error {let mut cmd = build_command();let mut err = clap::Error::new(ErrorKind::InvalidSubcommand).with_cmd(&cmd);@@ -97,7 +118,8 @@ fn unrecognized_subcommand_error(name: &str) -> clap::Error {ContextKind::InvalidSubcommand,ContextValue::String(name.to_string()),);- let suggestions = similar_subcommands(name, &cmd);+ let alias_names = alias_names_for_suggestions();+ let suggestions = similar_subcommands(name, &cmd, &alias_names);if !suggestions.is_empty() {err.insert(ContextKind::SuggestedSubcommand,@@ -144,22 +166,31 @@ fn run_external(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> RErr(WorktrunkError::AlreadyDisplayed { exit_code: code }.into())}-/// Return visible built-in subcommand names similar to `name`, sorted by-/// descending confidence. Mirrors clap's internal `did_you_mean` (Jaro–Winkler-/// similarity with a 0.7 threshold) so the `tip:` line reads the same as it-/// would have without `#[command(external_subcommand)]` intercepting the-/// error.-fn similar_subcommands(name: &str, cli_cmd: &clap::Command) -> Vec<String> {- let mut scored: Vec<(f64, String)> = cli_cmd+/// Return visible built-in subcommand names and configured alias names+/// similar to `name`, sorted by descending confidence. Mirrors clap's+/// internal `did_you_mean` (Jaro–Winkler similarity with a 0.7 threshold)+/// so the `tip:` line reads the same as it would have without+/// `#[command(external_subcommand)]` intercepting the error, plus aliases.+fn similar_subcommands(name: &str, cli_cmd: &clap::Command, alias_names: &[String]) -> Vec<String> {+ let builtins = cli_cmd.get_subcommands().filter(|c| !c.is_hide_set())- .map(|c| c.get_name())- .filter(|&candidate| candidate != "help")- .map(|candidate| (jaro_winkler(name, candidate), candidate.to_string()))+ .map(|c| c.get_name().to_string())+ .filter(|candidate| candidate != "help");+ let candidates = builtins.chain(alias_names.iter().cloned());+ let mut scored: Vec<(f64, String)> = candidates+ .map(|candidate| (jaro_winkler(name, &candidate), candidate)).filter(|(score, _)| *score > 0.7).collect();scored.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap_or(std::cmp::Ordering::Equal));- scored.into_iter().map(|(_, name)| name).collect()+ // Dedupe while preserving sort order (an alias with the same name as a+ // built-in would otherwise appear twice).+ let mut seen = std::collections::HashSet::new();+ scored+ .into_iter()+ .filter(|(_, n)| seen.insert(n.clone()))+ .map(|(_, n)| n)+ .collect()}#[cfg(test)]@@ -169,7 +200,7 @@ mod tests {#[test]fn similar_subcommands_finds_typo() {let cmd = build_command();- let suggestions = similar_subcommands("siwtch", &cmd);+ let suggestions = similar_subcommands("siwtch", &cmd, &[]);assert_eq!(suggestions.first().map(String::as_str),Some("switch"),@@ -180,7 +211,7 @@ mod tests {#[test]fn similar_subcommands_ignores_unrelated() {let cmd = build_command();- assert!(similar_subcommands("zzzzzzzz", &cmd).is_empty());+ assert!(similar_subcommands("zzzzzzzz", &cmd, &[]).is_empty());}#[test]@@ -188,7 +219,32 @@ mod tests {// `select` is hidden (deprecated); it should not be suggested even// though an exact-match candidate exists.let cmd = build_command();- assert!(!similar_subcommands("select", &cmd).contains(&"select".to_string()));+ assert!(!similar_subcommands("select", &cmd, &[]).contains(&"select".to_string()));+ }++ #[test]+ fn similar_subcommands_includes_aliases() {+ // Alias names mix into the candidate pool so a typo close to a+ // user-defined alias shows up in the `tip:` line.+ let cmd = build_command();+ let aliases = vec!["deploy".to_string(), "release".to_string()];+ let suggestions = similar_subcommands("deplyo", &cmd, &aliases);+ assert_eq!(+ suggestions.first().map(String::as_str),+ Some("deploy"),+ "got: {suggestions:?}"+ );+ }++ #[test]+ fn similar_subcommands_dedupes_alias_matching_builtin() {+ // An alias whose name shadows a built-in (e.g. `list`) should appear+ // only once in suggestions, not duplicated.+ let cmd = build_command();+ let aliases = vec!["list".to_string()];+ let suggestions = similar_subcommands("list", &cmd, &aliases);+ let count = suggestions.iter().filter(|n| *n == "list").count();+ assert_eq!(count, 1, "got: {suggestions:?}");}#[cfg(unix)]diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 1a69b7db4..d8c13ac9b 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -27,7 +27,9 @@ pub(crate) mod statusline;pub(crate) mod step_commands;pub(crate) mod worktree;-pub(crate) use alias::{AliasOptions, augment_step_help, step_alias};+pub(crate) use alias::{+ AliasOptions, HelpContext, alias_names_for_suggestions, augment_help, step_alias, try_alias,+};pub(crate) use config::{handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,handle_config_create, handle_config_show, handle_config_update, handle_hints_clear,diff --git a/src/completion.rs b/src/completion.rsindex da611ed10..33fbf84b6 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -405,53 +405,66 @@ fn completion_command() -> Command {hide_non_positional_options_for_completion(cmd)}-/// Inject configured aliases as subcommands of `step` so they appear in completions.+/// Inject configured aliases as subcommands at both the top level and under+/// `step` so they appear in completions for `wt <Tab>` and `wt step <Tab>`.////// Aliases are loaded from user config and project config (same merge order as-/// `step_alias`). Aliases that shadow built-in step commands are skipped.+/// `step_alias`). Aliases that shadow a built-in at a given level are skipped+/// for that level only — `commit` is shadowed under `step` but offered at the+/// top level, since `wt commit` runs the alias.fn inject_alias_subcommands(cmd: Command) -> Command {let aliases = load_aliases_for_completion();if aliases.is_empty() {return cmd;}+ let mut cmd = cmd;+ // Top-level injection: skip aliases that match a top-level built-in.+ for (name, cmd_config) in &aliases {+ if cmd.get_subcommands().any(|s| s.get_name() == name.as_str()) {+ continue;+ }+ cmd = cmd.subcommand(build_alias_completion_command(name, cmd_config));+ }+ // Step-level injection: keep historical `wt step <alias>` completions.cmd.mut_subcommand("step", |mut step| {for (name, cmd_config) in aliases {- // Skip aliases that shadow built-in step commandsif step.get_subcommands().any(|s| s.get_name() == name.as_str()){continue;}- // Use the first command's template for the help text- let first_template = cmd_config- .commands()- .next()- .map(|c| c.template.as_str())- .unwrap_or("");- let help = truncate_template(first_template);- // clap::Command::new() requires Into<Str>, and Str only implements- // From<&'static str> (not From<String>). Leak is fine: completion is- // a short-lived subprocess that exits after printing candidates.- let name: &'static str = Box::leak(name.into_boxed_str());- let about: &'static str = Box::leak(format!("alias: {help}").into_boxed_str());- let sub = Command::new(name)- .about(about)- .arg(clap::Arg::new("dry-run").long("dry-run"))- .arg(clap::Arg::new("yes").short('y').long("yes"))- .arg(- clap::Arg::new("var")- .long("var")- .num_args(1)- .action(clap::ArgAction::Append),- );- step = step.subcommand(sub);+ step = step.subcommand(build_alias_completion_command(&name, &cmd_config));}step})}+/// Build a completion stub `clap::Command` for an alias. Leaks strings since+/// completion is a short-lived subprocess that exits after printing candidates.+fn build_alias_completion_command(name: &str, cmd_config: &CommandConfig) -> Command {+ // Use the first command's template for the help text+ let first_template = cmd_config+ .commands()+ .next()+ .map(|c| c.template.as_str())+ .unwrap_or("");+ let help = truncate_template(first_template);+ let name: &'static str = Box::leak(name.to_string().into_boxed_str());+ let about: &'static str = Box::leak(format!("alias: {help}").into_boxed_str());+ Command::new(name)+ .about(about)+ .arg(clap::Arg::new("dry-run").long("dry-run"))+ .arg(clap::Arg::new("yes").short('y').long("yes"))+ .arg(+ clap::Arg::new("var")+ .long("var")+ .num_args(1)+ .action(clap::ArgAction::Append),+ )+}+/// Load aliases from user and project config for completion.////// Merges user and project aliases with append semantics (matching hooks).diff --git a/src/config/project.rs b/src/config/project.rsindex a1b95792a..140dad4d0 100644--- a/src/config/project.rs+++ b/src/config/project.rs@@ -170,7 +170,7 @@ pub struct ProjectConfig {#[serde(default, skip_serializing_if = "is_default")]pub step: StepConfig,- /// \[experimental\] Command aliases for `wt step <name>`.+ /// \[experimental\] Command aliases for `wt <name>`.////// Each alias maps a name to a [`CommandConfig`] — a string for a single/// command, a named table (`[aliases.NAME]`) for concurrent commands, ordiff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex b4a8072c1..0903591ba 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -322,7 +322,7 @@ pub struct UserConfig {#[serde(default, skip_serializing_if = "super::is_default")]pub step: sections::StepConfig,- /// Command aliases for `wt step <name>`+ /// Command aliases for `wt <name>`#[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]pub aliases: std::collections::BTreeMap<String, crate::config::commands::CommandConfig>,diff --git a/src/help.rs b/src/help.rsindex 41bcd14fb..4f2be6ff0 100644--- a/src/help.rs+++ b/src/help.rs@@ -71,10 +71,11 @@ use crate::cli;/// On a help/version/doc-generation request, prints output and calls/// `process::exit(0)`. Otherwise returns so the caller can continue normal parsing.///-/// `is_step_help` is computed by the caller from the same early-parse pass that-/// extracts global options, and controls whether we splice the configured-/// aliases into the rendered output.-pub fn maybe_handle_help_with_pager(is_step_help: bool) {+/// `alias_help_context` is computed by the caller from the same early-parse+/// pass that extracts global options. When `Some`, the configured aliases are+/// spliced into the rendered output — at the top level for `wt --help`, or+/// under the Aliases section for `wt step --help`.+pub fn maybe_handle_help_with_pager(alias_help_context: Option<crate::commands::HelpContext>) {let args: Vec<String> = std::env::args().collect();// --help uses pager, -h prints directly (git convention)@@ -140,13 +141,13 @@ pub fn maybe_handle_help_with_pager(is_step_help: bool) {// Use .ansi() to preserve them; .to_string() strips ANSI codes.let clap_output = err.render().ansi().to_string();- // Splice configured aliases into `wt step --help` / `-h`- // so the help here matches bare `wt step`. Scoped to the- // step subcommand only — other help passes through.- let clap_output = if is_step_help {- crate::commands::augment_step_help(&clap_output)- } else {- clap_output+ // Splice configured aliases into `wt --help` and+ // `wt step --help` (and their `-h` / bare-subcommand+ // equivalents) so the help surfaces both the built-ins and+ // the user's aliases. Other help pages pass through.+ let clap_output = match alias_help_context {+ Some(ctx) => crate::commands::augment_help(&clap_output, ctx),+ None => clap_output,};// Render markdown sections (tables, code blocks, prose) with proper wrapping.diff --git a/src/main.rs b/src/main.rsindex 200a1f868..aac373782 100644--- a/src/main.rs+++ b/src/main.rs@@ -944,17 +944,18 @@ fn parse_cli() -> Option<Cli> {return None;}- // Apply -C / --config before help handling so `wt -C other step --help`+ // Apply -C / --config before help handling so `wt -C other --help`// and `wt --config custom.toml step --help` resolve aliases against the// requested repo and user config (not the process cwd / default config).- // The same early parse also tells us whether this is `wt step` help, so- // the splice path in `augment_step_help` has no separate arg scanner.- let (directory, config, is_step_help) = parse_early_globals();+ // The same early parse also tells us whether this is help for the top+ // level or `wt step`, so the splice path in `augment_help` has no+ // separate arg scanner.+ let (directory, config, alias_help_context) = parse_early_globals();apply_global_options(directory, config);// Handle --help with pager before clap processes it.// Exits the process on a help/version/doc request; otherwise returns.- help::maybe_handle_help_with_pager(is_step_help);+ help::maybe_handle_help_with_pager(alias_help_context);// TODO: Enhance error messages to show possible values for missing enum arguments// Currently `wt config shell init` doesn't show available shells, but `wt config shell init invalid` does.@@ -982,32 +983,40 @@ fn apply_global_options(directory: Option<std::path::PathBuf>, config: Option<st}/// Parse global options (`-C`, `--config`) and detect whether this invocation-/// is `wt step` help, in a single pass against the real `Cli` definition.+/// renders help that should include the configured aliases — in a single pass+/// against the real `Cli` definition.////// Uses `ignore_errors(true)` so unknown args, missing values, and `--help`/// don't abort parsing — we just read what matched. This lets `wt -C other-/// step --help` apply `-C` before the help path renders, so `augment_step_help`+/// --help` apply `-C` before the help path renders, so `augment_help`/// resolves aliases against the requested repo instead of the process cwd.////// Using `cli::build_command()` rather than a hand-rolled mini-command keeps/// the global-flag definitions in one place (the derive on `Cli`), so renaming/// `-C` or adding a value-taking global doesn't silently desync this path.-fn parse_early_globals() -> (Option<std::path::PathBuf>, Option<std::path::PathBuf>, bool) {+fn parse_early_globals() -> (+ Option<std::path::PathBuf>,+ Option<std::path::PathBuf>,+ Option<commands::HelpContext>,+) {let cmd = cli::build_command().ignore_errors(true).disable_help_flag(true);let Ok(matches) = cmd.try_get_matches_from(std::env::args_os()) else {- return (None, None, false);+ return (None, None, None);};let directory = matches.get_one::<std::path::PathBuf>("directory").cloned();let config = matches.get_one::<std::path::PathBuf>("config").cloned();- // `wt step --help` (or `-h`) lands here with the `step` subcommand matched- // and nothing past it. `wt step promote --help` has a nested subcommand- // and should render plain clap help without the aliases splice.- let is_step_help = matches- .subcommand()- .is_some_and(|(name, sub)| name == "step" && sub.subcommand_name().is_none());- (directory, config, is_step_help)+ // Top-level help: `wt --help` (or `-h`, or bare `wt` via `arg_required_else_help`)+ // lands here with no subcommand matched. Step help: `wt step --help` (or+ // `-h`, or bare `wt step`) matches `step` with nothing past it. Other+ // subcommands' help renders plain clap output without the aliases splice.+ let alias_help_context = match matches.subcommand() {+ None => Some(commands::HelpContext::TopLevel),+ Some(("step", sub)) if sub.subcommand_name().is_none() => Some(commands::HelpContext::Step),+ _ => None,+ };+ (directory, config, alias_help_context)}fn init_command_log(command_line: &str) {diff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex f30afd005..bc3e2416d 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -2990,6 +2990,22 @@ fi(dir, path)}+ /// Point the spawned `wt` (and its child shells) at an empty config so+ /// user-config aliases don't leak into completion output. Aliases now+ /// surface as top-level completion candidates, so without this isolation+ /// any global aliases in the developer's `~/.config/worktrunk/config.toml`+ /// would pollute the snapshot.+ ///+ /// Project config (`.config/wt.toml`) is not isolated — the spawned `wt`+ /// runs in this repo's working directory and reads its project config.+ /// Today the project has no `[aliases]` so the snapshot is stable; if a+ /// future contributor adds an alias to this repo's own `.config/wt.toml`,+ /// that alias will start showing up in completion output. Watch for it.+ fn set_empty_user_config(cmd: &mut std::process::Command) {+ cmd.env("WORKTRUNK_CONFIG_PATH", "/dev/null");+ cmd.env("WORKTRUNK_SYSTEM_CONFIG_PATH", "/dev/null");+ }+/// Black-box test: zsh completion produces correct subcommands.////// Sources actual `wt config shell init zsh`, triggers completion, snapshots result.@@ -3023,12 +3039,10 @@ _wt_lazy_complete// `-f` skips ~/.zshenv (which typically sources ~/.cargo/env and// re-prepends ~/.cargo/bin). `/etc/zshenv` is still read — it can't// be bypassed — but doesn't touch PATH in our test environments.- let output = std::process::Command::new("zsh")- .args(["-f", "-c"])- .arg(&script)- .env("PATH", &clean_path)- .output()- .unwrap();+ let mut cmd = std::process::Command::new("zsh");+ cmd.args(["-f", "-c"]).arg(&script).env("PATH", &clean_path);+ set_empty_user_config(&mut cmd);+ let output = cmd.output().unwrap();assert_snapshot!(String::from_utf8_lossy(&output.stdout));}@@ -3058,12 +3072,12 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; done// `--noprofile --norc` skips ~/.bash_profile, ~/.bashrc, /etc/profile// so our clean PATH isn't polluted with ~/.cargo/bin etc.- let output = std::process::Command::new("bash")- .args(["--noprofile", "--norc", "-c"])+ let mut cmd = std::process::Command::new("bash");+ cmd.args(["--noprofile", "--norc", "-c"]).arg(&script)- .env("PATH", &clean_path)- .output()- .unwrap();+ .env("PATH", &clean_path);+ set_empty_user_config(&mut cmd);+ let output = cmd.output().unwrap();assert_snapshot!(String::from_utf8_lossy(&output.stdout));}@@ -3076,13 +3090,13 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; donelet wt_bin = wt_bin();let (_dir, clean_path) = completion_test_path(&wt_bin);- let output = std::process::Command::new(&wt_bin)- .args(["--", "wt", ""])+ let mut cmd = std::process::Command::new(&wt_bin);+ cmd.args(["--", "wt", ""]).env("COMPLETE", "fish").env("_CLAP_COMPLETE_INDEX", "1")- .env("PATH", &clean_path)- .output()- .unwrap();+ .env("PATH", &clean_path);+ set_empty_user_config(&mut cmd);+ let output = cmd.output().unwrap();// Fish format is "value\tdescription" - extract just valueslet completions: String = String::from_utf8_lossy(&output.stdout)@@ -3102,12 +3116,12 @@ for c in "${{COMPREPLY[@]}}"; do echo "${{c%% *}}"; donelet wt_bin = wt_bin();let (_dir, clean_path) = completion_test_path(&wt_bin);- let output = std::process::Command::new(&wt_bin)- .args(["--", "wt", ""])+ let mut cmd = std::process::Command::new(&wt_bin);+ cmd.args(["--", "wt", ""]).env("COMPLETE", "nu")- .env("PATH", &clean_path)- .output()- .unwrap();+ .env("PATH", &clean_path);+ set_empty_user_config(&mut cmd);+ let output = cmd.output().unwrap();// Nushell format is "value\tdescription" - extract just valueslet completions: String = String::from_utf8_lossy(&output.stdout)diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 58a82ca56..9f7cbceb2 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -211,14 +211,40 @@ greet = "echo Greetings from {{ branch }}"));}-/// Shadowed aliases are filtered from the "available" list in error messages+/// Top-level alias dispatch: `wt <name>` runs an alias when `<name>` is not+/// a built-in subcommand, with the same template-expansion and approval flow+/// as `wt step <name>`.#[rstest]-fn test_step_alias_shadows_builtin(mut repo: TestRepo) {+fn test_top_level_alias_dispatch(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+hello = "echo Hello from {{ branch }}"+"#,+ );+ repo.commit("Add alias config");+ let feature_path = repo.add_worktree("feature");++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "hello",+ &["--yes"],+ Some(&feature_path),+ ));+}++/// An alias whose name matches a `wt step` built-in is unreachable via+/// `wt step <name>` (the built-in always wins) but runs from the top level+/// via `wt <name>` — there's no top-level `commit` built-in.+#[rstest]+fn test_top_level_alias_with_step_builtin_name(mut repo: TestRepo) {repo.write_project_config(r#"[aliases]commit = "echo custom-commit"-hello = "echo hello""#,);repo.commit("Add alias config");@@ -227,24 +253,43 @@ hello = "echo hello"let settings = setup_snapshot_settings(&repo);let _guard = settings.bind_to_scope();- // "commit" is shadowed by the built-in and should not appear in available listassert_cmd_snapshot!(make_snapshot_cmd(&repo,- "step",- &["nonexistent"],+ "commit",+ &["--yes"],Some(&feature_path),));}-/// Multiple shadowed aliases use plural grammar+/// Top-level typo on an alias name suggests the alias in the `tip:` line,+/// matching `wt step <typo>`.+#[rstest]+fn test_top_level_alias_did_you_mean(mut repo: TestRepo) {+ repo.write_project_config(+ r#"+[aliases]+deploy = "make deploy"+hello = "echo Hello"+"#,+ );+ repo.commit("Add alias config");+ let feature_path = repo.add_worktree("feature");++ let settings = setup_snapshot_settings(&repo);+ let _guard = settings.bind_to_scope();++ assert_cmd_snapshot!(make_snapshot_cmd(&repo, "deplyo", &[], Some(&feature_path),));+}++/// Aliases shadowed by `wt step` built-ins are filtered from the typo+/// suggestion list — `wt step commit` does not suggest a (shadowed) alias+/// named `commit`, only the real built-in.#[rstest]-fn test_step_alias_shadows_builtin_plural(mut repo: TestRepo) {+fn test_step_alias_shadows_builtin(mut repo: TestRepo) {repo.write_project_config(r#"[aliases]commit = "echo custom-commit"-rebase = "echo custom-rebase"-hello = "echo hello""#,);repo.commit("Add alias config");@@ -256,7 +301,7 @@ hello = "echo hello"assert_cmd_snapshot!(make_snapshot_cmd(&repo,"step",- &["nonexistent"],+ &["comit"],Some(&feature_path),));}diff --git a/tests/snapshots/integration__integration_tests__help__help_config_create.snap b/tests/snapshots/integration__integration_tests__help__help_config_create.snapindex f9db6adb5..85830b5a9 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_create.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_create.snap@@ -185,7 +185,7 @@ Creates [2m~/.config/worktrunk/config.toml[0m with the following content:[107m [0m [2m#[0m[107m [0m [2m# ### Aliases[0m[107m [0m [2m#[0m-[107m [0m [2m# Command templates that run with `wt step <name>`. See `wt step` aliases (https://worktrunk.dev/step/#aliases) for usage and flags.[0m+[107m [0m [2m# Command templates that run as `wt <name>`. See Aliases (https://worktrunk.dev/extending/#aliases) for usage and flags.[0m[107m [0m [2m#[0m[107m [0m [2m# [aliases][0m[107m [0m [2m# greet = "echo Hello from {{ branch }}"[0m@@ -349,7 +349,7 @@ With [2m--project[0m, creates [2m.config/wt.toml[0m in the current repositor[107m [0m [2m#[0m[107m [0m [2m# ## Aliases[0m[107m [0m [2m#[0m-[107m [0m [2m# Command templates that run with `wt step <name>`. See `wt step` aliases (https://worktrunk.dev/step/#aliases) for usage and flags.[0m+[107m [0m [2m# Command templates that run as `wt <name>`. See Aliases (https://worktrunk.dev/extending/#aliases) for usage and flags.[0m[107m [0m [2m#[0m[107m [0m [2m# [aliases][0m[107m [0m [2m# deploy = "make deploy BRANCH={{ branch }}"[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 6d1af8a7f..ac32f6a8f 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -231,7 +231,7 @@ Built-in excludes always apply: VCS metadata directories ([2m.bzr/[0m, [2m.hg[32mAliases[0m-Command templates that run with [2mwt step <name>[0m. See [2mwt step[0m aliases for usage and flags.+Command templates that run as [2mwt <name>[0m. See Aliases for usage and flags.[107m [0m [2m[36m[aliases][0m[107m [0m [2mgreet = [0m[2m[32m"echo Hello from {{ branch }}"[0m@@ -386,7 +386,7 @@ Built-in excludes always apply: VCS metadata directories ([2m.bzr/[0m, [2m.hg[1m[32mAliases[0m-Command templates that run with [2mwt step <name>[0m. See [2mwt step[0m aliases for usage and flags.+Command templates that run as [2mwt <name>[0m. See Aliases for usage and flags.[107m [0m [2m[36m[aliases][0m[107m [0m [2mdeploy = [0m[2m[32m"make deploy BRANCH={{ branch }}"[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_step_long.snap b/tests/snapshots/integration__integration_tests__help__help_step_long.snapindex 7aa6604ad..93a5ebec9 100644--- a/tests/snapshots/integration__integration_tests__help__help_step_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_step_long.snap@@ -89,64 +89,12 @@ Manual merge workflow with review between steps:- [2mpromote[0m — [experimental] Swap a branch into the main worktree- [2mprune[0m — Remove worktrees and branches merged into the default branch- [2mrelocate[0m — [experimental] Move worktrees to expected paths-- [2m<alias>[0m — [experimental] Run a configured command alias+- [2m<alias>[0m — [experimental] Run a configured command alias (see Aliases)[1m[32mSee also[0m- [2mwt merge[0m — Runs commit → squash → rebase → hooks → push → cleanup automatically- [2mwt hook[0m — Run configured hooks--[1m[32mAliases [experimental][0m--Custom command templates configured in user config ([2m~/.config/worktrunk/config.toml[0m) or project config ([2m.config/wt.toml[0m). Aliases support the same template variables as hooks.--[107m [0m [2m# .config/wt.toml[0m-[107m [0m [2m[36m[aliases][0m-[107m [0m [2mdeploy = [0m[2m[32m"make deploy BRANCH={{ branch }}"[0m-[107m [0m [2mport = [0m[2m[32m"echo http://localhost:{{ branch | hash_port }}"[0m--[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy # run the alias[0m[2m[0m-[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy [0m[2m[36m--dry-run[0m[2m # show expanded command[0m[2m[0m-[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy [0m[2m[36m--env=staging[0m[2m # pass template variable[0m[2m[0m-[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy [0m[2m[36m--var[0m[2m env=staging # equivalent long form[0m[2m[0m-[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy [0m[2m[36m--my-var=value[0m[2m # hyphens become underscores ([0m[2m[32m{{[0m[2m my_var [0m[2m[32m}}[0m[2m)[0m[2m[0m-[107m [0m [2m[0m[2m[34mwt[0m[2m step deploy [0m[2m[36m--yes[0m[2m # skip approval prompt[0m[2m[0m--Hyphens in variable names are canonicalized to underscores at parse time, so [2m--my-var=value[0m is referenced as [2m{{ my_var }}[0m in templates. This lets flags use natural kebab-case while avoiding the minijinja parser's interpretation of [2m{{ my-var }}[0m as subtraction.--Multi-line aliases work too. This [2mup[0m alias fetches all remotes and rebases each worktree onto its upstream, skipping worktrees without a tracking branch or with a rebase already in progress:--[107m [0m [2m# ~/.config/worktrunk/config.toml[0m-[107m [0m [2m[36m[aliases][0m-[107m [0m [2mup = [0m[2m[32m''[0m[2m[32m'[0m-[107m [0m [2m[32mgit fetch --all --prune && wt step for-each -- '[0m-[107m [0m [2m git rev-parse --verify -q @{u} >/dev/null || exit 0[0m-[107m [0m [2m g=$(git rev-parse --git-dir)[0m-[107m [0m [2m test -d [0m[2m[32m"$g/rebase-merge"[0m[2m -o -d [0m[2m[32m"$g/rebase-apply"[0m[2m && exit 0[0m-[107m [0m [2m git rebase @{u} --no-autostash || git rebase --abort[0m-[107m [0m [2m[32m''[0m[2m[32m''[0m--[107m [0m [2m[0m[2m[34mwt[0m[2m step up[0m--Multi-step aliases run commands in order using [2m[[aliases.NAME]][0m blocks. Each block is one step; multiple keys within a block run concurrently.--[107m [0m [2m# .config/wt.toml[0m-[107m [0m [2m[36m[[aliases.release]][0m-[107m [0m [2mtest = [0m[2m[32m"cargo test"[0m-[107m [0m-[107m [0m [2m[36m[[aliases.release]][0m-[107m [0m [2mbuild = [0m[2m[32m"cargo build --release"[0m-[107m [0m [2mpackage = [0m[2m[32m"cargo package --no-verify"[0m-[107m [0m-[107m [0m [2m[36m[[aliases.release]][0m-[107m [0m [2mpublish = [0m[2m[32m"cargo publish"[0m--Here [2mtest[0m runs first, then [2mbuild[0m and [2mpackage[0m run together, then [2mpublish[0m runs last. A step failure aborts the remaining steps.--When defined in both user and project config, both run — user first, then project. Project-config aliases require command approval on first run, same as project hooks. User-config aliases are trusted.--Inside an alias body, an inner [2mwt switch[0m (or [2mwt switch --create[0m) passes its [2mcd[0m through to the parent shell, so an alias wrapping [2mwt switch --create[0m lands the shell in the new worktree just like running it directly.--Alias names that match a built-in step command ([2mcommit[0m, [2msquash[0m, etc.) are shadowed by the built-in and will never run.+- Aliases — Custom command templates run as [2mwt <name>[0m----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin.snapindex 732690f00..cad5ad1bc 100644--- a/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin.snap@@ -4,7 +4,7 @@ info:program: wtargs:- step- - nonexistent+ - comitenv:APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"@@ -44,8 +44,9 @@ exit_code: 2----- stdout ---------- stderr ------[33m▲[39m [33mAlias [1mcommit[22m shadows a built-in step command and will never run[39m-[1m[31merror:[0m unrecognized subcommand '[33mnonexistent[0m'+[1m[31merror:[0m unrecognized subcommand '[33mcomit[0m'++ [32mtip:[0m a similar subcommand exists: '[32mcommit[0m'[1m[4mUsage:[0m [1mwt step[0m <COMMAND>diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin_plural.snap b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_did_you_mean.snapsimilarity index 80%rename from tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin_plural.snaprename to tests/snapshots/integration__integration_tests__step_alias__top_level_alias_did_you_mean.snapindex c1b025e0c..598129f3b 100644--- a/tests/snapshots/integration__integration_tests__step_alias__step_alias_shadows_builtin_plural.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_did_you_mean.snap@@ -3,8 +3,7 @@ source: tests/integration_tests/step_alias.rsinfo:program: wtargs:- - step- - nonexistent+ - deplyoenv:APPDATA: "[TEST_CONFIG_HOME]"CLICOLOR_FORCE: "1"@@ -44,9 +43,10 @@ exit_code: 2----- stdout ---------- stderr ------[33m▲[39m [33mAliases [1mcommit[22m, [1mrebase[22m shadow built-in step commands and will never run[39m-[1m[31merror:[0m unrecognized subcommand '[33mnonexistent[0m'+[1m[31merror:[0m unrecognized subcommand '[1m[33mdeplyo[0m'-[1m[4mUsage:[0m [1mwt step[0m <COMMAND>+ [1m[32mtip:[0m some similar subcommands exist: '[1m[32mdeploy[0m', '[1m[32mhello[0m'-For more information, try '[1m--help[0m'.+[1m[32mUsage:[0m [1m[36mwt[0m [36m[OPTIONS][0m [36m[COMMAND]++For more information, try '[1m[36m--help[0m'.diff --git a/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_dispatch.snap b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_dispatch.snapnew file mode 100644index 000000000..33c4c7318--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_dispatch.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - hello+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning alias [1mhello[22m[39m+[0mHello from featurediff --git a/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_with_step_builtin_name.snap b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_with_step_builtin_name.snapnew file mode 100644index 000000000..0b87a85e5--- /dev/null+++ b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_with_step_builtin_name.snap@@ -0,0 +1,48 @@+---+source: tests/integration_tests/step_alias.rs+info:+ program: wt+ args:+ - commit+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"+ NO_COLOR: ""+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ PSModulePath: ""+ RUST_LOG: warn+ SHELL: ""+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: true+exit_code: 0+----- stdout -----++----- stderr -----+[36m◎[39m [36mRunning alias [1mcommit[22m[39m+[0mcustom-commit