Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
perf(alias): scope template-context build to vars the body references (#2556)
Maximilian Roos2a8db4160e36
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex 91a4d0ad3..b5a78773c 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -44,7 +44,7 @@ use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::{ALIAS_ARGS_KEY, CommandConfig, HookStep, LoadedConfigs, ProjectConfig, UserConfig,- format_alias_variables, referenced_vars_for_config,+ alias_context_filter, format_alias_variables, referenced_vars_for_config,};use worktrunk::git::Repository;use worktrunk::styling::{@@ -441,7 +441,7 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::R} = LoadedConfigs::load(&repo)?;let aliases = {let _span = Span::new("load_aliases");- load_aliases(Some(&repo), &user_config, project_config.as_ref())+ load_aliases(Some(&repo), user_config, project_config)};let Some(entry) = aliases.get(&name) else {return Ok(None);@@ -463,7 +463,16 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Rlet entry = aliases.get(&opts.name).expect("entry verified above and `opts.name` matches the dispatched name");- run_alias(opts, warnings, repo, user_config, entry, global_yes).map(Some)+ run_alias(+ opts,+ warnings,+ &repo,+ user_config,+ entry,+ referenced,+ global_yes,+ )+ .map(Some)}/// Run a configured alias from `wt step <name>`. Errors with a clap-style@@ -487,7 +496,7 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {user: user_config,project: project_config,} = LoadedConfigs::load(&repo)?;- let aliases = load_aliases(Some(&repo), &user_config, project_config.as_ref());+ let aliases = load_aliases(Some(&repo), user_config, project_config);let Some(name) = args.first().cloned() else {bail!("Missing alias name");};@@ -513,7 +522,15 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {let entry = aliases.get(&opts.name).expect("entry verified above and `opts.name` matches the dispatched name");- run_alias(opts, warnings, repo, user_config, entry, global_yes)+ run_alias(+ opts,+ warnings,+ &repo,+ user_config,+ entry,+ referenced,+ global_yes,+ )}/// Return alias names for use as suggestions when a top-level subcommand is@@ -544,9 +561,10 @@ pub fn alias_names_for_suggestions() -> Vec<String> {fn run_alias(opts: AliasOptions,warnings: Vec<String>,- repo: Repository,- user_config: UserConfig,+ repo: &Repository,+ user_config: &UserConfig,entry: &AliasEntry,+ referenced: BTreeSet<String>,global_yes: bool,) -> anyhow::Result<()> {let _span = Span::new(format!("run_alias:{}", opts.name));@@ -571,16 +589,19 @@ fn run_alias(let wt = repo.current_worktree();let wt_path = wt.root().context("Failed to get worktree root")?;let branch = wt.branch().ok().flatten();- let ctx = CommandContext::new(&repo, &user_config, branch.as_deref(), &wt_path, false);+ let ctx = CommandContext::new(repo, user_config, branch.as_deref(), &wt_path, false);let extra_refs: Vec<(&str, &str)> = opts.vars.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();+ // Filter to vars the body references — skips git lookups (commit, upstream,+ // default-branch on cold cache) that would never be substituted.+ let referenced = alias_context_filter(referenced);let mut context_map = {let _span = Span::new("build_hook_context");- build_hook_context(&ctx, &extra_refs)?+ build_hook_context(&ctx, &extra_refs, Some(&referenced))?};// Forward positional CLI args to templates as `{{ args }}`. Encoded as a// JSON list so it flows through the stable `HashMap<String, String>`@@ -595,7 +616,7 @@ fn run_alias(.expect("HashMap<String, String> serialization should never fail");if verbosity() >= 1 {- let vars = format_alias_variables(&context_map);+ let vars = format_alias_variables(&context_map, Some(&referenced));eprintln!("{}", info_message("template variables:"));eprintln!("{}", format_with_gutter(&vars, None));}@@ -639,12 +660,7 @@ fn run_alias(sourced_steps_to_foreground(sourced_steps, &PipelineKind::Alias { name: alias_name })};- execute_pipeline_foreground(- &foreground_steps,- &repo,- &wt_path,- FailureStrategy::FailFast,- )+ execute_pipeline_foreground(&foreground_steps, repo, &wt_path, FailureStrategy::FailFast)}/// Build a PreparedCommand for an alias, deferring template expansion to execution time.diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 50d498413..af1592db2 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -1,4 +1,4 @@-use std::collections::HashMap;+use std::collections::{BTreeSet, HashMap};use std::path::{Path, PathBuf};use anyhow::{Context, Result};@@ -196,9 +196,20 @@ impl<'a> CommandContext<'a> {////// The resulting HashMap is passed to hook commands as JSON on stdin,/// and used directly for template variable expansion.+///+/// `referenced`, when `Some`, restricts the map to keys named in the set —+/// vars the body doesn't reference are not computed. Aliases pass their+/// `referenced_vars_for_config` set (extended via `alias_context_filter`)+/// so unused git lookups (`var_commit` rev-parse, `var_default_branch` cold+/// detection, `branch().upstream()`) are skipped, and the verbose+/// `template variables:` table only lists vars the body actually references.+/// Hooks pass `None` so every standard var stays available — the child+/// receives the full context as JSON on stdin and may consume keys that+/// don't appear in the inline `{{ }}` template (e.g. via `jq`).pub fn build_hook_context(ctx: &CommandContext<'_>,extra_vars: &[(&str, &str)],+ referenced: Option<&BTreeSet<String>>,) -> Result<HashMap<String, String>> {let repo_root = ctx.repo.repo_path()?;let repo_name = repo_root@@ -217,15 +228,18 @@ pub fn build_hook_context(let repo_path = to_posix_path(&repo_root.to_string_lossy());+ let want = |key: &str| referenced.is_none_or(|r| r.contains(key));++ // Cheap vars (already in scope, no I/O) are populated unconditionally —+ // skipping them saves no work and would just turn the verbose table's+ // `(unused)` label into noise. Only the expensive blocks below+ // (subprocesses, git config / remote lookups) honor `want`.let mut map = HashMap::new();map.insert("repo".into(), repo_name.into());map.insert("branch".into(), ctx.branch_or_head().into());map.insert("worktree_name".into(), worktree_name.into());-- // Canonical path variablesmap.insert("repo_path".into(), repo_path.clone());map.insert("worktree_path".into(), worktree.clone());-// Deprecated aliases (kept for backward compatibility)map.insert("main_worktree".into(), repo_name.into());map.insert("repo_root".into(), repo_path);@@ -236,7 +250,7 @@ pub fn build_hook_context(}// Default branch- {+ if want("default_branch") {let _span = Span::new("var_default_branch");if let Some(default_branch) = ctx.repo.default_branch() {map.insert("default_branch".into(), default_branch);@@ -244,13 +258,17 @@ pub fn build_hook_context(}// Primary worktree path (where established files live)- {+ if want("primary_worktree_path") || want("main_worktree_path") {let _span = Span::new("var_primary_worktree");if let Ok(Some(path)) = ctx.repo.primary_worktree() {let path_str = to_posix_path(&path.to_string_lossy());- map.insert("primary_worktree_path".into(), path_str.clone());+ if want("primary_worktree_path") {+ map.insert("primary_worktree_path".into(), path_str.clone());+ }// Deprecated alias- map.insert("main_worktree_path".into(), path_str);+ if want("main_worktree_path") {+ map.insert("main_worktree_path".into(), path_str);+ }}}@@ -262,7 +280,7 @@ pub fn build_hook_context(// iterates over sibling worktrees, and a sibling on detached HEAD has a// different HEAD than the worktree `wt` runs in. Branched contexts go// through `rev-parse <branch>`, which is repo-wide.- {+ if want("commit") || want("short_commit") {let _span = Span::new("var_commit");let commit = match ctx.branch {Some(branch) => ctx@@ -278,22 +296,29 @@ pub fn build_hook_context(.flatten(),};if let Some(commit) = commit {- if commit.len() >= 7 {+ if want("short_commit") && commit.len() >= 7 {map.insert("short_commit".into(), commit[..7].into());}- map.insert("commit".into(), commit);+ if want("commit") {+ map.insert("commit".into(), commit);+ }}}- {+ if want("remote") || want("remote_url") || want("upstream") {let _span = Span::new("var_remote");if let Ok(remote) = ctx.repo.primary_remote() {- map.insert("remote".into(), remote.to_string());+ if want("remote") {+ map.insert("remote".into(), remote.to_string());+ }// Add remote URL for conditional hook execution (e.g., GitLab vs GitHub)- if let Some(url) = ctx.repo.remote_url(&remote) {+ if want("remote_url")+ && let Some(url) = ctx.repo.remote_url(&remote)+ {map.insert("remote_url".into(), url);}- if let Some(branch) = ctx.branch+ if want("upstream")+ && let Some(branch) = ctx.branch&& let Ok(Some(upstream)) = ctx.repo.branch(branch).upstream(){map.insert("upstream".into(), upstream);@@ -308,7 +333,9 @@ pub fn build_hook_context(to_posix_path(&ctx.worktree_path.to_string_lossy()),);- // Add extra vars (e.g., target branch for merge, base for switch)+ // Caller-set bindings (e.g., merge target, switch base, alias args).+ // Aliases pre-filter via `AliasOptions::parse`, hooks pass everything;+ // either way the value is already computed, so insert unconditionally.for (k, v) in extra_vars {map.insert((*k).into(), (*v).into());}@@ -646,7 +673,7 @@ fn expand_commands(source: HookSource,lazy_enabled: bool,) -> anyhow::Result<Vec<(Command, String, Option<String>)>> {- let mut base_context = build_hook_context(ctx, extra_vars)?;+ let mut base_context = build_hook_context(ctx, extra_vars, None)?;// hook_type is always available as a template variable and in JSON contextbase_context.insert("hook_type".into(), hook_type.to_string());diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 6a17aba42..892c686cf 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -47,13 +47,13 @@ pub fn handle_alias_show(name: String) -> anyhow::Result<()> {user: user_config,project: project_config,} = LoadedConfigs::load(&repo)?;- let entries = entries_for_name(&repo, &user_config, project_config.as_ref(), &name);+ let entries = entries_for_name(&repo, user_config, project_config, &name);if entries.is_empty() {return Err(unknown_alias_error(&repo,- &user_config,- project_config.as_ref(),+ user_config,+ project_config,&name,"show",));@@ -100,13 +100,13 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(user: user_config,project: project_config,} = LoadedConfigs::load(&repo)?;- let entries = entries_for_name(&repo, &user_config, project_config.as_ref(), &name);+ let entries = entries_for_name(&repo, user_config, project_config, &name);if entries.is_empty() {return Err(unknown_alias_error(&repo,- &user_config,- project_config.as_ref(),+ user_config,+ project_config,&name,"dry-run",));@@ -132,13 +132,13 @@ pub fn handle_alias_dry_run(name: String, args: Vec<String>) -> anyhow::Result<(let wt = repo.current_worktree();let wt_path = wt.root().context("Failed to get worktree root")?;let branch = wt.branch().ok().flatten();- let ctx = CommandContext::new(&repo, &user_config, branch.as_deref(), &wt_path, false);+ let ctx = CommandContext::new(&repo, user_config, branch.as_deref(), &wt_path, false);let extra_refs: Vec<(&str, &str)> = opts.vars.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();- let mut context_map = build_hook_context(&ctx, &extra_refs)?;+ let mut context_map = build_hook_context(&ctx, &extra_refs, None)?;context_map.insert(ALIAS_ARGS_KEY.to_string(),serde_json::to_string(&opts.positional_args)diff --git a/src/commands/context.rs b/src/commands/context.rsindex 1b6dce616..93177d2d0 100644--- a/src/commands/context.rs+++ b/src/commands/context.rs@@ -76,13 +76,12 @@ impl CommandEnv {let branch = current_wt.branch().context("Failed to determine current branch")?;- // `wt hook`-style callers always read project config downstream- // (`repo.load_project_config()`); use the bundle loader to warm- // both in parallel. `CommandEnv` only carries `UserConfig` —- // downstream picks up project from the cache.+ // Warm both configs in parallel; downstream hook code reads project+ // from the cache. Clone user out — `CommandEnv` owns its config.let config = LoadedConfigs::load(&repo).context("Failed to load config")?- .user;+ .user+ .clone();Ok(Self {repo,diff --git a/src/commands/eval.rs b/src/commands/eval.rsindex bc4a6f809..ecfc39957 100644--- a/src/commands/eval.rs+++ b/src/commands/eval.rs@@ -26,7 +26,7 @@ pub fn step_eval(template: &str, dry_run: bool) -> anyhow::Result<()> {let worktree_path = wt.root()?;let ctx = CommandContext::new(&repo, &config, branch.as_deref(), &worktree_path, false);- let context_map = build_hook_context(&ctx, &[])?;+ let context_map = build_hook_context(&ctx, &[], None)?;let vars: HashMap<&str, &str> = context_map.iter()diff --git a/src/commands/for_each.rs b/src/commands/for_each.rsindex 35a80e215..422ea1760 100644--- a/src/commands/for_each.rs+++ b/src/commands/for_each.rs@@ -75,7 +75,7 @@ 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"let ctx = CommandContext::new(&repo, &config, wt.branch.as_deref(), &wt.path, false);- let context_map = build_hook_context(&ctx, &[])?;+ let context_map = build_hook_context(&ctx, &[], None)?;// Expand each argv element through the template engine without// shell-escaping — values are interpolated directly into the argvdiff --git a/src/commands/handle_switch.rs b/src/commands/handle_switch.rsindex 4d952899c..aff123a6a 100644--- a/src/commands/handle_switch.rs+++ b/src/commands/handle_switch.rs@@ -382,7 +382,7 @@ pub fn handle_switch(result.path(),yes,);- let template_vars = build_hook_context(&ctx, &extra_vars)?;+ let template_vars = build_hook_context(&ctx, &extra_vars, None)?;let vars: HashMap<&str, &str> = template_vars.iter().map(|(k, v)| (k.as_str(), v.as_str()))diff --git a/src/commands/hook_commands.rs b/src/commands/hook_commands.rsindex fba0835f3..17f009362 100644--- a/src/commands/hook_commands.rs+++ b/src/commands/hook_commands.rs@@ -406,14 +406,14 @@ pub fn handle_hook_show(hook_type_filter: Option<&str>, expanded: bool) -> anyholet mut output = String::new();// Render user hooks- render_user_hooks(&mut output, &config, filter, ctx.as_ref())?;+ render_user_hooks(&mut output, config, filter, ctx.as_ref())?;output.push('\n');// Render project hooksrender_project_hooks(&mut output,&repo,- project_config.as_ref(),+ project_config,&approvals,project_id.as_deref(),filter,@@ -593,7 +593,7 @@ fn expand_command_template(let default_branch = ctx.repo.default_branch();let template_vars = build_manual_hook_template_vars(ctx, hook_type, default_branch.as_deref());let extra_vars = template_vars.as_extra_vars();- let mut template_ctx = build_hook_context(ctx, &extra_vars)?;+ let mut template_ctx = build_hook_context(ctx, &extra_vars, None)?;template_ctx.insert("hook_type".into(), hook_type.to_string());if let Some(name) = hook_name {template_ctx.insert("hook_name".into(), name.into());diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 4b7a5098e..0faa3ba24 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -727,14 +727,13 @@ pub fn handle_picker(} else {Repository::current().context("Failed to switch worktree")?};- // Load config, offering bare repo worktree-path fix if needed.- // Reload from disk so mutations are picked up by plan_switch.- // Warm project_config alongside — `run_pre_switch_hooks` /- // `plan_switch` consume it via `repo.load_project_config()` (cache- // hit). User config is what we read here; project sits in the cache.+ // Warm both configs in parallel; project sits in the cache for+ // downstream `run_pre_switch_hooks` / `plan_switch`. Clone user out+ // so `offer_bare_repo_worktree_path_fix` can mutate locally.let mut config = worktrunk::config::LoadedConfigs::load(&repo).context("Failed to load config")?- .user;+ .user+ .clone();offer_bare_repo_worktree_path_fix(&repo, &mut config)?;// Run pre-switch hooks before branch resolution or worktree creation.diff --git a/src/config/expansion.rs b/src/config/expansion.rsindex 05f5e7aa0..cbabdd44e 100644--- a/src/config/expansion.rs+++ b/src/config/expansion.rs@@ -196,19 +196,30 @@ pub fn vars_available_in(scope: ValidationScope) -> Vec<&'static str> {/// `(unset)`, surfacing operation-specific gaps (e.g., `target_worktree_path`/// during `wt switch -`, `upstream` when the branch doesn't track a remote).///+/// 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.-fn format_variables_table(vars: &[&'static str], ctx: &HashMap<String, String>) -> String {+fn format_variables_table(+ vars: &[&'static str],+ ctx: &HashMap<String, String>,+ referenced: Option<&BTreeSet<String>>,+) -> String {let max_name = vars.iter().map(|v| v.len()).max().unwrap_or(0);vars.iter()- .map(|var| {- let value = match ctx.get(*var) {- Some(v) => v.as_str(),- None => "(unset)",- };- format!("{var:<max_name$} = {value}")+ .map(|var| match ctx.get(*var) {+ Some(value) => format!("{var:<max_name$} = {value}"),+ None if referenced.is_some_and(|r| !r.contains(*var)) => {+ cformat!("<dim>{var:<max_name$} = (unused)</>")+ }+ None => format!("{var:<max_name$} = (unset)"),}).collect::<Vec<_>>().join("\n")@@ -229,7 +240,7 @@ pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>).chain(HOOK_INFRASTRUCTURE_VARS).copied().collect();- format_variables_table(&vars, ctx)+ format_variables_table(&vars, ctx, None)}/// Format the resolved template variables for an alias invocation.@@ -241,7 +252,15 @@ pub fn format_hook_variables(hook_type: HookType, ctx: &HashMap<String, String>)/// `args` is stored as a JSON-encoded `Vec<String>` per the [`ALIAS_ARGS_KEY`]/// contract; the table displays it space-joined and shell-escaped so it/// matches what `{{ args }}` substitutes in templates.-pub fn format_alias_variables(ctx: &HashMap<String, String>) -> String {+///+/// `referenced` (the set of vars the body actually substitutes) controls+/// the dim `(unused)` marker for vars the operation skipped computing —+/// the reader sees what's reachable without paying for values the body+/// won't substitute.+pub fn format_alias_variables(+ ctx: &HashMap<String, String>,+ referenced: Option<&BTreeSet<String>>,+) -> String {let vars: Vec<&'static str> = ACTIVE_VARS.iter().copied()@@ -255,7 +274,29 @@ pub fn format_alias_variables(ctx: &HashMap<String, String>) -> String {.expect("ALIAS_ARGS_KEY is always serialized from a Vec<String>");display_ctx.insert(ALIAS_ARGS_KEY.into(), shell_join(&args));}- format_variables_table(&vars, &display_ctx)+ format_variables_table(&vars, &display_ctx, referenced)+}++/// Extend `referenced` with the implicit context-map keys an alias dispatch+/// needs:+///+/// - [`ALIAS_ARGS_KEY`] (`args`) — always present in alias scope (`run_alias`+/// inserts it after `build_hook_context`), so include it so the verbose+/// table renders the row.+/// - `branch` when the body references `vars` — `expand_template` reads+/// `branch` out of the context map to look up `{{ vars.X }}` from git+/// config at execution time. Bare `{{ vars }}`, `{{ vars.X }}`, and+/// `{{ vars["X"] }}` all surface `vars` in `undeclared_variables`.+///+/// New implicit dependencies (template-level reads from the context map that+/// `undeclared_variables` doesn't see) belong here, not at each call site.+pub fn alias_context_filter(mut referenced: BTreeSet<String>) -> BTreeSet<String> {+ let needs_branch = referenced.contains("vars");+ referenced.insert(ALIAS_ARGS_KEY.to_string());+ if needs_branch {+ referenced.insert("branch".to_string());+ }+ referenced}/// Positional CLI args forwarded from `wt <alias> a b c` into the alias's@@ -2051,7 +2092,7 @@ mod tests {// decodes and shell-renders it to match `{{ args }}` substitution.ctx.insert(ALIAS_ARGS_KEY.into(), r#"["a","b c"]"#.into());- let out = format_alias_variables(&ctx);+ let out = format_alias_variables(&ctx, None);assert!(out.contains("args = a 'b c'"),"got: {out}"@@ -2066,7 +2107,7 @@ mod tests {fn test_format_alias_variables_args_empty() {let mut ctx: HashMap<String, String> = HashMap::new();ctx.insert(ALIAS_ARGS_KEY.into(), "[]".into());- let out = format_alias_variables(&ctx);+ let out = format_alias_variables(&ctx, None);// Empty args render as an empty string after the `=` — distinct from// `(unset)`, which means the key was absent entirely. `args` sits last// in alias ordering, so the output ends with it.diff --git a/src/config/loaded.rs b/src/config/loaded.rsindex 633564909..831dce972 100644--- a/src/config/loaded.rs+++ b/src/config/loaded.rs@@ -1,22 +1,19 @@//! Bundle type for loading user and project config together.//!-//! [`LoadedConfigs::load`] runs the user-config disk load, the project-config-//! disk load, and a `project_identifier` cache warm-up on three scoped-//! threads. All three share `Repository`'s `Arc<RepoCache>` — clones are-//! cheap, and the `OnceCell`/`DashMap` entries each thread populates are-//! visible to every other clone (and to subsequent cache reads).+//! [`LoadedConfigs::load`] warms the user-config and project-config caches in+//! parallel on scoped threads, then returns borrows into the per-`Repository`+//! cache. Both fields go through the same caching path, so subsequent+//! `Repository::user_config` / `Repository::project_config` calls are pure+//! cache hits — no second disk read, no asymmetry.//!//! ## When to use//!//! Call [`LoadedConfigs::load`] from command handlers that consume both//! configs — alias dispatch, `wt config alias show`/`dry-run`,-//! `wt hook show`, hook execution, and any path whose downstream code calls-//! `Repository::load_project_config`.-//!-//! Sites that only consume `UserConfig` should call [`UserConfig::load`]-//! directly. The bundle loader reads `.config/wt.toml` and would emit-//! deprecation/unknown-field warnings from project config in commands that-//! never use it.+//! `wt hook show`, hook execution, picker post-switch. Sites that only+//! consume `UserConfig` (e.g. `wt step eval`, `for-each`, `prune`,+//! `relocate`) call [`UserConfig::load`] directly so they don't trigger+//! `.config/wt.toml` reads or project-config deprecation warnings.//!//! ## Why not return a merged config?//!@@ -24,7 +21,8 @@//! project config requires command approval. Downstream merges//! (`load_aliases`, hook resolution) keep the source distinction so//! per-source policy can be applied. A flattened merged struct would erase-//! that.+//! that. Methods that walk both sources with the right precedence belong on+//! `LoadedConfigs` itself as the bundle grows.//!//! ## Warning ordering//!@@ -41,48 +39,48 @@ use crate::trace::Span;use super::{ProjectConfig, UserConfig};-/// User and project configs loaded together.+/// User and project configs borrowed together from `repo`'s cache.///-/// `project` is `None` when the repo has no `.config/wt.toml`.-pub struct LoadedConfigs {- pub user: UserConfig,- pub project: Option<ProjectConfig>,+/// `project` is `None` when the repo has no `.config/wt.toml`. Lifetime+/// `'r` is tied to the `Repository` whose cache the references point into.+pub struct LoadedConfigs<'r> {+ pub user: &'r UserConfig,+ pub project: Option<&'r ProjectConfig>,}-impl LoadedConfigs {- /// Load user config and project config in parallel; warm- /// `project_identifier` alongside.+impl<'r> LoadedConfigs<'r> {+ /// Warm the user- and project-config caches in parallel; warm+ /// `project_identifier` alongside the project load.////// On a cold cache the wall-clock cost is the longest pole rather than- /// the sum (~5ms vs ~13ms sequential on a typical project). On a warm- /// cache every thread is a no-op.- pub fn load(repo: &Repository) -> Result<Self> {+ /// the sum (~6ms vs ~13ms sequential on a typical project). On a warm+ /// cache both threads are no-ops.+ ///+ /// `project_identifier` shares its thread with the project-config load+ /// because both touch the same `Repository` and have no warning+ /// interleave concern; combining them saves a spawn/join for the same+ /// wall pole (the identifier's `git config --list -z` dominates either+ /// way).+ pub fn load(repo: &'r Repository) -> Result<Self> {std::thread::scope(|s| {- let user_handle = s.spawn(|| {+ s.spawn(|| {let _span = Span::new("user_config_load");- UserConfig::load().map_err(anyhow::Error::from)+ let _ = repo.user_config();});- let project_repo = repo.clone();- let project_handle = s.spawn(move || {- let _span = Span::new("project_config_load");- project_repo.load_project_config()+ s.spawn(|| {+ {+ let _span = Span::new("project_config_load");+ let _ = repo.project_config();+ }+ {+ let _span = Span::new("project_identifier_warm");+ let _ = repo.project_identifier();+ }});- let id_repo = repo.clone();- let id_handle = s.spawn(move || {- let _span = Span::new("project_identifier_warm");- let _ = id_repo.project_identifier();- });-- let user = user_handle- .join()- .map_err(|_| anyhow::anyhow!("user_config thread panicked"))??;- let project = project_handle- .join()- .map_err(|_| anyhow::anyhow!("project_config thread panicked"))??;- id_handle- .join()- .map_err(|_| anyhow::anyhow!("project_identifier thread panicked"))?;- Ok(Self { user, project })+ });+ Ok(Self {+ user: repo.user_config(),+ project: repo.project_config()?,})}}diff --git a/src/config/mod.rs b/src/config/mod.rsindex 0ee9736c3..4002ba786 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -123,10 +123,10 @@ pub use deprecation::{};pub use expansion::{ACTIVE_VARS, ALIAS_ARGS_KEY, DEPRECATED_TEMPLATE_VARS, EXEC_BASE_VARS, REPO_VARS,- TemplateExpandError, ValidationScope, base_vars, expand_template, format_alias_variables,- format_hook_variables, redact_credentials, referenced_vars_for_config, sanitize_branch_name,- sanitize_db, short_hash, template_references_var, validate_template, validate_template_syntax,- vars_available_in,+ TemplateExpandError, ValidationScope, alias_context_filter, base_vars, expand_template,+ format_alias_variables, format_hook_variables, redact_credentials, referenced_vars_for_config,+ sanitize_branch_name, sanitize_db, short_hash, template_references_var, validate_template,+ validate_template_syntax, vars_available_in,};pub use hooks::HooksConfig;pub use loaded::LoadedConfigs;diff --git a/src/config/user/mod.rs b/src/config/user/mod.rsindex 7c07a65f9..624e05f7b 100644--- a/src/config/user/mod.rs+++ b/src/config/user/mod.rs@@ -283,7 +283,7 @@ fn load_config_file(////// Environment variables can override config file settings using `WORKTRUNK_` prefix with/// `__` separator for nested fields (e.g., `WORKTRUNK_COMMIT__GENERATION__COMMAND`).-#[derive(Debug, Default, Serialize, Deserialize, JsonSchema)]+#[derive(Debug, Default, Clone, Serialize, Deserialize, JsonSchema)]pub struct UserConfig {/// Per-project configuration (approved commands, etc.)/// Uses BTreeMap for deterministic serialization order and better diff readabilitydiff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex e55850f84..ba6e4bf81 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -544,18 +544,28 @@ impl Repository {////// Result is cached in the repository's shared cache (same for all clones)./// Returns `None` if not in a worktree or if no config file exists.+ ///+ /// Returns an owned clone — use [`project_config`](Self::project_config)+ /// when a borrow suffices, to avoid the clone.pub fn load_project_config(&self) -> anyhow::Result<Option<ProjectConfig>> {+ Ok(self.project_config()?.cloned())+ }++ /// Borrow the cached project configuration.+ ///+ /// Same caching semantics as [`load_project_config`](Self::load_project_config),+ /// but returns a reference into the cache. Mirrors [`user_config`](Self::user_config)+ /// so callers that need both configs (e.g. via+ /// [`LoadedConfigs`](crate::config::LoadedConfigs)) can read them through+ /// the same borrow-from-cache shape.+ pub fn project_config(&self) -> anyhow::Result<Option<&ProjectConfig>> {self.cache.project_config- .get_or_try_init(|| {- match self.current_worktree().root() {- Ok(_) => {- ProjectConfig::load(self, true).context("Failed to load project config")- }- Err(_) => Ok(None), // Not in a worktree, no project config- }+ .get_or_try_init(|| match self.current_worktree().root() {+ Ok(_) => ProjectConfig::load(self, true).context("Failed to load project config"),+ Err(_) => Ok(None), // Not in a worktree, no project config})- .cloned()+ .map(Option::as_ref)}}diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex f65742b60..55f65c3a1 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -1370,9 +1370,20 @@ impl Cmd {}};- // Handle signals (Unix only)+ // Handle signals (Unix only).+ //+ // `seen_signal` records any signal forwarded by the listener thread,+ // covering the case where the child caught the signal and exited with+ // a code (no kernel `status.signal()` to read). The clean-exit gate+ // closes the wait-vs-handle.close window: if `child.wait()` returned+ // success and a signal then landed before `handle.close()` ran, the+ // signal arrived too late to have killed anything — the contract on+ // `signal: Some(_)` is "this child was killed by the signal" and+ // `interrupt_exit_code` callers in pipeline loops break on it.#[cfg(unix)]- if let Some(sig) = seen_signal {+ if let Some(sig) = seen_signal+ && !status.success()+ {trace_log.completed(false);external_log.record(Some(128 + sig));return Err(WorktrunkError::ChildProcessExited {diff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_args_shell_escaped.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_args_shell_escaped.snapindex 4a474c144..f4daf813c 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_args_shell_escaped.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_args_shell_escaped.snap@@ -13,10 +13,15 @@ info:COLUMNS: "500"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""HOME: "[TEST_HOME]"LANG: CLC_ALL: C@@ -51,16 +56,16 @@ hello foo bar baz[107m [0m branch = feature[107m [0m worktree_path = _REPO_.feature[107m [0m worktree_name = repo.feature-[107m [0m commit = 05a4a45d0b981dad5c27db59dca482836d59f89e-[107m [0m short_commit = 05a4a45-[107m [0m upstream = (unset)+[107m [0m [2mcommit = (unused)[22m+[107m [0m [2mshort_commit = (unused)[22m+[107m [0m [2mupstream = (unused)[22m[107m [0m repo = repo[107m [0m repo_path = _REPO_-[107m [0m owner = (unset)-[107m [0m primary_worktree_path = _REPO_-[107m [0m default_branch = main-[107m [0m remote = origin-[107m [0m remote_url = ../origin.git+[107m [0m [2mowner = (unused)[22m+[107m [0m [2mprimary_worktree_path = (unused)[22m+[107m [0m [2mdefault_branch = (unused)[22m+[107m [0m [2mremote = (unused)[22m+[107m [0m [2mremote_url = (unused)[22m[107m [0m cwd = _REPO_.feature[107m [0m args = foo 'bar baz'[36m◎[39m [36mRunning alias [1mgreet[22m[39mdiff --git a/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_variable_table.snap b/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_variable_table.snapindex 272d7ad57..d22a7f0e8 100644--- a/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_variable_table.snap+++ b/tests/snapshots/integration__integration_tests__step_alias__alias_verbose_variable_table.snap@@ -12,10 +12,15 @@ info:COLUMNS: "500"GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMON_DIR: ""GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"GIT_CONFIG_SYSTEM: /dev/null+ GIT_DIR: ""GIT_EDITOR: ""+ GIT_INDEX_FILE: ""+ GIT_OBJECT_DIRECTORY: ""GIT_TERMINAL_PROMPT: "0"+ GIT_WORK_TREE: ""HOME: "[TEST_HOME]"LANG: CLC_ALL: C@@ -50,16 +55,16 @@ hello world[107m [0m branch = feature[107m [0m worktree_path = _REPO_.feature[107m [0m worktree_name = repo.feature-[107m [0m commit = 05a4a45d0b981dad5c27db59dca482836d59f89e-[107m [0m short_commit = 05a4a45-[107m [0m upstream = (unset)+[107m [0m [2mcommit = (unused)[22m+[107m [0m [2mshort_commit = (unused)[22m+[107m [0m [2mupstream = (unused)[22m[107m [0m repo = repo[107m [0m repo_path = _REPO_-[107m [0m owner = (unset)-[107m [0m primary_worktree_path = _REPO_-[107m [0m default_branch = main-[107m [0m remote = origin-[107m [0m remote_url = ../origin.git+[107m [0m [2mowner = (unused)[22m+[107m [0m [2mprimary_worktree_path = (unused)[22m+[107m [0m [2mdefault_branch = (unused)[22m+[107m [0m [2mremote = (unused)[22m+[107m [0m [2mremote_url = (unused)[22m[107m [0m cwd = _REPO_.feature[107m [0m args = world[36m◎[39m [36mRunning alias [1mgreet[22m[39m