Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(error): introduce CommandError typed leaf for buffered git failures (#2580)
Maximilian Roos32e165bebb96
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex f5d49ce49..1434397b8 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -748,9 +748,12 @@ pub fn collect(.filter(|sha| *sha != worktrunk::git::NULL_OID).collect();let commit_details_map = repo.commit_details_many(&all_shas).unwrap_or_else(|err| {+ // Surface git's actual stderr (when available via the typed leaf)+ // rather than our `CommandError` summary.+ let detail = worktrunk::git::display_message(&err);eprintln!("{}",- warning_message(cformat!("Failed to batch-fetch commit details: {err}"))+ warning_message(cformat!("Failed to batch-fetch commit details: {detail}")));std::collections::HashMap::new()});diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex 6ed72522f..cbb37be43 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -84,7 +84,12 @@ impl TaskContext {} else {ErrorCause::Other};- TaskError::new(self.item_idx, kind, err.to_string(), cause)+ // Prefer the typed leaf's captured stderr/stdout when present so the+ // user sees git's actual error message (e.g., "fatal: bad object+ // HEAD") rather than our single-line `CommandError` summary+ // ("git status --porcelain failed (exit 128)").+ let message = worktrunk::git::display_message(err);+ TaskError::new(self.item_idx, kind, message, cause)}/// Get the default branch resolved for this list invocation.diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 1135240f2..243895bb9 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -590,12 +590,14 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {let is_rebasing = repo.worktree_state()?.is_some_and(|s| s.starts_with("REBASING"));+ // Pull git's stderr from the typed leaf when present so we get the+ // raw conflict-marker bytes regardless of how many `.context(...)`+ // layers wrap the error.+ let detail = worktrunk::git::display_message(&e);if is_rebasing {- // Extract git's stderr output from the error- let git_output = e.to_string();return Err(worktrunk::git::GitError::RebaseConflict {target_branch: integration_target,- git_output,+ git_output: detail,}.into());}@@ -604,7 +606,7 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {message: cformat!("Failed to rebase onto <bold>{}</>: {}",integration_target,- e+ detail),}.into());diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex 6050c43bf..39b9a0d53 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -315,7 +315,7 @@ pub fn handle_push(]).map_err(|e| GitError::PushFailed {target_branch: ctx.target_branch.clone(),- error: e.to_string(),+ error: worktrunk::git::display_message(&e),})?;ctx.restore_stash();@@ -411,7 +411,10 @@ pub fn handle_no_ff_merge(.run_command(&["update-ref", &target_ref, &merge_sha, &ctx.target_tip]).map_err(|e| GitError::PushFailed {target_branch: ctx.target_branch.clone(),- error: format!("Failed to update ref: {e:#}"),+ error: format!(+ "Failed to update ref: {}",+ worktrunk::git::display_message(&e)+ ),})?;// Sync the target worktree's working tree if it exists.diff --git a/src/git/error.rs b/src/git/error.rsindex 97b3f7ea8..81a062823 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -105,6 +105,116 @@ pub struct FailedCommand {pub exit_info: String,}+/// Typed leaf error for a command (e.g., `git`) that exited non-zero with+/// captured stdout/stderr.+///+/// Worktrunk's buffered command wrappers ([`super::Repository::run_command`],+/// [`super::WorkingTree::run_command`]) return this — wrapped via+/// `anyhow::Error` — instead of `bail!("{stderr}")`-ing a multi-line string.+/// The structured form lets the renderer distinguish a command's captured+/// output (which is often multi-line) from a context chain entry (which is+/// always one line per layer in the anyhow model), and lets callers that+/// embed the raw stderr in a higher-level error (`GitError::RebaseConflict`+/// stores git's conflict-marker stderr in `git_output`) read it directly+/// instead of round-tripping through `e.to_string()`.+///+/// `Display` is intentionally a single-line summary — `format_with_gutter`+/// in `print_command_error` renders [`Self::combined_output`] separately for+/// the multi-line body. The streaming path (`run_command_delayed_stream`)+/// uses a sibling crate-private `StreamCommandError` for the same role,+/// where stdout/stderr are interleaved and a string body is the most we can+/// recover.+#[derive(Debug, Clone)]+pub struct CommandError {+ /// Program name, e.g., `"git"`.+ pub program: String,+ /// Arguments, e.g., `["worktree", "list"]`.+ pub args: Vec<String>,+ /// Captured stderr with `\r` normalized to `\n` (git emits `\r` for+ /// progress; non-TTY contexts otherwise produce snapshot instability).+ pub stderr: String,+ /// Captured stdout — kept separate because some git subcommands print+ /// errors here (e.g., `commit` with nothing to commit).+ pub stdout: String,+ /// Process exit code; `None` if the child was killed by a signal.+ pub exit_code: Option<i32>,+}++impl CommandError {+ /// Build from the captured `Output` of a non-zero exit.+ pub fn from_failed_output(+ program: impl Into<String>,+ args: &[&str],+ output: &std::process::Output,+ ) -> Self {+ let stderr = String::from_utf8_lossy(&output.stderr).replace('\r', "\n");+ let stdout = String::from_utf8_lossy(&output.stdout).into_owned();+ Self {+ program: program.into(),+ args: args.iter().map(|&s| s.to_string()).collect(),+ stderr,+ stdout,+ exit_code: output.status.code(),+ }+ }++ /// Reconstruct the command line for display.+ pub fn command_string(&self) -> String {+ if self.args.is_empty() {+ self.program.clone()+ } else {+ format!("{} {}", self.program, self.args.join(" "))+ }+ }++ /// stderr + stdout, trimmed and joined by `\n`, with empty pieces+ /// dropped. Mirrors the legacy `bail!("{}", error_msg)` payload so+ /// callers that previously parsed `e.to_string()` (notably+ /// `GitError::RebaseConflict`) get the same bytes when they downcast.+ pub fn combined_output(&self) -> String {+ [self.stderr.trim(), self.stdout.trim()]+ .into_iter()+ .filter(|s| !s.is_empty())+ .collect::<Vec<_>>()+ .join("\n")+ }+}++impl std::fmt::Display for CommandError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self.exit_code {+ Some(code) => write!(f, "{} failed (exit {})", self.command_string(), code),+ None => write!(f, "{} failed", self.command_string()),+ }+ }+}++impl std::error::Error for CommandError {}++/// Walk an anyhow chain looking for a [`CommandError`].+///+/// Returns the first match. Useful for renderers and callers that need the+/// raw stderr regardless of how many `.context(...)` layers wrap it.+pub fn find_command_error(error: &anyhow::Error) -> Option<&CommandError> {+ error.chain().find_map(|e| e.downcast_ref::<CommandError>())+}++/// User-facing detail string for an error that may carry a [`CommandError`].+///+/// When a [`CommandError`] is anywhere in the chain, returns its captured+/// stderr/stdout via [`CommandError::combined_output`] — that's git's actual+/// error message. Otherwise falls back to the rendered top-level string.+///+/// Use this when embedding a sub-error's text inside another typed error's+/// message field (e.g., `GitError::WorktreeRemovalFailed::error`,+/// `GitError::PushFailed::error`) so the user sees git's real reason rather+/// than the [`CommandError`] single-line summary.+pub fn display_message(error: &anyhow::Error) -> String {+ find_command_error(error)+ .map(|cmd_err| cmd_err.combined_output())+ .unwrap_or_else(|| error.to_string())+}+/// Extra CLI context for enriching `wt switch` suggestions in error hints.////// When a switch error is raised deep in the planning layer, the error only knows@@ -1188,6 +1298,7 @@ fn format_error_block(header: impl Into<String>, error: &str) -> String {#[cfg(test)]mod tests {use super::*;+ use anyhow::Context;use insta::assert_snapshot;#[test]@@ -1831,4 +1942,102 @@ mod tests {// Errors without switch suggestions should render identicallyassert_eq!(inner.to_string(), wrapped.to_string());}++ fn sample_command_error() -> CommandError {+ CommandError {+ program: "git".into(),+ args: vec!["worktree".into(), "list".into()],+ stderr: "fatal: not a git repository\n".into(),+ stdout: String::new(),+ exit_code: Some(128),+ }+ }++ #[test]+ fn command_error_display_is_single_line() {+ let err = sample_command_error();+ let s = err.to_string();+ assert_eq!(s, "git worktree list failed (exit 128)");+ assert!(!s.contains('\n'));+ }++ #[test]+ fn command_error_command_string_handles_empty_args() {+ // Degenerate but reachable when a `Cmd` is built with no+ // `.args(...)` call. Covers the args-empty branch of+ // `command_string()` (codecov flagged this line).+ let err = CommandError {+ program: "git".into(),+ args: Vec::new(),+ stderr: String::new(),+ stdout: String::new(),+ exit_code: Some(1),+ };+ assert_eq!(err.command_string(), "git");+ assert_eq!(err.to_string(), "git failed (exit 1)");+ }++ #[test]+ fn command_error_combined_output_strips_trailing_whitespace_and_joins() {+ let err = CommandError {+ program: "git".into(),+ args: vec!["push".into()],+ stderr: "warning: line 1\nfatal: line 2\n\n".into(),+ stdout: " trailing-stdout-error\n".into(),+ exit_code: Some(1),+ };+ // Both streams are trimmed, then joined with `\n`.+ assert_eq!(+ err.combined_output(),+ "warning: line 1\nfatal: line 2\ntrailing-stdout-error",+ );+ }++ #[test]+ fn command_error_combined_output_drops_empty_streams() {+ let err = CommandError {+ program: "git".into(),+ args: vec!["status".into()],+ stderr: " ".into(),+ stdout: "actual error on stdout".into(),+ exit_code: Some(1),+ };+ assert_eq!(err.combined_output(), "actual error on stdout");+ }++ #[test]+ fn command_error_signal_kill_omits_exit_code() {+ let err = CommandError {+ program: "git".into(),+ args: vec!["fetch".into()],+ stderr: String::new(),+ stdout: String::new(),+ exit_code: None,+ };+ assert_eq!(err.to_string(), "git fetch failed");+ }++ #[test]+ fn find_command_error_walks_anyhow_chain() {+ // Wrapping with `.context(...)` must not hide the typed leaf — the+ // helper should pull it out regardless of how many layers wrap.+ let err: anyhow::Error = Err::<(), _>(sample_command_error())+ .context("listing worktrees")+ .context("running prune")+ .unwrap_err();++ let cmd_err = find_command_error(&err).expect("CommandError should be found in chain");+ assert_eq!(cmd_err.program, "git");+ assert_eq!(+ cmd_err.args,+ vec!["worktree".to_string(), "list".to_string()]+ );+ assert!(cmd_err.stderr.contains("not a git repository"));+ }++ #[test]+ fn find_command_error_returns_none_for_unrelated_error() {+ let err = anyhow::anyhow!("some other failure");+ assert!(find_command_error(&err).is_none());+ }}diff --git a/src/git/mod.rs b/src/git/mod.rsindex b6792e6af..3111a5c82 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -38,6 +38,8 @@ pub const NULL_OID: &str = "0000000000000000000000000000000000000000";pub(crate) use diff::DiffStats;pub use diff::{LineDiff, parse_numstat_line};pub use error::{+ // Typed leaf error for buffered command-runner failures (downcast target)+ CommandError,// Structured command failure infoFailedCommand,// Typed error enum (Display produces styled output)@@ -52,7 +54,11 @@ pub use error::{WorktrunkError,// Error inspection functionsadd_hook_skip_hint,+ // User-facing detail string (prefers CommandError stderr)+ display_message,exit_code,+ // Walk an anyhow chain for the first CommandError+ find_command_error,interrupt_exit_code,};pub use parse::{parse_porcelain_z, parse_untracked_files};diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex a027cc1f6..fd5b2bf5b 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -1289,18 +1289,9 @@ impl Repository {.with_context(|| format!("Failed to execute: git {}", args.join(" ")))?;if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- // Normalize carriage returns to newlines for consistent output- // Git uses \r for progress updates; in non-TTY contexts this causes snapshot instability- let stderr = stderr.replace('\r', "\n");- // Some git commands print errors to stdout (e.g., `commit` with nothing to commit)- let stdout = String::from_utf8_lossy(&output.stdout);- let error_msg = [stderr.trim(), stdout.trim()]- .into_iter()- .filter(|s| !s.is_empty())- .collect::<Vec<_>>()- .join("\n");- bail!("{}", error_msg);+ return Err(+ super::error::CommandError::from_failed_output("git", args, &output).into(),+ );}let stdout = String::from_utf8_lossy(&output.stdout).into_owned();@@ -1479,23 +1470,39 @@ impl Repository {.with_context(|| format!("Failed to execute: git {}", args.join(" ")))}- /// Extract structured failure info from a [`Repository::run_command_delayed_stream`] error.+ /// Extract structured failure info from a command-runner error.///- /// Returns `(output, Some(FailedCommand))` if the error is a `StreamCommandError`,- /// or `(error_string, None)` for other error types (e.g., spawn failures).+ /// Returns `(output, Some(FailedCommand))` when the chain carries+ /// either a `StreamCommandError` (from `run_command_delayed_stream`)+ /// or a [`super::error::CommandError`] (from `run_command` /+ /// `WorkingTree::run_command`). Falls back to `(error_string, None)`+ /// for other error types (e.g., spawn failures).pub fn extract_failed_command(err: &anyhow::Error,) -> (String, Option<super::error::FailedCommand>) {- match err.downcast_ref::<StreamCommandError>() {- Some(e) => (+ if let Some(e) = err.downcast_ref::<StreamCommandError>() {+ return (e.output.clone(),Some(super::error::FailedCommand {command: e.command.clone(),exit_info: e.exit_info.clone(),}),- ),- None => (err.to_string(), None),+ );+ }+ if let Some(cmd_err) = super::error::find_command_error(err) {+ let exit_info = match cmd_err.exit_code {+ Some(code) => format!("exit code {code}"),+ None => "killed by signal".to_string(),+ };+ return (+ cmd_err.combined_output(),+ Some(super::error::FailedCommand {+ command: cmd_err.command_string(),+ exit_info,+ }),+ );}+ (err.to_string(), None)}}diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rsindex 207f9e487..99078f04d 100644--- a/src/git/repository/tests.rs+++ b/src/git/repository/tests.rs@@ -562,6 +562,33 @@ fn extract_failed_command_from_other_error() {assert!(cmd.is_none());}+#[test]+fn extract_failed_command_from_command_error() {+ // A buffered `git` failure (Repository::run_command,+ // WorkingTree::run_command) surfaces as a typed CommandError, possibly+ // wrapped by `.context(...)`. extract_failed_command must walk the+ // chain so callers like switch::worktree_creation_error keep working.+ use crate::git::CommandError;+ use anyhow::Context;++ let inner = CommandError {+ program: "git".into(),+ args: vec!["worktree".into(), "add".into(), "/path".into()],+ stderr: "fatal: invalid reference: foo".into(),+ stdout: String::new(),+ exit_code: Some(128),+ };+ let err: anyhow::Error = Err::<(), _>(inner)+ .context("creating worktree")+ .unwrap_err();++ let (output, cmd) = super::Repository::extract_failed_command(&err);+ assert_eq!(output, "fatal: invalid reference: foo");+ let cmd = cmd.unwrap();+ assert_eq!(cmd.command, "git worktree add /path");+ assert_eq!(cmd.exit_info, "exit code 128");+}+#[test]fn is_builtin_fsmonitor_enabled_variants() {use super::RepoCache;diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 76ccc714c..35a8891c1 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -2,13 +2,14 @@use std::path::{Path, PathBuf};-use anyhow::{Context, bail};+use anyhow::Context;use dashmap::mapref::entry::Entry;use crate::shell_exec::Cmd;use dunce::canonicalize;use super::{GitError, LineDiff, Repository};+use crate::git::CommandError;/// Parse `git submodule status` output and detect whether any submodule is initialized.///@@ -120,15 +121,7 @@ impl<'a> WorkingTree<'a> {let output = self.run_command_output(args)?;if !output.status.success() {- let stderr = String::from_utf8_lossy(&output.stderr);- let stderr = stderr.replace('\r', "\n");- let stdout = String::from_utf8_lossy(&output.stdout);- let error_msg = [stderr.trim(), stdout.trim()]- .into_iter()- .filter(|s| !s.is_empty())- .collect::<Vec<_>>()- .join("\n");- bail!("{}", error_msg);+ return Err(CommandError::from_failed_output("git", args, &output).into());}let stdout = String::from_utf8_lossy(&output.stdout).into_owned();diff --git a/src/main.rs b/src/main.rsindex fb0672d9e..60a4f8272 100644--- a/src/main.rs+++ b/src/main.rs@@ -1289,20 +1289,81 @@ fn dispatch_command(}fn print_command_error(error: &anyhow::Error) {+ let formatted = format_command_error(error);+ if !formatted.is_empty() {+ // Route through `worktrunk::styling::eprintln` (anstream) so ANSI+ // codes are stripped when stderr isn't a TTY. Building a String+ // and using `std::eprint!` would bypass the strip stream and leak+ // raw escape sequences into snapshots.+ eprintln!("{}", formatted.trim_end_matches('\n'));+ }+}++/// Render an error for terminal display. Returns the full formatted output+/// (including a trailing newline when non-empty) so tests can assert on it+/// without capturing stderr.+fn format_command_error(error: &anyhow::Error) -> String {+ use std::fmt::Write;+ let mut out = String::new();// GitError, WorktrunkError, and HookErrorWithHint produce styled output via Display.// Some variants (AlreadyDisplayed, CommandNotApproved) have empty Display impls —- // skip eprintln! for those to avoid phantom blank lines.+ // skip writes for those to avoid phantom blank lines.if let Some(err) = error.downcast_ref::<worktrunk::git::GitError>() {- eprintln!("{}", err);+ let _ = writeln!(out, "{err}");} else if let Some(err) = error.downcast_ref::<worktrunk::git::WorktrunkError>() {let display = err.to_string();if !display.is_empty() {- eprintln!("{display}");+ let _ = writeln!(out, "{display}");}} else if let Some(err) = error.downcast_ref::<worktrunk::git::HookErrorWithHint>() {- eprintln!("{}", err);+ let _ = writeln!(out, "{err}");} else if let Some(err) = error.downcast_ref::<worktrunk::config::TemplateExpandError>() {- eprintln!("{}", err);+ let _ = writeln!(out, "{err}");+ } else if worktrunk::git::find_command_error(error).is_some() {+ // Captured stderr/stdout from a buffered command (Repository::run_command,+ // WorkingTree::run_command). The header is the top-level message+ // (the outermost `.context(...)` if any, else the CommandError's+ // single-line summary). The gutter shows intermediate context+ // entries followed by the captured output, so wrapped failures+ // like `.context("listing worktrees").context("running prune")`+ // keep their diagnostic context while still surfacing git's+ // actual stderr.+ let _ = writeln!(out, "{}", error_message(error.to_string()));++ let mut gutter_parts: Vec<String> = Vec::new();+ let mut command_handled = false;+ for cause in error.chain().skip(1) {+ if !command_handled+ && let Some(cmd_err) = cause.downcast_ref::<worktrunk::git::CommandError>()+ {+ let body = cmd_err.combined_output();+ gutter_parts.push(if body.is_empty() {+ cmd_err.to_string()+ } else {+ body+ });+ command_handled = true;+ } else {+ gutter_parts.push(cause.to_string());+ }+ }+ if !command_handled {+ // Top-level error itself was the CommandError — header is its+ // single-line summary; put the captured body in the gutter.+ if let Some(cmd_err) = error.downcast_ref::<worktrunk::git::CommandError>() {+ let body = cmd_err.combined_output();+ if !body.is_empty() {+ gutter_parts.push(body);+ }+ }+ }+ if !gutter_parts.is_empty() {+ let _ = writeln!(+ out,+ "{}",+ format_with_gutter(&gutter_parts.join("\n"), None)+ );+ }} else {// Anyhow error formatting:// - With context: show context as header, root cause in gutter@@ -1312,20 +1373,32 @@ fn print_command_error(error: &anyhow::Error) {if !msg.is_empty() {let chain: Vec<String> = error.chain().skip(1).map(|e| e.to_string()).collect();if !chain.is_empty() {- eprintln!("{}", error_message(&msg));+ let _ = writeln!(out, "{}", error_message(&msg));let chain_text = chain.join("\n");- eprintln!("{}", format_with_gutter(&chain_text, None));+ let _ = writeln!(out, "{}", format_with_gutter(&chain_text, None));} else if msg.contains('\n') || msg.contains('\r') {- debug_assert!(false, "Multiline error without context: {msg}");- log::warn!("Multiline error without context: {msg}");+ // A multi-line error reached this branch without being wrapped+ // in a typed `CommandError` and without `.context(...)` on top.+ // Buffered command failures should always surface as+ // `CommandError`; if you hit this assert, route the failing+ // path through `Repository::run_command` /+ // `WorkingTree::run_command` (or construct a+ // `worktrunk::git::CommandError` directly) instead of+ // `bail!("{stderr}")`.+ debug_assert!(+ false,+ "Multiline error without CommandError or context: {msg}"+ );+ log::warn!("Multiline error without CommandError or context: {msg}");let normalized = msg.replace("\r\n", "\n").replace('\r', "\n");- eprintln!("{}", error_message("Command failed"));- eprintln!("{}", format_with_gutter(&normalized, None));+ let _ = writeln!(out, "{}", error_message("Command failed"));+ let _ = writeln!(out, "{}", format_with_gutter(&normalized, None));} else {- eprintln!("{}", error_message(&msg));+ let _ = writeln!(out, "{}", error_message(&msg));}}}+ out}fn print_cwd_removed_hint_if_needed() {@@ -1453,22 +1526,110 @@ fn main() {#[cfg(test)]mod tests {use super::*;+ use worktrunk::git::CommandError;++ fn permission_denied_command_error() -> CommandError {+ // Faithful reproduction of the failure shape from issue #2564:+ // git emits a multi-line stderr (warning + fatal) and exits 128.+ CommandError {+ program: "git".into(),+ args: vec!["worktree".into(), "list".into()],+ stderr: "warning: unable to access '.git/config': Permission denied\nfatal: unknown error occurred while reading the configuration files".into(),+ stdout: String::new(),+ exit_code: Some(128),+ }+ }- /// Regression: an anyhow error whose top-level message has the multi-line- /// stderr from a failing git command — but a non-empty chain — must take- /// the chain branch, not the `debug_assert!` branch. Real-world example:- /// step_prune callers wrap `repo.run_command(...)` failures with- /// `.context("listing worktrees")?`, so the multi-line git stderr ends up- /// in the chain rather than as the top-level message.+ /// Regression for #2564: a buffered `git` failure surfaces as a typed+ /// `CommandError`. The single-line summary becomes the header and the+ /// multi-line stderr lands in the gutter — no `debug_assert!` panic.#[test]- fn print_command_error_handles_multiline_with_context() {- let inner = anyhow::anyhow!(- "warning: unable to access '.git/config': Permission denied\nfatal: unknown error occurred while reading the configuration files"- );- let err: anyhow::Error = Err::<(), _>(inner)+ fn renders_command_error_without_context() {+ let err: anyhow::Error = permission_denied_command_error().into();+ let out = format_command_error(&err);+ assert!(out.contains("git worktree list failed (exit 128)"));+ assert!(out.contains("Permission denied"));+ assert!(out.contains("unknown error occurred while reading"));+ }++ /// One `.context(...)` layer above the `CommandError` — the context is+ /// the header, captured stderr is the body.+ #[test]+ fn renders_command_error_with_one_context() {+ let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())+ .context("listing worktrees")+ .unwrap_err();+ let out = format_command_error(&err);+ assert!(out.contains("listing worktrees"));+ assert!(out.contains("Permission denied"));+ }++ /// Codex P3: when a `CommandError` is wrapped by *multiple*+ /// `.context(...)` layers, intermediate context entries must appear in+ /// the gutter — they were dropped by an earlier rev that only used the+ /// top-level message.+ #[test]+ fn renders_command_error_preserves_intermediate_context() {+ let err: anyhow::Error = Err::<(), _>(permission_denied_command_error()).context("listing worktrees")+ .context("running prune")+ .unwrap_err();+ let out = format_command_error(&err);+ // Outer context is the header+ assert!(+ out.contains("running prune"),+ "missing outer context: {out}"+ );+ // Intermediate context survives — the bug Codex flagged+ assert!(+ out.contains("listing worktrees"),+ "intermediate context dropped: {out}",+ );+ // Stderr body still rendered+ assert!(out.contains("Permission denied"), "stderr lost: {out}",);+ // The `CommandError` summary itself shouldn't appear when its+ // body replaced its slot — we want git's actual error, not our+ // wrapper.+ assert!(+ !out.contains("git worktree list failed"),+ "summary surfaced alongside stderr: {out}",+ );+ }++ /// A `CommandError` with empty stderr/stdout (e.g., a child killed by+ /// a signal before producing output) wrapped in context: the gutter+ /// should fall back to the `CommandError` summary so the user sees+ /// something more than just the outer context. Exercises the+ /// empty-body branch of the renderer's gutter assembly.+ #[test]+ fn renders_command_error_with_empty_body() {+ let empty = CommandError {+ program: "git".into(),+ args: vec!["fetch".into()],+ stderr: String::new(),+ stdout: String::new(),+ exit_code: None,+ };+ let err: anyhow::Error = Err::<(), _>(empty).context("syncing remotes").unwrap_err();+ let out = format_command_error(&err);+ assert!(out.contains("syncing remotes"));+ // No body to render, so the summary is what we surface.+ assert!(out.contains("git fetch failed"));+ }++ /// Codex P2: typed `GitError` wrappers (e.g., `WorktreeRemovalFailed`,+ /// `PushFailed`) embed a stringified sub-error into their `error`+ /// field. With `display_message`, that field carries git's stderr+ /// rather than our `CommandError` summary.+ #[test]+ fn display_message_prefers_command_error_stderr_over_summary() {+ let err: anyhow::Error = Err::<(), _>(permission_denied_command_error())+ .context("creating worktree").unwrap_err();- // Must not panic the debug_assert. The chain branch handles this.- print_command_error(&err);+ let detail = worktrunk::git::display_message(&err);+ assert!(detail.contains("Permission denied"));+ assert!(detail.contains("unknown error occurred while reading"));+ // Without find_command_error this would be "creating worktree".+ assert!(!detail.starts_with("creating worktree"));}}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 2525dd948..439cb0495 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -449,7 +449,10 @@ fn handle_branch_deletion_result("{}",error_message(cformat!("Failed to delete branch <bold>{branch_name}</>")));- eprintln!("{}", format_with_gutter(&e.to_string(), None));+ eprintln!(+ "{}",+ format_with_gutter(&worktrunk::git::display_message(&e), None)+ );Err(e)}}@@ -1265,7 +1268,7 @@ fn handle_detached_removed_worktree_output(branch: path_dir_name(ctx.worktree_path).to_string(),path: ctx.worktree_path.to_path_buf(),remaining_entries: list_remaining_entries(ctx.worktree_path),- error: err.to_string(),+ error: worktrunk::git::display_message(&err),})?;let (files, bytes) = output.staged_path@@ -1341,7 +1344,7 @@ fn handle_named_removed_worktree_foreground(branch: branch_name.into(),path: ctx.worktree_path.to_path_buf(),remaining_entries: list_remaining_entries(ctx.worktree_path),- error: err.to_string(),+ error: worktrunk::git::display_message(&err),})?;let stats = output.staged_path