Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Feat: Indicate when committed trees match main
Maximilian Roosead95ed77367
diff --git a/src/commands/list/collect.rs b/src/commands/list/collect.rsindex d3f52a449..65f45b3ea 100644--- a/src/commands/list/collect.rs+++ b/src/commands/list/collect.rs@@ -52,6 +52,11 @@ pub(super) enum CellUpdate {item_idx: usize,counts: AheadBehind,},+ /// Whether HEAD's tree SHA matches main's tree SHA (committed content identical)+ CommittedTreesMatch {+ item_idx: usize,+ committed_trees_match: bool,+ },/// Line diff vs main branchBranchDiff {item_idx: usize,@@ -99,6 +104,7 @@ impl CellUpdate {match self {CellUpdate::CommitDetails { item_idx, .. }| CellUpdate::AheadBehind { item_idx, .. }+ | CellUpdate::CommittedTreesMatch { item_idx, .. }| CellUpdate::BranchDiff { item_idx, .. }| CellUpdate::WorkingTreeDiff { item_idx, .. }| CellUpdate::MergeTreeConflicts { item_idx, .. }@@ -153,6 +159,12 @@ fn drain_cell_updates(CellUpdate::AheadBehind { item_idx, counts } => {items[item_idx].counts = Some(counts);}+ CellUpdate::CommittedTreesMatch {+ item_idx,+ committed_trees_match,+ } => {+ items[item_idx].committed_trees_match = Some(committed_trees_match);+ }CellUpdate::BranchDiff {item_idx,branch_diff,@@ -396,6 +408,7 @@ pub fn collect(commit: None,counts: None,branch_diff: None,+ committed_trees_match: None,upstream: None,pr_status: None,status_symbols: None,@@ -747,6 +760,7 @@ pub fn build_worktree_item(commit: None,counts: None,branch_diff: None,+ committed_trees_match: None,upstream: None,pr_status: None,status_symbols: None,diff --git a/src/commands/list/collect_progressive_impl.rs b/src/commands/list/collect_progressive_impl.rsindex 7a8bea0fb..a13d5a61e 100644--- a/src/commands/list/collect_progressive_impl.rs+++ b/src/commands/list/collect_progressive_impl.rs@@ -100,6 +100,27 @@ fn spawn_ahead_behind<'scope>(}}+/// Spawn task 2b: Tree identity check (does HEAD tree match main's tree?)+fn spawn_committed_trees_match<'scope>(+ s: &'scope std::thread::Scope<'scope, '_>,+ ctx: &TaskContext,+ tx: Sender<CellUpdate>,+) {+ if let Some(base) = ctx.default_branch.as_deref() {+ let item_idx = ctx.item_idx;+ let path = ctx.repo_path.clone();+ let base = base.to_string();+ s.spawn(move || {+ let repo = Repository::at(&path);+ let committed_trees_match = repo.head_tree_matches_branch(&base).unwrap_or(false);+ let _ = tx.send(CellUpdate::CommittedTreesMatch {+ item_idx,+ committed_trees_match,+ });+ });+ }+}+/// Spawn task 3: Branch difffn spawn_branch_diff<'scope>(s: &'scope std::thread::Scope<'scope, '_>,@@ -376,6 +397,8 @@ pub fn collect_worktree_progressive(cell_count.fetch_add(1, Ordering::Relaxed);spawn_ahead_behind(s, &ctx, tx.clone());cell_count.fetch_add(1, Ordering::Relaxed);+ spawn_committed_trees_match(s, &ctx, tx.clone());+ cell_count.fetch_add(1, Ordering::Relaxed);spawn_branch_diff(s, &ctx, tx.clone());cell_count.fetch_add(1, Ordering::Relaxed);spawn_working_tree_diff(s, &ctx, tx.clone());@@ -494,6 +517,8 @@ pub fn collect_branch_progressive(cell_count.fetch_add(1, Ordering::Relaxed);spawn_ahead_behind(s, &ctx, tx.clone());cell_count.fetch_add(1, Ordering::Relaxed);+ spawn_committed_trees_match(s, &ctx, tx.clone());+ cell_count.fetch_add(1, Ordering::Relaxed);spawn_branch_diff(s, &ctx, tx.clone());cell_count.fetch_add(1, Ordering::Relaxed);spawn_upstream(s, &ctx, false, tx.clone());diff --git a/src/commands/list/layout.rs b/src/commands/list/layout.rsindex 26c0daf76..87aee0e99 100644--- a/src/commands/list/layout.rs+++ b/src/commands/list/layout.rs@@ -835,6 +835,7 @@ mod tests {branch_diff: Some(BranchDiffTotals {diff: LineDiff::from((200, 30)),}),+ committed_trees_match: Some(false),upstream: Some(UpstreamStatus::from_parts(Some("origin".to_string()), 4, 2)),pr_status: None,status_symbols: Some(StatusSymbols::default()),@@ -921,6 +922,7 @@ mod tests {branch_diff: Some(BranchDiffTotals {diff: LineDiff::default(),}),+ committed_trees_match: Some(false),upstream: Some(UpstreamStatus::default()),pr_status: None,status_symbols: Some(StatusSymbols::default()),diff --git a/src/commands/list/model.rs b/src/commands/list/model.rsindex 6c443ca76..b4f358b96 100644--- a/src/commands/list/model.rs+++ b/src/commands/list/model.rs@@ -215,6 +215,11 @@ pub struct ListItem {pub counts: Option<AheadBehind>,#[serde(flatten, skip_serializing_if = "Option::is_none")]pub branch_diff: Option<BranchDiffTotals>,+ /// Whether HEAD's tree SHA matches main's tree SHA.+ /// True when committed content is identical regardless of commit history.+ /// Internal field used to compute BranchOpState::MatchesMain.+ #[serde(skip)]+ pub committed_trees_match: Option<bool>,// TODO: Same concern as counts/branch_diff above - should upstream fields always be present?#[serde(flatten, skip_serializing_if = "Option::is_none")]@@ -248,6 +253,7 @@ impl ListItem {commit: None,counts: None,branch_diff: None,+ committed_trees_match: None,upstream: None,pr_status: None,status_symbols: None,@@ -442,6 +448,7 @@ impl ListItem {data.is_main,default_branch,counts.ahead,+ self.committed_trees_match.unwrap_or(false),data.working_tree_diff.as_ref(),&data.working_tree_diff_with_main,);@@ -508,15 +515,31 @@ impl ListItem {/// Determine branch state for a worktree.///-/// Returns:-/// - `BranchOpState::None` if main worktree or no base branch-/// - `BranchOpState::NoCommits` if no commits ahead and working tree is clean-/// - `BranchOpState::MatchesMain` if ahead == 0 but dirty tree happens to match main (rare)-/// - `BranchOpState::None` otherwise+/// # States (mutually exclusive)+///+/// **`NoCommits`** (`ahead == 0`): Branch HEAD is an ancestor of main - no unique+/// commits exist. This is the "nothing to merge" state. Note: `ahead` compares+/// commit SHAs via `git rev-list`, not content. Cherry-picked commits create new+/// SHAs, so a branch with cherry-picked-to-main commits still has `ahead > 0`.+///+/// **`MatchesMain`** (`ahead > 0`): Branch has unique commits but working tree+/// content is identical to main. Examples: merge commits that pull in main,+/// reverts that undo changes, or independent development arriving at same result.+///+/// These states are mutually exclusive: `ahead == 0` means HEAD is an ancestor of+/// main (can fast-forward), while `MatchesMain` requires unique commits that happen+/// to produce identical content.+///+/// # Parameters+///+/// - `committed_trees_match`: Whether committed tree SHAs match (HEAD^{tree} == main^{tree})+/// - `working_tree_diff_with_main`: Diff between working tree and main. May be `None` (not+/// computed) or `Some(None)` (skipped). When unavailable, assumes no match.fn determine_worktree_base_state(is_main: bool,default_branch: Option<&str>,ahead: usize,+ committed_trees_match: bool,working_tree_diff: Option<&LineDiff>,working_tree_diff_with_main: &Option<Option<LineDiff>>,) -> BranchOpState {@@ -526,17 +549,22 @@ fn determine_worktree_base_state(let is_clean = working_tree_diff.map(|d| d.is_empty()).unwrap_or(true);- // Check if no commits and clean working tree (most common removable state)if ahead == 0 && is_clean {return BranchOpState::NoCommits;}- // Check if working tree matches main exactly (requires diff with main to be computed)- // This is rare - only when ahead == 0, tree is dirty, but dirty changes happen to match main- if let Some(Some(mdiff)) = working_tree_diff_with_main.as_ref()- && mdiff.is_empty()- && ahead == 0- {+ // If committed trees match AND no uncommitted changes, working tree must match main.+ let working_tree_matches_main = if committed_trees_match && is_clean {+ true+ } else {+ // Check pre-computed diff. None/Some(None) → assume no match+ working_tree_diff_with_main+ .as_ref()+ .and_then(|opt| opt.as_ref())+ .is_some_and(|diff| diff.is_empty())+ };++ if working_tree_matches_main {BranchOpState::MatchesMain} else {BranchOpState::Nonediff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4c0e322a2..5ad8a22ef 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -712,7 +712,7 @@ impl Repository {return Ok(Some(LineDiff::default()));};- if !self.branch_tree_matches_head(branch)? {+ if !self.head_tree_matches_branch(branch)? {return Ok(None);}@@ -1066,7 +1066,9 @@ impl Repository {Ok(branch)}- fn branch_tree_matches_head(&self, branch: &str) -> anyhow::Result<bool> {+ /// 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> {let head_tree = self.rev_parse_tree("HEAD^{tree}")?;let branch_tree = self.rev_parse_tree(&format!("{branch}^{{tree}}"))?;Ok(head_tree == branch_tree)diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 8cdc3632a..9acef3d6b 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -356,6 +356,59 @@ fn test_list_json_with_metadata() {snapshot_list_json("json_with_metadata", &repo);}+/// Test that committed_trees_match is true when a branch has commits ahead but identical tree content.+/// This tests the merge commit scenario where content matches main even with different commit history.+#[test]+fn test_list_json_tree_matches_main_after_merge() {+ let mut repo = TestRepo::new();+ repo.commit("Initial commit");++ // Create feature branch with a worktree+ let feature_path = repo.add_worktree("feature-merged");++ // Make a commit on feature branch+ std::fs::write(feature_path.join("feature.txt"), "feature content").unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "."])+ .current_dir(&feature_path)+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Feature commit"])+ .current_dir(&feature_path)+ .output()+ .unwrap();++ // Make the same commit on main (so trees will match after merge)+ std::fs::write(repo.root_path().join("feature.txt"), "feature content").unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["add", "."])+ .current_dir(repo.root_path())+ .output()+ .unwrap();+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["commit", "-m", "Same content on main"])+ .current_dir(repo.root_path())+ .output()+ .unwrap();++ // Merge main into feature (creates merge commit, but tree matches main)+ let mut cmd = Command::new("git");+ repo.configure_git_cmd(&mut cmd);+ cmd.args(["merge", "main", "-m", "Merge main into feature"])+ .current_dir(&feature_path)+ .output()+ .unwrap();++ // Now feature-merged is ahead of main (has merge commit) but tree content matches main+ // JSON output should show branch_op_state: "MatchesMain" with ahead > 0+ snapshot_list_json("json_tree_matches_main_after_merge", &repo);+}+#[test]fn test_list_with_branches_flag() {let mut repo = TestRepo::new();diff --git a/tests/snapshots/integration__integration_tests__list__json_tree_matches_main_after_merge.snap b/tests/snapshots/integration__integration_tests__list__json_tree_matches_main_after_merge.snapnew file mode 100644index 000000000..354066549--- /dev/null+++ b/tests/snapshots/integration__integration_tests__list__json_tree_matches_main_after_merge.snap@@ -0,0 +1,130 @@+---+source: tests/integration_tests/list.rs+info:+ program: wt+ args:+ - list+ - "--format=json"+ env:+ CLICOLOR_FORCE: "1"+ COLUMNS: "150"+ GIT_AUTHOR_DATE: "2025-01-01T00:00:00Z"+ GIT_COMMITTER_DATE: "2025-01-01T00:00:00Z"+ GIT_CONFIG_GLOBAL: "[TEST_GIT_CONFIG]"+ GIT_CONFIG_SYSTEM: /dev/null+ GIT_EDITOR: ""+ LANG: C+ LC_ALL: C+ SOURCE_DATE_EPOCH: "1735776000"+ WORKTRUNK_BIN: ""+ WORKTRUNK_CONFIG_PATH: "[TEST_CONFIG]"+---+success: true+exit_code: 0+----- stdout -----+[+ {+ "head_sha": "133d1f05a73a1478707f3438625069c7ebd8eb27",+ "branch": "main",+ "timestamp": 0,+ "commit_message": "Same content on main",+ "ahead": 0,+ "behind": 0,+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "pr_status": null,+ "status": {+ "working_tree": {+ "untracked": false,+ "modified": false,+ "staged": false,+ "renamed": false,+ "deleted": false+ },+ "branch_op_state": "",+ "main_divergence": "IsMain",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_symbols": {+ "working_tree": "",+ "branch_op_state": "",+ "main_divergence": "^",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_line": "main",+ "type": "worktree",+ "path": "[REPO]",+ "bare": false,+ "detached": false,+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "is_main": true,+ "is_current": true+ },+ {+ "head_sha": "d78d130165cc11f6df39113ded5bbf1c16f8ebc3",+ "branch": "feature-merged",+ "timestamp": 0,+ "commit_message": "Merge main into feature",+ "ahead": 2,+ "behind": 0,+ "branch_diff": {+ "added": 0,+ "deleted": 0+ },+ "upstream_remote": null,+ "upstream_ahead": 0,+ "upstream_behind": 0,+ "pr_status": null,+ "status": {+ "working_tree": {+ "untracked": false,+ "modified": false,+ "staged": false,+ "renamed": false,+ "deleted": false+ },+ "branch_op_state": "MatchesMain",+ "main_divergence": "Ahead",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "status_symbols": {+ "working_tree": "",+ "branch_op_state": "≡",+ "main_divergence": "↑",+ "upstream_divergence": "",+ "worktree_state": ""+ },+ "commits_display": "/u001b[32m↑2/u001b[0m",+ "status_line": "feature-merged /u001b[2m≡/u001b[0m /u001b[32m↑2/u001b[0m",+ "type": "worktree",+ "path": "[REPO].feature-merged",+ "bare": false,+ "detached": false,+ "working_tree_diff": {+ "added": 0,+ "deleted": 0+ },+ "working_tree_diff_with_main": {+ "added": 0,+ "deleted": 0+ },+ "is_main": false+ }+]++----- stderr -----