Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(alias)!: source-tag steps and decide EXEC per-step (#2474)
Worktrunk Botaf3be9e6557e
diff --git a/src/commands/alias.rs b/src/commands/alias.rsindex f01f92a6d..bdaa8eca0 100644--- a/src/commands/alias.rs+++ b/src/commands/alias.rs@@ -25,18 +25,26 @@//!//! User-config aliases are trusted (skip approval). Project-config aliases//! require command approval. When both define the same alias, both run — user-//! first, then project. The CD directive file is passed through to child-//! processes so inner `wt` invocations can redirect the parent shell's cwd;-//! the EXEC directive file is scrubbed so alias bodies cannot inject-//! arbitrary shell into the interactive session.+//! first, then project. The dispatch path keys aliases by name with each+//! source's body kept separate (`AliasEntry { user, project }`) rather than+//! merging into a single `CommandConfig`, so per-source policy can be applied+//! step-by-step without un-merging. Steps are tagged with their source+//! (`HookSource::User` / `Project`), and `sourced_steps_to_foreground`+//! applies per-step `DirectivePassthrough`: the CD directive file is passed+//! through to every step so inner `wt` invocations can redirect the parent+//! shell's cwd; the EXEC directive file passes through user-source steps but+//! is scrubbed for project-source steps. When the same name is defined in+//! both configs, the user's own steps still get the EXEC relaxation — the+//! decision is per-step, so the project side scrubbing doesn't bleed back+//! into the user steps. See issue #2101.use std::collections::{BTreeMap, BTreeSet};use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::{- ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, append_aliases,- format_alias_variables, referenced_vars_for_config,+ ALIAS_ARGS_KEY, CommandConfig, HookStep, ProjectConfig, UserConfig, format_alias_variables,+ referenced_vars_for_config,};use worktrunk::git::Repository;use worktrunk::styling::{@@ -46,12 +54,14 @@ use worktrunk::styling::{use crate::commands::command_approval::approve_alias_commands;use crate::commands::command_executor::{- AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,- alias_error_wrapper, build_hook_context, execute_pipeline_foreground,+ CommandContext, FailureStrategy, PipelineKind, PreparedCommand, PreparedStep,+ build_hook_context, execute_pipeline_foreground,+};+use crate::commands::hooks::{+ HookSource, SourcedStep, format_pipeline_summary_from_names, sourced_steps_to_foreground,+ step_names_from_config,};-use crate::commands::hooks::{format_pipeline_summary_from_names, step_names_from_config};use crate::commands::{build_invalid_subcommand_error, similar_subcommands};-use crate::output::DirectivePassthrough;/// Built-in `wt step` subcommand names. Aliases with these names are/// reachable via `wt <name>` (top-level) but shadowed via `wt step <name>`.@@ -263,21 +273,6 @@ impl AliasOptions {}}-/// Determine whether an alias requires project-config approval.-///-/// Returns the project-config commands for this alias, if any exist.-/// Project-config commands always need approval, regardless of whether-/// user config also defines the same alias — matching hook behavior.-fn alias_needs_approval(- alias_name: &str,- project_config: &Option<ProjectConfig>,-) -> Option<CommandConfig> {- project_config- .as_ref()- .and_then(|pc| pc.aliases.get(alias_name))- .cloned()-}-/// Synthesize clap's native `InvalidSubcommand` error for `wt step <name>`/// and return it via `enhance_clap_error`, so the output matches what/// `wt <typo>` produces at the top level. Suggestion candidates include both@@ -312,8 +307,11 @@ fn unknown_step_command_error(name: &str, alias_names: &[String]) -> anyhow::Err/// Sibling of `format_command_label` in `commands/mod.rs`, which builds the/// non-pipeline `Running {type} {name}` form for hooks. Both apply bold/// styling to the alias/command name — keep them in sync if styling evolves.-fn format_alias_announcement(name: &str, cmd_config: &CommandConfig) -> Option<String> {- let step_names = step_names_from_config(cmd_config);+fn format_alias_announcement(name: &str, entry: &AliasEntry) -> Option<String> {+ let step_names: Vec<Vec<Option<&str>>> = entry+ .iter()+ .flat_map(|(_, cfg)| step_names_from_config(cfg))+ .collect();let summary =format_pipeline_summary_from_names(&step_names, |n| cformat!("<bold>{n}</>"), |_| None);@@ -324,18 +322,96 @@ fn format_alias_announcement(name: &str, cmd_config: &CommandConfig) -> Option<S}}-/// Load the merged alias map (user config + project config, in runtime order).-fn load_merged_aliases(- repo: &Repository,+/// One alias entry, with each source's body kept separate.+///+/// At least one of `user` / `project` is always `Some` for entries that+/// `load_aliases` returns (a name only appears in the map if some source+/// defines it). When both are set, both bodies run — user first, then+/// project — and each runs under its own trust regime: user steps skip+/// approval and pass EXEC through (issue #2101); project steps require+/// approval and scrub EXEC.+pub(crate) struct AliasEntry {+ pub user: Option<CommandConfig>,+ pub project: Option<CommandConfig>,+}++impl AliasEntry {+ /// Walk the configured sources in runtime execution order: user first,+ /// then project. Skips sources that aren't configured.+ pub fn iter(&self) -> impl Iterator<Item = (HookSource, &CommandConfig)> {+ self.user+ .iter()+ .map(|c| (HookSource::User, c))+ .chain(self.project.iter().map(|c| (HookSource::Project, c)))+ }++ /// Representative config for single-pick contexts (completion help text,+ /// shadowed-by-builtin display). User wins over project, matching the+ /// order each source's body would run.+ pub fn representative(&self) -> &CommandConfig {+ self.user+ .as_ref()+ .or(self.project.as_ref())+ .expect("AliasEntry always has at least one source")+ }+}++/// Map of alias name → both sources' bodies. The merge that+/// `append_aliases` used to perform at this layer turns into per-source+/// fields, so downstream code never has to reconstitute the source split.+pub(crate) type AliasMap = BTreeMap<String, AliasEntry>;++/// Load aliases from user and project config, keyed by name with sources+/// kept separate. Per-project user-config overrides are still merged into+/// `entry.user` by [`UserConfig::aliases`] — that's the same axis (both+/// `HookSource::User`) and is correct. The user/project merge that produced+/// the old `load_merged_aliases` is what this function eliminates.+///+/// `repo` is `None` when called outside a git repo (e.g. completion), in+/// which case per-project user-config overrides aren't resolved and project+/// config is ignored.+pub(crate) fn load_aliases(+ repo: Option<&Repository>,user_config: &UserConfig,project_config: Option<&ProjectConfig>,-) -> BTreeMap<String, CommandConfig> {- let project_id = repo.project_identifier().ok();- let mut aliases = user_config.aliases(project_id.as_deref());+) -> AliasMap {+ let project_id = repo.and_then(|r| r.project_identifier().ok());+ let mut result: AliasMap = user_config+ .aliases(project_id.as_deref())+ .into_iter()+ .map(|(n, c)| {+ (+ n,+ AliasEntry {+ user: Some(c),+ project: None,+ },+ )+ })+ .collect();if let Some(pc) = project_config {- append_aliases(&mut aliases, &pc.aliases);+ for (name, cfg) in &pc.aliases {+ result+ .entry(name.clone())+ .or_insert_with(|| AliasEntry {+ user: None,+ project: None,+ })+ .project = Some(cfg.clone());+ }+ }+ result+}++/// Union of variables referenced across both source bodies of an alias.+/// Drives `--KEY=VALUE` routing in `AliasOptions::parse`: a flag binds to+/// `{{ KEY }}` if KEY is referenced by *any* source's body.+fn referenced_vars_for_entry(entry: &AliasEntry) -> anyhow::Result<BTreeSet<String>> {+ let mut out = BTreeSet::new();+ for (_, cfg) in entry.iter() {+ out.extend(referenced_vars_for_config(cfg)?);}- aliases+ Ok(out)}/// Try to run alias `name` with `rest` as its arg vector. Returns `Ok(None)`@@ -359,11 +435,11 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::R};let user_config = UserConfig::load()?;let project_config = ProjectConfig::load(&repo, true)?;- let aliases = load_merged_aliases(&repo, &user_config, project_config.as_ref());- let Some(cmd_config) = aliases.get(&name) else {+ let aliases = load_aliases(Some(&repo), &user_config, project_config.as_ref());+ let Some(entry) = aliases.get(&name) else {return Ok(None);};- let referenced = referenced_vars_for_config(cmd_config)?;+ let referenced = referenced_vars_for_entry(entry)?;if try_intercept_alias_help(&name, &rest, &referenced) {return Ok(Some(()));}@@ -371,16 +447,10 @@ pub fn try_alias(name: String, rest: Vec<String>, global_yes: bool) -> anyhow::Ralias_args.push(name);alias_args.extend(rest);let (opts, warnings) = AliasOptions::parse(alias_args, &referenced)?;- run_alias(- opts,- warnings,- repo,- user_config,- project_config,- aliases,- global_yes,- )- .map(Some)+ 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).map(Some)}/// Run a configured alias from `wt step <name>`. Errors with a clap-style@@ -402,11 +472,11 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {let repo = Repository::current()?;let user_config = UserConfig::load()?;let project_config = ProjectConfig::load(&repo, true)?;- let aliases = load_merged_aliases(&repo, &user_config, project_config.as_ref());+ let aliases = load_aliases(Some(&repo), &user_config, project_config.as_ref());let Some(name) = args.first().cloned() else {bail!("Missing alias name");};- let Some(cmd_config) = aliases.get(&name) else {+ let Some(entry) = aliases.get(&name) else {// Mirror clap's native `unrecognized subcommand` error so `wt step// <typo>` reads the same as `wt <typo>`. Aliases are fed into the// `SuggestedSubcommand` list so a typo like `wt step deplyo` still@@ -420,20 +490,15 @@ pub fn step_alias(args: Vec<String>, global_yes: bool) -> anyhow::Result<()> {.collect();return Err(unknown_step_command_error(&name, &alias_names));};- let referenced = referenced_vars_for_config(cmd_config)?;+ let referenced = referenced_vars_for_entry(entry)?;if try_intercept_alias_help(&name, &args[1..], &referenced) {return Ok(());}let (opts, warnings) = AliasOptions::parse(args, &referenced)?;- run_alias(- opts,- warnings,- repo,- user_config,- project_config,- aliases,- global_yes,- )+ 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)}/// Return alias names for use as suggestions when a top-level subcommand is@@ -450,14 +515,13 @@ pub fn alias_names_for_suggestions() -> Vec<String> {return Vec::new();};let project_config = ProjectConfig::load(&repo, false).ok().flatten();- load_merged_aliases(&repo, &user_config, project_config.as_ref())- .keys()- .cloned()+ load_aliases(Some(&repo), &user_config, project_config.as_ref())+ .into_keys().collect()}-/// Execute `cmd_config` for `opts.name`. Caller must have already verified-/// `aliases.contains_key(&opts.name)`.+/// Execute the alias body for `opts.name`. Caller must have already verified+/// the entry exists.////// `global_yes` is the top-level `--yes`/`-y` flag and is the only source for/// skipping approval — the post-alias form (`wt deploy --yes`) is no longer@@ -467,36 +531,26 @@ fn run_alias(warnings: Vec<String>,repo: Repository,user_config: UserConfig,- project_config: Option<ProjectConfig>,- aliases: BTreeMap<String, CommandConfig>,+ entry: &AliasEntry,global_yes: bool,) -> anyhow::Result<()> {- let cmd_config = aliases- .get(&opts.name)- .expect("caller verified alias is configured");-- // Surface parser advisories (e.g. `--KEY --VALUE` footgun) before- // announcing the run so they're visible in execution output.for warning in &warnings {eprintln!("{}", warning_message(warning));}- // Check if this alias needs project-config approval. project_id is required- // for approval — re-derive with error propagation rather than relying on- // `.ok()`. `global_yes` is the sole source for skipping approval now that- // `wt <alias> --yes` (post-alias form) is unsupported.- if let Some(project_commands) = alias_needs_approval(&opts.name, &project_config) {+ // Project bodies require approval even when user config also defines the+ // alias — same as hooks. `global_yes` is the sole skip source.+ if let Some(project_commands) = entry.project.as_ref() {let project_id = repo.project_identifier().context("Cannot determine project identifier for alias approval")?;let approved =- approve_alias_commands(&project_commands, &opts.name, &project_id, global_yes)?;+ approve_alias_commands(project_commands, &opts.name, &project_id, global_yes)?;if !approved {return Ok(());}}- // Build hook context for template expansionlet wt = repo.current_worktree();let wt_path = wt.root().context("Failed to get worktree root")?;let branch = wt.branch().ok().flatten();@@ -517,7 +571,6 @@ fn run_alias(.expect("Vec<String> serialization should never fail"),);- // Build JSON context for stdinlet context_json = serde_json::to_string(&context_map).expect("HashMap<String, String> serialization should never fail");@@ -527,7 +580,7 @@ fn run_alias(eprintln!("{}", format_with_gutter(&vars, None));}- if let Some(msg) = format_alias_announcement(&opts.name, cmd_config) {+ if let Some(msg) = format_alias_announcement(&opts.name, entry) {eprintln!("{}", progress_message(msg));} else if verbosity() >= 1 {eprintln!(@@ -536,17 +589,10 @@ fn run_alias();}- // CD passed through, EXEC scrubbed (see `output::global` for rationale).- let directives = DirectivePassthrough::inherit_from_env();-- // Build ForegroundSteps: all alias commands use lazy expansion so vars.*- // references resolved from git config at execution time are visible to- // later steps that set vars via `wt config state vars set`.let alias_name = opts.name.clone();- let foreground_steps: Vec<ForegroundStep> = cmd_config- .steps()- .iter()- .map(|step| {+ let mut sourced_steps = Vec::new();+ for (source, cfg) in entry.iter() {+ for step in cfg.steps() {let prepared = match step {HookStep::Single(cmd) => {PreparedStep::Single(alias_prepared_command(cmd, &context_json, &alias_name))@@ -557,25 +603,24 @@ fn run_alias(.collect(),),};- ForegroundStep {+ sourced_steps.push(SourcedStep {step: prepared,- concurrent: true,- announce: AnnouncePolicy::None,- pipe_stdin: false,- // Aliases pass child stdout through so `wt <alias> | …` works- // in scripts (#2478). Worktrunk's own messages still go to- // stderr.- redirect_stdout_to_stderr: false,- error_wrapper: alias_error_wrapper(alias_name.clone()),- }- })- .collect();+ source,+ hook_type: None,+ display_path: None,+ // Aliases have no deprecated single-table form, so concurrent+ // commands always run concurrently.+ is_pipeline: true,+ });+ }+ }+ let foreground_steps =+ sourced_steps_to_foreground(sourced_steps, &PipelineKind::Alias { name: alias_name });execute_pipeline_foreground(&foreground_steps,&repo,&wt_path,- &directives,FailureStrategy::FailFast,)}@@ -865,38 +910,49 @@ mod tests {toml::from_str::<Wrap>(toml_str).unwrap().cmd}+ /// Build a user-only `AliasEntry` for announcement-formatting tests. The+ /// announcement walks both sources, so a user-only entry exercises the+ /// same code path as the project-only or both-sources cases for these+ /// fixtures.+ fn user_entry_from_toml(toml_str: &str) -> AliasEntry {+ AliasEntry {+ user: Some(cfg_from_toml(toml_str)),+ project: None,+ }+ }+#[test]fn test_format_alias_announcement_single_unnamed() {// Single unnamed alias — banner would only echo the name, so suppress.- let cfg = cfg_from_toml(r#"cmd = "echo hi""#);- assert!(format_alias_announcement("deploy", &cfg).is_none());+ let entry = user_entry_from_toml(r#"cmd = "echo hi""#);+ assert!(format_alias_announcement("deploy", &entry).is_none());}#[test]fn test_format_alias_announcement_pipeline_all_unnamed() {// Pipeline of unnamed strings — still no summary content to show.- let cfg = cfg_from_toml(r#"cmd = ["echo a", "echo b"]"#);- assert!(format_alias_announcement("deploy", &cfg).is_none());+ let entry = user_entry_from_toml(r#"cmd = ["echo a", "echo b"]"#);+ assert!(format_alias_announcement("deploy", &entry).is_none());}#[test]fn test_format_alias_announcement_concurrent_named() {// Single concurrent step (named table form).- let cfg = cfg_from_toml(+ let entry = user_entry_from_toml(r#"[cmd]build = "cargo build"test = "cargo test""#,);- let msg = format_alias_announcement("check", &cfg).expect("summary expected");+ let msg = format_alias_announcement("check", &entry).expect("summary expected");insta::assert_snapshot!(msg.ansi_strip(), @"Running alias check: build & test");}#[test]fn test_format_alias_announcement_pipeline_named() {// Pipeline: serial named step then concurrent named step.- let cfg = cfg_from_toml(+ let entry = user_entry_from_toml(r#"cmd = [{ install = "npm install" },@@ -904,7 +960,7 @@ cmd = []"#,);- let msg = format_alias_announcement("deploy", &cfg).expect("summary expected");+ let msg = format_alias_announcement("deploy", &entry).expect("summary expected");insta::assert_snapshot!(msg.ansi_strip(), @"Running alias deploy: install, build & lint");}@@ -912,7 +968,7 @@ cmd = [fn test_format_alias_announcement_mixed_named_unnamed() {// Pipeline mixing anonymous strings and named steps. Unnamed entries// are skipped from the summary (aliases have no fallback label).- let cfg = cfg_from_toml(+ let entry = user_entry_from_toml(r#"cmd = ["echo first",@@ -920,10 +976,25 @@ cmd = []"#,);- let msg = format_alias_announcement("ci", &cfg).expect("summary expected");+ let msg = format_alias_announcement("ci", &entry).expect("summary expected");insta::assert_snapshot!(msg.ansi_strip(), @"Running alias ci: build & test");}+ #[test]+ fn test_format_alias_announcement_concatenates_user_and_project() {+ // When both sources define the alias, the announcement walks user+ // steps first, then project steps — matching runtime execution+ // order. Both summaries appear in the same banner.+ let entry = AliasEntry {+ user: Some(cfg_from_toml(r#"cmd = [{ install = "npm install" }]"#)),+ project: Some(cfg_from_toml(+ r#"cmd = [{ build = "npm build" }, { test = "npm test" }]"#,+ )),+ };+ let msg = format_alias_announcement("deploy", &entry).expect("summary expected");+ insta::assert_snapshot!(msg.ansi_strip(), @"Running alias deploy: install, build, test");+ }+#[test]fn test_parse_built_in_flags() {use insta::assert_debug_snapshot;diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex 100466138..56c9bda8e 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -78,6 +78,17 @@ pub enum AnnouncePolicy {/// `Send + Sync` bounds are required.pub type ErrorWrapper = Box<dyn Fn(&PreparedCommand, String, Option<i32>) -> anyhow::Error>;+/// What kind of pipeline a sourced step belongs to.+///+/// Supplied at conversion time (`sourced_steps_to_foreground`) so a single+/// `SourcedStep` shape can be produced by both alias and hook resolution.+/// Drives the per-step trust model (EXEC passthrough), announce policy,+/// stdin handling, and error wrapping.+pub enum PipelineKind {+ Hook,+ Alias { name: String },+}+/// A pipeline step ready for foreground execution, with rendering / error policy.pub struct ForegroundStep {pub step: PreparedStep,@@ -97,6 +108,12 @@ pub struct ForegroundStep {pub redirect_stdout_to_stderr: bool,/// Wraps a per-command failure into the final error returned to the caller.pub error_wrapper: ErrorWrapper,+ /// Per-step directive passthrough. Trust differs by source — user-source+ /// alias steps pass EXEC through (the body is the user's own config),+ /// while project-source steps and all hook steps scrub it. Per-step rather+ /// than per-pipeline so a merged user+project alias relaxes the user's+ /// own steps without leaking the project's body into the parent shell.+ pub directives: DirectivePassthrough,}/// Controls how foreground execution responds to command failures.@@ -363,28 +380,20 @@ pub fn execute_pipeline_foreground(steps: &[ForegroundStep],repo: &Repository,wt_path: &Path,- directives: &DirectivePassthrough,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {for fg_step in steps {match &fg_step.step {PreparedStep::Single(cmd) => {- run_one_command(cmd, fg_step, repo, wt_path, directives, failure_strategy)?;+ run_one_command(cmd, fg_step, repo, wt_path, failure_strategy)?;}PreparedStep::Concurrent(cmds) => {if !fg_step.concurrent {for cmd in cmds {- run_one_command(cmd, fg_step, repo, wt_path, directives, failure_strategy)?;+ run_one_command(cmd, fg_step, repo, wt_path, failure_strategy)?;}} else {- run_concurrent_group(- cmds,- fg_step,- repo,- wt_path,- directives,- failure_strategy,- )?;+ run_concurrent_group(cmds, fg_step, repo, wt_path, failure_strategy)?;}}}@@ -405,9 +414,9 @@ fn run_concurrent_group(fg_step: &ForegroundStep,repo: &Repository,wt_path: &Path,- directives: &DirectivePassthrough,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {+ let directives = &fg_step.directives;for cmd in cmds {announce_command(cmd, &fg_step.announce);}@@ -467,9 +476,9 @@ fn run_one_command(fg_step: &ForegroundStep,repo: &Repository,wt_path: &Path,- directives: &DirectivePassthrough,failure_strategy: FailureStrategy,) -> anyhow::Result<()> {+ let directives = &fg_step.directives;announce_command(cmd, &fg_step.announce);let command_str = resolve_command_str(cmd, repo)?;diff --git a/src/commands/config/alias.rs b/src/commands/config/alias.rsindex 7fdc739ad..8d815ca39 100644--- a/src/commands/config/alias.rs+++ b/src/commands/config/alias.rs@@ -23,13 +23,13 @@ use std::io::Write;use anyhow::Context;use color_print::cformat;use worktrunk::config::{- ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, append_aliases,- referenced_vars_for_config, template_references_var, validate_template_syntax,+ ALIAS_ARGS_KEY, CommandConfig, ProjectConfig, UserConfig, referenced_vars_for_config,+ template_references_var, validate_template_syntax,};use worktrunk::git::{Repository, WorktrunkError};use worktrunk::styling::{format_bash_with_gutter, info_message, println};-use crate::commands::alias::{AliasOptions, AliasSource, TOP_LEVEL_BUILTINS};+use crate::commands::alias::{AliasOptions, AliasSource, TOP_LEVEL_BUILTINS, load_aliases};use crate::commands::build_invalid_subcommand_error;use crate::commands::command_executor::{CommandContext, build_hook_context, expand_shell_template,@@ -262,12 +262,8 @@ fn unknown_alias_error(name: &str,sub: &str,) -> anyhow::Error {- let project_id = repo.project_identifier().ok();- let mut merged = user_config.aliases(project_id.as_deref());- if let Some(pc) = project_config {- append_aliases(&mut merged, &pc.aliases);- }- let suggestions = did_you_mean(name, merged.into_keys());+ let aliases = load_aliases(Some(repo), user_config, project_config);+ let suggestions = did_you_mean(name, aliases.into_keys());let mut top = crate::cli::build_command();let sub_cmd = topdiff --git a/src/commands/hooks.rs b/src/commands/hooks.rsindex d41f506b2..94cd7bd34 100644--- a/src/commands/hooks.rs+++ b/src/commands/hooks.rs@@ -79,8 +79,9 @@ use worktrunk::styling::{};use super::command_executor::{- AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PreparedCommand, PreparedStep,- execute_pipeline_foreground, hook_error_wrapper, prepare_steps,+ AnnouncePolicy, CommandContext, FailureStrategy, ForegroundStep, PipelineKind, PreparedCommand,+ PreparedStep, alias_error_wrapper, execute_pipeline_foreground, hook_error_wrapper,+ prepare_steps,};use crate::commands::process::{HookLog, spawn_detached_exec};use crate::output::DirectivePassthrough;@@ -147,7 +148,7 @@ fn prepare_sourced_steps(result.push(SourcedStep {step: filtered,source,- hook_type,+ hook_type: Some(hook_type),display_path: display_path.clone(),is_pipeline,});@@ -207,14 +208,20 @@ fn count_sourced_commands(steps: &[SourcedStep]) -> usize {}/// A pipeline step with source information, for pipeline-aware execution.+///+/// Used by both hook and alias dispatch as the source-tagged shape that feeds+/// `sourced_steps_to_foreground`. `hook_type` and `display_path` are+/// hook-only metadata; aliases leave them `None`. Pipeline kind (Hook vs+/// Alias) is supplied at conversion time, so this struct stays neutral.pub struct SourcedStep {pub step: PreparedStep,pub source: HookSource,- pub hook_type: HookType,+ /// Hook type for hook pipelines; `None` for aliases.+ pub hook_type: Option<HookType>,pub display_path: Option<PathBuf>,- /// Whether this step came from a pipeline config (`[[hook]]` blocks).- /// Pipeline `Concurrent` steps run concurrently; non-pipeline `Concurrent`- /// steps (deprecated single-table form) run serially.+ /// Whether `Concurrent` steps run concurrently. For hooks: derived from+ /// `is_pipeline()` (deprecated single-table form runs serially). For+ /// aliases: always true — no deprecated form.pub is_pipeline: bool,}@@ -499,7 +506,9 @@ fn run_hooks_background(// type render as one clause: `post-merge: sync, push (user); build (project)`.let mut type_summaries: Vec<(HookType, Vec<String>)> = Vec::new();for (_, group) in &pipelines {- let hook_type = group[0].hook_type;+ let hook_type = group[0]+ .hook_type+ .expect("background hook pipelines always set hook_type");let summary = format_pipeline_summary(group);if let Some(entry) = type_summaries.iter_mut().find(|(ht, _)| *ht == hook_type) {entry.1.push(summary);@@ -608,7 +617,7 @@ fn print_background_variable_table() {for (_, group) in pipelines {for sourced in group {- if sourced.hook_type != hook_type {+ if sourced.hook_type != Some(hook_type) {continue;}let cmd = match &sourced.step {@@ -633,7 +642,9 @@ fn print_background_variable_table(fn spawn_hook_pipeline_quiet(ctx: &CommandContext, steps: Vec<SourcedStep>) -> anyhow::Result<()> {use super::pipeline_spec::{PipelineCommandSpec, PipelineSpec, PipelineStepSpec};- let hook_type = steps[0].hook_type;+ let hook_type = steps[0]+ .hook_type+ .expect("background hook pipelines always set hook_type");let source = steps[0].source;// Extract base context from the first command. Both call sites@@ -782,6 +793,71 @@ pub(crate) fn prepare_and_check(Ok(sourced_steps)}+/// Convert source-tagged steps into foreground steps with pipeline-kind policy.+///+/// Shared between hook and alias dispatch. The `kind` argument supplies the+/// per-call-site policy (announce style, stdin handling, error wrapping) while+/// the `source` field on each step drives the per-step trust model+/// (`DirectivePassthrough`).+///+/// Trust model:+/// - User-source alias steps pass EXEC through. The body lives in the user's+/// own config, so a nested `wt switch --execute …` is no different from the+/// user typing it at the top level. See issue #2101.+/// - Project-source alias steps and all hook steps scrub EXEC (they can still+/// emit CD directives via `inherit_from_env`).+///+/// In a merged user+project alias body, the user's steps still get the+/// relaxation — the decision is per-step, so the project side scrubbing+/// doesn't bleed back into the user steps.+pub(crate) fn sourced_steps_to_foreground(+ sourced_steps: Vec<SourcedStep>,+ kind: &PipelineKind,+) -> Vec<ForegroundStep> {+ sourced_steps+ .into_iter()+ .map(|sourced| {+ let directives = match (kind, sourced.source) {+ (PipelineKind::Alias { .. }, HookSource::User) => {+ DirectivePassthrough::inherit_from_env_with_exec()+ }+ _ => DirectivePassthrough::inherit_from_env(),+ };+ let (announce, pipe_stdin, redirect_stdout_to_stderr, error_wrapper) = match kind {+ PipelineKind::Hook => {+ let hook_type = sourced+ .hook_type+ .expect("hook pipelines always set hook_type");+ (+ AnnouncePolicy::Hook {+ hook_type,+ display_path: sourced.display_path,+ },+ true,+ true,+ hook_error_wrapper(hook_type),+ )+ }+ PipelineKind::Alias { name } => (+ AnnouncePolicy::None,+ false,+ false,+ alias_error_wrapper(name.clone()),+ ),+ };+ ForegroundStep {+ step: sourced.step,+ concurrent: sourced.is_pipeline,+ announce,+ pipe_stdin,+ redirect_stdout_to_stderr,+ error_wrapper,+ directives,+ }+ })+ .collect()+}+/// Run user and project hooks for a given hook type in the foreground.////// Used directly only by the `wt hook <type>` path, which intentionally@@ -804,34 +880,12 @@ pub(crate) fn run_hooks_foreground(return Ok(());}- let directives = DirectivePassthrough::inherit_from_env();-- // Convert SourcedSteps → ForegroundSteps for the shared executor.- // Pipeline configs (`[[hook]]` blocks) get concurrent execution within each- // block. Non-pipeline configs (deprecated single-table `[hook]` form) run- // their commands serially.- let foreground_steps: Vec<ForegroundStep> = sourced_steps- .into_iter()- .map(|sourced| ForegroundStep {- concurrent: sourced.is_pipeline,- step: sourced.step,- announce: AnnouncePolicy::Hook {- hook_type: sourced.hook_type,- display_path: sourced.display_path,- },- pipe_stdin: true,- // Hooks merge stdout onto stderr so child output stays ordered- // with wt's own "Running …" announcement lines.- redirect_stdout_to_stderr: true,- error_wrapper: hook_error_wrapper(sourced.hook_type),- })- .collect();+ let foreground_steps = sourced_steps_to_foreground(sourced_steps, &PipelineKind::Hook);execute_pipeline_foreground(&foreground_steps,ctx.repo,ctx.worktree_path,- &directives,failure_strategy,)}@@ -946,7 +1000,7 @@ mod tests {SourcedStep {step,source: HookSource::User,- hook_type: worktrunk::HookType::PostStart,+ hook_type: Some(worktrunk::HookType::PostStart),display_path: None,is_pipeline: false,}diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex 7f8960a70..4d4aabfde 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -29,7 +29,8 @@ pub(crate) mod template_vars;pub(crate) mod worktree;pub(crate) use alias::{- HelpContext, alias_names_for_suggestions, augment_help, step_alias, try_alias,+ AliasMap, HelpContext, alias_names_for_suggestions, augment_help, load_aliases, step_alias,+ try_alias,};pub(crate) use config::{add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show, handle_claude_install,diff --git a/src/completion.rs b/src/completion.rsindex dbe4baa20..4dae6c18b 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -1,5 +1,4 @@use std::cell::RefCell;-use std::collections::BTreeMap;use std::ffi::{OsStr, OsString};use std::io::Write;@@ -8,8 +7,9 @@ use clap_complete::engine::{ArgValueCompleter, CompletionCandidate, ValueCompletuse clap_complete::env::CompleteEnv;use crate::cli;+use crate::commands::{AliasMap, load_aliases};use crate::display::format_relative_time_short;-use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig, append_aliases};+use worktrunk::config::{CommandConfig, ProjectConfig, UserConfig};use worktrunk::git::{BranchCategory, HookType, Repository};/// Handle shell-initiated completion requests via `COMPLETE=$SHELL wt`@@ -521,23 +521,29 @@ fn inject_alias_subcommands(cmd: Command) -> Command {}let mut cmd = cmd;- // Top-level injection: skip aliases that match a top-level built-in.- for (name, cmd_config) in &aliases {+ // Top-level injection: skip aliases that match a top-level built-in. The+ // help text on the stub uses the representative source's first command+ // template (user wins over project), matching how the announcement+ // banner orders the two when both are configured.+ for (name, entry) in &aliases {if cmd.get_subcommands().any(|s| s.get_name() == name.as_str()) {continue;}- cmd = cmd.subcommand(build_alias_completion_command(name, cmd_config));+ cmd = cmd.subcommand(build_alias_completion_command(name, entry.representative()));}// Step-level injection: keep historical `wt step <alias>` completions.cmd.mut_subcommand("step", |mut step| {- for (name, cmd_config) in aliases {+ for (name, entry) in aliases {if step.get_subcommands().any(|s| s.get_name() == name.as_str()){continue;}- step = step.subcommand(build_alias_completion_command(&name, &cmd_config));+ step = step.subcommand(build_alias_completion_command(+ &name,+ entry.representative(),+ ));}step})@@ -567,27 +573,18 @@ fn build_alias_completion_command(name: &str, cmd_config: &CommandConfig) -> Com)}-/// Load aliases from user and project config for completion.-///-/// Merges user and project aliases with append semantics (matching hooks).-fn load_aliases_for_completion() -> BTreeMap<String, CommandConfig> {- let mut aliases = BTreeMap::new();-- if let Ok(repo) = Repository::current() {- // User config first- if let Ok(user_config) = UserConfig::load() {- let project_id = repo.project_identifier().ok();- aliases.extend(user_config.aliases(project_id.as_deref()));- }- // Project config appends- if let Ok(Some(project_config)) = ProjectConfig::load(&repo, false) {- append_aliases(&mut aliases, &project_config.aliases);- }- } else if let Ok(user_config) = UserConfig::load() {- aliases.extend(user_config.aliases(None));- }-- aliases+/// Load aliases from user and project config for completion. Outside a git+/// repo, only user config is read (per-project user-config overrides aren't+/// resolved without a project_id).+fn load_aliases_for_completion() -> AliasMap {+ let Ok(user_config) = UserConfig::load() else {+ return AliasMap::new();+ };+ let repo = Repository::current().ok();+ let project_config = repo+ .as_ref()+ .and_then(|r| ProjectConfig::load(r, false).ok().flatten());+ load_aliases(repo.as_ref(), &user_config, project_config.as_ref())}/// Truncate a template string for use as completion help text.diff --git a/src/output/concurrent.rs b/src/output/concurrent.rsindex 8ec5667e2..f1995d254 100644--- a/src/output/concurrent.rs+++ b/src/output/concurrent.rs@@ -44,7 +44,8 @@ use anyhow::Context;use worktrunk::command_log::log_command;use worktrunk::git::WorktrunkError;use worktrunk::shell_exec::{- DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR, ShellConfig, scrub_directive_env_vars,+ DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_EXEC_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR, ShellConfig,+ scrub_directive_env_vars,};use worktrunk::styling::stderr;@@ -249,6 +250,9 @@ fn spawn_child(if let Some(path) = &cmd.directives.cd_file {command.env(DIRECTIVE_CD_FILE_ENV_VAR, path);}+ if let Some(path) = &cmd.directives.exec_file {+ command.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);+ }if let Some(path) = &cmd.directives.legacy_file {command.env(DIRECTIVE_FILE_ENV_VAR, path);}@@ -497,9 +501,9 @@ mod tests {// passing a log_label doesn't panic and the command still runs.}- /// `DirectivePassthrough` with both `cd_file` and `legacy_file` set must- /// propagate both env vars to the child. The child script echoes each env- /// var; we assert both values are delivered.+ /// `DirectivePassthrough` with `cd_file`, `exec_file`, and `legacy_file`+ /// set must propagate all three env vars to the child. The child script+ /// echoes each env var; we assert every value is delivered.////// Unix-only: the script uses POSIX `sh` redirect syntax and relies on/// native temp paths that don't need escaping. Git Bash on Windows would@@ -509,24 +513,29 @@ mod tests {fn test_directive_env_vars_passed_through() {use tempfile::NamedTempFile;let cd = NamedTempFile::new().unwrap();+ let exec = NamedTempFile::new().unwrap();let legacy = NamedTempFile::new().unwrap();let directives = DirectivePassthrough {cd_file: Some(cd.path().to_path_buf()),+ exec_file: Some(exec.path().to_path_buf()),legacy_file: Some(legacy.path().to_path_buf()),};// Write each env var's value to its matching temp file. If the child// didn't receive the env var, the redirect would fail or write an// empty file.let script = format!(- "printf CD > {} && printf LEGACY > {}",+ "printf CD > {} && printf EXEC > {} && printf LEGACY > {}",cd.path().display(),+ exec.path().display(),legacy.path().display(),);let outcomes = run_one_with_directives("job", &script, None, &directives);assert!(outcomes[0].is_ok(), "child should exit 0");let cd_contents = std::fs::read_to_string(cd.path()).unwrap();+ let exec_contents = std::fs::read_to_string(exec.path()).unwrap();let legacy_contents = std::fs::read_to_string(legacy.path()).unwrap();assert_eq!(cd_contents, "CD");+ assert_eq!(exec_contents, "EXEC");assert_eq!(legacy_contents, "LEGACY");}diff --git a/src/output/global.rs b/src/output/global.rsindex 1a94ae738..821249af4 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -20,17 +20,21 @@//! sources after the `cd`. This is how `wt switch --execute <cmd>` runs its//! payload in the user's interactive shell, inheriting functions and env.//! Because the contents are sourced verbatim, wt scrubs this env var from-//! alias and foreground-hook child processes so a hook body cannot inject-//! shell into the parent session.+//! project-alias and foreground-hook child processes so a body authored in+//! shared config cannot inject shell into the parent session.//!//! # Conservative scrub//!-//! Because the EXEC env var is scrubbed from alias/hook child environments, a-//! nested `wt` invocation inside an alias body (e.g. `wt step my-alias` where-//! the alias runs `wt switch main --execute claude`) sees no EXEC file and-//! refuses to run the `--execute` payload, emitting a warning and a link to+//! User-source aliases pass the EXEC env var through (issue #2101): the body+//! lives in the user's own config, so `wt step my-alias` running+//! `wt switch main --execute claude` is no different from the user typing+//! the same command at the top level.+//!+//! Project aliases and foreground hooks keep the scrub. A nested `wt+//! --execute …` inside one of those bodies sees no EXEC file and refuses to+//! run the payload, emitting a warning and a link to//! <https://github.com/max-sixty/worktrunk/issues/2101> so users can report-//! whether to relax the restriction.+//! whether to relax the restriction further.//!//! # Legacy compat//!@@ -64,8 +68,9 @@ use worktrunk::shell_exec::{};use worktrunk::styling::{hint_message, warning_message};-/// Issue tracking whether to relax the conservative EXEC scrub for alias/hook-/// bodies. Emitted in the warning so users can report use cases.+/// Issue tracking whether to relax the EXEC scrub further for project aliases+/// and hooks. (User aliases already pass EXEC through.) Emitted in the warning+/// so users can report use cases.pub const EXEC_SCRUB_ISSUE_URL: &str = "https://github.com/max-sixty/worktrunk/issues/2101";// Re-export set_verbosity from the library's styling module.@@ -292,13 +297,13 @@ fn warn_exec_scrubbed_once(command: &str) {eprintln!("{}",warning_message(cformat!(- "<bold>--execute</> disabled inside alias/hook bodies for safety; skipping <bold>{command}</>"+ "<bold>--execute</> disabled inside project alias / hook bodies for safety; skipping <bold>{command}</>")));eprintln!("{}",hint_message(cformat!(- "This is extremely conservative; comment at <underline>{EXEC_SCRUB_ISSUE_URL}</> if this affects you"+ "User-source aliases allow it. Comment at <underline>{EXEC_SCRUB_ISSUE_URL}</> if you need it for project aliases or hooks")));}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 25081f244..f6ffb83cf 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -1440,16 +1440,19 @@ fn handle_removed_worktree_output(////// `directives` controls whether the child can write shell-integration/// directives back to the parent shell. The CD file is always safe to pass-/// through (raw path, no injection surface); the EXEC file is never passed-/// through — only wt-internal Rust code writes arbitrary shell directives.+/// through (raw path, no injection surface); the EXEC file is normally scrubbed+/// because alias/hook bodies must not inject arbitrary shell into the parent+/// session — see [`DirectivePassthrough::inherit_from_env_with_exec`] for the+/// one exception.////// - `DirectivePassthrough::default()` — scrubs all directive env vars from/// the child. Used by background hooks (outlive the parent shell).-/// - `DirectivePassthrough::inherit_from_env()` — re-adds whichever directive-/// env vars are currently set in this process. Used by aliases and-/// foreground hooks, which may emit `cd` directives. In new-protocol mode-/// only the CD file passes through; in legacy compat mode the single-/// legacy file passes through to preserve pre-split behavior.+/// - `DirectivePassthrough::inherit_from_env()` — re-adds CD (and the legacy+/// compat var) but scrubs EXEC. Used by project aliases and foreground hooks,+/// which may emit `cd` directives but must not be able to inject shell.+/// - `DirectivePassthrough::inherit_from_env_with_exec()` — also re-adds EXEC.+/// Used only for user-source aliases, where the alias body is already user-+/// authored just like a top-level `wt switch --execute` invocation.////// ## Stdout routing///@@ -1513,6 +1516,9 @@ pub fn execute_shell_command(if let Some(path) = directives.cd_file {cmd = cmd.directive_cd_file(path);}+ if let Some(path) = directives.exec_file {+ cmd = cmd.directive_exec_file(path);+ }if let Some(path) = directives.legacy_file {cmd = cmd.directive_legacy_file(path);}@@ -1529,34 +1535,51 @@ pub fn execute_shell_command(////// `Default` (no fields set) scrubs all directive env vars from the child;/// [`DirectivePassthrough::inherit_from_env`] reads the current process-/// environment for trusted contexts. The EXEC file is intentionally never-/// included — alias/hook shell bodies must not inject arbitrary shell into-/// the parent session.+/// environment and re-adds CD only; [`DirectivePassthrough::inherit_from_env_with_exec`]+/// re-adds CD and EXEC. The EXEC file is only included by the `_with_exec`+/// variant — every other path scrubs it so alias/hook shell bodies cannot+/// inject arbitrary shell into the parent session.#[derive(Debug, Default, Clone)]pub struct DirectivePassthrough {pub cd_file: Option<std::path::PathBuf>,+ pub exec_file: Option<std::path::PathBuf>,pub legacy_file: Option<std::path::PathBuf>,}impl DirectivePassthrough {/// Pass CD and legacy directive files through to the child, reading the- /// current process environment. Used by trusted contexts (aliases,- /// foreground hooks) that may legitimately emit a `cd` directive. The- /// EXEC file is deliberately omitted.+ /// current process environment. Used by project aliases and foreground+ /// hooks that may legitimately emit a `cd` directive. The EXEC file is+ /// deliberately omitted — a project-config body could otherwise inject+ /// arbitrary shell into the parent session.pub fn inherit_from_env() -> Self {use worktrunk::shell_exec::{DIRECTIVE_CD_FILE_ENV_VAR, DIRECTIVE_FILE_ENV_VAR};- let read = |var: &str| {- std::env::var_os(var)- .map(std::path::PathBuf::from)- .filter(|p| !p.as_os_str().is_empty())- };Self {- cd_file: read(DIRECTIVE_CD_FILE_ENV_VAR),- legacy_file: read(DIRECTIVE_FILE_ENV_VAR),+ cd_file: read_directive_env(DIRECTIVE_CD_FILE_ENV_VAR),+ exec_file: None,+ legacy_file: read_directive_env(DIRECTIVE_FILE_ENV_VAR),+ }+ }++ /// Like [`Self::inherit_from_env`] but also passes the EXEC directive+ /// file through. Used only for user-source aliases: the body lives in the+ /// user's own config, so a nested `wt --execute` is no different from the+ /// user typing the same command at the top level. See issue #2101.+ pub fn inherit_from_env_with_exec() -> Self {+ use worktrunk::shell_exec::DIRECTIVE_EXEC_FILE_ENV_VAR;+ Self {+ exec_file: read_directive_env(DIRECTIVE_EXEC_FILE_ENV_VAR),+ ..Self::inherit_from_env()}}}+fn read_directive_env(var: &str) -> Option<std::path::PathBuf> {+ std::env::var_os(var)+ .map(std::path::PathBuf::from)+ .filter(|p| !p.as_os_str().is_empty())+}+#[cfg(test)]mod tests {use super::*;diff --git a/src/shell_exec.rs b/src/shell_exec.rsindex 8b145c52f..8cd2e6f99 100644--- a/src/shell_exec.rs+++ b/src/shell_exec.rs@@ -305,9 +305,10 @@ pub const DIRECTIVE_CD_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_CD_FILE";/// Shell wrappers set this to a temp file; wt writes shell commands (e.g. the/// body of `wt switch --execute`) to it and the wrapper sources the file after/// wt exits, so the command runs in the user's interactive shell. Because the-/// file contents are arbitrary shell, wt scrubs this from alias/hook child-/// environments — a hook body writing to this file could inject shell into-/// the parent shell. Only trusted wt-internal callers write to it.+/// file contents are arbitrary shell, wt scrubs this from project-alias and+/// hook child environments — a body authored in shared config could inject+/// shell into the parent shell. User-source aliases re-add it (issue #2101)+/// since the body is user-authored just like a top-level `wt --execute`.pub const DIRECTIVE_EXEC_FILE_ENV_VAR: &str = "WORKTRUNK_DIRECTIVE_EXEC_FILE";/// Legacy pre-split directive file env var. Honored for one release so users@@ -620,9 +621,14 @@ pub struct Cmd {/// When set, re-adds `WORKTRUNK_DIRECTIVE_CD_FILE` after the security scrub/// in `apply_common_settings`. Used by aliases and foreground hooks — their/// shell bodies may emit cd directives (the file holds a raw path, no shell- /// injection surface). `WORKTRUNK_DIRECTIVE_EXEC_FILE` is NEVER re-added,- /// so alias/hook bodies cannot inject arbitrary shell into the parent.+ /// injection surface).directive_cd_file: Option<std::path::PathBuf>,+ /// When set, re-adds `WORKTRUNK_DIRECTIVE_EXEC_FILE` after the security+ /// scrub. Set only by user-source aliases (issue #2101): the body is the+ /// user's own config, so a nested `wt --execute` is no different from the+ /// user typing it at the top level. Project aliases and hooks must NEVER+ /// set this — they could inject arbitrary shell into the parent session.+ directive_exec_file: Option<std::path::PathBuf>,/// When set, re-adds the legacy `WORKTRUNK_DIRECTIVE_FILE` env var. Used in/// legacy-wrapper compat mode to preserve pre-split behavior for alias/hook/// bodies running under an old shell wrapper.@@ -671,6 +677,7 @@ impl Cmd {forward_signals: false,external_label: None,directive_cd_file: None,+ directive_exec_file: None,directive_legacy_file: None,}}@@ -894,15 +901,25 @@ impl Cmd {/// contexts (aliases, foreground hooks) where the child should be able/// to request a directory change. It is always safe to pass through: the/// file holds a raw path, not shell, so there is no injection surface.- ///- /// `WORKTRUNK_DIRECTIVE_EXEC_FILE` is intentionally *not* exposed by any- /// `Cmd` method — only wt-internal Rust code writes arbitrary shell- /// directives, so no child process ever needs the env var.pub fn directive_cd_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {self.directive_cd_file = Some(path.into());self}+ /// Pass the EXEC directive file through to the child process.+ ///+ /// Re-adds `WORKTRUNK_DIRECTIVE_EXEC_FILE`, allowing the child to request+ /// arbitrary shell execution in the parent shell (the wrapper sources the+ /// file after wt exits). This is only safe when the child's command body+ /// is itself trusted user-authored input — currently just user-source+ /// aliases, where the alias body lives in the user's own config and+ /// nesting `wt --execute` is no different from the user typing it. Project+ /// aliases and hooks must not call this — see issue #2101.+ pub fn directive_exec_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {+ self.directive_exec_file = Some(path.into());+ self+ }+/// Pass the legacy (pre-split) directive file through to the child process.////// Used only in legacy-wrapper compat mode. Preserves pre-split behavior@@ -930,7 +947,9 @@ impl Cmd {"Cmd::shell() commands must use .stream(), not .run()");debug_assert!(- self.directive_cd_file.is_none() && self.directive_legacy_file.is_none(),+ self.directive_cd_file.is_none()+ && self.directive_exec_file.is_none()+ && self.directive_legacy_file.is_none(),"directive_*_file is only applied by .stream(), not .run()");@@ -1036,8 +1055,10 @@ impl Cmd {);debug_assert!(self.directive_cd_file.is_none()+ && self.directive_exec_file.is_none()&& self.directive_legacy_file.is_none()&& next.directive_cd_file.is_none()+ && next.directive_exec_file.is_none()&& next.directive_legacy_file.is_none(),"directive_*_file is only applied by .stream(), not pipe_into");@@ -1188,10 +1209,15 @@ impl Cmd {// Re-add directive files after security scrub for trusted contexts.// CD file is always safe to pass through (raw path, no shell). EXEC- // file is never re-added — alias/hook bodies must not inject shell.+ // file is only re-added for user-source aliases (issue #2101); project+ // aliases and hooks leave it scrubbed so their bodies cannot inject+ // shell into the parent session.if let Some(ref path) = self.directive_cd_file {cmd.env(DIRECTIVE_CD_FILE_ENV_VAR, path);}+ if let Some(ref path) = self.directive_exec_file {+ cmd.env(DIRECTIVE_EXEC_FILE_ENV_VAR, path);+ }if let Some(ref path) = self.directive_legacy_file {cmd.env(DIRECTIVE_FILE_ENV_VAR, path);}diff --git a/tests/integration_tests/step_alias.rs b/tests/integration_tests/step_alias.rsindex 974909648..b33e95624 100644--- a/tests/integration_tests/step_alias.rs+++ b/tests/integration_tests/step_alias.rs@@ -802,6 +802,172 @@ new-branch = "'{wt_toml}' switch --create alias-created");}+/// User-source aliases pass the EXEC directive file through to the body, so a+/// nested `wt switch --execute X` writes the payload back to the parent+/// shell's EXEC file the same as a top-level `wt switch --execute X` would.+///+/// Regression test for #2101: the conservative scrub used to refuse `--execute`+/// inside any alias body, breaking workflows like `issue = "wt switch --create+/// {{ args[0] }} --execute claude"` even when the alias lived in user config.+#[rstest]+fn test_user_alias_passes_exec_directive(repo: TestRepo) {+ repo.commit("initial");+ let wt = wt_bin();+ let wt_str = wt.to_string_lossy();+ assert!(+ !wt_str.contains('\''),+ "wt binary path should not contain single quotes: {wt_str}"+ );+ let wt_toml = wt_str.replace('\\', r"\\");++ repo.write_test_config(&format!(+ r#"+[aliases]+exec-passthrough = "'{wt_toml}' switch --create user-alias-target --execute 'echo from-user-alias'"+"#+ ));++ let (cd_path, exec_path, _guard) = directive_files();++ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ cmd.args(["step", "exec-passthrough"]);+ let output = cmd.output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "wt step exec-passthrough failed: stdout={}\nstderr={stderr}",+ String::from_utf8_lossy(&output.stdout),+ );+ assert!(+ !stderr.contains("disabled inside"),+ "user alias should not trip the EXEC scrub warning, got: {stderr}"+ );++ let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();+ assert!(+ exec_content.contains("echo from-user-alias"),+ "EXEC file should contain the alias's --execute payload, got: {exec_content:?}"+ );+}++/// Project-source aliases keep the conservative EXEC scrub: a nested+/// `wt switch --execute X` is refused with a warning pointing at the tracking+/// issue. The body is shared config, so allowing it would let the project+/// inject arbitrary shell into every contributor's interactive session.+#[rstest]+fn test_project_alias_scrubs_exec_directive(repo: TestRepo) {+ repo.commit("initial");+ let wt = wt_bin();+ let wt_str = wt.to_string_lossy();+ assert!(+ !wt_str.contains('\''),+ "wt binary path should not contain single quotes: {wt_str}"+ );+ let wt_toml = wt_str.replace('\\', r"\\");++ repo.write_project_config(&format!(+ r#"+[aliases]+exec-blocked = "'{wt_toml}' switch --create project-alias-target --execute 'echo should-not-pass'"+"#+ ));++ let (cd_path, exec_path, _guard) = directive_files();++ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ // -y skips the project-alias approval prompt.+ cmd.args(["-y", "step", "exec-blocked"]);+ let output = cmd.output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "wt -y step exec-blocked failed: stdout={}\nstderr={stderr}",+ String::from_utf8_lossy(&output.stdout),+ );+ assert!(+ stderr.contains("disabled inside project alias"),+ "project alias should warn that --execute is disabled, got: {stderr}"+ );+ assert!(+ stderr.contains("issues/2101"),+ "warning should link the tracking issue, got: {stderr}"+ );++ let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();+ assert!(+ !exec_content.contains("should-not-pass"),+ "EXEC file should NOT contain the scrubbed payload, got: {exec_content:?}"+ );+}++/// Same alias name in both user and project configs: EXEC passes through for+/// the user-source step but is scrubbed for the project-source step.+///+/// EXEC passthrough is a per-step decision driven by `HookSource` on each+/// `SourcedStep`, not a per-pipeline scrub. When both sources define the+/// alias, both run (user first, then project) — the user's own step still+/// gets the relaxation, and the project-authored step keeps the conservative+/// scrub even though it's part of the same merged body.+#[rstest]+fn test_user_and_project_alias_collision_scrubs_only_project_step(repo: TestRepo) {+ repo.commit("initial");+ let wt = wt_bin();+ let wt_str = wt.to_string_lossy();+ assert!(+ !wt_str.contains('\''),+ "wt binary path should not contain single quotes: {wt_str}"+ );+ let wt_toml = wt_str.replace('\\', r"\\");++ repo.write_test_config(&format!(+ r#"+[aliases]+shared = "'{wt_toml}' switch --create user-step-target --execute 'echo from-user-step'"+"#+ ));+ // Project step also tries `--execute` so we can assert its payload is+ // scrubbed even though the user step's payload passes through.+ repo.write_project_config(&format!(+ r#"+[aliases]+shared = "'{wt_toml}' switch --create project-step-target --execute 'echo from-project-step'"+"#,+ ));++ let (cd_path, exec_path, _guard) = directive_files();++ let mut cmd = repo.wt_command();+ configure_directive_files(&mut cmd, &cd_path, &exec_path);+ // -y skips the project-alias approval prompt.+ cmd.args(["-y", "step", "shared"]);+ let output = cmd.output().unwrap();++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "wt -y step shared failed: stdout={}\nstderr={stderr}",+ String::from_utf8_lossy(&output.stdout),+ );+ assert!(+ stderr.contains("disabled inside project alias"),+ "project-source step should still warn that --execute is disabled, got: {stderr}"+ );++ let exec_content = std::fs::read_to_string(&exec_path).unwrap_or_default();+ assert!(+ exec_content.contains("from-user-step"),+ "EXEC file should contain the user step's payload (per-step relaxation), got: {exec_content:?}"+ );+ assert!(+ !exec_content.contains("from-project-step"),+ "EXEC file should NOT contain the project step's payload (per-step scrub), got: {exec_content:?}"+ );+}+/// Alias subprocesses inherit the parent's stdin so interactive children/// (e.g. `wt switch`'s picker) keep the controlling terminal.///diff --git a/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap b/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snapindex a590aa63f..3b10e6fa2 100644--- a/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap+++ b/tests/snapshots/integration__integration_tests__directives__switch_exec_scrubbed_warns.snap@@ -50,5 +50,5 @@ exit_code: 0----- stderr -----[32m✓[39m [32mCreated branch [1mscrub-test[22m from [1mmain[22m and worktree @ [1m_REPO_.scrub-test[22m[39m[2m↳[22m [2mTo customize worktree locations, run [4mwt config create[24m[22m-[33m▲[39m [33m[1m--execute[22m disabled inside alias/hook bodies for safety; skipping [1mecho should-not-run[22m[39m-[2m↳[22m [2mThis is extremely conservative; comment at [4mhttps://github.com/max-sixty/worktrunk/issues/2101[24m if this affects you[22m+[33m▲[39m [33m[1m--execute[22m disabled inside project alias / hook bodies for safety; skipping [1mecho should-not-run[22m[39m+[2m↳[22m [2mUser-source aliases allow it. Comment at [4mhttps://github.com/max-sixty/worktrunk/issues/2101[24m if you need it for project aliases or hooks[22m