Skip to content

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

fix: detect squash-merged branches when merge-tree conflicts (#1820)

worktrunk-botf6e89009e5ab
diff --git a/benches/CLAUDE.md b/benches/CLAUDE.md
index d53196912..b4f014ee2 100644
--- a/benches/CLAUDE.md
+++ b/benches/CLAUDE.md
@@ -145,7 +145,9 @@ SELECT
WHEN name LIKE '%rev-parse%' THEN 'rev_parse'
ELSE 'other' END as task_type,
COUNT(*) as count,
- ROUND(SUM(dur)/1e6, 2) as total_ms
+ ROUND(SUM(dur)/1e6, 2) as total_ms,
+ ROUND(MAX(dur)/1e6, 2) as max_ms,
+ ROUND(AVG(dur)/1e6, 2) as avg_ms
FROM slice WHERE dur > 0
GROUP BY task_type ORDER BY total_ms DESC;
EOF
diff --git a/docs/content/list.md b/docs/content/list.md
index c8ca1e39a..17c594428 100644
--- a/docs/content/list.md
+++ b/docs/content/list.md
@@ -226,7 +226,7 @@ These values describe the relation to the default branch.
### integration_reason values
-When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"`
+When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"` `"patch-id-match"`
### ci.status values
diff --git a/docs/content/remove.md b/docs/content/remove.md
index a599ec4b5..c0c47c8b2 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -33,13 +33,14 @@ Force-delete an unmerged branch:
By default, branches are deleted when they would add no changes to the default branch if merged. This works with both unchanged git histories, and squash-merge or rebase workflows where commit history differs but file changes match.
-Worktrunk checks five conditions (in order of cost):
+Worktrunk checks six conditions (in order of cost):
1. **Same commit** — Branch HEAD equals the default branch. Shows `_` in `wt list`.
2. **Ancestor** — Branch is in target's history (fast-forward or rebase case). Shows `⊂`.
3. **No added changes** — Three-dot diff (`target...branch`) is empty. Shows `⊂`.
4. **Trees match** — Branch tree SHA equals target tree SHA. Shows `⊂`.
-5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced. Shows `⊂`.
+5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced with changes to different files. Shows `⊂`.
+6. **Patch-id match** — Branch's entire diff matches a single squash-merge commit on target. Fallback for when the simulated merge conflicts because target later modified the same files the branch touched. Shows `⊂`.
The 'same commit' check uses the local default branch; for other checks, 'target' means the default branch, or its upstream (e.g., `origin/main`) when strictly ahead.
diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.md
index 8c3e31468..d6e1cc228 100644
--- a/skills/worktrunk/reference/list.md
+++ b/skills/worktrunk/reference/list.md
@@ -240,7 +240,7 @@ These values describe the relation to the default branch.
### integration_reason values
-When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"`
+When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"` `"patch-id-match"`
### ci.status values
diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.md
index ba419f59f..c998f9394 100644
--- a/skills/worktrunk/reference/remove.md
+++ b/skills/worktrunk/reference/remove.md
@@ -33,13 +33,14 @@ $ wt remove -D experimental
By default, branches are deleted when they would add no changes to the default branch if merged. This works with both unchanged git histories, and squash-merge or rebase workflows where commit history differs but file changes match.
-Worktrunk checks five conditions (in order of cost):
+Worktrunk checks six conditions (in order of cost):
1. **Same commit** — Branch HEAD equals the default branch. Shows `_` in `wt list`.
2. **Ancestor** — Branch is in target's history (fast-forward or rebase case). Shows `⊂`.
3. **No added changes** — Three-dot diff (`target...branch`) is empty. Shows `⊂`.
4. **Trees match** — Branch tree SHA equals target tree SHA. Shows `⊂`.
-5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced. Shows `⊂`.
+5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced with changes to different files. Shows `⊂`.
+6. **Patch-id match** — Branch's entire diff matches a single squash-merge commit on target. Fallback for when the simulated merge conflicts because target later modified the same files the branch touched. Shows `⊂`.
The 'same commit' check uses the local default branch; for other checks, 'target' means the default branch, or its upstream (e.g., `origin/main`) when strictly ahead.
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index 2229338b7..a7eab81f3 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -708,7 +708,7 @@ These values describe the relation to the default branch.
### integration_reason values
-When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"`
+When `main_state == "integrated"`: `"ancestor"` `"trees_match"` `"no_added_changes"` `"merge_adds_nothing"` `"patch-id-match"`
### ci.status values
@@ -793,13 +793,14 @@ $ wt remove -D experimental
By default, branches are deleted when they would add no changes to the default branch if merged. This works with both unchanged git histories, and squash-merge or rebase workflows where commit history differs but file changes match.
-Worktrunk checks five conditions (in order of cost):
+Worktrunk checks six conditions (in order of cost):
1. **Same commit** — Branch HEAD equals the default branch. Shows `_` in `wt list`.
2. **Ancestor** — Branch is in target's history (fast-forward or rebase case). Shows `⊂`.
3. **No added changes** — Three-dot diff (`target...branch`) is empty. Shows `⊂`.
4. **Trees match** — Branch tree SHA equals target tree SHA. Shows `⊂`.
-5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced. Shows `⊂`.
+5. **Merge adds nothing** — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced with changes to different files. Shows `⊂`.
+6. **Patch-id match** — Branch's entire diff matches a single squash-merge commit on target. Fallback for when the simulated merge conflicts because target later modified the same files the branch touched. Shows `⊂`.
The 'same commit' check uses the local default branch; for other checks, 'target' means the default branch, or its upstream (e.g., `origin/main`) when strictly ahead.
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index c2ba63cce..a8f0f1172 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -548,6 +548,7 @@ pub fn collect(
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: None,
@@ -1133,6 +1134,7 @@ pub fn build_worktree_item(
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: None,
diff --git a/src/commands/list/collect/results.rs b/src/commands/list/collect/results.rs
index 90d3fc055..a10d0f9c7 100644
--- a/src/commands/list/collect/results.rs
+++ b/src/commands/list/collect/results.rs
@@ -47,6 +47,7 @@ pub(super) fn apply_default(
TaskKind::WouldMergeAdd => {
// Conservative: assume would add changes if we couldn't check
items[idx].would_merge_add = Some(true);
+ items[idx].is_patch_id_match = Some(false);
}
TaskKind::IsAncestor => {
// Conservative: don't claim merged if we couldn't check
@@ -226,9 +227,12 @@ pub(super) fn drain_results(
item.has_file_changes = Some(has_file_changes);
}
TaskResult::WouldMergeAdd {
- would_merge_add, ..
+ would_merge_add,
+ is_patch_id_match,
+ ..
} => {
item.would_merge_add = Some(would_merge_add);
+ item.is_patch_id_match = Some(is_patch_id_match);
}
TaskResult::IsAncestor { is_ancestor, .. } => {
item.is_ancestor = Some(is_ancestor);
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 13ff7b975..212cfff9c 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -254,17 +254,21 @@ impl Task for HasFileChangesTask {
}
}
-/// Task 3b: Merge simulation
+/// Task 3b: Merge simulation + patch-id fallback
///
-/// Checks if merging the branch into target would add any changes by simulating
-/// the merge with `git merge-tree --write-tree`. Returns false when the merge
-/// result equals target's tree, indicating the branch is already integrated.
+/// Delegates to [`Repository::merge_integration_probe()`], which runs:
///
-/// This catches branches where target has advanced past the squash-merge point -
-/// the three-dot diff might show changes, but those changes are already in target
-/// via the squash merge.
+/// 1. `merge-tree --write-tree` — simulates merging branch into target. If the
+/// result tree equals target's tree, the branch is integrated (`MergeAddsNothing`).
+/// 2. `patch-id` fallback — only when merge-tree conflicts (returns `None`).
+/// Computes the branch's entire diff as a single patch-id and checks if any
+/// target commit matches (`PatchIdMatch`). Detects squash merges where target
+/// later modified the same files.
///
-/// Uses target for integration detection.
+/// These are bundled in one task because patch-id only runs when merge-tree
+/// conflicts — it needs the merge-tree result first. Splitting them into separate
+/// parallel tasks would either waste work (running patch-id unconditionally) or
+/// require two-phase scheduling.
pub struct WouldMergeAddTask;
impl Task for WouldMergeAddTask {
@@ -276,6 +280,7 @@ impl Task for WouldMergeAddTask {
return Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add: true,
+ is_patch_id_match: false,
});
};
// When integration_target is None, return true (conservative: assume would add)
@@ -283,15 +288,17 @@ impl Task for WouldMergeAddTask {
return Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add: true,
+ is_patch_id_match: false,
});
};
- let repo = &ctx.repo;
- let would_merge_add = repo
- .would_merge_add_to_target(branch, &base)
+ let probe = ctx
+ .repo
+ .merge_integration_probe(branch, &base)
.map_err(|e| ctx.error(Self::KIND, &e))?;
Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
- would_merge_add,
+ would_merge_add: probe.would_merge_add,
+ is_patch_id_match: probe.is_patch_id_match,
})
}
}
diff --git a/src/commands/list/collect/types.rs b/src/commands/list/collect/types.rs
index 7a079eb23..efa54eec2 100644
--- a/src/commands/list/collect/types.rs
+++ b/src/commands/list/collect/types.rs
@@ -93,6 +93,7 @@ pub(crate) enum TaskResult {
WouldMergeAdd {
item_idx: usize,
would_merge_add: bool,
+ is_patch_id_match: bool,
},
/// Whether branch HEAD is ancestor of integration target (same commit or already merged)
IsAncestor { item_idx: usize, is_ancestor: bool },
diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rs
index d5338dfd2..97c1759cf 100644
--- a/src/commands/list/layout.rs
+++ b/src/commands/list/layout.rs
@@ -1318,6 +1318,7 @@ mod tests {
committed_trees_match: Some(false),
has_file_changes: Some(true),
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: Some(UpstreamStatus {
@@ -1421,6 +1422,7 @@ mod tests {
committed_trees_match: Some(false),
has_file_changes: Some(true),
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: Some(UpstreamStatus::default()),
@@ -1534,6 +1536,7 @@ mod tests {
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: None,
@@ -1776,6 +1779,7 @@ mod tests {
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: None,
@@ -1901,6 +1905,7 @@ mod tests {
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: upstream_status,
diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rs
index 073b52480..36a660baa 100644
--- a/src/commands/list/model/item.rs
+++ b/src/commands/list/model/item.rs
@@ -176,6 +176,10 @@ pub struct ListItem {
/// as the integration target. Catches squash-merged branches where the integration target advanced.
#[serde(skip)]
pub would_merge_add: Option<bool>,
+ /// Whether the branch's squashed patch-id matches a commit on the integration target.
+ /// Detects squash merges when merge-tree conflicts (both sides modified the same files).
+ #[serde(skip)]
+ pub is_patch_id_match: Option<bool>,
/// Whether branch HEAD is an ancestor of the integration target (or same commit).
/// True means branch is already part of the integration target's history.
/// This is the cheapest integration check (~1ms).
@@ -243,6 +247,7 @@ impl ListItem {
committed_trees_match: None,
has_file_changes: None,
would_merge_add: None,
+ is_patch_id_match: None,
is_ancestor: None,
is_orphan: None,
upstream: None,
@@ -613,6 +618,7 @@ impl ListItem {
has_added_changes: self.has_file_changes,
trees_match: self.committed_trees_match,
would_merge_add: self.would_merge_add,
+ is_patch_id_match: self.is_patch_id_match,
};
let reason = check_integration(&signals);
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 27dcb7c09..61b83bfa7 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -487,6 +487,8 @@ mod tests {
assert_eq!(s, "no-added-changes");
let s: &'static str = IntegrationReason::MergeAddsNothing.into();
assert_eq!(s, "merge-adds-nothing");
+ let s: &'static str = IntegrationReason::PatchIdMatch.into();
+ assert_eq!(s, "patch-id-match");
}
#[test]
@@ -518,6 +520,10 @@ mod tests {
MainState::Integrated(IntegrationReason::MergeAddsNothing).integration_reason(),
Some(IntegrationReason::MergeAddsNothing)
);
+ assert_eq!(
+ MainState::Integrated(IntegrationReason::PatchIdMatch).integration_reason(),
+ Some(IntegrationReason::PatchIdMatch)
+ );
}
#[test]
diff --git a/src/git/mod.rs b/src/git/mod.rs
index d80740d3e..6ea3eb06d 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -73,6 +73,7 @@ pub use url::parse_owner_repo;
/// 3. [`NoAddedChanges`](Self::NoAddedChanges) - three-dot diff (~50-100ms)
/// 4. [`TreesMatch`](Self::TreesMatch) - tree SHA comparison (~100-300ms)
/// 5. [`MergeAddsNothing`](Self::MergeAddsNothing) - merge simulation (~500ms-2s)
+/// 6. [`PatchIdMatch`](Self::PatchIdMatch) - patch-id matching when merge-tree conflicts (~1-3s)
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, strum::IntoStaticStr)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
@@ -101,11 +102,25 @@ pub enum IntegrationReason {
/// Symbol in `wt list`: `⊂`
TreesMatch,
- /// Simulated merge (`git merge-tree`) produces the same tree as target.
- /// The branch has changes, but they're already in target via a different path.
+ /// The branch has changes, but merging would produce the same tree as target.
+ ///
+ /// Detected via `git merge-tree` simulation. Handles squash-merged branches
+ /// where target has advanced with changes to different files.
///
/// Symbol in `wt list`: `⊂`
MergeAddsNothing,
+
+ /// The branch's entire squashed diff matches a single commit on target.
+ ///
+ /// Fallback for when `merge-tree` conflicts (both sides modified the same
+ /// files). Computes `git diff-tree -p merge-base branch` as one combined
+ /// diff and checks if any individual commit on target has the same
+ /// patch-id. This specifically detects GitHub/GitLab squash merges — the
+ /// squash commit contains the whole branch in one commit, so the patch-ids
+ /// match. Does NOT detect cherry-picks of individual commits.
+ ///
+ /// Symbol in `wt list`: `⊂`
+ PatchIdMatch,
}
impl IntegrationReason {
@@ -120,6 +135,7 @@ impl IntegrationReason {
Self::NoAddedChanges => "no added changes on",
Self::TreesMatch => "tree matches",
Self::MergeAddsNothing => "all changes in",
+ Self::PatchIdMatch => "all changes in",
}
}
@@ -150,6 +166,7 @@ pub struct IntegrationSignals {
pub has_added_changes: Option<bool>,
pub trees_match: Option<bool>,
pub would_merge_add: Option<bool>,
+ pub is_patch_id_match: Option<bool>,
}
/// Canonical integration check using pre-computed signals.
@@ -180,11 +197,16 @@ pub fn check_integration(signals: &IntegrationSignals) -> Option<IntegrationReas
return Some(IntegrationReason::TreesMatch);
}
- // Priority 5 (most expensive ~500ms-2s): Merge would not add anything
+ // Priority 5 (expensive ~500ms-2s): Merge would not add anything
if signals.would_merge_add == Some(false) {
return Some(IntegrationReason::MergeAddsNothing);
}
+ // Priority 6 (most expensive): Patch-id match detects squash merge when merge-tree conflicts
+ if signals.is_patch_id_match == Some(true) {
+ return Some(IntegrationReason::PatchIdMatch);
+ }
+
None
}
@@ -228,8 +250,13 @@ pub fn compute_integration_lazy(
return Ok(signals);
}
- // Priority 5: Would merge add (most expensive)
- signals.would_merge_add = Some(repo.would_merge_add_to_target(branch, target)?);
+ // Priority 5+6: Merge-tree simulation + patch-id fallback
+ let probe = repo.merge_integration_probe(branch, target)?;
+ signals.would_merge_add = Some(probe.would_merge_add);
+ if !probe.would_merge_add {
+ return Ok(signals);
+ }
+ signals.is_patch_id_match = Some(probe.is_patch_id_match);
Ok(signals)
}
@@ -547,14 +574,28 @@ mod tests {
#[test]
fn test_check_integration() {
// Each integration reason + not integrated
- // Tuple: (is_same_commit, is_ancestor, has_added_changes, trees_match, would_merge_add)
+ // Tuple: (is_same_commit, is_ancestor, has_added_changes, trees_match, would_merge_add, is_patch_id_match)
let cases = [
(
- (Some(true), Some(false), Some(true), Some(false), Some(true)),
+ (
+ Some(true),
+ Some(false),
+ Some(true),
+ Some(false),
+ Some(true),
+ None,
+ ),
Some(IntegrationReason::SameCommit),
),
(
- (Some(false), Some(true), Some(true), Some(false), Some(true)),
+ (
+ Some(false),
+ Some(true),
+ Some(true),
+ Some(false),
+ Some(true),
+ None,
+ ),
Some(IntegrationReason::Ancestor),
),
(
@@ -564,11 +605,19 @@ mod tests {
Some(false),
Some(false),
Some(true),
+ None,
),
Some(IntegrationReason::NoAddedChanges),
),
(
- (Some(false), Some(false), Some(true), Some(true), Some(true)),
+ (
+ Some(false),
+ Some(false),
+ Some(true),
+ Some(true),
+ Some(true),
+ None,
+ ),
Some(IntegrationReason::TreesMatch),
),
(
@@ -578,42 +627,65 @@ mod tests {
Some(true),
Some(false),
Some(false),
+ None,
),
Some(IntegrationReason::MergeAddsNothing),
),
(
+ // Patch-id match (merge-tree conflicts but patch-id finds squash commit)
+ (
+ Some(false),
+ Some(false),
+ Some(true),
+ Some(false),
+ Some(true),
+ Some(true),
+ ),
+ Some(IntegrationReason::PatchIdMatch),
+ ),
+ (
+ // Not integrated (nothing matches)
(
Some(false),
Some(false),
Some(true),
Some(false),
Some(true),
+ Some(false),
),
None,
- ), // Not integrated
+ ),
(
- (Some(true), Some(true), Some(false), Some(true), Some(false)),
+ (
+ Some(true),
+ Some(true),
+ Some(false),
+ Some(true),
+ Some(false),
+ None,
+ ),
Some(IntegrationReason::SameCommit),
), // Priority test: is_same_commit wins
// None values are treated conservatively (as if not integrated)
- ((None, None, None, None, None), None),
+ ((None, None, None, None, None, None), None),
(
- (None, Some(true), Some(false), Some(true), Some(false)),
+ (None, Some(true), Some(false), Some(true), Some(false), None),
Some(IntegrationReason::Ancestor),
),
];
- for ((same, ancestor, added, trees, merge), expected) in cases {
+ for ((same, ancestor, added, trees, merge, patch_id), expected) in cases {
let signals = IntegrationSignals {
is_same_commit: same,
is_ancestor: ancestor,
has_added_changes: added,
trees_match: trees,
would_merge_add: merge,
+ is_patch_id_match: patch_id,
};
assert_eq!(
check_integration(&signals),
expected,
- "case: {same:?},{ancestor:?},{added:?},{trees:?},{merge:?}"
+ "case: {same:?},{ancestor:?},{added:?},{trees:?},{merge:?},{patch_id:?}"
);
}
}
@@ -634,6 +706,10 @@ mod tests {
IntegrationReason::MergeAddsNothing.description(),
"all changes in"
);
+ assert_eq!(
+ IntegrationReason::PatchIdMatch.description(),
+ "all changes in"
+ );
}
#[test]
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 552449557..2576dd950 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -7,6 +7,22 @@ use anyhow::Context;
use super::Repository;
use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};
+use crate::shell_exec::Cmd;
+
+/// Result of the combined merge-tree + patch-id integration probe.
+///
+/// Encapsulates the two-step sequence: first try `merge-tree --write-tree` to
+/// check if merging would add anything, then fall back to patch-id matching
+/// when merge-tree conflicts.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MergeProbeResult {
+ /// Whether merging the branch into target would change the target's tree.
+ /// Always `true` when merge-tree conflicts (conservative).
+ pub would_merge_add: bool,
+ /// Whether patch-id matching found the branch's squashed diff in a target commit.
+ /// Only `true` when merge-tree conflicted AND patch-id found a match.
+ pub is_patch_id_match: bool,
+}
impl Repository {
/// Resolve a ref, preferring branches over tags when names collide.
@@ -128,42 +144,123 @@ impl Repository {
/// Check if merging a branch into target would add anything (not already integrated).
///
- /// Uses `git merge-tree` to simulate merging the branch into the target. If the
- /// resulting tree matches the target's tree, then merging would add nothing,
- /// meaning the branch's content is already integrated.
- ///
- /// This handles cases that simple tree comparison misses:
- /// - Squash-merged branches where main has advanced with additional commits
- /// - Rebased branches where the base has moved forward
+ /// Caller must pass resolved refs (via `resolve_preferring_branch`).
///
/// Returns:
- /// - `Ok(true)` if merging would change the target (branch has unintegrated changes)
- /// - `Ok(false)` if merging would NOT change target (branch is already integrated)
- /// - `Ok(true)` if merge would have conflicts (conservative: treat as not integrated)
- /// - `Err` if git commands fail
- pub fn would_merge_add_to_target(&self, branch: &str, target: &str) -> anyhow::Result<bool> {
- let branch = self.resolve_preferring_branch(branch);
- let target = self.resolve_preferring_branch(target);
+ /// - `Ok(Some(true))` if merging would change the target
+ /// - `Ok(Some(false))` if merging would NOT change target (branch is already integrated)
+ /// - `Ok(None)` if merge-tree conflicted (caller should try patch-id fallback)
+ fn would_merge_add_to_target(
+ &self,
+ branch: &str,
+ target: &str,
+ ) -> anyhow::Result<Option<bool>> {
// Simulate merging branch into target
// On conflict, merge-tree exits non-zero and we can't get a clean tree
- let merge_result = self.run_command(&["merge-tree", "--write-tree", &target, &branch]);
+ let merge_result = self.run_command(&["merge-tree", "--write-tree", target, branch]);
let Ok(merge_tree) = merge_result else {
- // merge-tree failed (likely conflicts) - conservatively treat as having changes
- return Ok(true);
+ // merge-tree failed (likely conflicts) — caller should try patch-id fallback
+ return Ok(None);
};
let merge_tree = merge_tree.trim();
if merge_tree.is_empty() {
// Empty output is unexpected - treat as having changes
- return Ok(true);
+ return Ok(Some(true));
}
// Get target's tree for comparison
let target_tree = self.rev_parse_tree(&format!("{target}^{{tree}}"))?;
// If merge result differs from target's tree, merging would add something
- Ok(merge_tree != target_tree)
+ Ok(Some(merge_tree != target_tree))
+ }
+
+ /// Detect squash merges via patch-id matching.
+ ///
+ /// Computes the combined diff of the entire branch (`diff-tree -p merge-base branch`)
+ /// and checks if any single commit on the target has the same patch-id. A match means
+ /// the target has a commit containing the exact same file changes as the whole branch
+ /// — i.e., a squash merge.
+ ///
+ /// Only runs when `merge-tree` conflicts (both sides modified the same files),
+ /// since `MergeAddsNothing` handles the non-conflict case. Cost scales with the
+ /// number of commits on target since the merge-base (`git log -p`).
+ ///
+ /// Returns `Ok(true)` if a matching squash-merge commit is found on the target,
+ /// `Ok(false)` otherwise (including when patch-id computation fails — conservative).
+ fn is_squash_merged_via_patch_id(&self, branch: &str, target: &str) -> anyhow::Result<bool> {
+ let Some(merge_base) = self.merge_base(target, branch)? else {
+ return Ok(false);
+ };
+
+ // Compute the squashed patch-id (combined diff of all branch changes).
+ let branch_diff = self.run_command(&["diff-tree", "-p", &merge_base, branch])?;
+ let branch_output = self.compute_patch_ids(&branch_diff)?;
+ let Some(branch_pid) = branch_output.split_whitespace().next() else {
+ return Ok(false);
+ };
+
+ // Get all target commits' patch-ids in one pass.
+ // `git log -p` pipes all patches through `git patch-id --verbatim`.
+ let target_log =
+ self.run_command(&["log", "-p", "--reverse", &format!("{merge_base}..{target}")])?;
+
+ let target_pids = self.compute_patch_ids(&target_log)?;
+
+ Ok(target_pids
+ .lines()
+ .any(|line| line.split_whitespace().next() == Some(branch_pid)))
+ }
+
+ /// Pipe diff content through `git patch-id --verbatim` and return the output.
+ ///
+ /// Uses `--verbatim` (not `--stable`) to avoid false positives from whitespace
+ /// normalization — `--stable` strips whitespace, so tabs-vs-spaces would produce
+ /// matching patch-ids even though the content differs.
+ fn compute_patch_ids(&self, diff: &str) -> anyhow::Result<String> {
+ let output = Cmd::new("git")
+ .args(["patch-id", "--verbatim"])
+ .current_dir(&self.discovery_path)
+ .context(self.logging_context())
+ .stdin_bytes(diff.to_owned())
+ .run()
+ .context("Failed to compute patch-id")?;
+ Ok(String::from_utf8_lossy(&output.stdout).into_owned())
+ }
+
+ /// Combined merge-tree + patch-id integration probe.
+ ///
+ /// Single implementation of the merge-tree → patch-id fallback sequence,
+ /// used by both `wt list` (parallel tasks) and `wt remove`/`wt merge`
+ /// (sequential via [`compute_integration_lazy`]).
+ pub fn merge_integration_probe(
+ &self,
+ branch: &str,
+ target: &str,
+ ) -> anyhow::Result<MergeProbeResult> {
+ let branch = self.resolve_preferring_branch(branch);
+ let target = self.resolve_preferring_branch(target);
+ let merge_result = self.would_merge_add_to_target(&branch, &target)?;
+ match merge_result {
+ Some(would_add) => Ok(MergeProbeResult {
+ would_merge_add: would_add,
+ is_patch_id_match: false,
+ }),
+ None => {
+ // merge-tree conflicted — try patch-id fallback.
+ // Patch-id errors are non-fatal: if we can't compute patch-ids,
+ // conservatively report no match (branch appears not integrated).
+ let matched = self
+ .is_squash_merged_via_patch_id(&branch, &target)
+ .unwrap_or(false);
+ Ok(MergeProbeResult {
+ would_merge_add: true,
+ is_patch_id_match: matched,
+ })
+ }
+ }
}
/// Determine the effective target for integration checks.
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index 09c5eec9b..e34754fdc 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -1168,6 +1168,91 @@ fn test_remove_squash_merged_then_main_advanced(repo: TestRepo) {
));
}
+/// Squash merge where target later modifies the SAME files (#1818).
+///
+/// This is the scenario from issue #1818:
+/// 1. Branch modifies file A
+/// 2. Squash-merge lands on main (file A matches branch content)
+/// 3. Main later modifies file A again (advancing past the squash merge)
+/// 4. `wt remove` should still detect integration
+///
+/// Previous behavior: `git merge-tree --write-tree` conflicts on file A because
+/// both sides changed it, and the code conservatively treats conflicts as
+/// "not integrated". The fix uses patch-id matching as a fallback.
+#[rstest]
+fn test_remove_squash_merged_then_same_files_modified(repo: TestRepo) {
+ // Create feature branch
+ repo.git_command()
+ .args(["checkout", "-b", "feature-squash-conflict"])
+ .run()
+ .unwrap();
+
+ // Make changes on feature branch (file A)
+ std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
+ repo.git_command()
+ .args(["add", "feature-a.txt"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .args(["commit", "-m", "Add feature A"])
+ .run()
+ .unwrap();
+
+ // Go back to main
+ repo.git_command().args(["checkout", "main"]).run().unwrap();
+
+ // Squash merge feature into main (simulating GitHub squash merge)
+ std::fs::write(repo.root_path().join("feature-a.txt"), "feature content").unwrap();
+ repo.git_command()
+ .args(["add", "feature-a.txt"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .args(["commit", "-m", "Add feature A (squash merged)"])
+ .run()
+ .unwrap();
+
+ // Main advances by modifying the SAME file (the key difference from the previous test)
+ std::fs::write(
+ repo.root_path().join("feature-a.txt"),
+ "feature content\nplus more changes on main",
+ )
+ .unwrap();
+ repo.git_command()
+ .args(["add", "feature-a.txt"])
+ .run()
+ .unwrap();
+ repo.git_command()
+ .args(["commit", "-m", "Main advances same file"])
+ .run()
+ .unwrap();
+
+ // Verify setup: merge-tree would conflict (this is the scenario from #1818)
+ let merge_tree_result = repo
+ .git_command()
+ .args([
+ "merge-tree",
+ "--write-tree",
+ "main",
+ "feature-squash-conflict",
+ ])
+ .run()
+ .unwrap();
+ assert!(
+ !merge_tree_result.status.success(),
+ "merge-tree should report conflicts (both sides modified feature-a.txt)"
+ );
+
+ // Remove the feature branch - should succeed because content is integrated
+ // (detected via patch-id fallback when merge-tree conflicts)
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "remove",
+ &["feature-squash-conflict"],
+ None
+ ));
+}
+
/// Simulate a GitHub squash merge: push feature to origin, squash-merge on
/// the remote side (via a temporary clone), fetch locally, then `wt remove`.
///
diff --git a/tests/integration_tests/step_prune.rs b/tests/integration_tests/step_prune.rs
index d1c06f194..f24299e24 100644
--- a/tests/integration_tests/step_prune.rs
+++ b/tests/integration_tests/step_prune.rs
@@ -515,6 +515,41 @@ fn test_prune_stale_plus_young(mut repo: TestRepo) {
));
}
+/// Prune detects squash-merged branches when target later modified the same files (#1818).
+///
+/// When `git merge-tree --write-tree` conflicts because the branch and target both
+/// changed the same files, the patch-id fallback detects the squash merge.
+#[rstest]
+fn test_prune_squash_merged_same_files_modified(mut repo: TestRepo) {
+ repo.commit("initial");
+
+ // Create worktree, make changes to a file
+ let wt_path = repo.add_worktree("feature-squash");
+ std::fs::write(wt_path.join("shared.txt"), "feature content").unwrap();
+ repo.run_git_in(&wt_path, &["add", "shared.txt"]);
+ repo.run_git_in(&wt_path, &["commit", "-m", "Add feature"]);
+
+ // Back on main: simulate squash merge (same content), then advance the same file
+ std::fs::write(repo.root_path().join("shared.txt"), "feature content").unwrap();
+ repo.run_git(&["add", "shared.txt"]);
+ repo.run_git(&["commit", "-m", "Squash merge feature"]);
+
+ std::fs::write(
+ repo.root_path().join("shared.txt"),
+ "feature content\nmore main changes",
+ )
+ .unwrap();
+ repo.run_git(&["add", "shared.txt"]);
+ repo.run_git(&["commit", "-m", "Advance same file on main"]);
+
+ assert_cmd_snapshot!(make_snapshot_cmd(
+ &repo,
+ "step",
+ &["prune", "--dry-run", "--min-age=0s"],
+ None
+ ));
+}
+
/// Default branch without a worktree should not be pruned despite being
/// trivially "integrated" into itself (tautological SameCommit).
#[test]
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
index b22637566..ba93f961f 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap
@@ -297,7 +297,7 @@ These values describe the relation to the default branch.
integration_reason values
-When main_state == "integrated": "ancestor" "trees_match" "no_added_changes" "merge_adds_nothing"
+When main_state == "integrated": "ancestor" "trees_match" "no_added_changes" "merge_adds_nothing" "patch-id-match"
ci.status values
diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
index 07f30ccd6..3e364d046 100644
--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap
@@ -333,7 +333,7 @@ These values describe the relation to the default branch.
integration_reason values
When main_state == "integrated": "ancestor" "trees_match" "no_added_changes"
-"merge_adds_nothing"
+"merge_adds_nothing" "patch-id-match"
ci.status values
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index 6319dbdaa..dd263499a 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -99,13 +99,14 @@ Force-delete an unmerged branch:
By default, branches are deleted when they would add no changes to the default branch if merged. This works with both unchanged git histories, and squash-merge or rebase workflows where commit history differs but file changes match.
-Worktrunk checks five conditions (in order of cost):
+Worktrunk checks six conditions (in order of cost):
1. Same commit — Branch HEAD equals the default branch. Shows _ in wt list.
2. Ancestor — Branch is in target's history (fast-forward or rebase case). Shows ⊂.
3. No added changes — Three-dot diff (target...branch) is empty. Shows ⊂.
4. Trees match — Branch tree SHA equals target tree SHA. Shows ⊂.
-5. Merge adds nothing — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced. Shows ⊂.
+5. Merge adds nothing — Simulated merge produces the same tree as target. Handles squash-merged branches where target has advanced with changes to different files. Shows ⊂.
+6. Patch-id match — Branch's entire diff matches a single squash-merge commit on target. Fallback for when the simulated merge conflicts because target later modified the same files the branch touched. Shows ⊂.
The 'same commit' check uses the local default branch; for other checks, 'target' means the default branch, or its upstream (e.g., origin/main) when strictly ahead.
diff --git a/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_same_files_modified.snap b/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_same_files_modified.snap
new file mode 100644
index 000000000..78341c19f
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__remove__remove_squash_merged_then_same_files_modified.snap
@@ -0,0 +1,46 @@
+---
+source: tests/integration_tests/remove.rs
+info:
+ program: wt
+ args:
+ - remove
+ - feature-squash-conflict
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ No worktree found for branch feature-squash-conflict
+✓ Removed branch feature-squash-conflict (all changes in main, ⊂)
diff --git a/tests/snapshots/integration__integration_tests__step_prune__prune_squash_merged_same_files_modified.snap b/tests/snapshots/integration__integration_tests__step_prune__prune_squash_merged_same_files_modified.snap
new file mode 100644
index 000000000..0701836ee
--- /dev/null
+++ b/tests/snapshots/integration__integration_tests__step_prune__prune_squash_merged_same_files_modified.snap
@@ -0,0 +1,48 @@
+---
+source: tests/integration_tests/step_prune.rs
+info:
+ program: wt
+ args:
+ - step
+ - prune
+ - "--dry-run"
+ - "--min-age=0s"
+ env:
+ APPDATA: "[TEST_CONFIG_HOME]"
+ CLICOLOR_FORCE: "1"
+ COLUMNS: "500"
+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
+ GIT_CONFIG_SYSTEM: /dev/null
+ GIT_EDITOR: ""
+ GIT_TERMINAL_PROMPT: "0"
+ HOME: "[TEST_HOME]"
+ LANG: C
+ LC_ALL: C
+ MOCK_CONFIG_DIR: "[MOCK_CONFIG_DIR]"
+ NO_COLOR: ""
+ PATH: "[PATH]"
+ PSModulePath: ""
+ RUST_LOG: warn
+ SHELL: ""
+ TERM: alacritty
+ USERPROFILE: "[TEST_HOME]"
+ WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
+ WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
+ WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
+ WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_NUSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
+---
+success: true
+exit_code: 0
+----- stdout -----
+
+----- stderr -----
+○ feature-squash — all changes in main
+↳ 1 worktree & branch would be removed (dry run)