Skip to content

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

fix: Standardize external command output handling

Maximilian Roos67dc70beccf0
diff --git a/CLAUDE.md b/CLAUDE.md
index 253d52272..aaa84531d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -765,6 +765,45 @@ This constraint maintains architectural integrity:
When adding new functionality to restricted commands, always ask: "Does this need output?" If yes, use `crate::output::progress()` or `crate::output::success()`, never direct prints.
+## Command Execution Principles
+
+### Real-time Output Streaming
+
+**CRITICAL: Command output must stream through in real-time. Never buffer external command output.**
+
+When executing external commands (git, npm, user scripts, etc.):
+
+- **Stream immediately**: Output from child processes must appear as it's generated
+- **No buffering**: Do NOT collect output into buffers before displaying
+- **Real-time feedback**: Users must see progress as it happens, not after completion
+
+**Why this matters:**
+- Long-running commands (npm install, cargo build) provide progress indicators
+- Users need to see what's happening in real-time for debugging
+- Buffering breaks interactive commands and progress bars
+- Commands may run for minutes - buffering until completion is unacceptable
+
+**Good - streaming output:**
+```rust
+// Read and write line-by-line as data arrives
+for line in reader.lines() {
+ println!("{}", line);
+ stdout().flush();
+}
+```
+
+**Bad - buffering output:**
+```rust
+// ❌ NEVER DO THIS - waits until command completes
+let lines: Vec<_> = reader.lines().collect();
+for line in lines {
+ println!("{}", line);
+}
+```
+
+**Implementation constraint:**
+Any solution to output ordering problems must maintain real-time streaming. If you need deterministic ordering, solve it at the pipe level (e.g., redirect stderr to stdout in the shell), not by buffering in Rust.
+
## Testing Guidelines
### Testing with --execute Commands
diff --git a/src/output/handlers.rs b/src/output/handlers.rs
index 0357cf477..99c6e36c8 100644
--- a/src/output/handlers.rs
+++ b/src/output/handlers.rs
@@ -107,13 +107,13 @@ pub fn handle_remove_output(result: &RemoveResult) -> Result<(), GitError> {
/// Execute a command in a worktree directory
///
-/// Uses Stdio::inherit() for real-time streaming output in both modes.
-/// Redirects child stdout to stderr to ensure all output appears on a single file descriptor,
-/// preventing terminal reordering issues between stdout and stderr.
+/// Merges stdout into stderr using shell redirection (1>&2) to ensure deterministic output ordering.
+/// Per CLAUDE.md guidelines: child process output goes to stderr, worktrunk output goes to stdout.
+/// Streams output line-by-line in real-time (no buffering) to provide immediate feedback for
+/// long-running commands.
///
-/// The redirect ensures that all child output and our progress messages go through the same FD
-/// (stderr), which guarantees deterministic ordering: bytes written later cannot appear before
-/// bytes written earlier to the same FD.
+/// The shell-level redirect ensures all output flows through a single pipe (stderr) in the order written,
+/// eliminating race conditions that would occur with separate stdout/stderr threads.
///
/// Calls terminate_output() after completion to handle mode-specific cleanup
/// (NUL terminator in directive mode, no-op in interactive mode).
@@ -121,23 +121,40 @@ pub fn execute_command_in_worktree(
worktree_path: &std::path::Path,
command: &str,
) -> Result<(), GitError> {
+ use std::io::{BufRead, BufReader, Write};
use std::process::{Command, Stdio};
// Flush stdout before executing command to ensure all our messages appear
// before the child process output
super::flush()?;
- // Run the command with inherited stdio - child stdout and stderr both appear on our stdout and stderr
- // All output goes through the terminal, which handles the display ordering
- let status = Command::new("sh")
+ // Redirect stdout to stderr in the shell command to merge streams
+ // This ensures deterministic ordering: all output flows through a single pipe (stderr)
+ // in the order it was written, with no race conditions between threads
+ // Per CLAUDE.md: child process output goes to stderr, worktrunk output goes to stdout
+ let merged_command = format!("{{ {}; }} 1>&2", command);
+
+ let mut child = Command::new("sh")
.arg("-c")
- .arg(command)
+ .arg(&merged_command)
.current_dir(worktree_path)
- .stdout(Stdio::inherit())
- .stderr(Stdio::inherit())
- .status()
+ .stdout(Stdio::inherit()) // Inherit stdout for any shell errors (though redirected to stderr)
+ .stderr(Stdio::piped())
+ .spawn()
.git_context("Failed to execute command")?;
+ // Read and stream output line-by-line in real-time (no buffering)
+ let stderr = child.stderr.take().unwrap();
+ let reader = BufReader::new(stderr);
+
+ for line in reader.lines().map_while(Result::ok) {
+ eprintln!("{}", line);
+ let _ = std::io::stderr().flush();
+ }
+
+ // Wait for command to complete
+ let status = child.wait().git_context("Failed to wait for command")?;
+
if !status.success() {
return Err(GitError::CommandFailed(format!(
"Command failed with exit code: {}",
diff --git a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
index 36d097e90..99b103a48 100644
--- a/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
+++ b/tests/snapshots/integration__integration_tests__merge__merge_pre_merge_command_stdout_stderr_ordering.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpKOfRHN/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpnWhJs0/test-config.toml
---
success: true
exit_code: 0
@@ -26,18 +26,10 @@ exit_code: 0
  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
  check1 3
-[check1] stdout line 1
-[check1] stdout line 2
-[check1] stdout line 3
-[check1] stdout complete
πŸ”„ Running pre-merge command check2:
  [PROJECT_ROOT]/tests/fixtures/mixed-output.sh
  check2 3
-[check2] stdout line 1
-[check2] stdout line 2
-[check2] stdout line 3
-[check2] stdout complete
πŸ”„ Rebasing onto main...
πŸ”„ Pushing 1 commit to main @ [SHA]
@@ -52,11 +44,19 @@ exit_code: 0
βœ… Returned to primary at [REPO]
----- stderr -----
+[check1] stdout line 1
[check1] stderr line 1
+[check1] stdout line 2
[check1] stderr line 2
+[check1] stdout line 3
[check1] stderr line 3
+[check1] stdout complete
[check1] stderr complete
+[check2] stdout line 1
[check2] stderr line 1
+[check2] stdout line 2
[check2] stderr line 2
+[check2] stdout line 3
[check2] stderr line 3
+[check2] stdout complete
[check2] stderr complete
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
index 11ec85271..df89e93d7 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_multiple_commands_array.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpWgEEAu/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpOAWWzk/test-config.toml
---
success: true
exit_code: 0
@@ -24,13 +24,13 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'First'
-First
πŸ”„ Executing (post-create):
  echo 'Second'
-Second
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
+First
+Second
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
index 2a55cef42..d0d64160c 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_named_commands.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp55Mjxv/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpozpGIq/test-config.toml
---
success: true
exit_code: 0
@@ -24,13 +24,13 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'Installing deps'
-Installing deps
πŸ”„ Executing (post-create):
  echo 'Running setup'
-Running setup
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
+Installing deps
+Running setup
diff --git a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
index 4a12399e0..6069ae313 100644
--- a/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
+++ b/tests/snapshots/integration__integration_tests__post_start_commands__post_create_single_command.snap
@@ -16,7 +16,7 @@ info:
LANG: C
LC_ALL: C
SOURCE_DATE_EPOCH: "1761609600"
- WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmp8A1ot3/test-config.toml
+ WORKTRUNK_CONFIG_PATH: /var/folders/wf/s6ycxvvs4ln8qsdbfx40hnc40000gn/T/.tmpADyORD/test-config.toml
---
success: true
exit_code: 0
@@ -24,9 +24,9 @@ exit_code: 0
πŸ”„ Executing (post-create):
  echo 'Setup complete'
-Setup complete
βœ… Created new worktree for feature at [REPO].feature
To enable automatic cd, run: wt configure-shell
----- stderr -----
+Setup complete