Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Leave the branch template variable unset in a detached worktree (#4010)
Worktrunk Bot3f87fec5a72d
diff --git a/docs/src/content/docs/hook.md b/docs/src/content/docs/hook.mdindex e5ab5f2cd..1b298fe5f 100644--- a/docs/src/content/docs/hook.md+++ b/docs/src/content/docs/hook.md@@ -120,7 +120,7 @@ Hooks can use template variables that expand at runtime:| Kind | Variable | Description ||------|----------|-------------|-| active | `{{ branch }}` | Branch name |+| active | `{{ branch }}` | Branch name; unset in a detached worktree || | `{{ worktree_path }}` | Worktree path || | `{{ worktree_name }}` | Worktree directory name || | `{{ commit }}` | Branch HEAD SHA |@@ -173,6 +173,8 @@ Undefined variables error — use conditionals or defaults for optional behaviorsync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"```+A detached worktree is on no branch, so `branch` is undefined there — as are the `base` and `target` names derived from it, whether by a manual `wt hook` or by an operation whose source or destination worktree is detached (`base` in a `pre-switch` fired from one, `target` in a removal that lands in one) — and the same `{% if branch %}` guard applies. This matches `wt list --format=json`, which reports `branch: null` for the same worktree.+Run any hook-firing command with `-v` to see the resolved variables for the actual invocation — each hook prints a `template variables:` block showing every in-scope variable and its value (`(unset)` for conditional vars that didn't populate, like `target_worktree_path` during `wt switch -`). Aliases do the same under `-v`: `wt -v <alias>` prints the alias's in-scope variables before the pipeline runs.Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:@@ -247,7 +249,7 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path## JSON context-Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express:+Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express. Variables that are unset in a template are absent from the JSON too, so read the optional ones with a default — `branch` has none in a detached worktree:```toml[pre-start]@@ -257,7 +259,7 @@ setup = "python3 scripts/pre-start-setup.py"```pythonimport json, sys, subprocessctx = json.load(sys.stdin)-if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+if ctx.get('branch', '').startswith('feature/') and 'backend' in ctx['repo']:subprocess.run(['make', 'seed-db'])```diff --git a/plugins/worktrunk/skills/worktrunk/reference/hook.md b/plugins/worktrunk/skills/worktrunk/reference/hook.mdindex b99039f97..2cde87d8e 100644--- a/plugins/worktrunk/skills/worktrunk/reference/hook.md+++ b/plugins/worktrunk/skills/worktrunk/reference/hook.md@@ -114,7 +114,7 @@ Hooks can use template variables that expand at runtime:| Kind | Variable | Description ||------|----------|-------------|-| active | `{{ branch }}` | Branch name |+| active | `{{ branch }}` | Branch name; unset in a detached worktree || | `{{ worktree_path }}` | Worktree path || | `{{ worktree_name }}` | Worktree directory name || | `{{ commit }}` | Branch HEAD SHA |@@ -167,6 +167,8 @@ Undefined variables error — use conditionals or defaults for optional behaviorsync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"```+A detached worktree is on no branch, so `branch` is undefined there — as are the `base` and `target` names derived from it, whether by a manual `wt hook` or by an operation whose source or destination worktree is detached (`base` in a `pre-switch` fired from one, `target` in a removal that lands in one) — and the same `{% if branch %}` guard applies. This matches `wt list --format=json`, which reports `branch: null` for the same worktree.+Run any hook-firing command with `-v` to see the resolved variables for the actual invocation — each hook prints a `template variables:` block showing every in-scope variable and its value (`(unset)` for conditional vars that didn't populate, like `target_worktree_path` during `wt switch -`). Aliases do the same under `-v`: `wt -v <alias>` prints the alias's in-scope variables before the pipeline runs.Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:@@ -241,7 +243,7 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path## JSON context-Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express:+Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express. Variables that are unset in a template are absent from the JSON too, so read the optional ones with a default — `branch` has none in a detached worktree:```toml[pre-start]@@ -251,7 +253,7 @@ setup = "python3 scripts/pre-start-setup.py"```pythonimport json, sys, subprocessctx = json.load(sys.stdin)-if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+if ctx.get('branch', '').startswith('feature/') and 'backend' in ctx['repo']:subprocess.run(['make', 'seed-db'])```diff --git a/skills/worktrunk/reference/hook.md b/skills/worktrunk/reference/hook.mdindex b99039f97..2cde87d8e 100644--- a/skills/worktrunk/reference/hook.md+++ b/skills/worktrunk/reference/hook.md@@ -114,7 +114,7 @@ Hooks can use template variables that expand at runtime:| Kind | Variable | Description ||------|----------|-------------|-| active | `{{ branch }}` | Branch name |+| active | `{{ branch }}` | Branch name; unset in a detached worktree || | `{{ worktree_path }}` | Worktree path || | `{{ worktree_name }}` | Worktree directory name || | `{{ commit }}` | Branch HEAD SHA |@@ -167,6 +167,8 @@ Undefined variables error — use conditionals or defaults for optional behaviorsync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"```+A detached worktree is on no branch, so `branch` is undefined there — as are the `base` and `target` names derived from it, whether by a manual `wt hook` or by an operation whose source or destination worktree is detached (`base` in a `pre-switch` fired from one, `target` in a removal that lands in one) — and the same `{% if branch %}` guard applies. This matches `wt list --format=json`, which reports `branch: null` for the same worktree.+Run any hook-firing command with `-v` to see the resolved variables for the actual invocation — each hook prints a `template variables:` block showing every in-scope variable and its value (`(unset)` for conditional vars that didn't populate, like `target_worktree_path` during `wt switch -`). Aliases do the same under `-v`: `wt -v <alias>` prints the alias's in-scope variables before the pipeline runs.Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:@@ -241,7 +243,7 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path## JSON context-Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express:+Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express. Variables that are unset in a template are absent from the JSON too, so read the optional ones with a default — `branch` has none in a detached worktree:```toml[pre-start]@@ -251,7 +253,7 @@ setup = "python3 scripts/pre-start-setup.py"```pythonimport json, sys, subprocessctx = json.load(sys.stdin)-if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+if ctx.get('branch', '').startswith('feature/') and 'backend' in ctx['repo']:subprocess.run(['make', 'seed-db'])```diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 67d290609..69f200b9b 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1676,7 +1676,7 @@ Hooks can use template variables that expand at runtime:| Kind | Variable | Description ||------|----------|-------------|-| active | `{{ branch }}` | Branch name |+| active | `{{ branch }}` | Branch name; unset in a detached worktree || | `{{ worktree_path }}` | Worktree path || | `{{ worktree_name }}` | Worktree directory name || | `{{ commit }}` | Branch HEAD SHA |@@ -1729,6 +1729,8 @@ Undefined variables error — use conditionals or defaults for optional behaviorsync = "{% if upstream %}git fetch && git rebase {{ upstream }}{% endif %}"```+A detached worktree is on no branch, so `branch` is undefined there — as are the `base` and `target` names derived from it, whether by a manual `wt hook` or by an operation whose source or destination worktree is detached (`base` in a `pre-switch` fired from one, `target` in a removal that lands in one) — and the same `{% if branch %}` guard applies. This matches `wt list --format=json`, which reports `branch: null` for the same worktree.+Run any hook-firing command with `-v` to see the resolved variables for the actual invocation — each hook prints a `template variables:` block showing every in-scope variable and its value (`(unset)` for conditional vars that didn't populate, like `target_worktree_path` during `wt switch -`). Aliases do the same under `-v`: `wt -v <alias>` prints the alias's in-scope variables before the pipeline runs.Variables use dot access and the `default` filter for missing keys. JSON object/array values are parsed automatically, so `{{ vars.config.port }}` works when the value is `{"port": 3000}`:@@ -1803,7 +1805,7 @@ setup = "cp {{ worktree_path_of_branch('main') }}/config.local {{ worktree_path## JSON context-Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express:+Hooks receive all template variables as JSON on stdin, enabling complex logic that templates can't express. Variables that are unset in a template are absent from the JSON too, so read the optional ones with a default — `branch` has none in a detached worktree:```toml[pre-start]@@ -1813,7 +1815,7 @@ setup = "python3 scripts/pre-start-setup.py"```pythonimport json, sys, subprocessctx = json.load(sys.stdin)-if ctx['branch'].startswith('feature/') and 'backend' in ctx['repo']:+if ctx.get('branch', '').startswith('feature/') and 'backend' in ctx['repo']:subprocess.run(['make', 'seed-db'])```diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 4945cc53a..b77df4b86 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -200,11 +200,6 @@ impl<'a> CommandContext<'a> {}}- /// Get branch name, using "HEAD" as fallback for detached HEAD state.- pub fn branch_or_head(&self) -> &str {- self.branch.unwrap_or("HEAD")- }-/// Get the project identifier for per-project config lookup.////// Uses the remote URL if available, otherwise the canonical repository path.@@ -273,7 +268,15 @@ pub fn build_hook_context(// (subprocesses, git config / remote lookups) consult `scope`.let mut map = HashMap::new();map.insert("repo".into(), repo_name.into());- map.insert("branch".into(), ctx.branch_or_head().into());+ // A detached worktree has no branch, so `branch` stays unset and+ // `{% if branch %}` guards it the way every other optional variable is+ // guarded. The old `HEAD` fallback was worse than useless: it is a string+ // git resolves as a ref, so a guard passed and the command ran against the+ // wrong thing (issue #4009). Unset also agrees with `wt list --json`,+ // which reports `branch: null` for the same worktree.+ if let Some(branch) = ctx.branch {+ map.insert("branch".into(), branch.into());+ }map.insert("worktree_name".into(), worktree_name.into());map.insert("repo_path".into(), repo_path.clone());map.insert("worktree_path".into(), worktree.clone());diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 0aac03496..30b6b44f9 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -75,7 +75,8 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any);// Build full hook context for this worktree- // Pass wt.branch directly (not the display string) so detached HEAD maps to None -> "HEAD"+ // Pass wt.branch directly (not the display string) so a detached+ // worktree maps to None and leaves `{{ branch }}` unsetlet ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);let context_map = build_hook_context(&ctx, &[], VarScope::All)?;diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex 625c1240d..a92cd8055 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -83,12 +83,17 @@ fn run_post_hook(/// provide reasonable defaults: the current branch as both base and target, and/// the current worktree path for directional path vars.///+/// The directional *path* vars apply either way, since the worktree exists+/// whether or not it is on a branch. The directional *branch* vars follow+/// `branch` itself: a detached worktree leaves them unset rather than naming+/// the literal `HEAD` (issue #4009).+////// This is the single source of truth for manual hook context — both `run_hook`/// (execution + dry-run) and [`hook_command_rows`] (`hook show --expanded`) use/// this function. Returns a `TemplateVars` so callers can extend with/// additional bindings (e.g. CLI shorthand) before materializing.fn build_manual_hook_template_vars(ctx: &CommandContext, hook_type: HookType) -> TemplateVars {- let branch = ctx.branch_or_head();+ let branch = ctx.branch;let worktree_path = ctx.worktree_path;match hook_type {// Merge/commit hooks: target = merge target (default branch for commit,@@ -100,18 +105,18 @@ fn build_manual_hook_template_vars(ctx: &CommandContext, hook_type: HookType) ->.default_branch().map_or_else(TemplateVars::new, |t| TemplateVars::new().with_target(&t)),HookType::PreMerge | HookType::PostMerge => TemplateVars::new()- .with_target(branch)+ .with_target_opt(branch).with_target_worktree_path(worktree_path),// Switch hooks: base = current (we're "switching from" here)HookType::PreSwitch | HookType::PreCreate | HookType::PostCreate | HookType::PostSwitch => {TemplateVars::new().with_base(branch, worktree_path)- .with_target(branch)+ .with_target_opt(branch).with_target_worktree_path(worktree_path)}// Remove hooks: target = where user ends up (current worktree is the best guess)HookType::PreRemove | HookType::PostRemove => TemplateVars::new()- .with_target(branch)+ .with_target_opt(branch).with_target_worktree_path(worktree_path),}}@@ -177,7 +182,8 @@ pub struct HookCliArgs<'a> {/// When explicitly invoking hooks, ALL hooks run (both user and project)./// There's no skip flag - if you explicitly run hooks, all configured hooks run.///-/// Works in detached HEAD state - `{{ branch }}` template variable will be "HEAD".+/// Works in detached HEAD state - the `{{ branch }}` template variable (and the+/// `{{ base }}` / `{{ target }}` names derived from it) is simply unset there.////// Template variables come from three sources in [`HookCliArgs`], routed per/// alias semantics:@@ -368,7 +374,8 @@ pub fn handle_hook_show(// Build context for template expansion (only used if --expanded).// Need to keep CommandEnv alive for the lifetime of ctx. Detached HEAD is- // fine: `{{ branch }}` expands to "HEAD" there.+ // fine: `{{ branch }}` is unset there, and `--expanded` renders the+ // guarded form the way any other unset variable renders.let env = if expanded {Some(CommandEnv::for_action_loading_config()?)} else {diff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex 8d9e23dc2..03e9b3afc 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -528,7 +528,9 @@ fn spawn_hook_pipeline_quiet(repo: &Repository, pipeline: PendingPipeline) -> an// so `steps[0]` is safe.let source = pipeline.steps[0].source;- // "HEAD" fallback matches `CommandContext::branch_or_head` for detached HEAD.+ // Only names the pipeline's log file, so a detached worktree needs some+ // literal here — unlike the `branch` template variable, which stays unset+ // rather than claiming a branch the worktree isn't on (issue #4009).let branch = pipeline.branch.unwrap_or_else(|| "HEAD".to_string());let hook_type = pipeline.hook_type;let spec = PipelineSpec {diff --git a/src/commands/template_vars.rs b/src/commands/template_vars.rsindex bd390f8c6..844e86da8 100644--- a/src/commands/template_vars.rs+++ b/src/commands/template_vars.rs@@ -42,9 +42,11 @@ impl TemplateVars {Self::default()}- /// Set `base` (source branch) and `base_worktree_path` from a path.- pub fn with_base(mut self, branch: &str, worktree_path: &Path) -> Self {- self.base = Some(branch.to_string());+ /// Set `base` (source branch) and `base_worktree_path` from a path. The+ /// branch is optional because a detached worktree has a path but no branch+ /// to name; the path is set either way.+ pub fn with_base(mut self, branch: Option<&str>, worktree_path: &Path) -> Self {+ self.base = branch.map(str::to_owned);self.base_worktree_path = Some(to_posix_path(&worktree_path.to_string_lossy()));self}@@ -64,6 +66,13 @@ impl TemplateVars {self}+ /// Set `target` when there is one — a detached worktree leaves it unset+ /// rather than naming the literal `HEAD` (issue #4009).+ pub fn with_target_opt(mut self, branch: Option<&str>) -> Self {+ self.target = branch.map(str::to_owned);+ self+ }+/// Set `target_worktree_path` from a path.pub fn with_target_worktree_path(mut self, path: &Path) -> Self {self.target_worktree_path = Some(to_posix_path(&path.to_string_lossy()));@@ -193,7 +202,7 @@ mod tests {#[test]fn directional_pairs_round_trip() {let vars = TemplateVars::new()- .with_base("main", &PathBuf::from("/repo"))+ .with_base(Some("main"), &PathBuf::from("/repo")).with_target("feature").with_target_worktree_path(&PathBuf::from("/repo.feature"));let pairs = vars.as_extra_vars();diff --git a/src/commands/worktree/hooks.rs b/src/commands/worktree/hooks.rsindex 4b11b5789..a4c74d8e4 100644--- a/src/commands/worktree/hooks.rs+++ b/src/commands/worktree/hooks.rs@@ -51,7 +51,7 @@ pub(crate) struct PostRemoveContext {commit: String,short_commit: String,target_path_str: String,- target_branch: String,+ target_branch: Option<String>,}impl PostRemoveContext {@@ -79,13 +79,12 @@ impl PostRemoveContext {};// Target vars: where the user ends up after removal (primary worktree).+ // A detached primary worktree leaves `target` unset rather than empty,+ // matching `branch`: `format_variables_table` renders an absent var as+ // `(unset)` — "the operation couldn't supply this" — and that label only+ // holds while a branch var nobody can name stays out of the map.let target_path_str = to_posix_path(&main_path.to_string_lossy());- let target_branch = repo- .worktree_at(main_path)- .branch()- .ok()- .flatten()- .unwrap_or_default();+ let target_branch = repo.worktree_at(main_path).branch().ok().flatten();Self {worktree_path_str,@@ -100,16 +99,26 @@ impl PostRemoveContext {/// Build extra_vars that override the base context with removed-worktree identity.////// `removed_branch` is borrowed from the caller (it outlives the returned Vec).- pub fn extra_vars<'a>(&'a self, removed_branch: &'a str) -> Vec<(&'a str, &'a str)> {- vec![- ("branch", removed_branch),- ("worktree_path", &self.worktree_path_str),+ /// It is `None` when the removed worktree was detached: `extra_vars` is+ /// applied unconditionally at the end of `build_hook_context`, so emitting a+ /// `"HEAD"` literal here would overwrite the unset `branch` that context+ /// deliberately leaves out (issue #4009). `target` is skipped the same way+ /// when the primary worktree the removal lands in is itself detached.+ pub fn extra_vars<'a>(&'a self, removed_branch: Option<&'a str>) -> Vec<(&'a str, &'a str)> {+ let mut vars = vec![+ ("worktree_path", &*self.worktree_path_str),("worktree", &self.worktree_path_str), // deprecated alias("worktree_name", &self.worktree_name),("commit", &self.commit),("short_commit", &self.short_commit),- ("target", &self.target_branch),("target_worktree_path", &self.target_path_str),- ]+ ];+ if let Some(target) = self.target_branch.as_deref() {+ vars.push(("target", target));+ }+ if let Some(branch) = removed_branch {+ vars.push(("branch", branch));+ }+ vars}}diff --git a/src/commands/worktree/switch.rs b/src/commands/worktree/switch.rsindex 758874935..f3812de18 100644--- a/src/commands/worktree/switch.rs+++ b/src/commands/worktree/switch.rs@@ -1513,12 +1513,15 @@ fn run_pre_switch_hooks(// Active overrides come from the destination worktree if it exists —// for creates the planned path is computed later during plan_switch,// so worktree_path stays at its default (the source = cwd).- let base_branch = current_wt.branch().ok().flatten().unwrap_or_default();+ // A detached source worktree leaves `base` unset rather than empty,+ // matching `branch` and what `wt hook pre-switch` already renders+ // there (issue #4009).+ let base_branch = current_wt.branch().ok().flatten();let dest_path = repo.worktree_for_branch(&resolved_target).ok().flatten();let ref_identity = ref_target.and_then(|t| t.ref_identity.as_ref());let mut vars = TemplateVars::new()- .with_base(&base_branch, ¤t_path)+ .with_base(base_branch.as_deref(), ¤t_path).with_target(&resolved_target).with_pr(ref_identity.map(|id| id.number),diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex a84d1c0f4..0843909e8 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -297,6 +297,12 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {vars}+/// Cheap vars `build_hook_context` computes regardless of [`VarScope`] but+/// which can still come out absent, so their absence is `(unset)` — a fact+/// about the worktree — rather than `(unused)`, which claims the scope gate+/// skipped the work. `branch` is absent in a detached worktree.+const ALWAYS_COMPUTED_VARS: &[&str] = &["branch"];+/// Shared formatter for [`format_hook_variables`] and [`format_alias_variables`].////// Renders `vars` as an aligned `name = value` block — no heading, no indent,@@ -307,14 +313,18 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {/// When `referenced` is `Some`, vars absent from `ctx` *and* not in the set/// render as dim `(unused)` — `build_hook_context` only skips computation for/// expensive vars, so this fires precisely when the gate saved real work.-/// Cheap vars are populated unconditionally and always show their value, even-/// when the body doesn't reference them. `(unset)` is reserved for the-/// distinct case of a referenced var the operation couldn't supply.-///-/// `(unset)` relies on an invariant in `build_hook_context`: optional vars-/// are omitted from the map rather than inserted as empty strings. If a-/// future caller starts inserting `""`, revisit the empty-vs-absent-/// distinction here.+/// Cheap vars are populated unconditionally, so they show their value even+/// when the body doesn't reference them — though a cheap var can still come+/// out absent. `(unset)` is reserved for the distinct case of a var the+/// operation couldn't supply — including [`ALWAYS_COMPUTED_VARS`], the cheap+/// vars that are computed whatever the scope but can still be genuinely+/// absent.+///+/// `(unset)` relies on an invariant in `build_hook_context` that the+/// `extra_vars` layered on top must hold too (see+/// `PostRemoveContext::extra_vars`): optional vars are omitted from the map+/// rather than inserted as empty strings. If a future caller starts inserting+/// `""`, revisit the empty-vs-absent distinction here.fn format_variables_table(vars: &[&'static str],ctx: &TemplateContext,@@ -324,7 +334,9 @@ fn format_variables_table(vars.iter().map(|var| match ctx.get(var) {Some(value) => format!("{var:<max_name$} = {value}"),- None if !scope.wants(var) => cformat!("<dim>{var:<max_name$} = (unused)</>"),+ None if !scope.wants(var) && !ALWAYS_COMPUTED_VARS.contains(var) => {+ cformat!("<dim>{var:<max_name$} = (unused)</>")+ }None => format!("{var:<max_name$} = (unset)"),}).collect::<Vec<_>>()@@ -1185,8 +1197,8 @@ pub fn expand_template_with(.map_err(|e| build_template_error(&e, template, name, Vec::new()))?;// Inject vars data as a nested object: {{ vars.env }}, {{ vars["env"] }},- // {{ vars.config.port }}. When branch is present, always inject (even if- // empty map) so {{ vars.key | default(...) }} works in SemiStrict mode.+ // {{ vars.config.port }}. Always inject (even as an empty map) so+ // {{ vars.key | default(...) }} works in SemiStrict mode.// Only look up vars data if the parsed template references the top-level// `vars` object (avoids a git process spawn per expansion while supporting// every MiniJinja access form without false positives from literal text).@@ -1201,12 +1213,18 @@ pub fn expand_template_with();}VarsMode::Resolve => {- if let Some(branch) = vars.get("branch") {- context.insert(- "vars".to_string(),- vars_map_to_value(&repo.vars_entries(branch)),- );- }+ // A detached worktree leaves `branch` unset, and per-branch+ // vars are keyed by branch — so there are none. Insert the+ // empty map rather than nothing, so `{{ vars.key |+ // default(…) }}` still renders under SemiStrict instead of+ // erroring on an undefined `vars` (same reason+ // `list::custom_columns` injects an empty map for a+ // branchless row).+ let entries = vars+ .get("branch")+ .map(|branch| repo.vars_entries(branch))+ .unwrap_or_default();+ context.insert("vars".to_string(), vars_map_to_value(&entries));}}}@@ -2734,17 +2752,20 @@ mod tests {let test = test_repo();let vars = HashMap::new(); // No branch var- // vars should be undefined (no branch to look up)+ // A detached worktree leaves `branch` unset, and per-branch vars are+ // keyed by branch — so there are none. `vars` is still the empty map+ // rather than undefined, so `default` fires on the missing key instead+ // of erroring on the missing object under SemiStrict.assert_eq!(expand_template(- "{{ vars | default('none') }}",+ "{{ vars.env | default('dev') }}",&vars,ShellEscapeMode::Literal,&test.repo,"test").unwrap(),- "none"+ "dev");}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 558cc4b19..8ac919083 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -16,6 +16,7 @@ use crate::commands::hooks::HookAnnouncer;use crate::commands::process::{HookLog, InternalOp, build_remove_command, build_remove_command_staged, spawn_detached,};+use crate::commands::template_vars::TemplateVars;use crate::commands::worktree::hooks::PostRemoveContext;use crate::commands::worktree::{BranchFate, RemovalPlan, RetainedReason, SharedBranchCheckout, SwitchBranchInfo, SwitchResult,@@ -1361,7 +1362,7 @@ fn handle_branch_only_output(fn spawn_hooks_after_remove(repo: &Repository,ctx: &WorktreeRemovalContext<'_>,- removed_branch: &str,+ removed_branch: Option<&str>,announcer: &mut HookAnnouncer<'_>,) -> anyhow::Result<()> {let Ok(config) = UserConfig::load() else {@@ -1385,7 +1386,7 @@ fn spawn_hooks_after_remove(// All hooks use remove_ctx for spawning: log files are named after the removed// branch since both post-remove and post-switch are consequences of that removal.- let remove_ctx = CommandContext::new(repo, &config, Some(removed_branch), ctx.main_path, false);+ let remove_ctx = CommandContext::new(repo, &config, removed_branch, ctx.main_path, false);// `post-remove` is *about* the removed worktree (gone by now); it was// selected and frozen into `hook_plan` at the gate, anchored at the removed@@ -1714,17 +1715,15 @@ fn execute_pre_remove_hooks_if_needed(} else {Some(ctx.worktree_path)};- let target_branch = repo- .worktree_at(ctx.main_path)- .branch()- .ok()- .flatten()- .unwrap_or_default();- let target_path_str = worktrunk::path::to_posix_path(&ctx.main_path.to_string_lossy());- let extra_vars: Vec<(&str, &str)> = vec![- ("target", &target_branch),- ("target_worktree_path", &target_path_str),- ];+ // `TemplateVars` rather than a hand-rolled vec: `as_extra_vars` omits an+ // absent `target` instead of pushing `""`, so a detached primary worktree+ // renders the same here as it does for the `post-remove` half of the same+ // removal (issue #4009).+ let target_branch = repo.worktree_at(ctx.main_path).branch().ok().flatten();+ let vars = TemplateVars::new()+ .with_target_opt(target_branch.as_deref())+ .with_target_worktree_path(ctx.main_path);+ let extra_vars = vars.as_extra_vars();execute_planned_hook(ctx.hook_plan,@@ -1838,8 +1837,9 @@ fn handle_detached_removed_worktree_output()?;}- // Post-remove hooks for detached HEAD use "HEAD" as the branch identifier- spawn_hooks_after_remove(repo, ctx, "HEAD", announcer)?;+ // A detached worktree was on no branch, so `{{ branch }}` stays unset for+ // the post-remove hooks (issue #4009).+ spawn_hooks_after_remove(repo, ctx, None, announcer)?;stderr().flush()?;Ok(BranchFate::NotAttempted)}@@ -1898,7 +1898,7 @@ fn handle_named_removed_worktree_foreground(}print_switch_message_if_changed(ctx.changed_directory, ctx.main_path)?;- spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;+ spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;stderr().flush()?;Ok(fate)}@@ -1946,7 +1946,7 @@ fn handle_named_removed_worktree_background(ctx.background_fallback(),)?;- spawn_hooks_after_remove(repo, ctx, branch_name, announcer)?;+ spawn_hooks_after_remove(repo, ctx, Some(branch_name), announcer)?;stderr().flush()?;Ok(fate)}@@ -2027,7 +2027,7 @@ fn remove_removed_worktree_silently(// Post-remove (and post-switch when the picker cd'd away) hooks — registered// onto the caller's announcer, which `flush`es after this returns.- spawn_hooks_after_remove(repo, ctx, ctx.branch_name.unwrap_or("HEAD"), announcer)?;+ spawn_hooks_after_remove(repo, ctx, ctx.branch_name, announcer)?;Ok(fate)}diff --git a/tests/integration_tests/for_each.rs b/tests/integration_tests/for_each.rsindex 11d42043d..44c247179 100644--- a/tests/integration_tests/for_each.rs+++ b/tests/integration_tests/for_each.rs@@ -67,11 +67,35 @@ fn test_for_each_with_template(repo: TestRepo) {));}+/// A detached worktree leaves `{{ branch }}` unset, so `{% if branch %}` guards+/// it and the loop visits every worktree (issue #4009).#[rstest]fn test_for_each_detached_branch_variable(mut repo: TestRepo) {repo.add_worktree("detached-test");repo.detach_head_in_worktree("detached-test");+ assert_cmd_snapshot!(make_snapshot_cmd(+ &repo,+ "step",+ &[+ "for-each",+ "--",+ "echo",+ "Branch: [{% if branch %}{{ branch }}{% endif %}]",+ ],+ None,+ ));+}++/// The unguarded form is an undefined-variable error in the detached worktree,+/// the same as any other optional variable. Before #4009 it rendered the+/// literal `HEAD` — a string git resolves as a ref, so the command ran against+/// the wrong thing instead of saying so.+#[rstest]+fn test_for_each_detached_branch_variable_unguarded(mut repo: TestRepo) {+ repo.add_worktree("detached-test");+ repo.detach_head_in_worktree("detached-test");+assert_cmd_snapshot!(make_snapshot_cmd(&repo,"step",@@ -500,7 +524,7 @@ fn test_for_each_commit_detached_sibling_matches_per_worktree_head(repo: TestRep"for-each","--","echo",- "{{ branch }} {{ commit }}",+ "[{% if branch %}{{ branch }}{% endif %}] {{ commit }}",]).output().expect("run wt step for-each");@@ -516,15 +540,16 @@ fn test_for_each_commit_detached_sibling_matches_per_worktree_head(repo: TestRepString::from_utf8_lossy(&output.stdout),String::from_utf8_lossy(&output.stderr));- // Detached HEAD surfaces as `{{ branch }} == "HEAD"`. The sibling's commit- // must be its own HEAD, not the running worktree's.- let needle = format!("HEAD {feature_b_sha}");+ // A detached worktree leaves `{{ branch }}` unset, so its row renders the+ // empty guard. The sibling's commit must be its own HEAD, not the running+ // worktree's.+ let needle = format!("[] {feature_b_sha}");assert!(combined.contains(&needle),"expected detached sibling's {{{{ commit }}}} = {feature_b_sha} in output\noutput={combined}",);assert!(- !combined.contains(&format!("HEAD {main_sha}")),+ !combined.contains(&format!("[] {main_sha}")),"detached sibling's {{{{ commit }}}} must not resolve to main's SHA {main_sha}\noutput={combined}",);}diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex fa4c4515f..bd1b8c0ea 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -2744,9 +2744,11 @@ fn test_pre_remove_hook_branch_expansion_detached_head(mut repo: TestRepo) {let branch_file = repo.root_path().join("branch-expansion.txt");let branch_path = branch_file.to_slash_lossy();- // Create project config with hook that writes {{ branch }} to file+ // Create project config with a hook that writes {{ branch }} to file,+ // guarded the way the hook docs prescribe for every optional variable —+ // a detached worktree is on no branch, so `branch` is unset there.repo.write_project_config(&format!(- r#"pre-remove = "echo 'branch={{{{ branch }}}}' > {branch_path}""#,+ r#"pre-remove = "echo 'branch={{% if branch %}}{{{{ branch }}}}{{% endif %}}' > {branch_path}""#,));repo.commit("Add config");@@ -2754,7 +2756,7 @@ fn test_pre_remove_hook_branch_expansion_detached_head(mut repo: TestRepo) {repo.write_test_config(r#"worktree-path = "../{{ repo }}.{{ branch }}""#);repo.write_test_approvals(&format!(r#"[projects."../origin"]-approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]+approved-commands = ["echo 'branch={{% if branch %}}{{{{ branch }}}}{{% endif %}}' > {branch_path}"]"#,));@@ -2777,13 +2779,15 @@ approved-commands = ["echo 'branch={{{{ branch }}}}' > {branch_path}"]String::from_utf8_lossy(&output.stderr));- // Verify {{ branch }} expanded to "HEAD" (fallback for detached HEAD state)+ // Verify {{ branch }} is unset — not the literal "HEAD", which git would+ // resolve as a ref and which every guard written around `branch` passed+ // (issue #4009).let content =std::fs::read_to_string(&branch_file).expect("Hook should have created the branch file");assert_eq!(content.trim(),- "branch=HEAD",- "{{ branch }} should expand to 'HEAD' for detached HEAD worktrees"+ "branch=",+ "{{ branch }} should be unset for detached HEAD worktrees");}diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 71a2e7f17..a291df7b2 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -8,6 +8,7 @@ use crate::common::{// or it reads as unused on Windows under `-D warnings`.#[cfg(unix)]use crate::common::SLEEP_FOR_ABSENCE_CHECK;+use ansi_str::AnsiStr;use insta_cmd::assert_cmd_snapshot;use rstest::rstest;use std::io::Write;@@ -2520,3 +2521,91 @@ record-git-env = "printf '[%s][%s]' \"$GIT_DIR\" \"$GIT_WORK_TREE\" > env_seen.t"alias should see wt's inherited git-discovery vars unchanged");}++/// A detached worktree leaves `{{ branch }}` undefined, so `{% if branch %}`+/// guards it the way the hook docs prescribe for every optional variable.+///+/// Regression test for #4009: `branch` used to fall back to the literal+/// `HEAD`, which is a non-empty string git happily resolves as a ref — so+/// every guard written around `branch` passed and the alias ran against the+/// wrong thing (`git push origin --delete HEAD`). It also disagreed with+/// `wt list --json`, which reports `branch: null` for the same worktree.+#[rstest]+fn test_alias_branch_unset_in_detached_worktree(mut repo: TestRepo) {+ repo.add_worktree("detached-test");+ repo.detach_head_in_worktree("detached-test");+ let detached = repo.worktree_path("detached-test").to_path_buf();++ repo.write_test_config(+ r#"+[aliases]+probe = "echo [{% if branch %}{{ branch }}{% endif %}]"+"#,+ );++ let output = repo+ .wt_command()+ .args(["-y", "probe"])+ .current_dir(&detached)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "alias failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );++ let combined = format!(+ "{}{}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ combined.contains("[]"),+ "`{{% if branch %}}` should not fire in a detached worktree, got: {combined}"+ );+ assert!(+ !combined.contains("[HEAD]"),+ "`branch` must not fall back to the literal `HEAD`, got: {combined}"+ );+}++/// `branch` is cheap enough that `build_hook_context` computes it whatever the+/// scope, so its absence in a detached worktree is `(unset)` — a fact about the+/// worktree — even in an alias body that never names it. `(unused)` is reserved+/// for a var the scope gate actually skipped computing.+#[rstest]+fn test_verbose_variables_table_marks_detached_branch_unset(mut repo: TestRepo) {+ repo.add_worktree("detached-vars");+ repo.detach_head_in_worktree("detached-vars");+ let detached = repo.worktree_path("detached-vars").to_path_buf();++ // The body references neither `branch` nor `upstream`, so the scope gate+ // skips only the latter — an expensive var behind a git-config read.+ repo.write_test_config(+ r#"+[aliases]+probe = "echo hello"+"#,+ );++ let output = repo+ .wt_command()+ .args(["-v", "-y", "probe"])+ .current_dir(&detached)+ .output()+ .unwrap();+ let raw_stderr = String::from_utf8_lossy(&output.stderr);+ let stderr = raw_stderr.ansi_strip();++ let branch_row = stderr+ .lines()+ .map(str::trim)+ .find(|line| line.starts_with("branch "))+ .unwrap_or_else(|| panic!("no `branch` row in the variables table:\n{stderr}"));+ assert!(+ branch_row.ends_with("= (unset)"),+ "detached `branch` should read `(unset)`, not `(unused)`, got: {branch_row}"+ );+}diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rsindex deffdb977..dc41395aa 100644--- a/tests/integration_tests/user_hooks.rs+++ b/tests/integration_tests/user_hooks.rs@@ -843,6 +843,96 @@ capture = "echo 'branch={{ branch }} worktree_path={{ worktree_path }} worktree_);}+/// A detached worktree is on no branch, so `post-remove` hooks see `branch`+/// unset rather than the literal `HEAD` — the string git resolves as a ref,+/// which made `git push origin --delete {{ branch }}` target the wrong thing+/// (issue #4009). `post-remove` overrides `branch` through+/// `PostRemoveContext::extra_vars`, which is applied after the base context, so+/// it needs the same `None` the base context has.+#[rstest]+fn test_user_post_remove_branch_unset_in_detached_worktree(mut repo: TestRepo) {+ repo.add_worktree("feature");+ repo.detach_head_in_worktree("feature");+ let feature_wt_path = repo.worktree_path("feature");++ // Guarded the way the hook docs prescribe for every optional variable.+ repo.write_test_config(+ r#"[post-remove]+capture = "echo 'branch=[{% if branch %}{{ branch }}{% endif %}]' > ../postremove_detached.txt"+"#,+ );++ repo.wt_command()+ .args([+ "remove",+ feature_wt_path.to_str().unwrap(),+ "--force",+ "--yes",+ ])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let vars_file = repo+ .root_path()+ .parent()+ .unwrap()+ .join("postremove_detached.txt");+ crate::common::wait_for_file_content(&vars_file);++ let content = std::fs::read_to_string(&vars_file).unwrap();+ assert_eq!(+ content.trim(),+ "branch=[]",+ "post-remove `branch` should be unset for a detached worktree, got: {content}"+ );+}++/// `target` names the branch the user lands on after removal — the primary+/// worktree's — so a detached primary leaves it unset for the same reason+/// `branch` is unset above. Both halves of one removal have to agree: the+/// `pre-remove` site builds its own extra vars, so it drifted to an empty+/// string while `post-remove` omitted the key. `is defined` is what separates+/// the two states — an empty string renders identically under+/// `{% if target %}`, but it makes `wt -v` print `target = ` where the var was+/// never supplied.+#[rstest]+fn test_user_remove_hooks_target_unset_with_detached_primary_worktree(mut repo: TestRepo) {+ repo.add_worktree("feature");+ repo.detach_head();++ repo.write_test_config(+ r#"[pre-remove]+capture = "echo 'target=[{% if target is defined %}defined:{{ target }}{% else %}unset{% endif %}]' > ../preremove_detached_target.txt"++[post-remove]+capture = "echo 'target=[{% if target is defined %}defined:{{ target }}{% else %}unset{% endif %}]' > ../postremove_detached_target.txt"+"#,+ );++ repo.wt_command()+ .args(["remove", "feature", "--force", "--yes"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ let parent = repo.root_path().parent().unwrap().to_path_buf();+ for (hook, file) in [+ ("pre-remove", "preremove_detached_target.txt"),+ ("post-remove", "postremove_detached_target.txt"),+ ] {+ let vars_file = parent.join(file);+ crate::common::wait_for_file_content(&vars_file);++ let content = std::fs::read_to_string(&vars_file).unwrap();+ assert_eq!(+ content.trim(),+ "target=[unset]",+ "{hook} `target` should be unset when the primary worktree is detached, got: {content}"+ );+ }+}+#[rstest]fn test_user_post_remove_skipped_with_no_hooks(mut repo: TestRepo) {// Create a worktree to remove@@ -3071,6 +3161,45 @@ check = "echo 'USER_PRE_SWITCH_RAN' > pre_switch_marker.txt");}+/// Switching out of a detached worktree leaves `base` unset rather than empty:+/// `base` is the source branch, and there isn't one. Only `is defined`+/// separates that from the `unwrap_or_default()` this replaced — both render+/// as nothing under `{% if base %}` — so this pins the distinction the+/// `(unset)` label in `wt -v` depends on (issue #4009).+#[rstest]+fn test_user_pre_switch_base_unset_in_detached_worktree(mut repo: TestRepo) {+ repo.add_worktree("feature");+ repo.add_worktree("detached-src");+ repo.detach_head_in_worktree("detached-src");+ let src_path = repo.worktree_path("detached-src");++ repo.write_test_config(+ r#"[pre-switch]+capture = "echo 'base=[{% if base is defined %}defined:{{ base }}{% else %}unset{% endif %}]' > ../preswitch_detached.txt"+"#,+ );++ repo.wt_command()+ .args(["switch", "feature"])+ .current_dir(src_path)+ .output()+ .unwrap();++ let vars_file = repo+ .root_path()+ .parent()+ .unwrap()+ .join("preswitch_detached.txt");+ crate::common::wait_for_file_content(&vars_file);++ let content = std::fs::read_to_string(&vars_file).unwrap();+ assert_eq!(+ content.trim(),+ "base=[unset]",+ "pre-switch `base` should be unset when switching out of a detached worktree, got: {content}"+ );+}+/// Test that a failing pre-switch hook blocks the switch (including --create)#[rstest]fn test_user_pre_switch_failure_blocks_switch(repo: TestRepo) {@@ -3138,6 +3267,49 @@ check = "echo 'MANUAL_PRE_SWITCH' > pre_switch_marker.txt");}+/// A manual `wt hook <type>` in a detached worktree leaves `branch` unset, and+/// the `base` / `target` names it derives from the current branch follow —+/// rather than naming the literal `HEAD`, which git resolves as a ref (issue+/// #4009). The directional *path* vars still apply: the worktree exists+/// whether or not it is on a branch, so `{{ base_worktree_path }}` renders+/// unguarded here.+#[rstest]+fn test_manual_hook_branch_vars_unset_in_detached_worktree(mut repo: TestRepo) {+ repo.add_worktree("detached-test");+ repo.detach_head_in_worktree("detached-test");+ let detached = repo.worktree_path("detached-test").to_path_buf();++ repo.write_test_config(+ r#"[pre-switch]+record = "echo 'branch=[{% if branch %}{{ branch }}{% endif %}] base=[{% if base %}{{ base }}{% endif %}] target=[{% if target %}{{ target }}{% endif %}] base_worktree_path=[{{ base_worktree_path }}]' > vars.txt"+"#,+ );++ let output = repo+ .wt_command()+ .args(["hook", "pre-switch"])+ .current_dir(&detached)+ .output()+ .unwrap();+ assert!(+ output.status.success(),+ "manual hook failed:\nstdout: {}\nstderr: {}",+ String::from_utf8_lossy(&output.stdout),+ String::from_utf8_lossy(&output.stderr)+ );++ let recorded = std::fs::read_to_string(detached.join("vars.txt"))+ .expect("hook should have recorded its variables");+ assert!(+ recorded.starts_with("branch=[] base=[] target=[] base_worktree_path=["),+ "branch, base and target must be unset in a detached worktree, got: {recorded}"+ );+ assert!(+ !recorded.contains("base_worktree_path=[]"),+ "base_worktree_path should still name the detached worktree, got: {recorded}"+ );+}+/// Test that `{{ branch }}` in pre-switch hooks is the destination branch argument, not the source.#[rstest]fn test_user_pre_switch_branch_var_is_destination(mut repo: TestRepo) {diff --git a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snapindex e43c0fb1e..b10e0c3d0 100644--- a/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable.snap@@ -7,7 +7,7 @@ info:- for-each- "--"- echo- - "Branch: {{ branch }}"+ - "Branch: [{% if branch %}{{ branch }}{% endif %}]"env:APPDATA: "[TEST_CONFIG_HOME]"CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"@@ -63,14 +63,14 @@ exit_code: 0----- stderr -----[36m◎[39m [36mRunning in [1mmain[22m...[39m-[0mBranch: main+[0mBranch: [main][36m◎[39m [36mRunning in [1mrepo.detached-test[22m (detached)...[39m-[0mBranch: HEAD+[0mBranch: [][36m◎[39m [36mRunning in [1mfeature-a[22m...[39m-[0mBranch: feature-a+[0mBranch: [feature-a][36m◎[39m [36mRunning in [1mfeature-b[22m...[39m-[0mBranch: feature-b+[0mBranch: [feature-b][36m◎[39m [36mRunning in [1mfeature-c[22m...[39m-[0mBranch: feature-c+[0mBranch: [feature-c][32m✓[39m [32mCompleted in 5 worktrees[39mdiff --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.snapnew file mode 100644index 000000000..a1932eaaa--- /dev/null+++ b/tests/snapshots/integration__integration_tests__for_each__for_each_detached_branch_variable_unguarded.snap@@ -0,0 +1,70 @@+---+source: tests/integration_tests/for_each.rs+info:+ program: wt+ args:+ - step+ - for-each+ - "--"+ - echo+ - "Branch: {{ branch }}"+ 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 -----+[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+[107m [0m Branch: {{ branch }}+[2m↳[22m [2mAvailable variables: [4mcommit[24m, [4mcwd[24m, [4mdefault_branch[24m, [4mmain_worktree[24m, [4mmain_worktree_path[24m, [4mprimary_worktree_path[24m, [4mremote[24m, [4mremote_url[24m, [4mrepo[24m, [4mrepo_path[24m, [4mrepo_root[24m, [4mshort_commit[24m, [4mworktree[24m, [4mworktree_name[24m, [4mworktree_path[24m[22m