Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(merge): leave target-worktree changes in place, drop the autostash (#3703)
Maximilian Roos4a6fd1ec4413
diff --git a/CLAUDE.md b/CLAUDE.mdindex 0dd658935..94656e51f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -103,7 +103,7 @@ When no structured alternative exists, document the fragility inline.### Immutable Ids Over List Positions-`stash@{0}` names a position in a list any process can reorder, so a handle captured before a mutation window and used after it can resolve to a different object — restoring the target worktree's autostash by position after `git push` silently restored a concurrent writer's entry and reported success. Capture the immutable id instead (`git stash list --format=%H`, `git stash create`, `rev-parse`) and act on that; where an operation accepts only a positional selector, re-derive it from something stable immediately beforehand, as `StashData::locate_by_message` does before dropping the entry. An index into a collection `wt` owns is a different thing — this is about namespaces other processes can mutate.+`stash@{0}` names a position in a list any process can reorder, so a handle captured before a mutation window and used after it can resolve to a different object — restoring the target worktree's autostash by position after `git push` silently restored a concurrent writer's entry and reported success. Capture the immutable id instead (`git stash list --format=%H`, `git stash create`, `rev-parse`) and act on that; where an operation accepts only a positional selector, re-derive it from something stable immediately beforehand. An index into a collection `wt` owns is a different thing — this is about namespaces other processes can mutate. The strongest form is not to enter the shared namespace at all: the autostash this rule came from was later deleted outright, replaced by a two-tree merge that leaves the target worktree's changes in place (`advance_target` in `src/commands/worktree/push.rs`).### Network Accessdiff --git a/docs/content/faq.md b/docs/content/faq.mdindex afca131c8..990f4a292 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -195,6 +195,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.### Other cleanup+- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — when migrating an integration to a new location, removes the file left at the old one: fish `conf.d/wt.fish` (now `functions/wt.fish`) and nushell wrappers stranded under `<config-dir>/vendor/autoload` (now `<data-dir>/vendor/autoload`). The old path is where worktrunk's own wrapper lived and is named after the command being installed, so it's taken back whole without reading it — a `conf.d/wt.fish` left in place would be sourced at startup and shadow the new wrapper anyway. Only that exact filename is touched, and each removal is printeddiff --git a/docs/content/step.md b/docs/content/step.mdindex 6aeda1bf2..50a7580c8 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. 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.+When the target branch has a worktree of its own, that worktree's files move to the new commits too. Uncommitted changes there never move: the update carries any file the push doesn't touch — staged or not — exactly where it is, and a change touching a file the push does change is refused upfront, naming the file. If the sync can't be applied for any reason — a conflicting file appearing in the race window after the check, or a busy index — the update is rolled back whole, leaving branch and worktree as they were.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/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex 3d055e05c..b5a1246d4 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -190,6 +190,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.### Other cleanup+- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — when migrating an integration to a new location, removes the file left at the old one: fish `conf.d/wt.fish` (now `functions/wt.fish`) and nushell wrappers stranded under `<config-dir>/vendor/autoload` (now `<data-dir>/vendor/autoload`). The old path is where worktrunk's own wrapper lived and is named after the command being installed, so it's taken back whole without reading it — a `conf.d/wt.fish` left in place would be sourced at startup and shadow the new wrapper anyway. Only that exact filename is touched, and each removal is printeddiff --git a/plugins/worktrunk/skills/worktrunk/reference/step.md b/plugins/worktrunk/skills/worktrunk/reference/step.mdindex a48a94358..c948c3436 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. 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.+When the target branch has a worktree of its own, that worktree's files move to the new commits too. Uncommitted changes there never move: the update carries any file the push doesn't touch — staged or not — exactly where it is, and a change touching a file the push does change is refused upfront, naming the file. If the sync can't be applied for any reason — a conflicting file appearing in the race window after the check, or a busy index — the update is rolled back whole, leaving branch and worktree as they were.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/faq.md b/skills/worktrunk/reference/faq.mdindex 3d055e05c..b5a1246d4 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -190,6 +190,7 @@ A branch checked out in a second worktree is retained regardless, `-D` included.### Other cleanup+- `wt merge` / `wt step push` — the target branch's checked-out worktree is updated to the merged commits, so a file those commits delete disappears from it, and an ignored file at a path they track is overwritten — the same result a `git merge` run in that worktree would produce. Uncommitted changes at paths the merge doesn't touch stay in place, staged or not; one at a path it does touch refuses the merge upfront, naming the file- `wt remove` — besides the target worktree, two cleanup mechanisms run. The removed worktree's own `git fsmonitor--daemon` (git's per-worktree filesystem watcher under `core.fsmonitor=true`, which would leak once its worktree is gone) is sent `git fsmonitor--daemon stop`, then force-terminated (`SIGTERM`, then `SIGKILL`) via the PID resolved from its IPC socket if it didn't exit. A background sweep then deletes `.git/wt/trash/` entries older than 24 hours (directories orphaned when a previous background removal was interrupted) and terminates fsmonitor daemons whose worktree no longer exists (orphans from `git worktree remove`, `rm -rf`, or a crashed `wt`)- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell install` — when migrating an integration to a new location, removes the file left at the old one: fish `conf.d/wt.fish` (now `functions/wt.fish`) and nushell wrappers stranded under `<config-dir>/vendor/autoload` (now `<data-dir>/vendor/autoload`). The old path is where worktrunk's own wrapper lived and is named after the command being installed, so it's taken back whole without reading it — a `conf.d/wt.fish` left in place would be sourced at startup and shadow the new wrapper anyway. Only that exact filename is touched, and each removal is printeddiff --git a/skills/worktrunk/reference/step.md b/skills/worktrunk/reference/step.mdindex a48a94358..c948c3436 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. 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.+When the target branch has a worktree of its own, that worktree's files move to the new commits too. Uncommitted changes there never move: the update carries any file the push doesn't touch — staged or not — exactly where it is, and a change touching a file the push does change is refused upfront, naming the file. If the sync can't be applied for any reason — a conflicting file appearing in the race window after the check, or a busy index — the update is rolled back whole, leaving branch and worktree as they were.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.rsindex ef322e8e1..780919232 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. 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.+When the target branch has a worktree of its own, that worktree's files move to the new commits too. Uncommitted changes there never move: the update carries any file the push doesn't touch — staged or not — exactly where it is, and a change touching a file the push does change is refused upfront, naming the file. If the sync can't be applied for any reason — a conflicting file appearing in the race window after the check, or a busy index — the update is rolled back whole, leaving branch and worktree as they were.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.rsindex 28f3fe737..e96890878 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, WorktrunkError};+use worktrunk::git::Repository;use worktrunk::styling::{eprintln, info_message};use super::command_approval::approve_commit_template_append;@@ -427,14 +427,13 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {squashed,rebased,});- let stash_restore_failed = if !ff {+ if !ff {// Create a merge commit on the target branch via commit-tree + update-ref- handle_no_ff_merge(Some(&target_branch), operations, ¤t_branch)?.stash_restore_failed+ handle_no_ff_merge(Some(&target_branch), operations, ¤t_branch)?;} else {// Fast-forward push to target branch- handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?- .stash_restore_failed- };+ handle_push(Some(&target_branch), PushKind::MergeFastForward, operations)?;+ }let removed = finish_after_merge(repo,@@ -462,21 +461,9 @@ 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.rsindex 6671f66df..eae428f25 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -1,18 +1,14 @@use std::path::{Path, PathBuf};-use std::process;-use std::time::{SystemTime, UNIX_EPOCH};use super::worktree::{RemovalPlan, SharedBranchCheckout};use anyhow::{Context, bail};use color_print::cformat;use worktrunk::git::{- BranchDeletionMode, GitError, IntegrationReason, RefSnapshot, Repository, WorkingTree,- WorktreeInfo, parse_porcelain_z, parse_untracked_files,+ BranchDeletionMode, GitError, IntegrationReason, RefSnapshot, Repository, WorktreeInfo,+ parse_porcelain_z, parse_untracked_files,};use worktrunk::path::format_path_for_display;-use worktrunk::styling::{- eprintln, format_with_gutter, progress_message, suggest_command, warning_message,-};+use worktrunk::styling::{eprintln, format_with_gutter, suggest_command, warning_message};/// Target for worktree removal.#[derive(Debug)]@@ -70,7 +66,12 @@ pub trait RepositoryCliExt {snapshot: Option<&RefSnapshot>,) -> anyhow::Result<RemovalPlan>;- /// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.+ /// Refuse the push when target-worktree changes overlap the push range.+ ///+ /// Uncommitted changes at paths the push range doesn't touch are left+ /// alone — the two-tree merge in `advance_target` carries them in place —+ /// so this only names the files that genuinely conflict, before anything+ /// moves.////// The caller has already established that `target_worktree` exists on disk/// (`MergeContext::prepare` refuses a registered-but-missing worktree), so@@ -80,11 +81,11 @@ pub trait RepositoryCliExt {/// `git status --porcelain` read this works from, and matching git there is/// the decision, not an oversight. The module spec in/// `commands/worktree/push.rs` says why.- fn prepare_target_worktree(+ fn ensure_no_target_conflicts(&self,target_worktree: Option<&PathBuf>,target_branch: &str,- ) -> anyhow::Result<Option<TargetWorktreeStash>>;+ ) -> anyhow::Result<()>;/// Check if HEAD is a linear extension of the target branch.///@@ -403,25 +404,28 @@ impl RepositoryCliExt for Repository {})}- fn prepare_target_worktree(+ fn ensure_no_target_conflicts(&self,target_worktree: Option<&PathBuf>,target_branch: &str,- ) -> anyhow::Result<Option<TargetWorktreeStash>> {+ ) -> anyhow::Result<()> {let Some(wt_path) = target_worktree else {- return Ok(None);+ return Ok(());};+ // `-uall` lists individual files inside untracked directories — the+ // default collapses them to a single `dir/` entry, which can never+ // match a file path in the push range — and, being explicit, it+ // overrides a user's `status.showUntrackedFiles=no`. `-z` handles+ // filenames with spaces and renames ("XY path\0" for normal files,+ // "XY new_path\0old_path\0" for renames/copies).let wt = self.worktree_at(wt_path);- if !wt.is_dirty()? {- return Ok(None);+ let wt_status_output = wt.run_command(&["status", "--porcelain", "-z", "-uall"])?;+ if wt_status_output.trim().is_empty() {+ return Ok(());}let push_files = self.changed_files(target_branch, "HEAD")?;- // Use -z for NUL-separated output: handles filenames with spaces and renames correctly- // Format: "XY path\0" for normal files, "XY new_path\0old_path\0" for renames/copies- let wt_status_output = wt.run_command(&["status", "--porcelain", "-z"])?;-let wt_files: Vec<String> = parse_porcelain_z(&wt_status_output);let overlapping: Vec<String> = push_files@@ -439,69 +443,7 @@ impl RepositoryCliExt for Repository {.into());}- let nanos = SystemTime::now()- .duration_since(UNIX_EPOCH)- .unwrap_or_default()- .as_nanos();- let stash_name = format!(- "worktrunk autostash::{}::{}::{}",- target_branch,- process::id(),- nanos- );-- eprintln!(- "{}",- progress_message(cformat!(- "Stashing changes in <bold>{}</>...",- format_path_for_display(wt_path)- ))- );-- // Stash all changes including untracked files.- // Note: git stash push returns exit code 0 whether or not anything was stashed.- wt.run_command(&["stash", "push", "--include-untracked", "-m", &stash_name])?;-- // Verify stash was created by checking the stash list for our entry, and- // capture its immutable commit SHA (`%H`) rather than the positional- // reflog selector (`%gd`, i.e. `stash@{0}`). The selector is a position:- // any stash pushed into the repo between now and the restore — a- // concurrent `wt merge`, an editor integration — shifts the indices, so- // popping `stash@{0}` later would restore (and drop) a different entry.- // The commit SHA is addressed by content and never moves.- let list_output = wt.run_command(&["stash", "list", "--format=%H%x00%gs%x00"])?;- let mut parts = list_output.split('\0');- while let Some(sha) = parts.next() {- // git separates stash-list records with `\n`, so every SHA after the- // first carries a leading newline; trim before use.- let sha = sha.trim();- if sha.is_empty() {- continue;- }- if let Some(message) = parts.next()- && (message == stash_name || message.ends_with(&stash_name))- {- return Ok(Some(TargetWorktreeStash::new(- wt_path,- sha.to_string(),- &stash_name,- )));- }- }-- // Stash entry not found. Verify the worktree is now clean — if it's still- // dirty, stashing may have failed silently or our lookup missed the entry.- if wt.is_dirty()? {- bail!(cformat!(- "Failed to stash changes in {}; worktree still has uncommitted changes. \- Expected stash entry: <bold>{}</>. Check <bold>git stash list</>.",- format_path_for_display(wt_path),- stash_name- ));- }-- // Worktree is clean and no stash entry — nothing needed to be stashed- Ok(None)+ Ok(())}fn is_rebased_onto(&self, target: &str) -> anyhow::Result<bool> {@@ -655,155 +597,6 @@ pub(crate) fn warn_about_untracked_files(status_output: &str) -> anyhow::Result<Ok(())}-/// Stash guard that auto-restores on drop.-///-/// Created by `prepare_target_worktree()` when the target worktree has changes-/// that don't conflict with the push. Automatically restores the stash when-/// dropped, ensuring cleanup happens in both success and error paths.-#[must_use = "stash guard restores immediately if dropped; hold it until push completes"]-pub(crate) struct TargetWorktreeStash {- /// Inner data wrapped in Option so we can take() in Drop.- /// None means already restored (or disarmed).- inner: Option<StashData>,-}--struct StashData {- path: PathBuf,- /// Immutable commit SHA of the stash entry. Restored by content, so a stash- /// pushed into the repo since capture can't redirect the restore.- stash_sha: String,- /// The unique `-m` message recorded at capture. Used to re-locate the entry- /// in the (possibly reordered) stash list when dropping it after apply.- stash_name: String,-}--impl StashData {- /// Restore the stash, printing progress and warning on failure.- ///- /// 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!(- "Restoring stashed changes in <bold>{}</>...",- format_path_for_display(&self.path)- ))- );-- 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.- ///- /// `git stash apply <sha>` is content-addressed, so it restores this exact- /// entry regardless of how the stash list has been reordered since capture —- /// unlike `git stash pop stash@{0}`, which would pop whatever now sits at- /// position 0. Because `apply` (unlike `pop`) leaves the entry in the list,- /// we then re-locate it by its unique message and drop it. A failed drop- /// only strands a stash entry — the working-tree content is already- /// restored — so it is not treated as a restore failure.- fn restore_inner(&self) -> anyhow::Result<()> {- let repo = Repository::current()?;- let wt = repo.worktree_at(&self.path);-- // Don't use --quiet so git shows conflicts if any.- wt.run_command(&["stash", "apply", &self.stash_sha])?;-- if let Some(selector) = Self::locate_by_message(&wt, &self.stash_name)?- && let Err(e) = wt.run_command(&["stash", "drop", &selector])- {- eprintln!(- "{}",- warning_message(cformat!(- "Restored changes but left the stash entry <bold>{selector}</> in <bold>{path}</>; drop it with <bold>git stash drop {selector}</> ({e})",- path = format_path_for_display(&self.path),- ))- );- }-- Ok(())- }-- /// Find the current `stash@{n}` selector for the entry with `stash_name`.- ///- /// The recorded selector from capture time is positional and may be stale by- /// restore time, so the entry is re-located by its unique message. `git- /// stash push -m X` records the subject as `On <branch>: X`, so both the- /// exact message and the `On …:`-prefixed form are accepted.- fn locate_by_message(wt: &WorkingTree, stash_name: &str) -> anyhow::Result<Option<String>> {- let list_output = wt.run_command(&["stash", "list", "--format=%gd%x00%gs%x00"])?;- let mut parts = list_output.split('\0');- while let Some(selector) = parts.next() {- // git separates stash-list records with `\n`, so every selector- // after the first carries a leading newline; trim before use.- let selector = selector.trim();- if selector.is_empty() {- continue;- }- if let Some(message) = parts.next()- && (message == stash_name || message.ends_with(stash_name))- {- return Ok(Some(selector.to_string()));- }- }- Ok(None)- }-}--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();- }- }-}--impl TargetWorktreeStash {- pub(crate) fn new(path: &Path, stash_sha: String, stash_name: &str) -> Self {- Self {- inner: Some(StashData {- path: path.to_path_buf(),- stash_sha,- stash_name: stash_name.to_string(),- }),- }- }-- /// Explicitly restore the stash now, preventing Drop from restoring again.- ///- /// Use this when you need the restore to happen at a specific point- /// (e.g., before a success message). Drop handles errors/early returns.- ///- /// 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,- }- }-}-#[cfg(test)]mod tests {use super::*;@@ -1034,82 +827,4 @@ mod tests {// All files are tracked (modified, staged, etc.)assert!(parse_untracked_files(" M file1.txt\0M file2.txt\0").is_empty());}-- /// `locate_by_message` re-finds a stash entry by its unique message so the- /// restore path never trusts a positional selector a concurrent stash could- /// have invalidated (#3683). It must find the entry after the list has been- /// reordered — matching the `On <branch>: <msg>` subject that `git stash- /// push -m` records — and report absence without matching an unrelated- /// entry.- #[test]- fn locate_by_message_finds_entry_after_reorder_and_reports_absence() {- let test = TestRepo::with_initial_commit();- let root = test.root_path();-- // Two stashes with distinct messages. The second push lands at- // stash@{0}, pushing the first to stash@{1} — the reorder the fix must- // tolerate.- std::fs::write(root.join("a.txt"), "a").unwrap();- test.run_git(&["stash", "push", "-u", "-m", "worktrunk autostash::alpha"]);- std::fs::write(root.join("b.txt"), "b").unwrap();- test.run_git(&["stash", "push", "-u", "-m", "worktrunk autostash::beta"]);-- let repo = Repository::at(root).unwrap();- let wt = repo.worktree_at(root);-- // The older entry is now at stash@{1}; located by message, not position.- assert_eq!(- StashData::locate_by_message(&wt, "worktrunk autostash::alpha")- .unwrap()- .as_deref(),- Some("stash@{1}"),- );-- // A message with no match scans every entry — including the trailing- // record separator — and returns None rather than a false positive.- assert!(- StashData::locate_by_message(&wt, "worktrunk autostash::gamma")- .unwrap()- .is_none()- );- }-- #[test]- fn test_stash_guard_restore_now_clears_inner() {- // Create a guard - note: this doesn't actually create a stash since we're not- // in a real git repo with that stash ref. We're just testing the state machine.- let mut guard = TargetWorktreeStash::new(- std::path::Path::new("/tmp"),- "0000000000000000000000000000000000000000".into(),- "worktrunk autostash::test",- );-- // Inner should be populated- assert!(guard.inner.is_some());-- // restore_now() should clear inner (the restore itself will fail since no real repo,- // but that's expected - we're testing the state transition)- guard.restore_now();-- // Inner should now be None- assert!(guard.inner.is_none());-- // Calling restore_now() again is a no-op- guard.restore_now();- assert!(guard.inner.is_none());- }-- #[test]- fn test_stash_guard_drop_clears_inner() {- // Test that Drop also consumes the inner- let guard = TargetWorktreeStash::new(- std::path::Path::new("/tmp"),- "0000000000000000000000000000000000000000".into(),- "worktrunk autostash::test",- );-- // Just drop it - the restore will fail (no real repo) but Drop shouldn't panic- drop(guard);- // If we get here, Drop worked without panicking- }}diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex c7002ee2d..7d5e37896 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -2,35 +2,39 @@//!//! Push changes to target branch with safety checks. Both fast-forward push and//! `--no-ff` merge share common scaffolding (target resolution, fast-forward check,-//! stash guard, progress/success output) extracted into [`MergeContext`].+//! conflict check, progress/success output) extracted into [`MergeContext`], and+//! both land through [`advance_target`].//!//! # Destination-worktree safety follows git//!-//! The checks cover what `git status --porcelain` reports: a modified or-//! untracked file at a path the push range changes is refused, and the rest of-//! a dirty tree is autostashed and restored. Ignored files fall outside that-//! report, so a push overwrites one whose path the incoming commits track.+//! Uncommitted changes in the target worktree stay in place. The worktree sync+//! is a two-tree merge (`read-tree -m -u`), which carries a dirty path the+//! push range doesn't touch — staged entries included — and refuses one it+//! does. The refusal is fronted by a check over `git status --porcelain` that+//! names the conflicting files before anything moves. Ignored files fall+//! outside that report, so a push overwrites one whose path the incoming+//! commits track.//!-//! That is git's own line, not an oversight, and it holds at the mechanisms-//! actually used: the fast-forward hands the checkout to-//! `receive.denyCurrentBranch=updateInstead`, `--no-ff` syncs with-//! `read-tree -m -u`, and both run git's unpack-trees checks, which refuse to-//! clobber an untracked file and silently overwrite an ignored one — the same-//! split a `git merge` there would produce. Matching git is the decision;-//! don't add an ignored-file probe to make `wt` stricter than the tool it-//! wraps.+//! That is git's own line, not an oversight: the two-tree merge runs git's+//! unpack-trees checks, which refuse to clobber a modified or untracked file+//! and silently overwrite an ignored one — the same split a `git merge` run+//! there would produce, and the same update the `push-to-checkout` hook's+//! documented lenient policy performs (githooks(5)). Matching git is the+//! decision; don't add an ignored-file probe to make `wt` stricter than the+//! tool it wraps.use std::path::PathBuf;use anyhow::Context;use color_print::cformat;use worktrunk::git::{ErrorExt, GitError, Repository};+use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, format_with_gutter, info_message, progress_message, success_message, warning_message,};use super::types::MergeOperations;-use crate::commands::repository_ext::{RepositoryCliExt, TargetWorktreeStash};+use crate::commands::repository_ext::RepositoryCliExt;/// Distinguishes a standalone push from a fast-forward push driven by `wt merge`.///@@ -58,6 +62,13 @@ impl PushKind {PushKind::MergeFastForward => "Merging",}}++ fn reflog_message(self) -> &'static str {+ match self {+ PushKind::Standalone => "wt step push: fast-forward",+ PushKind::MergeFastForward => "wt merge: fast-forward",+ }+ }}/// Outcome of a push or no-ff merge, returned for JSON output.@@ -65,26 +76,6 @@ 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 {@@ -103,21 +94,24 @@ pub enum PushOutcome {/// Pre-computed state shared by both fast-forward push and `--no-ff` merge.////// Created by [`MergeContext::prepare`], which resolves the target branch,-/// verifies fast-forward, sets up the stash guard, counts commits, and captures-/// diff statistics — all steps that are identical between the two strategies.+/// verifies fast-forward, checks for conflicting target-worktree changes,+/// counts commits, and captures diff statistics — all steps that are identical+/// between the two strategies.struct MergeContext {repo: Repository,target_branch: String,target_worktree_path: Option<PathBuf>,/// Snapshotted target SHA for TOCTOU-safe ref updates.target_tip: String,- stash_guard: Option<TargetWorktreeStash>,+ /// HEAD of the source worktree, resolved once for the ancestry check and+ /// the fast-forward ref update.+ head_sha: String,commit_count: usize,stats_summary: Vec<String>,}impl MergeContext {- /// Resolve target, verify fast-forward, stash guard, count commits, capture stats.+ /// Resolve target, verify fast-forward, check conflicts, count commits, capture stats.fn prepare(target: Option<&str>, operations: Option<MergeOperations>) -> anyhow::Result<Self> {let repo = Repository::current()?;@@ -132,13 +126,9 @@ impl MergeContext {let target_worktree_path = repo.worktree_for_branch(&target_branch)?;// A registered worktree whose directory is gone can't receive the- // update, and the two strategies disagreed about that: the- // fast-forward pushes with `receive.denyCurrentBranch=updateInstead`,- // whose receive-pack cd's into the directory and dies in git plumbing- // (`exec 'update-index': cd to '…' failed`), while `--no-ff` moves the- // ref with plumbing of its own and skipped the sync. Refusing gives- // one answer, and names the `git worktree prune` that clears the- // registration.+ // sync in `advance_target` — git dies trying to cd into it. Refusing+ // upfront gives a clear answer, and names the `git worktree prune`+ // that clears the registration.if let Some(path) = &target_worktree_path&& !path.exists(){@@ -180,9 +170,10 @@ impl MergeContext {.into());}- // Auto-stash non-overlapping changes in target worktree- let stash_guard =- repo.prepare_target_worktree(target_worktree_path.as_ref(), &target_branch)?;+ // Refuse when uncommitted changes in the target worktree overlap the+ // push range. Non-overlapping changes stay in place: the two-tree+ // merge in `advance_target` carries them through untouched.+ repo.ensure_no_target_conflicts(target_worktree_path.as_ref(), &target_branch)?;// TODO(#3519 follow-up): when `target_branch` was behind its upstream// (see `Repository::span_upstream`), this count mixes the carried@@ -209,7 +200,7 @@ impl MergeContext {target_branch,target_worktree_path,target_tip,- stash_guard,+ head_sha,commit_count,stats_summary,})@@ -235,8 +226,7 @@ impl MergeContext {} else {"commits"};- let full_sha = self.repo.run_command(&["rev-parse", "HEAD"])?;- let head_sha = self.repo.short_sha(full_sha.trim())?;+ let head_sha = self.repo.short_sha(&self.head_sha)?;let operations_note = format_operations_note(operations);@@ -283,17 +273,6 @@ impl MergeContext {true}- /// Explicitly restore the stash guard (before success message).- ///- /// 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,- }- }-/// Print success message with commit/file stats.////// `verb` is the past-tense action (e.g. "Merged to", "Pushed to").@@ -358,6 +337,132 @@ fn format_up_to_date_context(operations: Option<MergeOperations>) -> String {}}+// ---------------------------------------------------------------------------+// Target update+// ---------------------------------------------------------------------------++/// Advance `target_branch` to `new_sha` and sync its checked-out worktree.+///+/// The worktrees share one object store, so nothing needs transferring: the+/// update is a compare-and-swap `update-ref` against `old_sha`, which fails+/// cleanly if another process advanced the target since+/// [`MergeContext::prepare`] snapshotted it.+///+/// The worktree sync is git's documented lenient `push-to-checkout` policy+/// (githooks(5)): `update-index --refresh` then a two-tree merge+/// (`read-tree -m -u`). The two-tree merge leaves uncommitted changes at paths+/// the update doesn't touch exactly where they are — staged entries stay+/// staged — and refuses the update when a dirty path overlaps it. (`reset+/// --keep` can't express this sync: HEAD already points at `new_sha` through+/// the branch, so it sees old == new and is a no-op.) On refusal the ref+/// update is rolled back with a second compare-and-swap, so the branch and+/// its worktree move together or not at all.+///+/// `reflog_message` labels the target branch's reflog entry — the recovery+/// affordance for the one operation that moves a branch the user isn't+/// standing on, where every other mover (`push`, `merge`, `reset`) names+/// itself.+fn advance_target(+ repo: &Repository,+ target_branch: &str,+ target_worktree_path: Option<&PathBuf>,+ old_sha: &str,+ new_sha: &str,+ reflog_message: &str,+) -> anyhow::Result<()> {+ let target_ref = format!("refs/heads/{target_branch}");+ repo.run_command(&[+ "update-ref",+ "-m",+ reflog_message,+ &target_ref,+ new_sha,+ old_sha,+ ])+ .map_err(|e| GitError::PushFailed {+ target_branch: target_branch.to_string(),+ error: format!("Failed to update ref: {}", e.display_message()),+ })?;++ let Some(wt_path) = target_worktree_path else {+ return Ok(());+ };+ let target_wt = repo.worktree_at(wt_path);+ // Refresh first: `read-tree -m -u` trusts index stat data, so an entry+ // that is merely stat-dirty would otherwise refuse as "not uptodate".+ // `submodule.recurse=false`: the sync moves the superproject only —+ // recursing into submodules re-introduces #1604's failure mode when the+ // user has `submodule.recurse=true` (read-tree is on git's always-recurse+ // list).+ let sync_result = target_wt+ .run_command(&["update-index", "-q", "--refresh"])+ .and_then(|_| {+ target_wt.run_command(&[+ "-c",+ "submodule.recurse=false",+ "read-tree",+ "-m",+ "-u",+ old_sha,+ new_sha,+ ])+ });+ let e = match sync_result {+ Ok(_) => {+ // The compare-and-swap guarded the ref update, not the sync that+ // follows it: a commit racing into the target worktree inside+ // that window is built against the pre-sync index, so its tree+ // reverts the pushed content while keeping it in the ancestry — a+ // state the old fast-forward path couldn't reach because+ // receive-pack re-verifies the expected old value when committing+ // the ref. Re-read the ref so that interleaving surfaces instead+ // of being reported as a clean merge. The push range is in the+ // tip's ancestry either way, so this warns rather than fails.+ let tip_after = repo.run_command(&["rev-parse", &target_ref])?;+ if tip_after.trim() != new_sha {+ eprintln!(+ "{}",+ warning_message(cformat!(+ "<bold>{target_branch}</> moved while its worktree was being synced; check <bold>git -C {} status</>",+ format_path_for_display(wt_path)+ ))+ );+ }+ return Ok(());+ }+ Err(e) => e,+ };++ // The sync refused — a conflicting change appeared in the race window+ // after the upfront check, or the index is locked; git's own error names+ // the cause. unpack-trees runs its refusal checks before writing anything,+ // so the worktree is normally untouched — only a write error partway+ // through the update phase (ENOSPC, a read-only file) can leave a subset+ // of files already carrying the new content, and git's error says which+ // write failed. Either way, put the ref back so the branch and its+ // worktree stay consistent.+ let context = match repo.run_command(&[+ "update-ref",+ "-m",+ "wt: rollback (worktree sync failed)",+ &target_ref,+ old_sha,+ new_sha,+ ]) {+ Ok(_) => {+ format!("Syncing the {target_branch} worktree failed; the ref change was rolled back")+ }+ // Only a third writer moving the ref inside this window can land here;+ // report the state that remains rather than guessing at a fix.+ Err(rollback_err) => format!(+ "Syncing the {target_branch} worktree failed, and the ref change could not be \+ rolled back ({rollback_err}); {target_branch} has advanced but its worktree \+ was not synced"+ ),+ };+ Err(e).context(context)+}+// ---------------------------------------------------------------------------// Fast-forward push// ---------------------------------------------------------------------------@@ -367,52 +472,43 @@ fn format_up_to_date_context(operations: Option<MergeOperations>) -> String {/// The `operations` parameter indicates which merge operations occurred (commit, squash, rebase)./// Pass `None` for standalone push operations where these concepts don't apply.///-/// During the push stage we temporarily `git stash` non-overlapping changes in the-/// target worktree (if present) so that concurrent edits there do not block the-/// fast-forward. The stash is restored afterward and we bail out early if any file-/// overlaps with the push range.+/// Uncommitted changes in the target worktree don't move: [`advance_target`]'s+/// two-tree merge carries them in place, and [`MergeContext::prepare`] already+/// refused any that overlap the push range.pub fn handle_push(target: Option<&str>,kind: PushKind,operations: Option<MergeOperations>,) -> anyhow::Result<PushResult> {- let mut ctx = MergeContext::prepare(target, operations)?;+ let ctx = MergeContext::prepare(target, operations)?;ctx.show_progress(kind.verb_progressive(), "", operations)?;- // Perform the push via --receive-pack (atomically updates ref + working tree)- let git_common_dir = ctx.repo.git_common_dir();- let git_common_dir_str = git_common_dir.to_string_lossy();- let push_target = format!("HEAD:{}", ctx.target_branch);-- ctx.repo- .run_command(&[- "push",- "--recurse-submodules=no",- "--receive-pack=git -c receive.denyCurrentBranch=updateInstead receive-pack",- git_common_dir_str.as_ref(),- &push_target,- ])- .map_err(|e| GitError::PushFailed {- target_branch: ctx.target_branch.clone(),- error: e.display_message(),- })?;-- let stash_restore_failed = !ctx.restore_stash();-- let outcome = if ctx.commit_count > 0 {- ctx.show_success(kind.verb_past(), "", "");- PushOutcome::FastForwarded- } else {+ if ctx.commit_count == 0 {+ // The ancestry check passed and no commits are in target..HEAD, so+ // HEAD == target tip and there is nothing to advance.ctx.show_up_to_date_if_needed(operations);- PushOutcome::UpToDate- };+ return Ok(PushResult {+ target: ctx.target_branch,+ commit_count: 0,+ outcome: PushOutcome::UpToDate,+ });+ }+ advance_target(+ &ctx.repo,+ &ctx.target_branch,+ ctx.target_worktree_path.as_ref(),+ &ctx.target_tip,+ &ctx.head_sha,+ kind.reflog_message(),+ )?;++ ctx.show_success(kind.verb_past(), "", "");Ok(PushResult {target: ctx.target_branch,commit_count: ctx.commit_count,- stash_restore_failed,- outcome,+ outcome: PushOutcome::FastForwarded,})}@@ -422,41 +518,27 @@ pub fn handle_push(/// Merge to target branch using `--no-ff` (creates a merge commit).///-/// Uses git plumbing (`commit-tree` + `update-ref`) to create a merge commit-/// on the target branch without needing to check it out. This is safe because-/// [`MergeContext::prepare`] verified that the target is an ancestor of the-/// feature tip, so the feature tree is the correct integration result. The-/// source may be rebased or may retain an explicitly preserved merge-shaped-/// graph.-///-/// If the target branch has a checked-out worktree, its working tree is synced-/// via `read-tree -m -u` after the ref update. We use a two-tree merge-/// (`read-tree -m -u <old> <new>`) instead of `reset --hard` because it refuses-/// to overwrite tracked files with local modifications (TOCTOU safety), while-/// `reset --hard` would silently discard them. (`reset --keep` can't be used-/// here because after `update-ref`, HEAD already points to the merge commit, so-/// `reset --keep HEAD` sees old==new and is a no-op.) The stash guard pattern-/// from `handle_push` is reused for dirty target worktrees.+/// Uses git plumbing (`commit-tree` + [`advance_target`]) to create a merge+/// commit on the target branch without needing to check it out. This is safe+/// because [`MergeContext::prepare`] verified that the target is an ancestor+/// of the feature tip, so the feature tree is the correct integration result.+/// The source may be rebased or may retain an explicitly preserved+/// merge-shaped graph.pub fn handle_no_ff_merge(target: Option<&str>,operations: Option<MergeOperations>,feature_branch: &str,) -> anyhow::Result<PushResult> {- let mut ctx = MergeContext::prepare(target, operations)?;+ let ctx = MergeContext::prepare(target, operations)?;ctx.show_progress("Merging", " (--no-ff)", 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,});}@@ -465,13 +547,7 @@ pub fn handle_no_ff_merge(// whether the source was rebased or explicitly preserved.let tree = ctx.repo- .run_command(&["rev-parse", "HEAD^{tree}"])?- .trim()- .to_string();-- let feature_tip = ctx- .repo- .run_command(&["rev-parse", "HEAD"])?+ .run_command(&["rev-parse", &format!("{}^{{tree}}", ctx.head_sha)])?.trim().to_string();@@ -488,7 +564,7 @@ pub fn handle_no_ff_merge("-p",&ctx.target_tip,"-p",- &feature_tip,+ &ctx.head_sha,"-m",&merge_message,])@@ -496,39 +572,18 @@ pub fn handle_no_ff_merge(.trim().to_string();- // Atomically update the target branch ref (with old-value check for safety)- let target_ref = format!("refs/heads/{}", ctx.target_branch);- ctx.repo- .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.display_message()),- })?;-- // Sync the target worktree's working tree if it exists.- // Use `read-tree -m -u` (two-tree merge) instead of `reset --hard` so that- // any tracked-file modifications added between the pre-push dirty check and- // now cause the sync to fail rather than silently discarding work (TOCTOU- // safety). Note: `reset --keep` can't be used here because after- // `update-ref`, HEAD already equals the merge commit, making it a no-op.- // The merge is already done (ref updated), so treat sync failure as a warning.- if let Some(wt_path) = &ctx.target_worktree_path {- let target_wt = ctx.repo.worktree_at(wt_path);- if let Err(e) =- target_wt.run_command(&["read-tree", "-m", "-u", &ctx.target_tip, &merge_sha])- {- eprintln!(- "{}",- warning_message(cformat!(- "Failed to sync target worktree; run <bold>git -C {} reset --hard HEAD</> manually",- worktrunk::path::format_path_for_display(wt_path)- ))- );- tracing::warn!(error = %e, "Failed to sync target worktree: {e}");- }- }-- let stash_restore_failed = !ctx.restore_stash();+ advance_target(+ &ctx.repo,+ &ctx.target_branch,+ ctx.target_worktree_path.as_ref(),+ &ctx.target_tip,+ &merge_sha,+ if operations.is_some() {+ "wt merge: no-ff"+ } else {+ "wt step push: no-ff"+ },+ )?;// Display uses `Repository::short_sha`; the JSON payload carries the full SHA.let merge_sha_short = ctx.repo.short_sha(&merge_sha)?;@@ -539,7 +594,6 @@ pub fn handle_no_ff_merge(target: ctx.target_branch,commit_count: ctx.commit_count,outcome: PushOutcome::MergeCommit { merge_sha },- stash_restore_failed,})}@@ -547,6 +601,87 @@ pub fn handle_no_ff_merge(mod tests {use super::*;use crate::commands::worktree::types::MergeOperations;+ use worktrunk::testing::TestRepo;++ /// `advance_target` moves the branch and worktree together while leaving+ /// non-overlapping uncommitted changes — staged entries included — exactly+ /// in place, and refuses atomically otherwise: an overlapping dirty file+ /// rolls the ref update back, and a stale `old_sha` (a concurrently+ /// advanced target) fails the compare-and-swap before anything moves.+ /// These paths have no deterministic trigger through the CLI — the upfront+ /// conflict check catches everything slower than a race — so they are+ /// proven here.+ #[test]+ fn advance_target_carries_dirty_files_and_refuses_atomically() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let root = test.root_path().to_path_buf();+ std::fs::write(root.join("x.txt"), "base-x").unwrap();+ test.run_git(&["add", "x.txt"]);+ test.run_git(&["commit", "-m", "add x"]);+ let old = test.git_output(&["rev-parse", "HEAD"]);++ // Build the incoming commit on a side branch, then return to main so+ // the worktree sits at `old` with a clean tree.+ test.run_git(&["switch", "-c", "incoming"]);+ std::fs::write(root.join("x.txt"), "incoming-x").unwrap();+ test.run_git(&["commit", "-am", "change x"]);+ let new = test.git_output(&["rev-parse", "HEAD"]);+ test.run_git(&["switch", "main"]);++ // Non-overlapping uncommitted state: an unstaged edit, a staged new+ // file, and an untracked file.+ std::fs::write(root.join("file.txt"), "unstaged-edit").unwrap();+ std::fs::write(root.join("staged.txt"), "staged").unwrap();+ test.run_git(&["add", "staged.txt"]);+ std::fs::write(root.join("untracked.txt"), "untracked").unwrap();++ advance_target(&repo, "main", Some(&root), &old, &new, "test").unwrap();+ assert_eq!(test.git_output(&["rev-parse", "main"]), new);+ assert_eq!(+ std::fs::read_to_string(root.join("x.txt")).unwrap(),+ "incoming-x"+ );+ // Unstaged edit still unstaged, staged entry still staged (and only+ // it), untracked file still untracked.+ assert_eq!(test.git_output(&["diff", "--name-only"]), "file.txt");+ assert_eq!(+ test.git_output(&["diff", "--cached", "--name-only"]),+ "staged.txt"+ );+ assert_eq!(+ test.git_output(&["ls-files", "--others", "--exclude-standard"]),+ "untracked.txt"+ );++ // Overlap: a dirty edit to a file the next update changes. The sync+ // refuses and the ref update is rolled back.+ test.run_git(&["switch", "-c", "incoming2", "incoming"]);+ std::fs::write(root.join("x.txt"), "incoming2-x").unwrap();+ test.run_git(&["commit", "-am", "change x again"]);+ let new2 = test.git_output(&["rev-parse", "HEAD"]);+ test.run_git(&["switch", "main"]);+ std::fs::write(root.join("x.txt"), "local-edit").unwrap();++ let err = advance_target(&repo, "main", Some(&root), &new, &new2, "test").unwrap_err();+ assert!(+ err.to_string().contains("rolled back"),+ "unexpected error: {err:#}"+ );+ assert_eq!(test.git_output(&["rev-parse", "main"]), new);+ assert_eq!(+ std::fs::read_to_string(root.join("x.txt")).unwrap(),+ "local-edit"+ );++ // Stale old_sha: the compare-and-swap fails before anything moves.+ let err = advance_target(&repo, "main", Some(&root), &old, &new2, "test").unwrap_err();+ assert!(+ err.to_string().contains("Can't push"),+ "unexpected error: {err:#}"+ );+ assert_eq!(test.git_output(&["rev-parse", "main"]), new);+ }#[test]fn test_format_operations_note() {diff --git a/src/main.rs b/src/main.rsindex 45fd257df..e36f21ce1 100644--- a/src/main.rs+++ b/src/main.rs@@ -309,13 +309,11 @@ 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,@@ -325,22 +323,12 @@ 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/common/mod.rs b/tests/common/mod.rsindex 648132644..64086eb81 100644--- a/tests/common/mod.rs+++ b/tests/common/mod.rs@@ -23,30 +23,6 @@ use std::path::{Path, PathBuf};use tempfile::TempDir;use worktrunk::path::to_posix_path;-// =============================================================================-// Git hooks-// =============================================================================--/// Write `script` as a native git hook at `path` and make git willing to run it.-///-/// Git runs hooks through a shell it ships on every platform, so the script is-/// `sh` regardless of host and the hook itself needs no platform gate. Only the-/// executable bit does, since Windows has none to set. A path interpolated into-/// the script needs forward slashes (`path_slash::PathExt::to_slash_lossy`), or-/// a Windows path's separators reach `sh` as escapes.-pub fn write_git_hook(path: &Path, script: &str) {- if let Some(parent) = path.parent() {- std::fs::create_dir_all(parent).unwrap();- }- std::fs::write(path, script).unwrap();-- #[cfg(unix)]- {- use std::os::unix::fs::PermissionsExt as _;- std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o755)).unwrap();- }-}-// =============================================================================// Signal handling (for PTY tests)// =============================================================================diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 22fa0889e..56789168b 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -3,7 +3,7 @@ use crate::common::{mock_commands::{create_mock_cargo, create_mock_llm_auth},repo, repo_with_alternate_primary, repo_with_main_worktree, repo_with_multi_commit_feature,repo_with_remote, setup_snapshot_settings, wait_for_file, wait_for_file_content,- wait_for_worktree_removed, write_git_hook,+ wait_for_worktree_removed,};use insta::assert_snapshot;use insta_cmd::assert_cmd_snapshot;@@ -1829,7 +1829,7 @@ fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {assert!(feature_wt.exists(), "failed merge must keep the worktree");assert!(repo.git_output(&["stash", "list"]).is_empty(),- "known divergence must fail before target stashing"+ "a failed merge must not write to the stash list");}@@ -1879,7 +1879,7 @@ fn test_merge_no_commit_no_rebase_rejects_unrelated_history(repo: TestRepo) {assert!(orphan_wt.exists(), "failed merge must keep the worktree");assert!(repo.git_output(&["stash", "list"]).is_empty(),- "unrelated history must fail before target stashing"+ "a failed merge must not write to the stash list");}@@ -1933,7 +1933,7 @@ post-merge = "touch {{ repo_path }}/post-merge-race-ran"assert!(feature_wt.exists(), "failed merge must skip cleanup");assert!(repo.git_output(&["stash", "list"]).is_empty(),- "failed merge must not leave a target stash"+ "a failed merge must not write to the stash list");assert!(!post_merge_marker.exists(),@@ -1941,163 +1941,6 @@ post-merge = "touch {{ repo_path }}/post-merge-race-ran");}-#[rstest]-fn test_merge_target_diverges_during_receive_restores_autostash(mut repo: TestRepo) {- let feature_wt = repo.add_worktree_with_commit(- "feature-receive-race",- "feature.txt",- "feature content",- "Add feature",- );- fs::write(repo.root_path().join("notes.txt"), "target notes").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("pre-receive"),- r#"#!/bin/sh-set -eu-unset GIT_QUARANTINE_PATH GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES-target=$(git rev-parse refs/heads/main)-tree=$(git rev-parse "${target}^{tree}")-concurrent=$(printf 'concurrent target\n' | git commit-tree "$tree" -p "$target")-git update-ref refs/heads/main "$concurrent" "$target"-"#,- );-- let target_before = repo.git_output(&["rev-parse", "main"]);- let source_tip = repo.git_output(&["rev-parse", "feature-receive-race"]);- let output = repo- .wt_command()- .args([- "merge",- "main",- "--no-commit",- "--no-rebase",- "--no-remove",- "--no-hooks",- ])- .current_dir(&feature_wt)- .output()- .unwrap();-- assert!(- !output.status.success(),- "a divergent receive-time target update must reject the merge"- );- let target_after = repo.git_output(&["rev-parse", "main"]);- assert_ne!(- target_after,- target_before,- "receive hook did not advance target; stderr:\n{}",- String::from_utf8_lossy(&output.stderr)- );- assert_eq!(- repo.git_output(&["show", "-s", "--format=%s", "main"]),- "concurrent target"- );- assert_eq!(- repo.git_output(&["rev-parse", "feature-receive-race"]),- source_tip- );- assert!(feature_wt.exists(), "failed merge must skip cleanup");- assert_eq!(- fs::read_to_string(repo.root_path().join("notes.txt")).unwrap(),- "target notes",- "target autostash must be restored after receive rejection"- );- assert!(- repo.git_output(&["stash", "list"]).is_empty(),- "target autostash must not leak"- );-}--/// 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");@@ -2411,10 +2254,11 @@ fn test_merge_when_default_branch_missing_worktree(repo: TestRepo) {fn test_merge_doesnt_set_receive_deny_current_branch(merge_scenario: (TestRepo, PathBuf)) {let (repo, feature_wt) = merge_scenario;- // Explicitly set config to "refuse" - this would block pushes to checked-out branches+ // Hostile receive config: this would block a `git push` into a checked-out+ // branch. The merge advances the ref with plumbing, so it neither trips+ // over the setting nor rewrites it.repo.run_git(&["config", "receive.denyCurrentBranch", "refuse"]);- // Perform merge - should succeed despite "refuse" setting because we use --receive-packlet mut cmd = make_snapshot_cmd(&repo, "merge", &["main"], Some(&feature_wt));let output = cmd.output().unwrap();assert!(@@ -4367,16 +4211,19 @@ fn test_merge_no_ff_syncs_target_worktree(mut repo_with_main_worktree: TestRepo)/// --no-ff merge with non-overlapping dirty files in the target worktree.///-/// The target worktree has uncommitted changes to a file that doesn't overlap-/// with the merge. These should be auto-stashed, the merge commit created,-/// and the stash restored afterward.+/// The target worktree has uncommitted changes at paths the merge doesn't+/// touch. The two-tree merge carries them in place — staged state preserved,+/// stash list untouched — while the merge commit lands.#[rstest]-fn test_merge_no_ff_dirty_target_autostash(mut repo_with_main_worktree: TestRepo) {+fn test_merge_no_ff_dirty_target_stays_in_place(mut repo_with_main_worktree: TestRepo) {let repo = &mut repo_with_main_worktree;let main_wt = repo.root_path().to_path_buf();- // Make main worktree dirty with a non-conflicting file+ // Non-overlapping uncommitted state in the target worktree: an untracked+ // file and a staged new file.fs::write(main_wt.join("notes.txt"), "temporary notes").unwrap();+ fs::write(main_wt.join("staged.txt"), "staged").unwrap();+ repo.run_git(&["add", "staged.txt"]);let feature_wt = repo.add_worktree("feature");repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");@@ -4388,20 +4235,29 @@ fn test_merge_no_ff_dirty_target_autostash(mut repo_with_main_worktree: TestRepoSome(&feature_wt)));- // Verify dirty file was restored after autostash- let notes = fs::read_to_string(main_wt.join("notes.txt")).unwrap();+ // The uncommitted changes never moved — staged state included.+ assert_eq!(+ fs::read_to_string(main_wt.join("notes.txt")).unwrap(),+ "temporary notes"+ );+ assert_eq!(+ repo.git_output(&["diff", "--cached", "--name-only"]),+ "staged.txt",+ "the staged entry must stay staged"+ );assert_eq!(- notes, "temporary notes",- "Autostash should restore dirty file"+ repo.git_output(&["ls-files", "--others", "--exclude-standard"]),+ "notes.txt",+ "the untracked file must stay untracked");- // Verify autostash cleaned up (no leftover stash entries)+ // Nothing touches the stash list.let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();assert!(String::from_utf8_lossy(&stash_list.stdout).trim().is_empty(),- "Autostash should clean up after itself"+ "the merge must not create stash entries");// Verify merge commit was created@@ -4465,20 +4321,22 @@ fn test_merge_no_ff_dirty_target_conflict(mut repo_with_main_worktree: TestRepo));}-/// --no-ff merge succeeds with a warning when target worktree sync fails.+/// --no-ff merge fails whole when the target worktree can't be synced.///-/// Simulates a TOCTOU race by locking the target worktree's index before the-/// merge. The merge commit is still created (via update-ref), but the working-/// tree sync (read-tree) fails and emits a warning instead of aborting.+/// A locked index in the target worktree stands in for a sync failure in the+/// window after the upfront conflict check. The ref update is rolled back, so+/// the branch and its worktree move together or not at all — no half-landed+/// merge leaving the worktree stale behind its own branch.#[rstest]-fn test_merge_no_ff_sync_failure_warns(mut repo_with_main_worktree: TestRepo) {+fn test_merge_no_ff_sync_failure_rolls_back(mut repo_with_main_worktree: TestRepo) {let repo = &mut repo_with_main_worktree;let main_wt = repo.root_path().to_path_buf();let feature_wt = repo.add_worktree("feature");repo.commit_in_worktree(&feature_wt, "feature.txt", "feature content", "Add feature");- // Lock the target worktree's index to make read-tree fail+ // Lock the target worktree's index to make the sync fail+ let target_before = repo.git_output(&["rev-parse", "main"]);let index_lock = main_wt.join(".git/index.lock");fs::write(&index_lock, "").unwrap();@@ -4489,30 +4347,22 @@ fn test_merge_no_ff_sync_failure_warns(mut repo_with_main_worktree: TestRepo) {.output().unwrap();- // Merge should still succeed (ref was updated before sync)assert!(- output.status.success(),- "merge should succeed despite sync failure: {}",+ !output.status.success(),+ "a merge whose worktree sync fails must fail whole: {}",String::from_utf8_lossy(&output.stderr));-- // Should emit a warning about the sync failurelet stderr = String::from_utf8_lossy(&output.stderr);assert!(- stderr.contains("Failed to sync target worktree"),- "should warn about sync failure: {stderr}"+ stderr.contains("rolled back"),+ "the error must say the ref change was rolled back: {stderr}");- // Verify merge commit was created on the ref- let parent_count = repo.git_output(&["cat-file", "-p", "main"]);- let parents: Vec<&str> = parent_count- .lines()- .filter(|l| l.starts_with("parent "))- .collect();+ // The rollback left the target exactly where it started — no merge commit.assert_eq!(- parents.len(),- 2,- "Should create merge commit despite sync failure"+ repo.git_output(&["rev-parse", "main"]),+ target_before,+ "the ref update must be rolled back");// Clean up lock so test teardown doesn't fail@@ -4625,7 +4475,6 @@ 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.rsindex 791399efb..e2b4f7fc1 100644--- a/tests/integration_tests/push.rs+++ b/tests/integration_tests/push.rs@@ -1,33 +1,10 @@use crate::common::{TestRepo, make_snapshot_cmd, repo, repo_with_feature_worktree, repo_with_remote,- setup_snapshot_settings, write_git_hook,+ setup_snapshot_settings,};use insta_cmd::assert_cmd_snapshot;use rstest::rstest;-/// Install a `post-receive` hook whose body `build_body` composes from the repo-/// root, passed in forward-slashed form.-///-/// The hook fires during `wt`'s own `git push`, which is the window between the-/// autostash capture and its restore. Git runs hooks through a shell it-/// provides on every platform, so the script is `sh` either way, and the root-/// is forward-slashed for the same reason — a Windows path's backslashes would-/// otherwise reach `sh` as escapes.-fn install_post_receive_hook(root: &std::path::Path, build_body: impl FnOnce(&str) -> String) {- use path_slash::PathExt as _;-- let body = build_body(&root.to_slash_lossy());- write_git_hook(- &root.join(".git/hooks/post-receive"),- &format!(- "#!/bin/sh\n\- unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_QUARANTINE_PATH\n\- {body}\n\- exit 0\n"- ),- );-}-/// Helper to create snapshot with normalized pathsfn snapshot_push(test_name: &str, repo: &TestRepo, args: &[&str], cwd: Option<&std::path::Path>) {let settings = setup_snapshot_settings(repo);@@ -120,150 +97,66 @@ fn test_push_with_dirty_target(mut repo: TestRepo) {);}+/// Uncommitted changes in the target worktree that don't overlap the push+/// range never move: the two-tree merge carries them in place — an unstaged+/// edit stays unstaged, a staged entry stays staged, an untracked file stays+/// untracked. The stash list stays empty throughout, so nothing `wt` does can+/// collide with another process's stash operations (#3683's whole class).#[rstest]-fn test_push_dirty_target_autostash(mut repo: TestRepo) {- // Make main worktree (repo root) dirty with a non-conflicting file- std::fs::write(repo.root_path().join("notes.txt"), "temporary notes").unwrap();+fn test_push_dirty_target_changes_stay_in_place(mut repo: TestRepo) {+ // A tracked file committed to main before the feature branches, so the+ // push range doesn't touch it.+ let root = repo.root_path().to_path_buf();+ std::fs::write(root.join("tracked.txt"), "base").unwrap();+ repo.run_git(&["add", "tracked.txt"]);+ repo.run_git(&["commit", "-m", "Add tracked file"]);++ // Non-overlapping uncommitted state in the target worktree (repo root).+ std::fs::write(root.join("tracked.txt"), "unstaged-edit").unwrap();+ std::fs::write(root.join("staged.txt"), "staged").unwrap();+ repo.run_git(&["add", "staged.txt"]);+ std::fs::write(root.join("untracked.txt"), "untracked").unwrap();let feature_wt = repo.add_feature();- // Push should succeed by auto-stashing the non-conflicting target changessnapshot_push(- "push_dirty_target_autostash",+ "push_dirty_target_carried",&repo,&["main"],Some(&feature_wt),);- // Ensure the target worktree content is restored- let notes = std::fs::read_to_string(repo.root_path().join("notes.txt")).unwrap();- assert_eq!(notes, "temporary notes");-- // Autostash should clean up after itself- let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();- assert!(- String::from_utf8_lossy(&stash_list.stdout)- .trim()- .is_empty()- );-}--/// Regression test for #3683: the autostash restore must not hinge on a-/// positional `stash@{0}` selector. A stash pushed into the repo between the-/// autostash and its restore — a concurrent `wt merge`, an editor integration —-/// shifts the reflog indices, so restoring by position would pop (and drop) the-/// interloper's entry and silently discard the user's uncommitted work.-/// Restoring by the stash's immutable commit SHA is immune to the reorder.-///-/// A `post-receive` hook is the deterministic stand-in for the concurrent-/// writer: it fires during `wt`'s own fast-forward `git push`, which is exactly-/// the window between the autostash capture and its restore.-#[rstest]-fn test_push_autostash_survives_concurrent_stash(mut repo: TestRepo) {- // Uncommitted, non-conflicting work in the target worktree (repo root).- let notes = repo.root_path().join("notes.txt");- std::fs::write(¬es, "PRECIOUS-USER-WORK").unwrap();-- // A post-receive hook that pushes an unrelated stash during the push,- // shifting the reflog indices out from under the autostash entry.- install_post_receive_hook(repo.root_path(), |root| {- format!(- "printf 'interloper\\n' > '{root}/interloper.txt'\n\- git -C '{root}' -c user.email=i@i -c user.name=I \- stash push --include-untracked -m INTERLOPER >/dev/null 2>&1"- )- });-- let feature_wt = repo.add_feature();-- let output = repo- .wt_command()- .args(["step", "push", "main"])- .current_dir(&feature_wt)- .output()- .expect("failed to run push");- assert!(- output.status.success(),- "push failed: {}",- String::from_utf8_lossy(&output.stderr)- );-- // The user's uncommitted work must survive — not the interloper's content.+ // The push landed and every uncommitted change sits exactly where it was.assert_eq!(- std::fs::read_to_string(¬es).unwrap(),- "PRECIOUS-USER-WORK",- "autostash restored the wrong entry, discarding the user's work"- );-- // The interloper's stash is untouched; the autostash entry is cleaned up.- let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();- let stash_list = String::from_utf8_lossy(&stash_list.stdout);- assert!(- stash_list.contains("INTERLOPER"),- "the concurrent writer's stash was dropped: {stash_list:?}"- );- assert!(- !stash_list.contains("autostash"),- "the autostash entry was left behind: {stash_list:?}"+ repo.git_output(&["rev-parse", "main"]),+ repo.git_output(&["rev-parse", "feature"]));-}--/// A restore that genuinely can't replay — the stashed path is occupied again-/// by the time the push finishes — must warn with a recoverable `git stash-/// apply <sha>` rather than silently report success. Data-safety guard for-/// #3683: the stash entry is left intact so the work is recoverable.-#[rstest]-fn test_push_autostash_restore_failure_warns(mut repo: TestRepo) {- // Untracked, non-conflicting work in the target worktree (repo root).- std::fs::write(repo.root_path().join("notes.txt"), "USER-WORK").unwrap();-- // A post-receive hook re-creates the stashed path with different content,- // so `git stash apply` can't restore the untracked file and the restore- // fails after the push has already landed.- install_post_receive_hook(repo.root_path(), |root| {- format!("printf 'HOOK-CONFLICT\\n' > '{root}/notes.txt'")- });-- let feature_wt = repo.add_feature();-- let output = repo- .wt_command()- .args(["step", "push", "main"])- .current_dir(&feature_wt)- .output()- .expect("failed to run push");-- // 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)+ repo.git_output(&["diff", "--name-only"]),+ "tracked.txt",+ "the unstaged edit must stay unstaged");- let stderr = String::from_utf8_lossy(&output.stderr);- assert!(- stderr.contains("Failed to restore stashed changes"),- "expected a restore-failure warning, got: {stderr}"+ assert_eq!(+ repo.git_output(&["diff", "--cached", "--name-only"]),+ "staged.txt",+ "the staged entry must stay staged");- assert!(- stderr.contains("git stash apply"),- "warning must name the recovery command: {stderr}"+ assert_eq!(+ repo.git_output(&["ls-files", "--others", "--exclude-standard"]),+ "untracked.txt",+ "the untracked file must stay untracked");-- // 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"+ std::fs::read_to_string(root.join("tracked.txt")).unwrap(),+ "unstaged-edit");- // The stash entry survives for recovery — a failed apply does not drop it.+ // Nothing wt does touches the stash list.let stash_list = repo.git_command().args(["stash", "list"]).run().unwrap();assert!(- String::from_utf8_lossy(&stash_list.stdout).contains("autostash"),- "the recoverable stash entry must remain"+ String::from_utf8_lossy(&stash_list.stdout)+ .trim()+ .is_empty());}@@ -407,9 +300,10 @@ fn test_push_no_ff(mut repo: TestRepo) {#[rstest]fn test_push_with_submodule_recurse_config(mut repo: TestRepo) {- // Regression test for https://github.com/max-sixty/worktrunk/issues/1604- // When submodule.recurse=true is set, git push tries to recurse into- // submodules which fails for local worktree-to-worktree pushes.+ // Regression test for https://github.com/max-sixty/worktrunk/issues/1604:+ // submodule.recurse=true once broke the push stage. The update is now+ // plumbing (`update-ref` + `read-tree`) the setting can't reach; this+ // pins that hostile config stays harmless.repo.run_git(&["config", "submodule.recurse", "true"]);repo.add_main_worktree();@@ -445,13 +339,138 @@ fn test_push_no_ff_with_submodule_recurse_config(mut repo: TestRepo) {);}+/// An ignored file at a path the push range tracks is silently overwritten —+/// the documented Data Safety carve-out (module spec: the same split a+/// `git merge` run in the target would produce). Pinned here because+/// read-tree's deprecated `--exclude-per-directory` help text suggests the+/// opposite; modern git applies the standard excludes during the sync by+/// default.+#[rstest]+fn test_push_overwrites_ignored_file_at_tracked_path(mut repo: TestRepo) {+ let root = repo.root_path().to_path_buf();+ std::fs::write(root.join(".gitignore"), "dist.txt\n").unwrap();+ repo.run_git(&["add", ".gitignore"]);+ repo.run_git(&["commit", "-m", "Add gitignore"]);++ let feature_wt = repo.add_worktree("feature");+ std::fs::write(feature_wt.join("dist.txt"), "tracked").unwrap();+ repo.run_git_in(&feature_wt, &["add", "-f", "dist.txt"]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "Track dist.txt"]);++ // Ignored file in the target worktree at the path the push now tracks.+ std::fs::write(root.join("dist.txt"), "IGNORED-LOCAL").unwrap();++ let output = repo+ .wt_command()+ .args(["step", "push", "main"])+ .current_dir(&feature_wt)+ .output()+ .expect("failed to run push");+ assert!(+ output.status.success(),+ "push must overwrite the ignored file, matching git: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert_eq!(+ std::fs::read_to_string(root.join("dist.txt")).unwrap(),+ "tracked"+ );+}++/// An untracked file nested in an untracked directory still gets the upfront+/// named refusal. The overlap check lists untracked files individually+/// (`-uall`); default porcelain collapses the directory to a single `dir/`+/// entry, which can never match a file path in the push range — the refusal+/// would then come from the sync backstop, without naming the file.+#[rstest]+fn test_push_dirty_target_overlap_in_untracked_dir(mut repo: TestRepo) {+ let root = repo.root_path().to_path_buf();+ let feature_wt = repo.add_worktree("feature");+ std::fs::create_dir_all(feature_wt.join("docs/api")).unwrap();+ std::fs::write(feature_wt.join("docs/api/index.md"), "tracked").unwrap();+ repo.run_git_in(&feature_wt, &["add", "docs"]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "Add docs"]);++ // The same path, untracked inside an untracked directory, in the target.+ std::fs::create_dir_all(root.join("docs/api")).unwrap();+ std::fs::write(root.join("docs/api/index.md"), "LOCAL").unwrap();++ let target_before = repo.git_output(&["rev-parse", "main"]);+ let output = repo+ .wt_command()+ .args(["step", "push", "main"])+ .current_dir(&feature_wt)+ .output()+ .expect("failed to run push");++ assert!(+ !output.status.success(),+ "an overlapping untracked file must refuse the push: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("docs/api/index.md"),+ "the refusal must name the conflicting file: {stderr}"+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ target_before,+ "the ref must not move"+ );+ assert_eq!(+ std::fs::read_to_string(root.join("docs/api/index.md")).unwrap(),+ "LOCAL"+ );+}++/// A fast-forward whose target-worktree sync fails is rolled back whole.+///+/// A locked index in the target worktree stands in for a sync failure in the+/// window after the upfront conflict check. The ref update is rolled back and+/// the command exits non-zero — the fast-forward path's version of the+/// rollback `test_merge_no_ff_sync_failure_rolls_back` proves for `--no-ff`.+#[rstest]+fn test_push_sync_failure_rolls_back(mut repo: TestRepo) {+ // The repo root is main's worktree in this fixture; its `.git` is a real+ // directory, so the index lock can be planted directly.+ let feature_wt = repo.add_feature();++ let target_before = repo.git_output(&["rev-parse", "main"]);+ let index_lock = repo.root_path().join(".git/index.lock");+ std::fs::write(&index_lock, "").unwrap();++ let output = repo+ .wt_command()+ .args(["step", "push", "main"])+ .current_dir(&feature_wt)+ .output()+ .expect("failed to run push");++ assert!(+ !output.status.success(),+ "a push whose worktree sync fails must fail whole: {}",+ String::from_utf8_lossy(&output.stderr)+ );+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ stderr.contains("rolled back"),+ "the error must say the ref change was rolled back: {stderr}"+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ target_before,+ "the ref update must be rolled back"+ );++ let _ = std::fs::remove_file(&index_lock);+}+/// A registered target worktree whose directory is gone stops both strategies.///-/// The fast-forward pushes with `receive.denyCurrentBranch=updateInstead`, whose-/// receive-pack cd's into that directory and died in git plumbing-/// (`exec 'update-index': cd to '…' failed`) with the ref untouched. `--no-ff`-/// updates the ref with plumbing of its own and skipped the sync, so it-/// succeeded over the same broken registration — one command, two answers.+/// Nothing can be synced into a missing directory — git dies trying to cd+/// into it — so `MergeContext::prepare` refuses upfront with the ref+/// untouched, naming the `git worktree prune` that clears the registration.#[rstest]fn test_push_target_worktree_missing(mut repo: TestRepo) {let main_wt = repo.add_main_worktree();diff --git a/tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_autostash.snap b/tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_stays_in_place.snapsimilarity index 77%rename from tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_autostash.snaprename to tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_stays_in_place.snapindex 5a9480019..3ce3a1a5f 100644--- a/tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_autostash.snap+++ b/tests/snapshots/integration__integration_tests__merge__merge_no_ff_dirty_target_stays_in_place.snap@@ -9,12 +9,23 @@ info:- "--no-remove"env:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test UserGIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"- GIT_CONFIG_SYSTEM: /dev/null+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: C@@ -37,6 +48,7 @@ info:WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -48,11 +60,9 @@ exit_code: 0----- stdout ---------- stderr ------[36m◎[39m [36mStashing changes in [1m_REPO_[22m...[39m[36m◎[39m [36mMerging 1 commit to [1mmain[22m @ [2m[HASH][22m (--no-ff) (no commit/squash/rebase needed)[39m[107m [0m * [33m[HASH][m Add feature[107m [0m feature.txt | 1 [32m+[m[107m [0m 1 file changed, 1 insertion(+)-[36m◎[39m [36mRestoring stashed changes in [1m_REPO_[22m...[39m[32m✓[39m [32mMerged to [1mmain[22m @ [2m[HASH][22m [90m(1 commit, 1 file, [32m+1[39m, --no-ff[39m[90m)[39m[39m[2m○[22m Worktree preserved (--no-remove)diff --git a/tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snap b/tests/snapshots/integration__integration_tests__push__push_dirty_target_carried.snapsimilarity index 76%rename from tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snaprename to tests/snapshots/integration__integration_tests__push__push_dirty_target_carried.snapindex e88c35ef1..64f33e8a8 100644--- a/tests/snapshots/integration__integration_tests__push__push_dirty_target_autostash.snap+++ b/tests/snapshots/integration__integration_tests__push__push_dirty_target_carried.snap@@ -8,12 +8,23 @@ info:- mainenv:APPDATA: "[TEST_CONFIG_HOME]"+ CLAUDE_CONFIG_DIR: "[TEST_CLAUDE_CONFIG]"CLICOLOR_FORCE: "1"COLUMNS: "500"+ GIT_ALLOW_PROTOCOL: fileGIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_AUTHOR_EMAIL: [email protected]+ GIT_AUTHOR_NAME: Test UserGIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"- GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"- GIT_CONFIG_SYSTEM: /dev/null+ GIT_COMMITTER_EMAIL: [email protected]+ GIT_COMMITTER_NAME: Test User+ GIT_CONFIG_COUNT: "2"+ GIT_CONFIG_GLOBAL: /nonexistent/wt/gitconfig+ GIT_CONFIG_KEY_0: user.useConfigOnly+ GIT_CONFIG_KEY_1: rerere.enabled+ GIT_CONFIG_SYSTEM: /nonexistent/wt/gitconfig+ GIT_CONFIG_VALUE_0: "true"+ GIT_CONFIG_VALUE_1: "false"GIT_TERMINAL_PROMPT: "0"HOME: "[TEST_HOME]"LANG: C@@ -36,6 +47,7 @@ info:WORKTRUNK_TEST_MOCK_CONFIG_DIR: "[TEST_MOCK_CONFIG]"WORKTRUNK_TEST_NUSHELL_ENV: "0"WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"+ WORKTRUNK_TEST_PARENT_SHELL: ""WORKTRUNK_TEST_POWERSHELL_ENV: "0"WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"@@ -47,10 +59,8 @@ exit_code: 0----- stdout ---------- stderr ------[36m◎[39m [36mStashing changes in [1m_REPO_[22m...[39m[36m◎[39m [36mPushing 1 commit to [1mmain[22m @ [2m[HASH][22m[39m[107m [0m * [33m[HASH][m Add feature file[107m [0m feature.txt | 1 [32m+[m[107m [0m 1 file changed, 1 insertion(+)-[36m◎[39m [36mRestoring stashed changes in [1m_REPO_[22m...[39m[32m✓[39m [32mPushed to [1mmain[22m [90m(1 commit, 1 file, [32m+1[39m[39m[90m)[39m[39m