Skip to content

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

fix: replace reset --hard with safe read-tree for worktree sync (#1623)

worktrunk-bot3de3f6e180b3
diff --git a/CLAUDE.md b/CLAUDE.md
index bc5a162dc..2790c76c9 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -159,6 +159,7 @@ Never risk data loss without explicit user consent. A failed command that preser
- **Prefer failure over silent data loss** — If an operation might destroy untracked files, uncommitted changes, or user data, fail with an error
- **Explicit consent for destructive operations** — Operations that force-remove data (like `--force` on remove) require the user to explicitly request that behavior
- **No implicit destructive side effects** — A command must not silently delete, remove, or overwrite files/directories as a side effect of an unrelated operation. If cleanup is needed, make it a separate explicit action the user chooses to take
+- **Favor retaining data and failing on race conditions** — When there's a gap between checking safety and performing an operation, choose the variant that fails rather than silently discards work. Example: use `git reset --keep` (fails if tracked files were modified) over `git reset --hard` (silently overwrites). Similarly, prefer `git checkout --merge` over `git checkout --force`. If a safer variant doesn't exist, document the risk inline
- **Time-of-check vs time-of-use** — Be conservative when there's a gap between checking safety and performing an operation. Example: `wt merge` verifies the worktree is clean before rebasing, but files could be added before cleanup — don't force-remove during cleanup
For the full inventory of what Worktrunk creates and deletes, see the FAQ: [What files does Worktrunk create?](docs/content/faq.md#what-files-does-worktrunk-create) and [What can Worktrunk delete?](docs/content/faq.md#what-can-worktrunk-delete). New code that changes this surface area should be reviewed against these sections.
diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rs
index 1af5b0342..fb5c935d6 100644
--- a/src/commands/worktree/push.rs
+++ b/src/commands/worktree/push.rs
@@ -299,8 +299,13 @@ pub fn handle_push(
/// rebase has already run, so the feature branch tree IS the correct merge result.
///
/// If the target branch has a checked-out worktree, its working tree is synced
-/// via `reset --hard` after the ref update. The stash guard pattern from
-/// `handle_push` is reused for dirty target worktrees.
+/// 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.
pub fn handle_no_ff_merge(
target: Option<&str>,
operations: Option<MergeOperations>,
@@ -359,12 +364,19 @@ pub fn handle_no_ff_merge(
})?;
// 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
&& wt_path.exists()
{
let target_wt = ctx.repo.worktree_at(wt_path);
- if let Err(e) = target_wt.run_command(&["reset", "--hard", "HEAD"]) {
+ if let Err(e) =
+ target_wt.run_command(&["read-tree", "-m", "-u", &ctx.target_tip, &merge_sha])
+ {
eprintln!(
"{}",
warning_message(cformat!(
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 1c12836d5..7542bc58a 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2309,7 +2309,7 @@ fn test_merge_no_ff_diverged_no_rebase(mut repo_with_main_worktree: TestRepo) {
));
}
-/// --no-ff merge succeeds and syncs target worktree via reset --hard.
+/// --no-ff merge succeeds and syncs target worktree via read-tree.
///
/// Verifies that after a --no-ff merge, the target worktree's working tree
/// reflects the merge commit (not the old HEAD).
@@ -2340,10 +2340,10 @@ fn test_merge_no_ff_syncs_target_worktree(mut repo_with_main_worktree: TestRepo)
String::from_utf8_lossy(&output.stderr)
);
- // Verify the feature file exists in the main worktree (reset --hard synced it)
+ // Verify the feature file exists in the main worktree (read-tree synced it)
assert!(
main_wt.join("feature.txt").exists(),
- "Target worktree should contain the merged file after reset --hard"
+ "Target worktree should contain the merged file after read-tree"
);
// Verify the merge commit is on main
@@ -2363,7 +2363,7 @@ fn test_merge_no_ff_syncs_target_worktree(mut repo_with_main_worktree: TestRepo)
.to_string();
assert_eq!(
main_tip, wt_head,
- "Target worktree HEAD should match main after reset --hard"
+ "Target worktree HEAD should match main after read-tree"
);
}
@@ -2467,9 +2467,63 @@ 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.
+///
+/// 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.
+#[rstest]
+fn test_merge_no_ff_sync_failure_warns(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
+ let index_lock = main_wt.join(".git/index.lock");
+ fs::write(&index_lock, "").unwrap();
+
+ let output = repo
+ .wt_command()
+ .args(["merge", "main", "--no-ff", "--no-remove"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+
+ // Merge should still succeed (ref was updated before sync)
+ assert!(
+ output.status.success(),
+ "merge should succeed despite sync failure: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // Should emit a warning about the sync failure
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ stderr.contains("Failed to sync target worktree"),
+ "should warn about sync failure: {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();
+ assert_eq!(
+ parents.len(),
+ 2,
+ "Should create merge commit despite sync failure"
+ );
+
+ // Clean up lock so test teardown doesn't fail
+ let _ = fs::remove_file(&index_lock);
+}
+
/// --no-ff merge when the target branch has no checked-out worktree.
///
-/// The merge should succeed without attempting reset --hard (no worktree to sync).
+/// The merge should succeed without attempting read-tree (no worktree to sync).
#[rstest]
fn test_merge_no_ff_target_without_worktree(repo: TestRepo) {
// Move primary off main so main has no worktree