Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(git): close remaining cache-staleness vectors after RefSnapshot cutover (#2530)
Maximilian Roosee242f3090ee
diff --git a/src/commands/command_executor.rs b/src/commands/command_executor.rsindex a1830f980..beb890bac 100644--- a/src/commands/command_executor.rs+++ b/src/commands/command_executor.rs@@ -250,22 +250,17 @@ pub fn build_hook_context(// Resolve commit from the Active branch, not HEAD at discovery path.// This ensures {{ commit }} follows the Active branch even when the// CommandContext points to a different worktree than where we're running.- // When `ctx.branch` matches the running worktree's current branch — the- // alias / hook hot path — reuse the HEAD SHA already cached by- // `WorkingTree::prewarm_info` instead of firing a fresh `rev-parse`.// Detached HEAD (`ctx.branch == None`) must read HEAD from// `ctx.worktree_path`, not the running worktree: `wt step for-each`// iterates over sibling worktrees, and a sibling on detached HEAD has a- // different HEAD than the worktree `wt` runs in. Cross-worktree contexts- // on a branch fall through to `rev-parse <branch>`, which is repo-wide.- let running_wt = ctx.repo.current_worktree();+ // different HEAD than the worktree `wt` runs in. Branched contexts go+ // through `rev-parse <branch>`, which is repo-wide.let commit = match ctx.branch {- Some(branch) if running_wt.branch().ok().flatten().as_deref() != Some(branch) => ctx+ Some(branch) => ctx.repo.run_command(&["rev-parse", branch]).ok().map(|s| s.trim().to_owned()),- Some(_) => running_wt.head_sha().ok().flatten(),None => ctx.repo.worktree_at(ctx.worktree_path)diff --git a/src/commands/picker/mod.rs b/src/commands/picker/mod.rsindex 1b219da28..cb37baf7c 100644--- a/src/commands/picker/mod.rs+++ b/src/commands/picker/mod.rs@@ -305,6 +305,7 @@ impl CommandCollector for PickerCollector {config,caller_path,None,+ None,);match preparation {@@ -400,9 +401,9 @@ pub fn handle_picker(let state = PreviewState::new();worktrunk::shell_exec::trace_instant("Picker layout detected");- // Prime the current worktree's root / git-dir / branch / HEAD-SHA caches- // with one batched `git rev-parse`. Subsumes the two standalone forks that- // the speculative preview block below would otherwise make via `branch()`+ // Prime the current worktree's root / git-dir / branch caches with one+ // batched `git rev-parse`. Subsumes the two standalone forks that the+ // speculative preview block below would otherwise make via `branch()`// and `root()`, and is also short-circuited when `collect::collect` calls// `repo.url_template()` → `load_project_config()` → `project_config_path()`// (which runs `prewarm_info` again — now a cache hit).diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex ebe0d76b3..6409e1a28 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -7,8 +7,8 @@ use anyhow::{Context, bail};use color_print::cformat;use worktrunk::config::UserConfig;use worktrunk::git::{- BranchDeletionMode, GitError, IntegrationReason, Repository, WorktreeInfo, parse_porcelain_z,- parse_untracked_files,+ BranchDeletionMode, GitError, IntegrationReason, RefSnapshot, Repository, WorktreeInfo,+ parse_porcelain_z, parse_untracked_files,};use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, format_with_gutter, progress_message, warning_message};@@ -42,6 +42,12 @@ pub trait RepositoryCliExt {////// `worktrees` provides a pre-fetched worktree list to avoid redundant/// `git worktree list` calls. Pass `None` to fetch on demand.+ ///+ /// `snapshot` provides a pre-captured ref snapshot to avoid redundant+ /// `for-each-ref` scans when preparing many removals in a row (e.g.+ /// `step_prune` validates one candidate per loop iteration). Pass `None`+ /// to capture a fresh snapshot inside this call.+ #[allow(clippy::too_many_arguments)]fn prepare_worktree_removal(&self,target: RemoveTarget,@@ -50,6 +56,7 @@ pub trait RepositoryCliExt {config: &UserConfig,current_path: Option<PathBuf>,worktrees: Option<&[WorktreeInfo]>,+ snapshot: Option<&RefSnapshot>,) -> anyhow::Result<RemoveResult>;/// Prepare the target worktree for push by auto-stashing non-overlapping changes when safe.@@ -79,6 +86,7 @@ impl RepositoryCliExt for Repository {warn_about_untracked_files(&status)}+ #[allow(clippy::too_many_arguments)]fn prepare_worktree_removal(&self,target: RemoveTarget,@@ -87,6 +95,7 @@ impl RepositoryCliExt for Repository {config: &UserConfig,current_path: Option<PathBuf>,worktrees: Option<&[WorktreeInfo]>,+ snapshot: Option<&RefSnapshot>,) -> anyhow::Result<RemoveResult> {let current_path = current_path.map_or_else(|| self.current_worktree().root(), Ok)?;let worktrees = match worktrees {@@ -97,9 +106,16 @@ 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()?;+ // Reuse caller's snapshot when present; otherwise capture once for the+ // two `compute_integration_reason` calls below.+ let owned_snapshot;+ let snapshot = match snapshot {+ Some(s) => s,+ None => {+ owned_snapshot = self.capture_refs()?;+ &owned_snapshot+ }+ };// Phase 1: Resolve target to branch name and worktree disposition.// BranchOnly variants don't early-return — they go through shared validation below.@@ -230,7 +246,7 @@ impl RepositoryCliExt for Repository {let target = default_branch.as_deref().or(Some("HEAD"));let (integration_reason, target_branch) = compute_integration_reason(self,- &snapshot,+ snapshot,Some(&branch),target,deletion_mode,@@ -282,7 +298,7 @@ impl RepositoryCliExt for Repository {// display (e.g., origin/main when upstream is ahead).let (integration_reason, effective_target) = compute_integration_reason(self,- &snapshot,+ snapshot,branch_name.as_deref(),target_branch.as_deref(),deletion_mode,@@ -455,7 +471,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,+ snapshot: &RefSnapshot,branch_name: Option<&str>,target_branch: Option<&str>,deletion_mode: BranchDeletionMode,diff --git a/src/commands/step_commands.rs b/src/commands/step_commands.rsindex 3a03c2e55..117c83b86 100644--- a/src/commands/step_commands.rs+++ b/src/commands/step_commands.rs@@ -1416,6 +1416,7 @@ pub fn step_prune(foreground: bool,run_hooks: bool,worktrees: &[WorktreeInfo],+ snapshot: &worktrunk::git::RefSnapshot,) -> anyhow::Result<bool> {let target = match candidate.kind {CandidateKind::Current => RemoveTarget::Current,@@ -1442,6 +1443,7 @@ pub fn step_prune(config,None,Some(worktrees),+ Some(snapshot),) {Ok(plan) => plan,Err(_) => {@@ -1550,13 +1552,17 @@ pub fn step_prune(// integration_refs produces an empty par_iter that completes immediately.let repo_clone = repo.clone();let target = integration_target.clone();+ // Share by Arc — main thread keeps `snapshot_arc` for `try_remove`; the+ // rayon worker takes a refcount-bump clone. No deep snapshot copy.let snapshot_arc = std::sync::Arc::new(snapshot);+ let snapshot_for_thread = std::sync::Arc::clone(&snapshot_arc);std::thread::spawn(move || {integration_refs.into_par_iter().enumerate().for_each(|(idx, ref_name)| {- let result = repo_clone.integration_reason(&snapshot_arc, &ref_name, &target);+ let result =+ repo_clone.integration_reason(&snapshot_for_thread, &ref_name, &target);let _ = tx.send((idx, result));});});@@ -1635,7 +1641,15 @@ pub fn step_prune(dry_run_info.push((candidate, info));} else if is_current {deferred_current = Some(candidate);- } else if try_remove(&candidate, &repo, &config, foreground, run_hooks, worktrees)? {+ } else if try_remove(+ &candidate,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )? {removed.push(candidate);}continue;@@ -1686,7 +1700,15 @@ pub fn step_prune(suffix,};dry_run_info.push((candidate, info));- } else if try_remove(&candidate, &repo, &config, foreground, run_hooks, worktrees)? {+ } else if try_remove(+ &candidate,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )? {removed.push(candidate);}}@@ -1757,7 +1779,15 @@ pub fn step_prune(// Remove deferred current worktree last (cd-to-primary happens here)if let Some(current) = deferred_current- && try_remove(¤t, &repo, &config, foreground, run_hooks, worktrees)?+ && try_remove(+ ¤t,+ &repo,+ &config,+ foreground,+ run_hooks,+ worktrees,+ &snapshot_arc,+ )?{removed.push(current);}diff --git a/src/git/repository/config.rs b/src/git/repository/config.rsindex a4a649efd..01a097eae 100644--- a/src/git/repository/config.rs+++ b/src/git/repository/config.rs@@ -513,8 +513,8 @@ impl Repository {}// Batched rev-parse: asks `--is-inside-work-tree` and also pre-warms- // the worktree root / git-dir / branch / HEAD-SHA caches, sparing- // four later forks on the typical alias path.+ // the worktree root / git-dir / branch caches, sparing three later+ // forks on the typical alias path.let info = self.current_worktree().prewarm_info().unwrap_or_default();if let Some(root) = info.root {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 4f75bb369..373909304 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -285,11 +285,6 @@ pub(super) struct RepoCache {pub(super) worktree_roots: DashMap<PathBuf, PathBuf>,/// Current branch per worktree: worktree_path -> branch name (None = detached HEAD)pub(super) current_branches: DashMap<PathBuf, Option<String>>,- /// HEAD commit SHA per worktree: worktree_path -> SHA (None = unborn, HEAD unresolvable).- /// Primed in bulk by `WorkingTree::prewarm_info()`; lazily resolved on miss via- /// `WorkingTree::head_sha()`. Lets alias-context expansion consult the cache- /// instead of spawning a fresh `git rev-parse HEAD`.- pub(super) head_shas: DashMap<PathBuf, Option<String>>,/// Cached `git status --porcelain` output per worktree: worktree_path -> raw porcelain./// Populated by `WorkingTree::status_porcelain_cached()` so parallel tasks/// (working-tree diff + conflict detection) share one subprocess per worktreediff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex 45982ffaf..fae859d0f 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -27,15 +27,17 @@ fn has_initialized_submodules_from_status(status: &str) -> bool {/// Mirrors what the batched `git rev-parse` actually resolved so callers can/// read the data directly instead of round-tripping through the per-field/// cache accessors. `prewarm_info` still primes [`RepoCache`] so later calls-/// to [`WorkingTree::branch`], [`WorkingTree::root`], [`WorkingTree::git_dir`]-/// and [`WorkingTree::head_sha`] remain single cache hits.+/// to [`WorkingTree::branch`], [`WorkingTree::root`], and+/// [`WorkingTree::git_dir`] remain single cache hits. HEAD SHA is not cached:+/// `wt merge` and similar commands move HEAD mid-run, and a stale cached SHA+/// would surface in template variables (`{{ commit }}`) for hooks that fire+/// after the move. [`WorkingTree::head_sha`] always reads fresh.////// When `is_inside` is false every other field is `None` — nothing else ran./// When `is_inside` is true, `root` lands unconditionally and `git_dir` lands-/// unless canonicalization failed. HEAD-derived fields (`current_branch`,-/// `head_sha`) are only populated when the whole batch succeeded; on unborn-/// HEAD they stay `None` and the per-accessor fallback paths handle the-/// symbolic-ref lookup.+/// unless canonicalization failed. `current_branch` is only populated when+/// the whole batch succeeded; on unborn HEAD it stays `None` and the+/// per-accessor fallback paths handle the symbolic-ref lookup.////// [`RepoCache`]: super::RepoCache#[derive(Debug, Clone, Default)]@@ -52,8 +54,6 @@ pub struct WorkingTreeGitInfo {/// detached. `None` when HEAD was unresolvable (unborn branch) or outside/// a work tree.pub current_branch: Option<Option<String>>,- /// HEAD commit SHA. `None` on unborn branches or outside a work tree.- pub head_sha: Option<String>,}/// Get a short display name for a path, used in logging context.@@ -156,23 +156,21 @@ impl<'a> WorkingTree<'a> {/// Pre-warm the worktree caches with a single batched `git rev-parse` and/// return a snapshot of what it resolved.///- /// Folds five rev-parse selectors that would otherwise fire as separate+ /// Folds four rev-parse selectors that would otherwise fire as separate/// forks during alias/hook dispatch (`--is-inside-work-tree` from/// [`Repository::project_config_path`], plus [`Self::root`], [`Self::git_dir`],- /// [`Self::head_sha`], and [`Self::branch`]) into one. Bare `HEAD` sits- /// before `--symbolic-full-name HEAD` because `--symbolic-full-name` is a- /// sticky mode flag — emitting the unqualified `HEAD` first gives us a- /// commit SHA, then the mode switch makes the second `HEAD` resolve as a- /// ref name.+ /// and [`Self::branch`]) into one. HEAD SHA is intentionally NOT batched+ /// here: it moves mid-command (`wt merge`'s rebase, `wt step commit`,+ /// hook-emitted commits), so caching invites stale reads in template+ /// expansion. [`Self::head_sha`] forks fresh on each call.////// `--show-toplevel` and `--git-dir` succeed even on unborn branches —/// rev-parse prints them before HEAD errors — so `root`/`git_dir` are- /// cached whenever we're inside a work tree. `head_sha` and- /// `current_branch` are only populated when the whole batch succeeded,- /// so [`Self::branch`]'s `symbolic-ref` fallback still handles genuine- /// unborn HEADs. On unborn the symbolic-full-name line lands as a- /// fallback literal "HEAD", which would be indistinguishable from- /// detached HEAD without the exit status.+ /// cached whenever we're inside a work tree. `current_branch` is only+ /// populated when the whole batch succeeded, so [`Self::branch`]'s+ /// `symbolic-ref` fallback still handles genuine unborn HEADs. On unborn+ /// the symbolic-full-name line lands as a fallback literal "HEAD", which+ /// would be indistinguishable from detached HEAD without the exit status.////// Idempotent within a single command (for paths inside a work tree):/// once `worktree_roots` is primed — by this method or by [`Self::root`]@@ -189,7 +187,7 @@ impl<'a> WorkingTree<'a> {// reconstruct the snapshot from the caches instead of spawning another// `git rev-parse`. Fields with no cache entry stay `None`, matching// the semantics of a freshly-run batch on unborn HEAD (where- // HEAD-derived entries never land).+ // `current_branch` never lands).if let Some(root) = self.repo.cache@@ -207,12 +205,6 @@ impl<'a> WorkingTree<'a> {.current_branches.get(&self.path).map(|e| e.clone()),- head_sha: self- .repo- .cache- .head_shas- .get(&self.path)- .and_then(|e| e.clone()),});}@@ -221,7 +213,6 @@ impl<'a> WorkingTree<'a> {"--is-inside-work-tree","--show-toplevel","--git-dir",- "HEAD","--symbolic-full-name","HEAD",])?;@@ -264,22 +255,12 @@ impl<'a> WorkingTree<'a> {Some(resolved)});- // HEAD-derived lines (SHA, symbolic-full-name) are only trustworthy- // when the batch succeeded. On unborn HEAD the SHA line is absent- // (rev-parse errored on it) and the symbolic-full-name line still- // lands but is the literal "HEAD" fallback — we can't tell that from- // detached HEAD without the exit status.- let (head_sha, current_branch) = if output.status.success() {- let sha = lines.next().and_then(|raw| {- let sha = (!raw.trim().is_empty()).then(|| raw.trim().to_owned());- self.repo- .cache- .head_shas- .entry(self.path.clone())- .or_insert_with(|| sha.clone());- sha- });- let branch = lines.next().map(|raw| {+ // The `--symbolic-full-name HEAD` line is only trustworthy when the+ // batch succeeded. On unborn HEAD the line lands but is the literal+ // "HEAD" fallback — we can't tell that from detached HEAD without the+ // exit status.+ let current_branch = if output.status.success() {+ lines.next().map(|raw| {let branch = raw.trim().strip_prefix("refs/heads/").map(str::to_owned);self.repo.cache@@ -287,10 +268,9 @@ impl<'a> WorkingTree<'a> {.entry(self.path.clone()).or_insert_with(|| branch.clone());branch- });- (sha, branch)+ })} else {- (None, None)+ None};Ok(WorkingTreeGitInfo {@@ -298,7 +278,6 @@ impl<'a> WorkingTree<'a> {root,git_dir,current_branch,- head_sha,})}@@ -329,22 +308,19 @@ impl<'a> WorkingTree<'a> {/// Get the HEAD commit SHA for this worktree, or `None` on an unborn branch.///- /// Result is cached in the repository's shared cache (keyed by worktree path).- /// Populated in bulk by [`Self::prewarm_info`]; resolved lazily here on miss- /// via `git rev-parse HEAD`, which errors on unborn branches — treated as- /// `None` rather than an error so detached and unborn callers look the same.+ /// Always reads fresh via `git rev-parse HEAD` — HEAD moves mid-command in+ /// any flow that commits, rebases, or merges, and a cached SHA would+ /// surface stale in template variables (`{{ commit }}`) for hooks that+ /// fire after the move. The fork is cheap (~5 ms) and only fires on the+ /// few paths that need a HEAD SHA. Errors from `rev-parse` (unborn+ /// branches) are mapped to `None` so detached and unborn callers look the+ /// same.pub fn head_sha(&self) -> anyhow::Result<Option<String>> {- match self.repo.cache.head_shas.entry(self.path.clone()) {- Entry::Occupied(e) => Ok(e.get().clone()),- Entry::Vacant(e) => {- let sha = self- .run_command(&["rev-parse", "HEAD"])- .ok()- .map(|s| s.trim().to_owned())- .filter(|s| !s.is_empty());- Ok(e.insert(sha).clone())- }- }+ Ok(self+ .run_command(&["rev-parse", "HEAD"])+ .ok()+ .map(|s| s.trim().to_owned())+ .filter(|s| !s.is_empty()))}/// Return cached `git status --porcelain` output for this worktree.@@ -612,7 +588,6 @@ mod tests {let wt = repo.worktree_at(test.root_path());let info = wt.prewarm_info().unwrap();- let head_sha = wt.head_sha().unwrap().expect("HEAD resolved after commit");assert!(info.is_inside);assert_eq!(info.root.as_deref(), Some(wt.root().unwrap().as_path()));@@ -621,9 +596,27 @@ mod tests {Some(wt.git_dir().unwrap().as_path()));assert_eq!(info.current_branch, Some(Some("main".to_string())));- assert_eq!(info.head_sha.as_deref(), Some(head_sha.as_str()));- // Second call hits the shared cache (same values, no fresh subprocess semantics).- assert_eq!(wt.head_sha().unwrap().as_deref(), Some(head_sha.as_str()));+ }++ #[test]+ fn head_sha_tracks_head_movement() {+ // `head_sha()` always reads fresh — a commit between calls must be+ // visible without invalidation. Guards against re-introducing a cache.+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let wt = repo.worktree_at(test.root_path());++ let before = wt.head_sha().unwrap().expect("HEAD resolved after init");++ std::fs::write(test.root_path().join("file.txt"), "second").unwrap();+ test.run_git(&["add", "."]);+ test.run_git(&["commit", "-m", "second"]);++ let after = wt+ .head_sha()+ .unwrap()+ .expect("HEAD still resolved after second commit");+ assert_ne!(before, after, "head_sha must reflect the new commit");}#[test]@@ -648,7 +641,6 @@ mod tests {assert_eq!(second.root.as_deref(), Some(sentinel_root.as_path()));assert_eq!(second.git_dir, first.git_dir);assert_eq!(second.current_branch, first.current_branch);- assert_eq!(second.head_sha, first.head_sha);}#[test]@@ -719,12 +711,12 @@ mod tests {info.current_branch.is_none(),"batch failed, branch cache left to `symbolic-ref` fallback");- assert!(info.head_sha.is_none(), "no commits yet => no SHA");// `branch()` fallback still resolves the unborn branch name through// `symbolic-ref --short HEAD`, independently of the batch.assert_eq!(wt.branch().unwrap().as_deref(), Some("main"));- // `head_sha()` fallback returns None — `rev-parse HEAD` errors on unborn.+ // `head_sha()` returns None on unborn HEAD — `rev-parse HEAD` errors,+ // mapped to None so detached and unborn callers look the same.assert!(wt.head_sha().unwrap().is_none());}}diff --git a/src/main.rs b/src/main.rsindex 05eca70a6..b441db191 100644--- a/src/main.rs+++ b/src/main.rs@@ -654,6 +654,12 @@ fn validate_remove_targets(let deletion_mode = BranchDeletionMode::from_flags(keep_branch, force_delete);let worktrees = repo.list_worktrees().ok();+ // Capture once for the validation loop. Validation only reads — actual+ // removals run later in `handle_remove_output`, so ref state is stable+ // across candidates here. Errors propagate to per-candidate calls, which+ // fall back to capturing internally when None.+ let snapshot = repo.capture_refs().ok();+let mut plans = RemovePlans {others: Vec::new(),branch_only: Vec::new(),@@ -685,6 +691,7 @@ fn validate_remove_targets(config,None,worktrees,+ snapshot.as_ref(),) {Ok(result) => plans.current = Some(result),Err(e) => plans.record_error(e),@@ -706,6 +713,7 @@ fn validate_remove_targets(config,None,worktrees,+ snapshot.as_ref(),) {Ok(result) => plans.others.push(result),Err(e) => plans.record_error(e),@@ -719,6 +727,7 @@ fn validate_remove_targets(config,None,worktrees,+ snapshot.as_ref(),) {Ok(result) => plans.branch_only.push(result),Err(e) => plans.record_error(e),@@ -808,6 +817,7 @@ fn handle_remove_command(args: RemoveArgs, yes: bool) -> anyhow::Result<()> {&config,None,None,+ None,).context("Failed to remove worktree")?;diff --git a/tests/integration_tests/eval.rs b/tests/integration_tests/eval.rsindex 78a1eba79..27366fbb3 100644--- a/tests/integration_tests/eval.rs+++ b/tests/integration_tests/eval.rs@@ -107,8 +107,9 @@ fn test_eval_conditional(repo: TestRepo) {}/// `{{ commit }}` resolves to the running worktree's HEAD SHA on the on-branch-/// hot path. `build_hook_context` reads the SHA from the cache primed by-/// `WorkingTree::prewarm_info` instead of firing `git rev-parse <branch>`.+/// hot path. `build_hook_context` resolves it via `git rev-parse <branch>`+/// (always fresh from the ref store), so the value tracks any HEAD movement+/// during the command.#[rstest]fn test_eval_commit_matches_head_sha(repo: TestRepo) {let expected = repo.git_output(&["rev-parse", "HEAD"]);