Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Name undefined template variables and suggest corrections (#4350)
Maximilian Roos689bab3d3e31
diff --git a/Cargo.toml b/Cargo.tomlindex 484488258..64abafe67 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -195,12 +195,12 @@ tracing-log = { version = "0.2.0", optional = true }# `EnvFilter::builder().with_default_directive(...).from_env_lossy()` (used in# `src/logging.rs`) stabilized on top of the per-layer filtering rework.tracing-subscriber = { version = "0.3.17", default-features = false, features = ["ansi", "env-filter", "fmt", "registry"], optional = true }-# Only enable needed features - saves ~200KB by excluding debug, macros, multi_template.-# `unstable_machinery` exposes the parser `src/config/deprecation.rs` migrates retired-# template variables through, rather than re-deriving MiniJinja's grammar by hand; it-# pulls in `internal_debug`, which costs ~116KB of that saving back (~67KB stripped).-minijinja = { version = "2.20", default-features = false, features = [+# Only enable needed features; macros and multi-template loading remain disabled.+# `unstable_machinery` supplies syntax analysis for migrations and diagnostics;+# `debug` supplies error source spans, including release builds.+minijinja = { version = "2.24", default-features = false, features = ["builtins",+ "debug","serde","std_collections","unstable_machinery",diff --git a/src/cli/hook.rs b/src/cli/hook.rsindex 2d0a7cf26..6e4a8ed65 100644--- a/src/cli/hook.rs+++ b/src/cli/hook.rs@@ -169,7 +169,7 @@ pub fn parse_hook_type(name: &str) -> anyhow::Result<HookType> {"post-remove" => Ok(HookType::PostRemove),other => {let candidates = HOOK_TYPE_NAMES.iter().map(|s| s.to_string());- let suggestions = crate::commands::did_you_mean(other, candidates);+ let suggestions = worktrunk::utils::did_you_mean(other, candidates);if let Some(suggestion) = suggestions.first() {bail!("unknown hook type: `{other}` (did you mean `{suggestion}`?)");}diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex e6ad7d72d..50f20a082 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -37,8 +37,8 @@ use crate::commands::build_invalid_subcommand_error;use crate::commands::command_executor::{CommandContext, build_hook_context, render_template_preview,};-use crate::commands::did_you_mean;use worktrunk::config::HookSource;+use worktrunk::utils::did_you_mean;/// Show the configured template(s) for an alias — or, with no name, every/// configured alias's template(s).diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 826ed28b3..0dce1e957 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -29,6 +29,8 @@ pub(crate) mod step;pub(crate) mod template_vars;pub(crate) mod worktree;+use worktrunk::utils::did_you_mean;+pub(crate) use alias::{AliasMap, HelpContext, alias_names_for_suggestions, augment_help, load_aliases, step_alias,try_alias,@@ -93,29 +95,6 @@ pub(crate) fn format_command_label(command_type: &str, name: Option<&str>) -> St}}-/// Return candidates similar to `query`, sorted by descending Jaro–Winkler-/// similarity, filtered by `score > 0.7`, and deduplicated while preserving-/// order. The 0.7 threshold matches clap's internal `did_you_mean` so-/// wt-synthesized "unrecognized subcommand" tips read identically to clap's-/// native output — keep them aligned if clap ever changes it.-pub(crate) fn did_you_mean(- query: &str,- candidates: impl IntoIterator<Item = String>,-) -> Vec<String> {- let mut scored: Vec<(f64, String)> = candidates- .into_iter()- .map(|candidate| (strsim::jaro_winkler(query, &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));- let mut seen = std::collections::HashSet::new();- scored- .into_iter()- .filter(|(_, n)| seen.insert(n.clone()))- .map(|(_, n)| n)- .collect()-}-/// Return visible subcommand names of `parent` plus `alias_names`, filtered to/// those similar to `name`. Hidden subcommands (e.g., deprecated aliases) and/// clap's implicit `help` are excluded, and `name` itself never appears: somediff --git a/src/config/deprecation.rs b/src/config/deprecation.rsindex 054b04c29..c98964d84 100644--- a/src/config/deprecation.rs+++ b/src/config/deprecation.rs@@ -27,15 +27,14 @@use std::borrow::Cow;use std::collections::HashSet;use std::io::Write;-use std::ops::Range;use std::path::{Path, PathBuf};use std::sync::{LazyLock, Mutex, OnceLock};use anyhow::Context;use color_print::cformat;-use minijinja::machinery::{ast, parse as parse_template};use shell_escape::unix::escape;+use super::template_analysis::TemplateVars;use crate::config::WorktrunkConfig;use crate::shell_exec::Cmd;use crate::styling::{@@ -191,9 +190,8 @@ pub fn normalize_template_vars(template: &str) -> Cow<'_, str> {/// order.////// `None` leaves the template exactly as written: no retired name is read, it-/// doesn't parse, or a statement binds either half of a pair — see-/// [`TemplateVars`] for why a bound name drops the pair rather than renaming-/// half a scope. An identifier that isn't a variable read — an attribute+/// doesn't parse, or a statement binds either half of a pair. An identifier+/// that isn't a variable read — an attribute/// (`{{ foo.repo_root }}`), a keyword argument, an assignment target — isn't a/// use, so it doesn't bring a pair in on its own.///@@ -205,6 +203,8 @@ fn migrate_retired_vars(template: &str) -> Option<(String, Vec<(&'static str, &'return None;}+ // Renames are template-wide, so exclude both sides of a pair when either+ // is locally bound. Renaming only some reads could capture a local value.let vars = TemplateVars::of(template)?;let replacements = RETIRED_VARS.iter()@@ -243,243 +243,6 @@ fn migrate_retired_vars(template: &str) -> Option<(String, Vec<(&'static str, &'Some((migrated, replacements))}-/// A template as MiniJinja's own parser reads it: every variable read, with-/// the byte range of the identifier behind it, and every name a statement-/// binds.-///-/// Both halves were once scanned by hand, which meant re-deriving MiniJinja's-/// delimiters, whitespace control, string quoting, `{% raw %}` handling and-/// assignment-target grammar. Each place the two readings disagreed was-/// visible in the file worktrunk writes (#4117): a `}}` inside a string ended-/// a tag early, so the reference after it never migrated, and an unrecognized-/// target list renamed a local's uses out from under its binding. Parsing-/// through [`minijinja::machinery`] removes the second reading instead of-/// correcting it — the reads are the `Expr::Var` nodes, which is by-/// construction the set the renderer resolves against the context, and the-/// bindings are the statements' own target expressions.-///-/// `machinery` carries no semver guarantee, so the coupling is to the AST's-/// shape alone: the matches below are exhaustive over `Stmt` and `Expr`, and-/// `Cargo.toml` takes MiniJinja with `default-features = false`, so the-/// `macros`, `multi_template` and `loop_controls` variants don't exist to-/// handle. A MiniJinja that adds or moves a node fails this build rather than-/// quietly mis-migrating a config, and the compile error names what to-/// handle.-struct TemplateVars<'a> {- /// The name and byte range of every `Expr::Var`, in visit order.- reads: Vec<(&'a str, Range<usize>)>,- /// Every name a `set`, `for`, or `with` binds, at any depth.- ///- /// The rewrite has no notion of scope — it replaces reads wherever they- /// sit — so a deprecated name bound anywhere is dropped from the- /// replacement set entirely rather than renamed per scope:- /// `{{ repo_root }}{% set repo_root = "local" %}{{ repo_root }}` must not- /// have its last use renamed away from the binding it reads. Detection- /// reads that same set, so such a template neither migrates nor warns.- /// Losing the warning is the price of not quietly rendering something- /// else.- ///- /// Since [`RETIRED_VARS`] became a [`DeprecationRule::Structural`] row- /// that price is paid at render time rather than deferred: the retired- /// name survives the load-path rewrite and reaches a renderer that has- /// nothing to resolve it to, failing a `SemiStrict` expansion loudly or- /// rendering empty in a squash template. Both beat renaming one scope's- /// worth of uses out from under the template that bound the name.- ///- /// The *canonical* name is checked against this set too. Binding it- /// captures the global use the rename produces: `{% for repo_path in items- /// %}` around a `{{ repo_root }}` reads the global today and the loop- /// variable once renamed. The same collision reaches every pair — `{% for- /// commit_details in … %}{{ commits }}` is the squash-template shape of it.- bound: HashSet<&'a str>,-}--impl<'a> TemplateVars<'a> {- /// `None` when MiniJinja can't parse `template` — the templates its- /// renderer rejects too, left untouched rather than guessed at.- fn of(template: &'a str) -> Option<Self> {- // The syntax and whitespace defaults, spelled `Default::default()`- // because `SyntaxConfig` is a unit struct without MiniJinja's- // `custom_syntax` feature. Neither has to match the environment that- // renders the template — `expand_template_with` sets- // `keep_trailing_newline(true)` for every `ShellEscapeMode` but- // `Literal`, and a `WhitespaceConfig` only ever shapes literal text- // (which byte the tokenizer stops at, where an `EmitRaw` node's- // boundaries fall), never an `Expr::Var` span. Everything outside- // those spans is copied from the original string, so the two readings- // cannot move an edit apart.- let ast =- parse_template(template, "<config>", Default::default(), Default::default()).ok()?;- let mut vars = TemplateVars {- reads: Vec::new(),- bound: HashSet::new(),- };- vars.stmt(&ast);- Some(vars)- }-- fn body(&mut self, body: &[ast::Stmt<'a>]) {- for stmt in body {- self.stmt(stmt);- }- }-- fn stmt(&mut self, stmt: &ast::Stmt<'a>) {- match stmt {- ast::Stmt::Template(node) => self.body(&node.children),- ast::Stmt::EmitExpr(node) => self.expr(&node.expr),- // Literal output — the text around the tags, and everything inside- // a `{% raw %}` block.- ast::Stmt::EmitRaw(_) => {}- ast::Stmt::ForLoop(node) => {- self.target(&node.target);- self.expr(&node.iter);- if let Some(filter) = &node.filter_expr {- self.expr(filter);- }- self.body(&node.body);- self.body(&node.else_body);- }- ast::Stmt::IfCond(node) => {- self.expr(&node.expr);- self.body(&node.true_body);- self.body(&node.false_body);- }- ast::Stmt::WithBlock(node) => {- for (target, value) in &node.assignments {- self.target(target);- self.expr(value);- }- self.body(&node.body);- }- ast::Stmt::Set(node) => {- self.target(&node.target);- self.expr(&node.expr);- }- ast::Stmt::SetBlock(node) => {- self.target(&node.target);- if let Some(filter) = &node.filter {- self.expr(filter);- }- self.body(&node.body);- }- ast::Stmt::AutoEscape(node) => {- self.expr(&node.enabled);- self.body(&node.body);- }- ast::Stmt::FilterBlock(node) => {- self.expr(&node.filter);- self.body(&node.body);- }- ast::Stmt::Do(node) => self.call(&node.call),- }- }-- fn expr(&mut self, expr: &ast::Expr<'a>) {- match expr {- ast::Expr::Var(node) => {- let span = node.span();- self.reads.push((- node.id,- span.start_offset as usize..span.end_offset as usize,- ));- }- ast::Expr::Const(_) => {}- ast::Expr::Slice(node) => {- self.expr(&node.expr);- for bound in [&node.start, &node.stop, &node.step].into_iter().flatten() {- self.expr(bound);- }- }- ast::Expr::UnaryOp(node) => self.expr(&node.expr),- ast::Expr::BinOp(node) => {- self.expr(&node.left);- self.expr(&node.right);- }- ast::Expr::Compare(node) => {- self.expr(&node.expr);- for op in &node.ops {- self.expr(&op.expr);- }- }- ast::Expr::IfExpr(node) => {- self.expr(&node.test_expr);- self.expr(&node.true_expr);- if let Some(false_expr) = &node.false_expr {- self.expr(false_expr);- }- }- // A filter or test names a function the environment supplies, not- // a variable, so only its input and arguments are reads.- ast::Expr::Filter(node) => {- if let Some(expr) = &node.expr {- self.expr(expr);- }- self.args(&node.args);- }- ast::Expr::Test(node) => {- self.expr(&node.expr);- self.args(&node.args);- }- // `{{ foo.repo_root }}` reads `foo`; the attribute belongs to- // whatever that resolves to, never to the deprecated global.- ast::Expr::GetAttr(node) => self.expr(&node.expr),- ast::Expr::GetItem(node) => {- self.expr(&node.expr);- self.expr(&node.subscript_expr);- }- ast::Expr::Call(node) => self.call(node),- ast::Expr::List(node) => {- for item in &node.items {- self.expr(item);- }- }- ast::Expr::Map(node) => {- for entry in node.keys.iter().chain(&node.values) {- self.expr(entry);- }- }- }- }-- fn call(&mut self, call: &ast::Call<'a>) {- self.expr(&call.expr);- self.args(&call.args);- }-- /// A keyword argument's name belongs to the call it is passed to, so only- /// the argument values are reads.- fn args(&mut self, args: &[ast::CallArg<'a>]) {- for arg in args {- match arg {- ast::CallArg::Pos(expr)- | ast::CallArg::Kwarg(_, expr)- | ast::CallArg::PosSplat(expr)- | ast::CallArg::KwargSplat(expr) => self.expr(expr),- }- }- }-- /// The names an assignment target binds.- fn target(&mut self, target: &ast::Expr<'a>) {- match target {- ast::Expr::Var(node) => {- self.bound.insert(node.id);- }- // A tuple target, nested arbitrarily: `{% for (a, (b, c)) in … %}`.- ast::Expr::List(node) => {- for item in &node.items {- self.target(item);- }- }- // A dotted target mutates an attribute of whatever the path- // resolves to, so `{% set repo_root.x = … %}` reads the global- // rather than binding it.- read => self.expr(read),- }- }-}-/// Replace every [`RETIRED_VARS`] template variable in every string value of/// the document, mutating the `toml_edit` tree in place; returns one/// [`DeprecationKind::TemplateVar`] per `(old, new)` pair replaced, indiff --git a/src/config/expansion.rs b/src/config/expansion.rsindex a88cc18b3..76a360f30 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -7,6 +7,8 @@//! - `Literal` — values substituted verbatim, for filesystem paths.//!//! All templates support Jinja2 syntax including filters, conditionals, and loops.+//! Undefined-variable diagnostics use MiniJinja's source spans and shared syntax+//! analysis; preflight checks use its undeclared-variable analysis.//!//! See `wt hook --help` for available filters and functions.@@ -16,12 +18,13 @@ use std::hash::{Hash, Hasher};use std::sync::Arc;use color_print::cformat;-use minijinja::value::{Enumerator, Object, ObjectRepr};-use minijinja::{Environment, ErrorKind, UndefinedBehavior, Value};+use minijinja::value::{Enumerator, Object, ObjectRepr, StringInput};+use minijinja::{Environment, ErrorKind, State, UndefinedBehavior, Value};use regex::Regex;use serde::{Deserialize, Serialize};use sha2::{Digest, Sha256};+use super::template_analysis::TemplateVars;use crate::git::{Diagnostic, HookType, Repository};use crate::path::to_posix_path;use crate::shell_exec::{ShellEscapeMode, shell_escape_for};@@ -29,6 +32,7 @@ use crate::styling::{eprintln, error_message, format_bash_with_gutter, format_with_gutter, hint_message,info_message, verbosity,};+use crate::utils::did_you_mean;/// Active-context vars: point at the branch the operation acts on.///@@ -698,14 +702,18 @@ fn invalid_filter_arg(message: impl Into<String>) -> minijinja::Error {minijinja::Error::new(ErrorKind::InvalidOperation, message.into())}-fn codename_filter(value: Value, words: Option<usize>) -> Result<String, minijinja::Error> {+fn codename_filter(+ state: &State,+ value: Value,+ words: Option<usize>,+) -> Result<String, minijinja::Error> {let words = words.unwrap_or(2);if words == 0 || words > CODENAME_MAX_WORDS {return Err(invalid_filter_arg(format!("codename word count must be between 1 and {CODENAME_MAX_WORDS}")));}- Ok(codename(value.as_str().unwrap_or_default(), words))+ Ok(codename(filter_string(state, &value)?, words))}/// Redact credentials from URLs for safe logging.@@ -750,10 +758,12 @@ pub fn redact_credentials(s: &str) -> String {pub struct TemplateExpandError {/// Plain-text error summary for callers that embed errors in styled messages.pub message: String,- /// The failing template line (if identifiable).+ /// The failing template line, when identifiable.pub source_line: Option<String>,/// Variable names available in this template context.pub available_vars: Vec<String>,+ /// Closest available variable, when a missing name is identifiable.+ pub suggestion: Option<String>,}impl std::fmt::Display for TemplateExpandError {@@ -768,6 +778,11 @@ impl Diagnostic for TemplateExpandError {if let Some(ref line) = self.source_line {parts.push(format_with_gutter(line, None));}+ if let Some(ref suggestion) = self.suggestion {+ parts.push(+ hint_message(cformat!("Did you mean <underline>{suggestion}</>?")).to_string(),+ );+ }if !self.available_vars.is_empty() {let underlined_vars: Vec<String> = self.available_vars@@ -788,20 +803,7 @@ impl Diagnostic for TemplateExpandError {impl std::error::Error for TemplateExpandError {}-/// Build a [`TemplateExpandError`] from a minijinja error, the original template-/// source, the template name (for error messages), and the available variable names.-///-/// Message format: `Failed to expand {name}: {kind}[: {detail}] [@ line {n}]`-///-/// ```text-/// Failed to expand {name}: {kind}[: {detail}] [@ line {n}]-/// │ │ │ │ │-/// │ │ │ │ └─ e.line() from minijinja-/// │ │ │ └─ e.detail() from minijinja (None for UndefinedError)-/// │ │ └─ e.kind() from minijinja ("undefined value", "syntax error")-/// │ └─ `name` param passed by caller-/// └─ hardcoded prefix-/// ```+/// Keep MiniJinja's error detail and failing source line in the CLI diagnostic.fn build_template_error(e: &minijinja::Error,template: &str,@@ -813,13 +815,11 @@ fn build_template_error(let source_line =line_num.and_then(|n| lines.get(n.saturating_sub(1)).copied().map(String::from));- // Build message: "Failed to expand {name}: {kind}[: {detail}] [@ line {n}]"- // e.g. "Failed to expand --execute command: undefined value @ line 1"+ let is_undefined = e.kind() == ErrorKind::UndefinedError;let detail = match e.detail() {Some(detail) => format!("{}: {detail}", e.kind()),None => e.kind().to_string(),};- let is_undefined = e.kind() == ErrorKind::UndefinedError;// minijinja always provides a line number for syntax and render errorslet message = match line_num {@@ -836,6 +836,7 @@ fn build_template_error(} else {Vec::new()},+ suggestion: None,}}@@ -850,25 +851,45 @@ fn build_undefined_vars_error(name: &str,undefined_vars: &[String],available_vars: Vec<String>,+ template: &str,+ line_num: Option<usize>,) -> TemplateExpandError {- let names = undefined_vars- .iter()- .map(|var| format!("`{var}`"))- .collect::<Vec<_>>()- .join(", ");+ let names = undefined_vars.join(", ");let noun = if undefined_vars.len() == 1 {- "value"+ "variable"} else {- "values"+ "variables"};-+ let suggestion = match undefined_vars {+ [var] => did_you_mean(var, available_vars.iter().cloned())+ .into_iter()+ .next(),+ _ => None,+ };+ let location = line_num+ .map(|line| format!(" @ line {line}"))+ .unwrap_or_default();TemplateExpandError {- message: format!("Failed to expand {name}: undefined {noun}: {names}"),- source_line: None,+ message: format!("Failed to expand {name}: undefined {noun} {names}{location}"),+ source_line: match line_num {+ Some(line) => template+ .lines()+ .nth(line.saturating_sub(1))+ .map(String::from),+ None => (!template.contains('\n')).then(|| template.to_string()),+ },available_vars,+ suggestion,}}+/// Apply the engine's undefined-input policy while preserving the filters'+/// existing treatment of defined non-string values as empty strings.+fn filter_string<'a>(state: &State, value: &'a Value) -> Result<&'a str, minijinja::Error> {+ StringInput::new(state, value)?;+ Ok(value.as_str().unwrap_or_default())+}+/// Set up a minijinja environment with worktrunk's custom filters and functions.////// Shared by [`expand_template`], [`validate_template`], and the `wt list`@@ -882,30 +903,36 @@ pub fn template_environment(repo: &Repository) -> Environment<'static> {env.set_undefined_behavior(UndefinedBehavior::SemiStrict);// Register custom filters- env.add_filter("sanitize", |value: Value| -> String {- sanitize_branch_name(value.as_str().unwrap_or_default())+ env.add_filter("sanitize", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(sanitize_branch_name(filter_string(state, &value)?))});- env.add_filter("sanitize_db", |value: Value| -> String {- sanitize_db(value.as_str().unwrap_or_default())+ env.add_filter("sanitize_db", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(sanitize_db(filter_string(state, &value)?))});- env.add_filter("sanitize_hash", |value: Value| -> String {- crate::path::sanitize_for_filename(value.as_str().unwrap_or_default())+ env.add_filter("sanitize_hash", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(crate::path::sanitize_for_filename(filter_string(+ state, &value,+ )?))});- env.add_filter("hash", |value: Value| -> String {- short_hash(value.as_str().unwrap_or_default())+ env.add_filter("hash", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(short_hash(filter_string(state, &value)?))});env.add_filter("hash_port", |value: String| string_to_port(&value));- env.add_filter("dirname", |value: Value| -> String {- std::path::Path::new(value.as_str().unwrap_or_default())- .parent()- .map(|p| to_posix_path(&p.to_string_lossy()))- .unwrap_or_default()+ env.add_filter("dirname", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(+ std::path::Path::new(filter_string(state, &value)?)+ .parent()+ .map(|p| to_posix_path(&p.to_string_lossy()))+ .unwrap_or_default(),+ )});- env.add_filter("basename", |value: Value| -> String {- std::path::Path::new(value.as_str().unwrap_or_default())- .file_name()- .map(|n| n.to_string_lossy().into_owned())- .unwrap_or_default()+ env.add_filter("basename", |state: &State, value: Value| {+ Ok::<_, minijinja::Error>(+ std::path::Path::new(filter_string(state, &value)?)+ .file_name()+ .map(|n| n.to_string_lossy().into_owned())+ .unwrap_or_default(),+ )});env.add_filter("codename", codename_filter);@@ -1006,11 +1033,8 @@ pub fn validate_template_syntax(template: &str, name: &str) -> Result<(), Templa/// Validate that a template can be expanded without errors in the given scope.///-/// Performs a trial expansion with placeholder values for exactly the variables-/// available in `scope` (see [`vars_available_in`]). Catches syntax errors and-/// undefined variable references *before* irreversible operations like worktree-/// creation — including context-mismatch typos like `{{ base }}` in a-/// `pre-merge` hook or `{{ args }}` in a `--execute` template.+/// Checks syntax and top-level variable references against [`vars_available_in`]+/// and environment globals, then trial-renders with placeholder context values.////// This is deliberately more permissive than real expansion: conditional vars/// like `upstream` are provided even when they may be absent at runtime. A@@ -1057,7 +1081,7 @@ pub fn validate_template(let mut undefined: Vec<String> = tmpl.undeclared_variables(false).into_iter()- .filter(|var| !allowed.contains(var))+ .filter(|var| !allowed.contains(var) && env.globals().all(|(key, _)| key != var)).collect();undefined.sort();if !undefined.is_empty() {@@ -1065,6 +1089,8 @@ pub fn validate_template(name,&undefined,sorted_available_vars(&available),+ template,+ None,));}@@ -1231,13 +1257,21 @@ pub fn expand_template_with(}}- let result = tmpl- .render(minijinja::Value::from_object(context))- .map_err(|e| {- let mut keys: Vec<String> = vars.keys().map(|k| k.to_string()).collect();- keys.sort();- build_template_error(&e, template, name, keys)- })?;+ let result = tmpl.render(Value::from_object(context)).map_err(|e| {+ let mut keys = vars.keys().map(|key| key.to_string()).collect::<Vec<_>>();+ keys.sort();+ if e.kind() == ErrorKind::UndefinedError+ && let Some(range) = e.range()+ && let Some(analysis) = TemplateVars::of(template)+ && let Some(var) = analysis.output_at(range)+ && !vars.contains_key(var)+ && var != "vars"+ && env.globals().all(|(key, _)| key != var)+ {+ return build_undefined_vars_error(name, &[var.to_string()], keys, template, e.line());+ }+ build_template_error(&e, template, name, keys)+ })?;// -vv: Full debug logging with result// Redact credentials from result to prevent leaking tokens in logs@@ -1302,10 +1336,11 @@ impl Object for AnyKeyVars {/// Validate a `wt list` custom-column template.////// Checks syntax, restricts top-level variables to `LIST_COLUMN_VARS` ∪-/// `{vars, git}`, and trial-renders with placeholder values so filter errors-/// (e.g. a misspelled filter name) surface at config resolution rather than as-/// silently empty cells. `vars.*` and `git.branch.*` access is unconstrained —-/// any key validates, since which keys exist is per-branch runtime state.+/// `{vars, git}` plus environment globals, and trial-renders with placeholder+/// values so filter errors (e.g. a misspelled filter name) surface at config+/// resolution rather than as silently empty cells. `vars.*` and `git.branch.*`+/// access is unconstrained — any key validates, since which keys exist is+/// per-branch runtime state.pub fn validate_list_column_template(template: &str,repo: &Repository,@@ -1319,7 +1354,12 @@ pub fn validate_list_column_template(let mut undefined: Vec<String> = tmpl.undeclared_variables(false).into_iter()- .filter(|var| var != "vars" && var != "git" && !LIST_COLUMN_VARS.contains(&var.as_str()))+ .filter(|var| {+ var != "vars"+ && var != "git"+ && !LIST_COLUMN_VARS.contains(&var.as_str())+ && env.globals().all(|(key, _)| key != var)+ }).collect();undefined.sort();if !undefined.is_empty() {@@ -1330,6 +1370,8 @@ pub fn validate_list_column_template(name,&undefined,sorted_available_vars(&available),+ template,+ None,));}@@ -1580,11 +1622,7 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);}#[test]@@ -1676,8 +1714,8 @@ mod tests {).unwrap_err();assert!(- err.message.contains("undefined value"),- "should mention undefined value: {}",+ err.message.contains("undefined"),+ "should mention undefined variable: {}",err.message);assert!(err.available_vars.contains(&"branch".to_string()));@@ -1686,12 +1724,129 @@ mod tests {// Diagnostic::render produces source line and available vars hintassert_snapshot!(crate::git::Diagnostic::render(&err), @"- [31m✗[39m [31mFailed to expand test: undefined value @ line 1[39m+ [31m✗[39m [31mFailed to expand test: undefined variable target @ line 1[39m[107m [0m echo {{ target }}[2m↳[22m [2mAvailable variables: [4mbranch[24m, [4mremote[24m[22m");}+ #[test]+ fn test_expand_template_names_reached_typo() {+ let test = test_repo();+ let vars = HashMap::from([("branch", "main")]);+ for template in [+ "{% if branch %}{{ brnch }}{% endif %}",+ "{% for item in [1] %}{{ brnch }}{% endfor %}",+ "{% if upstream %}{{ unvisited }}{% endif %}\necho {{ brnch | upper }}",+ "{% set captured %}{{ brnch }}{% endset %}",+ "{% autoescape true %}{{ brnch }}{% endautoescape %}",+ "{% filter upper %}{{ brnch }}{% endfilter %}",+ "{% with local = branch %}{{ brnch }}{% endwith %}",+ "{% set ns = namespace() %}{% set ns.brnch = branch %}{{ brnch }}",+ ] {+ let err = expand_template(+ template,+ &vars,+ ShellEscapeMode::Literal,+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert_eq!(+ err.message,+ format!(+ "Failed to expand test: undefined variable brnch @ line {}",+ template.lines().count()+ )+ );+ assert_eq!(err.suggestion.as_deref(), Some("branch"));+ assert_eq!(err.source_line.as_deref(), template.lines().last());+ }+ }++ #[test]+ fn test_undefined_namespace_values_do_not_name_unreached_typos() {+ let test = test_repo();+ let vars = HashMap::from([("branch", "main"), ("args", "[]")]);+ for template in [+ "{{ args[0] }}{{ brnch }}",+ "{{ vars.missing }}{{ brnch }}",+ "{% if optional %}{{ brnch }}{% endif %}{{ vars.missing }}",+ "{% set local = brnch %}{{ local }}",+ "{{ brnch if branch else other_missing }}",+ "{{ branch | replace(brnch, '-') }}",+ "{% if false %}{{ brnch }}{% endif %}{% set brnch = vars.missing %}{{ brnch }}",+ "{% if false %}{{ brnch }}{% endif %}{% with brnch = vars.missing %}{{ brnch }}{% endwith %}",+ "{% if false %}{{ brnch }}{% endif %}{% for brnch in [vars.missing] %}{{ brnch }}{% endfor %}",+ "{% if false %}{{ brnch }}{% endif %}{% for brnch, other in [[vars.missing, 1]] %}{{ brnch }}{% endfor %}",+ "{% if false %}{{ brnch }}{% endif %}{% set captured %}{% set brnch = vars.missing %}{{ brnch }}{% endset %}",+ ] {+ let err = expand_template(+ template,+ &vars,+ ShellEscapeMode::Literal,+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert_eq!(+ err.message,+ "Failed to expand test: undefined value @ line 1"+ );+ assert_eq!(err.suggestion, None);+ }+ }++ /// Custom filters must let MiniJinja reject undefined input rather than+ /// silently turn a misspelled branch into an empty path or hash.+ #[test]+ fn test_custom_filters_reject_undefined_input() {+ let test = test_repo();+ for filter in [+ "sanitize",+ "sanitize_db",+ "sanitize_hash",+ "hash",+ "hash_port",+ "dirname",+ "basename",+ "codename",+ ] {+ let template = format!("{{{{ brnch | {filter} }}}}");+ let err = expand_template(+ &template,+ &HashMap::new(),+ ShellEscapeMode::Literal,+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert_eq!(+ err.message,+ "Failed to expand test: undefined variable brnch @ line 1"+ );+ }+ }++ #[test]+ fn test_template_validation_uses_environment_globals() {+ let test = test_repo();+ let template = "{% for item in range(2) %}{{ item }}{% endfor %}";+ validate_template(template, ValidationScope::Alias, &test.repo, "test").unwrap();+ validate_list_column_template(template, &test.repo, "test").unwrap();+ assert_eq!(+ expand_template(+ template,+ &HashMap::new(),+ ShellEscapeMode::Literal,+ &test.repo,+ "test",+ )+ .unwrap(),+ "01"+ );+ }+#[test]fn test_expand_template_jinja_features() {let test = test_repo();@@ -3011,11 +3166,7 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);// `base` is available in pre-start.assert!(@@ -3047,11 +3198,7 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);assert!(err.message.contains("targte"), "got: {}", err.message);// `pr_number`/`pr_url` are available in pre-start (populated when@@ -3077,11 +3224,7 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);// `args` is available in hook scope (forwarded via smart routing).assert!(@@ -3102,11 +3245,7 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);}#[test]@@ -3162,14 +3301,37 @@ mod tests {"test",).unwrap_err();- assert!(- err.message.contains("undefined value"),- "got: {}",- err.message- );+ assert!(err.message.contains("undefined"), "got: {}", err.message);// Should list available vars in hintassert!(!err.available_vars.is_empty(), "should list available vars");assert!(err.available_vars.contains(&"branch".to_string()));++ let err = validate_template(+ "echo {{ brnch }}",+ ValidationScope::Hook(HookType::PreMerge),+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert_eq!(+ err.message,+ "Failed to expand test: undefined variable brnch"+ );+ assert_eq!(err.source_line.as_deref(), Some("echo {{ brnch }}"));+ assert_eq!(err.suggestion.as_deref(), Some("branch"));++ let err = validate_template(+ "{{ brnch }}{{ other_missing }}",+ ValidationScope::Alias,+ &test.repo,+ "test",+ )+ .unwrap_err();+ assert_eq!(+ err.message,+ "Failed to expand test: undefined variables brnch, other_missing"+ );+ assert_eq!(err.suggestion, None);}#[test]diff --git a/src/config/mod.rs b/src/config/mod.rsindex 7cc119827..e827fd791 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -23,6 +23,7 @@ mod error;mod expansion;mod hooks;mod project;+mod template_analysis;#[cfg(test)]mod test;mod unknown_tree;diff --git a/src/config/template_analysis.rs b/src/config/template_analysis.rsnew file mode 100644index 000000000..6a5ef241b--- /dev/null+++ b/src/config/template_analysis.rs@@ -0,0 +1,229 @@+//! MiniJinja syntax analysis shared by config migration and error diagnostics.+//!+//! The dependency parser owns grammar and source spans. This exhaustive visitor+//! records reads, bindings, and unambiguous output expressions; it does not+//! reconstruct runtime scopes or guess which operand produced an undefined value.+//! With macros and multi-template loading disabled, every AST variant is handled.+//! Dependency AST changes fail compilation rather than silently skipping syntax.++use std::collections::HashSet;+use std::ops::Range;++use minijinja::machinery::{ast, parse as parse_template};++pub(super) struct TemplateVars<'a> {+ /// The name and byte range of every `Expr::Var`, in visit order.+ pub(super) reads: Vec<(&'a str, Range<usize>)>,+ /// Locally bound names are excluded conservatively across the template.+ /// Migration checks both retired and replacement names: renaming a global+ /// to a name bound by a loop or assignment would capture the local value.+ /// Diagnostics similarly avoid assigning a missing local to a global.+ pub(super) bound: HashSet<&'a str>,+ outputs: Vec<(&'a str, Range<usize>)>,+}++impl<'a> TemplateVars<'a> {+ /// `None` when MiniJinja can't parse `template` — the templates its+ /// renderer rejects too, left untouched rather than guessed at.+ pub(super) fn of(template: &'a str) -> Option<Self> {+ // Whitespace settings shape literal output, never variable spans.+ let ast =+ parse_template(template, "<config>", Default::default(), Default::default()).ok()?;+ let mut vars = TemplateVars {+ reads: Vec::new(),+ bound: HashSet::new(),+ outputs: Vec::new(),+ };+ vars.stmt(&ast);+ Some(vars)+ }++ /// Name an output only when the engine range selects a plain global read,+ /// optionally passed through argument-free filters. Locals, lookups and+ /// compound expressions cannot establish the missing input this way.+ pub(super) fn output_at(&self, range: Range<usize>) -> Option<&'a str> {+ self.outputs.iter().find_map(|(name, span)| {+ (span.start <= range.start && span.end >= range.end && !self.bound.contains(name))+ .then_some(*name)+ })+ }++ fn body(&mut self, body: &[ast::Stmt<'a>]) {+ for stmt in body {+ self.stmt(stmt);+ }+ }++ fn stmt(&mut self, stmt: &ast::Stmt<'a>) {+ match stmt {+ ast::Stmt::Template(node) => self.body(&node.children),+ ast::Stmt::EmitExpr(node) => {+ let mut expr = &node.expr;+ while let ast::Expr::Filter(filter) = expr {+ if !filter.args.is_empty() {+ break;+ }+ let Some(input) = &filter.expr else {+ break;+ };+ expr = input;+ }+ if let ast::Expr::Var(var) = expr {+ let span = node.span();+ self.outputs+ .push((var.id, span.start_offset as usize..span.end_offset as usize));+ }+ self.expr(&node.expr);+ }+ // Literal output — the text around the tags, and everything inside+ // a `{% raw %}` block.+ ast::Stmt::EmitRaw(_) => {}+ ast::Stmt::ForLoop(node) => {+ self.bound.insert("loop");+ self.target(&node.target);+ self.expr(&node.iter);+ if let Some(filter) = &node.filter_expr {+ self.expr(filter);+ }+ self.body(&node.body);+ self.body(&node.else_body);+ }+ ast::Stmt::IfCond(node) => {+ self.expr(&node.expr);+ self.body(&node.true_body);+ self.body(&node.false_body);+ }+ ast::Stmt::WithBlock(node) => {+ for (target, value) in &node.assignments {+ self.target(target);+ self.expr(value);+ }+ self.body(&node.body);+ }+ ast::Stmt::Set(node) => {+ self.target(&node.target);+ self.expr(&node.expr);+ }+ ast::Stmt::SetBlock(node) => {+ self.target(&node.target);+ if let Some(filter) = &node.filter {+ self.expr(filter);+ }+ self.body(&node.body);+ }+ ast::Stmt::AutoEscape(node) => {+ self.expr(&node.enabled);+ self.body(&node.body);+ }+ ast::Stmt::FilterBlock(node) => {+ self.expr(&node.filter);+ self.body(&node.body);+ }+ ast::Stmt::Do(node) => self.call(&node.call),+ }+ }++ fn expr(&mut self, expr: &ast::Expr<'a>) {+ match expr {+ ast::Expr::Var(node) => {+ let span = node.span();+ self.reads.push((+ node.id,+ span.start_offset as usize..span.end_offset as usize,+ ));+ }+ ast::Expr::Const(_) => {}+ ast::Expr::Slice(node) => {+ self.expr(&node.expr);+ for bound in [&node.start, &node.stop, &node.step].into_iter().flatten() {+ self.expr(bound);+ }+ }+ ast::Expr::UnaryOp(node) => self.expr(&node.expr),+ ast::Expr::BinOp(node) => {+ self.expr(&node.left);+ self.expr(&node.right);+ }+ ast::Expr::Compare(node) => {+ self.expr(&node.expr);+ for op in &node.ops {+ self.expr(&op.expr);+ }+ }+ ast::Expr::IfExpr(node) => {+ self.expr(&node.test_expr);+ self.expr(&node.true_expr);+ if let Some(false_expr) = &node.false_expr {+ self.expr(false_expr);+ }+ }+ // A filter or test names a function the environment supplies, not+ // a variable, so only its input and arguments are reads.+ ast::Expr::Filter(node) => {+ if let Some(expr) = &node.expr {+ self.expr(expr);+ }+ self.args(&node.args);+ }+ ast::Expr::Test(node) => {+ self.expr(&node.expr);+ self.args(&node.args);+ }+ // `{{ foo.repo_root }}` reads `foo`; the attribute belongs to+ // whatever that resolves to, never to the deprecated global.+ ast::Expr::GetAttr(node) => self.expr(&node.expr),+ ast::Expr::GetItem(node) => {+ self.expr(&node.expr);+ self.expr(&node.subscript_expr);+ }+ ast::Expr::Call(node) => self.call(node),+ ast::Expr::List(node) => {+ for item in &node.items {+ self.expr(item);+ }+ }+ ast::Expr::Map(node) => {+ for entry in node.keys.iter().chain(&node.values) {+ self.expr(entry);+ }+ }+ }+ }++ fn call(&mut self, call: &ast::Call<'a>) {+ self.expr(&call.expr);+ self.args(&call.args);+ }++ /// A keyword argument's name belongs to the call it is passed to, so only+ /// the argument values are reads.+ fn args(&mut self, args: &[ast::CallArg<'a>]) {+ for arg in args {+ match arg {+ ast::CallArg::Pos(expr)+ | ast::CallArg::Kwarg(_, expr)+ | ast::CallArg::PosSplat(expr)+ | ast::CallArg::KwargSplat(expr) => self.expr(expr),+ }+ }+ }++ /// The names an assignment target binds.+ fn target(&mut self, target: &ast::Expr<'a>) {+ match target {+ ast::Expr::Var(node) => {+ self.bound.insert(node.id);+ }+ // A tuple target, nested arbitrarily: `{% for (a, (b, c)) in … %}`.+ ast::Expr::List(node) => {+ for item in &node.items {+ self.target(item);+ }+ }+ // A dotted target mutates an attribute of whatever the path+ // resolves to, so `{% set repo_root.x = … %}` reads the global+ // rather than binding it.+ read => self.expr(read),+ }+ }+}diff --git a/src/config/test.rs b/src/config/test.rsindex f390162f3..2a2b48fab 100644--- a/src/config/test.rs+++ b/src/config/test.rs@@ -223,7 +223,7 @@ fn test_expand_template_missing_variable() {assert!(result.is_err());let err = result.unwrap_err();assert!(- err.message.contains("undefined value"),+ err.message.contains("undefined variable"),"got: {}",err.message);diff --git a/src/git/error.rs b/src/git/error.rsindex db063ffa0..1c0aa979b 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -2634,10 +2634,11 @@ mod tests {command_name: None,error: anyhow::anyhow!("setup failed"),};- assert_snapshot!(err.render(), @"- [31m✗[39m [31m[1mpre-start user hook[22m failed[39m- [107m [0m [2m[0m[2m[34mecho[0m[2m test[0m- [107m [0m setup failed+ // Shell decoration varies by feature; this snapshot covers error composition.+ assert_snapshot!(ansi_str::AnsiStr::ansi_strip(&err.render()), @"+ ✗ pre-start user hook failed+ echo test+ setup failed");// Silent errors produce empty outputdiff --git a/src/utils.rs b/src/utils.rsindex 4fbf34e01..9d4e55061 100644--- a/src/utils.rs+++ b/src/utils.rs@@ -5,6 +5,26 @@ use std::io::{self, Write};use std::path::Path;use std::time::{SystemTime, UNIX_EPOCH};+/// Return candidates similar to `query`, sorted by descending Jaro–Winkler+/// similarity, filtered by `score > 0.7`, and deduplicated while preserving+/// order. The 0.7 threshold matches clap's internal `did_you_mean` so+/// wt-synthesized "unrecognized subcommand" tips read identically to clap's+/// native output — keep them aligned if clap ever changes it.+pub fn did_you_mean(query: &str, candidates: impl IntoIterator<Item = String>) -> Vec<String> {+ let mut scored: Vec<(f64, String)> = candidates+ .into_iter()+ .map(|candidate| (strsim::jaro_winkler(query, &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));+ let mut seen = std::collections::HashSet::new();+ scored+ .into_iter()+ .filter(|(_, n)| seen.insert(n.clone()))+ .map(|(_, n)| n)+ .collect()+}+/// Replace C0/C1 control characters — other than tab and newline — with a/// visible escape so the text stays valid for plain-text and markdown sinks.///diff --git a/tests/integration_tests/foreground_jobs.rs b/tests/integration_tests/foreground_jobs.rsindex 068722472..6fdb1386b 100644--- a/tests/integration_tests/foreground_jobs.rs+++ b/tests/integration_tests/foreground_jobs.rs@@ -372,6 +372,7 @@ fn invalid_utf8_pager_is_not_executed(repo: TestRepo) {#[case::custom_caught_success(false, "caught-key", 0, 0)]#[case::custom_caught_130(false, "caught-key", 130, 130)]#[case::custom_raw_int(false, "raw-key", 0, 130)]+#[case::custom_raw_term(false, "raw-term", 0, 143)]#[case::custom_caught_term(false, "caught-term", 0, 143)]#[case::pager_caught_success(true, "caught-key", 0, 0)]#[case::pager_caught_130(true, "caught-key", 130, 0)]diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex fdec15ad9..b64371e76 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -1357,7 +1357,7 @@ broken = "echo {{ does_not_exist }} > should_not_exist.txt"// Same label the foreground path renders for this command (see the// foreground_pipeline_undefined_var_runs_earlier_steps snapshot).assert_snapshot!(log_content, @"- [31m✗[39m [31mFailed to expand user:broken: undefined value @ line 1[39m+ [31m✗[39m [31mFailed to expand user:broken: undefined variable does_not_exist @ line 1[39m[107m [0m echo {{ does_not_exist }} > should_not_exist.txt[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_name[24m, [4mhook_type[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mupstream[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m");@@ -1554,6 +1554,17 @@ fn test_foreground_pipeline_undefined_var_runs_earlier_steps(repo: TestRepo) {);}+#[rstest]+fn test_hook_template_typo_names_variable(repo: TestRepo) {+ repo.write_test_config("pre-merge = \"echo {{ brnch }}\"\n");+ let settings = setup_snapshot_settings(&repo);+ settings.bind(|| {+ let mut cmd = repo.wt_command();+ cmd.args(["hook", "pre-merge", "--yes"]);+ assert_cmd_snapshot!(cmd);+ });+}+/// The other half of that contract: a *syntax* error anywhere in the pipeline/// aborts before step 1. Preparation parses every template/// (`PreparedPipeline::validated`), so a pipeline that can't render in full neverdiff --git a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snapindex ec583c35c..f4fe39034 100644--- a/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap+++ b/tests/snapshots/integration__integration_tests__eval__eval_template_error.snap@@ -60,6 +60,6 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mFailed to expand eval: undefined value @ line 1[39m+[31m✗[39m [31mFailed to expand eval: undefined variable undefined_var @ line 1[39m[107m [0m {{ undefined_var }}[2m↳[22m [2mAvailable variables: [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mupstream[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snapindex befb5351c..4ac3aa58c 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap@@ -65,6 +65,6 @@ exit_code: 1[36m◎[39m [36mRunning in [1mmain[22m...[39m[0mBranch: main[36m◎[39m [36mRunning in [1mrepo.detached-test[22m (detached)...[39m-[31m✗[39m [31mFailed to expand for-each argument: undefined value @ line 1[39m+[31m✗[39m [31mFailed to expand for-each argument: undefined variable branch @ line 1[39m[107m [0m Branch: {{ branch }}[2m↳[22m [2mAvailable variables: [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snapindex 728f94d87..b4d89fc1f 100644--- a/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap+++ b/tests/snapshots/integration__integration_tests__hook_show__hook_show_expanded_undefined_var.snap@@ -64,7 +64,7 @@ exit_code: 0[36mPROJECT HOOKS[39m @ _REPO_/.config/wt.toml[36m❯[39m pre-commit [1moptional-var[22m: [2m(requires approval)[22m-[107m [0m [2m# Failed to expand project:optional-var: undefined value @ line 1[0m+[107m [0m [2m# Failed to expand project:optional-var: undefined variable base @ line 1[0m[107m [0m [2m[0m[2m[34mecho[0m[2m [0m[2m[32m{{[0m[2m base [0m[2m[32m}}[0m----- stderr -----diff --git a/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snap b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snapindex 765868e00..0faf7cdca 100644--- a/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snap+++ b/tests/snapshots/integration__integration_tests__list_config__list_custom_column_invalid_template.snap@@ -58,5 +58,7 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mFailed to expand list.custom-columns.Ticket: undefined value: `branhc`[39m+[31m✗[39m [31mFailed to expand list.custom-columns.Ticket: undefined variable branhc[39m+[107m [0m {{ branhc }}+[2m↳[22m [2mDid you mean [4mbranch[24m?[22m[2m↳[22m [2mAvailable variables: [4mbranch[24m, [4mgit.branch.<key>[24m, [4mvars.<key>[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snapindex 3088c45ff..bdf437d11 100644--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_start_upstream_template.snap@@ -61,6 +61,6 @@ exit_code: 1----- stdout ---------- stderr ------[31m✗[39m [31mFailed to expand pre-start project hook: undefined value @ line 1[39m+[31m✗[39m [31mFailed to expand pre-start project hook: undefined variable upstream @ line 1[39m[107m [0m echo 'Upstream: {{ upstream }}' > upstream.txt[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbase[24m, [4mbase_worktree_path[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snapindex ceb07f140..814e9113f 100644--- a/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap+++ b/tests/snapshots/integration__integration_tests__step_relocate__relocate_template_error.snap@@ -61,7 +61,7 @@ exit_code: 0----- stderr -----[33m▲[39m [33mSkipping [1mfeature[22m due to template error:[39m-[31m✗[39m [31mFailed to expand worktree-path: undefined value @ line 1[39m+[31m✗[39m [31mFailed to expand worktree-path: undefined variable nonexistent_variable @ line 1[39m[107m [0m {{ nonexistent_variable }}[2m↳[22m [2mAvailable variables: [4mbranch[24m, [4mrepo[24m, [4mrepo_path[24m[22m[2m○[22m No relocations performed; 1 skipped due to template errordiff --git a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snapindex 00036ba5f..d84b1c024 100644--- a/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap+++ b/tests/snapshots/integration__integration_tests__user_hooks__foreground_pipeline_undefined_var_runs_earlier_steps.snap@@ -47,6 +47,6 @@ exit_code: 1----- stderr -----[36m◎[39m [36mRunning pre-merge [1muser:first[22m[39m[107m [0m [2m[0m[2m[34mecho[0m[2m FIRST_RAN [0m[2m[36m>[0m[2m first_marker.txt[0m-[0m[31m✗[39m [31mFailed to expand user:broken: undefined value @ line 1[39m+[0m[31m✗[39m [31mFailed to expand user:broken: undefined variable does_not_exist @ line 1[39m[107m [0m echo {{ does_not_exist }}[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_name[24m, [4mhook_type[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mupstream[24m, [4mworktree_name[24m, [4mworktree_path[24m[22mdiff --git a/tests/snapshots/integration__integration_tests__user_hooks__hook_template_typo_names_variable.snap b/tests/snapshots/integration__integration_tests__user_hooks__hook_template_typo_names_variable.snapnew file mode 100644index 000000000..d58b0fc59--- /dev/null+++ b/tests/snapshots/integration__integration_tests__user_hooks__hook_template_typo_names_variable.snap@@ -0,0 +1,66 @@+---+source: tests/integration_tests/user_hooks.rs+info:+ program: wt+ args:+ - hook+ - pre-merge+ - "--yes"+ env:+ APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"+ CLICOLOR_FORCE: "1"+ COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: file+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test User+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"+ GIT_TERMINAL_PROMPT: "0"+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ LLVM_PROFILE_FILE: "[LLVM_PROFILE_FILE]"+ OPENCODE_CONFIG_DIR: "[TEST_OPENCODE_CONFIG]"+ PATH: "[PATH]"+ TERM: alacritty+ USERPROFILE: "[TEST_HOME]"+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"+ WORKTRUNK_TEST_BASH_INSTALLED: "0"+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"+ WORKTRUNK_TEST_CODEX_INSTALLED: "0"+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"+ WORKTRUNK_TEST_EPOCH: "1735776000"+ WORKTRUNK_TEST_FISH_INSTALLED: "0"+ WORKTRUNK_TEST_GEMINI_INSTALLED: "0"+ WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"+ WORKTRUNK_TEST_NUSHELL_ENV: "0"+ WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"+ WORKTRUNK_TEST_PROBE_TIMEOUT_MS: "60000"+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"+---+success: false+exit_code: 1+----- stdout -----++----- stderr -----+[31m✗[39m [31mFailed to expand pre-merge user hook: undefined variable brnch @ line 1[39m+[107m [0m echo {{ brnch }}+[2m↳[22m [2mDid you mean [4mbranch[24m?[22m+[2m↳[22m [2mAvailable variables: [4margs[24m, [4mbranch[24m, [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mhook_type[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mshort_commit[24m, [4mtarget[24m, [4mtarget_worktree_path[24m, [4mupstream[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m