Skip to content

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

feat(alias): route --key=value via template refs, add -- escape, drop --var (#2287)

Maximilian Roos8e3abf46db0f
diff --git a/docs/content/extending.md b/docs/content/extending.md
index b6dc70242..cc9174f46 100644
--- a/docs/content/extending.md
+++ b/docs/content/extending.md
@@ -112,15 +112,40 @@ Aliases are custom commands invoked as `wt <name>`. They share the same template
```toml
[aliases]
-deploy = "make deploy BRANCH={{ branch }}"
+deploy = "make deploy BRANCH={{ branch }} ENV={{ env }}"
open = "open http://localhost:{{ branch | hash_port }}"
```
-{{ terminal(cmd="wt deploy|||wt deploy --dry-run|||wt deploy --env=staging") }}
+{{ terminal(cmd="wt deploy --env=staging|||wt deploy --dry-run --env=prod") }}
`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.
+### How arguments are routed
+
+Tokens after the alias name fall into one of these buckets, decided by what the alias's template references:
+
+| Token shape | Routes to |
+|---|---|
+| `--KEY=VALUE` or `--KEY VALUE` where the template references `{{ KEY }}` | Bound — `KEY` becomes the template value |
+| `--KEY=VALUE` where the template doesn't reference `KEY` | Forwarded literally to `{{ args }}` |
+| `--KEY` followed by another flag or end of args | Forwarded literally to `{{ args }}` |
+| Bare positional (no `--` prefix) | Forwarded to `{{ args }}` |
+| Anything after a literal `--` | Forwarded to `{{ args }}` regardless of shape |
+
+Built-in flags (`--yes`/`-y`, `--dry-run`) are always recognized, so an alias can't shadow them. Built-in template variables (`branch`, `worktree_path`, `commit`, …) can be overridden — `--branch=override` for an alias referencing `{{ branch }}` binds to the user's value, but only inside the template; the worktree's actual branch is unchanged.
+
+Hyphens in variable names are canonicalized to underscores at parse time. `--my-var=value` binds to `{{ my_var }}` because minijinja parses `{{ my-var }}` as subtraction.
+
+### Escaping with `--`
+
+Use `--` to forward a flag-shaped value literally instead of letting the parser bind it. Everything after `--` goes into `{{ args }}` verbatim:
+
+```toml
+[aliases]
+search = "rg {{ args }}"
+```
+
+{{ terminal(cmd="wt search -- --hidden --glob '*.rs' pattern # --hidden and --glob reach rg, not the alias parser") }}
### Forwarding positional arguments
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index fddd98535..0e866040c 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -105,19 +105,45 @@ Aliases are custom commands invoked as `wt <name>`. They share the same template
```toml
[aliases]
-deploy = "make deploy BRANCH={{ branch }}"
+deploy = "make deploy BRANCH={{ branch }} ENV={{ env }}"
open = "open http://localhost:{{ branch | hash_port }}"
```
```bash
-wt deploy
-wt deploy --dry-run
wt deploy --env=staging
+wt deploy --dry-run --env=prod
```
`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.
+### How arguments are routed
+
+Tokens after the alias name fall into one of these buckets, decided by what the alias's template references:
+
+| Token shape | Routes to |
+|---|---|
+| `--KEY=VALUE` or `--KEY VALUE` where the template references `{{ KEY }}` | Bound — `KEY` becomes the template value |
+| `--KEY=VALUE` where the template doesn't reference `KEY` | Forwarded literally to `{{ args }}` |
+| `--KEY` followed by another flag or end of args | Forwarded literally to `{{ args }}` |
+| Bare positional (no `--` prefix) | Forwarded to `{{ args }}` |
+| Anything after a literal `--` | Forwarded to `{{ args }}` regardless of shape |
+
+Built-in flags (`--yes`/`-y`, `--dry-run`) are always recognized, so an alias can't shadow them. Built-in template variables (`branch`, `worktree_path`, `commit`, …) can be overridden — `--branch=override` for an alias referencing `{{ branch }}` binds to the user's value, but only inside the template; the worktree's actual branch is unchanged.
+
+Hyphens in variable names are canonicalized to underscores at parse time. `--my-var=value` binds to `{{ my_var }}` because minijinja parses `{{ my-var }}` as subtraction.
+
+### Escaping with `--`
+
+Use `--` to forward a flag-shaped value literally instead of letting the parser bind it. Everything after `--` goes into `{{ args }}` verbatim:
+
+```toml
+[aliases]
+search = "rg {{ args }}"
+```
+
+```bash
+wt search -- --hidden --glob '*.rs' pattern # --hidden and --glob reach rg, not the alias parser
+```
### Forwarding positional arguments
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index aea06ebff..689a5678f 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -30,14 +30,14 @@
//! the EXEC directive file is scrubbed so alias bodies cannot inject
//! arbitrary shell into the interactive session.
-use std::collections::{BTreeMap, HashMap};
+use std::collections::{BTreeMap, BTreeSet, HashMap};
use anyhow::{Context, bail};
use clap::error::{ContextKind, ContextValue, ErrorKind};
use color_print::cformat;
use worktrunk::config::{
ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases,
- template_references_var, validate_template_syntax,
+ referenced_vars_for_config, template_references_var, validate_template_syntax,
};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, format_bash_with_gutter, info_message, progress_message};
@@ -90,27 +90,42 @@ pub struct AliasOptions {
}
impl AliasOptions {
- /// Parse alias options from `wt step <alias>` args.
+ /// Parse alias options from `wt step <alias>` args, routing each token
+ /// using `referenced_vars` (the union of `{{ key }}` references across the
+ /// alias's pipeline templates).
///
- /// First element is the alias name, remaining tokens are either flags:
- /// `--dry-run`, `--var KEY=VALUE`, or `--KEY=VALUE`; or positional args
- /// that get forwarded to the template as `{{ args }}`.
+ /// First element is the alias name. Remaining tokens are walked
+ /// left-to-right under this grammar:
///
- /// Unknown `--key=value` flags are treated as template variable assignments,
- /// so `--env=staging` is equivalent to `--var env=staging`. The `=` is
- /// required — bare `--key` flags (without a value) are rejected. Use
- /// `--var KEY=VALUE` if a variable name collides with a built-in flag.
+ /// - `--` — literal-forward escape: every later token goes straight into
+ /// `positional_args`, no var binding.
+ /// - `--dry-run` — sets `dry_run`.
+ /// - `--KEY=VALUE` — binds `KEY=VALUE` if `KEY` is in `referenced_vars`,
+ /// otherwise forwards the whole `--KEY=VALUE` token as a positional.
+ /// - `--KEY VALUE` (separated by space, `VALUE` doesn't start with `--`)
+ /// — binds `KEY=VALUE` if `KEY` is in `referenced_vars`, otherwise
+ /// forwards `--KEY` as a positional and re-examines `VALUE` at its
+ /// normal position.
+ /// - `--KEY` followed by another `--…` (or end of args) — forwards
+ /// `--KEY` as a positional.
+ /// - Anything else — forwards as a positional.
///
- /// `--yes`/`-y` is a top-level global flag (`wt -y <alias>`) and is not
- /// recognized after the alias name — clap's `global = true` does not
- /// propagate flags across an `external_subcommand` boundary. A post-alias
- /// `--yes` errors here as an unknown flag; `-y` (single-dash) falls into
- /// the positional-args branch and gets forwarded to `{{ args }}` as `"-y"`.
+ /// `--yes`/`-y` is a top-level global flag (`wt -y <alias>`); the
+ /// post-alias form is not recognized here. `--yes` follows the
+ /// `--KEY` rule (forwards as positional unless `yes` is referenced),
+ /// and `-y` is a bare positional. Clap's `global = true` doesn't
+ /// propagate across `external_subcommand`, so the post-alias form
+ /// never reaches the global parser anyway.
///
- /// Hyphens in variable names are canonicalized to underscores so users can
- /// write `--my-var=value` and reference `{{ my_var }}` in templates
- /// (minijinja parses `{{ my-var }}` as subtraction).
- pub fn parse(args: Vec<String>) -> anyhow::Result<Self> {
+ /// Hyphens in variable names are canonicalized to underscores before
+ /// lookup and storage (minijinja parses `{{ my-var }}` as subtraction),
+ /// so `--my-var=value` binds to `{{ my_var }}` when the template
+ /// references it.
+ ///
+ /// `referenced_vars` is expected to contain the canonical underscore
+ /// form. `referenced_vars_for_config` produces it directly from the
+ /// alias's template.
+ pub fn parse(args: Vec<String>, referenced_vars: &BTreeSet<String>) -> anyhow::Result<Self> {
let Some(name) = args.first().cloned() else {
bail!("Missing alias name");
};
@@ -118,40 +133,55 @@ impl AliasOptions {
let mut dry_run = false;
let mut vars = Vec::new();
let mut positional_args = Vec::new();
+ let mut literal_mode = false;
let mut i = 1;
while i < args.len() {
- match args[i].as_str() {
- "--dry-run" => dry_run = true,
- "--var" => {
- i += 1;
- if i >= args.len() {
- bail!("--var requires a KEY=VALUE argument");
+ let arg = &args[i];
+ if literal_mode {
+ positional_args.push(arg.clone());
+ i += 1;
+ continue;
+ }
+ if arg == "--" {
+ literal_mode = true;
+ i += 1;
+ continue;
+ }
+ if arg == "--dry-run" {
+ dry_run = true;
+ i += 1;
+ continue;
+ }
+ if let Some(rest) = arg.strip_prefix("--") {
+ if let Some((key, value)) = rest.split_once('=') {
+ if key.is_empty() {
+ bail!("invalid KEY=VALUE: key cannot be empty");
}
- let pair =
- crate::cli::parse_key_val(&args[i]).map_err(|e| anyhow::anyhow!(e))?;
- vars.push(pair);
- }
- arg if arg.starts_with("--var=") => {
- let pair = crate::cli::parse_key_val(arg.strip_prefix("--var=").unwrap())
- .map_err(|e| anyhow::anyhow!(e))?;
- vars.push(pair);
- }
- arg if arg.starts_with("--") => {
- let rest = &arg[2..];
- if rest.contains('=') {
- let pair =
- crate::cli::parse_key_val(rest).map_err(|e| anyhow::anyhow!(e))?;
- vars.push(pair);
+ let canon = key.replace('-', "_");
+ if referenced_vars.contains(&canon) {
+ vars.push((canon, value.to_string()));
} else {
- bail!(
- "Unknown flag '{arg}' for alias '{name}' (use --{rest}=VALUE to pass a variable)"
- );
+ positional_args.push(arg.clone());
}
+ i += 1;
+ continue;
}
- other => {
- positional_args.push(other.to_string());
+ let canon = rest.replace('-', "_");
+ if let Some(next) = args.get(i + 1)
+ && !next.starts_with("--")
+ && referenced_vars.contains(&canon)
+ {
+ vars.push((canon, next.clone()));
+ i += 2;
+ continue;
}
+ // No bindable destination: forward the flag token as positional;
+ // the next token is re-examined at its normal position.
+ positional_args.push(arg.clone());
+ i += 1;
+ continue;
}
+ positional_args.push(arg.clone());
i += 1;
}
@@ -288,27 +318,36 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::R
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) {
+ let Some(cmd_config) = aliases.get(&name) else {
return Ok(None);
- }
+ };
+ let referenced = referenced_vars_for_config(cmd_config);
let mut alias_args = Vec::with_capacity(1 + rest.len());
alias_args.push(name);
alias_args.extend(rest);
- let opts = AliasOptions::parse(alias_args)?;
+ let opts = AliasOptions::parse(alias_args, &referenced)?;
run_alias(opts, repo, user_config, project_config, aliases, global_yes).map(Some)
}
/// Run a configured alias from `wt step <name>`. Errors with a clap-style
/// "unrecognized subcommand" if the alias isn't configured.
///
+/// Argument parsing happens inside this function — not at the clap dispatch
+/// site in `main.rs` — because the routing of `--KEY=VALUE` tokens depends on
+/// which template variables the alias references, which requires the alias's
+/// resolved `CommandConfig`.
+///
/// `global_yes` is the top-level `--yes`/`-y` flag, passed through to
/// `run_alias`.
-pub fn step_alias(opts: AliasOptions, global_yes: bool) -> anyhow::Result<()> {
+pub fn step_alias(args: Vec<String>, global_yes: bool) -> 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) {
+ let Some(name) = args.first().cloned() else {
+ bail!("Missing alias name");
+ };
+ let Some(cmd_config) = aliases.get(&name) else {
// 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
@@ -320,8 +359,10 @@ pub fn step_alias(opts: AliasOptions, global_yes: bool) -> anyhow::Result<()> {
.filter(|k| !BUILTIN_STEP_COMMANDS.contains(&k.as_str()))
.map(|k| k.as_str())
.collect();
- unknown_step_command_exit(&opts.name, &alias_names);
- }
+ unknown_step_command_exit(&name, &alias_names);
+ };
+ let referenced = referenced_vars_for_config(cmd_config);
+ let opts = AliasOptions::parse(args, &referenced)?;
run_alias(opts, repo, user_config, project_config, aliases, global_yes)
}
@@ -732,8 +773,17 @@ mod tests {
use super::*;
use ansi_str::AnsiStr;
+ /// Parse with an explicit `referenced_vars` set. Tests build the set
+ /// directly to exercise routing without needing a full template fixture.
+ fn parse_with(args: &[&str], referenced: &[&str]) -> anyhow::Result<AliasOptions> {
+ let refs: BTreeSet<String> = referenced.iter().map(|s| s.to_string()).collect();
+ AliasOptions::parse(args.iter().map(|s| s.to_string()).collect(), &refs)
+ }
+
+ /// Convenience wrapper for tests that don't care about var routing —
+ /// every `--KEY=VALUE` token forwards as a positional.
fn parse(args: &[&str]) -> anyhow::Result<AliasOptions> {
- AliasOptions::parse(args.iter().map(|s| s.to_string()).collect())
+ parse_with(args, &[])
}
/// Parse a TOML snippet of the form `cmd = ...` into a CommandConfig.
@@ -808,8 +858,9 @@ cmd = [
}
#[test]
- fn test_parse() {
+ fn test_parse_built_in_flags() {
use insta::assert_debug_snapshot;
+ // Plain alias name only.
assert_debug_snapshot!(parse(&["deploy"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -818,6 +869,7 @@ cmd = [
positional_args: [],
}
"#);
+ // --dry-run is recognized regardless of referenced_vars.
assert_debug_snapshot!(parse(&["deploy", "--dry-run"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -826,35 +878,38 @@ cmd = [
positional_args: [],
}
"#);
- assert_debug_snapshot!(parse(&["deploy", "--var", "key=value"]).unwrap(), @r#"
+ }
+
+ #[test]
+ fn test_parse_key_value_routing() {
+ use insta::assert_debug_snapshot;
+ // --KEY=VALUE binds when the template references KEY.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env=staging"], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
vars: [
(
- "key",
- "value",
+ "env",
+ "staging",
),
],
positional_args: [],
}
"#);
- // --var=key=value (equals form)
- assert_debug_snapshot!(parse(&["deploy", "--var=key=value"]).unwrap(), @r#"
+ // --KEY=VALUE forwards as positional when KEY is NOT referenced.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env=staging"], &[]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
- vars: [
- (
- "key",
- "value",
- ),
+ vars: [],
+ positional_args: [
+ "--env=staging",
],
- positional_args: [],
}
"#);
- // Value containing equals sign
- assert_debug_snapshot!(parse(&["deploy", "--var", "url=http://host?a=1"]).unwrap(), @r#"
+ // Equals-in-value still parses correctly when bound.
+ assert_debug_snapshot!(parse_with(&["deploy", "--url=http://host?a=1"], &["url"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
@@ -867,40 +922,38 @@ cmd = [
positional_args: [],
}
"#);
- // Multiple vars + flags
- assert_debug_snapshot!(parse(&["deploy", "--var", "a=1", "--var", "b=2", "--dry-run"]).unwrap(), @r#"
+ // Empty value accepted on bind.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env="], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
- dry_run: true,
+ dry_run: false,
vars: [
(
- "a",
- "1",
- ),
- (
- "b",
- "2",
+ "env",
+ "",
),
],
positional_args: [],
}
"#);
- // Empty value accepted
- assert_debug_snapshot!(parse(&["deploy", "--var", "key="]).unwrap(), @r#"
+ // Empty value forwarded literally when KEY is not referenced.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env="], &[]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
- vars: [
- (
- "key",
- "",
- ),
+ vars: [],
+ positional_args: [
+ "--env=",
],
- positional_args: [],
}
"#);
- // --key=value shorthand
- assert_debug_snapshot!(parse(&["deploy", "--env=staging"]).unwrap(), @r#"
+ }
+
+ #[test]
+ fn test_parse_space_separated_routing() {
+ use insta::assert_debug_snapshot;
+ // --KEY VALUE binds when KEY is referenced and VALUE is non-flag.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env", "staging"], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
@@ -913,54 +966,50 @@ cmd = [
positional_args: [],
}
"#);
- // --key=value with equals in value
- assert_debug_snapshot!(parse(&["deploy", "--url=http://host?a=1"]).unwrap(), @r#"
+ // --KEY VALUE forwards both as positionals when KEY is NOT referenced.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env", "staging"], &[]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
- vars: [
- (
- "url",
- "http://host?a=1",
- ),
+ vars: [],
+ positional_args: [
+ "--env",
+ "staging",
],
- positional_args: [],
}
"#);
- // --key=value mixed with --var and flags
- assert_debug_snapshot!(parse(&["deploy", "--env=prod", "--var", "region=us-east", "--dry-run"]).unwrap(), @r#"
+ // --KEY followed by another --flag: --KEY forwards alone, the next
+ // flag is processed at its normal position.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env", "--other"], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
- dry_run: true,
- vars: [
- (
- "env",
- "prod",
- ),
- (
- "region",
- "us-east",
- ),
+ dry_run: false,
+ vars: [],
+ positional_args: [
+ "--env",
+ "--other",
],
- positional_args: [],
}
"#);
- // --key= (empty value)
- assert_debug_snapshot!(parse(&["deploy", "--env="]).unwrap(), @r#"
+ // --KEY at end of args: nothing to consume, forwards alone.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env"], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
- vars: [
- (
- "env",
- "",
- ),
+ vars: [],
+ positional_args: [
+ "--env",
],
- positional_args: [],
}
"#);
- // Hyphens in shorthand key are canonicalized to underscores
- assert_debug_snapshot!(parse(&["deploy", "--my-var=value"]).unwrap(), @r#"
+ }
+
+ #[test]
+ fn test_parse_hyphen_canonicalization() {
+ use insta::assert_debug_snapshot;
+ // Hyphens in the key are canonicalized to underscores before lookup
+ // and storage. The set is keyed in canonical form.
+ assert_debug_snapshot!(parse_with(&["deploy", "--my-var=value"], &["my_var"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
@@ -973,8 +1022,8 @@ cmd = [
positional_args: [],
}
"#);
- // Hyphens in --var KEY=VALUE are canonicalized too
- assert_debug_snapshot!(parse(&["deploy", "--var", "my-var=value"]).unwrap(), @r#"
+ // Already-underscored keys pass through.
+ assert_debug_snapshot!(parse_with(&["deploy", "--my_var=value"], &["my_var"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
@@ -987,63 +1036,118 @@ cmd = [
positional_args: [],
}
"#);
- // Hyphens in --var=KEY=VALUE form
- assert_debug_snapshot!(parse(&["deploy", "--var=my-var=value"]).unwrap(), @r#"
+ // Hyphens in the value are preserved (only the key is canonicalized).
+ assert_debug_snapshot!(parse_with(&["deploy", "--region=us-east-1"], &["region"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
vars: [
(
- "my_var",
- "value",
+ "region",
+ "us-east-1",
),
],
positional_args: [],
}
"#);
- // Already-underscored keys pass through unchanged
- assert_debug_snapshot!(parse(&["deploy", "--my_var=value"]).unwrap(), @r#"
+ }
+
+ #[test]
+ fn test_parse_literal_forward_escape() {
+ use insta::assert_debug_snapshot;
+ // After `--`, every token is positional regardless of whether it
+ // looks like a flag or whether the template would have bound it.
+ assert_debug_snapshot!(parse_with(&["deploy", "--env=staging", "--", "--env=other", "x"], &["env"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
vars: [
(
- "my_var",
- "value",
+ "env",
+ "staging",
),
],
- positional_args: [],
+ positional_args: [
+ "--env=other",
+ "x",
+ ],
}
"#);
- // Multiple hyphens in a single key
- assert_debug_snapshot!(parse(&["deploy", "--long-var-name=x"]).unwrap(), @r#"
+ // `--` itself is consumed but does not appear in positionals;
+ // built-in flags after `--` forward as positional too.
+ assert_debug_snapshot!(parse_with(&["deploy", "--", "--yes", "-y", "--dry-run"], &[]).unwrap(), @r#"
AliasOptions {
name: "deploy",
dry_run: false,
- vars: [
- (
- "long_var_name",
- "x",
- ),
+ vars: [],
+ positional_args: [
+ "--yes",
+ "-y",
+ "--dry-run",
],
+ }
+ "#);
+ // Trailing `--` with nothing after: consumed silently, no positionals.
+ assert_debug_snapshot!(parse_with(&["deploy", "--"], &[]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: false,
+ vars: [],
positional_args: [],
}
"#);
- // Hyphens in value are preserved (only key is canonicalized)
- assert_debug_snapshot!(parse(&["deploy", "--region=us-east-1"]).unwrap(), @r#"
+ // A second `--` inside literal mode is just another positional —
+ // literal_mode never resets, matching POSIX `--` semantics.
+ assert_debug_snapshot!(parse_with(&["deploy", "--", "a", "--", "b"], &[]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: false,
+ vars: [],
+ positional_args: [
+ "a",
+ "--",
+ "b",
+ ],
+ }
+ "#);
+ }
+
+ #[test]
+ fn test_parse_mixed_pipeline() {
+ use insta::assert_debug_snapshot;
+ // Multiple referenced vars bind from a mix of `--KEY VALUE` and
+ // `--KEY=VALUE` forms; bare positionals interleave.
+ assert_debug_snapshot!(
+ parse_with(
+ &["deploy", "--env", "prod", "--region=us-east", "thing"],
+ &["env", "region"],
+ ).unwrap(),
+ @r#"
AliasOptions {
name: "deploy",
dry_run: false,
vars: [
+ (
+ "env",
+ "prod",
+ ),
(
"region",
- "us-east-1",
+ "us-east",
),
],
- positional_args: [],
+ positional_args: [
+ "thing",
+ ],
}
- "#);
- // Single positional is forwarded as `{{ args }}`
+ "#
+ );
+ }
+
+ #[test]
+ fn test_parse_positionals() {
+ use insta::assert_debug_snapshot;
+ // Single positional forwarded.
assert_debug_snapshot!(parse(&["s", "some-branch"]).unwrap(), @r#"
AliasOptions {
name: "s",
@@ -1054,7 +1158,7 @@ cmd = [
],
}
"#);
- // Multiple positionals preserve CLI order
+ // Multiple positionals preserve CLI order.
assert_debug_snapshot!(parse(&["deploy", "one", "two", "three"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -1067,7 +1171,7 @@ cmd = [
],
}
"#);
- // Positionals can interleave with flags; flags are captured, positionals keep order
+ // Built-in flags can interleave with positionals.
assert_debug_snapshot!(parse(&["deploy", "foo", "--dry-run", "bar"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -1079,8 +1183,8 @@ cmd = [
],
}
"#);
- // Positionals containing spaces or shell metacharacters pass through verbatim —
- // escaping happens only at template render time.
+ // Positionals with shell metacharacters pass through verbatim —
+ // escaping happens at template render time.
assert_debug_snapshot!(parse(&["deploy", "foo bar", "x;rm -rf /"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -1092,10 +1196,23 @@ cmd = [
],
}
"#);
- // Post-alias `-y` (single-dash) is no longer a flag — it falls into
- // the positional branch and gets forwarded to `{{ args }}` literally.
- // `wt deploy -y` skips approval only when `-y` is in the global
- // position (`wt -y deploy`), parsed by clap before this function runs.
+ // Post-alias `--yes` / `-y` are NOT recognized as approval-skip
+ // flags — the global `wt -y <alias>` form is the only path.
+ // `--yes` follows the `--KEY`-no-value rule and forwards as
+ // positional (since `yes` won't be a referenced template var).
+ // `-y` is a bare positional. Clap's `global = true` doesn't
+ // propagate across `external_subcommand`, so post-alias forms
+ // never reach the global parser anyway.
+ assert_debug_snapshot!(parse(&["deploy", "--yes"]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: false,
+ vars: [],
+ positional_args: [
+ "--yes",
+ ],
+ }
+ "#);
assert_debug_snapshot!(parse(&["deploy", "-y"]).unwrap(), @r#"
AliasOptions {
name: "deploy",
@@ -1112,16 +1229,26 @@ cmd = [
fn test_parse_errors() {
use insta::assert_snapshot;
assert_snapshot!(parse(&[]).unwrap_err(), @"Missing alias name");
- assert_snapshot!(parse(&["deploy", "--var"]).unwrap_err(), @"--var requires a KEY=VALUE argument");
- assert_snapshot!(parse(&["deploy", "--var", "noequals"]).unwrap_err(), @"invalid KEY=VALUE: no `=` found in `noequals`");
- assert_snapshot!(parse(&["deploy", "--verbose"]).unwrap_err(), @"Unknown flag '--verbose' for alias 'deploy' (use --verbose=VALUE to pass a variable)");
- assert_snapshot!(parse(&["deploy", "--var", "=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");
+ // `--=value` has an empty key — caught even when bind would forward.
assert_snapshot!(parse(&["deploy", "--=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");
- // Post-alias `--yes` is no longer recognized — `-y`/`--yes` must appear
- // before the alias name so clap captures it as the global. The long
- // form errors as an unknown flag; `-y` (single-dash) falls through to
- // the positional-args branch and gets forwarded to `{{ args }}`.
- assert_snapshot!(parse(&["deploy", "--yes"]).unwrap_err(), @"Unknown flag '--yes' for alias 'deploy' (use --yes=VALUE to pass a variable)");
+ }
+
+ /// `referenced_vars_for_config` unions across pipeline steps so a var
+ /// referenced in any one command is a binding candidate for the whole
+ /// alias. Single-step templates that fail to parse contribute nothing.
+ #[test]
+ fn test_referenced_vars_for_config_unions_steps() {
+ let cfg = cfg_from_toml(
+ r#"
+cmd = [
+ "echo {{ env }}",
+ { build = "make {{ target }}", lint = "lint {{ args }}" },
+]
+"#,
+ );
+ let refs = worktrunk::config::referenced_vars_for_config(&cfg);
+ let names: Vec<&str> = refs.iter().map(String::as_str).collect();
+ assert_eq!(names, vec!["args", "env", "target"]);
}
/// Verify BUILTIN_STEP_COMMANDS stays in sync with the actual StepCommand variants.
diff --git a/src/commands/mod.rs b/src/commands/mod.rs
index b540db973..80ae8484a 100644
--- a/src/commands/mod.rs
+++ b/src/commands/mod.rs
@@ -28,7 +28,7 @@ pub(crate) mod step_commands;
pub(crate) mod worktree;
pub(crate) use alias::{
- AliasOptions, HelpContext, alias_names_for_suggestions, augment_help, step_alias, try_alias,
+ HelpContext, alias_names_for_suggestions, augment_help, step_alias, try_alias,
};
pub(crate) use config::{
add_approvals, clear_approvals, handle_claude_install, handle_claude_install_statusline,
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index f994aa410..93c0d1f1d 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -142,7 +142,7 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {
vars
}
-use std::collections::HashMap;
+use std::collections::{BTreeSet, HashMap};
use std::hash::{Hash, Hasher};
/// Positional CLI args forwarded from `wt <alias> a b c` into the alias's
@@ -480,6 +480,24 @@ pub fn template_references_var(template: &str, var: &str) -> bool {
tmpl.undeclared_variables(false).contains(var)
}
+/// Union of top-level variables referenced by every command in a `CommandConfig`.
+///
+/// Drives alias-arg routing in `AliasOptions::parse`: a `--KEY=VALUE` token
+/// binds to `{{ KEY }}` only when KEY appears in this set; otherwise it
+/// forwards as a positional. Templates that fail to parse contribute nothing
+/// (the deferred expansion path will surface the syntax error at execution
+/// time).
+pub fn referenced_vars_for_config(cfg: &super::CommandConfig) -> BTreeSet<String> {
+ let env = minijinja::Environment::new();
+ let mut out = BTreeSet::new();
+ for cmd in cfg.commands() {
+ if let Ok(tmpl) = env.template_from_str(&cmd.template) {
+ out.extend(tmpl.undeclared_variables(false));
+ }
+ }
+ out
+}
+
/// Parse-only syntax check for a template.
///
/// Used on lazy-expansion paths (hooks + aliases) where rendering would fail
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 6b9cfd6a3..827cdffa6 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -122,8 +122,9 @@ pub use deprecation::{
};
pub use expansion::{
ALIAS_ARGS_KEY, BASE_VARS, DEPRECATED_TEMPLATE_VARS, TemplateExpandError, ValidationScope,
- expand_template, redact_credentials, sanitize_branch_name, sanitize_db, short_hash,
- template_references_var, validate_template, validate_template_syntax, vars_available_in,
+ expand_template, redact_credentials, referenced_vars_for_config, sanitize_branch_name,
+ sanitize_db, short_hash, template_references_var, validate_template, validate_template_syntax,
+ vars_available_in,
};
pub use hooks::HooksConfig;
pub use project::{ProjectCiConfig, ProjectConfig, ProjectListConfig, valid_project_config_keys};
diff --git a/src/main.rs b/src/main.rs
index 47be93df5..6e2f8d15e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -328,9 +328,7 @@ fn handle_step_command(action: StepCommand, yes: bool) -> anyhow::Result<()> {
commit,
clobber,
} => step_relocate(branches, dry_run, commit, clobber),
- StepCommand::External(args) => {
- commands::AliasOptions::parse(args).and_then(|opts| commands::step_alias(opts, yes))
- }
+ StepCommand::External(args) => commands::step_alias(args, yes),
}
}
diff --git a/tests/integration_tests/approval_ui.rs b/tests/integration_tests/approval_ui.rs
index 1ff5cf293..2be63cb75 100644
--- a/tests/integration_tests/approval_ui.rs
+++ b/tests/integration_tests/approval_ui.rs
@@ -662,14 +662,15 @@ deploy = "echo 'ran' > marker.txt"
assert_eq!(content.trim(), "ran");
}
-/// The post-alias `--yes` form (`wt deploy --yes`) is no longer supported —
+/// The post-alias `--yes` form (`wt deploy --yes`) does not skip approval —
/// clap's `global = true` does not propagate flags across an
-/// `external_subcommand` boundary, so the post-alias position never reached
-/// the global parser. `AliasOptions::parse` previously consumed it as a
-/// special case; that double-path was removed in favor of the canonical
-/// pre-alias form (`wt -y deploy` / `wt --yes deploy`).
+/// `external_subcommand` boundary, so the post-alias position never reaches
+/// the global `-y` parser. Under the smart-routing grammar `--yes` simply
+/// forwards as a positional into `{{ args }}` (since `yes` is not a
+/// referenced template var), and the alias still hits the approval path.
+/// Use `wt -y deploy` / `wt --yes deploy` to skip approval.
#[rstest]
-fn test_post_alias_yes_no_longer_supported(repo: TestRepo) {
+fn test_post_alias_yes_does_not_skip_approval(repo: TestRepo) {
repo.write_project_config(
r#"[aliases]
deploy = "echo 'ran' > marker.txt"
@@ -686,18 +687,18 @@ deploy = "echo 'ran' > marker.txt"
assert!(
!output.status.success(),
- "wt deploy --yes should error now that the post-alias form is removed"
+ "wt deploy --yes should fail at approval now that post-alias --yes is just a forwarded arg"
);
let stderr = String::from_utf8_lossy(&output.stderr);
assert!(
- stderr.contains("Unknown flag '--yes'"),
- "expected unknown-flag error, got: {stderr}"
+ stderr.contains("approval") || stderr.contains("Cannot prompt"),
+ "expected approval-failure error, got: {stderr}"
);
let marker = repo.root_path().join("marker.txt");
assert!(
!marker.exists(),
- "alias must not run when --yes is rejected"
+ "alias must not run when approval is denied"
);
}
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 9d289db19..a57d88244 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -121,9 +121,9 @@ fn test_step_alias_unknown_no_aliases(mut repo: TestRepo) {
));
}
-/// --var flag adds extra template variables (-y bypasses approval)
+/// `--KEY=VALUE` binds to `{{ KEY }}` when the template references it.
#[rstest]
-fn test_step_alias_with_var(mut repo: TestRepo) {
+fn test_step_alias_binds_referenced_var(mut repo: TestRepo) {
repo.write_project_config(
r#"
[aliases]
@@ -139,15 +139,16 @@ greet = "echo Hello {{ name }} from {{ branch }}"
assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
&repo,
"step",
- &["greet", "--dry-run", "--var", "name=World"],
+ &["greet", "--dry-run", "--name=World"],
Some(&feature_path),
&["-y"],
));
}
-/// --key=value shorthand for --var key=value
+/// `--KEY VALUE` (space-separated) binds the same way `--KEY=VALUE` does
+/// when KEY is referenced and VALUE doesn't look like a flag.
#[rstest]
-fn test_step_alias_with_shorthand_var(mut repo: TestRepo) {
+fn test_step_alias_binds_space_separated_var(mut repo: TestRepo) {
repo.write_project_config(
r#"
[aliases]
@@ -163,12 +164,117 @@ greet = "echo Hello {{ name }} from {{ branch }}"
assert_cmd_snapshot!(make_snapshot_cmd_with_global_flags(
&repo,
"step",
- &["greet", "--dry-run", "--name=World"],
+ &["greet", "--dry-run", "--name", "World"],
+ Some(&feature_path),
+ &["-y"],
+ ));
+}
+
+/// `--KEY=VALUE` for a key the template doesn't reference forwards to
+/// `{{ args }}` instead of binding silently.
+#[rstest]
+fn test_step_alias_unreferenced_key_forwards_to_args(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+run = "echo got {{ args }}"
+"#,
+ );
+ 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_with_global_flags(
+ &repo,
+ "run",
+ &["--env=staging", "foo"],
+ Some(&feature_path),
+ &["-y"],
+ ));
+}
+
+/// `--` is a literal-forward escape: every later token goes to `{{ args }}`,
+/// so flag-shaped values that would normally bind are passed through verbatim.
+#[rstest]
+fn test_step_alias_double_dash_escape(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+run = "echo got {{ args }}"
+"#,
+ );
+ 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_with_global_flags(
+ &repo,
+ "run",
+ &["--", "--env=staging", "literal"],
+ Some(&feature_path),
+ &["-y"],
+ ));
+}
+
+/// `--KEY=VALUE` overrides built-in template variables. The user-supplied
+/// value wins because `extra_refs` is applied after built-ins are seeded.
+#[rstest]
+fn test_step_alias_user_var_overshadows_builtin(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+show = "echo branch={{ 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_with_global_flags(
+ &repo,
+ "show",
+ &["--branch=override"],
Some(&feature_path),
&["-y"],
));
}
+/// Multi-step pipeline: each step's `{{ KEY }}` references contribute to
+/// the binding-eligible set, so a single invocation can bind both `env`
+/// (referenced in step 1) and `region` (referenced in step 2).
+#[rstest]
+fn test_step_alias_multi_step_binds_across_pipeline(mut repo: TestRepo) {
+ repo.write_test_config(
+ r#"
+[aliases]
+deploy = [
+ "echo step1 env={{ env }}",
+ { publish = "echo step2 region={{ region }}" },
+]
+"#,
+ );
+ repo.commit("initial");
+ let feature_path = repo.add_worktree("feature");
+
+ let settings = setup_snapshot_settings(&repo);
+ let _guard = settings.bind_to_scope();
+
+ let mut cmd = make_snapshot_cmd(
+ &repo,
+ "step",
+ &["deploy", "--env=prod", "--region=us-east"],
+ Some(&feature_path),
+ );
+ cmd.env("WORKTRUNK_TEST_SERIAL_CONCURRENT", "1");
+ assert_cmd_snapshot!(cmd);
+}
+
/// Alias command failure propagates exit code (-y bypasses approval)
#[rstest]
fn test_step_alias_exit_code(mut repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_with_shorthand_var.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_binds_referenced_var.snap
similarity index 100%
rename from tests/snapshots/integration__integration_tests__step_alias__step_alias_with_shorthand_var.snap
rename to tests/snapshots/integration__integration_tests__step_alias__step_alias_binds_referenced_var.snap
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_with_var.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_binds_space_separated_var.snap
similarity index 97%
rename from tests/snapshots/integration__integration_tests__step_alias__step_alias_with_var.snap
rename to tests/snapshots/integration__integration_tests__step_alias__step_alias_binds_space_separated_var.snap
index b5a76e3b0..b9a37ddab 100644
--- a/tests/snapshots/integration__integration_tests__step_alias__step_alias_with_var.snap
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_binds_space_separated_var.snap
@@ -6,8 +6,8 @@ info:
- step
- greet
- "--dry-run"
- - "--var"
- - name=World
+ - "--name"
+ - World
- "--yes"
env:
APPDATA: "[TEST_CONFIG_HOME]"
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_double_dash_escape.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_double_dash_escape.snap
new file mode 100644
index 000000000..772804f95
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_double_dash_escape.snap
@@ -0,0 +1,51 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - run
+ - "--yes"
+ - "--"
+ - "--env=staging"
+ - literal
+ 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 -----
+◎ Running alias run
+got --env=staging literal
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_multi_step_binds_across_pipeline.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_multi_step_binds_across_pipeline.snap
new file mode 100644
index 000000000..1d1f7602a
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_multi_step_binds_across_pipeline.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - step
+ - deploy
+ - "--env=prod"
+ - "--region=us-east"
+ 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_SERIAL_CONCURRENT: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+◎ Running alias deploy: publish
+step1 env=prod
+step2 region=us-east
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_unreferenced_key_forwards_to_args.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_unreferenced_key_forwards_to_args.snap
new file mode 100644
index 000000000..6c8a0e56e
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_unreferenced_key_forwards_to_args.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - run
+ - "--env=staging"
+ - foo
+ - "--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 -----
+◎ Running alias run
+got --env=staging foo
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_user_var_overshadows_builtin.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_user_var_overshadows_builtin.snap
new file mode 100644
index 000000000..a121b6a1d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_user_var_overshadows_builtin.snap
@@ -0,0 +1,49 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - show
+ - "--branch=override"
+ - "--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 -----
+◎ Running alias show
+branch=override