Skip to content

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

fix(prune): OR over local + upstream in step prune integration check (#2515)

Maximilian Roosd66faea86b3d
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index f944e30fe..2d34455ab 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -65,7 +65,7 @@
//! ├─ is_builtin_fsmonitor_enabled() (5ms, sequential - gate)
//! ├─ rayon::scope(
//! │ ├─ switch_previous() (5ms)
-//! │ ├─ integration_target() (10ms)
+//! │ ├─ integration_targets() (10ms)
//! │ ├─ start_fsmonitor_daemon × N worktrees (6ms each, all parallel)
//! │ ) // ~10ms total (max of all spawns)
//! ├─ populate ListItem.commit from cache (cache-hit lookups, sub-ms)
diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rs
index 347626427..405ed272e 100644
--- a/src/commands/step_commands.rs
+++ b/src/commands/step_commands.rs
@@ -1290,12 +1290,12 @@ pub fn step_prune(
let repo = Repository::current()?;
let config = UserConfig::load()?;
- let integration_target = match repo.integration_target() {
- Some(target) => target,
- None => {
- anyhow::bail!("cannot determine default branch");
- }
- };
+ // Pass the local default branch (e.g. "main") directly — `integration_reason`
+ // ORs over local + upstream internally, so a branch merged into either side
+ // counts as integrated.
+ let integration_target = repo
+ .default_branch()
+ .context("cannot determine default branch")?;
let worktrees = repo.list_worktrees()?;
let current_root = repo.current_worktree().root()?.to_path_buf();
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 3404a0e4a..d9feb8ec3 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -449,76 +449,6 @@ impl Repository {
Ok(result)
}
- /// Choose a single integration target for status display (`wt list`).
- ///
- /// 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).
- ///
- /// **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
- .effective_integration_targets
- .entry(local_target.to_string())
- .or_insert_with(|| {
- // Resolve the upstream via the cached branch inventory
- // (`Repository::local_branches`). On the first call the
- // inventory scan primes this and every subsequent upstream
- // lookup; on repeat calls it's a map lookup.
- let upstream = match self.branch(local_target).upstream() {
- Ok(Some(upstream)) => upstream,
- _ => return local_target.to_string(),
- };
-
- // If local and upstream are the same commit, prefer local for clearer messaging
- if self.same_commit(local_target, &upstream).unwrap_or(false) {
- return local_target.to_string();
- }
-
- // If upstream contains commits not present in local, prefer upstream so
- // remotely merged branches still count as integrated after a fetch.
- if self.is_ancestor(local_target, &upstream).unwrap_or(false) {
- return upstream;
- }
-
- // If upstream is strictly behind local, local is more complete.
- if self.is_ancestor(&upstream, local_target).unwrap_or(false) {
- return local_target.to_string();
- }
-
- // Local and upstream have diverged (neither is ancestor of the other).
- // Prefer upstream so remote merges are still visible to integration
- // checks even while local has extra commits.
- upstream
- })
- .clone()
- }
-
- /// Get the cached integration target for this repository.
- ///
- /// This is the effective target for integration checks (status symbols, safe deletion).
- /// May be upstream (e.g., "origin/main") if it's ahead of local, catching remotely-merged branches.
- ///
- /// Returns None if the default branch cannot be determined.
- ///
- /// Result is cached in the shared repo cache (shared across all worktrees).
- pub fn integration_target(&self) -> Option<String> {
- self.cache
- .integration_target
- .get_or_init(|| {
- let default_branch = self.default_branch()?;
- Some(self.effective_integration_target(&default_branch))
- })
- .clone()
- }
-
/// Resolve the integration targets for `wt list`'s status column.
///
/// Mirrors the local/upstream branching in
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 235fbd1b0..04594b795 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -223,8 +223,6 @@ pub(super) struct RepoCache {
pub(super) repo_path: OnceCell<PathBuf>,
/// Default branch (main, master, etc.)
pub(super) default_branch: OnceCell<Option<String>>,
- /// Effective integration target (local default branch or upstream if ahead)
- pub(super) integration_target: OnceCell<Option<String>>,
/// Project identifier derived from remote URL
pub(super) project_identifier: OnceCell<String>,
/// Project config (loaded from .config/wt.toml in main worktree)
@@ -251,11 +249,6 @@ pub(super) struct RepoCache {
/// Resolved refs: unresolved ref (e.g., "main") -> resolved form (e.g., "refs/heads/main")
/// or original if not a local branch. Populated by `resolve_preferring_branch()`.
pub(super) resolved_refs: DashMap<String, String>,
- /// Effective integration targets: local_target -> effective ref (may be upstream).
- /// Cached because `integration_reason()` calls `effective_integration_target()` for
- /// every branch, but the result depends only on the target ref's relationship with
- /// its upstream — stable for the duration of a command.
- pub(super) effective_integration_targets: DashMap<String, String>,
/// Integration reason cache: (branch, target) -> (effective_target, reason).
/// Populated by `integration_reason()`, avoids redundant `compute_integration_lazy()`
/// calls when the same branch is checked multiple times (e.g., step_prune Phase 1
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 3e8ec2987..bee597cd3 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1263,8 +1263,8 @@ fn test_remove_squash_merged_then_same_files_modified(repo: TestRepo) {
/// 3. `git fetch` locally
/// 4. `wt remove <branch>` — should detect integration via origin/main
///
-/// The integration detection must use `effective_integration_target()` to check
-/// against `origin/main` (which is ahead of local `main` after fetch).
+/// `integration_reason` ORs over local `main` and `origin/main` so the squash
+/// merge on `origin/main` (ahead of local `main` after fetch) is detected.
#[rstest]
fn test_remove_squash_merged_on_remote(#[from(repo_with_remote)] repo: TestRepo) {
let remote_path = repo.remote_path().unwrap();
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index 37e47dd82..af7f8d716 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -1,8 +1,9 @@
//! Integration tests for `wt step prune`
use crate::common::{
- BareRepoTest, TestRepo, make_snapshot_cmd, repo, setup_temp_snapshot_settings,
+ BareRepoTest, TestRepo, make_snapshot_cmd, repo, repo_with_remote, setup_temp_snapshot_settings,
};
+use ansi_str::AnsiStr;
use insta::assert_snapshot;
use insta_cmd::assert_cmd_snapshot;
use rstest::rstest;
@@ -782,6 +783,188 @@ fn test_prune_json_orphan_branch(repo: TestRepo) {
assert_snapshot!(String::from_utf8_lossy(&output.stdout));
}
+/// Regression: `wt step prune` ORs over local AND upstream like `wt remove` /
+/// `wt list`. A worktree merged into LOCAL `main` must still be pruned when
+/// `main` and `origin/main` have diverged. Mirrors
+/// `test_remove_merged_locally_when_upstream_diverged` in `remove.rs`.
+#[rstest]
+fn test_prune_locally_merged_when_upstream_diverged(#[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 so local and upstream diverge.
+ let github_sim = repo.home_path().join("github-sim-prune-local-merge");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-prune-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"]);
+
+ // Merge a feature into local main so local main contains the feature commit.
+ repo.add_worktree("feature-prune-local");
+ let feature_path = repo.worktree_path("feature-prune-local");
+ std::fs::write(feature_path.join("feature.txt"), "feature").unwrap();
+ repo.run_git_in(feature_path, &["add", "feature.txt"]);
+ repo.run_git_in(feature_path, &["commit", "-m", "Add feature"]);
+ repo.run_git(&[
+ "merge",
+ "--no-ff",
+ "-m",
+ "Merge feature",
+ "feature-prune-local",
+ ]);
+
+ 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 must 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 must not be an ancestor of local main",
+ );
+
+ let output = make_snapshot_cmd(&repo, "step", &["prune", "--yes", "--min-age=0s"], None)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+
+ assert!(
+ output.status.success(),
+ "prune should succeed\nstderr:\n{stderr}",
+ );
+
+ let worktree_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.feature-prune-local");
+ assert!(
+ !worktree_path.exists(),
+ "locally-merged worktree should be pruned even when origin/main has diverged\nstderr:\n{stderr}",
+ );
+
+ let branch_still_exists = repo
+ .git_command()
+ .args([
+ "rev-parse",
+ "--verify",
+ "--quiet",
+ "refs/heads/feature-prune-local",
+ ])
+ .run()
+ .unwrap()
+ .status
+ .success();
+ assert!(
+ !branch_still_exists,
+ "locally-merged branch should be deleted alongside its worktree\nstderr:\n{stderr}",
+ );
+}
+
+/// Regression companion: a worktree squash-merged on `origin/main` is pruned
+/// when local `main` has its own unique commits. Mirrors
+/// `test_remove_squash_merged_on_remote_when_local_main_diverged`.
+#[rstest]
+fn test_prune_squash_merged_on_remote_when_local_diverged(
+ #[from(repo_with_remote)] mut repo: TestRepo,
+) {
+ let remote_path = repo.remote_path().unwrap().to_path_buf();
+
+ // Build, push, and remote-squash-merge a feature branch.
+ repo.add_worktree("feature-prune-remote-squash");
+ let feature_path = repo.worktree_path("feature-prune-remote-squash");
+ std::fs::write(feature_path.join("feature-remote.txt"), "initial").unwrap();
+ repo.run_git_in(feature_path, &["add", "feature-remote.txt"]);
+ repo.run_git_in(feature_path, &["commit", "-m", "Add feature"]);
+ std::fs::write(feature_path.join("feature-remote.txt"), "final").unwrap();
+ repo.run_git_in(feature_path, &["add", "feature-remote.txt"]);
+ repo.run_git_in(feature_path, &["commit", "-m", "Finalize feature"]);
+ repo.run_git_in(
+ feature_path,
+ &["push", "-u", "origin", "feature-prune-remote-squash"],
+ );
+
+ let github_sim = repo.home_path().join("github-sim-prune-remote-squash");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-prune-remote-squash",
+ ],
+ );
+ repo.run_git_in(
+ &github_sim,
+ &["merge", "--squash", "origin/feature-prune-remote-squash"],
+ );
+ repo.run_git_in(&github_sim, &["commit", "-m", "Add feature (#1)"]);
+ repo.run_git_in(&github_sim, &["push", "origin", "main"]);
+
+ // Fetch the remote squash; advance local main with a unique commit so local
+ // and upstream diverge.
+ repo.run_git(&["fetch", "origin"]);
+ std::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"]);
+
+ 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,
+ "local main should diverge from origin/main"
+ );
+
+ let output = make_snapshot_cmd(&repo, "step", &["prune", "--yes", "--min-age=0s"], None)
+ .output()
+ .unwrap();
+ let stderr = String::from_utf8_lossy(&output.stderr)
+ .ansi_strip()
+ .into_owned();
+
+ assert!(
+ output.status.success(),
+ "prune should succeed\nstderr:\n{stderr}",
+ );
+
+ let worktree_path = repo
+ .root_path()
+ .parent()
+ .unwrap()
+ .join("repo.feature-prune-remote-squash");
+ assert!(
+ !worktree_path.exists(),
+ "remotely-squash-merged worktree should be pruned when local main has diverged\nstderr:\n{stderr}",
+ );
+}
+
/// Hook announcements during prune include the branch name for disambiguation
#[rstest]
fn test_prune_hook_announcements_include_branch(mut repo: TestRepo) {