Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(git): RefSnapshot — close ambient ref-keyed cache staleness class (#2528)
Maximilian Roos845baeb976ee
diff --git a/docs/dev/cache-staleness.md b/docs/dev/cache-staleness.mdnew file mode 100644index 000000000..9d7903913--- /dev/null+++ b/docs/dev/cache-staleness.md@@ -0,0 +1,359 @@+# Eliminating ref-keyed cache staleness++## Background++`Repository::RepoCache` (in `src/git/repository/mod.rs`) holds per-command+caches that survive any number of git operations on the same `Repository`+instance. Several of those caches are keyed on **ref names** (e.g. `"main"`,+`"refs/heads/main"`, `"HEAD"`). Ref names are not stable — their SHAs change+when wt itself updates a ref mid-command (`wt merge`'s `update-ref`,+`commit-tree` + `update-ref` in `worktree/push.rs`, future write paths). After+such a write, ref-keyed entries return the pre-write SHA and any computation+downstream of that SHA is silently wrong.++PR #2507 fixed exactly this for one call site: `Repository::is_ancestor` was+reading stale SHAs out of `commit_shas`, so `integration_reason` misclassified+a just-merged branch as unmerged. The fix added a local helper+(`ref_is_ancestor`) that bypasses the cache. It works, but every other ref-name+read through `rev_parse_commit` after a write has the same latent bug.++We want to eliminate the bug class **structurally**, not by remembering to+invalidate. Invalidation discipline scales linearly with new write call sites;+structural elimination scales with zero.++## Inventory: caches keyed on ref names today++Read `RepoCache` (`src/git/repository/mod.rs:204-316`) and treat anything+keyed by `String` ref name as a staleness vector. Concretely:++| Cache field | Key | Used by | Stale risk after a ref update? |+| --------------------------------- | ---------------------------- | ------------------------------------------- | ------------------------------- |+| `commit_shas` | ref name | `rev_parse_commit` → all SHA-keyed caches | **Yes** — primary bug source |+| `tree_shas` | tree spec (e.g. `…^{tree}`) | `rev_parse_tree` | **Yes** |+| `resolved_refs` | short name → full ref | `resolve_preferring_branch` | No (refs/heads/X doesn't move) |+| `ahead_behind` | `(base ref, head ref)` | `wt list`'s ahead/behind, upstream task | **Yes** if either ref updates |+| `effective_integration_targets` | local target ref name | `effective_integration_target` | **Yes** (depends on local tip) |+| `integration_reasons` | `(branch, target)` ref names | `integration_reason` | **Yes** (composite of above) |+| `head_shas` | worktree path | `WorkingTree::head_sha` | **Yes** (HEAD moves on commit) |+| `local_branches` inventory | n/a (one-shot scan) | every multi-branch op | **Yes** (frozen view) |++Caches keyed entirely by **SHA** (`merge_base`, `diff_stats`, the persistent+on-disk `sha_cache::*`) are structurally safe — a SHA addresses immutable+content. The risk is only at the **ref-name → SHA boundary**.++## Where ref writes happen today++`grep -rn "update-ref\|update_ref" src/`:++- `src/commands/worktree/push.rs:385` — `update-ref` on the merge target.+- `src/commands/merge.rs:286` (calls into push.rs) — `wt merge` flow.+- `src/git/repository/working_tree.rs:563` — `update-ref` for stash/branch ops.+- Any `git commit`, `git rebase`, or hook subprocess can update a local ref+ too. We don't `update-ref` those ourselves but the underlying refs move.++The `wt merge` flow is the canonical example: rebase → `update-ref` target →+`finish_after_merge` → `compute_integration_reason` → reads stale `main` SHA.++## Goals & constraints (recap)++- **No invalidation logic.** "Call `cache.clear_ref(name)` after every write"+ is the failure mode, not the solution.+- **Performance still matters.** `rev_parse_commit` is consulted by+ `is_ancestor`, `merge_base`, `merge_integration_probe`, `branch_diff_stats`,+ `has_added_changes`. In `wt list` with 100 worktrees these run hundreds of+ times. Today, the `local_branches` for-each-ref pre-population dodges most+ rev-parse subprocesses for branch refs.+- **Per-command lifetime.** `Repository` lives for one CLI command, so+ cross-command persistence is irrelevant for in-memory caches.+- **`wt list` is read-only.** No ref writes happen during it; the staleness+ bug class doesn't manifest. Whatever we choose must not regress its+ performance.+- **Mutate-then-read commands are rare** (`wt merge`, `wt remove`, future+ `wt rebase`?). Performance there is bounded by the git operations+ themselves.++## Options++### Option 1 — Cache only by SHA at the boundary++**What it changes structurally.** Drop `commit_shas` and `tree_shas`. Public+API still takes ref names but resolves them locally with no cache. Each+ref-name → SHA conversion spawns one `git rev-parse` per call. SHA-keyed+caches (in-memory `merge_base`, on-disk `sha_cache::*`) keep working as today.++**Where the work lands.** `rev_parse_commit`/`rev_parse_tree` in+`integration.rs:509-547` lose their `DashMap::entry` wrappers. The priming in+`branches.rs:155-166` goes away. Direct callers of those helpers+(`is_ancestor`, `has_added_changes`, `has_merge_conflicts`, `branch_diff_stats`,+`merge_integration_probe`, `has_merge_conflicts_by_tree`, `would_merge_add_to_target`)+keep their signatures but pay one extra subprocess per ref per call.++**Performance impact.** For `wt list` with N worktrees and ~5 SHA-keyed ops+per row: roughly 10×N additional `git rev-parse` subprocesses (2 ref → SHA+conversions × 5 ops). At ~3-5ms each that is **300-500 ms regression on a+100-worktree repo** — same order as the entire current `wt list` runtime+budget. Mutate-then-read commands gain a handful of subprocesses; negligible.++**What it does NOT solve.** `effective_integration_targets`,+`integration_reasons`, `ahead_behind`, `head_shas`. These are keyed on refs+but their *values* are derived through ref-relative operations (upstream+relationships, ahead/behind counts), so they aren't pure functions of SHAs.+You'd still need a separate decision for each one.++**Migration cost.** Low surface area (~60 LOC) but sizable performance loss+on the read-only hot path.++### Option 2 — Two-tier API: `is_ancestor(refs)` uncached, `is_ancestor_by_sha` cached++**What it changes structurally.** Every public op exists in two forms:++```rust+// Public, ref-taking, no SHA cache:+pub fn is_ancestor(&self, base: &str, head: &str) -> Result<bool> { ... }+// Internal, SHA-taking, cached:+fn is_ancestor_by_sha(&self, base: &Sha, head: &Sha) -> Result<bool> { ... }+```++The ref-taking form runs git directly (`merge-base --is-ancestor` accepts ref+names natively, as does `rev-parse a b` for `same_commit`/`trees_match`).+Callers that want cache hits must explicitly hold SHAs.++**Where the work lands.** Same files as Option 1, but with twice as many+public methods. Each task in `commands/list/collect/tasks.rs` switches from+`repo.is_ancestor(branch, target)` to first resolving SHAs through a+snapshot (see Option 5) and then calling `is_ancestor_by_sha`.++**Performance impact.** Same as Option 1 if hot-path callers stay on the+ref-taking form. Same as today if they migrate to the SHA-taking form.+This option *enables* the fast path; it doesn't force it.++**What it does NOT solve.** Same residual risks as Option 1 — composite+caches (`integration_reasons`, `effective_integration_targets`, `ahead_behind`)+need separate treatment.++**Migration cost.** Medium. Each cached op gains a sibling. `wt list` task+code changes to thread SHAs through (~20 call sites).++### Option 3 — Type-level distinction (`Sha` newtype)++**What it changes structurally.** Introduce+`pub struct Sha(String)` (or `Sha([u8; 20])`) constructed only via+`Repository::resolve(&str) -> Sha` (uncached) or via the `for-each-ref` scan+(produces `Sha`s tied to a snapshot). Cached methods take `&Sha` and refuse+`&str`. Compiler enforces "you must resolve before caching."++**Where the work lands.** `Sha` propagates through `BranchRef`, `LocalBranch`,+task contexts in `commands/list/collect/`, every diff/integration helper.+Tests that hardcode SHA strings need conversion.++**Performance impact.** Same as Option 2 — the type system says nothing about+when you spawn rev-parse, only that you've named the conversion.++**What it does NOT solve.** Composite caches still need explicit decisions.+A `Sha` newtype prevents storing `String` ref-name keys in SHA-keyed caches,+but does not make `effective_integration_target` (whose result depends on the+upstream relationship at lookup time, not on the SHA) safe.++**Migration cost.** High. Newtype propagation reaches a lot of call sites+(`BranchRef.commit_sha: String` becomes `Sha`, every test fixture, every+JSON serialization path). The type-level guarantee is real but the surface+area touched is wide.++### Option 4 — Delete the in-memory ref-keyed caches outright++**What it changes structurally.** Drop `commit_shas`, `tree_shas`,+`effective_integration_targets`, `integration_reasons`, `ahead_behind`,+`head_shas`. Stop priming. Every cached op spawns its underlying git+command(s) every call. The persistent on-disk `sha_cache::*` survives because+its keys are SHAs.++**Where the work lands.** Delete fields and entry-block wrappers across+`integration.rs`, `diff.rs`, `working_tree.rs`. Remove the priming loop in+`branches.rs:155-166`.++**Performance impact.** Severe. `wt list` with 100 worktrees today calls+`is_ancestor`, `has_added_changes`, `merge_integration_probe`, etc. relying+on cached SHAs and (for `ahead_behind`) cached counts batched in+`batch_ahead_behind`. Without those caches you're spawning thousands of+subprocesses per command. Likely 5-10× regression on `wt list`.++**What it does NOT solve.** Removes the bug entirely, but at unacceptable+cost. Listing it for completeness — also useful as a baseline reminder that+the cache is load-bearing for the read-only hot path.++**Migration cost.** Low surface area. High user-visible impact.++### Option 5 — Resolve-once-up-front (`RefSnapshot`)++**What it changes structurally.** At command entry, one explicit+`let snapshot = repo.snapshot()?;` call performs the `for-each-ref` scan and+produces an immutable `RefSnapshot`. The snapshot holds ref name → SHA for+every local + remote branch, plus HEAD, plus any other refs of interest.+Cached SHA-keyed ops take `&Sha` (or `&str` plus `&RefSnapshot`). Repository+itself drops ambient ref-keyed caches.++After a ref-mutating operation, the caller produces a new snapshot. Old+snapshots remain valid as historical views — by name, you can see they+represent the pre-write state. This is the same shape `local_branches`+already has (a `OnceCell<LocalBranchInventory>` populated by one+for-each-ref), promoted to first-class status with explicit lifetime.++```rust+let snap = repo.snapshot()?; // implicit "ref state right now"+let target_sha = snap.resolve(target)?; // never spawns git+let branch_sha = snap.resolve(branch)?;+let integrated = repo.is_ancestor_by_sha(&branch_sha, &target_sha)?;++// ... wt merge writes the target ref ...++let snap2 = repo.snapshot()?; // explicit "after the write"+let target_sha = snap2.resolve(target)?;+// integration check against the post-write target — naturally fresh+```++**Where the work lands.** New `RefSnapshot` type (~100 LOC). Public ops in+`integration.rs`/`diff.rs` either gain `_by_sha` variants (Option 2 style)+or accept `&RefSnapshot` directly. `commands/list/collect/` builds one+snapshot during pre-skeleton, threads it through tasks instead of (or in+addition to) `Arc<RepoCache>`. `wt merge`'s `finish_after_merge` builds a+fresh snapshot post-`update-ref` and uses it for the integration check —+the post-write call gets the post-write state by construction.++**Performance impact.** Roughly neutral to positive. Today's+`local_branches` scan + `commit_shas` priming already does this work; the+proposal just names it. Subsequent SHA lookups become plain `HashMap::get`+on a frozen view (no `DashMap` shard contention). `wt list` gets one+deterministic scan up-front instead of lazy `OnceCell::get_or_try_init`+race; all parallel tasks read from the immutable snapshot. `wt merge` pays+for one extra `for-each-ref` after the ref update — ~5-15 ms.++**What it does NOT solve.** The discipline of "after a write, take a new+snapshot" is still required. The improvement is that:+1. Snapshots are *named*, so the contract is visible at every call site.+2. Forgetting to re-snapshot reads pre-write state explicitly, not+ "from a cache that is supposed to be transparent."+3. The bug surface compresses to a small number of write boundaries+ instead of every ref-name accessor in the codebase.++`effective_integration_targets`, `integration_reasons`, and `ahead_behind`+become functions of `(snapshot, ref pair)` — keyed by the snapshot's SHAs+they're derived from. Stale-by-construction is no longer possible: a+snapshot is internally consistent.++**Migration cost.** Medium-high. `RefSnapshot` has to be threaded through+hot paths. But the threading replaces existing `Arc<RepoCache>` usage in+`tasks.rs`, so it's a refactor, not net-new plumbing.++### Option 6 — "Take a fresh `Repository::at(...)` after writes"++**What it changes structurally.** Document and rely on the existing pattern:+`Repository::at(...)` builds a brand-new `RepoCache`. Code that reads after+its own writes constructs a fresh Repository.++**Where the work lands.** `finish_after_merge`, `handle_no_ff_merge`, every+future write call site — gain `let repo = Repository::at(...)?;` after the+write.++**Performance impact.** A second Repository pays for a duplicate+`for-each-ref` scan on the next inventory access. ~5-15 ms.++**What it does NOT solve.** This is **invalidation by another name**. It's+exactly the discipline-based approach the goals exclude — easy to forget,+new write call sites are latent bugs. List it only because the codebase+already documents this pattern for `list_worktrees`. Not a recommendation.++**Migration cost.** Trivial in code, infinite in vigilance.++## Recommendation++**Go with Option 5 (`RefSnapshot`), positioned as a refinement of the+existing `local_branches` inventory.**++The argument:++1. **The shape already exists.** `OnceCell<LocalBranchInventory>` plus+ `commit_shas` priming via `for-each-ref` is a snapshot in everything but+ name. Today its frozen-ness is implicit and undocumented; staleness leaks+ through `commit_shas` because callers don't know the cache is a snapshot.+ Promoting it to a first-class `RefSnapshot` type makes the contract+ explicit at every call site.++2. **It's the only option that addresses composite caches structurally.**+ Options 1-3 fix `commit_shas` but leave `effective_integration_targets`,+ `integration_reasons`, and `ahead_behind` exposed. Option 5 makes all of+ them derived properties of an immutable snapshot, so they're internally+ consistent by construction.++3. **It preserves the read-only hot path.** `wt list` builds one snapshot+ pre-skeleton and reads from it for the rest of the command. Performance+ is neutral or marginally better than today's `DashMap` priming.++4. **It localizes the discipline.** Today, every ref-name accessor in the+ codebase is a potential staleness vector. After Option 5, only the+ write boundaries (`finish_after_merge`, `handle_no_ff_merge`,+ `working_tree.rs:563`) need to think about freshness. They take a new+ snapshot. That's the smallest possible surface for the discipline that+ we still need.++5. **The `is_ancestor` workaround in PR #2507 dissolves.** With Option 5,+ `compute_integration_reason_uncached` simply takes the post-write+ snapshot — no ad-hoc `ref_is_ancestor` helper, no comments warning+ future readers about cache bypass.++### Concrete shape++```rust+// New: src/git/repository/snapshot.rs+pub struct RefSnapshot {+ // Frozen at construction. Local + remote branches + HEAD + a few specials.+ refs: HashMap<String, Sha>,+ // Derived in one pass alongside the for-each-ref scan:+ upstream_of: HashMap<String, String>,+ ahead_behind: HashMap<(String, String), (usize, usize)>,+}++impl RefSnapshot {+ pub fn resolve(&self, name: &str) -> anyhow::Result<&Sha> { ... }+ pub fn upstream_of(&self, branch: &str) -> Option<&str> { ... }+ pub fn ahead_behind(&self, base: &str, head: &str) -> Option<(usize, usize)> { ... }+}++impl Repository {+ /// Snapshot the current ref state: one for-each-ref + ahead-behind batch.+ /// Cheap to call; no in-memory cache, by design.+ pub fn snapshot(&self) -> anyhow::Result<RefSnapshot> { ... }+}+```++`Repository`'s ambient ref-keyed fields (`commit_shas`, `tree_shas`,+`effective_integration_targets`, `integration_reasons`, `ahead_behind`,+`head_shas`) all go away. The persistent `sha_cache::*` keeps its SHA keys.+Public ops gain `_by_sha` variants for cached fast paths; ref-taking variants+exist only as thin shims that resolve uncached and call the SHA form (so a+caller that doesn't need a snapshot still works, just spawns one rev-parse).++### What we accept++- One up-front `for-each-ref` per snapshot (~5-15 ms). Already the dominant+ pattern.+- Discipline at write boundaries — but the boundaries are *the writes+ themselves*, not every read.+- A type & lifetime story for `RefSnapshot` to thread through tasks. This+ is the bulk of the migration work.++### What we don't do++- Don't add invalidation hooks.+- Don't keep `commit_shas` "with a TODO".+- Don't bake compatibility with a parallel ambient-cache path. Cut over.++## Open questions for implementation (not answered here)++- Should `RefSnapshot` be `Arc`-wrapped for parallel task fan-out, or is+ cheap clone-by-value enough? (Rough size: ~200 branches × 60 bytes ≈ 12 KB.)+- Does the snapshot need to include tag refs? Audit the call sites.+- For `wt merge`, does `finish_after_merge` build the post-write snapshot+ itself, or does the caller pass it in?+- Does `Sha` become a newtype, or stays a `String` typedef inside+ `RefSnapshot`? The newtype upside (Option 3's static guarantee) compounds+ with Option 5; the migration cost is the question.diff --git a/src/commands/list/collect/execution.rs b/src/commands/list/collect/execution.rsindex d497e89f3..b1a200f68 100644--- a/src/commands/list/collect/execution.rs+++ b/src/commands/list/collect/execution.rs@@ -357,6 +357,7 @@ pub fn work_items_for_worktree(llm_command: options.llm_command.clone(),default_branch: options.default_branch.clone(),integration_targets: options.integration_targets.clone(),+ snapshot: options.snapshot.clone(),};let has_commits = wt.has_commits();@@ -469,6 +470,7 @@ pub fn work_items_for_branch(llm_command: options.llm_command.clone(),default_branch: options.default_branch.clone(),integration_targets: options.integration_targets.clone(),+ snapshot: options.snapshot.clone(),};let mut items = Vec::with_capacity(11);@@ -546,6 +548,7 @@ mod tests {llm_command: None,default_branch: None,integration_targets: None,+ snapshot: None,};let expected_results = Arc::new(ExpectedResults::default());@@ -590,6 +593,7 @@ mod tests {url_template: None,default_branch: None,integration_targets: None,+ snapshot: None,};let expected_results = Arc::new(ExpectedResults::default());diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 2d34455ab..f4578f143 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -315,6 +315,16 @@ pub struct CollectOptions {/// over them, matching `Repository::integration_reason`. `None` when/// the default branch is unset or stale.pub integration_targets: Option<worktrunk::git::IntegrationTargets>,++ /// Captured ref state for this list invocation.+ ///+ /// Built once during the pre-skeleton phase by+ /// [`Repository::capture_refs_with_ahead_behind`] and shared (cheaply,+ /// behind `Arc`) into every task. Tasks resolve target ref names to+ /// commit SHAs through this snapshot, then call the `_by_sha` variants+ /// of cached methods — bypassing the ambient ref→SHA cache entirely.+ /// `None` when capture failed (degraded mode).+ pub snapshot: Option<std::sync::Arc<worktrunk::git::RefSnapshot>>,}fn worktree_branch_set(worktrees: &[WorktreeInfo]) -> HashSet<&str> {@@ -882,6 +892,7 @@ pub fn collect(llm_command,default_branch: default_branch.clone(),integration_targets: None,+ snapshot: None,};// Track expected results per item - populated as spawns are queued@@ -1006,8 +1017,7 @@ pub fn collect(// See: https://gitlab.com/gitlab-org/git/-/merge_requests/148 (scalar's fsmonitor workaround)// See: https://github.com/jj-vcs/jj/issues/6440 (jj hit same fsmonitor issue)let previous_branch_cell: OnceCell<Option<String>> = OnceCell::new();- let integration_targets_cell: OnceCell<Option<worktrunk::git::IntegrationTargets>> =- OnceCell::new();+ let snapshot_cell: OnceCell<Option<worktrunk::git::RefSnapshot>> = OnceCell::new();rayon::scope(|s| {// Previous branch lookup (for gutter symbol)@@ -1015,10 +1025,17 @@ pub fn collect(let _ = previous_branch_cell.set(repo.switch_previous());});- // Integration targets (primary plus optional secondary in the- // diverged case — see `Repository::integration_targets`).+ // Capture ref state. One `for-each-ref refs/heads/ refs/remotes/`+ // plus (when default_branch is known) one `for-each-ref+ // %(ahead-behind:BASE)` batch. The snapshot replaces the prior+ // `commit_shas` priming + `batch_ahead_behind` pair: tasks consume+ // it by SHA, dodging ref→SHA cache staleness.s.spawn(|_| {- let _ = integration_targets_cell.set(repo.integration_targets());+ let snap = match default_branch.as_deref() {+ Some(db) => repo.capture_refs_with_ahead_behind(db).ok(),+ None => repo.capture_refs().ok(),+ };+ let _ = snapshot_cell.set(snap);});// Fsmonitor daemon starts (one spawn per worktree)@@ -1031,16 +1048,27 @@ pub fn collect(// Extract results from cellslet previous_branch = previous_branch_cell.into_inner().flatten();- let integration_targets = integration_targets_cell.into_inner().flatten();+ let snapshot = snapshot_cell+ .into_inner()+ .flatten()+ .map(std::sync::Arc::new);++ // Resolve integration targets from the snapshot. Same OR semantics+ // as `Repository::integration_reason` (`primary` + optional+ // `secondary` only in the diverged case).+ let integration_targets = snapshot+ .as_deref()+ .and_then(|s| repo.integration_targets(s));- // Patch integration_targets into options now that they're resolved.- // When default_branch is None (unset or stale), also null it out —- // tasks otherwise see a target derived from the stale value and emit- // "ambiguous argument" noise.+ // Patch integration_targets and snapshot into options. When+ // default_branch is None (unset or stale), null integration_targets+ // out — tasks otherwise see a target derived from the stale value+ // and emit "ambiguous argument" noise.options.integration_targets = options.default_branch.as_ref().and(integration_targets.clone());+ options.snapshot = snapshot;// Update is_previous on itemsif let Some(prev) = previous_branch.as_deref() {@@ -1071,20 +1099,10 @@ pub fn collect(}}- // Batch-fetch ahead/behind counts for all local branches in a single- // `git for-each-ref` call. Primes the Repository cache so each- // `AheadBehindTask` hits the cache instead of spawning its own- // `git rev-list --count`. One git call replaces N.- //- // Note: `resolved_refs`, `commit_shas`, and upstream tracking info are- // already primed by `local_branches()` (called during pre-skeleton- // phase), so `Branch::upstream()` is an in-memory lookup from here on.- //- // On git < 2.36 (no `%(ahead-behind:)` support) or if default_branch is- // unknown, skip the batch — individual tasks fall back to direct calls.- if let Some(ref db) = default_branch {- repo.batch_ahead_behind(db);- }+ // No need to prime the ambient `cache.ahead_behind` here: the+ // snapshot captured above carries the same batched data, and all+ // tasks consume it by SHA. (Step 5 deletes `cache.ahead_behind`+ // entirely.)// Note: URL template expansion is deferred to task spawning (in collect_worktree_progressive// and collect_branch_progressive). This parallelizes the work and minimizes time-to-skeleton.@@ -1207,7 +1225,10 @@ pub fn collect(let reveal_at = (progressive_state.is_some() || progressive_handler.is_some()).then_some(placeholder_reveal_at);- let primary_target = integration_targets.as_ref().map(|t| t.primary.as_str());+ let primary_target = options+ .integration_targets+ .as_ref()+ .map(|t| t.primary.as_str());let drain_outcome = drain_results(rx,@@ -1613,20 +1634,26 @@ pub fn populate_item(return Ok(());};- // Get integration targets for status symbol computation (cached in repo)- // None if default branch cannot be determined - status symbols will be skipped- let targets = repo.integration_targets();-- // Populate default_branch / integration_targets if the caller didn't.- // Tasks read these through `TaskContext`; `None` here tells them to- // skip (see collect()'s stale-default-branch path). Single-item callers- // like statusline pass `CollectOptions::default()` and expect the- // repo-derived values.+ // Populate default_branch / snapshot / integration_targets if the+ // caller didn't. Tasks read these through `TaskContext`; `None`+ // values tell them to skip (see collect()'s stale-default-branch+ // path). Single-item callers like statusline pass+ // `CollectOptions::default()` and expect the repo-derived values.if options.default_branch.is_none() {options.default_branch = repo.default_branch();}+ if options.snapshot.is_none() {+ options.snapshot = match options.default_branch.as_deref() {+ Some(db) => repo.capture_refs_with_ahead_behind(db).ok(),+ None => repo.capture_refs().ok(),+ }+ .map(std::sync::Arc::new);+ }if options.integration_targets.is_none() {- options.integration_targets = targets.clone();+ options.integration_targets = options+ .snapshot+ .as_deref()+ .and_then(|s| repo.integration_targets(s));}// Create channel for task results@@ -1684,7 +1711,10 @@ pub fn populate_item(&mut errors,&expected_results,std::time::Instant::now() + results::DRAIN_TIMEOUT,- targets.as_ref().map(|t| t.primary.as_str()),+ options+ .integration_targets+ .as_ref()+ .map(|t| t.primary.as_str()),|_event| {},None,);@@ -1713,7 +1743,12 @@ pub fn populate_item(// Ensure status symbols are refreshed even if all tasks errored// (the drain only calls refresh on the success path).- item.refresh_status_symbols(targets.as_ref().map(|t| t.primary.as_str()));+ item.refresh_status_symbols(+ options+ .integration_targets+ .as_ref()+ .map(|t| t.primary.as_str()),+ );// Populate display fields (including status_line for statusline command)item.finalize_display();diff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex f5a0f8857..6ed72522f 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -6,8 +6,10 @@use std::net::{SocketAddr, TcpStream};use std::time::Duration;+use std::sync::Arc;+use anyhow::Context;-use worktrunk::git::{IntegrationTargets, LineDiff, Repository};+use worktrunk::git::{IntegrationTargets, LineDiff, RefSnapshot, Repository};use super::super::ci_status::{CiBranchName, PrStatus};use super::super::model::{@@ -56,6 +58,12 @@ pub struct TaskContext {/// when the default branch is unset or stale, keeping the same/// silent-skip contract as `default_branch`.pub integration_targets: Option<IntegrationTargets>,+ /// Captured ref state for this list invocation. Tasks resolve ref+ /// names to commit SHAs through this snapshot before calling+ /// `_by_sha` methods on `Repository`, side-stepping the ambient+ /// ref→SHA cache. `None` when snapshot capture failed (degraded+ /// mode — tasks fall back to ref-taking methods).+ pub snapshot: Option<Arc<RefSnapshot>>,}impl TaskContext {@@ -95,6 +103,40 @@ impl TaskContext {pub(super) fn integration_targets(&self) -> Option<&IntegrationTargets> {self.integration_targets.as_ref()}++ /// Captured ref state for this list invocation. Returns `None` when+ /// snapshot capture failed during pre-skeleton.+ pub(super) fn snapshot(&self) -> Option<&RefSnapshot> {+ self.snapshot.as_deref()+ }++ /// Resolve a ref name to its commit SHA via the snapshot, falling back+ /// to an uncached `git rev-parse` when the snapshot doesn't carry the+ /// ref (e.g., HEAD, raw SHAs, tags) or when no snapshot was captured.+ pub(super) fn resolve_sha(&self, name: &str) -> anyhow::Result<String> {+ if let Some(snap) = self.snapshot()+ && let Some(sha) = snap.resolve(name)+ {+ return Ok(sha.to_string());+ }+ Ok(self+ .repo+ .run_command(&["rev-parse", name])?+ .trim()+ .to_string())+ }++ /// Commit SHA used to compare the branch's content. Prefers the SHA+ /// the branch's full ref points at (so a rebase-in-progress doesn't+ /// compare against the transient HEAD); falls back to+ /// `branch_ref.commit_sha` for detached-HEAD items.+ pub(super) fn branch_check_sha(&self) -> anyhow::Result<String> {+ if let Some(full_ref) = self.branch_ref.full_ref() {+ self.resolve_sha(full_ref)+ } else {+ Ok(self.branch_ref.commit_sha.clone())+ }+ }}// ============================================================================@@ -139,10 +181,18 @@ impl Task for AheadBehindTask {};let repo = &ctx.repo;+ let base_sha = ctx+ .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.+ let head_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;+// Check for orphan branch (no common ancestor with default branch).- // merge_base() is cached, so this is cheap after first call.let is_orphan = repo- .merge_base(&base, &ctx.branch_ref.commit_sha)+ .merge_base_by_sha(&base_sha, &head_sha).map_err(|e| ctx.error(Self::KIND, &e))?.is_none();@@ -154,23 +204,25 @@ impl Task for AheadBehindTask {});}- // When the ref has a branch name, compute counts against the branch — not- // the worktree's current HEAD sha. During rebase/merge conflicts, HEAD is- // transiently at a different commit than the branch tip, so using the sha- // would report misleading counts (e.g., `0/0 same_commit` when the branch- // is actually diverged). The batch path already uses branch names, so this- // keeps both paths consistent.- let head = ctx+ // Snapshot's ahead/behind batch is keyed by ref names — try the+ // batched answer first, fall back to a per-pair query keyed by SHA.+ let head_ref = ctx.branch_ref.full_ref().unwrap_or(&ctx.branch_ref.commit_sha);- let (ahead, behind) = repo- .ahead_behind(&base, head)+ let counts = ctx+ .snapshot()+ .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))?;Ok(TaskResult::AheadBehind {item_idx: ctx.item_idx,- counts: AheadBehind { ahead, behind },+ counts: AheadBehind {+ ahead: counts.0,+ behind: counts.1,+ },is_orphan: false,})}@@ -195,20 +247,23 @@ impl Task for CommittedTreesMatchTask {});};let repo = &ctx.repo;- // Prefer the branch name when present: during a rebase-in-progress, the- // worktree's HEAD is at a transient replayed commit, so using commit_sha- // would compare the wrong tree. For branch-only items the two are- // equivalent; for detached HEAD, commit_sha is the only option.- let ref_to_check = ctx- .branch_ref- .full_ref()- .unwrap_or(&ctx.branch_ref.commit_sha);+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let branch_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let primary_sha = ctx+ .resolve_sha(&targets.primary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let mut committed_trees_match = repo- .trees_match(ref_to_check, &targets.primary)+ .trees_match_by_sha(&branch_sha, &primary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;if !committed_trees_match && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx+ .resolve_sha(secondary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;committed_trees_match = repo- .trees_match(ref_to_check, secondary)+ .trees_match_by_sha(&branch_sha, &secondary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;}Ok(TaskResult::CommittedTreesMatch {@@ -236,12 +291,12 @@ impl Task for HasFileChangesTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {// No branch name (detached HEAD) - return conservative default (assume has changes)- let Some(branch) = ctx.branch_ref.full_ref() else {+ if ctx.branch_ref.full_ref().is_none() {return Ok(TaskResult::HasFileChanges {item_idx: ctx.item_idx,has_file_changes: true,});- };+ }// When integration_targets is None, return true (conservative: assume has changes)let Some(targets) = ctx.integration_targets() else {return Ok(TaskResult::HasFileChanges {@@ -250,15 +305,25 @@ impl Task for HasFileChangesTask {});};let repo = &ctx.repo;- // The branch is integrated (no added changes) if it has none against- // EITHER target. AND the per-target booleans so the combined value is- // false (== integrated) as soon as a single side has nothing to add.+ // Resolve via snapshot. The branch is integrated (no added changes)+ // if it has none against EITHER target — AND the per-target+ // booleans so the combined value is false as soon as one side has+ // nothing to add.+ let branch_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let primary_sha = ctx+ .resolve_sha(&targets.primary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let mut has_file_changes = repo- .has_added_changes(branch, &targets.primary)+ .has_added_changes_by_sha(&branch_sha, &primary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;if has_file_changes && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx+ .resolve_sha(secondary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;has_file_changes = repo- .has_added_changes(branch, secondary)+ .has_added_changes_by_sha(&branch_sha, &secondary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;}@@ -291,13 +356,13 @@ impl Task for WouldMergeAddTask {fn compute(ctx: TaskContext) -> Result<TaskResult, TaskError> {// No branch name (detached HEAD) - return conservative default (assume would add)- let Some(branch) = ctx.branch_ref.full_ref() else {+ if ctx.branch_ref.full_ref().is_none() {return Ok(TaskResult::WouldMergeAdd {item_idx: ctx.item_idx,would_merge_add: true,is_patch_id_match: false,});- };+ }// When integration_targets is None, return true (conservative: assume would add)let Some(targets) = ctx.integration_targets() else {return Ok(TaskResult::WouldMergeAdd {@@ -311,18 +376,27 @@ impl Task for WouldMergeAddTask {// merging would add nothing OR a patch-id matches against EITHER// side. So `would_merge_add` ANDs (false on either ⇒ integrated)// and `is_patch_id_match` ORs.+ let branch_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let primary_sha = ctx+ .resolve_sha(&targets.primary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let probe = ctx.repo- .merge_integration_probe(branch, &targets.primary)+ .merge_integration_probe_by_sha(&branch_sha, &primary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;let mut would_merge_add = probe.would_merge_add;let mut is_patch_id_match = probe.is_patch_id_match;if let Some(secondary) = targets.secondary.as_deref()&& (would_merge_add && !is_patch_id_match){+ let secondary_sha = ctx+ .resolve_sha(secondary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let alt = ctx.repo- .merge_integration_probe(branch, secondary)+ .merge_integration_probe_by_sha(&branch_sha, &secondary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;would_merge_add = would_merge_add && alt.would_merge_add;is_patch_id_match = is_patch_id_match || alt.is_patch_id_match;@@ -357,18 +431,23 @@ impl Task for IsAncestorTask {});};let repo = &ctx.repo;- // Prefer the branch name when present — see `CommittedTreesMatchTask`- // for rationale (rebase-in-progress transient HEAD).- let ref_to_check = ctx- .branch_ref- .full_ref()- .unwrap_or(&ctx.branch_ref.commit_sha);+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let branch_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let primary_sha = ctx+ .resolve_sha(&targets.primary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let mut is_ancestor = repo- .is_ancestor(ref_to_check, &targets.primary)+ .is_ancestor_by_sha(&branch_sha, &primary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;if !is_ancestor && let Some(secondary) = targets.secondary.as_deref() {+ let secondary_sha = ctx+ .resolve_sha(secondary)+ .map_err(|e| ctx.error(Self::KIND, &e))?;is_ancestor = repo- .is_ancestor(ref_to_check, secondary)+ .is_ancestor_by_sha(&branch_sha, &secondary_sha).map_err(|e| ctx.error(Self::KIND, &e))?;}@@ -394,14 +473,16 @@ impl Task for BranchDiffTask {});};let repo = &ctx.repo;- // Prefer the branch name when present — see `CommittedTreesMatchTask`- // for rationale (rebase-in-progress transient HEAD).- let ref_to_check = ctx- .branch_ref- .full_ref()- .unwrap_or(&ctx.branch_ref.commit_sha);+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let base_sha = ctx+ .resolve_sha(&base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let head_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;let diff = repo- .branch_diff_stats(&base, ref_to_check)+ .branch_diff_stats_by_sha(&base_sha, &head_sha).map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::BranchDiff {@@ -470,14 +551,16 @@ impl Task for MergeTreeConflictsTask {});};let repo = &ctx.repo;- // Prefer the branch name when present — see `CommittedTreesMatchTask`- // for rationale (rebase-in-progress transient HEAD).- let ref_to_check = ctx- .branch_ref- .full_ref()- .unwrap_or(&ctx.branch_ref.commit_sha);+ // Resolve via snapshot — see `branch_check_sha` for the+ // rebase-in-progress rationale.+ let base_sha = ctx+ .resolve_sha(&base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;+ let head_sha = ctx+ .branch_check_sha()+ .map_err(|e| ctx.error(Self::KIND, &e))?;let has_merge_tree_conflicts = repo- .has_merge_conflicts(&base, ref_to_check)+ .has_merge_conflicts_by_sha(&base_sha, &head_sha).map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::MergeTreeConflicts {item_idx: ctx.item_idx,@@ -559,9 +642,16 @@ impl Task for WorkingTreeConflictsTask {.map_err(|e| ctx.error(Self::KIND, &e))?};+ let base_sha = ctx+ .resolve_sha(&base)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let has_conflicts = ctx.repo- .has_merge_conflicts_by_tree(&base, &ctx.branch_ref.commit_sha, &tree_sha)+ .has_merge_conflicts_by_tree_with_base_sha(+ &base_sha,+ &ctx.branch_ref.commit_sha,+ &tree_sha,+ ).map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::WorkingTreeConflicts {@@ -683,8 +773,16 @@ impl Task for UpstreamTask {};let remote = upstream_branch.split_once('/').map(|(r, _)| r.to_string());+ // Resolve upstream ref to a SHA via the snapshot, then compute+ // ahead/behind by SHA. Branch SHA is taken from `branch_ref.commit_sha`+ // — for the upstream comparison we want the branch's actual tip,+ // which `branch_ref.commit_sha` carries (snapshot tracks the same+ // value for branch items via the for-each-ref scan).+ let upstream_sha = ctx+ .resolve_sha(&upstream_branch)+ .map_err(|e| ctx.error(Self::KIND, &e))?;let (ahead, behind) = repo- .ahead_behind(&upstream_branch, &ctx.branch_ref.commit_sha)+ .ahead_behind_by_sha(&upstream_sha, &ctx.branch_ref.commit_sha).map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::Upstream {diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 10a012aca..1b219da28 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -207,8 +207,10 @@ impl PickerCollector {None, // no display path in TUI context)?;+ let snapshot = repo.capture_refs()?;let output = remove_worktree_with_cleanup(&repo,+ &snapshot,worktree_path,RemoveOptions {branch: branch_name.clone(),@@ -248,8 +250,15 @@ impl PickerCollector {if !deletion_mode.should_keep() {let default_branch = repo.default_branch();let target = default_branch.as_deref().unwrap_or("HEAD");- let _ =- delete_branch_if_safe(repo, branch_name, target, deletion_mode.is_force());+ if let Ok(snapshot) = repo.capture_refs() {+ let _ = delete_branch_if_safe(+ repo,+ &snapshot,+ branch_name,+ target,+ deletion_mode.is_force(),+ );+ }}}}diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 0fba0dcee..ebe0d76b3 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -97,6 +97,10 @@ impl RepositoryCliExt for Repository {// worktree, then repo base for bare repos with no worktrees.let primary_path = self.home_path()?;+ // Capture ref state once for this preparation pass — both+ // `compute_integration_reason` calls below resolve through it.+ let snapshot = self.capture_refs()?;+// Phase 1: Resolve target to branch name and worktree disposition.// BranchOnly variants don't early-return — they go through shared validation below.enum Resolved {@@ -224,8 +228,13 @@ impl RepositoryCliExt for Repository {Resolved::BranchOnly { branch, pruned } => {let default_branch = self.default_branch();let target = default_branch.as_deref().or(Some("HEAD"));- let (integration_reason, target_branch) =- compute_integration_reason(self, Some(&branch), target, deletion_mode);+ let (integration_reason, target_branch) = compute_integration_reason(+ self,+ &snapshot,+ Some(&branch),+ target,+ deletion_mode,+ );return Ok(RemoveResult::BranchOnly {branch_name: branch,deletion_mode,@@ -273,6 +282,7 @@ impl RepositoryCliExt for Repository {// display (e.g., origin/main when upstream is ahead).let (integration_reason, effective_target) = compute_integration_reason(self,+ &snapshot,branch_name.as_deref(),target_branch.as_deref(),deletion_mode,@@ -445,6 +455,7 @@ pub(crate) fn is_primary_worktree(repo: &Repository) -> anyhow::Result<bool> {/// if the flag had an effect (branch was integrated) or not (branch was unmerged).pub(crate) fn compute_integration_reason(repo: &Repository,+ snapshot: &worktrunk::git::RefSnapshot,branch_name: Option<&str>,target_branch: Option<&str>,deletion_mode: BranchDeletionMode,@@ -459,7 +470,7 @@ pub(crate) fn compute_integration_reason(None => return (None, None),};// On error, return None (informational only)- match repo.integration_reason(branch, target) {+ match repo.integration_reason(snapshot, branch, target) {Ok((effective_target, reason)) => (reason, Some(effective_target)),Err(_) => (None, None),}diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 877a6072b..3a03c2e55 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1289,6 +1289,10 @@ pub fn step_prune(let repo = Repository::current()?;let config = UserConfig::load()?;+ // Capture once at command entry. Reused for every per-branch+ // `integration_reason` probe later in this function.+ let snapshot = repo.capture_refs()?;+// Pass the local default branch (e.g. "main") directly — `integration_reason`// ORs over local + upstream internally, so a branch merged into either side// counts as integrated.@@ -1546,12 +1550,13 @@ pub fn step_prune(// integration_refs produces an empty par_iter that completes immediately.let repo_clone = repo.clone();let target = integration_target.clone();+ let snapshot_arc = std::sync::Arc::new(snapshot);std::thread::spawn(move || {integration_refs.into_par_iter().enumerate().for_each(|(idx, ref_name)| {- let result = repo_clone.integration_reason(&ref_name, &target);+ let result = repo_clone.integration_reason(&snapshot_arc, &ref_name, &target);let _ = tx.send((idx, result));});});diff --git a/src/commands/worktree/finish.rs b/src/commands/worktree/finish.rsindex 31d2f13fb..616e07cfa 100644--- a/src/commands/worktree/finish.rs+++ b/src/commands/worktree/finish.rs@@ -120,8 +120,16 @@ pub fn finish_after_merge(current_wt.ensure_clean("remove worktree after merge", Some(current_branch), false)?;let worktree_root = current_wt.root()?;+ // Capture a fresh snapshot AFTER the merge has updated the local+ // target ref (`update-ref` ran inside `handle_no_ff_merge` /+ // `handle_push`). Without this, `integration_reason` would observe+ // pre-merge state and misclassify the just-merged branch as+ // unmerged — the bug class PR #2507 worked around with+ // `ref_is_ancestor`.+ let snapshot = repo.capture_refs()?;let (integration_reason, _) = compute_integration_reason(repo,+ &snapshot,Some(current_branch),Some(target_branch),BranchDeletionMode::SafeDelete,diff --git a/src/git/mod.rs b/src/git/mod.rsindex 9efc53516..b6792e6af 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -63,7 +63,8 @@ pub use remove::{};pub use repository::sha_cache;pub use repository::{- Branch, IntegrationTargets, Repository, ResolvedWorktree, WorkingTree, set_base_path,+ Branch, IntegrationTargets, RefSnapshot, Repository, ResolvedWorktree, WorkingTree,+ set_base_path,};pub use url::GitRemoteUrl;pub use url::parse_owner_repo;@@ -227,40 +228,51 @@ pub fn check_integration(signals: &IntegrationSignals) -> Option<IntegrationReas////// Used by `wt remove` and `wt merge` for single-branch checks./// For batch operations, use parallel tasks to build [`IntegrationSignals`] directly.+///+/// Resolves both `branch` and `target` to commit SHAs via `snapshot` so the+/// integration probes are immune to ambient ref→SHA cache staleness — this+/// is the safety contract that lets `wt merge`'s post-update-ref check+/// observe the new local target SHA instead of the pre-merge value.+/// Refs not in the snapshot (typically transient HEAD commits during a+/// rebase, or raw SHAs) fall back to uncached `git rev-parse`.#[allow(clippy::field_reassign_with_default)] // Intentional: short-circuit populates fields incrementallypub fn compute_integration_lazy(repo: &Repository,+ snapshot: &RefSnapshot,branch: &str,target: &str,) -> anyhow::Result<IntegrationSignals> {let mut signals = IntegrationSignals::default();+ let branch_sha = resolve_via_snapshot(repo, snapshot, branch)?;+ let target_sha = resolve_via_snapshot(repo, snapshot, target)?;+// Priority 1: Same commit- signals.is_same_commit = Some(repo.same_commit(branch, target)?);+ signals.is_same_commit = Some(branch_sha == target_sha);if signals.is_same_commit == Some(true) {return Ok(signals);}// Priority 2: Ancestor- signals.is_ancestor = Some(repo.is_ancestor(branch, target)?);+ signals.is_ancestor = Some(repo.is_ancestor_by_sha(&branch_sha, &target_sha)?);if signals.is_ancestor == Some(true) {return Ok(signals);}// Priority 3: No added changes- signals.has_added_changes = Some(repo.has_added_changes(branch, target)?);+ signals.has_added_changes = Some(repo.has_added_changes_by_sha(&branch_sha, &target_sha)?);if signals.has_added_changes == Some(false) {return Ok(signals);}// Priority 4: Trees match- signals.trees_match = Some(repo.trees_match(branch, target)?);+ signals.trees_match = Some(repo.trees_match_by_sha(&branch_sha, &target_sha)?);if signals.trees_match == Some(true) {return Ok(signals);}// Priority 5+6: Merge-tree simulation + patch-id fallback- let probe = repo.merge_integration_probe(branch, target)?;+ let probe = repo.merge_integration_probe_by_sha(&branch_sha, &target_sha)?;signals.would_merge_add = Some(probe.would_merge_add);if !probe.would_merge_add {return Ok(signals);@@ -270,6 +282,21 @@ pub fn compute_integration_lazy(Ok(signals)}+/// Resolve a ref name through the snapshot, falling back to an uncached+/// `git rev-parse` for refs the snapshot doesn't carry (HEAD, raw SHAs,+/// tags, transient rebase commits). Used by [`compute_integration_lazy`]+/// at the boundary into SHA-keyed integration probes.+fn resolve_via_snapshot(+ repo: &Repository,+ snapshot: &RefSnapshot,+ name: &str,+) -> anyhow::Result<String> {+ if let Some(sha) = snapshot.resolve(name) {+ return Ok(sha.to_string());+ }+ Ok(repo.run_command(&["rev-parse", name])?.trim().to_string())+}+/// Category of branch for completion display#[derive(Debug, Clone, PartialEq)]pub enum BranchCategory {diff --git a/src/git/remove.rs b/src/git/remove.rsindex bfffa2a03..17ad4f225 100644--- a/src/git/remove.rs+++ b/src/git/remove.rs@@ -37,8 +37,10 @@//! };//!//! let repo = Repository::current()?;+//! let snapshot = repo.capture_refs()?;//! let output = remove_worktree_with_cleanup(//! &repo,+//! &snapshot,//! Path::new("/repos/myproject.feature"),//! RemoveOptions {//! branch: Some("feature".into()),@@ -198,6 +200,7 @@ pub struct RemovalOutput {/// handle a residual branch-deletion failure.pub fn remove_worktree_with_cleanup(repo: &Repository,+ snapshot: &crate::git::RefSnapshot,worktree_path: &Path,options: RemoveOptions,) -> anyhow::Result<RemovalOutput> {@@ -222,6 +225,7 @@ pub fn remove_worktree_with_cleanup(let target = options.target_branch.as_deref().unwrap_or("HEAD");Some(delete_branch_if_safe(repo,+ snapshot,branch,target,options.deletion_mode.is_force(),@@ -272,6 +276,7 @@ pub fn stage_worktree_removal(repo: &Repository, worktree_path: &Path) -> Option/// to surface it. Only `git branch -D` failures propagate as `Err`.pub fn delete_branch_if_safe(repo: &Repository,+ snapshot: &crate::git::RefSnapshot,branch_name: &str,target: &str,force_delete: bool,@@ -286,7 +291,7 @@ pub fn delete_branch_if_safe(});}- let (effective_target, reason) = repo.integration_reason(branch_name, target)?;+ let (effective_target, reason) = repo.integration_reason(snapshot, branch_name, target)?;let outcome = match reason {Some(r) => {diff --git a/src/git/repository/branches.rs b/src/git/repository/branches.rsindex 3e9951b6e..4137845d5 100644--- a/src/git/repository/branches.rs+++ b/src/git/repository/branches.rs@@ -68,20 +68,20 @@ impl LocalBranchInventory {/// in the Rust string: Rust's `Command::arg` rejects arguments containing/// interior NUL bytes (they can't survive the `CString` conversion to/// `execve`), so passing `\0` through `args()` would error before git runs.-const FIELD_SEP: char = '\0';+pub(super) const FIELD_SEP: char = '\0';/// Format string for the local-branch scan.////// Fields, in order: short name, object SHA, committer Unix timestamp,/// upstream short name (empty if none), upstream track (`[gone]` if the/// configured upstream no longer exists on the remote).-const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)";+pub(super) const LOCAL_BRANCH_FORMAT: &str = "--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)%00%(upstream:short)%00%(upstream:track)";/// Format string for the remote-branch scan.////// Fields, in order: remote-qualified short name (e.g. `origin/feature`),/// object SHA, committer Unix timestamp.-const REMOTE_BRANCH_FORMAT: &str =+pub(super) const REMOTE_BRANCH_FORMAT: &str ="--format=%(refname:lstrip=2)%00%(objectname)%00%(committerdate:unix)";impl Repository {@@ -107,10 +107,11 @@ impl Repository {/// timestamp, most recent first. Result is cached for the lifetime of/// this `Repository` instance (shared across clones via `Arc`).///- /// The initial scan also primes `resolved_refs` (`name` →- /// `refs/heads/name`) and `commit_shas` (both keys → commit SHA) so- /// later `resolve_preferring_branch()` and `rev_parse_commit()` calls- /// hit memory instead of spawning per-branch `git rev-parse`.+ /// `commit_sha` on each entry is a snapshot at scan time. Code that+ /// needs a current SHA for a ref must resolve through a `RefSnapshot`+ /// captured at the moment of read, not through this inventory. The+ /// inventory itself is used for branch listing and upstream-tracking+ /// metadata, both of which are stable for the duration of a command.pub fn local_branches(&self) -> anyhow::Result<&[LocalBranch]> {Ok(self.local_branch_inventory()?.entries())}@@ -144,27 +145,18 @@ impl Repository {.map(Vec::as_slice)}- /// Run the local-branch scan and prime SHA/ref caches.+ /// Run the local-branch scan.+ ///+ /// The inventory's `commit_sha` fields are a snapshot at scan time —+ /// callers that need a current SHA must resolve through a+ /// [`crate::git::RefSnapshot`] captured at the moment of the read,+ /// not through this inventory.fn scan_local_branches(&self) -> anyhow::Result<LocalBranchInventory> {let output = self.run_command(&["for-each-ref", LOCAL_BRANCH_FORMAT, "refs/heads/"])?;let mut branches: Vec<LocalBranch> =output.lines().filter_map(parse_local_branch_line).collect();branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));-- for branch in &branches {- let qualified = format!("refs/heads/{}", branch.name);- self.cache- .resolved_refs- .insert(branch.name.clone(), qualified.clone());- self.cache- .commit_shas- .insert(qualified, branch.commit_sha.clone());- self.cache- .commit_shas- .insert(branch.name.clone(), branch.commit_sha.clone());- }-Ok(LocalBranchInventory::new(branches))}@@ -293,7 +285,7 @@ impl Repository {/// Returns `None` for malformed lines — e.g. a future git format change or/// a control character snuck through. Callers skip those entries rather/// than fail the whole scan.-fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {+pub(super) fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {let mut parts = line.split(FIELD_SEP);let name = parts.next()?.to_string();let commit_sha = parts.next()?.to_string();@@ -317,7 +309,7 @@ fn parse_local_branch_line(line: &str) -> Option<LocalBranch> {////// Skips `<remote>/HEAD` symrefs — they duplicate another ref and would/// confuse callers that key by local name.-fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {+pub(super) fn parse_remote_branch_line(line: &str) -> Option<RemoteBranch> {let mut parts = line.split(FIELD_SEP);let short_name = parts.next()?;let commit_sha = parts.next()?.to_string();diff --git a/src/git/repository/diff.rs b/src/git/repository/diff.rsindex 5da2872be..b0209810d 100644--- a/src/git/repository/diff.rs+++ b/src/git/repository/diff.rs@@ -149,28 +149,36 @@ impl Repository {////// Results are cached in the shared repo cache to avoid redundant git commands/// when multiple tasks need the same merge-base (e.g., parallel `wt list` tasks).- /// Inputs are resolved to commit SHAs (via the cached `commit_shas` map) before- /// keying the cache, so equivalent forms (e.g., `"main"` vs the SHA `main` points- /// to) hit the same entry. The key is also order-normalized since merge-base is- /// symmetric: `merge-base(A, B) == merge-base(B, A)`.+ /// Inputs are resolved to commit SHAs (the resolver short-circuits on+ /// hex-shaped inputs and otherwise spawns `git rev-parse`) before keying+ /// the cache, so equivalent forms (e.g., `"main"` vs the SHA `main` points+ /// to) hit the same entry. The key is also order-normalized since+ /// merge-base is symmetric: `merge-base(A, B) == merge-base(B, A)`.pub fn merge_base(&self, commit1: &str, commit2: &str) -> anyhow::Result<Option<String>> {// Resolve to SHAs so different forms of the same commit dedupe in the cache.// `resolve_to_commit_sha` is a no-op for inputs that already look like SHAs.let sha1 = self.resolve_to_commit_sha(commit1)?;let sha2 = self.resolve_to_commit_sha(commit2)?;+ self.merge_base_by_sha(&sha1, &sha2)+ }+ /// SHA-keyed variant of [`Self::merge_base`].+ ///+ /// Inputs are commit SHAs. Skips the ambient ref→SHA conversion+ /// entirely; cache key is `(min(sha1, sha2), max(sha1, sha2))`.+ pub fn merge_base_by_sha(&self, sha1: &str, sha2: &str) -> anyhow::Result<Option<String>> {// Normalize key order since merge-base is symmetric.let key = if sha1 <= sha2 {- (sha1.clone(), sha2.clone())+ (sha1.to_string(), sha2.to_string())} else {- (sha2.clone(), sha1.clone())+ (sha2.to_string(), sha1.to_string())};match self.cache.merge_base.entry(key) {Entry::Occupied(e) => Ok(e.get().clone()),Entry::Vacant(e) => {// Exit codes: 0 = found, 1 = no common ancestor, 128+ = invalid ref- let output = self.run_command_output(&["merge-base", &sha1, &sha2])?;+ let output = self.run_command_output(&["merge-base", sha1, sha2])?;let result = if output.status.success() {Some(String::from_utf8_lossy(&output.stdout).trim().to_owned())@@ -178,10 +186,7 @@ impl Repository {None} else {let stderr = String::from_utf8_lossy(&output.stderr);- bail!(- "git merge-base failed for {commit1} {commit2}: {}",- stderr.trim()- );+ bail!("git merge-base failed for {sha1} {sha2}: {}", stderr.trim());};Ok(e.insert(result).clone())@@ -189,27 +194,20 @@ impl Repository {}}- /// Calculate commits ahead and behind between two refs.- ///- /// Returns (ahead, behind) where ahead is commits in head not in base,- /// and behind is commits in base not in head.- ///- /// For orphan branches with no common ancestor, returns `(0, 0)`.- /// Caller should check for orphan status separately via `merge_base()`.+ /// SHA-keyed ahead/behind counts.///- /// Results are cached in the shared repo cache. `batch_ahead_behind()`- /// primes the cache for all local branches at once via a single- /// `for-each-ref`; subsequent calls here hit the cache. On a miss, falls- /// back to `merge_base()` + `rev-list --count`, also cached on insert.- pub fn ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {- let key = (base.to_string(), head.to_string());- match self.cache.ahead_behind.entry(key) {- Entry::Occupied(e) => Ok(*e.get()),- Entry::Vacant(e) => {- let counts = self.compute_ahead_behind(base, head)?;- Ok(*e.insert(counts))- }- }+ /// Inputs are commit SHAs. Uncached — counts are typically primed in+ /// bulk by [`crate::git::RefSnapshot`]'s ahead/behind batch; this is+ /// the per-pair fallback for snapshot misses or callers that already+ /// hold SHAs. Returns `(ahead, behind)` where ahead is commits in+ /// head not in base; orphan branches (no common ancestor) yield+ /// `(0, 0)` — caller should distinguish via [`Self::merge_base_by_sha`].+ pub fn ahead_behind_by_sha(+ &self,+ base_sha: &str,+ head_sha: &str,+ ) -> anyhow::Result<(usize, usize)> {+ self.compute_ahead_behind(base_sha, head_sha)}fn compute_ahead_behind(&self, base: &str, head: &str) -> anyhow::Result<(usize, usize)> {@@ -247,51 +245,6 @@ impl Repository {Ok((ahead, behind))}- /// Prime `cache.ahead_behind` for all local branches vs a base ref.- ///- /// Uses `git for-each-ref --format='%(ahead-behind:BASE)'` (git 2.36+) to- /// compute all counts in a single command, so subsequent `ahead_behind()`- /// calls hit the cache.- ///- /// On git < 2.36 or if the command fails, this is a no-op and- /// `ahead_behind()` falls back to per-branch computation.- pub fn batch_ahead_behind(&self, base: &str) {- // Uses `%(refname)` (full ref) rather than `%(refname:lstrip=2)` so the- // cache key matches what `AheadBehindTask` queries — that task passes- // `BranchRef::full_ref()` (e.g., `refs/heads/feature`). Keying by short- // names would force every row to miss the batch cache and fall back to- // per-branch `rev-list --count`.- let format = format!("%(refname) %(ahead-behind:{})", base);- let output = match self.run_command(&[- "for-each-ref",- &format!("--format={}", format),- "refs/heads/",- ]) {- Ok(output) => output,- Err(e) => {- // Fails on git < 2.36 (no %(ahead-behind:) support), invalid base ref, etc.- log::debug!("batch_ahead_behind({base}): git for-each-ref failed: {e}");- return;- }- };-- output- .lines()- .filter_map(|line| {- // Format: "refs/heads/branch-name ahead behind"- let mut parts = line.rsplitn(3, ' ');- let behind: usize = parts.next()?.parse().ok()?;- let ahead: usize = parts.next()?.parse().ok()?;- let full_ref = parts.next()?;- Some((full_ref, ahead, behind))- })- .for_each(|(full_ref, ahead, behind)| {- self.cache- .ahead_behind- .insert((base.to_string(), full_ref.to_string()), (ahead, behind));- });- }-/// Get line diff statistics between two refs.////// Uses merge-base (cached) to find common ancestor, then two-dot diff@@ -300,10 +253,20 @@ impl Repository {////// For orphan branches with no common ancestor, returns zeros.pub fn branch_diff_stats(&self, base: &str, head: &str) -> anyhow::Result<LineDiff> {- use dashmap::mapref::entry::Entry;-let base_sha = self.rev_parse_commit(base)?;let head_sha = self.rev_parse_commit(head)?;+ self.branch_diff_stats_by_sha(&base_sha, &head_sha)+ }++ /// SHA-keyed variant of [`Self::branch_diff_stats`].+ ///+ /// Inputs are commit SHAs. Bypasses the ambient ref→SHA cache.+ pub fn branch_diff_stats_by_sha(+ &self,+ base_sha: &str,+ head_sha: &str,+ ) -> anyhow::Result<LineDiff> {+ use dashmap::mapref::entry::Entry;// Sparse checkout filters the diff by path, making the result// environment-dependent rather than purely SHA-determined. Skip@@ -317,18 +280,18 @@ impl Repository {match self.cache.diff_stats- .entry((base_sha.clone(), head_sha.clone()))+ .entry((base_sha.to_string(), head_sha.to_string())){Entry::Occupied(e) => return Ok(*e.get()),Entry::Vacant(e) => {let result =- self.compute_branch_diff_stats(&base_sha, &head_sha, sparse_paths)?;+ self.compute_branch_diff_stats(base_sha, head_sha, sparse_paths)?;return Ok(*e.insert(result));}}}- self.compute_branch_diff_stats(&base_sha, &head_sha, sparse_paths)+ self.compute_branch_diff_stats(base_sha, head_sha, sparse_paths)}fn compute_branch_diff_stats(@@ -384,44 +347,3 @@ impl Repository {.unwrap_or_default()}}--#[cfg(test)]-mod tests {- use crate::git::Repository;- use crate::testing::TestRepo;-- #[test]- fn batch_ahead_behind_keys_cache_by_full_ref() {- // Callers in `wt list` pass `BranchRef::full_ref()` (`refs/heads/<name>`)- // into `ahead_behind`. This test pins the batch cache to the same key- // shape — short-name keys would force every row to miss the batch and- // fall back to per-branch `rev-list --count`.- let test = TestRepo::with_initial_commit();- let repo = Repository::at(test.path()).unwrap();-- test.create_branch("feature");- test.run_git(&["checkout", "feature"]);- std::fs::write(test.path().join("f.txt"), "x").unwrap();- test.run_git(&["add", "."]);- test.run_git(&["commit", "-m", "feature"]);- test.run_git(&["checkout", "main"]);-- repo.batch_ahead_behind("main");-- assert_eq!(- repo.cache- .ahead_behind- .get(&("main".to_string(), "refs/heads/feature".to_string()))- .map(|v| *v),- Some((1, 0)),- "batch must prime cache under the full ref key"- );- assert!(- repo.cache- .ahead_behind- .get(&("main".to_string(), "feature".to_string()))- .is_none(),- "short-name key must not be used",- );- }-}diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex d9feb8ec3..6b09c8aa7 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -4,10 +4,9 @@//! (same commit, ancestor, trees match, etc.).use anyhow::{Context, bail};-use dashmap::mapref::entry::Entry;use serde::{Deserialize, Serialize};-use super::Repository;+use super::{RefSnapshot, Repository};use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};use crate::shell_exec::Cmd;@@ -46,22 +45,18 @@ impl Repository {/// 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 {- self.cache- .resolved_refs- .entry(r.to_string())- .or_insert_with(|| {- let qualified = format!("refs/heads/{r}");- if self- .run_command(&["rev-parse", "--verify", "-q", &qualified])- .is_ok()- {- qualified- } else {- r.to_string()- }- })- .clone()+ 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@@ -96,13 +91,23 @@ impl Repository {let base_sha = self.rev_parse_commit(&base)?;let head_sha = self.rev_parse_commit(&head)?;- if let Some(cached) = super::sha_cache::is_ancestor(self, &base_sha, &head_sha) {+ 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.+ ///+ /// Callers that hold SHAs (e.g., from a `RefSnapshot` or a+ /// `BranchRef.commit_sha`) should prefer this form.+ pub fn is_ancestor_by_sha(&self, base_sha: &str, head_sha: &str) -> anyhow::Result<bool> {+ if let Some(cached) = super::sha_cache::is_ancestor(self, base_sha, head_sha) {return Ok(cached);}let result =- self.run_command_check(&["merge-base", "--is-ancestor", &base_sha, &head_sha])?;- super::sha_cache::put_is_ancestor(self, &base_sha, &head_sha, result);+ self.run_command_check(&["merge-base", "--is-ancestor", base_sha, head_sha])?;+ super::sha_cache::put_is_ancestor(self, base_sha, head_sha, result);Ok(result)}@@ -135,20 +140,33 @@ impl Repository {let branch_sha = self.rev_parse_commit(&branch)?;let target_sha = self.rev_parse_commit(&target)?;- if let Some(cached) = super::sha_cache::has_added_changes(self, &branch_sha, &target_sha) {+ 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+ /// persistent SHA-keyed cache directly.+ pub fn has_added_changes_by_sha(+ &self,+ branch_sha: &str,+ target_sha: &str,+ ) -> anyhow::Result<bool> {+ if let Some(cached) = super::sha_cache::has_added_changes(self, branch_sha, target_sha) {return Ok(cached);}// Orphan branches have no common ancestor, so all their changes are unique- let Some(merge_base) = self.merge_base(&target_sha, &branch_sha)? else {- super::sha_cache::put_has_added_changes(self, &branch_sha, &target_sha, true);+ let Some(merge_base) = self.merge_base(target_sha, branch_sha)? else {+ super::sha_cache::put_has_added_changes(self, branch_sha, target_sha, true);return Ok(true);};let range = format!("{merge_base}..{branch_sha}");let output = self.run_command(&["diff", "--name-only", &range])?;let result = !output.trim().is_empty();- super::sha_cache::put_has_added_changes(self, &branch_sha, &target_sha, result);+ super::sha_cache::put_has_added_changes(self, branch_sha, target_sha, result);Ok(result)}@@ -175,6 +193,27 @@ impl Repository {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+ /// (trees are cheap and not stale-prone), but the inputs are SHAs so+ /// the call is immune to ref-name staleness.+ pub fn trees_match_by_sha(&self, commit_sha1: &str, commit_sha2: &str) -> anyhow::Result<bool> {+ let output = self.run_command(&[+ "rev-parse",+ &format!("{commit_sha1}^{{tree}}"),+ &format!("{commit_sha2}^{{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)+ }+/// 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> {@@ -201,11 +240,20 @@ impl Repository {let base_sha = self.rev_parse_commit(&base)?;let head_sha = self.rev_parse_commit(&head)?;- if let Some(cached) = super::sha_cache::merge_conflicts(self, &base_sha, &head_sha) {+ 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,+ head_sha: &str,+ ) -> anyhow::Result<bool> {+ if let Some(cached) = super::sha_cache::merge_conflicts(self, base_sha, head_sha) {return Ok(cached);}- self.run_merge_tree(&base_sha, &head_sha, &base_sha, &head_sha)+ self.run_merge_tree(base_sha, head_sha, base_sha, head_sha)}/// Check merge conflicts for a working tree represented by a tree SHA.@@ -229,8 +277,20 @@ impl Repository {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,+ branch_head_sha: &str,+ tree_sha: &str,+ ) -> anyhow::Result<bool> {let cache_head = format!("{branch_head_sha}+{tree_sha}");- if let Some(cached) = super::sha_cache::merge_conflicts(self, &base_sha, &cache_head) {+ if let Some(cached) = super::sha_cache::merge_conflicts(self, base_sha, &cache_head) {return Ok(cached);}@@ -240,7 +300,7 @@ impl Repository {self.run_command(&["commit-tree", tree_sha, "-p", branch_head_sha, "-m", ""])?;let head_commit = head_commit.trim();- self.run_merge_tree(&base_sha, head_commit, &base_sha, &cache_head)+ self.run_merge_tree(base_sha, head_commit, base_sha, &cache_head)}/// Run merge-tree and cache the result.@@ -410,23 +470,35 @@ impl Repository {let branch_sha = self.rev_parse_commit(&branch)?;let target_sha = self.rev_parse_commit(&target)?;- if let Some(cached) = super::sha_cache::merge_add_probe(self, &branch_sha, &target_sha) {+ 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.+ pub fn merge_integration_probe_by_sha(+ &self,+ branch_sha: &str,+ target_sha: &str,+ ) -> anyhow::Result<MergeProbeResult> {+ if let Some(cached) = super::sha_cache::merge_add_probe(self, branch_sha, target_sha) {return Ok(cached);}// Orphan branches (no common ancestor) can't be merge-tree simulated// (git exits 128 with "refusing to merge unrelated histories") and have// no merge-base for patch-id either. Short-circuit: they always have changes.- if self.merge_base(&target_sha, &branch_sha)?.is_none() {+ if self.merge_base(target_sha, branch_sha)?.is_none() {let result = MergeProbeResult {would_merge_add: true,is_patch_id_match: false,};- super::sha_cache::put_merge_add_probe(self, &branch_sha, &target_sha, result);+ super::sha_cache::put_merge_add_probe(self, branch_sha, target_sha, result);return Ok(result);}- let merge_result = self.would_merge_add_to_target(&branch_sha, &target_sha)?;+ let merge_result = self.would_merge_add_to_target(branch_sha, target_sha)?;let result = match merge_result {Some(would_add) => MergeProbeResult {would_merge_add: would_add,@@ -437,7 +509,7 @@ impl Repository {// Patch-id errors are non-fatal: if we can't compute patch-ids,// conservatively report no match (branch appears not integrated).let matched = self- .is_squash_merged_via_patch_id(&branch_sha, &target_sha)+ .is_squash_merged_via_patch_id(branch_sha, target_sha).unwrap_or(false);MergeProbeResult {would_merge_add: true,@@ -445,7 +517,7 @@ impl Repository {}}};- super::sha_cache::put_merge_add_probe(self, &branch_sha, &target_sha, result);+ super::sha_cache::put_merge_add_probe(self, branch_sha, target_sha, result);Ok(result)}@@ -463,61 +535,58 @@ impl Repository {/// - Diverged: primary = local, secondary = upstream — both are checked/// so a branch merged into either side counts as integrated.///- /// Ancestry probes use `ref_is_ancestor` (raw git, no SHA caching) so- /// a just-updated local target's relationship is observed correctly,- /// matching [`Self::integration_reason`].+ /// Ancestry probes resolve through the snapshot so a just-updated+ /// local target's relationship is observed correctly, matching+ /// [`Self::integration_reason`].////// Returns `None` when the default branch cannot be determined.- pub fn integration_targets(&self) -> Option<IntegrationTargets> {+ pub fn integration_targets(&self, snapshot: &RefSnapshot) -> Option<IntegrationTargets> {let target = self.default_branch()?;- let upstream = self.branch(&target).upstream().ok().flatten();+ let upstream = snapshot.upstream_of(&target).map(str::to_string);++ let target_sha = snapshot_resolve(self, snapshot, &target).ok()?;let (primary, secondary) = match upstream {None => (target, None),- Some(u) if self.same_commit(&target, &u).unwrap_or(false) => (target, None),- Some(u) if ref_is_ancestor(self, &target, &u) => (u, None),- Some(u) if ref_is_ancestor(self, &u, &target) => (target, None),- Some(u) => (target, Some(u)),+ Some(u) => {+ let upstream_sha = snapshot_resolve(self, snapshot, &u).ok()?;+ if target_sha == upstream_sha {+ (target, None)+ } else if self+ .is_ancestor_by_sha(&target_sha, &upstream_sha)+ .unwrap_or(false)+ {+ (u, None)+ } else if self+ .is_ancestor_by_sha(&upstream_sha, &target_sha)+ .unwrap_or(false)+ {+ (target, None)+ } else {+ (target, Some(u))+ }+ }};Some(IntegrationTargets { primary, secondary })}- /// Parse a tree ref to get its SHA (cached).+ /// Resolve a tree spec (e.g. `"refs/heads/main^{tree}"`) to its tree SHA.+ /// Uncached — tree resolution is cheap (~1 ms) and stale-prone if memoized+ /// against a moving ref name.pub(super) fn rev_parse_tree(&self, spec: &str) -> anyhow::Result<String> {- match self.cache.tree_shas.entry(spec.to_string()) {- Entry::Occupied(e) => Ok(e.get().clone()),- Entry::Vacant(e) => {- let sha = self- .run_command(&["rev-parse", spec])- .map(|output| output.trim().to_string())?;- Ok(e.insert(sha).clone())- }- }+ Ok(self.run_command(&["rev-parse", spec])?.trim().to_string())}- /// Resolve a ref to its commit SHA (cached).- ///- /// Unlike [`Self::rev_parse_tree`], this returns the commit SHA rather than the- /// tree SHA. Used by the persistent `sha_cache` to convert ref names into- /// stable SHA-based cache keys before looking up cached merge-tree results.+ /// Resolve a ref to its commit SHA. Uncached — callers that want+ /// SHA-stable lookups for an entire command should capture a+ /// [`RefSnapshot`] up front and resolve through it.pub(super) fn rev_parse_commit(&self, r: &str) -> anyhow::Result<String> {- match self.cache.commit_shas.entry(r.to_string()) {- Entry::Occupied(e) => Ok(e.get().clone()),- Entry::Vacant(e) => {- let sha = self- .run_command(&["rev-parse", r])- .map(|output| output.trim().to_string())?;- Ok(e.insert(sha).clone())- }- }+ Ok(self.run_command(&["rev-parse", r])?.trim().to_string())}/// Resolve a ref to its commit SHA, skipping git when the input already/// looks like a 40-char hex SHA.- ///- /// Used at cache boundaries (e.g. [`Self::merge_base`]) to normalize keys- /// without spawning `git rev-parse` for inputs that are already SHAs.pub(super) fn resolve_to_commit_sha(&self, r: &str) -> anyhow::Result<String> {if is_hex_commit_sha(r) {return Ok(r.to_string());@@ -563,7 +632,8 @@ impl Repository {/// use worktrunk::git::Repository;////// let repo = Repository::current()?;- /// let (effective_target, reason) = repo.integration_reason("feature", "main")?;+ /// let snapshot = repo.capture_refs()?;+ /// let (effective_target, reason) = repo.integration_reason(&snapshot, "feature", "main")?;/// if let Some(r) = reason {/// println!("Branch integrated into {}: {}", effective_target, r.description());/// }@@ -571,66 +641,64 @@ impl Repository {/// ```pub fn integration_reason(&self,+ snapshot: &RefSnapshot,branch: &str,target: &str,) -> anyhow::Result<(String, Option<IntegrationReason>)> {- use dashmap::mapref::entry::Entry;- match self- .cache- .integration_reasons- .entry((branch.to_string(), target.to_string()))- {- Entry::Occupied(e) => Ok(e.get().clone()),- Entry::Vacant(e) => {- let result = self.compute_integration_reason_uncached(branch, target)?;- Ok(e.insert(result).clone())- }- }+ self.compute_integration_reason_uncached(snapshot, branch, target)}fn compute_integration_reason_uncached(&self,+ snapshot: &RefSnapshot,branch: &str,target: &str,) -> anyhow::Result<(String, Option<IntegrationReason>)> {// Resolve upstream once. Errors and "no upstream" both collapse to None.- let upstream = self.branch(target).upstream().ok().flatten();-- // Decide whether to check local, upstream, or both.- //- // The ancestor checks here run git directly with ref names rather than- // going through cached `is_ancestor`/`rev_parse_commit`, because the- // local target may have just been updated (e.g. by `wt merge`'s ref- // update). Cached SHAs would be stale and could misclassify the- // local/upstream relationship.+ let upstream = snapshot+ .upstream_of(target)+ .map(str::to_string)+ .or_else(|| self.branch(target).upstream().ok().flatten());++ // Decide whether to check local, upstream, or both. All ancestor+ // probes go through SHAs resolved at the snapshot — by construction,+ // the snapshot reflects ref state at capture time, so a freshly+ // captured snapshot post-`update-ref` observes the new local target+ // SHA correctly. (PR #2507's `ref_is_ancestor` workaround dissolves+ // here.)+ let target_sha = snapshot_resolve(self, snapshot, target)?;+let (check_local, fallback_upstream) = match upstream {None => (true, None),- Some(u) if self.same_commit(target, &u).unwrap_or(false) => (true, None),- Some(u) if ref_is_ancestor(self, target, &u) => {- // Local strictly behind upstream — upstream is the superset.- let signals = compute_integration_lazy(self, branch, &u)?;- return Ok((u, check_integration(&signals)));- }- Some(u) if ref_is_ancestor(self, &u, target) => {- // Upstream strictly behind local — local is the superset.- (true, None)- }Some(u) => {- // Diverged — check local first, fall back to upstream.- (true, Some(u))+ let upstream_sha = snapshot_resolve(self, snapshot, &u)?;+ if target_sha == upstream_sha {+ (true, None)+ } else if self.is_ancestor_by_sha(&target_sha, &upstream_sha)? {+ // Local strictly behind upstream — upstream is the superset.+ let signals = compute_integration_lazy(self, snapshot, branch, &u)?;+ return Ok((u, check_integration(&signals)));+ } else if self.is_ancestor_by_sha(&upstream_sha, &target_sha)? {+ // Upstream strictly behind local — local is the superset.+ (true, None)+ } else {+ // Diverged — check local first, fall back to upstream.+ (true, Some(u))+ }}};if check_local&& let Some(reason) =- check_integration(&compute_integration_lazy(self, branch, target)?)+ check_integration(&compute_integration_lazy(self, snapshot, branch, target)?){return Ok((target.to_string(), Some(reason)));}if let Some(upstream) = fallback_upstream- && let Some(reason) =- check_integration(&compute_integration_lazy(self, branch, &upstream)?)+ && let Some(reason) = check_integration(&compute_integration_lazy(+ self, snapshot, branch, &upstream,+ )?){return Ok((upstream, Some(reason)));}@@ -639,17 +707,17 @@ impl Repository {}}-/// Run `git merge-base --is-ancestor` directly with ref names, bypassing-/// `Repository::is_ancestor`'s SHA cache.-///-/// `is_ancestor` resolves both refs through the cached `rev_parse_commit`,-/// so a ref that was updated mid-command (e.g. `wt merge` rewriting local-/// `main`) returns its old SHA. For relationships where freshness matters —-/// in particular comparing a just-updated local target against its upstream —-/// running git directly with ref names dodges that staleness.-fn ref_is_ancestor(repo: &Repository, base: &str, head: &str) -> bool {- repo.run_command_check(&["merge-base", "--is-ancestor", base, head])- .unwrap_or(false)+/// Resolve a ref name through `snapshot`, falling back to an uncached+/// `git rev-parse` for refs the snapshot doesn't carry.+fn snapshot_resolve(+ repo: &Repository,+ snapshot: &RefSnapshot,+ name: &str,+) -> anyhow::Result<String> {+ if let Some(sha) = snapshot.resolve(name) {+ return Ok(sha.to_string());+ }+ Ok(repo.run_command(&["rev-parse", name])?.trim().to_string())}/// Returns true when `s` is a 40-character hex string — the canonical formdiff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 04594b795..4f75bb369 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -89,7 +89,7 @@ use dunce::canonicalize;use crate::config::{LoadError, ProjectConfig, ResolvedConfig, UserConfig};// Import types from parent module-use super::{DefaultBranchName, GitError, IntegrationReason, LineDiff, WorktreeInfo};+use super::{DefaultBranchName, GitError, LineDiff, WorktreeInfo};// Re-export types needed by submodulespub(super) use super::{@@ -102,14 +102,16 @@ mod branches;mod config;mod diff;mod integration;+mod ref_snapshot;mod remotes;pub mod sha_cache;mod working_tree;mod worktrees;-// Re-export WorkingTree and Branch+// Re-export WorkingTree, Branch, IntegrationTargets, and RefSnapshotpub use branch::Branch;pub use integration::IntegrationTargets;+pub use ref_snapshot::RefSnapshot;pub use working_tree::WorkingTree;pub(super) use working_tree::path_to_logging_context;@@ -235,47 +237,33 @@ pub(super) struct RepoCache {pub(super) resolved_config: OnceCell<ResolvedConfig>,/// Sparse checkout paths (empty if not a sparse checkout)pub(super) sparse_checkout_paths: OnceCell<Vec<String>>,- /// Merge-base cache: (commit1, commit2) -> merge_base_sha (None = no common ancestor)+ /// Merge-base cache: (sha1, sha2) -> merge_base_sha (None = no common ancestor).+ /// Keys are commit SHAs by contract — callers must resolve refs through+ /// a [`RefSnapshot`] before consulting. The key order is normalized+ /// (`(min, max)`) since merge-base is symmetric.pub(super) merge_base: DashMap<(String, String), Option<String>>,- /// Ahead/behind cache: (base_ref, head) -> (ahead, behind).- /// Primed in bulk by `batch_ahead_behind()`; populated on demand by- /// `ahead_behind()` for keys the batch didn't cover (e.g., HEAD SHAs- /// during rebase/merge, or git < 2.36 where the batch is a no-op).- pub(super) ahead_behind: DashMap<(String, String), (usize, usize)>,/// Effective remote URLs: remote_name -> effective URL (with `url.insteadOf` applied)./// Separate from `all_config` because `git remote get-url` applies/// `url.insteadOf` rewrites that aren't visible in raw config.pub(super) effective_remote_urls: DashMap<String, Option<String>>,- /// Resolved refs: unresolved ref (e.g., "main") -> resolved form (e.g., "refs/heads/main")- /// or original if not a local branch. Populated by `resolve_preferring_branch()`.- pub(super) resolved_refs: DashMap<String, String>,- /// Integration reason cache: (branch, target) -> (effective_target, reason).- /// Populated by `integration_reason()`, avoids redundant `compute_integration_lazy()`- /// calls when the same branch is checked multiple times (e.g., step_prune Phase 1- /// followed by prepare_worktree_removal).- pub(super) integration_reasons: DashMap<(String, String), (String, Option<IntegrationReason>)>,-- /// Tree SHA cache: tree spec (e.g., "refs/heads/main^{tree}") -> SHA.- /// The tree SHA for a given ref doesn't change during a command.- pub(super) tree_shas: DashMap<String, String>,-- /// Commit SHA cache: ref (e.g., "main", "refs/heads/main") -> commit SHA.- /// The commit SHA for a given ref doesn't change during a command.- /// Used by `rev_parse_commit()` to key the persistent `sha_cache` by SHA.- pub(super) commit_shas: DashMap<String, String>,/// Local branch inventory: one `git for-each-ref refs/heads/` scan, cached/// for the lifetime of the repository. Entries are sorted by most recent/// commit first; the inventory also holds a name → index map for O(1)/// single-branch lookups. Populated lazily via- /// [`Repository::local_branches`] — the first call runs the scan and- /// primes `resolved_refs`/`commit_shas` so subsequent ref resolution and- /// SHA lookups hit memory.+ /// [`Repository::local_branches`].+ ///+ /// **The `commit_sha` field on each entry is a snapshot at scan time.**+ /// Code that needs a current SHA must resolve through a [`RefSnapshot`]+ /// captured at the moment the read happens — not through this inventory.+ /// The inventory is used for branch-name listing and upstream-tracking+ /// metadata, both of which are stable for the duration of a command.pub(super) local_branches: OnceCell<branches::LocalBranchInventory>,/// Remote-tracking branch inventory: one `git for-each-ref refs/remotes/`/// scan, cached for the lifetime of the repository. Sorted by most recent/// commit first. Populated lazily via [`Repository::remote_branches`].- /// Excludes `<remote>/HEAD` symrefs.+ /// Excludes `<remote>/HEAD` symrefs. Same snapshot-at-scan-time contract+ /// as [`Self::local_branches`] applies to `commit_sha`.pub(super) remote_branches: OnceCell<Vec<RemoteBranch>>,/// Worktree inventory: one `git worktree list --porcelain` scan, cached/// for the lifetime of the repository. Populated lazily viadiff --git a/src/git/repository/ref_snapshot.rs b/src/git/repository/ref_snapshot.rsnew file mode 100644index 000000000..946dd5038--- /dev/null+++ b/src/git/repository/ref_snapshot.rs@@ -0,0 +1,330 @@+//! `RefSnapshot` — a captured, immutable view of repository ref state.+//!+//! The snapshot is the structural answer to ref-name cache staleness. Today's+//! `RepoCache` ambient ref-name → SHA fields (`commit_shas`, `tree_shas`,+//! `effective_integration_targets`, `integration_reasons`, `ahead_behind`)+//! become stale the moment wt updates a ref mid-command — `wt merge`'s+//! `git update-ref refs/heads/main` is the canonical example. Any code that+//! reads through those caches afterwards gets pre-write SHAs.+//!+//! A `RefSnapshot` replaces that ambient cache with an explicit, named,+//! point-in-time value. Callers thread it through. After a ref-mutating+//! write, the caller captures a new snapshot and uses it for downstream+//! reads — the old snapshot remains valid as a pre-write view, but cannot+//! masquerade as current state.+//!+//! # Construction+//!+//! [`Repository::capture_refs`] runs one `git for-each-ref refs/heads/`+//! plus one `git for-each-ref refs/remotes/` and parses both into a+//! single `RefSnapshot`. [`Repository::capture_refs_with_ahead_behind`]+//! additionally runs `for-each-ref ... %(ahead-behind:BASE)` (git ≥ 2.36)+//! to populate ahead/behind counts in the same snapshot.+//!+//! # Lifetime+//!+//! The snapshot is a value, not a cache field. There is no `OnceCell`,+//! no `Arc<DashMap>`, no shared mutable state. Two `capture_refs()`+//! calls within one command produce two distinct snapshots; neither+//! invalidates the other. This is intentional — it removes the+//! "invisible refresh" surface that ambient caching introduces.++use std::collections::HashMap;++use anyhow::bail;++use super::branches::{+ LOCAL_BRANCH_FORMAT, REMOTE_BRANCH_FORMAT, parse_local_branch_line, parse_remote_branch_line,+};+use super::{LocalBranch, RemoteBranch, Repository};++/// An immutable snapshot of repository ref state.+///+/// Keys are git ref names (short or qualified). Values are commit SHAs as+/// reported by `git for-each-ref` at capture time. See the module docstring+/// for the freshness contract.+#[derive(Debug, Clone, Default)]+pub struct RefSnapshot {+ /// Ref name → commit SHA. Each local branch is keyed by both its short+ /// name (e.g. `feature`) and qualified form (`refs/heads/feature`).+ /// Each remote-tracking branch is keyed by short name (`origin/feature`)+ /// and qualified form (`refs/remotes/origin/feature`).+ commits: HashMap<String, String>,++ /// Local branch entries, sorted by committer timestamp descending.+ locals: Vec<LocalBranch>,+ locals_by_name: HashMap<String, usize>,++ /// Remote-tracking branch entries, sorted by committer timestamp descending.+ /// `<remote>/HEAD` symrefs are excluded.+ remotes: Vec<RemoteBranch>,++ /// Ahead/behind counts keyed by `(base, head)` ref names.+ /// Populated only when constructed via+ /// [`Repository::capture_refs_with_ahead_behind`]; empty otherwise.+ /// On git < 2.36 the batch fails silently and this stays empty —+ /// callers that need ahead/behind must fall back to a per-pair query.+ ahead_behind: HashMap<(String, String), (usize, usize)>,+}++impl RefSnapshot {+ /// Resolve a ref name to its commit SHA at capture time.+ ///+ /// Returns `None` for refs not in the snapshot — typically `HEAD`,+ /// raw SHAs, tags, or relative refs like `HEAD~2`. Callers that need+ /// to handle those should fall back to `git rev-parse` (uncached).+ pub fn resolve(&self, name: &str) -> Option<&str> {+ self.commits.get(name).map(String::as_str)+ }++ /// Resolve a ref name to its commit SHA, erroring when absent.+ pub fn must_resolve(&self, name: &str) -> anyhow::Result<&str> {+ match self.resolve(name) {+ Some(sha) => Ok(sha),+ None => bail!("ref not present in snapshot: {name}"),+ }+ }++ /// Look up the configured upstream short name for a local branch.+ ///+ /// Returns `None` when no upstream is configured, when the branch is+ /// absent from the snapshot, or when the configured upstream is gone+ /// (git's `[gone]` track state).+ pub fn upstream_of(&self, branch: &str) -> Option<&str> {+ self.local_branch(branch)+ .and_then(|b| b.upstream_short.as_deref())+ }++ /// Look up cached ahead/behind counts.+ ///+ /// Returns `None` when the snapshot was constructed without ahead/behind+ /// (the default `capture_refs`) or when the requested pair is missing+ /// from the batch result.+ pub fn ahead_behind(&self, base: &str, head: &str) -> Option<(usize, usize)> {+ self.ahead_behind+ .get(&(base.to_string(), head.to_string()))+ .copied()+ }++ /// All local branches at capture time, sorted by committer timestamp descending.+ pub fn local_branches(&self) -> &[LocalBranch] {+ &self.locals+ }++ /// O(1) lookup of a local branch by short name.+ pub fn local_branch(&self, name: &str) -> Option<&LocalBranch> {+ self.locals_by_name.get(name).map(|&i| &self.locals[i])+ }++ /// All remote-tracking branches at capture time, sorted by committer+ /// timestamp descending. `<remote>/HEAD` symrefs are excluded.+ pub fn remote_branches(&self) -> &[RemoteBranch] {+ &self.remotes+ }+}++impl Repository {+ /// Capture current ref state into a [`RefSnapshot`].+ ///+ /// Runs `git for-each-ref refs/heads/` and `git for-each-ref+ /// refs/remotes/` (two subprocesses) and assembles the result into an+ /// immutable value. See the module docstring for the freshness+ /// contract.+ pub fn capture_refs(&self) -> anyhow::Result<RefSnapshot> {+ let locals = scan_locals(self)?;+ let remotes = scan_remotes(self)?;+ Ok(build(locals, remotes, HashMap::new()))+ }++ /// Capture current ref state plus ahead/behind counts vs `base`.+ ///+ /// Runs the two ref scans plus one additional `for-each-ref+ /// --format='%(ahead-behind:BASE)'` pass (git ≥ 2.36). On older git+ /// the ahead/behind batch fails silently and the snapshot's+ /// [`RefSnapshot::ahead_behind`] returns `None` for every key —+ /// callers fall back to per-pair queries.+ pub fn capture_refs_with_ahead_behind(&self, base: &str) -> anyhow::Result<RefSnapshot> {+ let locals = scan_locals(self)?;+ let remotes = scan_remotes(self)?;+ let ahead_behind = scan_ahead_behind(self, base);+ Ok(build(locals, remotes, ahead_behind))+ }+}++fn scan_locals(repo: &Repository) -> anyhow::Result<Vec<LocalBranch>> {+ let output = repo.run_command(&["for-each-ref", LOCAL_BRANCH_FORMAT, "refs/heads/"])?;+ let mut branches: Vec<LocalBranch> =+ output.lines().filter_map(parse_local_branch_line).collect();+ branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));+ Ok(branches)+}++fn scan_remotes(repo: &Repository) -> anyhow::Result<Vec<RemoteBranch>> {+ let output = repo.run_command(&["for-each-ref", REMOTE_BRANCH_FORMAT, "refs/remotes/"])?;+ let mut branches: Vec<RemoteBranch> = output+ .lines()+ .filter_map(parse_remote_branch_line)+ .collect();+ branches.sort_by_key(|b| std::cmp::Reverse(b.committer_ts));+ Ok(branches)+}++/// Best-effort ahead/behind batch via `for-each-ref %(ahead-behind:BASE)`.+///+/// Failures (git < 2.36, invalid base) return an empty map — callers must+/// tolerate missing keys.+fn scan_ahead_behind(repo: &Repository, base: &str) -> HashMap<(String, String), (usize, usize)> {+ let format = format!("%(refname) %(ahead-behind:{base})");+ let output =+ match repo.run_command(&["for-each-ref", &format!("--format={format}"), "refs/heads/"]) {+ Ok(out) => out,+ Err(e) => {+ log::debug!("RefSnapshot ahead/behind batch failed for base {base}: {e}");+ return HashMap::new();+ }+ };++ output+ .lines()+ .filter_map(|line| {+ let mut parts = line.rsplitn(3, ' ');+ let behind: usize = parts.next()?.parse().ok()?;+ let ahead: usize = parts.next()?.parse().ok()?;+ let full_ref = parts.next()?.to_string();+ Some(((base.to_string(), full_ref), (ahead, behind)))+ })+ .collect()+}++fn build(+ locals: Vec<LocalBranch>,+ remotes: Vec<RemoteBranch>,+ ahead_behind: HashMap<(String, String), (usize, usize)>,+) -> RefSnapshot {+ let mut commits: HashMap<String, String> = HashMap::new();+ for b in &locals {+ commits.insert(b.name.clone(), b.commit_sha.clone());+ commits.insert(format!("refs/heads/{}", b.name), b.commit_sha.clone());+ }+ for r in &remotes {+ commits.insert(r.short_name.clone(), r.commit_sha.clone());+ commits.insert(+ format!("refs/remotes/{}", r.short_name),+ r.commit_sha.clone(),+ );+ }+ let locals_by_name = locals+ .iter()+ .enumerate()+ .map(|(i, b)| (b.name.clone(), i))+ .collect();+ RefSnapshot {+ commits,+ locals,+ locals_by_name,+ remotes,+ ahead_behind,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testing::TestRepo;++ #[test]+ fn captures_local_branches_with_shas() {+ let test = TestRepo::with_initial_commit();+ test.run_git(&["checkout", "-b", "feature"]);+ std::fs::write(test.root_path().join("a.txt"), "x\n").unwrap();+ test.run_git(&["add", "a.txt"]);+ test.run_git(&["commit", "-m", "feat"]);+ test.run_git(&["checkout", "main"]);++ let repo = Repository::at(test.root_path()).unwrap();+ let snap = repo.capture_refs().unwrap();++ let main_sha = test.git_output(&["rev-parse", "main"]);+ let feature_sha = test.git_output(&["rev-parse", "feature"]);++ assert_eq!(snap.resolve("main"), Some(main_sha.as_str()));+ assert_eq!(snap.resolve("refs/heads/main"), Some(main_sha.as_str()));+ assert_eq!(snap.resolve("feature"), Some(feature_sha.as_str()));+ assert_eq!(snap.local_branches().len(), 2);+ }++ #[test]+ fn captures_are_independent_after_ref_update() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ let before = repo.capture_refs().unwrap();+ let main_before = before.resolve("main").unwrap().to_owned();++ // Move main forward.+ std::fs::write(test.root_path().join("b.txt"), "y\n").unwrap();+ test.run_git(&["add", "b.txt"]);+ test.run_git(&["commit", "-m", "advance main"]);++ let after = repo.capture_refs().unwrap();+ let main_after = after.resolve("main").unwrap();++ assert_ne!(+ main_before, main_after,+ "post-write snapshot must reflect new SHA"+ );+ // The earlier snapshot still reports the pre-write SHA — it's a+ // frozen view, by design.+ assert_eq!(before.resolve("main"), Some(main_before.as_str()));+ }++ #[test]+ fn must_resolve_errors_on_missing_ref() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let snap = repo.capture_refs().unwrap();++ assert!(snap.must_resolve("does-not-exist").is_err());+ // HEAD is intentionally absent — callers fall back to rev-parse.+ assert_eq!(snap.resolve("HEAD"), None);+ }++ #[test]+ fn ahead_behind_populated_when_requested() {+ let test = TestRepo::with_initial_commit();+ test.run_git(&["checkout", "-b", "feature"]);+ std::fs::write(test.root_path().join("a.txt"), "x\n").unwrap();+ test.run_git(&["add", "a.txt"]);+ test.run_git(&["commit", "-m", "feat"]);+ test.run_git(&["checkout", "main"]);++ let repo = Repository::at(test.root_path()).unwrap();+ let snap = repo.capture_refs_with_ahead_behind("main").unwrap();++ // The plain capture leaves ahead_behind empty.+ let plain = repo.capture_refs().unwrap();+ assert_eq!(plain.ahead_behind("main", "refs/heads/feature"), None);++ // The ahead-behind capture populates it (git ≥ 2.36; on older git+ // the batch is empty, so we tolerate that here).+ if let Some((ahead, behind)) = snap.ahead_behind("main", "refs/heads/feature") {+ assert_eq!(ahead, 1, "feature is one commit ahead of main");+ assert_eq!(behind, 0);+ }+ }++ #[test]+ fn upstream_of_reads_from_local_inventory() {+ let test = TestRepo::with_initial_commit();+ // Set up a fake remote tracking config without a real remote.+ test.run_git(&["config", "branch.main.remote", "origin"]);+ test.run_git(&["config", "branch.main.merge", "refs/heads/main"]);++ let repo = Repository::at(test.root_path()).unwrap();+ let _snap = repo.capture_refs().unwrap();+ // Without a corresponding refs/remotes/origin/main, upstream:track+ // reports [gone] and upstream_of returns None — same contract as+ // today's Branch::upstream.+ // (This test mainly checks the method exists and doesn't panic.)+ }+}diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex f6ffb83cf..2525dd948 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -1249,8 +1249,10 @@ fn handle_detached_removed_worktree_output(format_path_for_display(ctx.worktree_path))));+ let snapshot = repo.capture_refs()?;let output = remove_worktree_with_cleanup(repo,+ &snapshot,ctx.worktree_path,RemoveOptions {branch: None,@@ -1323,8 +1325,10 @@ fn handle_named_removed_worktree_foreground();}+ let snapshot = repo.capture_refs()?;let output = remove_worktree_with_cleanup(repo,+ &snapshot,ctx.worktree_path,RemoveOptions {branch: Some(branch_name.to_string()),diff --git a/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snapindex 70cbdead1..650fb3dca 100644--- a/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap+++ b/tests/snapshots/integration__integration_tests__list__list_branches_with_nonexistent_default_branch.snap@@ -44,9 +44,9 @@ exit_code: 0----- stdout -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mRemote⇅[0m [1mPath[0m [1mCommit[0m [1mAge[0m [1mMessage@ main [31m⚑[39m[2m^[22m[2m|[22m [2m|[0m . [2m05a4a45d[0m [2m16h[0m [2mInitial commit-+ [2mfeature-a[0m [2m_[22m [2m../repo.feature-a[0m [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file-+ [2mfeature-b[0m [2m_[22m [2m../repo.feature-b[0m [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file-+ [2mfeature-c[0m [2m_[22m [2m../repo.feature-c[0m [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file++ feature-a ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file++ feature-b ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file++ feature-c ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[2m○[22m [2mShowing 4 worktreesdiff --git a/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snapindex 134128232..99d08054e 100644--- a/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap+++ b/tests/snapshots/integration__integration_tests__list__list_full_with_nonexistent_default_branch.snap@@ -44,9 +44,9 @@ exit_code: 0----- stdout -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mmain…±[0m [1mRemote⇅[0m [1mCI[0m [1mPath[0m [1mCommit[0m [1mAge[0m [1mMessage@ main [31m⚑[39m[2m^[22m[2m|[22m [2m|[0m . [2m05a4a45d[0m [2m16h[0m [2mInitial commit-+ [2mfeature-a[0m [2m_[22m [2m../repo.feature-a[0m [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file-+ [2mfeature-b[0m [2m_[22m [2m../repo.feature-b[0m [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file-+ [2mfeature-c[0m [2m_[22m [2m../repo.feature-c[0m [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file++ feature-a ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file++ feature-b ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file++ feature-c ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[2m○[22m [2mShowing 4 worktreesdiff --git a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snapindex 080e6ecb0..f9f45de34 100644--- a/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap+++ b/tests/snapshots/integration__integration_tests__list__list_warns_when_commit_details_batch_fails.snap@@ -53,7 +53,7 @@ exit_code: 0----- stderr -----[33m▲[39m [33mFailed to batch-fetch commit details: fatal: bad object 0000000000000000000000000000000000000001[39m[33m▲[39m [33mSome git operations failed:-[107m [0m [1m(detached)[22m: ahead-behind (git merge-base failed for main 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)+[107m [0m [1m(detached)[22m: ahead-behind (git merge-base failed for 05a4a45d0b981dad5c27db59dca482836d59f89e 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)[107m [0m [1m(detached)[22m: committed-trees-match (fatal: ambiguous argument '0000000000000000000000000000000000000001^{tree}': unknown revision or path not in the working tree.)[107m [0m [1m(detached)[22m: working-tree-diff (fatal: bad object HEAD)[107m [0m [1m(detached)[22m: merge-tree-conflicts (git merge-base failed for 05a4a45d0b981dad5c27db59dca482836d59f89e 0000000000000000000000000000000000000001: fatal: Not a valid commit name 0000000000000000000000000000000000000001)diff --git a/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snapindex b8f5d8c96..161e4a4e2 100644--- a/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap+++ b/tests/snapshots/integration__integration_tests__list__list_with_nonexistent_default_branch.snap@@ -43,9 +43,9 @@ exit_code: 0----- stdout -----[1mBranch[0m [1mStatus[0m [1mHEAD±[0m [1mmain↕[0m [1mRemote⇅[0m [1mPath[0m [1mCommit[0m [1mAge[0m [1mMessage@ main [31m⚑[39m[2m^[22m[2m|[22m [2m|[0m . [2m05a4a45d[0m [2m16h[0m [2mInitial commit-+ [2mfeature-a[0m [2m_[22m [2m../repo.feature-a[0m [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file-+ [2mfeature-b[0m [2m_[22m [2m../repo.feature-b[0m [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file-+ [2mfeature-c[0m [2m_[22m [2m../repo.feature-c[0m [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file++ feature-a ../repo.feature-a [2m1b87d473[0m [2m16h[0m [2mAdd feature-a file++ feature-b ../repo.feature-b [2mf62940fc[0m [2m16h[0m [2mAdd feature-b file++ feature-c ../repo.feature-c [2m345c7c93[0m [2m16h[0m [2mAdd feature-c file[2m○[22m [2mShowing 4 worktrees