Skip to content

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

fix(list): OR over local + upstream in integration column (#2513)

Maximilian Roos369923f53515
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index 7bdf8d4e8..d497e89f3 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -356,7 +356,7 @@ pub fn work_items_for_worktree(
item_url,
llm_command: options.llm_command.clone(),
default_branch: options.default_branch.clone(),
- integration_target: options.integration_target.clone(),
+ integration_targets: options.integration_targets.clone(),
};
let has_commits = wt.has_commits();
@@ -468,7 +468,7 @@ pub fn work_items_for_branch(
item_url: None, // Branches without worktrees don't have URLs
llm_command: options.llm_command.clone(),
default_branch: options.default_branch.clone(),
- integration_target: options.integration_target.clone(),
+ integration_targets: options.integration_targets.clone(),
};
let mut items = Vec::with_capacity(11);
@@ -545,7 +545,7 @@ mod tests {
url_template: Some("http://localhost/{{ branch }}".to_string()),
llm_command: None,
default_branch: None,
- integration_target: None,
+ integration_targets: None,
};
let expected_results = Arc::new(ExpectedResults::default());
@@ -589,7 +589,7 @@ mod tests {
llm_command: None,
url_template: None,
default_branch: None,
- integration_target: None,
+ integration_targets: None,
};
let expected_results = Arc::new(ExpectedResults::default());
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rs
index 050c2134f..f944e30fe 100644
--- a/src/commands/list/collect/mod.rs
+++ b/src/commands/list/collect/mod.rs
@@ -310,9 +310,11 @@ pub struct CollectOptions {
/// persisted value degrades silently (empty cells) here rather than
/// emitting a cascade of "ambiguous argument" errors from every task.
pub default_branch: Option<String>,
- /// Integration target (`default_branch`, or its upstream when ahead).
- /// `None` when the default branch is unset or stale.
- pub integration_target: Option<String>,
+ /// Integration targets resolved for this list invocation. The diverged
+ /// case carries both local and upstream so per-branch tasks can OR
+ /// over them, matching `Repository::integration_reason`. `None` when
+ /// the default branch is unset or stale.
+ pub integration_targets: Option<worktrunk::git::IntegrationTargets>,
}
fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> HashSet<&str> {
@@ -870,7 +872,7 @@ pub fn collect(
// Single-line invariant: use safe width to prevent line wrapping
let max_width = crate::display::terminal_width();
- // Create collection options from skip set. `integration_target` is
+ // Create collection options from skip set. `integration_targets` is
// patched in after the parallel phase below extracts it — at this
// point we haven't yet resolved it, but task spawning doesn't happen
// until line 1090+ so late population is safe.
@@ -879,7 +881,7 @@ pub fn collect(
url_template: url_template.clone(),
llm_command,
default_branch: default_branch.clone(),
- integration_target: None,
+ integration_targets: None,
};
// Track expected results per item - populated as spawns are queued
@@ -1004,7 +1006,8 @@ pub fn collect(
// See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's fsmonitor workaround)
// See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same fsmonitor issue)
let previous_branch_cell: OnceCell<Option<String>> = OnceCell::new();
- let integration_target_cell: OnceCell<Option<String>> = OnceCell::new();
+ let integration_targets_cell: OnceCell<Option<worktrunk::git::IntegrationTargets>> =
+ OnceCell::new();
rayon::scope(|s| {
// Previous branch lookup (for gutter symbol)
@@ -1012,9 +1015,10 @@ pub fn collect(
let _ = previous_branch_cell.set(repo.switch_previous());
});
- // Integration target (upstream if ahead of local, else local)
+ // Integration targets (primary plus optional secondary in the
+ // diverged case — see `Repository::integration_targets`).
s.spawn(|_| {
- let _ = integration_target_cell.set(repo.integration_target());
+ let _ = integration_targets_cell.set(repo.integration_targets());
});
// Fsmonitor daemon starts (one spawn per worktree)
@@ -1027,16 +1031,16 @@ pub fn collect(
// Extract results from cells
let previous_branch = previous_branch_cell.into_inner().flatten();
- let integration_target = integration_target_cell.into_inner().flatten();
+ let integration_targets = integration_targets_cell.into_inner().flatten();
- // Patch integration_target into options now that it's resolved. When
- // default_branch is None (unset or stale), also null it out — tasks
- // otherwise see a target derived from the stale value and emit
+ // Patch integration_targets into options now that they're resolved.
+ // When default_branch is None (unset or stale), also null it out —
+ // tasks otherwise see a target derived from the stale value and emit
// "ambiguous argument" noise.
- options.integration_target = options
+ options.integration_targets = options
.default_branch
.as_ref()
- .and(integration_target.clone());
+ .and(integration_targets.clone());
// Update is_previous on items
if let Some(prev) = previous_branch.as_deref() {
@@ -1203,13 +1207,15 @@ pub fn collect(
let reveal_at = (progressive_state.is_some() || progressive_handler.is_some())
.then_some(placeholder_reveal_at);
+ let primary_target = integration_targets.as_ref().map(|t| t.primary.as_str());
+
let drain_outcome = drain_results(
rx,
&mut all_items,
&mut errors,
&expected_results,
drain_deadline,
- integration_target.as_deref(),
+ primary_target,
|event| {
let dim = Style::new().dimmed();
let total_results = expected_results.count();
@@ -1379,7 +1385,7 @@ pub fn collect(
// pre-seeded main_state for unborn/prunable items) still materialize.
// The call is idempotent — already-resolved gates are skipped.
for item in all_items.iter_mut() {
- item.refresh_status_symbols(integration_target.as_deref());
+ item.refresh_status_symbols(primary_target);
}
// Count errors for summary
@@ -1607,11 +1613,11 @@ pub fn populate_item(
return Ok(());
};
- // Get integration target for status symbol computation (cached in repo)
+ // Get integration targets for status symbol computation (cached in repo)
// None if default branch cannot be determined - status symbols will be skipped
- let target = repo.integration_target();
+ let targets = repo.integration_targets();
- // Populate default_branch / integration_target if the caller didn't.
+ // Populate default_branch / integration_targets if the caller didn't.
// Tasks read these through `TaskContext`; `None` here tells them to
// skip (see collect()'s stale-default-branch path). Single-item callers
// like statusline pass `CollectOptions::default()` and expect the
@@ -1619,8 +1625,8 @@ pub fn populate_item(
if options.default_branch.is_none() {
options.default_branch = repo.default_branch();
}
- if options.integration_target.is_none() {
- options.integration_target = target.clone();
+ if options.integration_targets.is_none() {
+ options.integration_targets = targets.clone();
}
// Create channel for task results
@@ -1678,7 +1684,7 @@ pub fn populate_item(
&mut errors,
&expected_results,
std::time::Instant::now() + results::DRAIN_TIMEOUT,
- target.as_deref(),
+ targets.as_ref().map(|t| t.primary.as_str()),
|_event| {},
None,
);
@@ -1707,7 +1713,7 @@ pub fn populate_item(
// Ensure status symbols are refreshed even if all tasks errored
// (the drain only calls refresh on the success path).
- item.refresh_status_symbols(target.as_deref());
+ item.refresh_status_symbols(targets.as_ref().map(|t| t.primary.as_str()));
// Populate display fields (including status_line for statusline command)
item.finalize_display();
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index 591378122..f5a0f8857 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -7,7 +7,7 @@ use std::net::{SocketAddr, TcpStream};
use std::time::Duration;
use anyhow::Context;
-use worktrunk::git::{LineDiff, Repository};
+use worktrunk::git::{IntegrationTargets, LineDiff, Repository};
use super::super::ci_status::{CiBranchName, PrStatus};
use super::super::model::{
@@ -24,7 +24,7 @@ use super::types::{ErrorCause, TaskError, TaskKind, TaskResult};
/// Contains all data needed by any task. The `repo` field shares its cache
/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from
/// cached merge-base results, ahead/behind counts, default branch, and
-/// integration target.
+/// integration targets.
#[derive(Clone)]
pub struct TaskContext {
/// Shared repository handle. All clones share the same cache via Arc.
@@ -48,11 +48,14 @@ pub struct TaskContext {
/// degrades silently (empty cells) here rather than emitting a cascade
/// of "ambiguous argument" errors.
pub default_branch: Option<String>,
- /// Integration target (`default_branch`, or its upstream when ahead).
- /// `None` when the default branch is unset or stale — keeps the same
- /// silent-skip contract as `default_branch` for tasks that compare
- /// against the integration target.
- pub integration_target: Option<String>,
+ /// Integration targets for this list invocation. Carries the primary
+ /// ref the column is reported against, plus an optional secondary ref
+ /// to also check (only set when local and upstream have diverged). A
+ /// branch is treated as integrated if it is integrated against either
+ /// — same OR semantics as `Repository::integration_reason`. `None`
+ /// when the default branch is unset or stale, keeping the same
+ /// silent-skip contract as `default_branch`.
+ pub integration_targets: Option<IntegrationTargets>,
}
impl TaskContext {
@@ -85,12 +88,12 @@ impl TaskContext {
self.default_branch.clone()
}
- /// Get the integration target resolved for this list invocation.
+ /// Get the integration targets resolved for this list invocation.
///
/// Used for integration checks (status symbols, safe deletion).
/// Returns `None` if default branch cannot be determined or is stale.
- pub(super) fn integration_target(&self) -> Option<String> {
- self.integration_target.clone()
+ pub(super) fn integration_targets(&self) -> Option<&IntegrationTargets> {
+ self.integration_targets.as_ref()
}
}
@@ -175,15 +178,17 @@ impl Task for AheadBehindTask {
/// Task 3: Tree identity check (does the item's commit tree match integration target's tree?)
///
-/// Uses target for integration detection (squash merge, rebase).
+/// Uses target for integration detection (squash merge, rebase). When local
+/// and upstream have diverged, ORs across both — a tree match against either
+/// counts as integrated, matching `Repository::integration_reason`.
pub struct CommittedTreesMatchTask;
impl Task for CommittedTreesMatchTask {
const KIND: TaskKind = TaskKind::CommittedTreesMatch;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- // When integration_target is None, return false (conservative: don't mark as integrated)
- let Some(base) = ctx.integration_target() else {
+ // When integration_targets is None, return false (conservative: don't mark as integrated)
+ let Some(targets) = ctx.integration_targets() else {
return Ok(TaskResult::CommittedTreesMatch {
item_idx: ctx.item_idx,
committed_trees_match: false,
@@ -198,9 +203,14 @@ impl Task for CommittedTreesMatchTask {
.branch_ref
.full_ref()
.unwrap_or(&ctx.branch_ref.commit_sha);
- let committed_trees_match = repo
- .trees_match(ref_to_check, &base)
+ let mut committed_trees_match = repo
+ .trees_match(ref_to_check, &targets.primary)
.map_err(|e| ctx.error(Self::KIND, &e))?;
+ if !committed_trees_match && let Some(secondary) = targets.secondary.as_deref() {
+ committed_trees_match = repo
+ .trees_match(ref_to_check, secondary)
+ .map_err(|e| ctx.error(Self::KIND, &e))?;
+ }
Ok(TaskResult::CommittedTreesMatch {
item_idx: ctx.item_idx,
committed_trees_match,
@@ -232,17 +242,25 @@ impl Task for HasFileChangesTask {
has_file_changes: true,
});
};
- // When integration_target is None, return true (conservative: assume has changes)
- let Some(target) = ctx.integration_target() else {
+ // When integration_targets is None, return true (conservative: assume has changes)
+ let Some(targets) = ctx.integration_targets() else {
return Ok(TaskResult::HasFileChanges {
item_idx: ctx.item_idx,
has_file_changes: true,
});
};
let repo = &ctx.repo;
- let has_file_changes = repo
- .has_added_changes(branch, &target)
+ // The branch is integrated (no added changes) if it has none against
+ // EITHER target. AND the per-target booleans so the combined value is
+ // false (== integrated) as soon as a single side has nothing to add.
+ let mut has_file_changes = repo
+ .has_added_changes(branch, &targets.primary)
.map_err(|e| ctx.error(Self::KIND, &e))?;
+ if has_file_changes && let Some(secondary) = targets.secondary.as_deref() {
+ has_file_changes = repo
+ .has_added_changes(branch, secondary)
+ .map_err(|e| ctx.error(Self::KIND, &e))?;
+ }
Ok(TaskResult::HasFileChanges {
item_idx: ctx.item_idx,
@@ -280,22 +298,39 @@ impl Task for WouldMergeAddTask {
is_patch_id_match: false,
});
};
- // When integration_target is None, return true (conservative: assume would add)
- let Some(base) = ctx.integration_target() else {
+ // When integration_targets is None, return true (conservative: assume would add)
+ let Some(targets) = ctx.integration_targets() else {
return Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
would_merge_add: true,
is_patch_id_match: false,
});
};
+ // Combine probes the same way `compute_integration_reason_uncached`
+ // ORs the two `check_integration` calls: a branch is integrated if
+ // merging would add nothing OR a patch-id matches against EITHER
+ // side. So `would_merge_add` ANDs (false on either ⇒ integrated)
+ // and `is_patch_id_match` ORs.
let probe = ctx
.repo
- .merge_integration_probe(branch, &base)
+ .merge_integration_probe(branch, &targets.primary)
.map_err(|e| ctx.error(Self::KIND, &e))?;
+ let mut would_merge_add = probe.would_merge_add;
+ let mut is_patch_id_match = probe.is_patch_id_match;
+ if let Some(secondary) = targets.secondary.as_deref()
+ && (would_merge_add && !is_patch_id_match)
+ {
+ let alt = ctx
+ .repo
+ .merge_integration_probe(branch, secondary)
+ .map_err(|e| ctx.error(Self::KIND, &e))?;
+ would_merge_add = would_merge_add && alt.would_merge_add;
+ is_patch_id_match = is_patch_id_match || alt.is_patch_id_match;
+ }
Ok(TaskResult::WouldMergeAdd {
item_idx: ctx.item_idx,
- would_merge_add: probe.would_merge_add,
- is_patch_id_match: probe.is_patch_id_match,
+ would_merge_add,
+ is_patch_id_match,
})
}
}
@@ -314,8 +349,8 @@ impl Task for IsAncestorTask {
const KIND: TaskKind = TaskKind::IsAncestor;
fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {
- // When integration_target is None, return false (conservative: don't mark as ancestor)
- let Some(base) = ctx.integration_target() else {
+ // When integration_targets is None, return false (conservative: don't mark as ancestor)
+ let Some(targets) = ctx.integration_targets() else {
return Ok(TaskResult::IsAncestor {
item_idx: ctx.item_idx,
is_ancestor: false,
@@ -328,9 +363,14 @@ impl Task for IsAncestorTask {
.branch_ref
.full_ref()
.unwrap_or(&ctx.branch_ref.commit_sha);
- let is_ancestor = repo
- .is_ancestor(ref_to_check, &base)
+ let mut is_ancestor = repo
+ .is_ancestor(ref_to_check, &targets.primary)
.map_err(|e| ctx.error(Self::KIND, &e))?;
+ if !is_ancestor && let Some(secondary) = targets.secondary.as_deref() {
+ is_ancestor = repo
+ .is_ancestor(ref_to_check, secondary)
+ .map_err(|e| ctx.error(Self::KIND, &e))?;
+ }
Ok(TaskResult::IsAncestor {
item_idx: ctx.item_idx,
diff --git a/src/git/mod.rs b/src/git/mod.rs
index 36e9bf510..9efc53516 100644
--- a/src/git/mod.rs
+++ b/src/git/mod.rs
@@ -62,7 +62,9 @@ pub use remove::{
delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,
};
pub use repository::sha_cache;
-pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};
+pub use repository::{
+ Branch, IntegrationTargets, Repository, ResolvedWorktree, WorkingTree, set_base_path,
+};
pub use url::GitRemoteUrl;
pub use url::parse_owner_repo;
/// Why branch content is considered integrated into the target branch.
diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rs
index 9228ceec2..3404a0e4a 100644
--- a/src/git/repository/integration.rs
+++ b/src/git/repository/integration.rs
@@ -11,6 +11,20 @@ use super::Repository;
use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};
use crate::shell_exec::Cmd;
+/// Integration targets for `wt list`'s status column.
+///
+/// In the diverged case (local and upstream both have unique commits), the
+/// safety path ORs over both — so the column needs to consider both, too.
+/// Every other case collapses to a single target. See
+/// [`Repository::integration_targets`] for the resolution rules.
+#[derive(Debug, Clone)]
+pub struct IntegrationTargets {
+ /// Primary target — the only ref to check unless `secondary` is set.
+ pub primary: String,
+ /// Secondary target, only set in the diverged case.
+ pub secondary: Option<String>,
+}
+
/// Result of the combined merge-tree + patch-id integration probe.
///
/// Encapsulates the two-step sequence: first try `merge-tree --write-tree` to
@@ -505,6 +519,40 @@ impl Repository {
.clone()
}
+ /// Resolve the integration targets for `wt list`'s status column.
+ ///
+ /// Mirrors the local/upstream branching in
+ /// [`Self::integration_reason`] so the column's yes/no answer agrees
+ /// with the safety path in `wt remove` / `wt merge`. The relationship
+ /// determines whether a single ref or a (primary, secondary) pair is
+ /// returned:
+ ///
+ /// - No upstream / local==upstream: primary = local, secondary = None.
+ /// - Local strictly behind upstream: primary = upstream (superset).
+ /// - Upstream strictly behind local: primary = local (superset).
+ /// - Diverged: primary = local, secondary = upstream — both are checked
+ /// so a branch merged into either side counts as integrated.
+ ///
+ /// Ancestry probes use `ref_is_ancestor` (raw git, no SHA caching) so
+ /// a just-updated local target's relationship is observed correctly,
+ /// matching [`Self::integration_reason`].
+ ///
+ /// Returns `None` when the default branch cannot be determined.
+ pub fn integration_targets(&self) -> Option<IntegrationTargets> {
+ let target = self.default_branch()?;
+ let upstream = self.branch(&target).upstream().ok().flatten();
+
+ let (primary, secondary) = match upstream {
+ None => (target, None),
+ Some(u) if self.same_commit(&target, &u).unwrap_or(false) => (target, None),
+ Some(u) if ref_is_ancestor(self, &target, &u) => (u, None),
+ Some(u) if ref_is_ancestor(self, &u, &target) => (target, None),
+ Some(u) => (target, Some(u)),
+ };
+
+ Some(IntegrationTargets { primary, secondary })
+ }
+
/// Parse a tree ref to get its SHA (cached).
pub(super) fn rev_parse_tree(&self, spec: &str) -> anyhow::Result<String> {
match self.cache.tree_shas.entry(spec.to_string()) {
diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rs
index 0d781a8f7..235fbd1b0 100644
--- a/src/git/repository/mod.rs
+++ b/src/git/repository/mod.rs
@@ -109,6 +109,7 @@ mod worktrees;
// Re-export WorkingTree and Branch
pub use branch::Branch;
+pub use integration::IntegrationTargets;
pub use working_tree::WorkingTree;
pub(super) use working_tree::path_to_logging_context;
diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rs
index 4cbca8b64..225c41bc2 100644
--- a/tests/integration_tests/list.rs
+++ b/tests/integration_tests/list.rs
@@ -3229,3 +3229,181 @@ fn test_list_empty_repo_json() {
assert_eq!(item["commit"]["sha"], "");
assert_eq!(item["commit"]["short_sha"], "");
}
+
+/// Regression: the `wt list` integration column ORs over local AND upstream,
+/// matching `Repository::integration_reason`. A branch whose content lives in
+/// LOCAL `main` (via a merge commit) must still render as integrated when
+/// `main` and `origin/main` have diverged — symmetric to the merged-on-remote
+/// case covered by `test_list_integrated_when_squash_merged_on_remote_with_local_diverged`
+/// below. Mirrors `test_remove_merged_locally_when_upstream_diverged` in
+/// `remove.rs`.
+///
+/// Uses `--no-ff` so the feature ref's HEAD differs from `main`'s HEAD: the
+/// `IsAncestor` parallel task is the load-bearing signal here, exercising the
+/// OR-over-targets fix. A `--ff-only` merge would collapse to "same commit"
+/// (`MainState::Empty`), which already worked because counts are computed
+/// against the default branch directly.
+#[rstest]
+fn test_list_integrated_when_merged_locally_with_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-list-local-merge");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-list-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 with --no-ff so feature HEAD is an
+ // ancestor of (but not equal to) main HEAD.
+ repo.add_worktree("feature-list-local");
+ let feature_path = repo.worktree_path("feature-list-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-list-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 = repo
+ .wt_command()
+ .args(["list", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "wt list should succeed");
+
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json
+ .iter()
+ .find(|w| w["branch"] == "feature-list-local")
+ .expect("feature-list-local should appear in wt list output");
+
+ assert_eq!(
+ feature["main_state"], "integrated",
+ "main_state must be \"integrated\" when local main contains the feature \
+ even though origin/main has diverged — instead got entry: {feature}"
+ );
+ assert!(
+ !feature["integration_reason"].is_null(),
+ "integration_reason must be set — instead got entry: {feature}"
+ );
+}
+
+/// Regression companion to the test above: branch squash-merged on
+/// `origin/main` must still render as integrated when local `main` has its own
+/// unique commits (the diverged case where the safety path used to be the
+/// only way to spot the merge). Mirrors
+/// `test_remove_squash_merged_on_remote_when_local_main_diverged`.
+#[rstest]
+fn test_list_integrated_when_squash_merged_on_remote_with_local_diverged(
+ #[from(repo_with_remote)] repo: TestRepo,
+) {
+ let remote_path = repo.remote_path().unwrap().to_path_buf();
+
+ // Build, push, and remote-squash-merge a feature branch.
+ repo.run_git(&["checkout", "-b", "feature-list-remote-squash"]);
+ std::fs::write(repo.root_path().join("feature-remote.txt"), "initial").unwrap();
+ repo.run_git(&["add", "feature-remote.txt"]);
+ repo.run_git(&["commit", "-m", "Add feature"]);
+ std::fs::write(repo.root_path().join("feature-remote.txt"), "final").unwrap();
+ repo.run_git(&["add", "feature-remote.txt"]);
+ repo.run_git(&["commit", "-m", "Finalize feature"]);
+ repo.run_git(&["push", "-u", "origin", "feature-list-remote-squash"]);
+ repo.run_git(&["checkout", "main"]);
+
+ let github_sim = repo.home_path().join("github-sim-list-remote-squash");
+ repo.run_git_in(
+ repo.home_path(),
+ &[
+ "clone",
+ remote_path.to_str().unwrap(),
+ "github-sim-list-remote-squash",
+ ],
+ );
+ repo.run_git_in(
+ &github_sim,
+ &["merge", "--squash", "origin/feature-list-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; then 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 = repo
+ .wt_command()
+ .args(["list", "--branches", "--format=json"])
+ .output()
+ .unwrap();
+ assert!(output.status.success(), "wt list should succeed");
+
+ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();
+ let feature = json
+ .iter()
+ .find(|w| w["branch"] == "feature-list-remote-squash")
+ .expect("feature-list-remote-squash should appear in wt list output");
+
+ assert!(
+ !feature["integration_reason"].is_null(),
+ "integration_reason must be set for a remotely-squash-merged branch even when \
+ local main has diverged — instead got entry: {feature}"
+ );
+ assert_eq!(
+ feature["main_state"], "integrated",
+ "main_state must be \"integrated\" — instead got entry: {feature}"
+ );
+}