Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(merge): measure squash/rebase against the target's upstream, not a stale local ref (#3549)
Maximilian Roos9ecd7945e078
diff --git a/docs/content/merge.md b/docs/content/merge.mdindex 19a023f5e..8de43cca0 100644--- a/docs/content/merge.md+++ b/docs/content/merge.md@@ -77,6 +77,8 @@ Preserve the exact clean commit graph and tip: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.+`wt merge` targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's `main` left behind `origin/main` — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. `wt step squash` and `wt step rebase` measure the same way. A local target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+## Local CIFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.diff --git a/plugins/worktrunk/skills/worktrunk/reference/merge.md b/plugins/worktrunk/skills/worktrunk/reference/merge.mdindex 269471180..cba3b8754 100644--- a/plugins/worktrunk/skills/worktrunk/reference/merge.md+++ b/plugins/worktrunk/skills/worktrunk/reference/merge.md@@ -74,6 +74,8 @@ $ wt merge --no-commit --no-rebaseUse `--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.+`wt merge` targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's `main` left behind `origin/main` — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. `wt step squash` and `wt step rebase` measure the same way. A local target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+## Local CIFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.diff --git a/skills/worktrunk/reference/merge.md b/skills/worktrunk/reference/merge.mdindex 269471180..cba3b8754 100644--- a/skills/worktrunk/reference/merge.md+++ b/skills/worktrunk/reference/merge.md@@ -74,6 +74,8 @@ $ wt merge --no-commit --no-rebaseUse `--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.+`wt merge` targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's `main` left behind `origin/main` — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. `wt step squash` and `wt step rebase` measure the same way. A local target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+## Local CIFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex 2323ee272..34c49821a 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -1408,6 +1408,8 @@ $ wt merge --no-commit --no-rebaseUse `--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.+`wt merge` targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's `main` left behind `origin/main` — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. `wt step squash` and `wt step rebase` measure the same way. A local target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+## Local CIFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 699486f5d..7ae5026b9 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -1,6 +1,7 @@use std::path::Path;use anyhow::Context;+use color_print::cformat;use worktrunk::HookType;use worktrunk::config::{MergeConfig, UserConfig};use worktrunk::git::Repository;@@ -204,6 +205,51 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// Get and validate target branch (must be a branch since we're updating it)let target_branch = repo.require_target_branch(target)?;++ // #3519: when the branch is based past the local target into the target's+ // upstream, the rewrite steps measure against the upstream (see+ // `span_upstream`) and the final fast-forward carries the local target+ // through the upstream commits by their real SHAs. That fast-forward exists+ // only while the local target is strictly behind its upstream; a target+ // that has *diverged* — its own commits AND behind — can never fast-forward+ // to this branch, so refuse up front with the real reason rather than+ // failing late in the push step. Local-only check — no fetch.+ if let Some(upstream) = repo.span_upstream(&target_branch)? {+ let target_sha = repo+ .run_command(&[+ "rev-parse",+ "--verify",+ "--end-of-options",+ &format!("refs/heads/{target_branch}"),+ ])?+ .trim()+ .to_string();+ let upstream_sha = repo+ .run_command(&["rev-parse", "--verify", "--end-of-options", &upstream])?+ .trim()+ .to_string();+ if repo.is_ancestor_by_sha(&target_sha, &upstream_sha)? {+ let carried = repo.count_commits(&target_branch, &upstream)?;+ let (commit_text, pronoun) = if carried == 1 {+ ("commit", "it")+ } else {+ ("commits", "them")+ };+ eprintln!(+ "{}",+ info_message(cformat!(+ "Local <bold>{target_branch}</> is {carried} {commit_text} behind <bold>{upstream}</>; the merge fast-forwards through {pronoun}"+ ))+ );+ } else {+ return Err(worktrunk::git::GitError::MergeTargetDivergedFromUpstream {+ target_branch: target_branch.clone(),+ upstream,+ }+ .into());+ }+ }+// Worktree for target is optional: if present we use it for safety checks and as destination.let target_worktree_path = repo.worktree_for_branch(&target_branch)?;// Where `post-merge` / `post-remove` / `post-switch` run: the targetdiff --git a/src/commands/step/rebase.rs b/src/commands/step/rebase.rsindex a74f212b3..7ec3e1179 100644--- a/src/commands/step/rebase.rs+++ b/src/commands/step/rebase.rs@@ -21,6 +21,13 @@ pub fn handle_rebase(target: Option<&str>) -> anyhow::Result<RebaseResult> {// Get and validate target ref (any commit-ish for rebase)let integration_target = repo.require_target_ref(target)?;+ // #3519: when the branch's history extends past the local target into the+ // target's upstream, rebase onto the upstream instead — replaying the span+ // onto the stale local ref would duplicate commits the upstream already+ // contains under new SHAs.+ let integration_target = repo+ .span_upstream(&integration_target)?+ .unwrap_or(integration_target);// Check if already up-to-date (linear extension of target, no merge commits)if repo.is_rebased_onto(&integration_target)? {diff --git a/src/commands/step/squash.rs b/src/commands/step/squash.rsindex acaf8549d..fc4cb04e6 100644--- a/src/commands/step/squash.rs+++ b/src/commands/step/squash.rs@@ -139,6 +139,12 @@ pub fn handle_squash(// Get and validate target ref (any commit-ish for merge-base calculation)let integration_target = repo.require_target_ref(target)?;+ // #3519: when the branch's history extends past the local target into the+ // target's upstream, measure the squash against the upstream — so commits+ // already published there are never folded into the squash commit.+ let span_target = repo+ .span_upstream(&integration_target)?+ .unwrap_or_else(|| integration_target.clone());let template_vars = TemplateVars::new().with_target(&integration_target);// Auto-stage changes before running pre-commit hooks so both beta and merge paths behave identically@@ -169,7 +175,7 @@ pub fn handle_squash(// Get merge base with target branch (required for squash)let merge_base = repo- .merge_base("HEAD", &integration_target)?+ .merge_base("HEAD", &span_target)?.context("Cannot squash: no common ancestor with target branch")?;// Count commits since merge base@@ -182,7 +188,7 @@ pub fn handle_squash(// Handle different scenariosif commit_count == 0 && !has_staged {// No commits and no staged changes - nothing to squash- return Ok(SquashResult::NoCommitsAhead(integration_target));+ return Ok(SquashResult::NoCommitsAhead(span_target));}if commit_count == 1 && !has_staged {@@ -251,7 +257,7 @@ pub fn handle_squash(// Create safety backup before potentially destructive reset if there are working tree changesif has_staged {- let backup_message = format!("{} → {} (squash)", current_branch, integration_target);+ let backup_message = format!("{} → {} (squash)", current_branch, span_target);let sha = wt.create_safety_backup(&backup_message)?;eprintln!("{}", hint_message(format!("Backup created @ {sha}")));}@@ -275,7 +281,7 @@ pub fn handle_squash(.unwrap_or("repo");let commit_message = crate::llm::generate_squash_message(- &integration_target,+ &span_target,&merge_base,&commit_details,¤t_branch,@@ -363,12 +369,16 @@ fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Reslet commit_config = config.commit_generation(project_id.as_deref());let integration_target = repo.require_target_ref(target)?;+ // #3519: preview against the same upstream-aware span the real squash uses.+ let span_target = repo+ .span_upstream(&integration_target)?+ .unwrap_or(integration_target);let wt = repo.current_worktree();let current_branch = wt.branch()?.unwrap_or_else(|| "HEAD".to_string());let merge_base = repo- .merge_base("HEAD", &integration_target)?+ .merge_base("HEAD", &span_target)?.context("Cannot generate squash message: no common ancestor with target branch")?;let range = format!("{}..HEAD", merge_base);@@ -385,7 +395,7 @@ fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Reslet project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;let prompt = crate::llm::build_squash_prompt(- &integration_target,+ &span_target,&merge_base,&commit_details,¤t_branch,@@ -398,7 +408,7 @@ fn preview_squash(target: Option<&str>, dry_run: bool, yes: bool) -> anyhow::Resreturn Ok(());}let message = crate::llm::generate_squash_message(- &integration_target,+ &span_target,&merge_base,&commit_details,¤t_branch,diff --git a/src/git/error.rs b/src/git/error.rsindex cdef26301..3a4e42e39 100644--- a/src/git/error.rs+++ b/src/git/error.rs@@ -531,6 +531,16 @@ pub enum GitError {target_branch: String,error: String,},+ /// `wt merge` requires the local target ref to fast-forward to the merge+ /// result. When the target has both fallen behind its upstream and grown+ /// its own commits — diverged — while the branch is based past it on the+ /// upstream side, no fast-forward exists in any mode: the target's own+ /// commits first need reconciling with the upstream (#3519). Detected+ /// locally, with no fetch, before any rewrite or approval prompt.+ MergeTargetDivergedFromUpstream {+ target_branch: String,+ upstream: String,+ },// Validation/other errorsNotInteractive,@@ -745,6 +755,13 @@ impl GitError {cformat!("Can't push to local <bold>{target_branch}</> branch")}+ GitError::MergeTargetDivergedFromUpstream {+ target_branch,+ upstream,+ } => cformat!(+ "Local <bold>{target_branch}</> has diverged from <bold>{upstream}</> — can't fast-forward to a branch based on <bold>{upstream}</>"+ ),+GitError::NotInteractive => {"Cannot prompt for approval in non-interactive environment".to_string()}@@ -1210,6 +1227,21 @@ impl GitError {write!(f, "{}", format_error_block(error_message(&title), error))}+ GitError::MergeTargetDivergedFromUpstream {+ target_branch,+ upstream,+ } => {+ let title = self.title();+ write!(+ f,+ "{}\n{}",+ error_message(&title),+ hint_message(cformat!(+ "Reconcile <underline>{target_branch}</> with <underline>{upstream}</> (rebase or merge its local commits), or specify a different target"+ ))+ )+ }+GitError::NotInteractive => {let title = self.title();let approvals_cmd = suggest_command("config", &["approvals", "add"], &[]);diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex df1501c03..3bce7c92d 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -727,6 +727,47 @@ impl Repository {self.rev_parse_commit(r)}+ /// The target's upstream, when the current branch's history extends past+ /// the local `target_branch` ref into it — the #3519 stale-local-target+ /// topology.+ ///+ /// The rewrite steps (`wt step squash`, `wt step rebase`, and `wt merge`+ /// through them) measure "the branch's own commits" as+ /// `merge-base(target, HEAD)..HEAD`. When the local target ref lags its+ /// upstream (e.g. the primary checkout's `main` left behind `origin/main`)+ /// and the branch was built on the newer upstream tip, that span sweeps in+ /// commits the upstream already contains — folding (squash) or replaying+ /// (rebase) them would duplicate published history under new SHAs. Callers+ /// measure against the returned upstream instead, which keeps the span to+ /// the branch's own commits; `wt merge`'s final fast-forward then carries+ /// the local target through the upstream commits by their real SHAs.+ ///+ /// Detected locally, with no fetch (worktrunk is local-first): returns+ /// `Some(upstream)` (short name, e.g. `origin/main`) when the target branch+ /// has a configured upstream and `merge-base(HEAD, upstream)` is not an+ /// ancestor of the local `target` ref — i.e. the local-target span would+ /// reach commits the upstream already has. `None` — measure against the+ /// local target as usual — for a legitimately-diverged local target whose+ /// span holds only the branch's own commits (the fork point is still an+ /// ancestor of the local target), an orphan branch with no shared history,+ /// a non-branch target (an explicit `origin/main` has no upstream of its+ /// own), or a target with no upstream at all.+ pub fn span_upstream(&self, target_branch: &str) -> anyhow::Result<Option<String>> {+ // `upstream()` already excludes a `[gone]` upstream, so a `Some` value+ // is a live remote-tracking ref that `merge_base` resolves locally — no+ // fetch, and no separate existence check.+ let Some(upstream) = self.branch(target_branch).upstream()? else {+ return Ok(None);+ };+ let target_sha = self.resolve_to_commit_sha(target_branch)?;+ match self.merge_base("HEAD", &upstream)? {+ Some(fork_point) if !self.is_ancestor_by_sha(&fork_point, &target_sha)? => {+ Ok(Some(upstream))+ }+ _ => Ok(None),+ }+ }+/// Check if a branch is integrated into a target.////// Combines [`compute_integration_lazy()`] and [`check_integration()`], anddiff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rsindex ffdb37d55..c8fe11b44 100644--- a/tests/integration_tests/merge.rs+++ b/tests/integration_tests/merge.rs@@ -4400,6 +4400,291 @@ fn test_merge_removes_branch_when_local_main_diverged_from_upstream();}+/// Set up the #3519 stale-local-default topology: origin/main advanced by two+/// commits (stand-ins for already-merged PRs) that the primary has fetched but+/// not fast-forwarded into its local main.+fn setup_stale_local_main(repo: &TestRepo) {+ let remote_path = repo.remote_path().unwrap().to_path_buf();+ let github_sim = repo.home_path().join("github-sim");+ repo.run_git_in(+ repo.home_path(),+ &["clone", remote_path.to_str().unwrap(), "github-sim"],+ );+ for (file, msg) in [+ ("upstream-1.txt", "Upstream PR 1 (already merged)"),+ ("upstream-2.txt", "Upstream PR 2 (already merged)"),+ ] {+ fs::write(github_sim.join(file), "upstream").unwrap();+ repo.run_git_in(&github_sim, &["add", file]);+ repo.run_git_in(&github_sim, &["commit", "-m", msg]);+ }+ repo.run_git_in(&github_sim, &["push", "origin", "main"]);++ // Fetch so origin/main is known locally, but leave local main stale —+ // behind origin/main by the two upstream commits.+ repo.run_git(&["fetch", "origin"]);+ assert!(+ !repo+ .git_command()+ .args(["merge-base", "--is-ancestor", "origin/main", "main"])+ .run()+ .unwrap()+ .status+ .success(),+ "setup: local main should be behind origin/main"+ );+}++/// Add a `feature` worktree branched from `base`, with commits for the given+/// (file, message) pairs.+fn add_feature_worktree(+ repo: &TestRepo,+ base: &str,+ commits: &[(&str, &str)],+) -> std::path::PathBuf {+ let feature_wt = repo.root_path().parent().unwrap().join("repo.feature");+ repo.run_git(&[+ "worktree",+ "add",+ "-b",+ "feature",+ feature_wt.to_str().unwrap(),+ base,+ ]);+ for (file, msg) in commits {+ fs::write(feature_wt.join(file), "feature").unwrap();+ repo.run_git_in(&feature_wt, &["add", file]);+ repo.run_git_in(&feature_wt, &["commit", "-m", msg]);+ }+ feature_wt+}++/// #3519: `wt merge` from a branch based on origin/main, with the primary's+/// local main left behind it, measures the squash against the *upstream* — so+/// only the branch's own commits fold — and the final fast-forward carries+/// local main through the upstream commits by their real SHAs.+///+/// Contrast with `test_merge_removes_branch_when_local_main_diverged_from_upstream`:+/// there the feature forks from the *shared base*, so the span is only the+/// feature's own commit and the merge proceeds against the local ref unchanged.+#[rstest]+fn test_merge_carries_stale_local_main_through_upstream(#[from(repo_with_remote)] repo: TestRepo) {+ setup_stale_local_main(&repo);+ let upstream_tip = repo.git_output(&["rev-parse", "origin/main"]);+ // Two feature commits so the squash step actually rewrites (one commit+ // takes the AlreadySingleCommit early-out).+ let feature_wt = add_feature_worktree(+ &repo,+ "origin/main",+ &[+ ("feature-1.txt", "feature commit one"),+ ("feature-2.txt", "feature commit two"),+ ],+ );++ let output = repo+ .wt_command()+ .args(["merge", "main", "--yes", "--no-hooks", "--no-remove"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "merge must carry a stale local main through its upstream\nstderr:\n{stderr}",+ );+ assert!(+ stderr.contains("2 commits behind"),+ "merge should announce the carry\nstderr:\n{stderr}",+ );++ // The squash folded only the branch's own commits: the merged tip sits+ // directly on the origin/main tip and its message names no upstream PR.+ assert_eq!(+ repo.git_output(&["rev-parse", "main^"]),+ upstream_tip,+ "squash commit must sit on the origin/main tip",+ );+ let tip_message = repo.git_output(&["log", "-1", "--format=%B", "main"]);+ assert!(+ tip_message.contains("feature commit one") && !tip_message.contains("Upstream PR"),+ "squash must fold only the branch's own commits\nmessage:\n{tip_message}",+ );+ // The upstream commits arrived by their real SHAs — main descends from+ // origin/main instead of duplicating its content.+ assert!(+ repo.git_command()+ .args(["merge-base", "--is-ancestor", "origin/main", "main"])+ .run()+ .unwrap()+ .status+ .success(),+ "origin/main must be an ancestor of the merged main",+ );+}++/// #3519 (standalone step): `wt step squash` measures against the target's+/// upstream when the local target ref is stale, folding only the branch's own+/// commits — and never touches the target ref at all.+#[rstest]+fn test_step_squash_measures_against_upstream_when_local_main_stale(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ setup_stale_local_main(&repo);+ let stale_main = repo.git_output(&["rev-parse", "main"]);+ let upstream_tip = repo.git_output(&["rev-parse", "origin/main"]);+ let feature_wt = add_feature_worktree(+ &repo,+ "origin/main",+ &[+ ("feature-1.txt", "feature commit one"),+ ("feature-2.txt", "feature commit two"),+ ],+ );++ let output = repo+ .wt_command()+ .args(["step", "squash", "main", "--yes", "--no-hooks"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "step squash must succeed against the upstream span\nstderr:\n{stderr}",+ );++ // Only the branch's own commits folded: the squash sits on the origin/main+ // tip, and no upstream commit was swept into it.+ assert_eq!(+ repo.git_output(&["rev-parse", "feature^"]),+ upstream_tip,+ "squash commit must sit on the origin/main tip",+ );+ let tip_message = repo.git_output(&["log", "-1", "--format=%B", "feature"]);+ assert!(+ tip_message.contains("feature commit two") && !tip_message.contains("Upstream PR"),+ "squash must fold only the branch's own commits\nmessage:\n{tip_message}",+ );+ // A standalone squash rewrites the branch only — the target ref is not its+ // business.+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ stale_main,+ "step squash must never move the target ref",+ );+}++/// #3519 (standalone step): `wt step rebase` with a stale local target rebases+/// onto the target's *upstream*, replaying only the branch's own commits.+/// Rebasing onto the stale local ref would replay the upstream commits too,+/// duplicating them under new SHAs.+#[rstest]+fn test_step_rebase_targets_upstream_when_local_main_stale(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ setup_stale_local_main(&repo);+ let stale_main = repo.git_output(&["rev-parse", "main"]);+ // A branch forked from the *old* local main tip that then merged+ // origin/main — non-linear history whose local-main span contains the+ // upstream commits, so the rebase step actually rewrites.+ let feature_wt = add_feature_worktree(+ &repo,+ "main",+ &[("feature.txt", "the one real feature commit")],+ );+ repo.run_git_in(&feature_wt, &["merge", "--no-edit", "origin/main"]);++ let output = repo+ .wt_command()+ .args(["step", "rebase", "main"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ output.status.success(),+ "step rebase must succeed onto the upstream\nstderr:\n{stderr}",+ );+ assert!(+ stderr.contains("origin/main"),+ "rebase should name the upstream it targeted\nstderr:\n{stderr}",+ );++ // The upstream commits stay by their real SHAs (origin/main is an+ // ancestor), the merge commit is linearized away, and the local target ref+ // is untouched.+ assert!(+ repo.git_command()+ .args(["merge-base", "--is-ancestor", "origin/main", "feature"])+ .run()+ .unwrap()+ .status+ .success(),+ "origin/main must be an ancestor of the rebased branch",+ );+ assert_eq!(+ repo.git_output(&["rev-list", "--merges", "--count", "feature"]),+ "0",+ "rebase must linearize the branch",+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ stale_main,+ "step rebase must never move the target ref",+ );+}++/// #3519: a local target that has *diverged* from its upstream — its own+/// commits and behind — can never fast-forward to a branch based on the+/// upstream. The merge refuses up front, mutating nothing.+#[rstest]+fn test_merge_refuses_diverged_target_when_branch_based_on_upstream(+ #[from(repo_with_remote)] repo: TestRepo,+) {+ setup_stale_local_main(&repo);+ // Give local main its own commit so it diverges from origin/main.+ fs::write(repo.root_path().join("local-only.txt"), "local").unwrap();+ repo.run_git(&["add", "local-only.txt"]);+ repo.run_git(&["commit", "-m", "local-only commit on main"]);+ let diverged_main = repo.git_output(&["rev-parse", "main"]);+ let feature_wt = add_feature_worktree(+ &repo,+ "origin/main",+ &[("feature.txt", "the one real feature commit")],+ );++ let output = repo+ .wt_command()+ .args(["merge", "main", "--yes", "--no-hooks"])+ .current_dir(&feature_wt)+ .output()+ .unwrap();+ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(+ !output.status.success(),+ "merge must refuse a diverged local target\nstderr:\n{stderr}",+ );+ assert!(+ stderr.contains("has diverged"),+ "error should explain the divergence\nstderr:\n{stderr}",+ );+ assert_eq!(+ repo.git_output(&["rev-parse", "main"]),+ diverged_main,+ "local main must not be mutated by a refused merge",+ );+ assert!(+ repo.git_command()+ .args(["rev-parse", "--verify", "--quiet", "refs/heads/feature"])+ .run()+ .unwrap()+ .status+ .success(),+ "feature branch must survive a refused merge",+ );+}+/// Approval-boundary TOCTOU regression: a `post-merge` command that enters the/// invoking worktree's `.config/wt.toml` only via the rebase — after the gate/// froze the plan — must not run.diff --git a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap b/tests/snapshots/integration__integration_tests__help__help_md_merge.snapindex e98c9ed84..c6e97222c 100644--- a/tests/snapshots/integration__integration_tests__help__help_md_merge.snap+++ b/tests/snapshots/integration__integration_tests__help__help_md_merge.snap@@ -24,6 +24,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"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"@@ -173,6 +174,8 @@ $ wt merge --no-commit --no-rebaseUse `--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.+`wt merge` targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's `main` left behind `origin/main` — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. `wt step squash` and `wt step rebase` measure the same way. A local target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+## Local CIFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.diff --git a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap b/tests/snapshots/integration__integration_tests__help__help_merge_long.snapindex 42884494d..4c1213c6a 100644--- a/tests/snapshots/integration__integration_tests__help__help_merge_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_merge_long.snap@@ -24,6 +24,7 @@ info:WORKTRUNK_TEST_GEMINI_INSTALLED: "0"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"@@ -157,6 +158,9 @@ Preserve the exact clean commit graph and tip: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.+[2mwt merge[0m targets the *local* default-branch ref and never fetches. When that ref lags its upstream — e.g. a primary checkout's [2mmain[0m left behind [2morigin/main[0m — a branch based on the newer upstream tip is measured, squashed, and rebased against the upstream (so already-upstream commits are never folded into the squash), and the final fast-forward carries the local ref through the already-fetched upstream commits by their real SHAs. [2mwt step squash[0m and [2mwt step rebase[0m measure the same way. A local+target that has *diverged* from its upstream — its own commits and behind — cannot fast-forward, so the merge is refused until the target is reconciled.+[1m[32mLocal CI[0mFor personal projects, pre-merge hooks open up the possibility of a workflow with much faster iteration — an order of magnitude more small changes instead of fewer large ones.