Skip to content

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

fix(merge): exit non-zero when the target autostash can't be restored (#3693)

Maximilian Roos03f49ce93a1e
diff --git a/docs/content/step.md b/docs/content/step.md
index 4af08d1cf..6aeda1bf2 100644
--- a/docs/content/step.md
+++ b/docs/content/step.md
@@ -372,7 +372,7 @@ The target is a branch, and must already be an ancestor of the current branch. O
### Target worktree
-When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file.
+When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file. A restore that can't replay keeps the stash entry and exits non-zero, naming the `git stash apply` that recovers it — the push itself still stands.
A worktree that is still registered but whose directory is gone is refused as well, since nothing can be synced into it — `git worktree prune` clears the registration.
diff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.md
index 631953640..a48a94358 100644
--- a/plugins/worktrunk/skills/worktrunk/reference/step.md
+++ b/plugins/worktrunk/skills/worktrunk/reference/step.md
@@ -379,7 +379,7 @@ $ wt step push --no-ff # Merge commit instead of a fast-forward
### Target worktree
-When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file.
+When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file. A restore that can't replay keeps the stash entry and exits non-zero, naming the `git stash apply` that recovers it — the push itself still stands.
A worktree that is still registered but whose directory is gone is refused as well, since nothing can be synced into it — `git worktree prune` clears the registration.
diff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.md
index 631953640..a48a94358 100644
--- a/skills/worktrunk/reference/step.md
+++ b/skills/worktrunk/reference/step.md
@@ -379,7 +379,7 @@ $ wt step push --no-ff # Merge commit instead of a fast-forward
### Target worktree
-When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file.
+When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file. A restore that can't replay keeps the stash entry and exits non-zero, naming the `git stash apply` that recovers it — the push itself still stands.
A worktree that is still registered but whose directory is gone is refused as well, since nothing can be synced into it — `git worktree prune` clears the registration.
diff --git a/src/cli/step.rs b/src/cli/step.rs
index 6be3b7dc4..ef322e8e1 100644
--- a/src/cli/step.rs
+++ b/src/cli/step.rs
@@ -212,7 +212,7 @@ $ wt step push --no-ff # Merge commit instead of a fast-forward
## Target worktree
-When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file.
+When the target branch has a worktree of its own, that worktree's files move to the new commits too. A fast-forward does both at once, pushing into this repository with `receive.denyCurrentBranch=updateInstead`; `--no-ff` moves the ref first and syncs the worktree after, warning rather than failing if that sync doesn't apply. Uncommitted changes in that worktree are stashed for the duration and restored afterward; one touching a file the push also changes is refused instead, naming the file. A restore that can't replay keeps the stash entry and exits non-zero, naming the `git stash apply` that recovers it — the push itself still stands.
A worktree that is still registered but whose directory is gone is refused as well, since nothing can be synced into it — `git worktree prune` clears the registration.
"#
diff --git a/src/commands/merge.rs b/src/commands/merge.rs
index 6781dcd3f..28f3fe737 100644
--- a/src/commands/merge.rs
+++ b/src/commands/merge.rs
@@ -4,7 +4,7 @@ use anyhow::Context;
use color_print::cformat;
use worktrunk::HookType;
use worktrunk::config::{MergeConfig, UserConfig};
-use worktrunk::git::Repository;
+use worktrunk::git::{Repository, WorktrunkError};
use worktrunk::styling::{eprintln, info_message};
use super::command_approval::approve_commit_template_append;
@@ -427,13 +427,14 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
squashed,
rebased,
});
- if !ff {
+ let stash_restore_failed = if !ff {
// Create a merge commit on the target branch via commit-tree + update-ref
- let _ = handle_no_ff_merge(Some(&target_branch), operations, &current_branch)?;
+ handle_no_ff_merge(Some(&target_branch), operations, &current_branch)?.stash_restore_failed
} else {
// Fast-forward push to target branch
- let _ = handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?;
- }
+ handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?
+ .stash_restore_failed
+ };
let removed = finish_after_merge(
repo,
@@ -461,9 +462,21 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {
"squashed": squashed,
"rebased": rebased,
"removed": removed,
+ // The exit code alone leaves a consumer that reads stdout seeing a
+ // success-shaped payload, so the failure is named on both channels.
+ "stash_restore_failed": stash_restore_failed,
});
println!("{}", serde_json::to_string_pretty(&output)?);
}
+ if stash_restore_failed {
+ // The merge landed and every follow-up ran; only the target worktree's
+ // autostash didn't replay, leaving the user's uncommitted changes in a
+ // stash instead of their worktree. `restore_stash` already warned with
+ // the recovery command, so this only makes the exit code say the
+ // command didn't finish what it set out to do.
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());
+ }
+
Ok(())
}
diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rs
index 6bd7b409d..6671f66df 100644
--- a/src/commands/repository_ext.rs
+++ b/src/commands/repository_ext.rs
@@ -679,7 +679,12 @@ struct StashData {
impl StashData {
/// Restore the stash, printing progress and warning on failure.
- fn restore(self) {
+ ///
+ /// Returns whether the stashed content made it back into the working tree.
+ /// The warning is printed here, so a caller only needs the outcome — to
+ /// finish its remaining work and then exit non-zero rather than reporting
+ /// success while the user's changes sit in a stash.
+ fn restore(self) -> bool {
eprintln!(
"{}",
progress_message(cformat!(
@@ -688,17 +693,20 @@ impl StashData {
))
);
- if let Err(e) = self.restore_inner() {
- eprintln!(
- "{}",
- warning_message(cformat!(
- "Failed to restore stashed changes in <bold>{path}</>; run <bold>git stash apply {sha}</> there to recover ({err})",
- path = format_path_for_display(&self.path),
- sha = self.stash_sha,
- err = e,
- ))
- );
- }
+ let Err(e) = self.restore_inner() else {
+ return true;
+ };
+
+ eprintln!(
+ "{}",
+ warning_message(cformat!(
+ "Failed to restore stashed changes in <bold>{path}</>; run <bold>git stash apply {sha}</> there to recover ({err})",
+ path = format_path_for_display(&self.path),
+ sha = self.stash_sha,
+ err = e,
+ ))
+ );
+ false
}
/// Apply the stash by its immutable commit SHA, then drop the entry.
@@ -761,6 +769,10 @@ impl StashData {
impl Drop for TargetWorktreeStash {
fn drop(&mut self) {
if let Some(data) = self.inner.take() {
+ // `Drop` can't report the outcome, and doesn't need to: the guard
+ // only reaches here still armed on a path that is already returning
+ // an error, which exits non-zero on its own. The success path calls
+ // `restore_now` and acts on what it returns.
data.restore();
}
}
@@ -781,9 +793,13 @@ impl TargetWorktreeStash {
///
/// Use this when you need the restore to happen at a specific point
/// (e.g., before a success message). Drop handles errors/early returns.
- pub(crate) fn restore_now(&mut self) {
- if let Some(data) = self.inner.take() {
- data.restore();
+ ///
+ /// Returns whether the stashed content is back in the working tree; an
+ /// already-restored (or disarmed) guard reports success.
+ pub(crate) fn restore_now(&mut self) -> bool {
+ match self.inner.take() {
+ Some(data) => data.restore(),
+ None => true,
}
}
}
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 962d8877c..c7002ee2d 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -65,6 +65,26 @@ pub struct PushResult {
pub target: String,
pub commit_count: usize,
pub outcome: PushOutcome,
+ /// The target worktree's autostash could not be replayed.
+ ///
+ /// The push itself landed, so the caller finishes its remaining work
+ /// (worktree removal, post-merge hooks, `--format=json` payload) and only
+ /// then exits non-zero. Reporting success here would say the user's
+ /// uncommitted changes are back in their worktree when they are still in a
+ /// stash. The warning naming the recovery command is already printed, so
+ /// the caller raises [`worktrunk::git::WorktrunkError::AlreadyDisplayed`].
+ ///
+ /// The `--format=json` payloads carry this as `stash_restore_failed`. Both
+ /// output channels have to name the failure: a consumer reading stdout
+ /// would otherwise get a success-shaped object and never see the exit code.
+ ///
+ /// Diverging from git here is deliberate: `git rebase --autostash` exits 0
+ /// on the same failure. Its replay conflict leaves conflict markers in the
+ /// working tree, where the user meets them immediately; a failed `git stash
+ /// apply` can leave the worktree untouched instead — an untracked path
+ /// re-created underneath it, say — so nothing but the exit code outlives
+ /// the warning.
+ pub stash_restore_failed: bool,
}
pub enum PushOutcome {
@@ -264,9 +284,13 @@ impl MergeContext {
}
/// Explicitly restore the stash guard (before success message).
- fn restore_stash(&mut self) {
- if let Some(guard) = self.stash_guard.as_mut() {
- guard.restore_now();
+ ///
+ /// Returns whether the stashed content is back in the target worktree; a
+ /// push that stashed nothing reports success.
+ fn restore_stash(&mut self) -> bool {
+ match self.stash_guard.as_mut() {
+ Some(guard) => guard.restore_now(),
+ None => true,
}
}
@@ -374,7 +398,7 @@ pub fn handle_push(
error: e.display_message(),
})?;
- ctx.restore_stash();
+ let stash_restore_failed = !ctx.restore_stash();
let outcome = if ctx.commit_count > 0 {
ctx.show_success(kind.verb_past(), "", "");
@@ -387,6 +411,7 @@ pub fn handle_push(
Ok(PushResult {
target: ctx.target_branch,
commit_count: ctx.commit_count,
+ stash_restore_failed,
outcome,
})
}
@@ -421,11 +446,17 @@ pub fn handle_no_ff_merge(
ctx.show_progress("Merging", " (--no-ff)", operations)?;
- if ctx.show_up_to_date_if_needed(operations) {
+ // A dirty target worktree is stashed even when there is nothing to merge,
+ // so this early return restores too — and, as in `handle_push`, before the
+ // "Already up to date" line.
+ if ctx.commit_count == 0 {
+ let stash_restore_failed = !ctx.restore_stash();
+ ctx.show_up_to_date_if_needed(operations);
return Ok(PushResult {
target: ctx.target_branch,
commit_count: 0,
outcome: PushOutcome::UpToDate,
+ stash_restore_failed,
});
}
@@ -497,7 +528,7 @@ pub fn handle_no_ff_merge(
}
}
- ctx.restore_stash();
+ let stash_restore_failed = !ctx.restore_stash();
// Display uses `Repository::short_sha`; the JSON payload carries the full SHA.
let merge_sha_short = ctx.repo.short_sha(&merge_sha)?;
@@ -508,6 +539,7 @@ pub fn handle_no_ff_merge(
target: ctx.target_branch,
commit_count: ctx.commit_count,
outcome: PushOutcome::MergeCommit { merge_sha },
+ stash_restore_failed,
})
}
diff --git a/src/main.rs b/src/main.rs
index e36f21ce1..45fd257df 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -309,11 +309,13 @@ fn handle_step_command(
} else {
handle_push(target.as_deref(), PushKind::Standalone, None)?
};
+ let stash_restore_failed = result.stash_restore_failed;
if format == SwitchFormat::Json {
let PushResult {
target,
commit_count,
outcome,
+ ..
} = result;
let mut payload = serde_json::json!({
"target": target,
@@ -323,12 +325,22 @@ fn handle_step_command(
PushOutcome::MergeCommit { .. } => "merge_commit",
},
"commits": commit_count,
+ // The exit code alone leaves a consumer that reads stdout
+ // seeing a success-shaped payload, so the failure is named
+ // on both channels.
+ "stash_restore_failed": stash_restore_failed,
});
if let PushOutcome::MergeCommit { merge_sha } = outcome {
payload["merge_sha"] = serde_json::Value::String(merge_sha);
}
println!("{}", serde_json::to_string_pretty(&payload)?);
}
+ if stash_restore_failed {
+ // The push landed; the target worktree's autostash didn't
+ // replay. `restore_stash` already warned with the recovery
+ // command, so this only sets the exit code.
+ return Err(WorktrunkError::AlreadyDisplayed { exit_code: 1 }.into());
+ }
Ok(())
}
StepCommand::Rebase { target, format } => {
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index d81cb203a..22fa0889e 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2014,6 +2014,90 @@ git update-ref refs/heads/main "$concurrent" "$target"
);
}
+/// A merge whose target autostash can't replay finishes everything it started —
+/// the ref advances and the source worktree is removed — and only then exits
+/// non-zero. Exiting 0 would report the user's uncommitted changes as back in
+/// their worktree while they sit in a stash; aborting mid-flow would instead
+/// leave a landed merge with its cleanup half-done.
+#[rstest]
+fn test_merge_autostash_restore_failure_exits_non_zero_after_cleanup(mut repo: TestRepo) {
+ let feature_wt = repo.add_worktree_with_commit(
+ "feature-restore-fail",
+ "feature.txt",
+ "feature content",
+ "Add feature",
+ );
+
+ // Untracked work in the target worktree, plus a post-receive hook that
+ // re-creates that path during the push, so `git stash apply` can't put the
+ // untracked file back and the restore fails after the merge has landed.
+ fs::write(repo.root_path().join("notes.txt"), "USER-WORK").unwrap();
+ let git_common_dir =
+ repo.git_output(&["rev-parse", "--path-format=absolute", "--git-common-dir"]);
+ write_git_hook(
+ &PathBuf::from(git_common_dir)
+ .join("hooks")
+ .join("post-receive"),
+ &format!(
+ "#!/bin/sh\n\
+ unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_QUARANTINE_PATH\n\
+ printf 'HOOK-CONFLICT\\n' > '{root}/notes.txt'\n\
+ exit 0\n",
+ root = repo.root_path().to_slash_lossy(),
+ ),
+ );
+
+ let target_before = repo.git_output(&["rev-parse", "main"]);
+ let output = repo
+ .wt_command()
+ .args([
+ "merge",
+ "main",
+ "--no-commit",
+ "--no-rebase",
+ "--no-hooks",
+ "--format=json",
+ ])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert_eq!(
+ output.status.code(),
+ Some(1),
+ "an autostash that couldn't replay must not exit 0: {stderr}"
+ );
+ assert!(
+ stderr.contains("Failed to restore stashed changes"),
+ "expected a restore-failure warning: {stderr}"
+ );
+
+ // Every output channel names the failure. A consumer reading the payload
+ // rather than `$?` would otherwise see a success-shaped object.
+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
+ assert_eq!(json["stash_restore_failed"], true);
+
+ // The merge landed and its cleanup ran — the exit code reports the restore,
+ // not the merge.
+ assert_ne!(
+ repo.git_output(&["rev-parse", "main"]),
+ target_before,
+ "the merge must still have landed: {stderr}"
+ );
+ assert_eq!(
+ repo.git_output(&["show", "main:feature.txt"]),
+ "feature content"
+ );
+ wait_for_worktree_removed(&feature_wt);
+
+ // The user's work stays recoverable from the surviving stash entry.
+ assert!(
+ repo.git_output(&["stash", "list"]).contains("autostash"),
+ "the recoverable stash entry must remain"
+ );
+}
+
#[rstest]
fn test_merge_primary_on_different_branch(mut repo: TestRepo) {
repo.switch_primary_to("develop");
@@ -4541,6 +4625,7 @@ fn test_merge_json(repo: TestRepo) {
"rebased": false,
"removed": true,
"squashed": false,
+ "stash_restore_failed": false,
"target": "main"
}
"#);
diff --git a/tests/integration_tests/push.rs b/tests/integration_tests/push.rs
index 2e9fbbac7..791399efb 100644
--- a/tests/integration_tests/push.rs
+++ b/tests/integration_tests/push.rs
@@ -233,10 +233,12 @@ fn test_push_autostash_restore_failure_warns(mut repo: TestRepo) {
.output()
.expect("failed to run push");
- // The push itself succeeded; only the restore couldn't replay.
- assert!(
- output.status.success(),
- "push should still succeed: {}",
+ // Exit non-zero: the user's changes are in a stash rather than their
+ // worktree, so reporting success would misstate where their work is.
+ assert_eq!(
+ output.status.code(),
+ Some(1),
+ "a restore that couldn't replay must not exit 0: {}",
String::from_utf8_lossy(&output.stderr)
);
let stderr = String::from_utf8_lossy(&output.stderr);
@@ -249,6 +251,14 @@ fn test_push_autostash_restore_failure_warns(mut repo: TestRepo) {
"warning must name the recovery command: {stderr}"
);
+ // The push itself landed — the non-zero exit reports the restore, not the
+ // push, so the target must still have advanced to the feature commit.
+ assert_eq!(
+ repo.git_output(&["rev-parse", "main"]),
+ repo.git_output(&["rev-parse", "feature"]),
+ "the push must still have landed on the target"
+ );
+
// The stash entry survives for recovery — a failed apply does not drop it.
let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();
assert!(