Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Improve shell integration detection robustness (#362)

Maximilian Roosa18f9a3a6c48
diff --git a/Cargo.lock b/Cargo.lock
index 090a13e85..4c8c69eef 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2629,6 +2629,12 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
+[[package]]
+name = "urlencoding"
+version = "2.1.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da"
+
[[package]]
name = "utf8parse"
version = "0.2.2"
@@ -3145,6 +3151,7 @@ dependencies = [
"tree-sitter-bash",
"tree-sitter-highlight",
"unicode-width 0.2.2",
+ "urlencoding",
"vergen-gitcl",
"vt100",
"which 8.0.0",
diff --git a/Cargo.toml b/Cargo.toml
index c90e44c62..5e952e08a 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -110,6 +110,7 @@ which = "8.0"
dunce = "1.0"
termimad = "0.34.1"
rayon-join-macro = "0.1.1"
+urlencoding = "2.1"
[target.'cfg(unix)'.dependencies]
skim = "0.20"
diff --git a/src/commands/config.rs b/src/commands/config.rs
index 073f0971d..e0b89f98e 100644
--- a/src/commands/config.rs
+++ b/src/commands/config.rs
@@ -7,10 +7,10 @@ use worktrunk::config::WorktrunkConfig;
use worktrunk::config::{find_unknown_project_keys, find_unknown_user_keys};
use worktrunk::git::Repository;
use worktrunk::path::format_path_for_display;
-use worktrunk::shell::Shell;
+use worktrunk::shell::{Shell, scan_for_detection_details};
use worktrunk::styling::{
- error_message, format_heading, format_toml, format_with_gutter, hint_message, info_message,
- progress_message, success_message, warning_message,
+ error_message, format_bash_with_gutter, format_heading, format_toml, format_with_gutter,
+ hint_message, info_message, progress_message, success_message, warning_message,
};
use worktrunk::utils::get_now;
@@ -357,7 +357,11 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
}
};
+ // Get detection details to show matched lines inline
+ let detection_results = scan_for_detection_details(&cmd).unwrap_or_default();
+
let mut any_not_configured = false;
+ let mut has_any_unmatched = false;
// Show configured and not-configured shells (matching `config shell install` format exactly)
// Bash/Zsh: inline completions, show "shell extension & completions"
@@ -374,14 +378,37 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
match result.action {
ConfigAction::AlreadyExists => {
+ // Show the matched lines directly under this status
+ let detection = detection_results
+ .iter()
+ .find(|d| d.path == result.path && !d.matched_lines.is_empty());
+
+ // Build file:line location (clickable in terminals)
+ let location = if let Some(det) = detection {
+ let line_nums: Vec<_> = det
+ .matched_lines
+ .iter()
+ .map(|d| d.line_number.to_string())
+ .collect();
+ format!("{}:{}", path, line_nums.join(","))
+ } else {
+ path.to_string()
+ };
+
writeln!(
out,
"{}",
info_message(cformat!(
- "Already configured {what} for <bold>{shell}</> @ {path}"
+ "Already configured {what} for <bold>{shell}</> @ {location}"
))
)?;
+ if let Some(det) = detection {
+ for detected in &det.matched_lines {
+ writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;
+ }
+ }
+
// Check if zsh has compinit enabled (required for completions)
if matches!(shell, Shell::Zsh) && check_zsh_compinit_missing() {
writeln!(
@@ -457,6 +484,68 @@ fn render_shell_status(out: &mut String) -> anyhow::Result<()> {
)?;
}
+ // Show potential false negatives (lines containing cmd but not detected)
+ for detection in &detection_results {
+ if !detection.unmatched_candidates.is_empty() {
+ has_any_unmatched = true;
+ let path = format_path_for_display(&detection.path);
+ // Build file:line location (clickable in terminals)
+ let line_nums: Vec<_> = detection
+ .unmatched_candidates
+ .iter()
+ .map(|d| d.line_number.to_string())
+ .collect();
+ let location = format!("{}:{}", path, line_nums.join(","));
+ writeln!(
+ out,
+ "{}",
+ warning_message(cformat!(
+ "Found <bold>{cmd}</> in <bold>{location}</> but not detected as integration:"
+ ))
+ )?;
+ for detected in &detection.unmatched_candidates {
+ writeln!(out, "{}", format_bash_with_gutter(detected.content.trim()))?;
+ }
+ }
+ }
+
+ // If we have unmatched candidates but no configured shells, suggest raising an issue
+ let has_any_configured = scan_result
+ .configured
+ .iter()
+ .any(|r| matches!(r.action, ConfigAction::AlreadyExists));
+ if has_any_unmatched && !has_any_configured {
+ let unmatched_summary: Vec<_> = detection_results
+ .iter()
+ .filter(|r| !r.unmatched_candidates.is_empty())
+ .flat_map(|r| {
+ r.unmatched_candidates
+ .iter()
+ .map(|d| d.content.trim().to_string())
+ })
+ .collect();
+ let body = format!(
+ "Shell integration not detected despite config containing `{cmd}`.\n\n\
+ **Unmatched lines:**\n```\n{}\n```\n\n\
+ **Expected behavior:** These lines should be detected as shell integration.",
+ unmatched_summary.join("\n")
+ );
+ let issue_url = format!(
+ "https://github.com/max-sixty/worktrunk/issues/new?title={}&body={}",
+ urlencoding::encode("Shell integration detection false negative"),
+ urlencoding::encode(&body)
+ );
+
+ writeln!(out)?;
+ writeln!(
+ out,
+ "{}",
+ hint_message(format!(
+ "If this is shell integration, report a false negative: {issue_url}"
+ ))
+ )?;
+ }
+
Ok(())
}
diff --git a/src/shell.rs b/src/shell.rs
index 3e87fe090..245be8f43 100644
--- a/src/shell.rs
+++ b/src/shell.rs
@@ -41,15 +41,79 @@ fn home_dir_required() -> Result<PathBuf, std::io::Error> {
})
}
-/// Check if a line contains shell integration for the given command.
+/// Detect if a line contains shell integration for a specific command.
///
-/// Returns true if the line:
-/// - Is not a comment (doesn't start with #)
-/// - Contains `{cmd} config shell init`
-/// - Contains an execution context (eval, source, Invoke-Expression, or conditional)
+/// # Detection Goal
///
-/// Used by both detection (is shell integration configured?) and
-/// uninstall (which lines to remove?).
+/// We need to answer: "Is shell integration configured for THIS binary?"
+///
+/// When running as `wt`, we should detect `wt` integration but NOT `git-wt` integration
+/// (and vice versa). This prevents misleading "restart shell to activate" messages when
+/// the user has integration for a different command name.
+///
+/// # Command Name Patterns
+///
+/// Users invoke worktrunk in several ways, each creating different command names:
+///
+/// | Invocation | Binary name | Function created |
+/// |-------------------------|-------------|------------------|
+/// | `wt` | `wt` | `wt()` |
+/// | `git wt` (subcommand) | `git-wt` | `git-wt()` |
+/// | `git-wt` (direct) | `git-wt` | `git-wt()` |
+///
+/// Note: `git wt` dispatches to the `git-wt` binary, so both create the same function.
+///
+/// # Detection Strategy
+///
+/// We detect shell integration by looking for eval/source lines in shell config files.
+///
+/// Lines like `eval "$(wt config shell init bash)"` in `.bashrc`/`.zshrc`.
+///
+/// **Challenge:** `wt config shell init` is a substring of `git wt config shell init`.
+///
+/// **Solution:** Use negative lookbehind to exclude `git ` and `git-` prefixes:
+/// - For `wt`: match `wt config shell init` NOT preceded by `git ` or `git-`
+/// - For `git-wt`: match `git-wt config shell init` OR `git wt config shell init`
+///
+/// # Pattern Details
+///
+/// **Eval line patterns** (for `wt`):
+/// ```text
+/// eval "$(wt config shell init bash)" ✓ matches
+/// eval "$(command wt config shell init bash)" ✓ matches
+/// eval "$(git wt config shell init bash)" ✗ no match (git- prefix)
+/// eval "$(git-wt config shell init bash)" ✗ no match (git- prefix)
+/// source <(wt config shell init zsh) ✓ matches
+/// ```
+///
+/// # Edge Cases Handled
+///
+/// - Quoted command names: `eval "$('wt' config shell init bash)"` - rare but matched
+/// - Comment lines: `# eval "$(wt config shell init bash)"` - skipped
+/// - Partial matches: `newt config shell init` - not matched (word boundary)
+///
+/// # Usage
+///
+/// Used by:
+/// - `is_integration_configured()` - detect "configured but not restarted" state
+/// - `uninstall` - identify lines to remove from shell config
+/// - `wt config show` - display shell integration status
+///
+/// # Impact of False Negatives
+///
+/// Detection is ONLY used when shell integration is NOT active (i.e., user ran
+/// the binary directly without the shell wrapper). Once the shell wrapper is
+/// active (after shell restart), `WORKTRUNK_DIRECTIVE_FILE` is set and no
+/// detection is needed.
+///
+/// **When binary is run directly (wrapper not active):**
+/// - If detection finds integration → "restart the shell to activate"
+/// - If detection misses (false negative) → "shell integration not installed"
+///
+/// **When wrapper is active:** No warnings shown regardless of detection.
+///
+/// This means false negatives only cause incorrect messaging in `wt config show`
+/// and when users run the binary directly before restarting their shell.
pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {
let trimmed = line.trim();
@@ -58,17 +122,230 @@ pub fn is_shell_integration_line(line: &str, cmd: &str) -> bool {
return false;
}
- // Must contain the init pattern for this command
+ // Check for eval/source line pattern
+ has_init_invocation(trimmed, cmd)
+}
+
+/// Check if line contains `{cmd} config shell init` as a command invocation.
+///
+/// For `wt`: matches `wt config shell init` but NOT `git wt` or `git-wt`.
+/// For `git-wt`: matches `git-wt config shell init` OR `git wt config shell init`.
+fn has_init_invocation(line: &str, cmd: &str) -> bool {
+ // For git-wt, we need to match both "git-wt config shell init" AND "git wt config shell init"
+ // because users invoke it both ways (and git dispatches "git wt" to "git-wt")
+ if cmd == "git-wt" {
+ // Match either form, with boundary check for "git" in "git wt" form
+ return has_init_pattern_with_prefix_check(line, "git-wt")
+ || has_init_pattern_with_prefix_check(line, "git wt");
+ }
+
+ // For other commands, use normal matching with prefix exclusion
+ has_init_pattern_with_prefix_check(line, cmd)
+}
+
+/// Check if line has the init pattern, with prefix exclusion for non-git-wt commands.
+fn has_init_pattern_with_prefix_check(line: &str, cmd: &str) -> bool {
let init_pattern = format!("{cmd} config shell init");
- if !trimmed.contains(&init_pattern) {
+
+ // Find all occurrences of the pattern
+ let mut search_start = 0;
+ while let Some(pos) = line[search_start..].find(&init_pattern) {
+ let absolute_pos = search_start + pos;
+
+ // Check what precedes the match
+ if is_valid_command_position(line, absolute_pos, cmd) {
+ // Must be in an execution context
+ if line.contains("eval")
+ || line.contains("source")
+ || line.contains("Invoke-Expression")
+ || line.contains("if ")
+ {
+ return true;
+ }
+ }
+
+ // Continue searching after this match
+ search_start = absolute_pos + 1;
+ }
+
+ false
+}
+
+/// Check if the command at `pos` is a valid standalone command, not part of another command.
+///
+/// For `wt` at position `pos`:
+/// - Valid: start of line, after `$(`, after whitespace, after `command `
+/// - Invalid: after `git ` (would be `git wt`), after `git-` (would be `git-wt`)
+///
+/// For `git-wt`: must not be preceded by alphanumeric, underscore, or hyphen
+/// (e.g., `my-git-wt` should NOT match)
+fn is_valid_command_position(line: &str, pos: usize, cmd: &str) -> bool {
+ if pos == 0 {
+ return true; // Start of line
+ }
+
+ let before = &line[..pos];
+
+ // For git-wt, just check it's not part of a longer identifier
+ // e.g., `my-git-wt` should not match
+ if cmd == "git-wt" {
+ let last_char = before.chars().last().unwrap();
+ return !last_char.is_alphanumeric() && last_char != '_' && last_char != '-';
+ }
+
+ // For other commands (like `wt`), check for git prefix
+ // This handles: `git wt config...` and `git-wt config...`
+ if before.ends_with("git ") || before.ends_with("git-") {
return false;
}
- // Must be in an execution context
- trimmed.contains("eval")
- || trimmed.contains("source")
- || trimmed.contains("Invoke-Expression")
- || trimmed.contains("if ")
+ // Valid if preceded by: whitespace, $(, (, ", ', or `command `
+ let last_char = before.chars().last().unwrap();
+ matches!(last_char, ' ' | '\t' | '$' | '(' | '"' | '\'' | '`')
+}
+
+/// Check if a line contains the command name at a word boundary.
+///
+/// Used to identify potential false negatives - lines that contain the command
+/// but weren't detected as integration lines.
+fn contains_cmd_at_word_boundary(line: &str, cmd: &str) -> bool {
+ let mut search_start = 0;
+ while let Some(pos) = line[search_start..].find(cmd) {
+ let absolute_pos = search_start + pos;
+
+ // Check character before (must be non-identifier or start of string)
+ let before_ok = if absolute_pos == 0 {
+ true
+ } else {
+ let prev_char = line[..absolute_pos].chars().last().unwrap();
+ !prev_char.is_alphanumeric() && prev_char != '_' && prev_char != '-'
+ };
+
+ // Check character after (must be non-identifier or end of string)
+ let after_pos = absolute_pos + cmd.len();
+ let after_ok = if after_pos >= line.len() {
+ true
+ } else {
+ let next_char = line[after_pos..].chars().next().unwrap();
+ !next_char.is_alphanumeric() && next_char != '_' && next_char != '-'
+ };
+
+ if before_ok && after_ok {
+ return true;
+ }
+
+ search_start = absolute_pos + 1;
+ }
+ false
+}
+
+/// A detected line with its 1-based line number.
+#[derive(Debug, Clone)]
+pub struct DetectedLine {
+ pub line_number: usize,
+ pub content: String,
+}
+
+/// Result of scanning a shell config file for integration detection.
+#[derive(Debug, Clone)]
+pub struct FileDetectionResult {
+ /// Path to the config file that was scanned.
+ pub path: PathBuf,
+ /// Lines that matched as shell integration (detected).
+ pub matched_lines: Vec<DetectedLine>,
+ /// Lines containing the command at word boundary but NOT detected.
+ /// These are potential false negatives.
+ pub unmatched_candidates: Vec<DetectedLine>,
+}
+
+/// Scan a single file for shell integration lines and potential false negatives.
+fn scan_file(path: &std::path::Path, cmd: &str) -> Option<FileDetectionResult> {
+ use std::fs;
+ use std::io::{BufRead, BufReader};
+
+ let file = fs::File::open(path).ok()?;
+ let reader = BufReader::new(file);
+ let mut matched_lines = Vec::new();
+ let mut unmatched_candidates = Vec::new();
+
+ for (line_number, line) in reader.lines().map_while(Result::ok).enumerate() {
+ let line_number = line_number + 1; // 1-based
+ let trimmed = line.trim();
+ // Skip empty lines and comments
+ if trimmed.is_empty() || trimmed.starts_with('#') {
+ continue;
+ }
+
+ if is_shell_integration_line(&line, cmd) {
+ matched_lines.push(DetectedLine {
+ line_number,
+ content: line.clone(),
+ });
+ } else if contains_cmd_at_word_boundary(&line, cmd) {
+ unmatched_candidates.push(DetectedLine {
+ line_number,
+ content: line.clone(),
+ });
+ }
+ }
+
+ // Only return if we found something interesting
+ if matched_lines.is_empty() && unmatched_candidates.is_empty() {
+ return None;
+ }
+
+ Some(FileDetectionResult {
+ path: path.to_path_buf(),
+ matched_lines,
+ unmatched_candidates,
+ })
+}
+
+/// Scan shell config files for detailed detection results.
+///
+/// Returns information about:
+/// - Which lines matched as shell integration
+/// - Which lines contain the command but didn't match (potential false negatives)
+///
+/// Used by `wt config show` to provide debugging output.
+pub fn scan_for_detection_details(cmd: &str) -> Result<Vec<FileDetectionResult>, std::io::Error> {
+ use std::collections::HashSet;
+
+ let home = home_dir_required()?;
+ let mut results = Vec::new();
+
+ // Collect all config file paths to scan
+ // Use HashSet to deduplicate paths (e.g., when ZDOTDIR == $HOME)
+ let mut config_files: Vec<PathBuf> = vec![
+ // Bash
+ home.join(".bashrc"),
+ home.join(".bash_profile"),
+ home.join(".profile"),
+ // Zsh
+ home.join(".zshrc"),
+ std::env::var("ZDOTDIR")
+ .map(PathBuf::from)
+ .unwrap_or_else(|_| home.clone())
+ .join(".zshrc"),
+ // Fish conf.d
+ home.join(".config/fish/conf.d").join(format!("{cmd}.fish")),
+ ];
+
+ // Add PowerShell profiles
+ config_files.extend(powershell_profile_paths(&home));
+
+ // Deduplicate and scan
+ let mut seen = HashSet::new();
+ for path in config_files {
+ if !seen.insert(path.clone()) || !path.exists() {
+ continue;
+ }
+ if let Some(result) = scan_file(&path, cmd) {
+ results.push(result);
+ }
+ }
+
+ Ok(results)
}
/// Supported shells
@@ -206,71 +483,11 @@ impl Shell {
/// This ensures we only consider integration "configured" if it uses the same binary
/// we're running as - prevents confusion when users have multiple installs.
pub fn is_integration_configured(cmd: &str) -> Result<Option<PathBuf>, std::io::Error> {
- use std::fs;
- use std::io::{BufRead, BufReader};
-
- let home = home_dir_required()?;
-
- // Check common shell config files for integration patterns
- let config_files = vec![
- // Bash
- home.join(".bashrc"),
- home.join(".bash_profile"),
- home.join(".profile"),
- // Zsh
- home.join(".zshrc"),
- std::env::var("ZDOTDIR")
- .map(PathBuf::from)
- .unwrap_or_else(|_| home.clone())
- .join(".zshrc"),
- ];
-
- for path in config_files {
- if !path.exists() {
- continue;
- }
-
- if let Ok(file) = fs::File::open(&path) {
- let reader = BufReader::new(file);
- for line in reader.lines().map_while(Result::ok) {
- if is_shell_integration_line(&line, cmd) {
- return Ok(Some(path));
- }
- }
- }
- }
-
- // Check Fish conf.d directory - look for {cmd}.fish file specifically
- let fish_conf_d = home.join(".config/fish/conf.d");
- let fish_config = fish_conf_d.join(format!("{cmd}.fish"));
- if fish_config.exists()
- && let Ok(file) = fs::File::open(&fish_config)
- {
- let reader = BufReader::new(file);
- for line in reader.lines().map_while(Result::ok) {
- if is_shell_integration_line(&line, cmd) {
- return Ok(Some(fish_config));
- }
- }
- }
-
- // Check PowerShell profiles for integration (both Core and 5.1)
- for profile_path in powershell_profile_paths(&home) {
- if !profile_path.exists() {
- continue;
- }
-
- if let Ok(file) = fs::File::open(&profile_path) {
- let reader = BufReader::new(file);
- for line in reader.lines().map_while(Result::ok) {
- if is_shell_integration_line(&line, cmd) {
- return Ok(Some(profile_path));
- }
- }
- }
- }
-
- Ok(None)
+ let results = scan_for_detection_details(cmd)?;
+ Ok(results
+ .into_iter()
+ .find(|r| !r.matched_lines.is_empty())
+ .map(|r| r.path))
}
}
@@ -614,4 +831,452 @@ mod tests {
"{shell} config_line({prefix:?}) not detected:\n {line}"
);
}
+
+ // ==========================================================================
+ // Detection tests: eval/source lines
+ // ==========================================================================
+
+ /// Basic eval patterns that SHOULD match for `wt`
+ #[rstest]
+ #[case::basic_eval(r#"eval "$(wt config shell init bash)""#)]
+ #[case::with_command(r#"eval "$(command wt config shell init bash)""#)]
+ #[case::source_process_sub(r#"source <(wt config shell init zsh)"#)]
+ #[case::fish_source(r#"wt config shell init fish | source"#)]
+ #[case::with_if_check(
+ r#"if command -v wt >/dev/null; then eval "$(wt config shell init bash)"; fi"#
+ )]
+ #[case::single_quotes(r#"eval '$( wt config shell init bash )'"#)]
+ fn test_wt_eval_patterns_match(#[case] line: &str) {
+ assert!(
+ is_shell_integration_line(line, "wt"),
+ "Should match for 'wt': {line}"
+ );
+ }
+
+ /// Patterns that should NOT match for `wt` (they're for git-wt)
+ #[rstest]
+ #[case::git_space_wt(r#"eval "$(git wt config shell init bash)""#)]
+ #[case::git_hyphen_wt(r#"eval "$(git-wt config shell init bash)""#)]
+ #[case::command_git_wt(r#"eval "$(command git wt config shell init bash)""#)]
+ #[case::command_git_hyphen_wt(r#"eval "$(command git-wt config shell init bash)""#)]
+ fn test_git_wt_patterns_dont_match_wt(#[case] line: &str) {
+ assert!(
+ !is_shell_integration_line(line, "wt"),
+ "Should NOT match for 'wt' (this is git-wt integration): {line}"
+ );
+ }
+
+ /// Patterns that SHOULD match for `git-wt`
+ #[rstest]
+ #[case::git_hyphen_wt(r#"eval "$(git-wt config shell init bash)""#)]
+ #[case::git_space_wt(r#"eval "$(git wt config shell init bash)""#)]
+ #[case::command_git_wt(r#"eval "$(command git wt config shell init bash)""#)]
+ fn test_git_wt_eval_patterns_match(#[case] line: &str) {
+ assert!(
+ is_shell_integration_line(line, "git-wt"),
+ "Should match for 'git-wt': {line}"
+ );
+ }
+
+ /// Comment lines should never match
+ #[rstest]
+ #[case::bash_comment(r#"# eval "$(wt config shell init bash)""#)]
+ #[case::indented_comment(r#" # eval "$(wt config shell init bash)""#)]
+ fn test_comments_dont_match(#[case] line: &str) {
+ assert!(
+ !is_shell_integration_line(line, "wt"),
+ "Comment should not match: {line}"
+ );
+ }
+
+ /// Lines without execution context should not match
+ #[rstest]
+ #[case::just_command("wt config shell init bash")]
+ #[case::echo(r#"echo "wt config shell init bash""#)]
+ fn test_no_execution_context_doesnt_match(#[case] line: &str) {
+ assert!(
+ !is_shell_integration_line(line, "wt"),
+ "Without eval/source should not match: {line}"
+ );
+ }
+
+ // ==========================================================================
+ // Edge cases and real-world patterns
+ // ==========================================================================
+
+ /// Real-world patterns from user dotfiles
+ #[rstest]
+ #[case::chezmoi_style(
+ r#"if command -v wt &>/dev/null; then eval "$(wt config shell init bash)"; fi"#,
+ "wt",
+ true
+ )]
+ #[case::nikiforov_style(r#"eval "$(command git wt config shell init bash)""#, "git-wt", true)]
+ #[case::nikiforov_not_wt(r#"eval "$(command git wt config shell init bash)""#, "wt", false)]
+ fn test_real_world_patterns(#[case] line: &str, #[case] cmd: &str, #[case] should_match: bool) {
+ assert_eq!(
+ is_shell_integration_line(line, cmd),
+ should_match,
+ "Line: {line}\nCommand: {cmd}\nExpected: {should_match}"
+ );
+ }
+
+ /// Word boundary: `newt` should not match `wt`
+ #[test]
+ fn test_word_boundary_newt() {
+ let line = r#"eval "$(newt config shell init bash)""#;
+ // This line contains "wt config shell init" as a substring
+ // but the command is "newt", not "wt"
+ assert!(
+ !is_shell_integration_line(line, "wt"),
+ "newt should not match wt"
+ );
+ }
+
+ /// Partial command names should not match
+ #[test]
+ fn test_partial_command_no_match() {
+ // "swt" contains "wt" but is not "wt"
+ let line = r#"eval "$(swt config shell init bash)""#;
+ assert!(
+ !is_shell_integration_line(line, "wt"),
+ "swt should not match wt"
+ );
+ }
+
+ // ==========================================================================
+ // ADVERSARIAL FALSE NEGATIVE TESTS
+ // These test cases attempt to find patterns that SHOULD be detected but ARE NOT
+ // ==========================================================================
+
+ /// Helper to test false negatives - if this panics, we found one
+ fn assert_detects(line: &str, cmd: &str, description: &str) {
+ assert!(
+ is_shell_integration_line(line, cmd),
+ "FALSE NEGATIVE: {} not detected for cmd={}\nLine: {}",
+ description,
+ cmd,
+ line
+ );
+ }
+
+ /// Helper to verify non-detection (expected behavior)
+ fn assert_not_detects(line: &str, cmd: &str, description: &str) {
+ assert!(
+ !is_shell_integration_line(line, cmd),
+ "UNEXPECTED MATCH: {} matched for cmd={}\nLine: {}",
+ description,
+ cmd,
+ line
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: dot (.) command as source equivalent
+ // ------------------------------------------------------------------------
+
+ /// The `.` command is POSIX-equivalent to `source` but NOT detected
+ #[test]
+ fn test_fn_dot_command_process_substitution() {
+ // . <(wt config shell init bash) is equivalent to source <(...)
+ // This is a common POSIX pattern
+ assert_not_detects(
+ ". <(wt config shell init bash)",
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: dot command with process substitution",
+ );
+ }
+
+ #[test]
+ fn test_fn_dot_command_zsh_equals() {
+ // . =(wt config shell init zsh) is zsh-specific
+ assert_not_detects(
+ ". =(wt config shell init zsh)",
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: dot command with zsh =() substitution",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: PowerShell iex alias
+ // ------------------------------------------------------------------------
+
+ /// iex is PowerShell's alias for Invoke-Expression
+ #[test]
+ fn test_fn_powershell_iex_alias() {
+ // Common in PowerShell profiles
+ assert_not_detects(
+ "iex (wt config shell init powershell)",
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: PowerShell iex alias",
+ );
+ }
+
+ #[test]
+ fn test_fn_powershell_iex_with_ampersand() {
+ assert_not_detects(
+ "iex (& wt config shell init powershell)",
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: PowerShell iex with &",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: PowerShell block comments
+ // Note: This is actually a FALSE POSITIVE risk (comments matching)
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_fn_powershell_block_comment() {
+ // PowerShell block comments <# #> should NOT match
+ // But current code doesn't skip them
+ let line = "<# Invoke-Expression (wt config shell init powershell) #>";
+ let result = is_shell_integration_line(line, "wt");
+ // This DOES match (false positive) - documenting the behavior
+ assert!(
+ result,
+ "PowerShell block comment currently matches (false positive risk)"
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: zsh =() process substitution without source/eval
+ // ------------------------------------------------------------------------
+
+ /// Zsh allows sourcing with just =() which creates a temp file
+ #[test]
+ fn test_fn_zsh_bare_equals_substitution() {
+ // Some zsh configs might use: . =(command)
+ // Already covered above, but this is a variant
+ assert_not_detects(
+ ". =(command wt config shell init zsh)",
+ "wt",
+ "dot with command prefix",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // EDGE CASE: Backtick command substitution
+ // ------------------------------------------------------------------------
+
+ /// Backticks (older syntax) should work - they DO
+ #[test]
+ fn test_backtick_substitution() {
+ assert_detects(
+ "eval \"`wt config shell init bash`\"",
+ "wt",
+ "backtick substitution",
+ );
+ }
+
+ /// Backticks without quotes
+ #[test]
+ fn test_backtick_no_outer_quotes() {
+ assert_detects(
+ "eval `wt config shell init bash`",
+ "wt",
+ "backtick without outer quotes",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: Path prefixes to binary
+ // The detection checks for specific preceding characters (' ', '\t', '$', etc.)
+ // but '/' is not included, so paths like /usr/local/bin/wt don't match
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_fn_absolute_path() {
+ // Path-prefixed binary invocation - NOT detected because '/' not in allowed chars
+ assert_not_detects(
+ r#"eval "$(/usr/local/bin/wt config shell init bash)""#,
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: absolute path to binary",
+ );
+ }
+
+ #[test]
+ fn test_fn_home_path() {
+ assert_not_detects(
+ r#"eval "$(~/.cargo/bin/wt config shell init bash)""#,
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: home-relative path",
+ );
+ }
+
+ #[test]
+ fn test_fn_env_var_path() {
+ assert_not_detects(
+ r#"eval "$($HOME/.cargo/bin/wt config shell init bash)""#,
+ "wt",
+ "CONFIRMED FALSE NEGATIVE: env var in path",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // EDGE CASE: WORKTRUNK_BIN fallback variations
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_worktrunk_bin_only() {
+ // Using only WORKTRUNK_BIN without default
+ assert_not_detects(
+ r#"eval "$($WORKTRUNK_BIN config shell init bash)""#,
+ "wt",
+ "WORKTRUNK_BIN without default (expected: no match - cant tell which cmd)",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // EDGE CASE: git wt spacing variations
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_git_wt_double_space() {
+ // Extra space between git and wt
+ assert_not_detects(
+ r#"eval "$(git wt config shell init bash)""#,
+ "git-wt",
+ "double space (expected: no match due to pattern)",
+ );
+ }
+
+ #[test]
+ fn test_git_wt_tab_separator() {
+ // Tab between git and wt
+ let line = "eval \"$(git\twt config shell init bash)\"";
+ assert_not_detects(
+ line,
+ "git-wt",
+ "tab separator (expected: no match - only single space matched)",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: fish without explicit source/eval keyword
+ // The fish pattern wt config shell init fish | source works because "source" is detected
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_fish_standard() {
+ assert_detects(
+ "wt config shell init fish | source",
+ "wt",
+ "standard fish pattern",
+ );
+ }
+
+ #[test]
+ fn test_fish_with_command() {
+ assert_detects(
+ "command wt config shell init fish | source",
+ "wt",
+ "fish with command prefix",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // FALSE NEGATIVE: Nushell (unsupported but users might try)
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_nushell_pattern() {
+ // Nushell uses "source" so it might match
+ let line = "wt config shell init nu | source";
+ // This actually matches because it contains "source" and "wt config shell init"
+ assert_detects(line, "wt", "nushell pattern (unexpectedly matches)");
+ }
+
+ // ------------------------------------------------------------------------
+ // Verify comment handling edge cases
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_inline_comment() {
+ // The line starts with actual code, not a comment
+ assert_detects(
+ r#"eval "$(wt config shell init bash)" # setup wt"#,
+ "wt",
+ "inline comment after code",
+ );
+ }
+
+ #[test]
+ fn test_commented_in_middle() {
+ // Line starts with #
+ assert_not_detects(
+ r#"#eval "$(wt config shell init bash)""#,
+ "wt",
+ "line starting with # (expected: no match)",
+ );
+ }
+
+ // ------------------------------------------------------------------------
+ // Multiple commands on one line
+ // ------------------------------------------------------------------------
+
+ #[test]
+ fn test_multiple_evals() {
+ // Both wt and git-wt on same line
+ let line =
+ r#"eval "$(wt config shell init bash)"; eval "$(git-wt config shell init bash)""#;
+ assert_detects(line, "wt", "wt in multi-command line");
+ assert_detects(line, "git-wt", "git-wt in multi-command line");
+ }
+
+ // ==========================================================================
+ // WORD BOUNDARY TESTS - Bugs fixed in adversarial testing rounds 3-4
+ // ==========================================================================
+
+ /// Prefixed git-wt commands should NOT match git-wt
+ #[rstest]
+ #[case::my_git_wt(r#"eval "$(my-git-wt config shell init bash)""#)]
+ #[case::test_git_wt(r#"eval "$(test-git-wt config shell init bash)""#)]
+ #[case::underscore_git_wt(r#"eval "$(_git-wt config shell init bash)""#)]
+ #[case::x_git_wt(r#"eval "$(x-git-wt config shell init bash)""#)]
+ fn test_prefixed_git_wt_no_match(#[case] line: &str) {
+ assert_not_detects(line, "git-wt", "prefixed git-wt command should NOT match");
+ }
+
+ /// Prefixed "git wt" (space form) should NOT match git-wt
+ #[rstest]
+ #[case::agit_wt(r#"eval "$(agit wt config shell init bash)""#)]
+ #[case::xgit_wt(r#"eval "$(xgit wt config shell init bash)""#)]
+ #[case::mygit_wt(r#"eval "$(mygit wt config shell init bash)""#)]
+ fn test_prefixed_git_space_wt_no_match(#[case] line: &str) {
+ assert_not_detects(line, "git-wt", "prefixed 'git wt' should NOT match git-wt");
+ }
+
+ // ------------------------------------------------------------------------
+ // Summary of confirmed ACCEPTABLE FALSE NEGATIVES:
+ // (These are documented limitations, not bugs to fix)
+ //
+ // 1. `. <(cmd ...)` - POSIX dot command (rare, users can use `source`)
+ // 2. `. =(cmd ...)` - zsh =() substitution (rare)
+ // 3. `iex (cmd ...)` - PowerShell iex alias (would need to add `iex` check)
+ // 4. `/path/to/wt` - path-prefixed binary (would need path parsing)
+ // 5. `~/path/to/wt` - home-relative path (would need path parsing)
+ // 6. `$HOME/path/wt` - env var path (would need path parsing)
+ // 7. Line continuations (`\` or backtick) - architectural limitation
+ // 8. Heredoc context (`: <<'EOF'`) - architectural limitation
+ //
+ // Summary of ACCEPTABLE FALSE POSITIVE risks:
+ // 9. PowerShell block comments `<# #>` - rare in shell configs
+ // 10. Subshell `(eval ...)` - detected correctly but doesn't persist
+ //
+ // FIXED in this version (were bugs, now correct):
+ // 11. `my-git-wt` no longer matches `git-wt`
+ // 12. `agit wt` no longer matches `git wt`
+ //
+ // By design (not bugs):
+ // 13. `git wt` (double space) - only single space "git wt" is valid
+ //
+ // IMPACT OF FALSE NEGATIVES:
+ // Detection is ONLY used when shell wrapper is NOT active. Once the user
+ // restarts their shell, WORKTRUNK_DIRECTIVE_FILE is set and no detection
+ // is needed. False negatives only affect:
+ // - `wt config show` status display
+ // - Warning message before shell restart ("not installed" vs "restart to activate")
+ // - `wt config shell uninstall` (lines might not be found)
+ // ------------------------------------------------------------------------
}
diff --git a/tests/integration_tests/config_show.rs b/tests/integration_tests/config_show.rs
index bed1361bc..0f28e2b49 100644
--- a/tests/integration_tests/config_show.rs
+++ b/tests/integration_tests/config_show.rs
@@ -590,3 +590,41 @@ fn test_config_show_whitespace_only_project_config(mut repo: TestRepo, temp_home
assert_cmd_snapshot!(cmd);
});
}
+
+/// Test `wt config show` shows warning for unmatched candidates (potential false negatives)
+///
+/// When a shell config contains `wt` at a word boundary but it's NOT detected as
+/// shell integration, show a warning with file:line format to help debug detection.
+#[rstest]
+fn test_config_show_unmatched_candidate_warning(mut repo: TestRepo, temp_home: TempDir) {
+ // Setup mock gh/glab for deterministic BINARIES output
+ repo.setup_mock_ci_tools_unauthenticated();
+
+ // Create global config
+ let global_config_dir = temp_home.path().join(".config").join("worktrunk");
+ fs::create_dir_all(&global_config_dir).unwrap();
+ fs::write(global_config_dir.join("config.toml"), "").unwrap();
+
+ // Create .bashrc with a line containing `wt` but NOT a valid integration pattern
+ // This should trigger the "unmatched candidate" warning
+ fs::write(
+ temp_home.path().join(".bashrc"),
+ r#"# Some bash config
+export PATH="$HOME/bin:$PATH"
+alias wt="git worktree"
+"#,
+ )
+ .unwrap();
+
+ let settings = setup_snapshot_settings_with_home(&repo, &temp_home);
+ settings.bind(|| {
+ let mut cmd = wt_command();
+ repo.configure_wt_cmd(&mut cmd);
+ repo.configure_mock_commands(&mut cmd);
+ cmd.arg("config").arg("show").current_dir(repo.root_path());
+ set_temp_home_env(&mut cmd, temp_home.path());
+ cmd.env("WORKTRUNK_TEST_COMPINIT_CONFIGURED", "1");
+
+ assert_cmd_snapshot!(cmd);
+ });
+}
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_partial_shell_config_shows_hint.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_partial_shell_config_shows_hint.snap
index 4d126e686..620207bb6 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_partial_shell_config_shows_hint.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_partial_shell_config_shows_hint.snap
@@ -24,6 +24,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_TEST_COMPINIT_CONFIGURED: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -39,7 +40,8 @@ exit_code: 0
SHELL INTEGRATION
↳ Not configured shell extension & completions for bash @ ~/.bashrc
-○ Already configured shell extension & completions for zsh @ ~/.zshrc
+○ Already configured shell extension & completions for zsh @ ~/.zshrc:2
+  if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
○ Skipped fish; ~/.config/fish/conf.d not found
↳ To enable shell integration, run wt config shell install
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_unmatched_candidate_warning.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_unmatched_candidate_warning.snap
new file mode 100644
index 000000000..4db581a37
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_unmatched_candidate_warning.snap
@@ -0,0 +1,50 @@
+---
+source: tests/integration_tests/config_show.rs
+info:
+ program: wt
+ args:
+ - config
+ - show
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "150"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ PATH: "[PATH]"
+ RUST_LOG: warn
+ SOURCE_DATE_EPOCH: "1735776000"
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_TEST_COMPINIT_CONFIGURED: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+USER CONFIG ~/.config/worktrunk/config.toml
+↳ Empty file (using defaults)
+
+PROJECT CONFIG _REPO_/.config/wt.toml
+↳ Not found
+
+SHELL INTEGRATION
+↳ Not configured shell extension & completions for bash @ ~/.bashrc
+○ Skipped zsh; ~/.zshrc not found
+○ Skipped fish; ~/.config/fish/conf.d not found
+
+↳ To enable shell integration, run wt config shell install
+▲ Found wt in ~/.bashrc:3 but not detected as integration:
+  alias wt="git worktree"
+
+↳ If this is shell integration, report a false negative: https://github.com/max-sixty/worktrunk/issues/new?title=Shell%20integration%20detection%20false%20negative&body=Shell%20integration%20not%20detected%20despite%20config%20containing%20%60wt%60.%0A%0A%2A%2AUnmatched%20lines%3A%2A%2A%0A%60%60%60%0Aalias%20wt%3D%22git%20worktree%22%0A%60%60%60%0A%0A%2A%2AExpected%20behavior%3A%2A%2A%20These%20lines%20should%20be%20detected%20as%20shell%20integration.
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_correct_order.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_correct_order.snap
index 0c914cd9c..de3fdb339 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_correct_order.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_correct_order.snap
@@ -24,6 +24,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_TEST_COMPINIT_CONFIGURED: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -38,6 +39,7 @@ exit_code: 0
↳ Not found
SHELL INTEGRATION
-○ Already configured shell extension & completions for zsh @ ~/.zshrc
+○ Already configured shell extension & completions for zsh @ ~/.zshrc:5
+  if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
○ Skipped bash; ~/.bashrc not found
○ Skipped fish; ~/.config/fish/conf.d not found
diff --git a/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_warning.snap b/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_warning.snap
index 833b25a1e..e8a94d5ad 100644
--- a/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_warning.snap
+++ b/tests/snapshots/integration__integration_tests__config_show__config_show_zsh_compinit_warning.snap
@@ -24,6 +24,7 @@ info:
USERPROFILE: "[TEST_HOME]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_TEST_COMPINIT_MISSING: "1"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -38,7 +39,8 @@ exit_code: 0
↳ Not found
SHELL INTEGRATION
-○ Already configured shell extension & completions for zsh @ ~/.zshrc
+○ Already configured shell extension & completions for zsh @ ~/.zshrc:2
+  if command -v wt >/dev/null 2>&1; then eval "$(command wt config shell init zsh)"; fi
▲ Completions won't work; add to ~/.zshrc before the wt line:
  autoload -Uz compinit && compinit
○ Skipped bash; ~/.bashrc not found