Skip to content

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

Enforce Ctrl-C cancellation policy across command loops (#2182)

Maximilian Roosa0157c3343bc
diff --git a/CLAUDE.md b/CLAUDE.md
index fa91f89df..d2561d4a3 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -238,6 +238,21 @@ if msg.contains("no merge base") { return Ok(true); }
When no structured alternative exists, document the fragility inline.
+### Signal Handling: Ctrl-C Cancels the Current Command
+
+**Policy:** when a child process exits from a signal (SIGINT, SIGTERM), every loop in the foreground execution path MUST abort rather than continue to the next iteration. This applies to worktree loops (`wt step for-each`), hook pipelines, alias steps, concurrent groups, and any future code that runs multiple child processes in sequence.
+
+**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` (or any multi-step command) would let wt charge through the remaining hook steps, with `FailureStrategy::Warn` silently swallowing each interrupt. Users expect Ctrl-C to stop the command; treating signal-derived exits as ordinary per-iteration failures violates that.
+
+**Implementation:**
+
+- 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.
+- Use `worktrunk::git::interrupt_exit_code(&err)` to detect them. When it returns `Some(exit_code)`, propagate via `WorktrunkError::AlreadyDisplayed { exit_code }` (`128 + sig` by convention — 130 for SIGINT, 143 for SIGTERM) and break the loop.
+- The check happens **before** any `FailureStrategy` branch — Warn must NOT swallow signal-derived errors.
+- `handle_command_error` in `src/commands/command_executor.rs` enforces the policy for hook and alias pipelines (foreground and concurrent groups). `for_each.rs` enforces it directly for the worktree loop.
+
+When adding a new code path that loops over child processes, run `interrupt_exit_code` on per-iteration errors and break.
+
## Hook Output Logs
Hook output logs are centralized in `.git/wt/logs/` (main worktree's git directory). Per-branch logs live in subtrees; same operation on same branch overwrites the previous log.
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rs
index 8659c33fe..4bb061c44 100644
--- a/src/commands/command_executor.rs
+++ b/src/commands/command_executor.rs
@@ -8,7 +8,7 @@ use worktrunk::config::{
Command, CommandConfig, HookStep, UserConfig, expand_template, template_references_var,
validate_template_syntax,
};
-use worktrunk::git::{Repository, WorktrunkError};
+use worktrunk::git::{Repository, WorktrunkError, interrupt_exit_code};
use worktrunk::path::{format_path_for_display, to_posix_path};
use worktrunk::styling::{eprintln, error_message, format_bash_with_gutter, progress_message};
@@ -513,12 +513,22 @@ fn expansion_label(cmd: &PreparedCommand, origin: &CommandOrigin) -> String {
}
/// Handle a command execution error per origin and failure strategy.
+///
+/// Signal-derived child exits (SIGINT/SIGTERM) bypass both `origin` wrapping
+/// 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.
fn handle_command_error(
err: anyhow::Error,
cmd: &PreparedCommand,
origin: &CommandOrigin,
failure_strategy: FailureStrategy,
) -> anyhow::Result<()> {
+ if let Some(exit_code) = interrupt_exit_code(&err) {
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code }.into());
+ }
+
let (err_msg, exit_code) = if let Some(wt_err) = err.downcast_ref::<WorktrunkError>() {
match wt_err {
WorktrunkError::ChildProcessExited { message, code, .. } => {
diff --git a/src/commands/for_each.rs b/src/commands/for_each.rs
index 4c5071fab..8f6527ee8 100644
--- a/src/commands/for_each.rs
+++ b/src/commands/for_each.rs
@@ -23,7 +23,7 @@
use color_print::cformat;
use worktrunk::config::UserConfig;
-use worktrunk::git::{Repository, WorktrunkError};
+use worktrunk::git::{Repository, WorktrunkError, interrupt_exit_code};
use worktrunk::styling::{
eprintln, error_message, format_with_gutter, progress_message, success_message, warning_message,
};
@@ -104,15 +104,12 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
}
}
Err(err) => {
- let (signal, exit_info, exit_code, error_msg, show_detail) =
- if let Some(WorktrunkError::ChildProcessExited {
- code,
- message,
- signal,
- }) = err.downcast_ref::<WorktrunkError>()
+ let signal_exit = interrupt_exit_code(&err);
+ let (exit_info, exit_code, error_msg, show_detail) =
+ if let Some(WorktrunkError::ChildProcessExited { code, message, .. }) =
+ err.downcast_ref::<WorktrunkError>()
{
(
- *signal,
format!(" (exit code {code})"),
serde_json::json!(code),
message.clone(),
@@ -121,7 +118,6 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
} else {
let msg = err.to_string();
(
- None,
" (spawn failed)".to_string(),
serde_json::json!(null),
msg,
@@ -145,8 +141,8 @@ pub fn step_for_each(args: Vec<String>, format: crate::cli::SwitchFormat) -> any
"error": error_msg,
}));
}
- if let Some(sig) = signal {
- interrupted = Some(128 + sig);
+ if let Some(code) = signal_exit {
+ interrupted = Some(code);
break;
}
}
diff --git a/src/git/error.rs b/src/git/error.rs
index f9dbb25b8..cd670895f 100644
--- a/src/git/error.rs
+++ b/src/git/error.rs
@@ -1014,6 +1014,28 @@ pub fn exit_code(err: &anyhow::Error) -> Option<i32> {
})
}
+/// If `err` is a signal-derived child exit, return the equivalent shell exit
+/// code (`128 + 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 to the next iteration. The returned code is what wt itself
+/// should exit with, preserving the standard `128 + sig` shell convention
+/// (130 for SIGINT, 143 for SIGTERM).
+///
+/// See the "Signal Handling" section of the project `CLAUDE.md` for the
+/// rationale and the full list of loops that apply this policy.
+pub fn interrupt_exit_code(err: &anyhow::Error) -> Option<i32> {
+ if let Some(WorktrunkError::ChildProcessExited {
+ signal: Some(sig), ..
+ }) = err.downcast_ref::<WorktrunkError>()
+ {
+ Some(128 + sig)
+ } else {
+ None
+ }
+}
+
/// If the error is a HookCommandFailed, wrap it to add a hint about using --no-hooks.
///
/// ## When to use
@@ -1187,6 +1209,51 @@ mod tests {
assert_eq!(exit_code(&add_hook_skip_hint(inner)), Some(7));
}
+ #[test]
+ fn test_interrupt_exit_code() {
+ // Signal-derived child exit → 128 + sig
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 130,
+ message: "terminated by signal 2".into(),
+ signal: Some(2),
+ }
+ .into();
+ assert_eq!(interrupt_exit_code(&err), Some(130));
+
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 143,
+ message: "terminated by signal 15".into(),
+ signal: Some(15),
+ }
+ .into();
+ assert_eq!(interrupt_exit_code(&err), Some(143));
+
+ // Ordinary non-zero exit → not an interrupt
+ let err: anyhow::Error = WorktrunkError::ChildProcessExited {
+ code: 1,
+ message: "exit status: 1".into(),
+ signal: None,
+ }
+ .into();
+ assert_eq!(interrupt_exit_code(&err), None);
+
+ // Other WorktrunkError variants → not an interrupt
+ assert_eq!(
+ interrupt_exit_code(&WorktrunkError::AlreadyDisplayed { exit_code: 130 }.into()),
+ None,
+ );
+ assert_eq!(
+ interrupt_exit_code(&WorktrunkError::CommandNotApproved.into()),
+ None,
+ );
+
+ // Plain anyhow error → not an interrupt
+ assert_eq!(
+ interrupt_exit_code(&anyhow::anyhow!("some unrelated failure")),
+ None,
+ );
+ }
+
#[test]
fn snapshot_add_hook_skip_hint() {
// Wraps HookCommandFailed with --no-hooks hint
diff --git a/src/git/mod.rs b/src/git/mod.rs
index fa8fec03b..320a91736 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -52,6 +52,7 @@ pub use error::{
// Error inspection functions
add_hook_skip_hint,
exit_code,
+ interrupt_exit_code,
};
pub use parse::{parse_porcelain_z, parse_untracked_files};
pub use recover::{current_or_recover, cwd_removed_hint};
diff --git a/tests/integration_tests/user_hooks.rs b/tests/integration_tests/user_hooks.rs
index 05232b8d7..f0e82b940 100644
--- a/tests/integration_tests/user_hooks.rs
+++ b/tests/integration_tests/user_hooks.rs
@@ -443,6 +443,54 @@ long = "sh -c 'echo start >> hook.log; sleep 30; echo done >> hook.log'"
);
}
+/// A signal-derived exit in one hook step must abort the rest of the pipeline
+/// rather than treating the signal like an ordinary per-step failure. Drives
+/// the `handle_command_error` interrupt branch end-to-end through the hook
+/// path (the for-each test in `for_each.rs` covers the worktree-loop branch).
+///
+/// Implementation mirrors `test_for_each_aborts_on_signal_exit`: the first
+/// hook step self-signals via SIGTERM after touching a marker. SIGINT against
+/// the parent wt would kill the test harness, so we drive the same
+/// `ChildProcessExited { signal: Some(_), .. }` path with an in-child signal.
+#[rstest]
+#[cfg(unix)]
+fn test_pre_merge_pipeline_aborts_on_signal_exit(repo: TestRepo) {
+ repo.commit("Initial commit");
+
+ // Two pre-merge hooks: the first writes a marker then self-signals with
+ // SIGTERM; the second (which must NOT run) would write its own marker.
+ repo.write_project_config(
+ r#"[pre-merge]
+abort = "sh -c 'echo first >> hook.log; kill -TERM $$'"
+after = "sh -c 'echo second >> hook.log'"
+"#,
+ );
+ repo.commit("Add pre-merge hooks");
+
+ let output = crate::common::wt_command()
+ .current_dir(repo.root_path())
+ .args(["hook", "pre-merge", "--yes"])
+ .output()
+ .expect("run wt hook pre-merge");
+
+ // 128 + SIGTERM (15) = 143
+ assert_eq!(
+ output.status.code(),
+ Some(143),
+ "expected exit 143 (SIGTERM); got {:?}\nstderr: {}",
+ output.status.code(),
+ String::from_utf8_lossy(&output.stderr),
+ );
+
+ let hook_log = repo.root_path().join("hook.log");
+ let contents = std::fs::read_to_string(&hook_log).unwrap_or_default();
+ assert_eq!(
+ contents.trim(),
+ "first",
+ "second hook step ran after the first was killed by signal; got: {contents:?}",
+ );
+}
+
// ============================================================================
// User Post-Merge Hook Tests
// ============================================================================