Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
fix(list): diff branches against the default branch's upstream tip (#3280)
Maximilian Roosa0f07ac6d7f4
diff --git a/docs/content/list.md b/docs/content/list.mdindex 17ae3ff3f..90ca1c5d3 100644--- a/docs/content/list.md+++ b/docs/content/list.md@@ -91,6 +91,8 @@ Output as JSON for scripting:The `main` header label is used regardless of the default branch's actual name.+`main↕` and `main…±` measure against the default branch's upstream tip when the local copy lags it — so in a fork whose local `main` trails `origin/main`, a branch reads as ahead of the real mainline, not of a stale local checkout. The `↑`/`↓`/`↕` Status symbols derive from these counts, so they track the upstream tip too.+### GutterThe leftmost column marks each row by physical presence, from most present to least:diff --git a/skills/worktrunk/reference/list.md b/skills/worktrunk/reference/list.mdindex efcd54f72..4f5db1ce0 100644--- a/skills/worktrunk/reference/list.md+++ b/skills/worktrunk/reference/list.md@@ -80,6 +80,8 @@ $ wt list --format=jsonThe `main` header label is used regardless of the default branch's actual name.+`main↕` and `main…±` measure against the default branch's upstream tip when the local copy lags it — so in a fork whose local `main` trails `origin/main`, a branch reads as ahead of the real mainline, not of a stale local checkout. The `↑`/`↓`/`↕` Status symbols derive from these counts, so they track the upstream tip too.+### GutterThe leftmost column marks each row by physical presence, from most present to least:diff --git a/src/cli/mod.rs b/src/cli/mod.rsindex c683077eb..bb4c245e6 100644--- a/src/cli/mod.rs+++ b/src/cli/mod.rs@@ -823,6 +823,8 @@ $ wt list --format=jsonThe `main` header label is used regardless of the default branch's actual name.+`main↕` and `main…±` measure against the default branch's upstream tip when the local copy lags it — so in a fork whose local `main` trails `origin/main`, a branch reads as ahead of the real mainline, not of a stale local checkout. The `↑`/`↓`/`↕` Status symbols derive from these counts, so they track the upstream tip too.+### GutterThe leftmost column marks each row by physical presence, from most present to least:diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex fe9448090..3b610b654 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -27,6 +27,28 @@ use super::types::{ErrorCause, TaskError, TaskKind, TaskResult};/// across all clones via `Arc<RepoCache>`, so parallel tasks benefit from/// cached merge-base results, ahead/behind counts, default branch, and/// integration targets.+///+/// # Comparison bases+///+/// Three accessors expose "the mainline ref" a task compares against, and+/// which one to use is decided by the question the task answers:+///+/// - [`default_branch`](Self::default_branch) is the local ref. Conflict+/// prediction (`WouldConflict`) and the `wt merge` / `wt switch --base`+/// writes use it, since that is the branch the merge actually updates and+/// a remote-tracking ref is not writable.+/// - [`comparison_base`](Self::comparison_base) is the upstream-aware+/// superset tip. The ahead/behind (`main↕`) and branch-diff (`main…±`)+/// columns measure against it, so a local default that lags its upstream+/// does not inflate the distance from the real mainline.+/// - [`integration_targets`](Self::integration_targets) is that superset+/// plus, when local and upstream diverge, both sides. Integration status+/// checks whether the work has landed in the mainline on either.+///+/// All three resolve the upstream from the default branch's configured+/// `@{upstream}` alone ([`RefSnapshot::upstream_of`]); there is no+/// remote-name heuristic. The superset selection itself lives on+/// [`Repository::integration_targets`].#[derive(Clone)]pub struct TaskContext {/// Shared repository handle. All clones share the same cache via Arc.@@ -95,15 +117,40 @@ impl TaskContext {TaskError::new(self.item_idx, kind, message, cause)}- /// Get the default branch resolved for this list invocation.- ///- /// Used for informational stats (ahead/behind, branch diff). Returns- /// `None` if default branch cannot be determined, or if the persisted- /// value is stale (see `TaskContext::default_branch` docs).+ /// Get the default branch resolved for this list invocation: the local+ /// ref, used by conflict prediction and the merge/`--base` writes (see+ /// the type-level "Comparison bases" note). Returns `None` if the default+ /// branch cannot be determined, or if the persisted value is stale (see+ /// the `default_branch` field docs).pub(super) fn default_branch(&self) -> Option<String> {self.default_branch.clone()}+ /// The base ref the informational comparison columns — ahead/behind+ /// (`main↕`) and branch diff (`main…±`) — measure a branch against.+ ///+ /// This is the same upstream-aware "superset" mainline ref the+ /// integration column already uses ([`IntegrationTargets::primary`]):+ /// the local default branch when it is up to date with (or ahead of)+ /// its upstream or has no upstream, and the upstream ref when the local+ /// default *lags* it. The lagging case is the one that matters — a fork+ /// whose local `master` sits dozens of commits behind `origin/master`+ /// would otherwise make every feature read as dozens of commits and+ /// thousands of lines ahead of "main", measuring each branch against a+ /// stale base instead of the real mainline tip. Routing these columns+ /// through `primary` keeps them consistent with the integration symbol+ /// and immune to a stale local default.+ ///+ /// Falls back to the raw default branch name when integration targets+ /// could not be resolved (snapshot capture failed) so the columns still+ /// render in that degraded mode.+ pub(super) fn comparison_base(&self) -> Option<&str> {+ self.integration_targets+ .as_ref()+ .map(|t| t.primary.as_str())+ .or(self.default_branch.as_deref())+ }+/// Get the integration targets resolved for this list invocation.////// Used for integration checks (status symbols, safe deletion).@@ -172,15 +219,18 @@ pub trait Task: Send + Sync + 'static {// Task Implementations// ============================================================================-/// Task: Ahead/behind counts vs local default branch (informational stats)+/// Task: Ahead/behind counts vs the mainline tip (informational stats).+///+/// Measures against [`TaskContext::comparison_base`] — the upstream-aware+/// default-branch tip — so a stale local default doesn't inflate the counts.pub struct AheadBehindTask;impl Task for AheadBehindTask {const KIND: TaskKind = TaskKind::AheadBehind;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return zero counts (cells show empty)- let Some(base) = ctx.default_branch() else {+ // When no comparison base resolves, return zero counts (cells show empty)+ let Some(base) = ctx.comparison_base() else {return Ok(TaskResult::AheadBehind {item_idx: ctx.item_idx,counts: AheadBehind::default(),@@ -190,7 +240,7 @@ impl Task for AheadBehindTask {let repo = &ctx.repo;let base_sha = ctx- .resolve_sha(&base)+ .resolve_sha(base).map_err(|e| ctx.error(Self::KIND, &e))?;// Compare against the branch tip via its full ref when present —// see `branch_check_sha` for the rebase-in-progress rationale.@@ -220,7 +270,7 @@ impl Task for AheadBehindTask {.unwrap_or(&ctx.branch_ref.commit_sha);let counts = ctx.snapshot()- .and_then(|s| s.ahead_behind(&base, head_ref))+ .and_then(|s| s.ahead_behind(base, head_ref)).map(Ok).unwrap_or_else(|| repo.ahead_behind_by_sha(&base_sha, &head_sha)).map_err(|e| ctx.error(Self::KIND, &e))?;@@ -466,15 +516,18 @@ impl Task for IsAncestorTask {}}-/// Task 4: Branch diff stats vs local default branch (informational stats)+/// Task 4: Branch diff stats vs the mainline tip (informational stats).+///+/// Measures against [`TaskContext::comparison_base`] — the upstream-aware+/// default-branch tip — so a stale local default doesn't inflate the diff.pub struct BranchDiffTask;impl Task for BranchDiffTask {const KIND: TaskKind = TaskKind::BranchDiff;fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {- // When default_branch is None, return empty diff (cells show empty)- let Some(base) = ctx.default_branch() else {+ // When no comparison base resolves, return empty diff (cells show empty)+ let Some(base) = ctx.comparison_base() else {return Ok(TaskResult::BranchDiff {item_idx: ctx.item_idx,branch_diff: BranchDiffTotals::default(),@@ -484,7 +537,7 @@ impl Task for BranchDiffTask {// Resolve via snapshot — see `branch_check_sha` for the// rebase-in-progress rationale.let base_sha = ctx- .resolve_sha(&base)+ .resolve_sha(base).map_err(|e| ctx.error(Self::KIND, &e))?;let head_sha = ctx.branch_check_sha()diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 178be0b56..28a7044c6 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -715,6 +715,117 @@ fn test_list_with_upstream_tracking(mut repo: TestRepo) {});}+/// When the local default branch lags its upstream (a fork whose `main` sits+/// behind `origin/main`), the `main↕`/`main…±` columns must measure each+/// branch against the upstream tip, not the stale local tip. Otherwise every+/// branch reads as ahead by every commit the local default is missing.+#[rstest]+fn test_list_branch_stats_use_upstream_when_local_default_lags(mut repo: TestRepo) {+ repo.commit("c0");+ repo.setup_remote("main");+ // Persist the default branch so detection is deterministic.+ repo.run_git(&["config", "worktrunk.default-branch", "main"]);++ // Advance origin/main three commits ahead, then pin local main back so it+ // lags its upstream by three commits (the stale-fork shape).+ repo.commit("upstream 1");+ repo.commit("upstream 2");+ repo.commit("upstream 3");+ repo.run_git(&["push", "origin", "main"]);+ repo.run_git(&["reset", "--hard", "HEAD~3"]);+ repo.run_git(&["fetch", "origin"]);++ // Feature branch off the real upstream tip, two commits ahead.+ let feature_wt = repo.add_worktree("feature");+ repo.run_git_in(&feature_wt, &["reset", "--hard", "origin/main"]);+ std::fs::write(feature_wt.join("feat.txt"), "a\n").unwrap();+ repo.run_git_in(&feature_wt, &["add", "."]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "feature commit 1"]);+ std::fs::write(feature_wt.join("feat.txt"), "a\nb\n").unwrap();+ repo.run_git_in(&feature_wt, &["add", "."]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "feature commit 2"]);++ let output = repo+ .wt_command()+ .args(["list", "--branches", "--format=json"])+ .output()+ .unwrap();+ assert!(output.status.success(), "wt list should succeed");++ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();+ let feature = json+ .iter()+ .find(|w| w["branch"] == "feature")+ .expect("feature row should be present");++ // Two commits ahead of the upstream tip — not five (3 stale + 2 feature).+ assert_eq!(+ feature["main"]["ahead"].as_u64(),+ Some(2),+ "ahead must be measured against origin/main, not the stale local main: {feature:#?}"+ );+ assert_eq!(feature["main"]["behind"].as_u64(), Some(0));+ // The diff reflects only the feature's own additions, not the three+ // upstream commits the local default is missing.+ assert_eq!(+ feature["main"]["diff"]["added"].as_u64(),+ Some(2),+ "branch diff must be measured against origin/main: {feature:#?}"+ );+}++/// The mirror of the lagging-fork case: when the local default branch is+/// *ahead* of its upstream (local commits not yet pushed, e.g. just after a+/// local `wt merge`), the base must stay local. Otherwise a sibling branch+/// would show those unpushed default-branch commits in its own counts. This+/// pins the contract that `comparison_base` reuses `integration_targets`'+/// superset selection rather than naively preferring the upstream ref.+#[rstest]+fn test_list_branch_stats_stay_local_when_default_ahead_of_upstream(mut repo: TestRepo) {+ repo.commit("c0");+ repo.setup_remote("main");+ repo.run_git(&["config", "worktrunk.default-branch", "main"]);++ // Advance local main three commits past origin/main, leaving them unpushed+ // so the local default is ahead of its upstream.+ repo.commit("local main 1");+ repo.commit("local main 2");+ repo.commit("local main 3");+ repo.run_git(&["fetch", "origin"]);++ // Feature off the local default tip, two commits ahead.+ let feature_wt = repo.add_worktree("feature");+ std::fs::write(feature_wt.join("feat.txt"), "a\n").unwrap();+ repo.run_git_in(&feature_wt, &["add", "."]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "feature commit 1"]);+ std::fs::write(feature_wt.join("feat.txt"), "a\nb\n").unwrap();+ repo.run_git_in(&feature_wt, &["add", "."]);+ repo.run_git_in(&feature_wt, &["commit", "-m", "feature commit 2"]);++ let output = repo+ .wt_command()+ .args(["list", "--branches", "--format=json"])+ .output()+ .unwrap();+ assert!(output.status.success(), "wt list should succeed");++ let json: Vec<serde_json::Value> = serde_json::from_slice(&output.stdout).unwrap();+ let feature = json+ .iter()+ .find(|w| w["branch"] == "feature")+ .expect("feature row should be present");++ // Two commits ahead of the LOCAL default tip — not five (which would+ // wrongly fold in the three unpushed local-main commits by measuring+ // against origin/main).+ assert_eq!(+ feature["main"]["ahead"].as_u64(),+ Some(2),+ "ahead must stay measured against local main when it leads origin/main: {feature:#?}"+ );+ assert_eq!(feature["main"]["behind"].as_u64(), Some(0));+}+#[rstest]fn test_list_primary_on_different_branch(mut repo: TestRepo) {repo.switch_primary_to("develop");diff --git a/tests/snapshots/integration__integration_tests__help__help_list_long.snap b/tests/snapshots/integration__integration_tests__help__help_list_long.snapindex 9af454eac..42405d12b 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_long.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_long.snap@@ -150,6 +150,8 @@ Output as JSON for scripting:The [2mmain[0m header label is used regardless of the default branch's actual name.+[2mmain↕[0m and [2mmain…±[0m measure against the default branch's upstream tip when the local copy lags it — so in a fork whose local [2mmain[0m trails [2morigin/main[0m, a branch reads as ahead of the real mainline, not of a stale local checkout. The [2m↑[0m/[2m↓[0m/[2m↕[0m Status symbols derive from these counts, so they track the upstream tip too.+[32mGutter[0mThe leftmost column marks each row by physical presence, from most present to least:diff --git a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snapindex a5d7b00d5..8dce57bce 100644--- a/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap+++ b/tests/snapshots/integration__integration_tests__help__help_list_narrow_80.snap@@ -163,6 +163,11 @@ Output as JSON for scripting:The [2mmain[0m header label is used regardless of the default branch's actual name.+[2mmain↕[0m and [2mmain…±[0m measure against the default branch's upstream tip when the+local copy lags it — so in a fork whose local [2mmain[0m trails [2morigin/main[0m, a branch+reads as ahead of the real mainline, not of a stale local checkout. The [2m↑[0m/[2m↓[0m/[2m↕[0m+Status symbols derive from these counts, so they track the upstream tip too.+[32mGutter[0mThe leftmost column marks each row by physical presence, from most present to