Skip to content

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

perf(list): skip redundant MergeTreeConflicts on dirty worktrees (#2602)

Maximilian Roos8ce2c262d23f
diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rs
index b1a200f68..cbce51dad 100644
--- a/src/commands/list/collect/execution.rs
+++ b/src/commands/list/collect/execution.rs
@@ -375,11 +375,9 @@ pub fn work_items_for_worktree(
TaskKind::UserMarker,
TaskKind::WorkingTreeConflicts,
TaskKind::BranchDiff,
- // TODO: For dirty worktrees, WorkingTreeConflicts already runs merge-tree
- // (via stash-create + merge-tree). MergeTreeConflicts duplicates that call
- // against HEAD. Could skip MergeTreeConflicts when WorkingTreeConflicts
- // produces a non-None answer, but needs result-ordering changes since both
- // tasks run in parallel today.
+ // MergeTreeConflictsTask peeks the shared porcelain cache and
+ // skips its own merge-tree call when WorkingTreeConflictsTask
+ // will produce an authoritative dirty-tree result.
TaskKind::MergeTreeConflicts,
TaskKind::CiStatus,
TaskKind::WouldMergeAdd,
diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rs
index cbb37be43..c0a2cc7e7 100644
--- a/src/commands/list/collect/tasks.rs
+++ b/src/commands/list/collect/tasks.rs
@@ -542,6 +542,19 @@ impl Task for WorkingTreeDiffTask {
///
/// Uses default_branch (local main) for consistency with other Main subcolumn symbols.
/// Shows whether merging to your local main would conflict.
+///
+/// **Skip-when-dirty optimization:** for worktree items, peek at the shared
+/// porcelain cache. When the worktree is dirty (and has no unmerged
+/// entries), `WorkingTreeConflictsTask` will produce a `Some(Some(_))`
+/// dirty-tree result that is authoritative for tier 3 (`tier_would_conflict`
+/// short-circuits on `Some(Some(_))` and ignores the HEAD probe). Returning
+/// the redundant HEAD probe in that case would mean a second `git merge-tree`
+/// call against HEAD for the same row. Skip with a sentinel `false` —
+/// the value is ignored by the gate, and seeding `Some(false)` keeps the
+/// "loaded" invariant other gates expect.
+///
+/// Branch-only items have no working tree, so they fall through to the
+/// normal HEAD-vs-base merge-tree call.
pub struct MergeTreeConflictsTask;
impl Task for MergeTreeConflictsTask {
@@ -555,6 +568,21 @@ impl Task for MergeTreeConflictsTask {
has_merge_tree_conflicts: false,
});
};
+ // Skip-when-dirty: defer to WorkingTreeConflictsTask. Only when the
+ // worktree is dirty without unmerged entries — the unmerged path
+ // returns `Some(None)` from WorkingTreeConflictsTask, which falls
+ // back to this HEAD probe.
+ if let Some(wt) = ctx.branch_ref.working_tree(&ctx.repo) {
+ let porcelain = wt
+ .status_porcelain_cached()
+ .map_err(|e| ctx.error(Self::KIND, &e))?;
+ if !porcelain.trim().is_empty() && !has_unmerged_entries(&porcelain) {
+ return Ok(TaskResult::MergeTreeConflicts {
+ item_idx: ctx.item_idx,
+ has_merge_tree_conflicts: false,
+ });
+ }
+ }
let repo = &ctx.repo;
// Resolve via snapshot — see `branch_check_sha` for the
// rebase-in-progress rationale.
diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rs
index 02d1f2642..b9b65f606 100644
--- a/src/commands/list/model/state.rs
+++ b/src/commands/list/model/state.rs
@@ -298,7 +298,8 @@ pub fn tier_orphan(is_orphan: Option<bool>) -> Tier<MainState> {
}
}
-/// Tier 3: `WouldConflict`. Requires *both* conflict probes to be loaded.
+/// Tier 3: `WouldConflict`. Authoritative source depends on which probe
+/// landed.
///
/// `has_merge_tree_conflicts` is the committed-HEAD probe (from
/// `MergeTreeConflicts`). `has_working_tree_conflicts` is the dirty-tree
@@ -307,37 +308,42 @@ pub fn tier_orphan(is_orphan: Option<bool>) -> Tier<MainState> {
/// dirty-tree result, fall back to the HEAD probe), `Some(Some(b))` =
/// dirty-tree result.
///
+/// **The working-tree probe is authoritative when present.** A dirty
+/// worktree's tree includes HEAD's content plus any uncommitted changes,
+/// so its merge-tree result reflects the user's current state better than
+/// the HEAD-only probe. When `has_working_tree_conflicts` is
+/// `Some(Some(b))`, fire/rule out on `b` and ignore the HEAD probe.
+/// `MergeTreeConflictsTask` skips its merge-tree call in that case to
+/// avoid a redundant subprocess (returning a sentinel `false` that this
+/// gate ignores).
+///
/// Behavior:
-/// - If either probe reports `true`, fire `WouldConflict` — no need to
-/// wait for the other.
-/// - If the HEAD probe is `None`, wait (we can't rule out a conflict
-/// without it).
-/// - If the HEAD probe is `Some(false)` and the working-tree probe is
-/// `None`, wait — the working-tree result could still flip us to
-/// `WouldConflict`.
-/// - If both report "no conflict" (HEAD probe `Some(false)` and
-/// working-tree probe either `Some(None)` or `Some(Some(false))`), rule
-/// out.
+/// - `has_working_tree_conflicts == Some(Some(true))` → fire (dirty
+/// conflict, authoritative).
+/// - `has_working_tree_conflicts == Some(Some(false))` → rule out (dirty
+/// no-conflict, authoritative).
+/// - Otherwise consult the HEAD probe:
+/// - `Some(true)` → fire.
+/// - `Some(false)` and working-tree probe loaded (`Some(None)`, i.e.,
+/// clean or unmerged) → rule out.
+/// - `Some(false)` and working-tree probe still `None` → wait (the
+/// working-tree probe could still flip us).
+/// - `None` → wait.
pub fn tier_would_conflict(
has_merge_tree_conflicts: Option<bool>,
has_working_tree_conflicts: Option<Option<bool>>,
) -> Tier<MainState> {
- // Working-tree probe short-circuit: if it reports a dirty conflict,
- // fire regardless of the HEAD probe.
- if let Some(Some(true)) = has_working_tree_conflicts {
- return Tier::Fired(MainState::WouldConflict);
- }
- // HEAD probe short-circuit.
- match has_merge_tree_conflicts {
- Some(true) => return Tier::Fired(MainState::WouldConflict),
- Some(false) => {}
- None => return Tier::Wait,
- }
- // HEAD probe says "no conflict" — still need the working-tree probe
- // to complete (unless it's already reported a non-dirty result).
- match has_working_tree_conflicts {
- Some(_) => Tier::RuledOut,
- None => Tier::Wait,
+ use Tier::*;
+ match (has_merge_tree_conflicts, has_working_tree_conflicts) {
+ // Working-tree probe is authoritative when it reports a dirty result.
+ (_, Some(Some(true))) => Fired(MainState::WouldConflict),
+ (_, Some(Some(false))) => RuledOut,
+ // Otherwise consult HEAD probe.
+ (Some(true), _) => Fired(MainState::WouldConflict),
+ (Some(false), Some(None)) => RuledOut,
+ // HEAD says "no conflict" but WT hasn't reported — wait.
+ (Some(false), None) => Wait,
+ (None, _) => Wait,
}
}
@@ -781,12 +787,32 @@ mod tests {
// Some(None) meaning "working tree is clean, no dirty-tree
// result") → rule out.
assert_eq!(tier_would_conflict(Some(false), Some(None)), Tier::RuledOut);
- // HEAD probe says "no conflict" and WT probe reports a clean
- // dirty-tree result (Some(Some(false))) → rule out.
+ // WT probe reports a clean dirty-tree result (Some(Some(false)))
+ // → rule out, regardless of HEAD probe.
assert_eq!(
tier_would_conflict(Some(false), Some(Some(false))),
Tier::RuledOut
);
+ // WT probe is authoritative: rule out even when HEAD probe was
+ // skipped (None) because MergeTreeConflictsTask deferred to it.
+ assert_eq!(tier_would_conflict(None, Some(Some(false))), Tier::RuledOut);
+ // WT probe is authoritative: fire even when HEAD probe says no
+ // conflict (the dirty tree's merge result wins).
+ assert_eq!(
+ tier_would_conflict(Some(false), Some(Some(true))),
+ Tier::Fired(MainState::WouldConflict)
+ );
+ // WT probe is authoritative: rule out even when HEAD probe says
+ // "would conflict" (uncommitted changes resolve it). This
+ // combination shouldn't arise in production — the
+ // `MergeTreeConflictsTask` skip-when-dirty path keeps HEAD as a
+ // sentinel `false` whenever WT is `Some(Some(_))` — but pin the
+ // contract so a future refactor that reorders the matches
+ // doesn't silently regress.
+ assert_eq!(
+ tier_would_conflict(Some(true), Some(Some(false))),
+ Tier::RuledOut
+ );
// HEAD probe hasn't reported → wait (could flip us to conflict).
assert_eq!(tier_would_conflict(None, None), Tier::Wait);
assert_eq!(tier_would_conflict(None, Some(None)), Tier::Wait);
diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rs
index ed289c525..940cea81f 100644
--- a/src/commands/list/model/status_symbols.rs
+++ b/src/commands/list/model/status_symbols.rs
@@ -106,8 +106,11 @@
//! 1. `is_main == true` (metadata) → `^`. Always immediate for the main
//! worktree, regardless of any other field.
//! 2. `is_orphan == Some(true)` → orphan display.
-//! 3. `has_merge_tree_conflicts == Some(true)` or
-//! `has_working_tree_conflicts == Some(Some(true))` → `✗`.
+//! 3. `has_working_tree_conflicts == Some(Some(true))` (dirty-tree probe
+//! is authoritative when present) or `has_merge_tree_conflicts == Some(true)`
+//! → `✗`. When the dirty-tree probe says `Some(Some(false))` it rules
+//! out tier 3 even if the HEAD probe was skipped (see
+//! [`tier_would_conflict`](super::state::tier_would_conflict)).
//! 4. Distinguish Empty / SameCommitDirty / Integrated — requires `counts`,
//! `is_clean` (from `working_tree_diff` + `working_tree_status` for
//! worktrees; trivially clean for branches), and the integration signals.
diff --git a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
index f9f45de34..c7976c82b 100644
--- a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
+++ b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap
@@ -10,10 +10,15 @@ info:
COLUMNS: "500"
GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"
GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"
+ GIT_COMMON_DIR: ""
GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"
GIT_CONFIG_SYSTEM: /dev/null
+ GIT_DIR: ""
GIT_EDITOR: ""
+ GIT_INDEX_FILE: ""
+ GIT_OBJECT_DIRECTORY: ""
GIT_TERMINAL_PROMPT: "0"
+ GIT_WORK_TREE: ""
HOME: "[TEST_HOME]"
LANG: C
LC_ALL: C
@@ -29,13 +34,17 @@ info:
WORKTRUNK_APPROVALS_PATH: "[TEST_APPROVALS]"
WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"
WORKTRUNK_SYSTEM_CONFIG_PATH: "[TEST_SYSTEM_CONFIG]"
+ WORKTRUNK_TEST_BASH_INSTALLED: "0"
WORKTRUNK_TEST_CLAUDE_INSTALLED: "0"
WORKTRUNK_TEST_DELAYED_STREAM_MS: "-1"
WORKTRUNK_TEST_EPOCH: "1735776000"
+ WORKTRUNK_TEST_FISH_INSTALLED: "0"
WORKTRUNK_TEST_NUSHELL_ENV: "0"
WORKTRUNK_TEST_OPENCODE_INSTALLED: "0"
WORKTRUNK_TEST_POWERSHELL_ENV: "0"
+ WORKTRUNK_TEST_POWERSHELL_INSTALLED: "0"
WORKTRUNK_TEST_SKIP_URL_HEALTH_CHECK: "1"
+ WORKTRUNK_TEST_ZSH_INSTALLED: "0"
XDG_CONFIG_HOME: "[TEST_CONFIG_HOME]"
---
success: true
@@ -56,6 +65,6 @@ exit_code: 0
  (detached): ahead-behind (git merge-base failed for 05a4a45d0b981dad5c27db59dca482836d59f89e 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)
  (detached): committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000001^{tree}': unknown revision or path not in the working tree.)
  (detached): working-tree-diff (fatal: bad object HEAD)
-  (detached): merge-tree-conflicts (git merge-base failed for 05a4a45d0b981dad5c27db59dca482836d59f89e 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)
+  (detached): merge-tree-conflicts (fatal: bad object HEAD)
  (detached): working-tree-conflicts (fatal: bad object HEAD)
↳ To create a diagnostic file, run with -vv