Skip to content

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

fix(integration): OR over local + upstream for integration detection (#2507)

Maximilian Roos5a12324dd31d
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 8fead466a..9228ceec2 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -435,18 +435,19 @@ impl Repository {
Ok(result)
}
- /// Determine the effective target for integration checks.
+ /// Choose a single integration target for status display (`wt list`).
///
- /// If the upstream of the local target (e.g., `origin/main`) contains commits that
- /// the local target does not, uses the upstream. This handles both the common "local
- /// branch is behind upstream" case and the diverged case where local has extra commits
- /// but upstream contains a remote merge that local hasn't integrated yet.
+ /// Picks one ref so a status column renders unambiguously:
+ /// - Same commit: local (cleaner messaging).
+ /// - Local strictly behind upstream: upstream (superset).
+ /// - Upstream strictly behind local: local (superset).
+ /// - Diverged: upstream (so remotely merged branches still show as
+ /// integrated in the column).
///
- /// When local and upstream are the same commit, prefers local for clearer messaging.
- ///
- /// Returns the effective target ref to check against.
- ///
- /// Used by both `wt list` and `wt remove` to ensure consistent integration detection.
+ /// **Not for safety-critical integration checks.** Picking one ref in the
+ /// diverged case misses branches merged into the unchosen side. Use
+ /// [`Self::integration_reason()`] when deciding whether a branch is safe
+ /// to delete — it ORs over both refs.
///
pub fn effective_integration_target(&self, local_target: &str) -> String {
self.cache
@@ -548,17 +549,36 @@ impl Repository {
/// Check if a branch is integrated into a target.
///
- /// This is a convenience method that combines [`compute_integration_lazy()`] and
- /// [`check_integration()`]. The `target` is transformed via [`Self::effective_integration_target()`]
- /// before checking, which may use an upstream ref if it's ahead of the local target.
+ /// Combines [`compute_integration_lazy()`] and [`check_integration()`], and
+ /// considers both the local target and its upstream so a branch counts as
+ /// integrated whether it was merged locally OR remotely.
+ ///
+ /// Behavior depends on how local and upstream relate:
+ ///
+ /// - No upstream, or upstream at the same commit: check local only.
+ /// - Local is an ancestor of upstream (local strictly behind): upstream is
+ /// a superset, so check upstream only — anything in local is also in
+ /// upstream.
+ /// - Upstream is an ancestor of local (upstream strictly behind): local is
+ /// a superset, so check local only.
+ /// - Diverged (neither is an ancestor): check local first; if not
+ /// integrated, also check upstream. The branch is integrated if either
+ /// matches.
///
- /// Uses lazy evaluation with short-circuit: stops as soon as any check confirms
- /// integration, avoiding expensive operations like merge simulation when cheaper
- /// checks succeed.
+ /// The "diverged → OR" case is the safety-critical one. After `wt merge`
+ /// updates local main, local and upstream diverge until the merge is
+ /// pushed; checking only one side would falsely report the just-merged
+ /// branch as unmerged.
+ ///
+ /// Uses lazy evaluation with short-circuit: stops as soon as any check
+ /// confirms integration, avoiding expensive operations like merge
+ /// simulation when cheaper checks succeed.
///
/// Returns `(effective_target, reason)` where:
- /// - `effective_target` is the ref actually checked (may be upstream like "origin/main")
- /// - `reason` is `Some(reason)` if integrated, `None` if not
+ /// - `effective_target` is the ref that actually matched (the local target
+ /// when local matches or the branch is unmerged; the upstream ref when
+ /// only upstream matches).
+ /// - `reason` is `Some(reason)` if integrated, `None` if not.
///
/// # Example
/// ```no_run
@@ -584,13 +604,74 @@ impl Repository {
{
Entry::Occupied(e) => Ok(e.get().clone()),
Entry::Vacant(e) => {
- let effective_target = self.effective_integration_target(target);
- let signals = compute_integration_lazy(self, branch, &effective_target)?;
- let result = (effective_target, check_integration(&signals));
+ let result = self.compute_integration_reason_uncached(branch, target)?;
Ok(e.insert(result).clone())
}
}
}
+
+ fn compute_integration_reason_uncached(
+ &self,
+ branch: &str,
+ target: &str,
+ ) -> anyhow::Result<(String, Option<IntegrationReason>)> {
+ // Resolve upstream once. Errors and "no upstream" both collapse to None.
+ let upstream = self.branch(target).upstream().ok().flatten();
+
+ // Decide whether to check local, upstream, or both.
+ //
+ // The ancestor checks here run git directly with ref names rather than
+ // going through cached `is_ancestor`/`rev_parse_commit`, because the
+ // local target may have just been updated (e.g. by `wt merge`'s ref
+ // update). Cached SHAs would be stale and could misclassify the
+ // local/upstream relationship.
+ let (check_local, fallback_upstream) = match upstream {
+ None => (true, None),
+ Some(u) if self.same_commit(target, &u).unwrap_or(false) => (true, None),
+ Some(u) if ref_is_ancestor(self, target, &u) => {
+ // Local strictly behind upstream — upstream is the superset.
+ let signals = compute_integration_lazy(self, branch, &u)?;
+ return Ok((u, check_integration(&signals)));
+ }
+ Some(u) if ref_is_ancestor(self, &u, target) => {
+ // Upstream strictly behind local — local is the superset.
+ (true, None)
+ }
+ Some(u) => {
+ // Diverged — check local first, fall back to upstream.
+ (true, Some(u))
+ }
+ };
+
+ if check_local
+ && let Some(reason) =
+ check_integration(&compute_integration_lazy(self, branch, target)?)
+ {
+ return Ok((target.to_string(), Some(reason)));
+ }
+
+ if let Some(upstream) = fallback_upstream
+ && let Some(reason) =
+ check_integration(&compute_integration_lazy(self, branch, &upstream)?)
+ {
+ return Ok((upstream, Some(reason)));
+ }
+
+ Ok((target.to_string(), None))
+ }
+}
+
+/// Run `git merge-base --is-ancestor` directly with ref names, bypassing
+/// `Repository::is_ancestor`'s SHA cache.
+///
+/// `is_ancestor` resolves both refs through the cached `rev_parse_commit`,
+/// so a ref that was updated mid-command (e.g. `wt merge` rewriting local
+/// `main`) returns its old SHA. For relationships where freshness matters —
+/// in particular comparing a just-updated local target against its upstream —
+/// running git directly with ref names dodges that staleness.
+fn ref_is_ancestor(repo: &Repository, base: &str, head: &str) -> bool {
+ repo.run_command_check(&["merge-base", "--is-ancestor", base, head])
+ .unwrap_or(false)
}
/// Returns true when `s` is a 40-character hex string — the canonical form
diff --git a/tests/integration_tests/merge.rs b/tests/integration_tests/merge.rs
index 43ca3ae1a..bb14ce56d 100644
--- a/tests/integration_tests/merge.rs
+++ b/tests/integration_tests/merge.rs
@@ -2,7 +2,8 @@ use crate::common::{
TestRepo, make_snapshot_cmd, merge_scenario,
mock_commands::{create_mock_cargo, create_mock_llm_auth},
repo, repo_with_alternate_primary, repo_with_feature_worktree, repo_with_main_worktree,
- repo_with_multi_commit_feature, setup_snapshot_settings, wait_for_file, wait_for_file_content,
+ repo_with_multi_commit_feature, repo_with_remote, setup_snapshot_settings, wait_for_file,
+ wait_for_file_content,
};
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
@@ -3038,3 +3039,85 @@ fn test_merge_json(repo: TestRepo) {
}
"#);
}
+
+/// Regression: post-merge integration check uses the LOCAL target ref, not the
+/// upstream. When local `main` and `origin/main` have diverged, the merge just
+/// performed lands in local `main` only — checking against `origin/main` would
+/// falsely report the branch as unmerged and skip removal.
+#[rstest]
+fn test_merge_removes_branch_when_local_main_diverged_from_upstream(
+ #[from(repo_with_remote)] mut repo: TestRepo,
+) {
+ let remote_path = repo.remote_path().unwrap().to_path_buf();
+
+ // Advance origin/main with a remote-only commit (clone bare remote, commit, push).
+ let github_sim = repo.home_path().join("github-sim");
+ repo.run_git_in(
+ repo.home_path(),
+ &["clone", remote_path.to_str().unwrap(), "github-sim"],
+ );
+ fs::write(github_sim.join("remote-only.txt"), "remote only").unwrap();
+ repo.run_git_in(&github_sim, &["add", "remote-only.txt"]);
+ repo.run_git_in(&github_sim, &["commit", "-m", "Remote-only main commit"]);
+ repo.run_git_in(&github_sim, &["push", "origin", "main"]);
+
+ // Fetch origin so the local repo knows about origin/main, then add a
+ // local-only commit so local main and origin/main diverge.
+ repo.run_git(&["fetch", "origin"]);
+ fs::write(repo.root_path().join("local-only.txt"), "local only").unwrap();
+ repo.run_git(&["add", "local-only.txt"]);
+ repo.run_git(&["commit", "-m", "Local-only main commit"]);
+
+ // Sanity: local main and origin/main have diverged (neither is ancestor).
+ assert!(
+ !repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "main", "origin/main"])
+ .run()
+ .unwrap()
+ .status
+ .success(),
+ "local main should not be an ancestor of origin/main"
+ );
+ assert!(
+ !repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "origin/main", "main"])
+ .run()
+ .unwrap()
+ .status
+ .success(),
+ "origin/main should not be an ancestor of local main"
+ );
+
+ // Create feature off current local main and add a commit.
+ let feature_wt = repo.add_feature();
+
+ // Merge — should detect integration against local main, not origin/main.
+ let output = repo
+ .wt_command()
+ .args(["merge", "main", "--yes"])
+ .current_dir(&feature_wt)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr);
+ assert!(
+ output.status.success(),
+ "merge should succeed despite local/upstream divergence\nstderr:\n{stderr}",
+ );
+ assert!(
+ !stderr.contains("Branch unmerged"),
+ "post-merge integration check must use local target, not upstream\nstderr:\n{stderr}",
+ );
+
+ // Branch should be deleted as part of the safe removal path.
+ let branch_check = repo
+ .git_command()
+ .args(["rev-parse", "--verify", "--quiet", "refs/heads/feature"])
+ .run()
+ .unwrap();
+ assert!(
+ !branch_check.status.success(),
+ "feature branch should be deleted after a clean merge"
+ );
+}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 88d39a047..3e8ec2987 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -3008,3 +3008,101 @@ fn test_remove_json_multi_with_current(mut repo: TestRepo) {
assert_eq!(items[1]["branch"], "current-feature");
assert_eq!(items[1]["kind"], "worktree");
}
+
+/// Regression: integration check ORs over local AND upstream. A branch merged
+/// into LOCAL `main` must still be detected as integrated when `main` and
+/// `origin/main` have diverged — symmetric to
+/// `test_remove_squash_merged_on_remote_when_local_main_diverged`, which
+/// covers the merged-on-remote side.
+#[rstest]
+fn test_remove_merged_locally_when_upstream_diverged(#[from(repo_with_remote)] repo: TestRepo) {
+ let remote_path = repo.remote_path().unwrap().to_path_buf();
+
+ // Advance origin/main with a remote-only commit so local and upstream diverge.
+ let github_sim = repo.home_path().join("github-sim-local-merge");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-local-merge",
+ ],
+ );
+ std::fs::write(github_sim.join("remote-only.txt"), "remote only").unwrap();
+ repo.run_git_in(&github_sim, &["add", "remote-only.txt"]);
+ repo.run_git_in(&github_sim, &["commit", "-m", "Remote-only main commit"]);
+ repo.run_git_in(&github_sim, &["push", "origin", "main"]);
+
+ // Create a feature branch off the original main and merge it locally
+ // (no fetch yet, so local main moves while origin/main stays at the
+ // original tip in our local view).
+ repo.run_git(&["checkout", "-b", "feature-local-merge"]);
+ std::fs::write(repo.root_path().join("feature.txt"), "feature").unwrap();
+ repo.run_git(&["add", "feature.txt"]);
+ repo.run_git(&["commit", "-m", "Add feature"]);
+ repo.run_git(&["checkout", "main"]);
+ repo.run_git(&["merge", "--ff-only", "feature-local-merge"]);
+
+ // Now fetch — origin/main holds the remote commit, local main holds the
+ // feature merge, neither is an ancestor of the other.
+ repo.run_git(&["fetch", "origin"]);
+
+ let local_main = repo.git_output(&["rev-parse", "main"]);
+ let origin_main = repo.git_output(&["rev-parse", "origin/main"]);
+ assert_ne!(
+ local_main, origin_main,
+ "main and origin/main should differ"
+ );
+ assert!(
+ !repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "main", "origin/main"])
+ .run()
+ .unwrap()
+ .status
+ .success(),
+ "local main should not be an ancestor of origin/main"
+ );
+ assert!(
+ !repo
+ .git_command()
+ .args(["merge-base", "--is-ancestor", "origin/main", "main"])
+ .run()
+ .unwrap()
+ .status
+ .success(),
+ "origin/main should not be an ancestor of local main"
+ );
+
+ // Remove the feature branch — should detect integration via local main
+ // even though origin/main does not contain the feature commit.
+ let output = make_snapshot_cmd(&repo, "remove", &["feature-local-merge"], None)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+ assert!(
+ output.status.success(),
+ "remove should succeed\nstderr:\n{stderr}",
+ );
+ assert!(
+ !stderr.contains("Branch unmerged"),
+ "integration check must detect local merges, not just upstream\nstderr:\n{stderr}",
+ );
+
+ let branch_still_exists = repo
+ .git_command()
+ .args([
+ "rev-parse",
+ "--verify",
+ "--quiet",
+ "refs/heads/feature-local-merge",
+ ])
+ .run()
+ .unwrap();
+ assert!(
+ !branch_still_exists.status.success(),
+ "feature branch should be deleted after detection via local main"
+ );
+}
diff --git a/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap
index eb9ddaf5a..d14d24a10 100644
--- a/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap
+++ b/tests/snapshots/integration__integration_tests__user_hooks__merge_auto_commit_combines_post_commit_post_remove_post_switch_post_merge.snap
@@ -59,8 +59,7 @@ exit_code: 0
  feature.txt | 1 +
  2 files changed, 2 insertions(+)
✓ Merged to main (2 commits, 2 files, +2)
-◎ Removing feature worktree in background
-↳ Branch unmerged; to delete, run wt remove -D feature
+◎ Removing feature worktree & branch in background (same commit as main, _)
▲ Cannot change directory — shell integration not installed
↳ To enable automatic cd, run wt config shell install
◎ Running post-commit: mark (user); post-remove: cleanup (user); post-switch: notify (user); post-merge: sync (user) @ _REPO_