Skip to content

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

feat(alias): forward positional args to templates via {{ args }} (#2280)

Maximilian Roos4ec7023ee5da
diff --git a/docs/content/extending.md b/docs/content/extending.md
index 1a2aefd1d..2b8c72e9a 100644
--- a/docs/content/extending.md
+++ b/docs/content/extending.md
@@ -122,6 +122,19 @@ open = "open http://localhost:{{ branch | hash_port }}"
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.
+### Forwarding positional arguments
+
+Non-flag tokens after the alias name are forwarded to the template as `{{ args }}`. Bare `{{ args }}` renders as a space-joined, shell-escaped string ready to append to a command line — so `wt s some-branch` with `s = "wt switch {{ args }}"` expands to `wt switch some-branch`.
+
+```toml
+[aliases]
+s = "wt switch {{ args }}"
+```
+
+{{ terminal(cmd="wt s some-branch|||wt s feature/api # multiple tokens pass through in order|||wt s 'has a space' # spaces and metacharacters are escaped safely") }}
+
+Access elements with `{{ args[0] }}`, iterate with `{% for a in args %}…{% endfor %}`, or count with `{{ args | length }}`. Each element is individually shell-escaped, so `wt run 'a b' 'c;d'` splices in as `'a b' 'c;d'` without shell injection.
+
An `up` alias that fetches all remotes and rebases each worktree onto its upstream:
```toml
diff --git a/skills/worktrunk/reference/extending.md b/skills/worktrunk/reference/extending.md
index 05319760c..44079be5f 100644
--- a/skills/worktrunk/reference/extending.md
+++ b/skills/worktrunk/reference/extending.md
@@ -119,6 +119,23 @@ wt deploy --env=staging
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.
+### Forwarding positional arguments
+
+Non-flag tokens after the alias name are forwarded to the template as `{{ args }}`. Bare `{{ args }}` renders as a space-joined, shell-escaped string ready to append to a command line — so `wt s some-branch` with `s = "wt switch {{ args }}"` expands to `wt switch some-branch`.
+
+```toml
+[aliases]
+s = "wt switch {{ args }}"
+```
+
+```bash
+wt s some-branch
+wt s feature/api # multiple tokens pass through in order
+wt s 'has a space' # spaces and metacharacters are escaped safely
+```
+
+Access elements with `{{ args[0] }}`, iterate with `{% for a in args %}…{% endfor %}`, or count with `{{ args | length }}`. Each element is individually shell-escaped, so `wt run 'a b' 'c;d'` splices in as `'a b' 'c;d'` without shell injection.
+
An `up` alias that fetches all remotes and rebases each worktree onto its upstream:
```toml
diff --git a/src/commands/alias.rs b/src/commands/alias.rs
index 514b1dee0..6b317c0f5 100644
--- a/src/commands/alias.rs
+++ b/src/commands/alias.rs
@@ -36,8 +36,8 @@ use anyhow::{Context, bail};
use clap::error::{ContextKind, ContextValue, ErrorKind};
use color_print::cformat;
use worktrunk::config::{
- CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases, template_references_var,
- validate_template_syntax,
+ ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases,
+ template_references_var, validate_template_syntax,
};
use worktrunk::git::Repository;
use worktrunk::styling::{eprintln, format_bash_with_gutter, info_message, progress_message};
@@ -83,13 +83,19 @@ pub struct AliasOptions {
pub dry_run: bool,
pub yes: bool,
pub vars: Vec<(String, String)>,
+ /// Non-flag positional tokens passed after the alias name. Forwarded into
+ /// the template context as `{{ args }}` (a `ShellArgs` sequence). Appear
+ /// in CLI order, interleaving freely with flags: `wt s foo --dry-run bar`
+ /// collects `["foo", "bar"]`.
+ pub positional_args: Vec<String>,
}
impl AliasOptions {
/// Parse alias options from `wt step <alias>` args.
///
- /// First element is the alias name, remaining are flags:
- /// `--dry-run`, `--yes`/`-y`, `--var KEY=VALUE`, or `--KEY=VALUE`.
+ /// First element is the alias name, remaining tokens are either flags:
+ /// `--dry-run`, `--yes`/`-y`, `--var KEY=VALUE`, or `--KEY=VALUE`; or
+ /// positional args that get forwarded to the template as `{{ args }}`.
///
/// Unknown `--key=value` flags are treated as template variable assignments,
/// so `--env=staging` is equivalent to `--var env=staging`. The `=` is
@@ -107,6 +113,7 @@ impl AliasOptions {
let mut dry_run = false;
let mut yes = false;
let mut vars = Vec::new();
+ let mut positional_args = Vec::new();
let mut i = 1;
while i < args.len() {
match args[i].as_str() {
@@ -139,7 +146,7 @@ impl AliasOptions {
}
}
other => {
- bail!("Unexpected argument '{other}' for alias '{name}'");
+ positional_args.push(other.to_string());
}
}
i += 1;
@@ -150,6 +157,7 @@ impl AliasOptions {
dry_run,
yes,
vars,
+ positional_args,
})
}
}
@@ -369,7 +377,15 @@ fn run_alias(
.iter()
.map(|(k, v)| (k.as_str(), v.as_str()))
.collect();
- let context_map = build_hook_context(&ctx, &extra_refs)?;
+ let mut context_map = build_hook_context(&ctx, &extra_refs)?;
+ // Forward positional CLI args to templates as `{{ args }}`. Encoded as a
+ // JSON list so it flows through the stable `HashMap<String, String>`
+ // context — `expand_template` rehydrates it into a `ShellArgs` sequence.
+ context_map.insert(
+ ALIAS_ARGS_KEY.to_string(),
+ serde_json::to_string(&opts.positional_args)
+ .expect("Vec<String> serialization should never fail"),
+ );
// Build JSON context for stdin
let context_json = serde_json::to_string(&context_map)
@@ -785,6 +801,7 @@ cmd = [
dry_run: false,
yes: false,
vars: [],
+ positional_args: [],
}
"#);
assert_debug_snapshot!(parse(&["deploy", "--dry-run"]).unwrap(), @r#"
@@ -793,6 +810,7 @@ cmd = [
dry_run: true,
yes: false,
vars: [],
+ positional_args: [],
}
"#);
assert_debug_snapshot!(parse(&["deploy", "--yes"]).unwrap(), @r#"
@@ -801,6 +819,7 @@ cmd = [
dry_run: false,
yes: true,
vars: [],
+ positional_args: [],
}
"#);
assert_debug_snapshot!(parse(&["deploy", "-y"]).unwrap(), @r#"
@@ -809,6 +828,7 @@ cmd = [
dry_run: false,
yes: true,
vars: [],
+ positional_args: [],
}
"#);
assert_debug_snapshot!(parse(&["deploy", "--var", "key=value"]).unwrap(), @r#"
@@ -822,6 +842,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// --var=key=value (equals form)
@@ -836,6 +857,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// Value containing equals sign
@@ -850,6 +872,7 @@ cmd = [
"http://host?a=1",
),
],
+ positional_args: [],
}
"#);
// Multiple vars + flags
@@ -868,6 +891,7 @@ cmd = [
"2",
),
],
+ positional_args: [],
}
"#);
// Empty value accepted
@@ -882,6 +906,7 @@ cmd = [
"",
),
],
+ positional_args: [],
}
"#);
// --key=value shorthand
@@ -896,6 +921,7 @@ cmd = [
"staging",
),
],
+ positional_args: [],
}
"#);
// --key=value with equals in value
@@ -910,6 +936,7 @@ cmd = [
"http://host?a=1",
),
],
+ positional_args: [],
}
"#);
// --key=value mixed with --var and flags
@@ -928,6 +955,7 @@ cmd = [
"us-east",
),
],
+ positional_args: [],
}
"#);
// --key= (empty value)
@@ -942,6 +970,7 @@ cmd = [
"",
),
],
+ positional_args: [],
}
"#);
// Hyphens in shorthand key are canonicalized to underscores
@@ -956,6 +985,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// Hyphens in --var KEY=VALUE are canonicalized too
@@ -970,6 +1000,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// Hyphens in --var=KEY=VALUE form
@@ -984,6 +1015,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// Already-underscored keys pass through unchanged
@@ -998,6 +1030,7 @@ cmd = [
"value",
),
],
+ positional_args: [],
}
"#);
// Multiple hyphens in a single key
@@ -1012,6 +1045,7 @@ cmd = [
"x",
),
],
+ positional_args: [],
}
"#);
// Hyphens in value are preserved (only key is canonicalized)
@@ -1026,6 +1060,60 @@ cmd = [
"us-east-1",
),
],
+ positional_args: [],
+ }
+ "#);
+ // Single positional is forwarded as `{{ args }}`
+ assert_debug_snapshot!(parse(&["s", "some-branch"]).unwrap(), @r#"
+ AliasOptions {
+ name: "s",
+ dry_run: false,
+ yes: false,
+ vars: [],
+ positional_args: [
+ "some-branch",
+ ],
+ }
+ "#);
+ // Multiple positionals preserve CLI order
+ assert_debug_snapshot!(parse(&["deploy", "one", "two", "three"]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: false,
+ yes: false,
+ vars: [],
+ positional_args: [
+ "one",
+ "two",
+ "three",
+ ],
+ }
+ "#);
+ // Positionals can interleave with flags; flags are captured, positionals keep order
+ assert_debug_snapshot!(parse(&["deploy", "foo", "--dry-run", "bar"]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: true,
+ yes: false,
+ vars: [],
+ positional_args: [
+ "foo",
+ "bar",
+ ],
+ }
+ "#);
+ // Positionals containing spaces or shell metacharacters pass through verbatim —
+ // escaping happens only at template render time.
+ assert_debug_snapshot!(parse(&["deploy", "foo bar", "x;rm -rf /"]).unwrap(), @r#"
+ AliasOptions {
+ name: "deploy",
+ dry_run: false,
+ yes: false,
+ vars: [],
+ positional_args: [
+ "foo bar",
+ "x;rm -rf /",
+ ],
}
"#);
}
@@ -1037,7 +1125,6 @@ cmd = [
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", "arg1"]).unwrap_err(), @"Unexpected argument 'arg1' for alias 'deploy'");
assert_snapshot!(parse(&["deploy", "--var", "=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");
assert_snapshot!(parse(&["deploy", "--=value"]).unwrap_err(), @"invalid KEY=VALUE: key cannot be empty");
}
diff --git a/src/config/expansion.rs b/src/config/expansion.rs
index 0b22b794d..2892f4c97 100644
--- a/src/config/expansion.rs
+++ b/src/config/expansion.rs
@@ -9,8 +9,11 @@
//! See `wt hook --help` for available filters and functions.
use std::borrow::Cow;
+use std::fmt::{self, Write};
+use std::sync::Arc;
use color_print::cformat;
+use minijinja::value::{Enumerator, Object, ObjectRepr};
use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};
use regex::Regex;
use shell_escape::escape;
@@ -47,10 +50,20 @@ pub const TEMPLATE_VARS: &[&str] = &[
"base", // Added by creation/switch hooks via extra_vars
"base_worktree_path", // Added by creation/switch hooks via extra_vars
"cwd", // Execution directory (always exists on disk)
- // Note: `vars` is NOT listed here — it's a structured object injected by expand_template,
- // not a simple string that --var can override.
+ // Positional args forwarded to aliases (injected as ShellArgs object by expand_template).
+ "args",
+ // Note: `vars` is NOT listed here — it's a structured object injected by expand_template,
+ // not a simple string that --var can override.
];
+/// Reserved context key carrying a JSON-encoded `Vec<String>` of positional
+/// CLI args forwarded to an alias. The key flows through
+/// `HashMap<String, String>` — stable for stdin JSON — and
+/// [`expand_template`] rehydrates it as a `ShellArgs` object so bare
+/// `{{ args }}` renders as a space-joined, shell-escaped string while
+/// indexing, iteration, and `length` behave like a sequence.
+pub const ALIAS_ARGS_KEY: &str = "args";
+
/// Deprecated template variable aliases (still valid for backward compatibility).
///
/// These map to current variables:
@@ -68,6 +81,54 @@ pub const DEPRECATED_TEMPLATE_VARS: &[&str] = &[
use std::collections::HashMap;
use std::hash::{Hash, Hasher};
+/// Positional CLI args forwarded from `wt <alias> a b c` into the alias's
+/// template context. Bare `{{ args }}` renders as a space-joined,
+/// shell-escaped string ready to append to a command line; `{{ args[0] }}`
+/// and `{% for a in args %}…{% endfor %}` and `{{ args | length }}` all
+/// behave as expected because the object reports as an
+/// [`ObjectRepr::Seq`].
+///
+/// Shell escaping happens at render time via `shell_escape::unix::escape`
+/// rather than through the template environment's formatter — the formatter
+/// would otherwise quote the already-escaped joined string as a whole. The
+/// formatter installed by `expand_template` detects `ShellArgs` and writes
+/// it through unmodified.
+#[derive(Debug)]
+struct ShellArgs(Vec<String>);
+
+impl ShellArgs {
+ fn new(args: Vec<String>) -> Self {
+ Self(args)
+ }
+}
+
+impl Object for ShellArgs {
+ fn repr(self: &Arc<Self>) -> ObjectRepr {
+ ObjectRepr::Seq
+ }
+
+ fn get_value(self: &Arc<Self>, key: &Value) -> Option<Value> {
+ let idx = key.as_usize()?;
+ self.0.get(idx).cloned().map(Value::from)
+ }
+
+ fn enumerate(self: &Arc<Self>) -> Enumerator {
+ Enumerator::Seq(self.0.len())
+ }
+
+ fn render(self: &Arc<Self>, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ let mut first = true;
+ for arg in &self.0 {
+ if !first {
+ f.write_char(' ')?;
+ }
+ first = false;
+ f.write_str(&escape(Cow::Borrowed(arg)))?;
+ }
+ Ok(())
+ }
+}
+
/// Hash a string to a port in range 10000-19999.
fn string_to_port(s: &str) -> u16 {
let mut h = std::collections::hash_map::DefaultHasher::new();
@@ -387,6 +448,7 @@ pub fn validate_template(
) -> Result<(), TemplateExpandError> {
let all_vars = TEMPLATE_VARS.iter().chain(DEPRECATED_TEMPLATE_VARS.iter());
let mut context: HashMap<String, minijinja::Value> = all_vars
+ .filter(|&&k| k != ALIAS_ARGS_KEY)
.map(|&k| (k.to_string(), minijinja::Value::from("PLACEHOLDER")))
.collect();
// Inject vars as empty map so {{ vars.key | default(...) }} doesn't error
@@ -394,6 +456,12 @@ pub fn validate_template(
"vars".to_string(),
minijinja::Value::from_serialize(std::collections::BTreeMap::<String, String>::new()),
);
+ // Inject `args` as an empty sequence so `{{ args }}`, `{{ args[0] | default(...) }}`,
+ // `{{ args | length }}`, and `{% for a in args %}…{% endfor %}` all validate.
+ context.insert(
+ ALIAS_ARGS_KEY.to_string(),
+ Value::from_object(ShellArgs::new(Vec::new())),
+ );
let env = setup_template_env(repo);
@@ -442,13 +510,20 @@ pub fn expand_template(
repo: &Repository,
name: &str,
) -> Result<String, TemplateExpandError> {
- // Build context map with raw values (shell escaping is applied at output time via formatter)
+ // Build context map with raw values (shell escaping is applied at output time via formatter).
+ // The `args` key is reserved: run_alias encodes positional CLI args as a JSON list string,
+ // and we rehydrate it here as a `ShellArgs` object so `{{ args }}` behaves sequence-like.
let mut context = HashMap::new();
for (key, value) in vars {
- context.insert(
- key.to_string(),
- minijinja::Value::from((*value).to_string()),
- );
+ if *key == ALIAS_ARGS_KEY {
+ let parsed: Vec<String> = serde_json::from_str(value).unwrap_or_default();
+ context.insert(key.to_string(), Value::from_object(ShellArgs::new(parsed)));
+ } else {
+ context.insert(
+ key.to_string(),
+ minijinja::Value::from((*value).to_string()),
+ );
+ }
}
// Inject vars data as a nested object: {{ vars.env }}, {{ vars.config.port }}
@@ -490,6 +565,15 @@ pub fn expand_template(
if value.is_none() {
return Ok(());
}
+ // ShellArgs renders each element pre-escaped and space-joined
+ // (see [`ShellArgs::render`]); passing through its Display
+ // output avoids re-escaping the whole joined string as one
+ // opaque token. Iteration and indexing yield plain string
+ // values that still flow through the generic escape branch.
+ if value.downcast_object_ref::<ShellArgs>().is_some() {
+ write!(out, "{value}")?;
+ return Ok(());
+ }
let s = value.to_string();
let escaped = escape(Cow::Borrowed(&s));
write!(out, "{escaped}")?;
@@ -1350,6 +1434,98 @@ mod tests {
);
}
+ #[test]
+ fn test_expand_template_args_sequence() {
+ let test = test_repo();
+ let args_json = serde_json::to_string(&["foo", "bar baz", "qux"]).unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("args", args_json.as_str());
+
+ // Bare {{ args }} with shell escaping: space-joined, per-element escaped,
+ // NOT wrapped in outer quotes as a single token.
+ assert_eq!(
+ expand_template("wt switch {{ args }}", &vars, true, &test.repo, "test").unwrap(),
+ "wt switch foo 'bar baz' qux"
+ );
+
+ // Indexing returns a plain string — flows through the shell-escape formatter.
+ assert_eq!(
+ expand_template("{{ args[0] }}", &vars, true, &test.repo, "test").unwrap(),
+ "foo"
+ );
+ assert_eq!(
+ expand_template("{{ args[1] }}", &vars, true, &test.repo, "test").unwrap(),
+ "'bar baz'"
+ );
+
+ // Length works like any sequence.
+ assert_eq!(
+ expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
+ "3"
+ );
+
+ // Iteration yields per-element string values; each escaped by the formatter.
+ assert_eq!(
+ expand_template(
+ "{% for a in args %}[{{ a }}]{% endfor %}",
+ &vars,
+ true,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ "[foo]['bar baz'][qux]"
+ );
+ }
+
+ #[test]
+ fn test_expand_template_args_empty() {
+ let test = test_repo();
+ let args_json = serde_json::to_string(&Vec::<String>::new()).unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("args", args_json.as_str());
+
+ // Empty args renders empty. No stray whitespace, no error.
+ assert_eq!(
+ expand_template("wt switch{{ args }}", &vars, true, &test.repo, "test").unwrap(),
+ "wt switch"
+ );
+
+ // Length still defined for empty.
+ assert_eq!(
+ expand_template("{{ args | length }}", &vars, false, &test.repo, "test").unwrap(),
+ "0"
+ );
+
+ // Iteration yields nothing.
+ assert_eq!(
+ expand_template(
+ "{% for a in args %}X{% endfor %}",
+ &vars,
+ true,
+ &test.repo,
+ "test"
+ )
+ .unwrap(),
+ ""
+ );
+ }
+
+ #[test]
+ fn test_expand_template_args_shell_metachar_safety() {
+ // The point of ShellArgs is that bare {{ args }} is safe to splice into
+ // a command line even when args contain shell metacharacters — each
+ // element is individually single-quoted by `shell_escape::unix::escape`,
+ // and the outer formatter doesn't re-quote the joined result.
+ let test = test_repo();
+ let args_json = serde_json::to_string(&["; rm -rf /", "$(whoami)", "a'b"]).unwrap();
+ let mut vars = HashMap::new();
+ vars.insert("args", args_json.as_str());
+
+ let rendered = expand_template("echo {{ args }}", &vars, true, &test.repo, "test").unwrap();
+ assert_eq!(rendered, r#"echo '; rm -rf /' '$(whoami)' 'a'\''b'"#);
+ }
+
#[test]
fn test_validate_template_valid() {
let test = test_repo();
@@ -1379,6 +1555,13 @@ mod tests {
// Deprecated vars still valid
assert!(validate_template("{{ main_worktree }}", &test.repo, "test").is_ok());
+
+ // `args` is injected as an empty sequence, so templates referencing it validate.
+ assert!(validate_template("wt switch {{ args }}", &test.repo, "test").is_ok());
+ assert!(validate_template("{{ args | length }}", &test.repo, "test").is_ok());
+ assert!(
+ validate_template("{% for a in args %}{{ a }}{% endfor %}", &test.repo, "test").is_ok()
+ );
}
#[test]
diff --git a/src/config/mod.rs b/src/config/mod.rs
index 47d1a7daa..cfdeb1ec4 100644
--- a/src/config/mod.rs
+++ b/src/config/mod.rs
@@ -121,7 +121,7 @@ pub use deprecation::{
key_belongs_in, warn_unknown_fields,
};
pub use expansion::{
- DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, TemplateExpandError, expand_template,
+ ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, TEMPLATE_VARS, TemplateExpandError, expand_template,
redact_credentials, sanitize_branch_name, sanitize_db, short_hash, template_references_var,
validate_template, validate_template_syntax,
};
diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rs
index 9f7cbceb2..c1204dd1f 100644
--- a/tests/integration_tests/step_alias.rs
+++ b/tests/integration_tests/step_alias.rs
@@ -1224,6 +1224,104 @@ xyzzy = "echo nothing happens"
);
}
+/// Positional args after the alias name forward to `{{ args }}` in the
+/// template — space-joined and shell-escaped so args with spaces, quotes,
+/// or metacharacters splice safely into a command line.
+#[rstest]
+fn test_step_alias_forwards_positional_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(
+ &repo,
+ "run",
+ &["one", "two three", "four", "--yes"],
+ Some(&feature_path),
+ ));
+}
+
+/// Templates can treat `{{ args }}` as a sequence: indexing, iteration,
+/// and `length` all work because `ShellArgs` reports as `ObjectRepr::Seq`.
+#[rstest]
+fn test_step_alias_args_sequence_access(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+show = '''echo first={{ args[0] }}; echo count={{ args | length }}; echo each={% for a in args %} {{ a }}{% endfor %}'''
+"#,
+ );
+ 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,
+ "show",
+ &["alpha", "beta gamma", "--yes"],
+ Some(&feature_path),
+ ));
+}
+
+/// With no positionals, `{{ args }}` renders empty — the rest of the line
+/// stays intact and no stray whitespace is introduced.
+#[rstest]
+fn test_step_alias_empty_args_renders_empty(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+run = "echo [{{ 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(
+ &repo,
+ "run",
+ &["--yes"],
+ Some(&feature_path),
+ ));
+}
+
+/// `wt s some-branch` with `s = "wt switch {{ args }}"` forwards the
+/// positional into the expanded command. Verified via `--dry-run` so the
+/// inner `wt switch` is not actually executed.
+#[rstest]
+fn test_top_level_alias_positional_expands_in_dry_run(mut repo: TestRepo) {
+ repo.write_project_config(
+ r#"
+[aliases]
+s = "wt switch {{ 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(
+ &repo,
+ "s",
+ &["target-branch", "--dry-run", "--yes"],
+ Some(&feature_path),
+ ));
+}
+
/// Declining approval prevents alias execution
#[rstest]
fn test_alias_approval_decline(mut repo: TestRepo) {
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_args_sequence_access.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_args_sequence_access.snap
new file mode 100644
index 000000000..bfbe6f9e7
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_args_sequence_access.snap
@@ -0,0 +1,52 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - show
+ - alpha
+ - beta gamma
+ - "--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
+first=alpha
+count=2
+each= alpha beta gamma
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_empty_args_renders_empty.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_empty_args_renders_empty.snap
new file mode 100644
index 000000000..1e8ba6a8d
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_empty_args_renders_empty.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - run
+ - "--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
+[]
diff --git a/tests/snapshots/integration__integration_tests__step_alias__step_alias_forwards_positional_args.snap b/tests/snapshots/integration__integration_tests__step_alias__step_alias_forwards_positional_args.snap
new file mode 100644
index 000000000..9644b932e
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__step_alias_forwards_positional_args.snap
@@ -0,0 +1,51 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - run
+ - one
+ - two three
+ - four
+ - "--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 one two three four
diff --git a/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_positional_expands_in_dry_run.snap b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_positional_expands_in_dry_run.snap
new file mode 100644
index 000000000..e64e7b506
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_alias__top_level_alias_positional_expands_in_dry_run.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/step_alias.rs
+info:
+ program: wt
+ args:
+ - s
+ - target-branch
+ - "--dry-run"
+ - "--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 -----
+○ Alias s would run:
+  wt switch target-branch