Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(merge): Accept merge-shaped fast-forward histories (#3509)
Rene Leonhardt79be81a4bb1b
diff --git a/docs/content/merge.md b/docs/content/merge.mdindex 6b9ab1c94..19a023f5e 100644--- a/docs/content/merge.md+++ b/docs/content/merge.md@@ -50,7 +50,7 @@ Preserve commit history (no squash):{{ terminal(cmd="wt merge --no-squash") }}-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:{{ terminal(cmd="wt merge --no-ff") }}@@ -58,20 +58,24 @@ Skip committing/squashing (rebase still runs unless --no-rebase):{{ terminal(cmd="wt merge --no-commit") }}+Preserve the exact clean commit graph and tip:++{{ terminal(cmd="wt merge --no-commit --no-rebase") }}+## Pipeline`wt merge` runs these steps:1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.-3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](@/hook.md).-5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. **Post-remove + post-merge hooks** — Run in background after cleanup.-Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.+Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.## Local CI@@ -116,7 +120,7 @@ Usage: <b><span class=c>wt merge</span></b> <span class=c>[OPTIONS]</span> <spanSkip commit and squash<b><span class=c>--no-rebase</span></b>- Skip rebase (fail if not already rebased)+ Skip rebase; require the target to fast-forward to the resulting tip<b><span class=c>--no-remove</span></b>Keep worktree after mergediff --git a/plugins/worktrunk/skills/worktrunk/reference/merge.md b/plugins/worktrunk/skills/worktrunk/reference/merge.mdindex e114fb1e9..269471180 100644--- a/plugins/worktrunk/skills/worktrunk/reference/merge.md+++ b/plugins/worktrunk/skills/worktrunk/reference/merge.md@@ -41,7 +41,7 @@ Preserve commit history (no squash):$ wt merge --no-squash```-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:```bash$ wt merge --no-ff@@ -53,20 +53,26 @@ Skip committing/squashing (rebase still runs unless --no-rebase):$ wt merge --no-commit```+Preserve the exact clean commit graph and tip:++```bash+$ wt merge --no-commit --no-rebase+```+## Pipeline`wt merge` runs these steps:1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.-3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).-5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. **Post-remove + post-merge hooks** — Run in background after cleanup.-Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.+Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.## Local CI@@ -105,7 +111,7 @@ Options:Skip commit and squash--no-rebase- Skip rebase (fail if not already rebased)+ Skip rebase; require the target to fast-forward to the resulting tip--no-removeKeep worktree after mergediff --git a/skills/worktrunk/reference/merge.md b/skills/worktrunk/reference/merge.mdindex e114fb1e9..269471180 100644--- a/skills/worktrunk/reference/merge.md+++ b/skills/worktrunk/reference/merge.md@@ -41,7 +41,7 @@ Preserve commit history (no squash):$ wt merge --no-squash```-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:```bash$ wt merge --no-ff@@ -53,20 +53,26 @@ Skip committing/squashing (rebase still runs unless --no-rebase):$ wt merge --no-commit```+Preserve the exact clean commit graph and tip:++```bash+$ wt merge --no-commit --no-rebase+```+## Pipeline`wt merge` runs these steps:1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.-3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](https://worktrunk.dev/hook/).-5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. **Post-remove + post-merge hooks** — Run in background after cleanup.-Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.+Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.## Local CI@@ -105,7 +111,7 @@ Options:Skip commit and squash--no-rebase- Skip rebase (fail if not already rebased)+ Skip rebase; require the target to fast-forward to the resulting tip--no-removeKeep worktree after mergediff --git a/src/cli/mod.rs b/src/cli/mod.rsindex d33ce6a6c..6dcb1d89f 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -552,7 +552,7 @@ pub(crate) struct MergeArgs {#[arg(long, overrides_with = "no_rebase", hide = true)]pub(crate) rebase: bool,- /// Skip rebase (fail if not already rebased)+ /// Skip rebase; require the target to fast-forward to the resulting tip#[arg(long = "no-rebase", overrides_with = "rebase")]pub(crate) no_rebase: bool,@@ -1375,7 +1375,7 @@ Preserve commit history (no squash):$ wt merge --no-squash```-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:```console$ wt merge --no-ff@@ -1387,20 +1387,26 @@ Skip committing/squashing (rebase still runs unless --no-rebase):$ wt merge --no-commit```+Preserve the exact clean commit graph and tip:++```console+$ wt merge --no-commit --no-rebase+```+## Pipeline`wt merge` runs these steps:1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.-3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](@/hook.md).-5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. **Post-remove + post-merge hooks** — Run in background after cleanup.-Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.+Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.## Local CIdiff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 2fd583221..699486f5d 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -13,7 +13,6 @@ use super::context::CommandEnv;use super::flag_pair;use super::hook_plan::{ApprovedHookPlan, HookPlanBuilder, execute_planned_hook};use super::hooks::HookAnnouncer;-use super::repository_ext::RepositoryCliExt;use super::template_vars::TemplateVars;use super::worktree::{FinishAfterMergeArgs, MergeOperations, PushKind, finish_after_merge, handle_no_ff_merge,@@ -333,11 +332,22 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {super::step::RebaseResult::Rebased { .. })} else {- // --no-rebase: verify already rebased, fail if not- if !repo.is_rebased_onto(&target_branch)? {+ // --no-rebase preserves the graph produced by the commit/squash stages+ // above. Merge commits in that graph are valid as long as the target+ // can fast-forward to the final tip.+ let target_ref = format!("refs/heads/{target_branch}");+ let target_sha = repo+ .run_command(&["rev-parse", "--verify", "--end-of-options", &target_ref])?+ .trim()+ .to_string();+ let source_sha = repo+ .run_command(&["rev-parse", "--verify", "HEAD"])?+ .trim()+ .to_string();+ if !repo.is_ancestor_by_sha(&target_sha, &source_sha)? {return Err(worktrunk::git::GitError::NotRebased { target_branch }.into());}- false // Already rebased, no rebase occurred+ false // Rebase skipped; the graph produced by earlier stages remains};// Run pre-merge checks unless --no-hooks was specifieddiff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex b6a6a23de..1ad7a3f2c 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -352,7 +352,10 @@ pub fn handle_push(////// 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-/// rebase has already run, so the feature branch tree IS the correct merge result.+/// [`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@@ -380,7 +383,8 @@ pub fn handle_no_ff_merge(}// Create the merge commit using git plumbing.- // Since rebase has already run, HEAD's tree is the correct merge result.+ // The target-is-ancestor check makes HEAD's tree the correct merge result,+ // whether the source was rebased or explicitly preserved.let tree = ctx.repo.run_command(&["rev-parse", "HEAD^{tree}"])?diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rsindex 31d6fdef9..964af2ecf 100644--- a/tests/integration_tests/help.rs+++ b/tests/integration_tests/help.rs@@ -12,6 +12,7 @@#![cfg(not(windows))]use crate::common::{add_standard_env_redactions, wt_command};+use ansi_str::AnsiStr as _;use insta::Settings;use insta_cmd::assert_cmd_snapshot;use rstest::rstest;@@ -54,6 +55,29 @@ fn snapshot_help(test_name: &str, args: &[&str]) {});}+#[test]+fn test_merge_help_describes_exact_shape_no_rebase() {+ let output = wt_command()+ .args(["merge", "--help"])+ .output()+ .expect("failed to run wt merge --help");+ assert!(output.status.success());+ let stdout = String::from_utf8_lossy(&output.stdout);+ let stdout = stdout.ansi_strip();+ assert!(+ stdout.contains("Skip rebase; require the target to fast-forward to the resulting tip"),+ "missing graph-preservation contract:\n{stdout}"+ );+ assert!(+ stdout.contains("wt merge --no-commit --no-rebase"),+ "missing exact-shape example:\n{stdout}"+ );+ assert!(+ stdout.contains("explicit --no-rebase preserves the graph produced by earlier steps"),+ "missing no-ff qualification:\n{stdout}"+ );+}+// Root command (wt)#[rstest]#[case("help_root_short", "-h")]diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex 350a590dd..ffdb37d55 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -1533,6 +1533,8 @@ fn test_merge_no_commit_with_dirty_tree(mut repo: TestRepo) {// Add uncommitted changesfs::write(feature_wt.join("uncommitted.txt"), "uncommitted content").unwrap();+ let target_tip = repo.git_output(&["rev-parse", "main"]);+ let source_tip = repo.git_output(&["rev-parse", "feature"]);// Try to merge with --no-commit (should fail - dirty tree)assert_cmd_snapshot!(make_snapshot_cmd(@@ -1541,6 +1543,18 @@ fn test_merge_no_commit_with_dirty_tree(mut repo: TestRepo) {&["main", "--no-commit"],Some(&feature_wt)));++ assert_eq!(repo.git_output(&["rev-parse", "main"]), target_tip);+ assert_eq!(repo.git_output(&["rev-parse", "feature"]), source_tip);+ assert!(feature_wt.exists(), "failed merge must keep the worktree");+ assert!(+ feature_wt.join("uncommitted.txt").exists(),+ "failed merge must keep uncommitted files"+ );+ assert!(+ repo.git_output(&["stash", "list"]).is_empty(),+ "failed merge must not create a stash"+ );}#[rstest]@@ -1643,6 +1657,18 @@ fn test_merge_rebase_true_rebase(mut repo: TestRepo) {// --no-rebase tests// =============================================================================+fn add_merge_shaped_feature(repo: &mut TestRepo) -> PathBuf {+ let feature_wt =+ repo.add_worktree_with_commit("feature", "feature.txt", "feature content", "Add feature");+ let _side_wt =+ repo.add_worktree_with_commit("side", "side.txt", "side content", "Add side change");+ repo.run_git_in(+ &feature_wt,+ &["merge", "--no-ff", "side", "-m", "Merge side into feature"],+ );+ feature_wt+}+#[rstest]fn test_merge_no_rebase_when_already_rebased(merge_scenario: (TestRepo, PathBuf)) {// Feature branch is based on main (no divergence), so --no-rebase should succeed@@ -1656,6 +1682,178 @@ fn test_merge_no_rebase_when_already_rebased(merge_scenario: (TestRepo, PathBuf)));}+#[rstest]+fn test_merge_no_commit_no_rebase_preserves_merge_graph(mut repo: TestRepo) {+ let feature_wt = add_merge_shaped_feature(&mut repo);++ let source_tip = repo.git_output(&["rev-parse", "feature"]);+ let source_graph = repo.git_output(&["rev-list", "--parents", "feature"]);+ let commit_count = repo.git_output(&["rev-list", "--count", "feature"]);++ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-commit",+ "--no-rebase",+ "--no-remove",+ "--no-hooks",+ "--format=json",+ ])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "merge failed:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["committed"], false);+ assert_eq!(json["squashed"], false);+ assert_eq!(json["rebased"], false);+ assert_eq!(json["removed"], false);+ assert_eq!(repo.git_output(&["rev-parse", "main"]), source_tip);+ assert_eq!(repo.git_output(&["rev-parse", "feature"]), source_tip);+ assert_eq!(+ repo.git_output(&["rev-list", "--parents", "feature"]),+ source_graph+ );+ assert_eq!(+ repo.git_output(&["rev-list", "--count", "feature"]),+ commit_count+ );+}++#[rstest]+fn test_merge_no_commit_no_rebase_removes_merge_shaped_worktree(mut repo: TestRepo) {+ let feature_wt = add_merge_shaped_feature(&mut repo);+ let source_tip = repo.git_output(&["rev-parse", "feature"]);+ let source_graph = repo.git_output(&["rev-list", "--parents", "feature"]);++ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-commit",+ "--no-rebase",+ "--no-hooks",+ "--format=json",+ ])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "merge failed:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["removed"], true);+ assert_eq!(repo.git_output(&["rev-parse", "main"]), source_tip);+ assert_eq!(+ repo.git_output(&["rev-list", "--parents", "main"]),+ source_graph+ );+ wait_for_worktree_removed(&feature_wt);+ let feature_ref = repo+ .git_command()+ .args(["show-ref", "--verify", "--quiet", "refs/heads/feature"])+ .run()+ .unwrap();+ assert!(+ !feature_ref.status.success(),+ "removed source branch should no longer exist"+ );+}++#[rstest]+fn test_merge_shaped_no_ff_no_rebase_preserves_source_graph(mut repo: TestRepo) {+ let feature_wt = add_merge_shaped_feature(&mut repo);+ let target_tip = repo.git_output(&["rev-parse", "main"]);+ let source_tip = repo.git_output(&["rev-parse", "feature"]);+ let source_tree = repo.git_output(&["rev-parse", "feature^{tree}"]);+ let source_graph = repo.git_output(&["rev-list", "--parents", "feature"]);++ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-commit",+ "--no-rebase",+ "--no-ff",+ "--no-remove",+ "--no-hooks",+ "--format=json",+ ])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "merge failed:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let target_after = repo.git_output(&["rev-parse", "main"]);+ assert_ne!(target_after, source_tip, "--no-ff should create a commit");+ assert_eq!(+ repo.git_output(&["show", "-s", "--format=%P", "main"]),+ format!("{target_tip} {source_tip}")+ );+ assert_eq!(repo.git_output(&["rev-parse", "main^{tree}"]), source_tree);+ assert_eq!(repo.git_output(&["rev-parse", "feature"]), source_tip);+ assert_eq!(+ repo.git_output(&["rev-list", "--parents", "feature"]),+ source_graph+ );+}++#[rstest]+fn test_merge_shaped_default_flags_still_squash(mut repo: TestRepo) {+ let feature_wt = add_merge_shaped_feature(&mut repo);+ let original_source_tip = repo.git_output(&["rev-parse", "feature"]);++ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-remove",+ "--no-hooks",+ "--format=json",+ ])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "merge failed:\n{}",+ String::from_utf8_lossy(&output.stderr)+ );+ let json: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();+ assert_eq!(json["squashed"], true);+ let rewritten_source_tip = repo.git_output(&["rev-parse", "feature"]);+ assert_ne!(rewritten_source_tip, original_source_tip);+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ rewritten_source_tip+ );+ assert_eq!(+ repo.git_output(&["show", "-s", "--format=%P", "main"])+ .split_whitespace()+ .count(),+ 1,+ "default squash result should remain linear"+ );+}+#[rstest]fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {// Create a feature worktree with a commit@@ -1670,6 +1868,8 @@ fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {fs::write(repo.root_path().join("main-update.txt"), "main content").unwrap();repo.run_git(&["add", "main-update.txt"]);repo.run_git(&["commit", "-m", "Update main"]);+ let target_tip = repo.git_output(&["rev-parse", "main"]);+ let source_tip = repo.git_output(&["rev-parse", "not-rebased-test"]);// --no-rebase should fail because feature is not rebased onto mainassert_cmd_snapshot!(make_snapshot_cmd(@@ -1678,6 +1878,204 @@ fn test_merge_no_rebase_when_not_rebased(mut repo: TestRepo) {&["main", "--no-rebase"],Some(&feature_wt)));++ assert_eq!(repo.git_output(&["rev-parse", "main"]), target_tip);+ assert_eq!(+ repo.git_output(&["rev-parse", "not-rebased-test"]),+ source_tip+ );+ 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"+ );+}++#[rstest]+fn test_merge_no_commit_no_rebase_rejects_unrelated_history(repo: TestRepo) {+ let orphan_wt = repo.root_path().parent().unwrap().join("repo.orphan-merge");+ let add = repo+ .git_command()+ .args([+ "worktree",+ "add",+ "--orphan",+ "-b",+ "orphan-merge",+ orphan_wt.to_str().unwrap(),+ ])+ .run()+ .unwrap();+ assert!(+ add.status.success(),+ "git worktree add --orphan failed: {}",+ String::from_utf8_lossy(&add.stderr)+ );+ fs::write(orphan_wt.join("orphan.txt"), "unrelated content").unwrap();+ repo.run_git_in(&orphan_wt, &["add", "orphan.txt"]);+ repo.run_git_in(&orphan_wt, &["commit", "-m", "Create unrelated history"]);++ let target_tip = repo.git_output(&["rev-parse", "main"]);+ let source_tip = repo.git_output(&["rev-parse", "orphan-merge"]);+ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-commit",+ "--no-rebase",+ "--no-remove",+ "--no-hooks",+ ])+ .current_dir(&orphan_wt)+ .output()+ .unwrap();++ assert!(!output.status.success(), "unrelated history must fail");+ assert_eq!(repo.git_output(&["rev-parse", "main"]), target_tip);+ assert_eq!(repo.git_output(&["rev-parse", "orphan-merge"]), source_tip);+ 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"+ );+}++#[rstest]+fn test_merge_target_diverges_during_pre_merge_hook(mut repo: TestRepo) {+ let feature_wt = repo.add_worktree_with_commit(+ "feature-race",+ "feature.txt",+ "feature content",+ "Add feature",+ );+ let post_merge_marker = repo.root_path().join("post-merge-race-ran");+ fs::create_dir_all(feature_wt.join(".config")).unwrap();+ fs::write(+ feature_wt.join(".config/wt.toml"),+ r#"pre-merge = "git -C {{ target_worktree_path }} commit --allow-empty -m concurrent-main"+post-merge = "touch {{ repo_path }}/post-merge-race-ran"+"#,+ )+ .unwrap();+ repo.run_git_in(&feature_wt, &["add", ".config/wt.toml"]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "Add merge race hooks"]);++ let target_before = repo.git_output(&["rev-parse", "main"]);+ let source_tip = repo.git_output(&["rev-parse", "feature-race"]);+ let output = repo+ .wt_command()+ .args([+ "merge",+ "main",+ "--no-rebase",+ "--no-squash",+ "--no-remove",+ "--yes",+ ])+ .current_dir(&feature_wt)+ .output()+ .unwrap();++ assert!(+ !output.status.success(),+ "target divergence introduced by pre-merge must fail"+ );+ let target_after = repo.git_output(&["rev-parse", "main"]);+ assert_ne!(target_after, target_before);+ assert_eq!(+ repo.git_output(&["show", "-s", "--format=%s", "main"]),+ "concurrent-main"+ );+ assert_eq!(repo.git_output(&["rev-parse", "feature-race"]), source_tip);+ 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"+ );+ assert!(+ !post_merge_marker.exists(),+ "post-merge must not run after final ancestry rejection"+ );+}++#[cfg(unix)]+#[rstest]+fn test_merge_target_diverges_during_receive_restores_autostash(mut repo: TestRepo) {+ use std::os::unix::fs::PermissionsExt as _;++ 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"]);+ let hooks_dir = PathBuf::from(git_common_dir).join("hooks");+ fs::create_dir_all(&hooks_dir).unwrap();+ let hook_path = hooks_dir.join("pre-receive");+ fs::write(+ &hook_path,+ 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"+"#,+ )+ .unwrap();+ fs::set_permissions(&hook_path, fs::Permissions::from_mode(0o755)).unwrap();++ 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"+ );}#[rstest]diff --git a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap b/tests/snapshots/integration__integration_tests__help__help_md_merge.snapindex 5efaef565..e98c9ed84 100644--- a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap+++ b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap@@ -52,7 +52,7 @@ Options:Skip commit and squash--no-rebase- Skip rebase (fail if not already rebased)+ Skip rebase; require the target to fast-forward to the resulting tip--no-removeKeep worktree after merge@@ -140,7 +140,7 @@ Preserve commit history (no squash):$ wt merge --no-squash```-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:```bash$ wt merge --no-ff@@ -152,20 +152,26 @@ Skip committing/squashing (rebase still runs unless --no-rebase):$ wt merge --no-commit```+Preserve the exact clean commit graph and tip:++```bash+$ wt merge --no-commit --no-rebase+```+## Pipeline`wt merge` runs these steps:1. **Commit** — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With `--no-squash`, this is the only commit step.2. **Squash** — Combines all commits since target into one (like GitHub's "Squash and merge"). Use `--stage` to control what gets staged: `all` (default), `tracked`, or `none`. A backup ref is saved to `refs/wt-backup/<branch>`. With `--no-squash`, individual commits are preserved.-3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. **Rebase** — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With `--no-rebase`, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. **Pre-merge hooks** — Hooks run after rebase, before merge. Failures abort. See [`wt hook`](@/hook.md).-5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. **Merge** — Fast-forward merge to the target branch. With `--no-ff`, a merge commit is created instead — semi-linear history after the default rebase, while explicit `--no-rebase` preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. **Pre-remove hooks** — Hooks run before removing worktree. Failures abort.7. **Cleanup** — Removes the worktree and branch. Use `--no-remove` to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. **Post-remove + post-merge hooks** — Run in background after cleanup.-Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.+Use `--no-commit` to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless `--no-rebase` is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with `wt step commit`. Requires a clean working tree.## Local CIdiff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snapindex e66beab69..42884494d 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap@@ -52,7 +52,7 @@ Usage: [1m[36mwt merge[0m [36m[OPTIONS][0m [36m[TARGET][0mSkip commit and squash[1m[36m--no-rebase[0m- Skip rebase (fail if not already rebased)+ Skip rebase; require the target to fast-forward to the resulting tip[1m[36m--no-remove[0mKeep worktree after merge@@ -130,7 +130,7 @@ Preserve commit history (no squash):[107m [0m [2m[0m[2m[34mwt[0m[2m merge [0m[2m[36m--no-squash[0m-Create a merge commit — semi-linear history:+Create a merge commit — rebased semi-linear history by default:[107m [0m [2m[0m[2m[34mwt[0m[2m merge [0m[2m[36m--no-ff[0m@@ -138,20 +138,24 @@ Skip committing/squashing (rebase still runs unless --no-rebase):[107m [0m [2m[0m[2m[34mwt[0m[2m merge [0m[2m[36m--no-commit[0m+Preserve the exact clean commit graph and tip:++[107m [0m [2m[0m[2m[34mwt[0m[2m merge [0m[2m[36m--no-commit[0m[2m [0m[2m[36m--no-rebase[0m+[1m[32mPipeline[0m[2mwt merge[0m runs these steps:1. [1mCommit[0m — Pre-commit hooks run, then uncommitted changes are committed. Post-commit hooks run in background. Skipped when squashing (the default) — changes are staged during the squash step instead. With [2m--no-squash[0m, this is the only commit step.2. [1mSquash[0m — Combines all commits since target into one (like GitHub's "Squash and merge"). Use [2m--stage[0m to control what gets staged: [2mall[0m (default), [2mtracked[0m, or [2mnone[0m. A backup ref is saved to [2mrefs/wt-backup/<branch>[0m. With [2m--no-squash[0m, individual commits are preserved.-3. [1mRebase[0m — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately.+3. [1mRebase[0m — Rebases onto target if behind. Skipped if already up-to-date. Conflicts abort immediately. With [2m--no-rebase[0m, the graph produced by earlier commit/squash steps is preserved and the target must be able to fast-forward to its tip.4. [1mPre-merge hooks[0m — Hooks run after rebase, before merge. Failures abort. See [2mwt hook[0m.-5. [1mMerge[0m — Fast-forward merge to the target branch. With [2m--no-ff[0m, a merge commit is created instead — semi-linear history with rebased commits plus a merge commit. Non-fast-forward merges are rejected.+5. [1mMerge[0m — Fast-forward merge to the target branch. With [2m--no-ff[0m, a merge commit is created instead — semi-linear history after the default rebase, while explicit [2m--no-rebase[0m preserves the graph produced by earlier steps before adding the merge commit. Non-fast-forward merges are rejected.6. [1mPre-remove hooks[0m — Hooks run before removing worktree. Failures abort.7. [1mCleanup[0m — Removes the worktree and branch. Use [2m--no-remove[0m to keep the worktree. When already on the target branch or in the primary worktree, the worktree is preserved.8. [1mPost-remove + post-merge hooks[0m — Run in background after cleanup.-Use [2m--no-commit[0m to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless [2m--no-rebase[0m is passed. Useful after preparing commits manually with [2mwt step commit[0m. Requires a clean working tree.+Use [2m--no-commit[0m to skip committing uncommitted changes and squashing; rebase still runs by default and can rewrite commits unless [2m--no-rebase[0m is passed. Combining both flags preserves the exact source graph and requires the target to be its ancestor. Useful after preparing commits manually with [2mwt step commit[0m. Requires a clean working tree.[1m[32mLocal CI[0mdiff --git a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap b/tests/snapshots/integration__integration_tests__help__help_merge_short.snapindex c8b1c953c..88cf959c6 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_short.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_short.snap@@ -42,7 +42,7 @@ Usage: [1m[36mwt merge[0m [36m[OPTIONS][0m [36m[TARGET][0m[1m[32mOptions:[0m[1m[36m--no-squash[0m Skip commit squashing[1m[36m--no-commit[0m Skip commit and squash- [1m[36m--no-rebase[0m Skip rebase (fail if not already rebased)+ [1m[36m--no-rebase[0m Skip rebase; require the target to fast-forward to the resulting tip[1m[36m--no-remove[0m Keep worktree after merge[1m[36m--no-ff[0m Create a merge commit (no fast-forward)[1m[36m--stage[0m[36m [0m[36m<STAGE>[0m What to stage before committing [default: all] [possible values: all, tracked, none]