Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor: delete dead code paths left by completed cut-overs (#2931)
Maximilian Roos5eb17d441b81
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 375989257..bd17e053f 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -245,7 +245,7 @@//! ### Cached via tree SHA//!//! `WorkingTreeConflicts` uses `git write-tree` to snapshot the index as a tree SHA,-//! then checks for merge conflicts via `has_merge_conflicts_by_tree`. The tree SHA is+//! then checks for merge conflicts via `has_merge_conflicts_by_tree_with_base_sha`. The tree SHA is//! content-addressed and stable — identical index state produces the same SHA.//!//! When there are unstaged modifications or untracked files, the task copies the@@ -253,7 +253,7 @@//! then `write-tree`.//!//! The cache key is `(base_commit_sha, branch_head_sha+tree_sha)`. The branch HEAD-//! SHA captures the merge-base dependency. On cache miss, `has_merge_conflicts_by_tree`+//! SHA captures the merge-base dependency. On cache miss, `has_merge_conflicts_by_tree_with_base_sha`//! creates an ephemeral commit via `git commit-tree` for merge-tree; on cache hit,//! no commit is created. This makes the cache-hit path a single `git write-tree`//! (~15ms) instead of the previous `git stash create` (~50-265ms).@@ -293,7 +293,7 @@ use worktrunk::styling::{use crate::commands::is_worktree_at_expected_path;-use super::model::{CommitDetails, DisplayFields, ItemKind, ListItem, StatusSymbols, WorktreeData};+use super::model::{CommitDetails, ItemKind, ListItem, StatusSymbols, WorktreeData};use super::progressive::RenderTarget;use super::progressive_table::ProgressiveTable;@@ -1004,7 +1004,7 @@ pub fn collect(has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(worktree_data)),}})@@ -1821,7 +1821,7 @@ pub fn build_worktree_item(has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData::from_worktree(wt,is_main,diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex 5c53082fc..2257fa1da 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -344,7 +344,7 @@ impl Task for HasFileChangesTask {/// Task 3b: Merge simulation + patch-id fallback///-/// Delegates to [`Repository::merge_integration_probe()`], which runs:+/// Delegates to [`Repository::merge_integration_probe_by_sha()`], which runs:////// 1. `merge-tree --write-tree` — simulates merging branch into target. If the/// result tree equals target's tree, the branch is integrated (`MergeAddsNothing`).diff --git a/src/commands/list/json_output.rs b/src/commands/list/json_output.rsindex 45277e79c..be1ca792b 100644--- a/src/commands/list/json_output.rs+++ b/src/commands/list/json_output.rs@@ -339,7 +339,7 @@ impl JsonItem {.map(JsonCi::from);// Statusline and symbols (raw, without ANSI codes)- let statusline = item.display.statusline.clone();+ let statusline = item.statusline.clone();let symbols = Some(format_raw_symbols(&item.status_symbols)).filter(|s| !s.is_empty());// Per-branch vars data (pre-fetched, moved out to avoid cloning)@@ -650,7 +650,6 @@ mod tests {has_working_tree_conflicts: None,git_operation: Some(ActiveGitOperation::None),branch_worktree_mismatch: false,- working_diff_display: None,}}diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex aa103a305..ad5016e9f 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -304,14 +304,13 @@ pub struct DiffDisplayConfig {pub variant: DiffVariant,pub positive_style: Style,pub negative_style: Style,- pub always_show_zeros: bool,}impl DiffDisplayConfig {/// Format diff values with fixed-width alignment for tabular display.////// Numbers are right-aligned within a 3-digit column width.- /// Returns empty spaces if both values are zero (unless `always_show_zeros` is set).+ /// Returns empty spaces if both values are zero.#[cfg(unix)] // Only used by picker module which is unix-onlypub fn format_aligned(&self, positive: usize, negative: usize) -> String {const DIGITS: usize = 3;@@ -331,17 +330,17 @@ impl DiffDisplayConfig {/// Format diff values as plain text with ANSI colors (no fixed-width alignment).///- /// Returns `None` if both values are zero (unless `always_show_zeros` is set).+ /// Returns `None` if both values are zero./// Format: `+N -M` with appropriate colors for each component.pub fn format_plain(&self, positive: usize, negative: usize) -> Option<String> {- if !self.always_show_zeros && positive == 0 && negative == 0 {+ if positive == 0 && negative == 0 {return None;}let symbols = self.variant.symbols();let mut parts = Vec::with_capacity(2);- if positive > 0 || self.always_show_zeros {+ if positive > 0 {parts.push(format!("{}{}{}{}",self.positive_style,@@ -351,7 +350,7 @@ impl DiffDisplayConfig {));}- if negative > 0 || self.always_show_zeros {+ if negative > 0 {parts.push(format!("{}{}{}{}",self.negative_style,@@ -401,19 +400,16 @@ impl ColumnKind {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,}),ColumnKind::AheadBehind => Some(DiffDisplayConfig {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: DELETION.dimmed(),- always_show_zeros: false,}),ColumnKind::Upstream => Some(DiffDisplayConfig {variant: DiffVariant::UpstreamArrows,positive_style: ADDITION,negative_style: DELETION.dimmed(),- always_show_zeros: false, // 0/0 case handled specially with | symbol}),_ => None,}@@ -1296,8 +1292,8 @@ mod tests {#[test]fn test_visible_columns_follow_gap_rule() {use crate::commands::list::model::{- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,- ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,+ ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, ItemKind, ListItem,+ StatusSymbols, UpstreamStatus, WorktreeData,};// Create test data with specific widths to verify position calculation@@ -1334,7 +1330,7 @@ mod tests {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test/path"),detached: false,@@ -1349,7 +1345,6 @@ mod tests {is_current: false,is_previous: false,branch_worktree_mismatch: false,- working_diff_display: None,})),};@@ -1406,8 +1401,8 @@ mod tests {#[test]fn test_column_positions_with_empty_columns() {use crate::commands::list::model::{- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,- ItemKind, ListItem, StatusSymbols, UpstreamStatus, WorktreeData,+ ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, ItemKind, ListItem,+ StatusSymbols, UpstreamStatus, WorktreeData,};// Create minimal data - most columns will be empty@@ -1440,7 +1435,7 @@ mod tests {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test"),detached: false,@@ -1455,7 +1450,6 @@ mod tests {is_current: false,is_previous: false,branch_worktree_mismatch: false,- working_diff_display: None,})),};@@ -1537,7 +1531,7 @@ mod tests {/// Helper: create a minimal ListItem for layout tests.fn make_test_item(branch: &str) -> super::super::model::ListItem {use crate::commands::list::model::{- ActiveGitOperation, DisplayFields, ItemKind, StatusSymbols, WorktreeData,+ ActiveGitOperation, ItemKind, StatusSymbols, WorktreeData,};super::super::model::ListItem {head: "abc12345".to_string(),@@ -1560,7 +1554,7 @@ mod tests {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from("/test/wt"),detached: false,@@ -1575,7 +1569,6 @@ mod tests {is_current: false,is_previous: false,branch_worktree_mismatch: false,- working_diff_display: None,})),}}@@ -1785,7 +1778,7 @@ mod tests {/// Helper: create a test item with a specific worktree path and no mismatch.fn make_test_item_at(branch: &str, path: &str) -> super::super::model::ListItem {use crate::commands::list::model::{- ActiveGitOperation, DisplayFields, ItemKind, StatusSymbols, WorktreeData,+ ActiveGitOperation, ItemKind, StatusSymbols, WorktreeData,};super::super::model::ListItem {head: "abc12345".to_string(),@@ -1808,7 +1801,7 @@ mod tests {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from(path),detached: false,@@ -1823,7 +1816,6 @@ mod tests {is_current: false,is_previous: false,branch_worktree_mismatch: false,- working_diff_display: None,})),}}@@ -1886,8 +1878,8 @@ mod tests {#[test]fn test_snapshot_path_yields_to_summary() {use crate::commands::list::model::{- ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, DisplayFields,- ItemKind, StatusSymbols, UpstreamStatus, WorktreeData,+ ActiveGitOperation, AheadBehind, BranchDiffTotals, CommitDetails, ItemKind,+ StatusSymbols, UpstreamStatus, WorktreeData,};use worktrunk::git::LineDiff;@@ -1940,7 +1932,7 @@ mod tests {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Worktree(Box::new(WorktreeData {path: PathBuf::from(path),detached: false,@@ -1955,7 +1947,6 @@ mod tests {is_current,is_previous: false,branch_worktree_mismatch: false,- working_diff_display: None,})),}};diff --git a/src/commands/list/model/item.rs b/src/commands/list/model/item.rsindex 2b561f878..0f9cffb50 100644--- a/src/commands/list/model/item.rs+++ b/src/commands/list/model/item.rs@@ -13,75 +13,6 @@ use super::status_symbols::{StatusSymbols, WorkingTreeStatus};use crate::commands::list::ci_status::PrStatus;use crate::commands::list::columns::ColumnKind;-/// Display fields shared between WorktreeInfo and BranchInfo-/// These contain formatted strings with ANSI colors for json-pretty output-#[derive(Clone, serde::Serialize, Default)]-pub struct DisplayFields {- #[serde(skip_serializing_if = "Option::is_none")]- pub commits_display: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub branch_diff_display: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub upstream_display: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub ci_status_display: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]- pub status_display: Option<String>,- /// Pre-formatted single-line representation for statusline tools.- /// Format: `branch status @working commits ^branch_diff upstream ci` (2-space separators)- ///- /// Use via JSON: `wt list --format=json | jq '.[] | select(.is_current) | .statusline'`- #[serde(skip_serializing_if = "Option::is_none")]- pub statusline: Option<String>,-}--impl DisplayFields {- pub(crate) fn from_common_fields(- counts: &Option<AheadBehind>,- branch_diff: &Option<BranchDiffTotals>,- upstream: &Option<UpstreamStatus>,- ) -> Self {- let commits_display = counts- .as_ref()- .and_then(|c| ColumnKind::AheadBehind.format_diff_plain(c.ahead, c.behind));-- let branch_diff_display = branch_diff.as_ref().and_then(|bd| {- ColumnKind::BranchDiff.format_diff_plain(bd.diff.added, bd.diff.deleted)- });-- let upstream_display = upstream.as_ref().and_then(|u| {- u.active().and_then(|active| {- ColumnKind::Upstream.format_diff_plain(active.ahead, active.behind)- })- });-- Self {- commits_display,- branch_diff_display,- upstream_display,- // CI renders via render_indicator() in render.rs, not as display text- ci_status_display: None,- status_display: None,- statusline: None,- }- }-}--/// Serde helper: skip `git_operation` when it is absent (unloaded) or an-/// active `ActiveGitOperation::None` — preserving the original-/// `skip_serializing_if = "ActiveGitOperation::is_none"` behavior now that-/// the field is wrapped in `Option`.-// `clippy::ref_option` fires because we take `&Option<T>` instead of-// `Option<&T>`, but `skip_serializing_if` calls this with `&field`, so the-// signature is forced by serde.-#[allow(clippy::ref_option)]-fn git_operation_is_none_or_unloaded(op: &Option<ActiveGitOperation>) -> bool {- match op {- None => true,- Some(inner) => inner.is_none(),- }-}-/// Compute the `WorktreeState` from `WorktreeData` metadata alone.////// Used by both `compute_status_symbols` (full computation) and the@@ -100,48 +31,36 @@ fn metadata_worktree_state(data: &WorktreeData) -> WorktreeState {}/// Type-specific data for worktrees-#[derive(Clone, serde::Serialize, Default)]+#[derive(Clone, Default)]pub struct WorktreeData {pub path: PathBuf,pub detached: bool,- #[serde(skip_serializing_if = "Option::is_none")]pub locked: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]pub prunable: Option<String>,- #[serde(skip_serializing_if = "Option::is_none")]pub working_tree_diff: Option<LineDiff>,/// Working-tree change flags (tracked/untracked/modified). `None` = not yet/// loaded; `Some` = loaded (possibly empty). Fed by the `WorkingTreeDiff` task.- #[serde(skip)]pub working_tree_status: Option<WorkingTreeStatus>,/// Whether the working tree has merge conflicts in tracked files. `None` =/// not yet loaded; `Some` = loaded. Fed by the `WorkingTreeDiff` task.- #[serde(skip)]pub has_conflicts: Option<bool>,/// Result of `WorkingTreeConflicts` task (`--full` mode only). Outer `None`/// = task hasn't run yet. Outer `Some(None)` = task ran but working tree/// was clean, so fall back to the committed-HEAD merge-tree check./// Outer `Some(Some(b))` = dirty working tree, `b` is the conflict result.- #[serde(skip)]pub has_working_tree_conflicts: Option<Option<bool>>,/// Git operation in progress (rebase/merge). `None` = not yet loaded;/// `Some(ActiveGitOperation::None)` = loaded, no operation in progress./// Fed by the `GitOperation` task.- #[serde(skip_serializing_if = "git_operation_is_none_or_unloaded")]pub git_operation: Option<ActiveGitOperation>,pub is_main: bool,/// Whether this is the current worktree (matches repo discovery path: PWD or `-C`)- #[serde(skip_serializing_if = "std::ops::Not::not")]pub is_current: bool,/// Whether this was the previous worktree (from `worktrunk.history`)- #[serde(skip_serializing_if = "std::ops::Not::not")]pub is_previous: bool,/// Whether the worktree is at an unexpected location (branch-worktree mismatch)./// Only true when: has branch name, not main worktree, and path differs from template.- #[serde(skip_serializing_if = "std::ops::Not::not")]pub branch_worktree_mismatch: bool,- #[serde(skip_serializing_if = "Option::is_none")]- pub working_diff_display: Option<String>,}impl WorktreeData {@@ -178,8 +97,7 @@ impl WorktreeData {/// WorktreeData is boxed to reduce the size of ItemKind enum (304 bytes → 24 bytes)./// This reduces stack pressure when passing ListItem by value and improves cache locality/// in `Vec<ListItem>` by keeping the discriminant and common fields together.-#[derive(serde::Serialize, Clone)]-#[serde(tag = "type", rename_all = "lowercase")]+#[derive(Clone)]pub enum ItemKind {Worktree(Box<WorktreeData>),Branch,@@ -191,82 +109,65 @@ pub enum ItemKind {/// was collected (`None` = not loaded, render shows placeholder). The inner type `U` is/// whatever the data naturally is — e.g., `AheadBehind` (always has a value, even if zero)/// or `Option<PrStatus>` (CI may not exist).-#[derive(serde::Serialize, Clone)]+#[derive(Clone)]pub struct ListItem {// Common fields (present for both worktrees and branches)- #[serde(rename = "head_sha")]pub head: String,/// Abbreviated form of `head`, honoring `core.abbrev` and auto-extending/// for ambiguous prefixes. Always populated when there is a HEAD commit/// to abbreviate (the `git log` batch in `collect()` emits `%h` for every/// row, including prunable worktrees). Empty for null OIDs (unborn/// branches) or when the batch failed for this row.- #[serde(skip)]pub short_sha: String,/// Branch name - None for detached worktreespub branch: Option<String>,- #[serde(flatten, skip_serializing_if = "Option::is_none")]pub commit: Option<CommitDetails>,- #[serde(flatten, skip_serializing_if = "Option::is_none")]pub counts: Option<AheadBehind>,- #[serde(flatten, skip_serializing_if = "Option::is_none")]pub branch_diff: Option<BranchDiffTotals>,/// Whether HEAD's tree SHA matches the integration target's tree SHA./// True when committed content is identical regardless of commit history./// Internal field used to compute `BranchState::Integrated(TreesMatch)`.- #[serde(skip)]pub committed_trees_match: Option<bool>,/// Whether branch has file changes beyond the merge-base with the integration target./// False when three-dot diff (`<integration-target>...branch`) is empty./// Internal field used for integration detection (no unique content).- #[serde(skip)]pub has_file_changes: Option<bool>,/// Whether merging branch into the integration target would add changes (merge simulation)./// False when `git merge-tree --write-tree <integration-target> branch` produces the same tree/// 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).- #[serde(skip)]pub is_ancestor: Option<bool>,/// Whether this branch is an orphan (no common ancestor with default branch)./// Orphan branches have independent history and can't compute meaningful ahead/behind counts.- #[serde(skip)]pub is_orphan: Option<bool>,- #[serde(flatten, skip_serializing_if = "Option::is_none")]pub upstream: Option<UpstreamStatus>,/// CI/PR status (inner Option: whether CI exists for this branch)pub pr_status: Option<Option<PrStatus>>,/// Dev server URL computed from project config template- #[serde(skip_serializing_if = "Option::is_none")]pub url: Option<String>,/// Whether the URL's port is actively listening- #[serde(skip_serializing_if = "Option::is_none")]pub url_active: Option<bool>,/// LLM-generated branch summary (inner Option: whether LLM produced a summary)- #[serde(skip)]pub summary: Option<Option<String>>,/// Potential merge conflicts with the integration target, computed from/// the committed HEAD via `git merge-tree`. `None` = not yet loaded;/// `Some` = loaded. Fed by the `MergeTreeConflicts` task.- #[serde(skip)]pub has_merge_tree_conflicts: Option<bool>,/// User-defined status marker from git config. Outer `None` = task/// hasn't run yet; `Some(None)` = task ran, no marker configured;/// `Some(Some(s))` = task ran, marker is `s`. Fed by the `UserMarker` task.- #[serde(skip)]pub user_marker: Option<Option<String>>,/// Git status symbols — one `StatusSymbols` struct per item, always@@ -274,17 +175,16 @@ pub struct ListItem {/// `Option` that progresses from `None` (loading, renders `·`) to `Some`/// as task results arrive. See the `status_symbols` module docstring for/// the per-gate rendering rules.- ///- /// Not serialized directly — JSON output converts to `JsonItem` first.- #[serde(skip)]pub status_symbols: StatusSymbols,- // Display fields for json-pretty format (with ANSI colors)- #[serde(flatten)]- pub display: DisplayFields,+ /// Pre-formatted single-line representation for statusline tools.+ /// Format: `branch status @working commits ^branch_diff upstream ci` (2-space separators)+ ///+ /// Populated by [`finalize_display`](Self::finalize_display); read by+ /// `JsonItem` for the `statusline` field.+ pub statusline: Option<String>,// Type-specific data (worktree vs branch)- #[serde(flatten)]pub kind: ItemKind,}@@ -317,7 +217,7 @@ impl ListItem {has_merge_tree_conflicts: None,user_marker: None,status_symbols: StatusSymbols::default(),- display: DisplayFields::default(),+ statusline: None,kind: ItemKind::Branch,}}@@ -506,20 +406,11 @@ impl ListItem {segments}- /// Populate display fields for JSON output and statusline.+ /// Populate the pre-formatted statusline for JSON output.////// Call after all computed fields (counts, diffs, upstream, CI) are available.pub fn finalize_display(&mut self) {- self.display =- DisplayFields::from_common_fields(&self.counts, &self.branch_diff, &self.upstream);- self.display.statusline = Some(self.format_statusline());-- if let ItemKind::Worktree(ref mut wt_data) = self.kind- && let Some(ref working_tree_diff) = wt_data.working_tree_diff- {- wt_data.working_diff_display = ColumnKind::WorkingDiff- .format_diff_plain(working_tree_diff.added, working_tree_diff.deleted);- }+ self.statusline = Some(self.format_statusline());}/// Refresh status symbols for this item, populating any gates whosediff --git a/src/commands/list/model/mod.rs b/src/commands/list/model/mod.rsindex 422418795..39c3d9757 100644--- a/src/commands/list/model/mod.rs+++ b/src/commands/list/model/mod.rs@@ -8,7 +8,7 @@//! - [`state`] - State enums for worktree and branch status (Divergence, MainState, etc.)//! - [`stats`] - Statistics types (AheadBehind, BranchDiffTotals, UpstreamStatus)//! - [`status_symbols`] - Status symbol rendering (StatusSymbols, PositionMask)-//! - [`item`] - Core list item types (ListItem, WorktreeData, DisplayFields)+//! - [`item`] - Core list item types (ListItem, WorktreeData, ItemKind)//! - [`statusline_segment`] - Statusline output with smart truncationpub mod item;@@ -22,7 +22,7 @@ pub mod statusline_segment;// via `crate::commands::list::model::...` paths. The allow is needed because// rustc doesn't track re-export usage across module boundaries.#[allow(unused_imports)]-pub use item::{DisplayFields, ItemKind, ListData, ListItem, WorktreeData};+pub use item::{ItemKind, ListData, ListItem, WorktreeData};#[allow(unused_imports)]pub use state::{ActiveGitOperation, Divergence, MainState, OperationState, WorktreeState};#[allow(unused_imports)]diff --git a/src/commands/list/model/state.rs b/src/commands/list/model/state.rsindex b9b65f606..f3c004857 100644--- a/src/commands/list/model/state.rs+++ b/src/commands/list/model/state.rs@@ -103,15 +103,6 @@ impl std::fmt::Display for WorktreeState {}}-impl serde::Serialize for WorktreeState {- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>- where- S: serde::Serializer,- {- serializer.serialize_str(&self.to_string())- }-}-/// Default branch relationship state////// Represents the combined relationship to the default branch in a single position.@@ -384,15 +375,6 @@ pub fn tier_integration_or_counts())}-impl serde::Serialize for MainState {- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>- where- S: serde::Serializer,- {- serializer.serialize_str(&self.to_string())- }-}-/// Worktree operation state////// Represents blocking git operations in progress that require resolution.@@ -447,26 +429,13 @@ impl OperationState {}}-impl serde::Serialize for OperationState {- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>- where- S: serde::Serializer,- {- serializer.serialize_str(&self.to_string())- }-}-/// Active git operation in a worktree////// Represents raw data about whether a worktree is in the middle of a git operation./// This is distinct from [`OperationState`] which is the display enum (includes Conflicts,/// has symbols/colors).-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, serde::Serialize, strum::IntoStaticStr)]-#[serde(rename_all = "kebab-case")]-#[strum(serialize_all = "kebab-case")]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]pub enum ActiveGitOperation {- #[strum(serialize = "")]- #[serde(rename = "")]#[default]None,/// Rebase in progress (rebase-merge or rebase-apply directory exists)@@ -475,12 +444,6 @@ pub enum ActiveGitOperation {Merge,}-impl ActiveGitOperation {- pub fn is_none(&self) -> bool {- matches!(self, Self::None)- }-}-#[cfg(test)]mod tests {use super::*;@@ -538,19 +501,6 @@ mod tests {assert_eq!(format!("{}", WorktreeState::Branch), "/");}- #[test]- fn test_worktree_state_serialize() {- // Serialize to JSON and check the string representation- let json = serde_json::to_string(&WorktreeState::None).unwrap();- assert_eq!(json, "\"\"");-- let json = serde_json::to_string(&WorktreeState::BranchWorktreeMismatch).unwrap();- assert_eq!(json, "\"⚑\"");-- let json = serde_json::to_string(&WorktreeState::Branch).unwrap();- assert_eq!(json, "\"/\"");- }-// ============================================================================// MainState Tests// ============================================================================@@ -582,21 +532,6 @@ mod tests {assert_snapshot!(MainState::Orphan.styled().unwrap(), @"[2m∅[22m");}- #[test]- fn test_main_state_serialize() {- let json = serde_json::to_string(&MainState::None).unwrap();- assert_eq!(json, "\"\"");-- let json = serde_json::to_string(&MainState::IsMain).unwrap();- assert_eq!(json, "\"^\"");-- let json = serde_json::to_string(&MainState::Diverged).unwrap();- assert_eq!(json, "\"↕\"");-- let json = serde_json::to_string(&MainState::Orphan).unwrap();- assert_eq!(json, "\"∅\"");- }-#[test]fn test_main_state_as_json_str() {assert_eq!(MainState::None.as_json_str(), None);@@ -931,15 +866,6 @@ mod tests {assert_snapshot!(OperationState::Merge.styled().unwrap(), @"[33m⤵[39m");}- #[test]- fn test_operation_state_serialize() {- let json = serde_json::to_string(&OperationState::None).unwrap();- assert_eq!(json, "\"\"");-- let json = serde_json::to_string(&OperationState::Conflicts).unwrap();- assert_eq!(json, "\"✘\"");- }-#[test]fn test_operation_state_as_json_str() {assert_eq!(OperationState::None.as_json_str(), None);@@ -947,16 +873,4 @@ mod tests {assert_eq!(OperationState::Rebase.as_json_str(), Some("rebase"));assert_eq!(OperationState::Merge.as_json_str(), Some("merge"));}-- // ============================================================================- // ActiveGitOperation Tests- // ============================================================================-- #[test]- fn test_git_operation_state_is_none() {- assert!(ActiveGitOperation::None.is_none());- assert!(ActiveGitOperation::default().is_none());- assert!(!ActiveGitOperation::Rebase.is_none());- assert!(!ActiveGitOperation::Merge.is_none());- }}diff --git a/src/commands/list/model/stats.rs b/src/commands/list/model/stats.rsindex 40d61626b..fae1770be 100644--- a/src/commands/list/model/stats.rs+++ b/src/commands/list/model/stats.rs@@ -11,34 +11,30 @@ use worktrunk::git::LineDiff;/// when this struct isn't populated (prunable worktrees, items missing from the/// pre-skeleton batch); the fields here are the per-commit data fetched/// alongside it in the same `git log` batch.-#[derive(serde::Serialize, Clone, Default, Debug)]+#[derive(Clone, Default, Debug)]pub struct CommitDetails {pub timestamp: i64,pub commit_message: String,}/// Ahead/behind counts relative to a base branch.-#[derive(serde::Serialize, Default, Copy, Clone, Debug)]+#[derive(Default, Copy, Clone, Debug)]pub struct AheadBehind {pub ahead: usize,pub behind: usize,}/// Line diff totals for a branch compared to the integration target.-#[derive(serde::Serialize, Default, Copy, Clone, Debug)]+#[derive(Default, Copy, Clone, Debug)]pub struct BranchDiffTotals {- #[serde(rename = "branch_diff")]pub diff: LineDiff,}/// Upstream tracking information for a branch.-#[derive(serde::Serialize, Default, Clone, Debug)]+#[derive(Default, Clone, Debug)]pub struct UpstreamStatus {- #[serde(rename = "upstream_remote")]pub(crate) remote: Option<String>,- #[serde(rename = "upstream_ahead")]pub(crate) ahead: usize,- #[serde(rename = "upstream_behind")]pub(crate) behind: usize,}diff --git a/src/commands/list/model/status_symbols.rs b/src/commands/list/model/status_symbols.rsindex 940cea81f..b18dfb0f4 100644--- a/src/commands/list/model/status_symbols.rs+++ b/src/commands/list/model/status_symbols.rs@@ -288,7 +288,7 @@ impl PositionMask {/// Working tree changes as structured booleans////// This is the canonical internal representation. Display strings are derived from this.-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize)]+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pub struct WorkingTreeStatus {pub staged: bool,pub modified: bool,diff --git a/src/commands/list/render.rs b/src/commands/list/render.rsindex 39e61cbae..57457e9f3 100644--- a/src/commands/list/render.rs+++ b/src/commands/list/render.rs@@ -38,11 +38,6 @@ impl DiffColumnConfig {value > max_value}- /// Check if a subcolumn value should be rendered (non-zero or explicitly showing zeros)- fn should_render(value: usize, always_show_zeros: bool) -> bool {- value > 0 || (value == 0 && always_show_zeros)- }-/// Format a value using compact notation (K for thousands, optionally C for hundreds)////// Returns (formatted_string, uses_compact_notation)@@ -124,7 +119,7 @@ impl DiffColumnConfig {let positive_overflow = Self::exceeds_width(positive, self.positive_digits);let negative_overflow = Self::exceeds_width(negative, self.negative_digits);- if positive == 0 && negative == 0 && !self.display.always_show_zeros {+ if positive == 0 && negative == 0 {segment.push_raw(" ".repeat(self.total_width));return segment;}@@ -142,7 +137,7 @@ impl DiffColumnConfig {}// Render positive (added) subcolumn- if Self::should_render(positive, self.display.always_show_zeros) {+ if positive > 0 {Self::render_subcolumn(&mut segment,symbols.positive,@@ -161,7 +156,7 @@ impl DiffColumnConfig {segment.push_raw(" ");// Render negative (deleted) subcolumn- if Self::should_render(negative, self.display.always_show_zeros) {+ if negative > 0 {Self::render_subcolumn(&mut segment,symbols.negative,@@ -504,15 +499,6 @@ impl ColumnLayout {cell.truncate_to_width(self.width)}ColumnKind::CiStatus => {- // Check display field first for pending indicators during progressive rendering- // (works for both worktrees and branches)- if let Some(ref ci_display) = item.display.ci_status_display {- let mut cell = StyledLine::new();- // ci_status_display contains pre-formatted ANSI text (either actual status or the placeholder)- cell.push_raw(ci_display.clone());- return cell;- }-match &item.pr_status {None => self.placeholder_cell(placeholder),Some(None) => StyledLine::new(), // No CI for this branch@@ -596,7 +582,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,};// Test various values@@ -642,7 +627,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,};// Insertions only@@ -688,7 +672,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -711,7 +694,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -734,7 +716,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -757,7 +738,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -782,7 +762,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -919,7 +898,6 @@ mod tests {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: dim_deletion,- always_show_zeros: false,},},);@@ -947,7 +925,6 @@ mod tests {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: dim_deletion,- always_show_zeros: false,},},);@@ -964,68 +941,12 @@ mod tests {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: dim_deletion,- always_show_zeros: false,},},);assert_eq!(behind_only.width(), total);}- #[test]- fn test_always_show_zeros_renders_zero_values() {- use super::super::columns::DiffVariant;- use worktrunk::styling::{ADDITION, DELETION};-- let total = 7;-- let dim_deletion = DELETION.dimmed();-- // With always_show_zeros=false, (0, 0) renders as blank- let without = format_diff_like_column(- 0,- 0,- DiffColumnConfig {- positive_digits: 1,- negative_digits: 1,- total_width: total,- display: DiffDisplayConfig {- variant: DiffVariant::Arrows,- positive_style: ADDITION,- negative_style: dim_deletion,- always_show_zeros: false,- },- },- );- assert_eq!(without.width(), total);- let rendered_without = without.render();- let clean_without = rendered_without.ansi_strip().into_owned();- assert_eq!(clean_without, " ");-- // With always_show_zeros=true, (0, 0) renders as "↑0 ↓0"- let with = format_diff_like_column(- 0,- 0,- DiffColumnConfig {- positive_digits: 1,- negative_digits: 1,- total_width: total,- display: DiffDisplayConfig {- variant: DiffVariant::Arrows,- positive_style: ADDITION,- negative_style: dim_deletion,- always_show_zeros: true,- },- },- );- assert_eq!(with.width(), total);- let rendered_with = with.render();- let clean_with = rendered_with.ansi_strip().into_owned();- assert_eq!(- clean_with, " ↑0 ↓0",- "Should render ↑0 ↓0 with padding (right-aligned)"- );- }-#[test]fn test_status_column_padding_with_emoji() {use unicode_width::UnicodeWidthStr;@@ -1107,7 +1028,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1127,7 +1047,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1147,7 +1066,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1199,7 +1117,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1219,7 +1136,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1239,7 +1155,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1258,7 +1173,6 @@ mod tests {variant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1285,7 +1199,6 @@ mod tests {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1305,7 +1218,6 @@ mod tests {variant: DiffVariant::Arrows,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},},);@@ -1395,7 +1307,6 @@ mod tests {variant: super::super::columns::DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,},}),};@@ -1439,7 +1350,6 @@ mod tests {variant: super::super::columns::DiffVariant::UpstreamArrows,positive_style: ADDITION,negative_style: DELETION.dimmed(),- always_show_zeros: false,},}),};diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex e3f87fa4f..0c881082c 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -63,7 +63,7 @@ pub(crate) use step::{step_relocate, step_show_squash_prompt, step_tether,};pub(crate) use worktree::{- OperationMode, SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,+ SwitchOptions, is_worktree_at_expected_path, resolve_worktree_arg, run_switch,worktree_display_name,};diff --git a/src/commands/picker/log_formatter.rs b/src/commands/picker/log_formatter.rsindex 8dd8c4232..c25e483f7 100644--- a/src/commands/picker/log_formatter.rs+++ b/src/commands/picker/log_formatter.rs@@ -271,7 +271,6 @@ wherevariant: DiffVariant::Signs,positive_style: ADDITION,negative_style: DELETION,- always_show_zeros: false,};let stat_str = format!(" {}", diff_config.format_aligned(insertions, deletions));diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rsindex 55c4caf09..3e5a93649 100644--- a/src/commands/worktree/mod.rs+++ b/src/commands/worktree/mod.rs@@ -98,4 +98,4 @@ pub use resolve::{#[cfg(unix)]pub(crate) use switch::SwitchPipeline;pub use switch::{SwitchOptions, run_switch};-pub use types::{MergeOperations, OperationMode, RemoveResult, SwitchBranchInfo, SwitchResult};+pub use types::{MergeOperations, RemoveResult, SwitchBranchInfo, SwitchResult};diff --git a/src/commands/worktree/push.rs b/src/commands/worktree/push.rsindex a30a17dda..82db3db21 100644--- a/src/commands/worktree/push.rs+++ b/src/commands/worktree/push.rs@@ -96,8 +96,11 @@ impl MergeContext {.trim().to_string();- // Fast-forward check (target must be ancestor of HEAD)- if !repo.is_ancestor(&target_tip, "HEAD")? {+ // Fast-forward check (target must be ancestor of HEAD).+ // target_tip is already a SHA; resolve HEAD to one too so the+ // ancestry probe hits the SHA-keyed cache directly.+ let head_sha = repo.run_command(&["rev-parse", "HEAD"])?.trim().to_string();+ if !repo.is_ancestor_by_sha(&target_tip, &head_sha)? {let commits_formatted = repo.run_command(&["log",diff --git a/src/commands/worktree/resolve.rs b/src/commands/worktree/resolve.rsindex 44b057736..556176fb9 100644--- a/src/commands/worktree/resolve.rs+++ b/src/commands/worktree/resolve.rs@@ -9,7 +9,7 @@ use anyhow::Context;use color_print::cformat;use normalize_path::NormalizePath;use worktrunk::config::UserConfig;-use worktrunk::git::{GitError, Repository, ResolvedWorktree};+use worktrunk::git::{Repository, ResolvedWorktree};use worktrunk::path::{format_path_for_display, paths_match};use worktrunk::styling::{eprintln, format_toml, hint_message, info_message, success_message, warning_message,@@ -17,29 +17,19 @@ use worktrunk::styling::{use crate::output::prompt::{PromptResponse, prompt_yes_no_preview};-use super::types::OperationMode;-/// Resolve a worktree argument using branch-first lookup.////// Resolution order:/// 1. Special symbols ("@", "-", "^") are handled specially/// 2. Resolve argument as branch name/// 3. If branch has a worktree, return it-/// 4. For `Remove`: fall back to path-based lookup (supports detached worktrees)+/// 4. Fall back to path-based lookup (supports detached worktrees)/// 5. Otherwise, return branch-only (no worktree)///-/// For `CreateOrSwitch` context: If the branch has no worktree but expected-/// path is occupied by another branch's worktree, an error is raised.-///-/// For `Remove` context: If branch lookup fails to find a worktree, the-/// argument is tried as a filesystem path (absolute or relative to CWD).-/// This supports removing detached HEAD worktrees which have no branch name.-pub fn resolve_worktree_arg(- repo: &Repository,- name: &str,- config: &UserConfig,- context: OperationMode,-) -> anyhow::Result<ResolvedWorktree> {+/// If branch lookup fails to find a worktree, the argument is tried as a+/// filesystem path (absolute or relative to CWD). This supports removing+/// detached HEAD worktrees which have no branch name.+pub fn resolve_worktree_arg(repo: &Repository, name: &str) -> anyhow::Result<ResolvedWorktree> {// Special symbols - delegate to Repository for consistent error handlingmatch name {"@" | "-" | "^" => {@@ -59,40 +49,24 @@ pub fn resolve_worktree_arg(});}- // No worktree for branch - check if expected path is occupied (only for create/switch)- if context == OperationMode::CreateOrSwitch {- let expected_path = compute_worktree_path(repo, name, config)?;- if let Some((_, occupant_branch)) = repo.worktree_at_path(&expected_path)? {- // Path is occupied by a different branch's worktree- return Err(GitError::WorktreePathOccupied {- branch,- path: expected_path,- occupant: occupant_branch,- }- .into());- }- }-- // For Remove: fall back to path-based lookup (supports detached worktrees)- if context == OperationMode::Remove {- let candidate = Path::new(name);- // Try as absolute path, or resolve relative to CWD- let abs_path = if candidate.is_absolute() {- candidate.to_path_buf()- } else {- std::env::current_dir()- .context("Failed to determine current directory")?- .join(candidate)- };- if let Some((path, wt_branch)) = repo.worktree_at_path(&abs_path)? {- return Ok(ResolvedWorktree::Worktree {- path,- branch: wt_branch,- });- }+ // No worktree for branch - fall back to path-based lookup (supports detached worktrees)+ let candidate = Path::new(name);+ // Try as absolute path, or resolve relative to CWD+ let abs_path = if candidate.is_absolute() {+ candidate.to_path_buf()+ } else {+ std::env::current_dir()+ .context("Failed to determine current directory")?+ .join(candidate)+ };+ if let Some((path, wt_branch)) = repo.worktree_at_path(&abs_path)? {+ return Ok(ResolvedWorktree::Worktree {+ path,+ branch: wt_branch,+ });}- // No worktree for branch (and path not occupied, or we don't care about path)+ // No worktree for branch and no worktree at the pathOk(ResolvedWorktree::BranchOnly { branch })}diff --git a/src/commands/worktree/types.rs b/src/commands/worktree/types.rsindex 30b74c1ae..0851d94bc 100644--- a/src/commands/worktree/types.rs+++ b/src/commands/worktree/types.rs@@ -244,17 +244,6 @@ impl RemoveResult {}}-/// Operation mode for worktree resolution - determines which checks are performed.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]-pub enum OperationMode {- /// Creating or switching to a worktree - path occupation is an error- /// because we need to create a worktree at the expected path.- CreateOrSwitch,- /// Removing a worktree - we only care if the branch has a worktree,- /// path occupation is irrelevant since we're not creating anything.- Remove,-}-#[cfg(test)]mod tests {use super::*;diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 1b7b69a3b..66d5edf35 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -72,60 +72,6 @@ pub struct MergeProbeResult {const PATCH_ID_SCAN_MAX_COMMITS: usize = 500;impl Repository {- /// Resolve a ref, preferring branches over tags when names collide.- ///- /// Uses git to check if `refs/heads/{ref}` exists. If so, returns the- /// qualified form to ensure we reference the branch, not a same-named tag.- /// Otherwise returns the original ref unchanged (for HEAD, SHAs, remote refs).- /// Uncached: this is only consulted by the ref-taking convenience- /// wrappers; hot paths go through a [`RefSnapshot`] instead.- fn resolve_preferring_branch(&self, r: &str) -> String {- let qualified = format!("refs/heads/{r}");- if self- .run_command(&["rev-parse", "--verify", "-q", &qualified])- .is_ok()- {- qualified- } else {- r.to_string()- }- }-- /// Resolve a ref for integration helpers — passthrough for already-qualified- /// refs, branch-preferring resolution for short names.- ///- /// Inputs starting with `refs/` (e.g., from `BranchRef::full_ref()`) are- /// returned unchanged: they're already unambiguous, and re-qualifying would- /// either (a) waste a `rev-parse` in the common case, or (b) pick the wrong- /// ref when a branch literally named e.g. `refs/heads/foo` exists — the- /// caller gave us `refs/heads/foo` meaning the branch `foo`, not the- /// pathological branch at `refs/heads/refs/heads/foo`.- ///- /// Short names go through `resolve_preferring_branch` so its- /// branch-over-tag disambiguation still applies to user/CLI input.- fn resolve_ref(&self, r: &str) -> String {- if r.starts_with("refs/") {- r.to_string()- } else {- self.resolve_preferring_branch(r)- }- }-- /// Check if base is an ancestor of head (i.e., would be a fast-forward).- ///- /// See [`--is-ancestor`][1] for details.- ///- /// [1]: https://git-scm.com/docs/git-merge-base#Documentation/git-merge-base.txt---is-ancestor- pub fn is_ancestor(&self, base: &str, head: &str) -> anyhow::Result<bool> {- let base = self.resolve_ref(base);- let head = self.resolve_ref(head);-- let base_sha = self.rev_parse_commit(&base)?;- let head_sha = self.rev_parse_commit(&head)?;-- self.is_ancestor_by_sha(&base_sha, &head_sha)- }-/// Check if `base_sha` is an ancestor of `head_sha`, taking commit SHAs/// directly. Hits the persistent SHA-keyed cache without going through/// the (stale-prone) ambient ref→SHA cache.@@ -143,21 +89,6 @@ impl Repository {Ok(result)}- /// Check if two refs point to the same commit.- pub fn same_commit(&self, ref1: &str, ref2: &str) -> anyhow::Result<bool> {- let ref1 = self.resolve_ref(ref1);- let ref2 = self.resolve_ref(ref2);- // Parse both refs in a single git command- let output = self.run_command(&["rev-parse", &ref1, &ref2])?;- let mut lines = output.lines();- let sha1 = lines.next().context("rev-parse returned no output")?.trim();- let sha2 = lines- .next()- .context("rev-parse returned only one line")?- .trim();- Ok(sha1 == sha2)- }-/// Check if a branch has file changes beyond the merge-base with target.////// Uses merge-base (cached) to find common ancestor, then two-dot diff to@@ -165,17 +96,6 @@ impl Repository {////// For orphan branches (no common ancestor with target), returns true since all/// their changes are unique.- pub fn has_added_changes(&self, branch: &str, target: &str) -> anyhow::Result<bool> {- let branch = self.resolve_ref(branch);- let target = self.resolve_ref(target);-- let branch_sha = self.rev_parse_commit(&branch)?;- let target_sha = self.rev_parse_commit(&target)?;-- self.has_added_changes_by_sha(&branch_sha, &target_sha)- }-- /// SHA-keyed variant of [`Self::has_added_changes`].////// Bypasses the ambient ref→SHA cache so callers holding SHAs from a/// [`RefSnapshot`] (or `BranchRef.commit_sha`) can short-circuit to the@@ -202,30 +122,11 @@ impl Repository {Ok(result)}- /// Check if two refs have identical tree content (same files/directories).+ /// Check if two commits have identical tree content (same files/directories)./// Returns true when content is identical even if commit history differs.////// Useful for detecting squash merges or rebases where the content has been/// integrated but commit ancestry doesn't show the relationship.- pub fn trees_match(&self, ref1: &str, ref2: &str) -> anyhow::Result<bool> {- let ref1 = self.resolve_ref(ref1);- let ref2 = self.resolve_ref(ref2);- // Parse both tree refs in a single git command- let output = self.run_command(&[- "rev-parse",- &format!("{ref1}^{{tree}}"),- &format!("{ref2}^{{tree}}"),- ])?;- let mut lines = output.lines();- let tree1 = lines.next().context("rev-parse returned no output")?.trim();- let tree2 = lines- .next()- .context("rev-parse returned only one line")?- .trim();- Ok(tree1 == tree2)- }-- /// SHA-keyed variant of [`Self::trees_match`].////// Resolves each commit SHA to its tree SHA in a single `git rev-parse`/// call and compares. The commit→tree resolution is itself uncached@@ -246,36 +147,10 @@ impl Repository {Ok(tree1 == tree2)}- /// Check if HEAD's tree SHA matches a branch's tree SHA.- /// Returns true when content is identical even if commit history differs.- pub fn head_tree_matches_branch(&self, branch: &str) -> anyhow::Result<bool> {- self.trees_match("HEAD", branch)- }-- /// Check if merging head into base would result in conflicts.+ /// Check if merging `head_sha` into `base_sha` would result in conflicts.////// Uses `git merge-tree` to simulate a merge without touching the working tree./// Returns true if conflicts would occur, false for a clean merge.- ///- /// # Examples- /// ```no_run- /// use worktrunk::git::Repository;- ///- /// let repo = Repository::current()?;- /// let has_conflicts = repo.has_merge_conflicts("main", "feature-branch")?;- /// # Ok::<(), anyhow::Error>(())- /// ```- pub fn has_merge_conflicts(&self, base: &str, head: &str) -> anyhow::Result<bool> {- let base = self.resolve_ref(base);- let head = self.resolve_ref(head);-- let base_sha = self.rev_parse_commit(&base)?;- let head_sha = self.rev_parse_commit(&head)?;-- self.has_merge_conflicts_by_sha(&base_sha, &head_sha)- }-- /// SHA-keyed variant of [`Self::has_merge_conflicts`].pub fn has_merge_conflicts_by_sha(&self,base_sha: &str,@@ -290,31 +165,16 @@ impl Repository {/// Check merge conflicts for a working tree represented by a tree SHA.///- /// Unlike [`Self::has_merge_conflicts`] which takes commit refs, this accepts a- /// raw tree SHA (from `git write-tree`) and the branch HEAD commit SHA.- /// On cache miss, creates an ephemeral commit via `git commit-tree` to- /// feed `merge-tree` (which requires commit objects for merge-base- /// resolution). On cache hit, no commit is created.+ /// Unlike [`Self::has_merge_conflicts_by_sha`] which takes commit SHAs,+ /// this accepts a raw tree SHA (from `git write-tree`) and the branch HEAD+ /// commit SHA. On cache miss, creates an ephemeral commit via+ /// `git commit-tree` to feed `merge-tree` (which requires commit objects+ /// for merge-base resolution). On cache hit, no commit is created.////// The cache key is `(base_commit_sha, branch_head_sha+tree_sha)` — a/// composite that captures all three inputs to the three-way merge:/// the base tree, the merge-base (via branch HEAD ancestry), and the/// working tree content.- pub fn has_merge_conflicts_by_tree(- &self,- base: &str,- branch_head_sha: &str,- tree_sha: &str,- ) -> anyhow::Result<bool> {- let base = self.resolve_ref(base);- let base_sha = self.rev_parse_commit(&base)?;-- self.has_merge_conflicts_by_tree_with_base_sha(&base_sha, branch_head_sha, tree_sha)- }-- /// SHA-keyed variant of [`Self::has_merge_conflicts_by_tree`] —- /// `base_sha` is taken as a SHA (the other two arguments are already- /// SHA-shaped). Same composite cache key as the ref-taking form.pub fn has_merge_conflicts_by_tree_with_base_sha(&self,base_sha: &str,@@ -374,7 +234,7 @@ impl Repository {/// Check if merging a branch into target would add anything (not already integrated).///- /// Caller must pass resolved refs (via `resolve_ref`).+ /// Caller must pass commit SHAs for both `branch` and `target`.////// Returns:/// - `Ok(Some(true))` if merging would change the target@@ -526,30 +386,11 @@ impl Repository {/// 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_ref(branch);- let target = self.resolve_ref(target);-- // Resolve refs to commit SHAs for the persistent cache key.- // The probe result depends only on the two committed trees (the- // patch-id fallback reads commits in merge_base..target, also a- // pure function of the two SHAs). Asymmetric key: branch first,- // then target, because the merge-tree result is compared against- // target's tree.- let branch_sha = self.rev_parse_commit(&branch)?;- let target_sha = self.rev_parse_commit(&target)?;-- self.merge_integration_probe_by_sha(&branch_sha, &target_sha)- }-- /// SHA-keyed variant of [`Self::merge_integration_probe`].///- /// Asymmetric: branch first, then target — the merge-tree result is- /// compared against target's tree.+ /// The probe result depends only on the two committed trees (the patch-id+ /// fallback reads commits in `merge_base..target`, also a pure function of+ /// the two SHAs). Asymmetric: branch first, then target — the merge-tree+ /// result is compared against target's tree.pub fn merge_integration_probe_by_sha(&self,branch_sha: &str,diff --git a/src/git/repository/sha_cache.rs b/src/git/repository/sha_cache.rsindex 769189633..e3e9118cf 100644--- a/src/git/repository/sha_cache.rs+++ b/src/git/repository/sha_cache.rs@@ -4,7 +4,7 @@//! content-addressed SHAs — diffing commit A against commit B is the same//! today as last week. One variant (working-tree conflict checks) uses a//! composite key that includes a tree SHA; see-//! [`Repository::has_merge_conflicts_by_tree`]. No TTL, no invalidation+//! [`Repository::has_merge_conflicts_by_tree_with_base_sha`]. No TTL, no invalidation//! logic, only a per-kind LRU size bound to prevent unbounded growth.//!//! Layout: `.git/wt/cache/{kind}/{key}.json` where `kind` is one of@@ -58,14 +58,14 @@ fn asymmetric_key(first: &str, second: &str) -> String {// merge-tree conflicts (symmetric)-/// Look up a cached `has_merge_conflicts(sha1, sha2)` result.+/// Look up a cached `has_merge_conflicts_by_sha(sha1, sha2)` result.////// The key is order-independent: `(A, B)` and `(B, A)` hit the same entry.pub(super) fn merge_conflicts(repo: &Repository, sha1: &str, sha2: &str) -> Option<bool> {cache::read(repo, KIND_MERGE_TREE_CONFLICTS, &symmetric_key(sha1, sha2))}-/// Store a `has_merge_conflicts(sha1, sha2)` result, triggering an LRU+/// Store a `has_merge_conflicts_by_sha(sha1, sha2)` result, triggering an LRU/// sweep if the per-kind entry bound is exceeded.pub(super) fn put_merge_conflicts(repo: &Repository, sha1: &str, sha2: &str, value: bool) {cache::write_with_lru(@@ -79,7 +79,7 @@ pub(super) fn put_merge_conflicts(repo: &Repository, sha1: &str, sha2: &str, val// merge-add probe (asymmetric)-/// Look up a cached `merge_integration_probe(branch, target)` result.+/// Look up a cached `merge_integration_probe_by_sha(branch, target)` result.////// The key is order-dependent: the merge result is compared against/// `target`'s tree, so swapping arguments changes the semantics.@@ -95,7 +95,7 @@ pub(super) fn merge_add_probe()}-/// Store a `merge_integration_probe(branch, target)` result, triggering+/// Store a `merge_integration_probe_by_sha(branch, target)` result, triggering/// an LRU sweep if the per-kind entry bound is exceeded.pub(super) fn put_merge_add_probe(repo: &Repository,@@ -114,14 +114,14 @@ pub(super) fn put_merge_add_probe(// is-ancestor (asymmetric)-/// Look up a cached `is_ancestor(base_sha, head_sha)` result.+/// Look up a cached `is_ancestor_by_sha(base_sha, head_sha)` result.////// Asymmetric: "is base ancestor of head?" differs from "is head ancestor of base?".pub(super) fn is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str) -> Option<bool> {cache::read(repo, KIND_IS_ANCESTOR, &asymmetric_key(base_sha, head_sha))}-/// Store an `is_ancestor(base_sha, head_sha)` result.+/// Store an `is_ancestor_by_sha(base_sha, head_sha)` result.pub(super) fn put_is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str, value: bool) {cache::write_with_lru(repo,@@ -134,7 +134,7 @@ pub(super) fn put_is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str,// has-added-changes (asymmetric)-/// Look up a cached `has_added_changes(branch_sha, target_sha)` result.+/// Look up a cached `has_added_changes_by_sha(branch_sha, target_sha)` result.////// Asymmetric: diff from merge-base to branch is directional.pub(super) fn has_added_changes(@@ -149,7 +149,7 @@ pub(super) fn has_added_changes()}-/// Store a `has_added_changes(branch_sha, target_sha)` result.+/// Store a `has_added_changes_by_sha(branch_sha, target_sha)` result.pub(super) fn put_has_added_changes(repo: &Repository,branch_sha: &str,@@ -359,10 +359,17 @@ mod tests {test.run_git(&["commit", "-m", "Add file"]);test.run_git(&["checkout", "main"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);+ let feature_sha = test.git_output(&["rev-parse", "feature"]);+let repo = Repository::at(test.root_path()).unwrap();// First call: real computation — clean merge → false- assert!(!repo.has_merge_conflicts("main", "feature").unwrap());+ assert!(+ !repo+ .has_merge_conflicts_by_sha(&main_sha, &feature_sha)+ .unwrap()+ );// Tamper with the cache file to return the wrong answerlet dir = cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);@@ -374,14 +381,14 @@ mod tests {assert_eq!(entries.len(), 1, "exactly one cache entry expected");fs::write(entries[0].path(), "true").unwrap();- // Second call: reads the tampered value from cache- // Note: we need a fresh Repository so the in-memory RepoCache doesn't- // interfere (resolved_refs, merge_base, etc. are all keyed by ref name- // and would bypass the cache for the same invocation — but- // rev_parse_commit is cached per command, and on a fresh Repo the SHAs- // will resolve identically to the first run).+ // Second call on a fresh Repository reads the tampered value from the+ // persistent cache.let repo2 = Repository::at(test.root_path()).unwrap();- assert!(repo2.has_merge_conflicts("main", "feature").unwrap());+ assert!(+ repo2+ .has_merge_conflicts_by_sha(&main_sha, &feature_sha)+ .unwrap()+ );}#[test]@@ -395,12 +402,13 @@ mod tests {let branch_head = test.git_output(&["rev-parse", "HEAD"]);let tree_sha = test.git_output(&["write-tree"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);let repo = Repository::at(test.root_path()).unwrap();// Call with composite keying — computes and cacheslet result = repo- .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)+ .has_merge_conflicts_by_tree_with_base_sha(&main_sha, &branch_head, &tree_sha).unwrap();// Verify the cache entry uses the composite key@@ -424,7 +432,7 @@ mod tests {let repo2 = Repository::at(test.root_path()).unwrap();let cached = repo2- .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)+ .has_merge_conflicts_by_tree_with_base_sha(&main_sha, &branch_head, &tree_sha).unwrap();assert_eq!(cached, tampered, "should read tampered value from cache");}@@ -456,12 +464,13 @@ mod tests {let head_before = test.git_output(&["rev-parse", "HEAD"]);let tree1 = test.git_output(&["write-tree"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);let repo = Repository::at(test.root_path()).unwrap();// Before rebase: feature conflicts with main (both modified shared.txt)let result_before = repo- .has_merge_conflicts_by_tree("main", &head_before, &tree1)+ .has_merge_conflicts_by_tree_with_base_sha(&main_sha, &head_before, &tree1).unwrap();assert!(result_before, "should conflict before rebase");@@ -484,7 +493,7 @@ mod tests {let repo2 = Repository::at(test.root_path()).unwrap();let result_after = repo2- .has_merge_conflicts_by_tree("main", &head_after, &tree2)+ .has_merge_conflicts_by_tree_with_base_sha(&main_sha, &head_after, &tree2).unwrap();// After rebase onto main, feature is based on main — no conflicts@@ -506,10 +515,15 @@ mod tests {test.run_git(&["checkout", "main"]);test.run_git(&["merge", "feature"]);+ let feature_sha = test.git_output(&["rev-parse", "feature"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);+let repo = Repository::at(test.root_path()).unwrap();// First call: feature is fully integrated → would_merge_add=false- let real = repo.merge_integration_probe("feature", "main").unwrap();+ let real = repo+ .merge_integration_probe_by_sha(&feature_sha, &main_sha)+ .unwrap();assert!(!real.would_merge_add);// Tamper with the cache to flip the answer@@ -528,7 +542,9 @@ mod tests {// Fresh repo reads the tampered cachelet repo2 = Repository::at(test.root_path()).unwrap();- let cached = repo2.merge_integration_probe("feature", "main").unwrap();+ let cached = repo2+ .merge_integration_probe_by_sha(&feature_sha, &main_sha)+ .unwrap();assert!(cached.would_merge_add);assert!(cached.is_patch_id_match);}@@ -612,10 +628,13 @@ mod tests {test.run_git(&["commit", "-m", "Feature"]);test.run_git(&["checkout", "main"]);+ let feature_sha = test.git_output(&["rev-parse", "feature"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);+let repo = Repository::at(test.root_path()).unwrap();// feature is NOT an ancestor of main (main didn't merge feature)- assert!(!repo.is_ancestor("feature", "main").unwrap());+ assert!(!repo.is_ancestor_by_sha(&feature_sha, &main_sha).unwrap());// Tamper with cache to flip the answerlet dir = cache::cache_dir(&repo, KIND_IS_ANCESTOR);@@ -628,7 +647,7 @@ mod tests {fs::write(entries[0].path(), "true").unwrap();let repo2 = Repository::at(test.root_path()).unwrap();- assert!(repo2.is_ancestor("feature", "main").unwrap());+ assert!(repo2.is_ancestor_by_sha(&feature_sha, &main_sha).unwrap());}#[test]@@ -641,10 +660,16 @@ mod tests {test.run_git(&["commit", "-m", "Feature"]);test.run_git(&["checkout", "main"]);+ let feature_sha = test.git_output(&["rev-parse", "feature"]);+ let main_sha = test.git_output(&["rev-parse", "main"]);+let repo = Repository::at(test.root_path()).unwrap();// feature has added changes compared to main- assert!(repo.has_added_changes("feature", "main").unwrap());+ assert!(+ repo.has_added_changes_by_sha(&feature_sha, &main_sha)+ .unwrap()+ );// Tamper with cache to flip the answerlet dir = cache::cache_dir(&repo, KIND_HAS_ADDED_CHANGES);@@ -657,7 +682,11 @@ mod tests {fs::write(entries[0].path(), "false").unwrap();let repo2 = Repository::at(test.root_path()).unwrap();- assert!(!repo2.has_added_changes("feature", "main").unwrap());+ assert!(+ !repo2+ .has_added_changes_by_sha(&feature_sha, &main_sha)+ .unwrap()+ );}#[test]diff --git a/src/main.rs b/src/main.rsindex 63c12aa7c..6fc82a6e7 100644--- a/src/main.rs+++ b/src/main.rs@@ -49,18 +49,18 @@ use commands::handle_picker;use commands::repository_ext::RepositoryCliExt;use commands::worktree::{PushKind, PushOutcome, PushResult, handle_no_ff_merge, handle_push};use commands::{- HookCliArgs, MergeFlagOverrides, MergeOptions, OperationMode, RebaseResult, RemoveTarget,- SquashResult, SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run,- handle_alias_show, handle_claude_install, handle_claude_install_statusline,- handle_claude_uninstall, handle_codex_install, handle_codex_uninstall, handle_completions,- handle_config_create, handle_config_show, handle_config_update, handle_configure_shell,- handle_custom_command, handle_hints_clear, handle_hints_get, handle_hook_show, handle_init,- handle_list, handle_logs_list, handle_merge, handle_opencode_install,- handle_opencode_uninstall, handle_promote, handle_rebase, handle_show_theme, handle_squash,- handle_state_clear, handle_state_clear_all, handle_state_get, handle_state_set,- handle_state_show, handle_unconfigure_shell, handle_vars_clear, handle_vars_get,- handle_vars_list, handle_vars_set, resolve_worktree_arg, run_hook, run_switch, step_commit,- step_copy_ignored, step_diff, step_eval, step_for_each, step_prune, step_relocate, step_tether,+ HookCliArgs, MergeFlagOverrides, MergeOptions, RebaseResult, RemoveTarget, SquashResult,+ SwitchOptions, add_approvals, clear_approvals, handle_alias_dry_run, handle_alias_show,+ handle_claude_install, handle_claude_install_statusline, handle_claude_uninstall,+ handle_codex_install, handle_codex_uninstall, handle_completions, handle_config_create,+ handle_config_show, handle_config_update, handle_configure_shell, handle_custom_command,+ handle_hints_clear, handle_hints_get, handle_hook_show, handle_init, handle_list,+ handle_logs_list, handle_merge, handle_opencode_install, handle_opencode_uninstall,+ handle_promote, handle_rebase, handle_show_theme, handle_squash, handle_state_clear,+ handle_state_clear_all, handle_state_get, handle_state_set, handle_state_show,+ handle_unconfigure_shell, handle_vars_clear, handle_vars_get, handle_vars_list,+ handle_vars_set, resolve_worktree_arg, run_hook, run_switch, step_commit, step_copy_ignored,+ step_diff, step_eval, step_for_each, step_prune, step_relocate, step_tether,};use output::{BackgroundFallbackMode, handle_remove_output};use worktrunk::git::BranchDeletionMode;@@ -793,8 +793,7 @@ fn validate_remove_targets(};for branch_name in &branches {- let resolved = match resolve_worktree_arg(repo, branch_name, config, OperationMode::Remove)- {+ let resolved = match resolve_worktree_arg(repo, branch_name) {Ok(r) => r,Err(e) => {plans.record_error(e);diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 2a48a287a..bb4cca791 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -538,7 +538,7 @@ fn test_list_json_with_display_fields(mut repo: TestRepo) {&["commit", "--allow-empty", "-m", "Feature commit 2"],);- // Add uncommitted changes to show working_diff_display+ // Add uncommitted changes to populate the working-diff columnstd::fs::write(feature_path.join("uncommitted.txt"), "uncommitted").unwrap();std::fs::write(feature_path.join("feature.txt"), "modified content").unwrap();diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rsindex 1e10a8a6b..54c7221f2 100644--- a/tests/integration_tests/remove.rs+++ b/tests/integration_tests/remove.rs@@ -201,8 +201,8 @@ fn test_remove_nonexistent_worktree(repo: TestRepo) {////// Regression test for bug where `wt remove npm` would show "Cannot create worktree for npm"-/// when the expected path was occupied. The fix uses `OperationMode::Remove` which skips-/// the path occupation check entirely, correctly treating this as a branch-only removal.+/// when the expected path was occupied. Resolution skips the path occupation check entirely,+/// correctly treating this as a branch-only removal.////// Setup:/// - Branch `npm` exists but has no worktree@@ -2443,7 +2443,7 @@ fn test_remove_detached_worktree_by_path(mut repo: TestRepo) {}/// Verify that detached worktrees can be removed by relative path.-/// This tests resolve_worktree_arg's CWD-relative path resolution for Remove context.+/// This tests resolve_worktree_arg's CWD-relative path resolution.#[rstest]fn test_remove_detached_worktree_by_relative_path(mut repo: TestRepo) {repo.add_worktree("feature-detached");diff --git a/tests/integration_tests/repository.rs b/tests/integration_tests/repository.rsindex 5086790a2..18c64fa41 100644--- a/tests/integration_tests/repository.rs+++ b/tests/integration_tests/repository.rs@@ -703,176 +703,11 @@ fn test_unset_config_propagates_error_on_corrupt_config() {);}-// =============================================================================-// Bug #1: Tag/branch name collision tests-// =============================================================================--/// When a tag and branch share the same name, git resolves unqualified refs to-/// the tag by default. This can cause is_ancestor() to return incorrect results-/// if the tag points to a different commit than the branch.-///-/// This test verifies that integration checking uses qualified refs (refs/heads/)-/// to avoid this ambiguity.-#[test]-fn test_tag_branch_name_collision_is_ancestor() {- let repo = TestRepo::with_initial_commit();-- // Initial commit already exists from with_initial_commit()- let main_sha = repo.git_output(&["rev-parse", "HEAD"]);-- // Create feature branch with additional commits- repo.run_git(&["checkout", "-b", "feature"]);- fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();- repo.run_git(&["add", "feature.txt"]);- repo.run_git(&["commit", "-m", "Feature commit"]);-- // Create a tag named "feature" pointing to the MAIN commit (earlier)- // This simulates the scenario where someone creates a tag with the same name- repo.run_git(&["tag", "feature", &main_sha]);-- // Now git has ambiguity: "feature" could be the tag (at main_sha) or the branch (ahead)- // The branch "feature" is NOT an ancestor of main (it's ahead)- // But the tag "feature" points to main_sha, which IS an ancestor of main (same commit)-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // Without qualified refs, this would incorrectly return true- // (checking the tag, which equals main, instead of the branch, which is ahead)- // With the fix (using refs/heads/), this should correctly return false- let result = repository.is_ancestor("feature", "main").unwrap();-- // The branch "feature" is ahead of main, so it should NOT be an ancestor- assert!(- !result,- "is_ancestor should check the branch 'feature', not the tag 'feature'"- );-}--/// Test that same_commit() correctly distinguishes between tag and branch-/// when they share the same name but point to different commits.-#[test]-fn test_tag_branch_name_collision_same_commit() {- let repo = TestRepo::with_initial_commit();-- // Get main's SHA- let main_sha = repo.git_output(&["rev-parse", "HEAD"]);-- // Create feature branch with additional commits- repo.run_git(&["checkout", "-b", "feature"]);- fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();- repo.run_git(&["add", "feature.txt"]);- repo.run_git(&["commit", "-m", "Feature commit"]);-- // Create a tag named "feature" pointing to main (different from branch)- repo.run_git(&["tag", "feature", &main_sha]);-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // The branch "feature" is NOT at the same commit as main- // But the tag "feature" IS at the same commit as main- // Without qualified refs, this would incorrectly return true- let result = repository.same_commit("feature", "main").unwrap();-- assert!(- !result,- "same_commit should check the branch 'feature', not the tag 'feature'"- );-}--/// Test that trees_match() correctly distinguishes between tag and branch-/// when they share the same name but point to commits with different trees.-#[test]-fn test_tag_branch_name_collision_trees_match() {- let repo = TestRepo::with_initial_commit();-- // Get main's SHA- let main_sha = repo.git_output(&["rev-parse", "HEAD"]);-- // Create feature branch with different content- repo.run_git(&["checkout", "-b", "feature"]);- fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();- repo.run_git(&["add", "feature.txt"]);- repo.run_git(&["commit", "-m", "Feature commit"]);-- // Create a tag named "feature" pointing to main (different tree)- repo.run_git(&["tag", "feature", &main_sha]);-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // The branch "feature" has different tree content than main- // But the tag "feature" has the same tree as main- // Without qualified refs, this would incorrectly return true- let result = repository.trees_match("feature", "main").unwrap();-- assert!(- !result,- "trees_match should check the branch 'feature', not the tag 'feature'"- );-}--/// Test that integration functions correctly handle HEAD (not a branch).-#[test]-fn test_integration_functions_handle_head() {- let repo = TestRepo::new();-- // Create a commit so HEAD differs from an empty state- fs::write(repo.root_path().join("file.txt"), "content").unwrap();- repo.run_git(&["add", "file.txt"]);- repo.run_git(&["commit", "-m", "Add file"]);-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // HEAD should work in all integration functions- // (resolve_preferring_branch should pass HEAD through unchanged)- assert!(repository.same_commit("HEAD", "main").unwrap());- assert!(repository.is_ancestor("main", "HEAD").unwrap());- assert!(repository.trees_match("HEAD", "main").unwrap());-}--/// Test that integration functions correctly handle commit SHAs.-#[test]-fn test_integration_functions_handle_shas() {- let repo = TestRepo::with_initial_commit();-- let main_sha = repo.git_output(&["rev-parse", "HEAD"]);-- // Create feature branch- repo.run_git(&["checkout", "-b", "feature"]);- fs::write(repo.root_path().join("feature.txt"), "content").unwrap();- repo.run_git(&["add", "feature.txt"]);- repo.run_git(&["commit", "-m", "Feature"]);-- let feature_sha = repo.git_output(&["rev-parse", "HEAD"]);-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // SHAs should work in all integration functions- // (resolve_preferring_branch should pass SHAs through unchanged)- assert!(repository.same_commit(&main_sha, "main").unwrap());- assert!(!repository.same_commit(&feature_sha, &main_sha).unwrap());- assert!(repository.is_ancestor(&main_sha, &feature_sha).unwrap());-}--/// Test that integration functions correctly handle remote refs.-#[test]-fn test_integration_functions_handle_remote_refs() {- let mut repo = TestRepo::with_initial_commit();- repo.setup_remote("main");-- let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();-- // Remote refs like origin/main should work- // (resolve_preferring_branch should pass them through unchanged since- // refs/heads/origin/main doesn't exist)- assert!(repository.same_commit("origin/main", "main").unwrap());- assert!(repository.is_ancestor("origin/main", "main").unwrap());-}-// =============================================================================// merge-tree exit code handling tests// =============================================================================-/// has_merge_conflicts returns false for clean merges (exit 0)+/// has_merge_conflicts_by_sha returns false for clean merges (exit 0)/// and true for conflicts (exit 1).#[test]fn test_has_merge_conflicts_clean_vs_conflicting() {@@ -898,20 +733,24 @@ fn test_has_merge_conflicts_clean_vs_conflicting() {repo.run_git(&["add", "base.txt"]);repo.run_git(&["commit", "-m", "Edit base on main"]);+ let main_sha = repo.git_output(&["rev-parse", "main"]);+ let clean_sha = repo.git_output(&["rev-parse", "clean-feature"]);+ let conflict_sha = repo.git_output(&["rev-parse", "conflict-feature"]);+let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();assert!(!repository- .has_merge_conflicts("main", "clean-feature")+ .has_merge_conflicts_by_sha(&main_sha, &clean_sha).unwrap());assert!(repository- .has_merge_conflicts("main", "conflict-feature")+ .has_merge_conflicts_by_sha(&main_sha, &conflict_sha).unwrap());}-/// has_merge_conflicts returns true (not Err) for orphan branches,+/// has_merge_conflicts_by_sha returns true (not Err) for orphan branches,/// since unrelated histories can't be cleanly merged.#[test]fn test_has_merge_conflicts_orphan_branch() {@@ -924,13 +763,20 @@ fn test_has_merge_conflicts_orphan_branch() {repo.run_git(&["commit", "-m", "Orphan commit"]);repo.run_git(&["checkout", "main"]);+ let main_sha = repo.git_output(&["rev-parse", "main"]);+ let orphan_sha = repo.git_output(&["rev-parse", "orphan"]);+let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();// Orphan branches have no merge base — treated as conflicting, not as an error- assert!(repository.has_merge_conflicts("main", "orphan").unwrap());+ assert!(+ repository+ .has_merge_conflicts_by_sha(&main_sha, &orphan_sha)+ .unwrap()+ );}-/// merge_integration_probe short-circuits for orphan branches:+/// merge_integration_probe_by_sha short-circuits for orphan branches:/// would_merge_add=true, is_patch_id_match=false.#[test]fn test_merge_integration_probe_orphan_branch() {@@ -943,9 +789,12 @@ fn test_merge_integration_probe_orphan_branch() {repo.run_git(&["commit", "-m", "Orphan commit"]);repo.run_git(&["checkout", "main"]);+ let orphan_sha = repo.git_output(&["rev-parse", "orphan"]);+ let main_sha = repo.git_output(&["rev-parse", "main"]);+let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let probe = repository- .merge_integration_probe("orphan", "main")+ .merge_integration_probe_by_sha(&orphan_sha, &main_sha).unwrap();assert!(probe.would_merge_add, "orphan branch always has changes");@@ -955,7 +804,7 @@ fn test_merge_integration_probe_orphan_branch() {);}-/// merge_integration_probe correctly detects already-integrated branches+/// merge_integration_probe_by_sha correctly detects already-integrated branches/// (clean merge that doesn't change target tree).#[test]fn test_merge_integration_probe_already_integrated() {@@ -969,9 +818,12 @@ fn test_merge_integration_probe_already_integrated() {repo.run_git(&["checkout", "main"]);repo.run_git(&["merge", "feature"]);+ let feature_sha = repo.git_output(&["rev-parse", "feature"]);+ let main_sha = repo.git_output(&["rev-parse", "main"]);+let repository = Repository::at(repo.root_path().to_path_buf()).unwrap();let probe = repository- .merge_integration_probe("feature", "main")+ .merge_integration_probe_by_sha(&feature_sha, &main_sha).unwrap();assert!(!probe.would_merge_add, "already-merged branch adds nothing");