Skip to content

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

fix(rebase): surface Ctrl-C during rebase as interrupt, not conflict (#3539)

Worktrunk Bot3554f4979aca
diff --git a/.config/clawpatch/features/feat_custom_signal_handling.json b/.config/clawpatch/features/feat_custom_signal_handling.json
index 6ecb47806..1ec6eb982 100644
--- a/.config/clawpatch/features/feat_custom_signal_handling.json
+++ b/.config/clawpatch/features/feat_custom_signal_handling.json
@@ -2,7 +2,7 @@
"schemaVersion": 1,
"featureId": "feat_custom_signal_handling",
"title": "Signal handling: Ctrl-C aborts every child-process loop",
- "summary": "wt installs a signal_hook SIGINT/SIGTERM handler that forwards signals to child process groups, so wt itself does not die from the user's Ctrl-C, only the current child does. Every foreground loop that runs multiple child processes (`wt step for-each`, hook pipelines, alias steps, concurrent groups) MUST abort on a signal-derived child exit instead of charging into the next iteration: otherwise one Ctrl-C against `wt merge` runs the remaining hook steps, with FailureStrategy::Warn silently swallowing each interrupt. Detect via `err.interrupt_exit_code()` (the worktrunk::git::ErrorExt trait); the check happens before any FailureStrategy branch. The structured channel is WorktrunkError::ChildProcessExited { signal }, never sniff code >= 128. See CLAUDE.md > Signal Handling.",
+ "summary": "wt installs a signal_hook SIGINT/SIGTERM handler that forwards signals to child process groups, so wt itself does not die from the user's Ctrl-C, only the current child does. Every foreground loop that runs multiple child processes (`wt step for-each`, hook pipelines, alias steps, concurrent groups) MUST abort on a signal-derived child exit instead of charging into the next iteration: otherwise one Ctrl-C against `wt merge` runs the remaining hook steps, with FailureStrategy::Warn silently swallowing each interrupt. Detect via `err.interrupt_signal()` (the worktrunk::git::ErrorExt trait); the check happens before any FailureStrategy branch. The structured channel is WorktrunkError::ChildProcessExited { signal }, never sniff code >= 128. See CLAUDE.md > Signal Handling.",
"kind": "library",
"source": "manual",
"confidence": "high",
@@ -25,7 +25,7 @@
},
{
"path": "src/git/error.rs",
- "reason": "ErrorExt::interrupt_exit_code and the WorktrunkError::ChildProcessExited signal channel"
+ "reason": "ErrorExt::interrupt_signal and the WorktrunkError::ChildProcessExited signal channel"
}
],
"contextFiles": [
diff --git a/CLAUDE.md b/CLAUDE.md
index 516bdce45..2d33f9632 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -122,10 +122,11 @@ When a child process exits from a signal (SIGINT, SIGTERM), every loop in the fo
Why: wt installs a `signal_hook` SIGINT/SIGTERM handler so it can forward signals to child process groups before exiting cleanly. As a side effect wt itself does not die from the user's Ctrl-C — only the current child does. Without this policy a single Ctrl-C against `wt merge` would charge through the remaining hook steps, with `FailureStrategy::Warn` silently swallowing each interrupt.
-- Signal-derived child exits surface as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`. The `signal` field is the structured channel — never sniff `code >= 128` or parse error messages.
-- Detect via `err.interrupt_exit_code()` (the `worktrunk::git::ErrorExt` trait). When it returns `Some(exit_code)`, propagate as `WorktrunkError::AlreadyDisplayed { exit_code }` (`128 + sig` by convention — 130 SIGINT, 143 SIGTERM) and break the loop.
+- Signal-derived child exits surface structurally: stream mode (`Cmd::stream`) as `WorktrunkError::ChildProcessExited { signal: Some(sig), .. }`, capture mode (`Cmd::run`) as `CommandError { signal: Some(sig), .. }`. These fields are the structured channel — never sniff `code >= 128` or parse error messages.
+- Detect via `err.interrupt_signal()` (the `worktrunk::git::ErrorExt` trait). When it returns `Some(signal)`, propagate as `WorktrunkError::Interrupted { signal, hint }` and break the loop. `Interrupted` exits `128 + signal` (130 SIGINT, 143 SIGTERM) and renders once, at exit, per shell convention: silent for SIGINT (the terminal echoed `^C`), `Terminated` for SIGTERM — the line the shell would print if wt weren't trapping the signal. `hint` carries an optional recovery line for state the interrupt left behind (e.g. a mid-rebase worktree).
+- In capture mode only SIGINT/SIGTERM classify as interrupts. Capture children get no forwarding or escalation, and their captured output would be discarded by the silent exit — so a child killed by any other signal (a crash, an OOM kill) surfaces as a visible error instead. Stream mode counts any signal: output already streamed to the terminal, and user-initiated kills are normalized upstream to the originating SIGINT/SIGTERM (`seen_signal` in `shell_exec`, the concurrent runner's originating-signal override).
- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.
-- `handle_command_error` in `src/commands/command_executor.rs` enforces this for hook and alias pipelines (foreground and concurrent groups); `for_each.rs` enforces it for the worktree loop. New code that loops over child processes calls `.interrupt_exit_code()` on per-iteration errors and breaks.
+- `handle_command_error` in `src/commands/command_executor.rs` enforces this for hook and alias pipelines (foreground and concurrent groups); `for_each.rs` enforces it for the worktree loop. New code that loops over child processes calls `.interrupt_signal()` on per-iteration errors and breaks.
### Project Commands Run Only After Approval
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 885fc97f1..16eb66108 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -71,7 +71,7 @@ impl PreparedStep {
/// Receives the failing command, the message extracted from the inner error,
/// and the optional exit code (set when the inner error is
/// `WorktrunkError::ChildProcessExited`). Signal-derived errors bypass this
-/// wrapper and short-circuit to `AlreadyDisplayed` — see
+/// wrapper and short-circuit to `Interrupted` — see
/// [`handle_command_error`] for the rationale.
///
/// The wrapper is invoked on the calling thread after concurrent children
@@ -668,19 +668,19 @@ pub fn alias_error_wrapper(alias_name: String) -> ErrorWrapper {
/// Handle a command execution error via the step's `ErrorWrapper`.
///
-/// Signal-derived child exits (SIGINT/SIGTERM) bypass the wrapper and
-/// `failure_strategy`: the error is returned as `AlreadyDisplayed` with the
-/// `128 + signal` exit code so the enclosing loop aborts. This enforces the
-/// project-wide Ctrl-C cancellation policy — see the "Signal Handling"
-/// section of the root `CLAUDE.md` for the rationale.
+/// Signal-derived child exits bypass the wrapper and `failure_strategy`:
+/// the error is returned as `Interrupted` (exiting `128 + signal`) so the
+/// enclosing loop aborts. This enforces the project-wide Ctrl-C cancellation
+/// policy — see the "Signal Handling" section of the root `CLAUDE.md` for
+/// the rationale.
fn handle_command_error(
err: anyhow::Error,
cmd: &PreparedCommand,
error_wrapper: &ErrorWrapper,
failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
- if let Some(exit_code) = err.interrupt_exit_code() {
- return Err(WorktrunkError::AlreadyDisplayed { exit_code }.into());
+ if let Some(signal) = err.interrupt_signal() {
+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());
}
let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
@@ -895,7 +895,10 @@ mod tests {
let wt_err = err.downcast_ref::<WorktrunkError>().unwrap();
assert!(matches!(
wt_err,
- WorktrunkError::AlreadyDisplayed { exit_code: 143 }
+ WorktrunkError::Interrupted {
+ signal: 15,
+ hint: None
+ }
));
}
diff --git a/src/commands/custom.rs b/src/commands/custom.rs
index 0da94a122..0c6b02675 100644
--- a/src/commands/custom.rs
+++ b/src/commands/custom.rs
@@ -48,7 +48,8 @@ use crate::enhance_clap_error;
/// for project-config aliases.
///
/// On success (child exit code 0), returns `Ok(())`. On non-zero exit, returns
-/// `WorktrunkError::AlreadyDisplayed` with the child's exit code so `main`
+/// `WorktrunkError::AlreadyDisplayed` with the child's exit code (or
+/// `Interrupted` for a signal kill) so `main`
/// can propagate it without printing an extra error line. When the command
/// isn't found on PATH, returns `AlreadyDisplayed` via `enhance_clap_error`
/// with clap's standard exit code 2.
@@ -150,15 +151,19 @@ fn run_custom(path: &Path, args: &[OsString], working_dir: Option<&Path>) -> Res
return Ok(());
}
- // Propagate the exact exit code — including signal codes on Unix — so
- // `wt foo` behaves like running `wt-foo` directly. We use
- // `AlreadyDisplayed` (not `ChildProcessExited`) because the custom
- // command has already reported its own failure to the user; `wt` should
- // just forward the exit code without adding a second error line.
+ // Propagate the exact exit status so `wt foo` behaves like running
+ // `wt-foo` directly. A signal kill surfaces as `Interrupted` (exit
+ // `128 + sig`, rendered per shell convention — a signal-killed child
+ // usually never got to report anything, and wt's own survival suppresses
+ // the shell's "Terminated" line). A plain non-zero exit surfaces as
+ // `AlreadyDisplayed` (not `ChildProcessExited`): the custom command
+ // already reported its own failure, so `wt` just forwards the code
+ // without adding a second error line.
#[cfg(unix)]
if let Some(sig) = std::os::unix::process::ExitStatusExt::signal(&status) {
- return Err(WorktrunkError::AlreadyDisplayed {
- exit_code: 128 + sig,
+ return Err(WorktrunkError::Interrupted {
+ signal: sig,
+ hint: None,
}
.into());
}
@@ -252,14 +257,17 @@ mod tests {
let sh = Path::new("/bin/sh");
let args = [OsString::from("-c"), OsString::from("kill -TERM $$")];
+ use worktrunk::git::ErrorExt;
+
let err = run_custom(sh, &args, None).expect_err("child killed by SIGTERM");
let wt_err = err
.downcast_ref::<WorktrunkError>()
- .expect("signal should surface as WorktrunkError::AlreadyDisplayed");
+ .expect("signal should surface as WorktrunkError::Interrupted");
match wt_err {
- WorktrunkError::AlreadyDisplayed { exit_code } => {
- // SIGTERM = 15, and the shell-style convention is 128 + signal.
- assert_eq!(*exit_code, 128 + 15);
+ WorktrunkError::Interrupted { signal, hint: None } => {
+ assert_eq!(*signal, 15);
+ // The shell-style convention is 128 + signal.
+ assert_eq!(err.exit_code(), Some(143));
}
other => panic!("unexpected WorktrunkError variant: {other:?}"),
}
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 6395a8c13..90cc985a4 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -59,9 +59,9 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
let mut failed: Vec<String> = Vec::new();
let mut json_results: Vec<serde_json::Value> = Vec::new();
- // Set when a child dies from a signal (Ctrl-C / SIGTERM). We abort the
- // loop and propagate an equivalent exit code rather than visiting the
- // remaining worktrees — the user asked for the work to stop.
+ // The signal a child died from (Ctrl-C / SIGTERM), if any. We abort the
+ // loop and propagate `Interrupted` rather than visiting the remaining
+ // worktrees — the user asked for the work to stop.
let mut interrupted: Option<i32> = None;
let total = worktrees.len();
@@ -113,7 +113,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
}
}
Err(err) => {
- let signal_exit = err.interrupt_exit_code();
+ let signal_exit = err.interrupt_signal();
// Two error strings: a styled block for stderr (preserves
// hints from typed diagnostics) and a plain string for
// JSON (consumers shouldn't see ANSI codes or symbols).
@@ -153,15 +153,15 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
"error": json_detail,
}));
}
- if let Some(code) = signal_exit {
- interrupted = Some(code);
+ if let Some(signal) = signal_exit {
+ interrupted = Some(signal);
break;
}
}
}
}
- if let Some(exit_code) = interrupted {
+ if let Some(signal) = interrupted {
if json_mode {
println!("{}", serde_json::to_string_pretty(&json_results)?);
} else {
@@ -171,7 +171,7 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
warning_message("Interrupted — skipped remaining worktrees")
);
}
- return Err(WorktrunkError::AlreadyDisplayed { exit_code }.into());
+ return Err(WorktrunkError::Interrupted { signal, hint: None }.into());
}
if json_mode {
diff --git a/src/commands/run_pipeline.rs b/src/commands/run_pipeline.rs
index 9dd276c03..50229311e 100644
--- a/src/commands/run_pipeline.rs
+++ b/src/commands/run_pipeline.rs
@@ -312,7 +312,7 @@ fn create_command_log(spec: &PipelineSpec, name: &str) -> anyhow::Result<fs::Fil
/// Signal-killed children surface as `WorktrunkError::ChildProcessExited`
/// with `signal: Some(sig)` and `code: 128 + sig`, matching the foreground
/// convention established by `shell_exec`. That lets `exit_code()` and
-/// `interrupt_exit_code()` work consistently and the `wt hook run-pipeline`
+/// `interrupt_signal()` work consistently and the `wt hook run-pipeline`
/// process exits 130 on SIGINT and 143 on SIGTERM — the expectation the
/// "Signal Handling" section of the project `CLAUDE.md` sets for every
/// command loop.
@@ -404,9 +404,9 @@ mod tests {
assert_eq!(code, expected_code, "exit code for {sig}");
assert_eq!(message, expected_msg, "message for {sig}");
assert_eq!(
- err.interrupt_exit_code(),
- Some(expected_code),
- "interrupt_exit_code for {sig}",
+ err.interrupt_signal(),
+ Some(sig),
+ "interrupt_signal for {sig}"
);
}
}
@@ -421,6 +421,6 @@ mod tests {
assert_eq!(code, 2);
assert_eq!(message, "command failed with exit code 2: my-step");
// Non-signal errors must NOT trip the interrupt abort path.
- assert_eq!(err.interrupt_exit_code(), None);
+ assert_eq!(err.interrupt_signal(), None);
}
}
diff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rs
index b15b8bde4..a74f212b3 100644
--- a/src/commands/step/rebase.rs
+++ b/src/commands/step/rebase.rs
@@ -44,32 +44,12 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
let rebase_result = repo.run_command(&["rebase", "--end-of-options", &integration_target]);
- // If rebase failed, check if it's due to conflicts
+ // If rebase failed, classify the failure (interrupt vs conflict vs other).
if let Err(e) = rebase_result {
- // Check if it's a rebase conflict
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 = e.display_message();
- if is_rebasing {
- return Err(worktrunk::git::GitError::RebaseConflict {
- target_branch: integration_target,
- git_output: detail,
- }
- .into());
- }
- // Not a rebase conflict, return original error
- return Err(worktrunk::git::GitError::Other {
- message: cformat!(
- "Failed to rebase onto <bold>{}</>: {}",
- integration_target,
- detail
- ),
- }
- .into());
+ return Err(classify_rebase_failure(e, is_rebasing, &integration_target));
}
// Verify rebase completed successfully (safety check for edge cases)
@@ -94,3 +74,178 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {
fast_forward: is_fast_forward,
})
}
+
+/// Turn a failed `git rebase` invocation into the right typed error.
+///
+/// A forwarded Ctrl-C/SIGTERM kills git mid-rebase and leaves the worktree in
+/// `REBASING` state, which is otherwise indistinguishable from a merge
+/// conflict. The interrupt is surfaced as `Interrupted` *before* the conflict
+/// check, per the signal-handling policy in `CLAUDE.md`: otherwise a user who
+/// aborts `wt merge` gets conflict-resolution guidance and a non-130 exit code
+/// instead of a clean interrupt. When the kill left the worktree mid-rebase,
+/// the interrupt carries a recovery hint — git ran in capture mode, so none
+/// of its output was shown, and without the hint the otherwise-clean exit
+/// would hide the `REBASING` state left behind.
+fn classify_rebase_failure(e: anyhow::Error, is_rebasing: bool, target: &str) -> anyhow::Error {
+ if let Some(signal) = e.interrupt_signal() {
+ let hint = is_rebasing.then(|| {
+ cformat!(
+ "Rebase onto <underline>{target}</> left in progress; to abort, run <underline>git rebase --abort</>"
+ )
+ });
+ return worktrunk::git::WorktrunkError::Interrupted { signal, hint }.into();
+ }
+
+ // 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 = e.display_message();
+ if is_rebasing {
+ return worktrunk::git::GitError::RebaseConflict {
+ target_branch: target.to_string(),
+ git_output: detail,
+ }
+ .into();
+ }
+ worktrunk::git::GitError::Other {
+ message: cformat!("Failed to rebase onto <bold>{target}</>: {detail}"),
+ }
+ .into()
+}
+
+#[cfg(test)]
+mod tests {
+ use super::classify_rebase_failure;
+ use worktrunk::git::WorktrunkError::Interrupted;
+ use worktrunk::git::{CommandError, ErrorExt, GitError, WorktrunkError};
+
+ fn child_exit(code: i32, signal: Option<i32>) -> anyhow::Error {
+ WorktrunkError::ChildProcessExited {
+ code,
+ message: "rebase failed".to_string(),
+ signal,
+ }
+ .into()
+ }
+
+ /// The error shape `run_command` (capture mode) actually returns on a
+ /// signal-killed git: a `CommandError` carrying `status.signal()`, wrapped
+ /// by `run_command`'s `.context("Failed to execute: git …")` layer.
+ fn capture_signal_failure(signal: i32) -> anyhow::Error {
+ use anyhow::Context;
+ Err::<(), _>(CommandError {
+ program: "git".into(),
+ args: vec!["rebase".into()],
+ stderr: String::new(),
+ stdout: String::new(),
+ exit_code: None,
+ signal: Some(signal),
+ })
+ .context("Failed to execute: git rebase")
+ .unwrap_err()
+ }
+
+ #[test]
+ fn capture_mode_interrupt_is_not_classified_as_conflict() {
+ // This is the real path: `repo.run_command(["rebase", …])` returns a
+ // CommandError (not ChildProcessExited), so the classifier must recover
+ // the signal from the CommandError's `signal` field. With `is_rebasing`
+ // true (git left the worktree REBASING), the old code fell through to
+ // RebaseConflict; the interrupt must win.
+ let err = classify_rebase_failure(capture_signal_failure(2), true, "main");
+ assert_eq!(err.exit_code(), Some(130));
+ // Downcasts are bound (and the variant imported) so each `matches!`
+ // stays on one line: a passing positive `matches!` never runs its
+ // generated false arm, and with a multi-line opener that region makes
+ // the opener line read as missed in patch coverage.
+ let wt_err = err.downcast_ref::<WorktrunkError>();
+ assert!(
+ matches!(wt_err, Some(Interrupted { signal: 2, .. })),
+ "capture-mode interrupt must surface as Interrupted, not a rebase conflict"
+ );
+ // Mid-rebase, the interrupt carries the recovery hint for the
+ // REBASING state it leaves behind.
+ let Some(Interrupted {
+ hint: Some(hint), ..
+ }) = wt_err
+ else {
+ panic!("mid-rebase interrupt must carry a recovery hint, got {wt_err:?}");
+ };
+ assert!(
+ hint.contains("git rebase --abort"),
+ "hint must name the recovery command, got: {hint}"
+ );
+ let git_err = err.downcast_ref::<GitError>();
+ assert!(
+ !matches!(git_err, Some(GitError::RebaseConflict { .. })),
+ "capture-mode interrupt must not be reclassified as a rebase conflict"
+ );
+ }
+
+ #[test]
+ fn capture_mode_crash_signal_stays_a_visible_error() {
+ // SIGSEGV/SIGKILL can't be wt's own doing in capture mode — no signal
+ // forwarding or escalation exists there — so the child crashed or was
+ // killed externally. That must surface as a visible error (mid-rebase,
+ // the REBASING state makes it a RebaseConflict, whose rendering
+ // carries the --abort hint), never a silent interrupt exit.
+ let crashed = classify_rebase_failure(capture_signal_failure(11), true, "main");
+ let git_err = crashed.downcast_ref::<GitError>();
+ assert!(
+ matches!(git_err, Some(GitError::RebaseConflict { .. })),
+ "a crashed git mid-rebase must surface, not exit silently"
+ );
+
+ let killed = classify_rebase_failure(capture_signal_failure(9), false, "main");
+ assert!(matches!(
+ killed.downcast_ref::<GitError>(),
+ Some(GitError::Other { .. })
+ ));
+ }
+
+ #[test]
+ fn interrupt_during_rebase_is_not_classified_as_conflict() {
+ // SIGINT (2) forwarded to git leaves the worktree REBASING; it must
+ // surface as an interrupt carrying exit 130, not a RebaseConflict
+ // with resolution guidance. Before the interrupt check this returned a
+ // GitError::RebaseConflict, whose exit_code() is None.
+ let err = classify_rebase_failure(child_exit(130, Some(2)), true, "main");
+ assert_eq!(err.exit_code(), Some(130));
+ let wt_err = err.downcast_ref::<WorktrunkError>();
+ assert!(
+ matches!(wt_err, Some(Interrupted { signal: 2, .. })),
+ "interrupt must surface as Interrupted, not a rebase conflict"
+ );
+ let git_err = err.downcast_ref::<GitError>();
+ assert!(
+ !matches!(git_err, Some(GitError::RebaseConflict { .. })),
+ "interrupt must not be reclassified as a rebase conflict"
+ );
+
+ // Outside REBASING state there's nothing to recover — no hint.
+ let err = classify_rebase_failure(child_exit(130, Some(2)), false, "main");
+ let wt_err = err.downcast_ref::<WorktrunkError>();
+ assert!(
+ matches!(wt_err, Some(Interrupted { hint: None, .. })),
+ "interrupt outside REBASING must carry no hint, got {wt_err:?}"
+ );
+ }
+
+ #[test]
+ fn conflict_in_rebasing_state_is_a_rebase_conflict() {
+ let err = classify_rebase_failure(child_exit(1, None), true, "main");
+ assert!(matches!(
+ err.downcast_ref::<GitError>(),
+ Some(GitError::RebaseConflict { .. })
+ ));
+ }
+
+ #[test]
+ fn non_rebasing_failure_is_other_error() {
+ let err = classify_rebase_failure(child_exit(1, None), false, "main");
+ assert!(matches!(
+ err.downcast_ref::<GitError>(),
+ Some(GitError::Other { .. })
+ ));
+ }
+}
diff --git a/src/git/error.rs b/src/git/error.rs
index 258933a7c..cdef26301 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -153,18 +153,17 @@ pub trait ErrorExt {
/// [`WorktrunkError`] variants that carry an exit code.
fn exit_code(&self) -> Option<i32>;
- /// If the error is signal-derived, return the equivalent shell exit
- /// code (`128 + signal`).
+ /// If the error is signal-derived, return the terminating signal.
///
/// Implements the Ctrl-C cancellation policy: command loops call this
- /// on every per-iteration failure and, when it returns `Some`, abort
- /// the loop rather than continuing. The returned code preserves the
- /// standard `128 + sig` shell convention (130 for SIGINT, 143 for
- /// SIGTERM).
+ /// on every per-iteration failure and, when it returns `Some(signal)`,
+ /// propagate [`WorktrunkError::Interrupted`] — which exits `128 + signal`
+ /// per the shell convention (130 SIGINT, 143 SIGTERM) — rather than
+ /// continuing.
///
/// See the "Signal Handling" section of the project `CLAUDE.md` for
/// the rationale and the full list of loops that apply this policy.
- fn interrupt_exit_code(&self) -> Option<i32>;
+ fn interrupt_signal(&self) -> Option<i32>;
}
/// Information about a failed command, for display in error messages.
@@ -213,8 +212,22 @@ pub struct CommandError {
pub stdout: String,
/// Process exit code; `None` if the child was killed by a signal.
pub exit_code: Option<i32>,
+ /// Terminating signal (Unix), e.g. `Some(2)` for SIGINT — `None` when the
+ /// child exited normally or on non-Unix. Capture mode (`Cmd::run`) reads
+ /// the raw `ExitStatus`, so a Ctrl-C/SIGTERM delivered to the child (which
+ /// shares the foreground process group) surfaces here; `interrupt_signal`
+ /// recovers SIGINT/SIGTERM before higher-level classification runs, while
+ /// other signals (a crash, an external kill) stay on the visible error
+ /// path.
+ pub signal: Option<i32>,
}
+/// POSIX signal numbers, defined locally so the interrupt classification
+/// compiles on Windows too (where [`CommandError::signal`] is always `None`);
+/// the `nix`/`signal-hook` crates that export these are unix-gated.
+const SIGINT: i32 = 2;
+const SIGTERM: i32 = 15;
+
impl CommandError {
/// Build from the captured `Output` of a non-zero exit.
pub fn from_failed_output(
@@ -224,12 +237,17 @@ impl CommandError {
) -> Self {
let stderr = String::from_utf8_lossy(&output.stderr).replace('\r', "\n");
let stdout = String::from_utf8_lossy(&output.stdout).replace('\r', "\n");
+ #[cfg(unix)]
+ let signal = std::os::unix::process::ExitStatusExt::signal(&output.status);
+ #[cfg(not(unix))]
+ let signal = None;
Self {
program: program.into(),
args: args.iter().map(|s| s.as_ref().to_string()).collect(),
stderr,
stdout,
exit_code: output.status.code(),
+ signal,
}
}
@@ -266,9 +284,10 @@ impl CommandError {
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()),
+ match (self.exit_code, self.signal) {
+ (Some(code), _) => write!(f, "{} failed (exit {})", self.command_string(), code),
+ (None, Some(sig)) => write!(f, "{} failed (signal {})", self.command_string(), sig),
+ (None, None) => write!(f, "{} failed", self.command_string()),
}
}
}
@@ -1382,6 +1401,15 @@ pub enum WorktrunkError {
CommandNotApproved,
/// Error already displayed, just exit with given code (silent error)
AlreadyDisplayed { exit_code: i32 },
+ /// A signal killed the foreground child and the command aborted.
+ ///
+ /// Exits `128 + signal` and renders once, at exit, following the shell
+ /// convention for a killed job: nothing for SIGINT (the terminal already
+ /// echoed `^C`), `Terminated` for SIGTERM. wt traps signals to forward
+ /// them to children, so the shell never sees wt die and won't print that
+ /// line itself. `hint` carries an optional recovery line (e.g. a rebase
+ /// left in progress) rendered under the message.
+ Interrupted { signal: i32, hint: Option<String> },
}
impl std::fmt::Display for WorktrunkError {
@@ -1400,6 +1428,11 @@ impl std::fmt::Display for WorktrunkError {
// on_skip callback handles the printing for CommandNotApproved;
// AlreadyDisplayed has already shown its error via output functions.
WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => Ok(()),
+ WorktrunkError::Interrupted { signal, .. } => match *signal {
+ SIGINT => Ok(()),
+ SIGTERM => f.write_str("Terminated"),
+ sig => write!(f, "Killed by signal {sig}"),
+ },
}
}
}
@@ -1411,6 +1444,7 @@ impl WorktrunkError {
WorktrunkError::ChildProcessExited { code, .. } => Some(*code),
WorktrunkError::HookCommandFailed { exit_code, .. } => *exit_code,
WorktrunkError::AlreadyDisplayed { exit_code } => Some(*exit_code),
+ WorktrunkError::Interrupted { signal, .. } => Some(128 + signal),
WorktrunkError::CommandNotApproved => None,
}
}
@@ -1441,6 +1475,25 @@ impl Diagnostic for WorktrunkError {
WorktrunkError::CommandNotApproved | WorktrunkError::AlreadyDisplayed { .. } => {
String::new()
}
+ WorktrunkError::Interrupted { signal, hint } => {
+ // Shell convention for a killed job: silent for SIGINT (the
+ // terminal already echoed ^C), "Terminated" for SIGTERM, the
+ // signal number otherwise (reachable only from stream mode,
+ // where any signal classifies as an interrupt).
+ let message = match *signal {
+ SIGINT => None,
+ SIGTERM => Some("Terminated".to_string()),
+ sig => Some(format!("Killed by signal {sig}")),
+ };
+ let mut parts = Vec::new();
+ if let Some(message) = message {
+ parts.push(error_message(message).to_string());
+ }
+ if let Some(hint) = hint {
+ parts.push(hint_message(hint).to_string());
+ }
+ parts.join("\n")
+ }
}
}
}
@@ -1477,15 +1530,36 @@ impl ErrorExt for anyhow::Error {
.and_then(WorktrunkError::exit_code)
}
- fn interrupt_exit_code(&self) -> Option<i32> {
- if let Some(WorktrunkError::ChildProcessExited {
- signal: Some(sig), ..
- }) = self.downcast_ref::<WorktrunkError>()
+ fn interrupt_signal(&self) -> Option<i32> {
+ // Stream mode (`Cmd::stream`) reports a signal kill as a typed
+ // `ChildProcessExited { signal }`. An error that already classified
+ // as `Interrupted` stays one, so loops that re-check errors bubbling
+ // through them can't demote it.
+ match self.downcast_ref::<WorktrunkError>() {
+ Some(WorktrunkError::ChildProcessExited {
+ signal: Some(sig), ..
+ }) => return Some(*sig),
+ Some(WorktrunkError::Interrupted { signal, .. }) => return Some(*signal),
+ _ => {}
+ }
+ // Capture mode (`Cmd::run`) reports it as a `CommandError` carrying the
+ // raw `status.signal()`. Walk the chain so `.context(...)` layers (e.g.
+ // `run_command`'s "Failed to execute: git …") don't hide it. Only
+ // SIGINT/SIGTERM classify as interrupts here: capture children get no
+ // signal forwarding or escalation (unlike stream mode, where a
+ // SIGKILL death can be wt's own escalation of a second Ctrl-C,
+ // normalized upstream to the originating signal), so any other signal
+ // means the child fell over on its own — and because its captured
+ // output was never displayed, a silent interrupt exit would discard
+ // the evidence. Those fall through to the caller's visible error path.
+ if let Some(CommandError {
+ signal: Some(sig @ (SIGINT | SIGTERM)),
+ ..
+ }) = CommandError::find_in(self)
{
- Some(128 + sig)
- } else {
- None
+ return Some(*sig);
}
+ None
}
}
@@ -1745,15 +1819,15 @@ mod tests {
}
#[test]
- fn test_interrupt_exit_code() {
- // Signal-derived child exit → 128 + sig
+ fn test_interrupt_signal() {
+ // Signal-derived child exit → the signal
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
code: 130,
message: "terminated by signal 2".into(),
signal: Some(2),
}
.into();
- assert_eq!(err.interrupt_exit_code(), Some(130));
+ assert_eq!(err.interrupt_signal(), Some(2));
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
code: 143,
@@ -1761,7 +1835,16 @@ mod tests {
signal: Some(15),
}
.into();
- assert_eq!(err.interrupt_exit_code(), Some(143));
+ assert_eq!(err.interrupt_signal(), Some(15));
+
+ // An already-classified interrupt stays one (idempotence for loops
+ // that re-check errors bubbling through them).
+ let err: anyhow::Error = WorktrunkError::Interrupted {
+ signal: 15,
+ hint: None,
+ }
+ .into();
+ assert_eq!(err.interrupt_signal(), Some(15));
// Ordinary non-zero exit → not an interrupt
let err: anyhow::Error = WorktrunkError::ChildProcessExited {
@@ -1770,26 +1853,47 @@ mod tests {
signal: None,
}
.into();
- assert_eq!(err.interrupt_exit_code(), None);
+ assert_eq!(err.interrupt_signal(), None);
// Other WorktrunkError variants → not an interrupt
assert_eq!(
anyhow::Error::from(WorktrunkError::AlreadyDisplayed { exit_code: 130 })
- .interrupt_exit_code(),
+ .interrupt_signal(),
None,
);
assert_eq!(
- anyhow::Error::from(WorktrunkError::CommandNotApproved).interrupt_exit_code(),
+ anyhow::Error::from(WorktrunkError::CommandNotApproved).interrupt_signal(),
None,
);
// Plain anyhow error → not an interrupt
assert_eq!(
- anyhow::anyhow!("some unrelated failure").interrupt_exit_code(),
+ anyhow::anyhow!("some unrelated failure").interrupt_signal(),
None,
);
}
+ #[test]
+ fn interrupt_signal_capture_mode_narrows_to_sigint_sigterm() {
+ // Capture mode has no signal forwarding or escalation, so SIGINT and
+ // SIGTERM are the only signals a user interrupt can deliver; anything
+ // else (a crash, an OOM kill) must stay on the visible error path
+ // rather than exiting silently and discarding the captured output.
+ let cases = [(2, Some(2)), (15, Some(15)), (9, None), (11, None)];
+ for (sig, expected) in cases {
+ let err: anyhow::Error = CommandError {
+ program: "git".into(),
+ args: vec!["rebase".into()],
+ stderr: String::new(),
+ stdout: String::new(),
+ exit_code: None,
+ signal: Some(sig),
+ }
+ .into();
+ assert_eq!(err.interrupt_signal(), expected, "signal {sig}");
+ }
+ }
+
#[test]
fn snapshot_add_hook_skip_hint() {
// Wraps HookCommandFailed with --no-hooks hint
@@ -2396,6 +2500,7 @@ mod tests {
stderr: "fatal: not a git repository\n".into(),
stdout: String::new(),
exit_code: Some(128),
+ signal: None,
}
}
@@ -2418,6 +2523,7 @@ mod tests {
stderr: String::new(),
stdout: String::new(),
exit_code: Some(1),
+ signal: None,
};
assert_eq!(err.command_string(), "git");
assert_eq!(err.to_string(), "git failed (exit 1)");
@@ -2431,6 +2537,7 @@ mod tests {
stderr: "warning: line 1\nfatal: line 2\n\n".into(),
stdout: " trailing-stdout-error\n".into(),
exit_code: Some(1),
+ signal: None,
};
// Both streams are trimmed, then joined with `\n`.
assert_eq!(
@@ -2447,6 +2554,7 @@ mod tests {
stderr: " ".into(),
stdout: "actual error on stdout".into(),
exit_code: Some(1),
+ signal: None,
};
assert_eq!(err.combined_output(), "actual error on stdout");
}
@@ -2481,13 +2589,25 @@ mod tests {
}
#[test]
- fn command_error_signal_kill_omits_exit_code() {
+ fn command_error_signal_kill_shows_signal_not_exit_code() {
+ // A signal-killed child has no exit code; the summary names the
+ // signal instead so the surfaced error says what happened. Matters
+ // for non-interrupt signals (SIGSEGV, SIGKILL), which reach the
+ // visible error path rather than the silent interrupt exit.
let err = CommandError {
program: "git".into(),
args: vec!["fetch".into()],
stderr: String::new(),
stdout: String::new(),
exit_code: None,
+ signal: Some(11),
+ };
+ assert_eq!(err.to_string(), "git fetch failed (signal 11)");
+
+ // No exit code and no signal (e.g. hand-built in tests): bare summary.
+ let err = CommandError {
+ signal: None,
+ ..err
};
assert_eq!(err.to_string(), "git fetch failed");
}
@@ -2515,4 +2635,78 @@ mod tests {
let err = anyhow::anyhow!("some other failure");
assert!(CommandError::find_in(&err).is_none());
}
+
+ #[cfg(unix)]
+ #[test]
+ fn from_failed_output_preserves_signal_and_interrupt_signal_recovers_it() {
+ use std::os::unix::process::ExitStatusExt;
+
+ // Capture mode (`Cmd::run`) returns the raw `Output`; a child killed by
+ // SIGINT has wait status == signal number, so `.code()` is None and
+ // `.signal()` is Some(2). Before this the signal was dropped, so
+ // `interrupt_signal()` returned None even for a signal-killed child —
+ // the classification bug that surfaced a rebase interrupt as a conflict.
+ let output = std::process::Output {
+ status: std::process::ExitStatus::from_raw(2),
+ stdout: Vec::new(),
+ stderr: Vec::new(),
+ };
+ let err = CommandError::from_failed_output("git", &["rebase"], &output);
+ assert_eq!(err.signal, Some(2));
+ assert_eq!(err.exit_code, None);
+
+ // The signal must survive `.context(...)` wrapping (run_command adds a
+ // "Failed to execute: git …" layer).
+ let wrapped: anyhow::Error = Err::<(), _>(err)
+ .context("Failed to execute: git rebase")
+ .unwrap_err();
+ assert_eq!(wrapped.interrupt_signal(), Some(2));
+ }
+
+ #[test]
+ fn interrupted_renders_by_signal_and_exits_128_plus_signal() {
+ // SIGINT: silent — the terminal already echoed ^C.
+ let sigint = WorktrunkError::Interrupted {
+ signal: 2,
+ hint: None,
+ };
+ assert_eq!(sigint.render(), "");
+ assert_eq!(sigint.to_string(), "");
+ assert_eq!(sigint.exit_code(), Some(130));
+
+ // SIGTERM: the line the shell would print if wt weren't trapping
+ // the signal.
+ let sigterm = WorktrunkError::Interrupted {
+ signal: 15,
+ hint: None,
+ };
+ assert_snapshot!(sigterm.render(), @"✗ Terminated");
+ assert_eq!(sigterm.to_string(), "Terminated");
+ assert_eq!(sigterm.exit_code(), Some(143));
+
+ // Any other signal (stream mode counts all): named by number.
+ let sigkill = WorktrunkError::Interrupted {
+ signal: 9,
+ hint: None,
+ };
+ assert_snapshot!(sigkill.render(), @"✗ Killed by signal 9");
+ assert_eq!(sigkill.to_string(), "Killed by signal 9");
+ assert_eq!(sigkill.exit_code(), Some(137));
+
+ // A hint renders under the message; with a silent SIGINT it stands
+ // alone under the user's own ^C.
+ let sigterm_hint = WorktrunkError::Interrupted {
+ signal: 15,
+ hint: Some("Rebase left in progress".to_string()),
+ };
+ assert_snapshot!(sigterm_hint.render(), @"
+ ✗ Terminated
+ ↳ Rebase left in progress
+ ");
+ let sigint_hint = WorktrunkError::Interrupted {
+ signal: 2,
+ hint: Some("Rebase left in progress".to_string()),
+ };
+ assert_snapshot!(sigint_hint.render(), @"↳ Rebase left in progress");
+ }
}
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 3785f9391..bca3227c3 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -49,7 +49,7 @@ pub use error::{
// distinct from their short single-line `Display`
Diagnostic,
// Extension methods on `anyhow::Error` (render_diagnostic,
- // display_message, exit_code, interrupt_exit_code). Bring into scope
+ // display_message, exit_code, interrupt_signal). Bring into scope
// to call them via method syntax.
ErrorExt,
// Structured command failure info
diff --git a/src/git/repository/tests.rs b/src/git/repository/tests.rs
index e48db4b00..40141bb04 100644
--- a/src/git/repository/tests.rs
+++ b/src/git/repository/tests.rs
@@ -623,6 +623,7 @@ fn extract_failed_command_from_command_error() {
stderr: "fatal: invalid reference: foo".into(),
stdout: String::new(),
exit_code: Some(128),
+ signal: None,
};
let err: anyhow::Error = Err::<(), _>(inner)
.context("creating worktree")
diff --git a/src/main.rs b/src/main.rs
index c221a43ba..c9babfbbb 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1175,6 +1175,7 @@ mod tests {
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),
+ signal: None,
}
}
@@ -1247,6 +1248,7 @@ mod tests {
stderr: String::new(),
stdout: String::new(),
exit_code: None,
+ signal: None,
};
let err: anyhow::Error = Err::<(), _>(empty).context("syncing remotes").unwrap_err();
let out = format_command_error(&err);
@@ -1283,6 +1285,7 @@ mod tests {
stderr: String::new(),
stdout: String::new(),
exit_code: None,
+ signal: None,
};
let err: anyhow::Error = empty.into();
assert_eq!(err.display_message(), "git fetch failed");
diff --git a/src/output/concurrent.rs b/src/output/concurrent.rs
index fb67870fb..3f64e5f4b 100644
--- a/src/output/concurrent.rs
+++ b/src/output/concurrent.rs
@@ -184,7 +184,7 @@ pub fn run_concurrent_commands(
// user-visible exit code shouldn't be 137 — they only ever sent SIGINT, and
// wt's escalation to SIGKILL on the second press is an implementation
// detail. Override each child's reported signal with the originating signal
- // so wt's `exit_code()` and `interrupt_exit_code()` reflect the user's
+ // so wt's `exit_code()` and `interrupt_signal()` reflect the user's
// intent (130 from SIGINT, not 137 from SIGKILL).
if let Some(orig) = originating_signal {
for outcome in &mut outcomes {
diff --git a/src/shell_exec.rs b/src/shell_exec.rs
index d18b29fa7..31b9a8b6a 100644
--- a/src/shell_exec.rs
+++ b/src/shell_exec.rs
@@ -32,7 +32,7 @@
//! exit surfaces as `WorktrunkError::ChildProcessExited { signal: Some(_) }` —
//! the structured channel that loop callers (`for-each`, hook/alias pipelines)
//! use to abort their loops on Ctrl-C rather than continuing to the next
-//! iteration. See `git/interrupt_exit_code` for the consumer side.
+//! iteration. See `git/interrupt_signal` for the consumer side.
//!
//! Concurrent foreground children (`output/concurrent.rs`) and detached
//! background children (`commands/process.rs::spawn_detached_*`) have separate
@@ -1745,7 +1745,7 @@ impl Cmd {
// success and a signal then landed before `handle.close()` ran, the
// signal arrived too late to have killed anything — the contract on
// `signal: Some(_)` is "this child was killed by the signal" and
- // `interrupt_exit_code` callers in pipeline loops break on it.
+ // `interrupt_signal` callers in pipeline loops break on it.
#[cfg(unix)]
if let Some(sig) = seen_signal
&& !status.success()