Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(shell): register completions under the `--cmd` name, not clap's (#3817)
Worktrunk Bot96c6c846f778
diff --git a/docs/content/config.md b/docs/content/config.mdindex f84784b0b..3843c007e 100644--- a/docs/content/config.md+++ b/docs/content/config.md@@ -667,6 +667,7 @@ Override the LLM command in CI to use a mock:| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file || `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |+| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) || `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach || `RUST_LOG` | Logging directive (e.g. `worktrunk=debug`); overrides the verbosity baseline for what reaches stderr |diff --git a/plugins/worktrunk/skills/worktrunk/reference/config.md b/plugins/worktrunk/skills/worktrunk/reference/config.mdindex 22b75abc2..0413ba8c7 100644--- a/plugins/worktrunk/skills/worktrunk/reference/config.md+++ b/plugins/worktrunk/skills/worktrunk/reference/config.md@@ -664,6 +664,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file || `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |+| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) || `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach || `RUST_LOG` | Logging directive (e.g. `worktrunk=debug`); overrides the verbosity baseline for what reaches stderr |diff --git a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.mdindex d19dfdadb..615cc8fa1 100644--- a/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md+++ b/plugins/worktrunk/skills/worktrunk/reference/shell-integration.md@@ -273,6 +273,7 @@ If you see path issues, ensure you're using a recent Git for Windows version.| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Set by shell wrapper; wt writes shell commands, wrapper sources the file || `WORKTRUNK_BIN` | Override binary path (for testing dev builds) || `WORKTRUNK_SHELL` | Set by the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |+| `WORKTRUNK_COMPLETE_NAME` | Set by the bash, zsh, and PowerShell wrappers when they load completions; names the command the registration binds to, so `--cmd` integrations complete |## See Alsodiff --git a/skills/worktrunk/reference/config.md b/skills/worktrunk/reference/config.mdindex 22b75abc2..0413ba8c7 100644--- a/skills/worktrunk/reference/config.md+++ b/skills/worktrunk/reference/config.md@@ -664,6 +664,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file || `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |+| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) || `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach || `RUST_LOG` | Logging directive (e.g. `worktrunk=debug`); overrides the verbosity baseline for what reaches stderr |diff --git a/skills/worktrunk/reference/shell-integration.md b/skills/worktrunk/reference/shell-integration.mdindex d19dfdadb..615cc8fa1 100644--- a/skills/worktrunk/reference/shell-integration.md+++ b/skills/worktrunk/reference/shell-integration.md@@ -273,6 +273,7 @@ If you see path issues, ensure you're using a recent Git for Windows version.| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Set by shell wrapper; wt writes shell commands, wrapper sources the file || `WORKTRUNK_BIN` | Override binary path (for testing dev builds) || `WORKTRUNK_SHELL` | Set by the PowerShell (`powershell`) and fish (`fish`) wrappers; selects how wt escapes the EXEC directive payload for that shell |+| `WORKTRUNK_COMPLETE_NAME` | Set by the bash, zsh, and PowerShell wrappers when they load completions; names the command the registration binds to, so `--cmd` integrations complete |## See Alsodiff --git a/src/cli/mod.rs b/src/cli/mod.rsindex d629ac604..c84b0f7f9 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -2555,6 +2555,7 @@ $ WORKTRUNK_COMMIT__GENERATION__COMMAND="echo 'test: automated commit'" wt merge| `WORKTRUNK_DIRECTIVE_EXEC_FILE` | Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file || `WORKTRUNK_SHELL_CWD` | Internal: set by wt on alias and hook bodies, so a nested `wt` preserves the user's subdirectory || `WORKTRUNK_SHELL` | Internal: set by shell wrappers to indicate shell type (e.g., `powershell`) |+| `WORKTRUNK_COMPLETE_NAME` | Internal: set by shell wrappers to the command name completions register under (defaults to the binary name) || `WORKTRUNK_MAX_CONCURRENT_COMMANDS` | Max parallel git commands (default: 32). Lower if hitting file descriptor limits. || `WORKTRUNK_VERBOSE` | Verbosity level (`0`/`1`/`2`), like `-v`/`-vv` but applied everywhere — including shell completion, which no flag can reach || `RUST_LOG` | Logging directive (e.g. `worktrunk=debug`); overrides the verbosity baseline for what reaches stderr |diff --git a/src/commands/init.rs b/src/commands/init.rsindex d619e9444..af8765f7a 100644--- a/src/commands/init.rs+++ b/src/commands/init.rs@@ -122,7 +122,10 @@ pub fn handle_completions(shell: shell::Shell) -> anyhow::Result<()> {/// styles before the completer call means `_describe` sees them on the *first* TAB, not/// only on the second.fn make_zsh_autoload_safe(script: &str, cmd_name: &str) -> String {- let func = format!("_clap_dynamic_completer_{}", cmd_name.replace('-', "_"));+ let func = format!(+ "_clap_dynamic_completer_{}",+ shell::clap_completer_ident(cmd_name)+ );let trailing = format!("compdef {func} {cmd_name}");let replacement = format!(r#"# Single-column display keeps descriptions visually associated with each branch.diff --git a/src/completion.rs b/src/completion.rsindex ad992f29a..8b9e54752 100644--- a/src/completion.rs+++ b/src/completion.rs@@ -88,9 +88,20 @@ pub(crate) fn maybe_handle_env_completion() -> bool {// If no args after `--`, output the shell registration scriptif args.is_empty() {- // Use CompleteEnv for registration script generation+ // Use CompleteEnv for registration script generation, under the name the+ // shell integration binds — not clap's own (see `registration_name`).+ //+ // A bare `Command` is all the registration needs: clap_complete 4.6.9's+ // `write_registration` reads `cmd.get_name()` and `self.bin` (set below,+ // so its `cmd.get_bin_name()` fallback never fires), and nothing else off+ // the command. Handing it `completion_command()` instead would build the+ // whole completion tree — `Repository::current()`, both config loads, and+ // a scan of every `PATH` directory for `wt-*` — to produce one string, on+ // the first TAB of every new shell.+ let name = registration_name();let all_args: Vec<OsString> = std::env::args_os().collect();- let _ = CompleteEnv::with_factory(completion_command)+ let _ = CompleteEnv::with_factory(move || Command::new(name))+ .bin(name).try_complete(all_args, current_dir.as_deref());CONTEXT.with(|ctx| ctx.borrow_mut().take());return true;@@ -489,6 +500,48 @@ thread_local! {static CONTEXT: RefCell<Option<CompletionContext>> = const { RefCell::new(None) };}+/// The command name the registration script binds completions to.+///+/// clap derives every identifier in that script — the completer function name,+/// zsh's trailing `compdef`, bash's `complete -F`, PowerShell's+/// `Register-ArgumentCompleter -CommandName` — from its own `Command` name,+/// which is the compile-time `wt`. The shell integration can be generated for a+/// different name (`wt config shell init --cmd git-wt`, or a binary installed+/// under another name), and then the generated loader guards on and calls a+/// function the registration never defines: nothing completes, and since the+/// guard never becomes true the script is regenerated on every TAB (#3816).+/// zsh's trailing `compdef` is worse than inert — it hands worktrunk's+/// completer to whatever name it carries, i.e. to the *other* `wt` that+/// `--cmd` exists to step around.+///+/// So the generated loader passes the name it bound in `WORKTRUNK_COMPLETE_NAME`+/// and the registration is emitted under that name. The fallback is+/// [`crate::binary_name`], which covers a binary installed as `git-wt` and+/// invoked directly.+///+/// Both arms are validated, because both end up embedded verbatim in generated+/// shell code and neither has necessarily been through the `--cmd` gate:+/// `binary_name` is `argv[0]`'s file stem, so a binary installed under a name+/// outside the allowlist would otherwise emit `complete -F _clap_complete_<name>`+/// with an identifier the shell can't parse — completions would silently do+/// nothing rather than fall back. `handle_completions` in `src/commands/init.rs`+/// validates `binary_name` for the same reason before writing a registration.+/// A rejected env var still defers to the binary name, which is the more useful+/// answer than the constant; only a binary name that also fails lands on `wt`.+///+/// Leaked because `Command::name` takes a `clap::builder::Str`, which borrows+/// unless clap's `string` feature is on — the same trade `build_hook_completion_command`+/// makes. One small allocation in a process that writes the script and exits.+fn registration_name() -> &'static str {+ let is_valid = |name: &String| worktrunk::shell::validate_shell_command_name(name).is_ok();+ let name = std::env::var("WORKTRUNK_COMPLETE_NAME")+ .ok()+ .filter(is_valid)+ .or_else(|| Some(crate::binary_name()).filter(is_valid))+ .unwrap_or_else(|| "wt".to_string());+ Box::leak(name.into_boxed_str())+}+fn completion_command() -> Command {let cmd = cli::build_command();let cmd = inject_alias_subcommands(cmd);diff --git a/src/shell/mod.rs b/src/shell/mod.rsindex ba8870593..81e63369e 100644--- a/src/shell/mod.rs+++ b/src/shell/mod.rs@@ -267,11 +267,15 @@ impl ShellInit {let template = BashTemplate {shell_name: self.shell.to_string(),cmd: &self.cmd,+ cmd_ident: clap_completer_ident(&self.cmd),};template.render()}Shell::Zsh => {- let template = ZshTemplate { cmd: &self.cmd };+ let template = ZshTemplate {+ cmd: &self.cmd,+ cmd_ident: clap_completer_ident(&self.cmd),+ };template.render()}Shell::Fish => {@@ -300,12 +304,30 @@ impl ShellInit {}}+/// Suffix of the completer function clap names its registration script after.+///+/// clap builds it as `<prefix><command name with '-' replaced by '_'>`+/// (`_clap_complete_git_wt`, `_clap_dynamic_completer_git_wt`), so the lazy+/// loader in the bash and zsh templates has to apply the same escaping to guard+/// on and call the function the registration actually defines. The registration+/// is emitted under this command name via `WORKTRUNK_COMPLETE_NAME`, which the+/// templates set on the eval — see `registration_name` in `src/completion.rs`.+///+/// This is the one place the rule is encoded: `make_zsh_autoload_safe` in+/// `src/commands/init.rs` rewrites the same function name in clap's zsh+/// registration and calls here for it, so a change to clap's escaping is one+/// edit rather than two sites that can drift apart silently.+pub fn clap_completer_ident(cmd: &str) -> String {+ cmd.replace('-', "_")+}+/// Bash shell template#[derive(Template)]#[template(path = "bash.sh", escape = "none")]struct BashTemplate<'a> {shell_name: String,cmd: &'a str,+ cmd_ident: String,}/// Zsh shell template@@ -313,6 +335,7 @@ struct BashTemplate<'a> {#[template(path = "zsh.zsh", escape = "none")]struct ZshTemplate<'a> {cmd: &'a str,+ cmd_ident: String,}/// Fish shell template (full function for `wt config shell init fish`)diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snapindex ae7f5b93f..5cd32aa25 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_bash.snap@@ -71,7 +71,10 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `wt` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="wt" COMPLETE=bash command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || returnfi_clap_complete_wt "$@"}diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snapindex 8bc428e34..10782b384 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_powershell.snap@@ -103,6 +103,10 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {$wtBinForComplete = (Get-Command wt -CommandType Application | Select-Object -First 1).Source}$env:COMPLETE = "powershell"+ # Register under the name this integration binds. clap names its+ # Register-ArgumentCompleter target after its own command name, so without+ # this the --cmd name is never registered and nothing completes (#3816).+ $env:WORKTRUNK_COMPLETE_NAME = "wt"try {# Capture output first, then pipe - avoids "Cannot run a document in the middle of a pipeline"# error that can occur in some PowerShell configurations/terminals@@ -116,5 +120,6 @@ if ((Get-Command wt -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {}finally {Remove-Item Env:\COMPLETE -ErrorAction SilentlyContinue+ Remove-Item Env:\WORKTRUNK_COMPLETE_NAME -ErrorAction SilentlyContinue}}diff --git a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snapindex 60b3a851f..0c9b69413 100644--- a/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__init_zsh.snap@@ -74,7 +74,10 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `wt` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="wt" COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || returnfi_clap_dynamic_completer_wt "$@"}diff --git a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snapindex 2ba0dae08..5db2aad6b 100644--- a/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap+++ b/src/shell/snapshots/worktrunk__shell__tests__shell_init_with_custom_prefix.snap@@ -71,7 +71,10 @@ if command -v custom >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `custom` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-custom}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="custom" COMPLETE=bash command "${WORKTRUNK_BIN:-custom}" 2>/dev/null)" || returnfi_clap_complete_custom "$@"}diff --git a/templates/bash.sh b/templates/bash.shindex 16ce0a40a..8cef38d9e 100644--- a/templates/bash.sh+++ b/templates/bash.sh@@ -63,13 +63,16 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Lazy completions - generate on first TAB, then delegate to clap's completer_{{ cmd }}_lazy_complete() {# Generate completions function once (check if clap's function exists)- if ! declare -F _clap_complete_{{ cmd }} >/dev/null; then+ if ! declare -F _clap_complete_{{ cmd_ident }} >/dev/null; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `{{ cmd }}` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="{{ cmd }}" COMPLETE=bash command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || returnfi- _clap_complete_{{ cmd }} "$@"+ _clap_complete_{{ cmd_ident }} "$@"}complete -o nospace -o bashdefault -F _{{ cmd }}_lazy_complete {{ cmd }}diff --git a/templates/powershell.ps1 b/templates/powershell.ps1index 6117465f5..1dad924c2 100644--- a/templates/powershell.ps1+++ b/templates/powershell.ps1@@ -99,6 +99,10 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN$wtBinForComplete = (Get-Command {{ cmd }} -CommandType Application | Select-Object -First 1).Source}$env:COMPLETE = "powershell"+ # Register under the name this integration binds. clap names its+ # Register-ArgumentCompleter target after its own command name, so without+ # this the --cmd name is never registered and nothing completes (#3816).+ $env:WORKTRUNK_COMPLETE_NAME = "{{ cmd }}"try {# Capture output first, then pipe - avoids "Cannot run a document in the middle of a pipeline"# error that can occur in some PowerShell configurations/terminals@@ -112,5 +116,6 @@ if ((Get-Command {{ cmd }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN}finally {Remove-Item Env:\COMPLETE -ErrorAction SilentlyContinue+ Remove-Item Env:\WORKTRUNK_COMPLETE_NAME -ErrorAction SilentlyContinue}}diff --git a/templates/zsh.zsh b/templates/zsh.zshindex 1318a1cd7..cbdc44a0f 100644--- a/templates/zsh.zsh+++ b/templates/zsh.zsh@@ -66,13 +66,16 @@ if command -v {{ cmd }} >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Lazy completions - generate on first TAB, then delegate to clap's completer_{{ cmd }}_lazy_complete() {# Generate completions function once (check if clap's function exists)- if ! (( $+functions[_clap_dynamic_completer_{{ cmd }}] )); then+ if ! (( $+functions[_clap_dynamic_completer_{{ cmd_ident }}] )); then# Use `command` to bypass the shell function and call the binary directly.# Without this, `{{ cmd }}` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="{{ cmd }}" COMPLETE=zsh command "${WORKTRUNK_BIN:-{{ cmd }}}" 2>/dev/null)" || returnfi- _clap_dynamic_completer_{{ cmd }} "$@"+ _clap_dynamic_completer_{{ cmd_ident }} "$@"}# Register completion (silently skip if compinit hasn't run yet).diff --git a/tests/integration_tests/completion.rs b/tests/integration_tests/completion.rsindex c7586fbac..68edae431 100644--- a/tests/integration_tests/completion.rs+++ b/tests/integration_tests/completion.rs@@ -2219,3 +2219,178 @@ printf '%s\n%s\n%s' '--custom-flag' '--another' "retired:${WORKTRUNK_DIRECTIVE_F"the retired directive file must remain untouched");}++/// Regression for #3816: `config shell init --cmd <name>` must generate a+/// completion loader whose clap-derived identifiers match the ones the binary+/// emits at TAB time.+///+/// The loader is lazy — the first TAB evals `COMPLETE=<shell> <binary>` and+/// then calls clap's completer function. clap derives that function's name+/// from its own `Command` name, so before the fix the loader guarded on and+/// called `_clap_complete_wot` while the eval only ever defined+/// `_clap_complete_wt`: nothing completed, and because the guard never became+/// true the script was re-generated and re-evaluated on every TAB.+///+/// Driven through a real bash so the whole chain is exercised: init output →+/// loader function → eval → clap's completer must exist afterwards.+#[cfg(unix)]+#[rstest]+#[case("wot", "_clap_complete_wot")]+// A `-` is not valid in a clap-escaped function name, so the documented+// `--cmd=git-wt` case needs the same `-` → `_` escaping clap applies.+#[case("git-wt", "_clap_complete_git_wt")]+fn test_init_custom_cmd_defines_clap_completer_in_bash(+ #[case] cmd_name: &str,+ #[case] clap_fn: &str,+) {+ let wt = crate::common::wt_bin();+ let wt = wt.to_str().unwrap();+ let script = format!(+ r#"export WORKTRUNK_BIN="{wt}"+eval "$("{wt}" config shell init bash --cmd {cmd_name})"+COMP_WORDS=({cmd_name} ""); COMP_CWORD=1+_{cmd_name}_lazy_complete {cmd_name} "" {cmd_name} >/dev/null 2>&1+declare -F {clap_fn} >/dev/null && echo DEFINED || echo MISSING+"#+ );++ let output = std::process::Command::new("bash")+ .arg("-c")+ .arg(&script)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(+ stdout.contains("DEFINED"),+ "`--cmd {cmd_name}` loader must define {clap_fn} after its lazy eval, got:\n{stdout}\n----- stderr -----\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+}++/// Companion to the bash end-to-end test above, for the shells that can't be+/// driven from CI. The registration the binary emits must name the command the+/// shell integration was generated for, not clap's own `wt`.+///+/// zsh's registration also ends with `compdef <completer> <cmd>`, which binds+/// worktrunk's completer to whatever name it carries — with clap's `wt` that+/// hijacked completions for the *other* `wt` on PATH, the exact conflict+/// `--cmd` exists to avoid.+#[rstest]+#[case(+ "zsh",+ "wot",+ "_clap_dynamic_completer_wot",+ "compdef _clap_dynamic_completer_wot wot"+)]+#[case(+ "zsh",+ "git-wt",+ "_clap_dynamic_completer_git_wt",+ "compdef _clap_dynamic_completer_git_wt git-wt"+)]+#[case("bash", "wot", "_clap_complete_wot", "-F _clap_complete_wot wot")]+#[case("powershell", "wot", "Register-ArgumentCompleter", "-CommandName wot")]+fn test_completion_registration_uses_shell_integration_cmd_name(+ #[case] shell: &str,+ #[case] cmd_name: &str,+ #[case] completer_fn: &str,+ #[case] registration: &str,+) {+ // The generated init script must reference the same identifier…+ let init = wt_command()+ .args(["config", "shell", "init", shell, "--cmd", cmd_name])+ .output()+ .unwrap();+ let init_stdout = String::from_utf8_lossy(&init.stdout);+ if shell != "powershell" {+ assert!(+ init_stdout.contains(completer_fn),+ "{shell}: init --cmd {cmd_name} should reference {completer_fn}, got:\n{init_stdout}"+ );+ }++ // …that the binary actually defines when the loader evals it.+ let output = wt_command()+ .env("COMPLETE", shell)+ .env("WORKTRUNK_COMPLETE_NAME", cmd_name)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(+ stdout.contains(completer_fn),+ "{shell}: registration should define {completer_fn}, got:\n{stdout}"+ );+ assert!(+ stdout.contains(registration),+ "{shell}: registration should bind via `{registration}`, got:\n{stdout}"+ );+}++/// `WORKTRUNK_COMPLETE_NAME` lands verbatim in generated shell code, so it is+/// validated before it gets there. wt's own shell integration only ever sets it+/// to a name `--cmd` already validated; a value outside the allowlist means+/// something else set it, and the registration falls back to the binary name+/// rather than emitting an unusable — or injected — identifier.+#[rstest]+#[case("wt; rm -rf /")]+#[case("wt$(id)")]+#[case("git wt")]+#[case("-wt")]+#[case("")]+fn test_completion_registration_rejects_invalid_complete_name(#[case] name: &str) {+ let output = wt_command()+ .env("COMPLETE", "bash")+ .env("WORKTRUNK_COMPLETE_NAME", name)+ .output()+ .unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(+ stdout.contains("-F _clap_complete_wt wt"),+ "an invalid WORKTRUNK_COMPLETE_NAME ({name:?}) must fall back to the binary name, got:\n{stdout}"+ );+ assert!(+ name.is_empty() || !stdout.contains(name),+ "a rejected WORKTRUNK_COMPLETE_NAME ({name:?}) must not reach the generated script:\n{stdout}"+ );+}++/// The binary-name fallback is validated for the same reason the env var is:+/// it is `argv[0]`'s file stem, which no `--cmd` gate has seen. A binary+/// installed under a name outside the allowlist would otherwise register+/// `complete -F _clap_complete_<name>` with an identifier bash can't parse, so+/// the last resort is the compile-time `wt`.+///+/// Unix-only because it needs a symlink named for the invalid case; the+/// validation itself is platform-independent.+#[cfg(unix)]+#[rstest]+fn test_completion_registration_falls_back_when_binary_name_is_invalid() {+ let dir = tempfile::tempdir().unwrap();+ let link = dir.path().join("wt+odd");+ std::os::unix::fs::symlink(crate::common::wt_bin(), &link).unwrap();++ // Borrow the isolated environment `wt_command` sets up — only the program+ // itself differs, and `Command` can't have its program swapped.+ let template = wt_command();+ let mut cmd = std::process::Command::new(&link);+ for (key, value) in template.get_envs() {+ match value {+ Some(value) => cmd.env(key, value),+ None => cmd.env_remove(key),+ };+ }+ if let Some(cwd) = template.get_current_dir() {+ cmd.current_dir(cwd);+ }++ let output = cmd.env("COMPLETE", "bash").output().unwrap();+ let stdout = String::from_utf8_lossy(&output.stdout);++ assert!(+ stdout.contains("-F _clap_complete_wt wt"),+ "an invalid binary name must fall back to `wt`, got:\n{stdout}"+ );+}diff --git a/tests/snapshots/integration__integration_tests__help__help_config_long.snap b/tests/snapshots/integration__integration_tests__help__help_config_long.snapindex 51d170829..ddf5651a0 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_long.snap@@ -649,6 +649,7 @@ Override the LLM command in CI to use a mock:[2mWORKTRUNK_DIRECTIVE_EXEC_FILE[0m Internal: set by shell wrappers. wt writes shell commands; the wrapper sources the file[2mWORKTRUNK_SHELL_CWD[0m Internal: set by wt on alias and hook bodies, so a nested [2mwt[0m preserves the user's subdirectory[2mWORKTRUNK_SHELL[0m Internal: set by shell wrappers to indicate shell type (e.g., [2mpowershell[0m)+ [2mWORKTRUNK_COMPLETE_NAME[0m Internal: set by shell wrappers to the command name completions register under (defaults to the binary name)[2mWORKTRUNK_MAX_CONCURRENT_COMMANDS[0m Max parallel git commands (default: 32). Lower if hitting file descriptor limits.[2mWORKTRUNK_VERBOSE[0m Verbosity level ([2m0[0m/[2m1[0m/[2m2[0m), like [2m-v[0m/[2m-vv[0m but applied everywhere — including shell completion, which no flag can reach[2mRUST_LOG[0m Logging directive (e.g. [2mworktrunk=debug[0m); overrides the verbosity baseline for what reaches stderrdiff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex a2587f3b4..a55299e4d 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -115,7 +115,10 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `wt` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=bash command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="wt" COMPLETE=bash command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || returnfi_clap_complete_wt "$@"}diff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 0f2f52678..8d2b8ef50 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -118,7 +118,10 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# Use `command` to bypass the shell function and call the binary directly.# Without this, `wt` would call the shell function which evals# the completion script internally but doesn't re-emit it.- eval "$(COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || return+ # WORKTRUNK_COMPLETE_NAME emits the registration under the name bound+ # below; clap would otherwise name everything after its own command+ # name and the call below would hit an undefined function (#3816).+ eval "$(WORKTRUNK_COMPLETE_NAME="wt" COMPLETE=zsh command "${WORKTRUNK_BIN:-wt}" 2>/dev/null)" || returnfi_clap_dynamic_completer_wt "$@"}