Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Replace git stash create with write-tree for working tree conflict checks (#2119)
Maximilian Roos8e9b2ebd61d0
diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex 127af4d68..ae144d682 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -123,6 +123,7 @@//! | Task | Cache |//! |------|-------|//! | `MergeTreeConflicts` | `sha_cache` (merge-tree-conflicts) |+//! | `WorkingTreeConflicts` | `sha_cache` (merge-tree-conflicts, tree-SHA keyed) |//! | `WouldMergeAdd` | `sha_cache` (merge-add-probe) |//! | `IsAncestor` | `sha_cache` (is-ancestor) |//! | `HasFileChanges` | `sha_cache` (has-added-changes) |@@ -143,11 +144,27 @@//! - `Upstream` — `ahead_behind()` against the tracking branch; same SHA-pair//! pattern as `sha_cache`, just not wired up yet//!+//! ### Cached via tree SHA+//!+//! `WorkingTreeConflicts` uses `git write-tree` to snapshot the index as a tree SHA,+//! then checks for merge conflicts via `has_merge_conflicts_by_tree`. The tree SHA is+//! content-addressed and stable — identical index state produces the same SHA.+//!+//! When there are unstaged modifications or untracked files, the task copies the+//! index to a temp file, runs `git add -A` to stage all working tree content,+//! then `write-tree`.+//!+//! The cache key is `(base_commit_sha, branch_head_sha+tree_sha)`. The branch HEAD+//! SHA captures the merge-base dependency. On cache miss, `has_merge_conflicts_by_tree`+//! creates an ephemeral commit via `git commit-tree` for merge-tree; on cache hit,+//! no commit is created. This makes the cache-hit path a single `git write-tree`+//! (~15ms) instead of the previous `git stash create` (~50-265ms).+//!//! ### Fundamentally uncacheable//!//! Some task outputs depend on state outside the commit graph://!-//! - `WorkingTreeDiff`, `WorkingTreeConflicts` — uncommitted changes and index state+//! - `WorkingTreeDiff` — uncommitted changes and index state//! - `GitOperation` — presence of `.git/rebase-merge`, `.git/rebase-apply`, or `MERGE_HEAD`//! - `UserMarker` — local git config value//! - `UrlStatus` — TCP connect to a local dev server port; real-time by naturediff --git a/src/commands/list/collect/tasks.rs b/src/commands/list/collect/tasks.rsindex 4faada360..5e9b28bf9 100644--- a/src/commands/list/collect/tasks.rs+++ b/src/commands/list/collect/tasks.rs@@ -6,6 +6,7 @@use std::net::{SocketAddr, TcpStream};use std::time::Duration;+use anyhow::Context;use worktrunk::git::{LineDiff, Repository};use super::super::ci_status::{CiBranchName, PrStatus};@@ -405,8 +406,8 @@ impl Task for WorkingTreeDiffTask {.working_tree(&ctx.repo).ok_or_else(|| ctx.error(Self::KIND, &anyhow::anyhow!("requires a worktree")))?;- // Use --no-optional-locks to avoid index lock contention with WorkingTreeConflictsTask's- // `git stash create` which needs the index lock.+ // Use --no-optional-locks to avoid index lock contention with+ // WorkingTreeConflictsTask's `git write-tree`.let status_output = wt.run_command(&["--no-optional-locks", "status", "--porcelain"]).map_err(|e| ctx.error(Self::KIND, &e))?;@@ -467,9 +468,14 @@ impl Task for MergeTreeConflictsTask {/// Task 6b (worktree only): Working tree conflict check///-/// For dirty worktrees, uses `git stash create` to get a tree object that-/// includes uncommitted changes, then runs merge-tree against that.-/// Returns None if working tree is clean (caller should fall back to MergeTreeConflicts).+/// For dirty worktrees, builds a tree SHA from the index (plus untracked+/// files if present) via `git write-tree`, then checks for merge conflicts+/// against the default branch. Much cheaper than `git stash create` (~15ms+/// vs ~50-265ms) because it reads the index directly instead of creating a+/// full stash commit with working-tree diffing.+///+/// Returns None if working tree is clean (caller should fall back to+/// MergeTreeConflicts).pub struct WorkingTreeConflictsTask;impl Task for WorkingTreeConflictsTask {@@ -490,7 +496,6 @@ impl Task for WorkingTreeConflictsTask {.ok_or_else(|| ctx.error(Self::KIND, &anyhow::anyhow!("requires a worktree")))?;// Use --no-optional-locks to avoid index lock contention with WorkingTreeDiffTask.- // Both tasks run in parallel, and `git stash create` below needs the index lock.let status_output = wt.run_command(&["--no-optional-locks", "status", "--porcelain"]).map_err(|e| ctx.error(Self::KIND, &e))?;@@ -505,39 +510,40 @@ impl Task for WorkingTreeConflictsTask {});}- // Dirty working tree - create a temporary tree object via stash create- // `git stash create` returns a commit SHA without modifying refs- //- // Note: stash create fails when there are unmerged files (merge conflict in progress).- // In that case, fall back to the commit-based check.- let stash_result = wt.run_command(&["stash", "create"]);-- let stash_sha = match stash_result {- Ok(sha) => sha,- Err(_) => {- // Stash create failed (likely unmerged files during rebase/merge)- // Fall back to commit-based check- return Ok(TaskResult::WorkingTreeConflicts {- item_idx: ctx.item_idx,- has_working_tree_conflicts: None,- });- }- };-- let stash_sha = stash_sha.trim();-- // If stash create returns empty, working tree is clean (shouldn't happen but handle it)- if stash_sha.is_empty() {+ // Unmerged entries (UU, AU, UA, DU, UD, DD, AA) mean a merge/rebase+ // conflict is in progress. Fall back to the commit-based check to+ // preserve prior behavior — write-tree on unmerged entries would+ // produce a tree with conflict markers as content.+ let has_unmerged = status_output+ .lines()+ .any(|l| l.len() >= 2 && l.as_bytes()[0..2].contains(&b'U'));+ if has_unmerged {return Ok(TaskResult::WorkingTreeConflicts {item_idx: ctx.item_idx,has_working_tree_conflicts: None,});}- // Run merge-tree with the stash commit (repo-wide operation, doesn't need worktree)+ // Porcelain format: XY where X=index, Y=working-tree.+ // Fast path when all changes are staged (Y is space for every line):+ // write-tree on the real index is sufficient.+ // Slow path when there are unstaged modifications (Y != ' ') or+ // untracked files ('??'): copy index, `git add -A`, write-tree.+ let needs_working_tree = status_output+ .lines()+ .any(|l| l.starts_with("??") || l.as_bytes().get(1) != Some(&b' '));++ let tree_sha = if needs_working_tree {+ write_tree_with_working_tree(&wt).map_err(|e| ctx.error(Self::KIND, &e))?+ } else {+ wt.run_command(&["write-tree"])+ .map(|s| s.trim().to_string())+ .map_err(|e| ctx.error(Self::KIND, &e))?+ };+let has_conflicts = ctx.repo- .has_merge_conflicts(&base, stash_sha)+ .has_merge_conflicts_by_tree(&base, &ctx.branch_ref.commit_sha, &tree_sha).map_err(|e| ctx.error(Self::KIND, &e))?;Ok(TaskResult::WorkingTreeConflicts {@@ -547,6 +553,52 @@ impl Task for WorkingTreeConflictsTask {}}+/// Build a tree SHA representing the full working tree state (staged ++/// unstaged + untracked) by staging everything into a temporary index.+///+/// Copies the real index (preserving git's stat cache for unchanged files),+/// then `git add -A` to stage all modifications and untracked files, then+/// `git write-tree` to produce the tree SHA. The real index is untouched.+fn write_tree_with_working_tree(wt: &worktrunk::git::WorkingTree) -> anyhow::Result<String> {+ use worktrunk::shell_exec::Cmd;++ let git_dir = wt.git_dir()?;+ let worktree_root = wt.root()?;+ let real_index = git_dir.join("index");+ let log_ctx = wt+ .path()+ .file_name()+ .and_then(|n| n.to_str())+ .unwrap_or(".")+ .to_string();++ let temp_index = tempfile::NamedTempFile::new().context("Failed to create temporary index")?;+ std::fs::copy(&real_index, temp_index.path()).context("Failed to copy index file")?;+ let temp_index_path = temp_index+ .path()+ .to_str()+ .context("Temporary index path is not valid UTF-8")?;++ // Stage all changes (unstaged modifications + untracked files)+ Cmd::new("git")+ .args(["add", "-A"])+ .current_dir(&worktree_root)+ .context(&log_ctx)+ .env("GIT_INDEX_FILE", temp_index_path)+ .run()+ .context("Failed to stage working tree changes")?;++ let output = Cmd::new("git")+ .args(["write-tree"])+ .current_dir(&worktree_root)+ .context(&log_ctx)+ .env("GIT_INDEX_FILE", temp_index_path)+ .run()+ .context("Failed to write tree from temporary index")?;++ Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())+}+/// Task 7 (worktree only): Git operation state detection (rebase/merge)pub struct GitOperationTask;diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex ee0a98522..d8ff9a7c3 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -166,9 +166,6 @@ impl Repository {let base = self.resolve_preferring_branch(base);let head = self.resolve_preferring_branch(head);- // Resolve refs to commit SHAs for the persistent cache key.- // merge-tree conflict results are a pure function of the two- // committed trees, so SHA pairs are eternally valid cache keys.let base_sha = self.rev_parse_commit(&base)?;let head_sha = self.rev_parse_commit(&head)?;@@ -176,18 +173,68 @@ impl Repository {return Ok(cached);}+ self.run_merge_tree(&base_sha, &head_sha, &base_sha, &head_sha)+ }++ /// Check merge conflicts for a working tree represented by a tree SHA.+ ///+ /// Unlike [`Self::has_merge_conflicts`] which takes commit refs, this accepts a+ /// raw tree SHA (from `git write-tree`) and the branch HEAD commit SHA.+ /// On cache miss, creates an ephemeral commit via `git commit-tree` to+ /// feed `merge-tree` (which requires commit objects for merge-base+ /// resolution). On cache hit, no commit is created.+ ///+ /// The cache key is `(base_commit_sha, branch_head_sha+tree_sha)` — a+ /// composite that captures all three inputs to the three-way merge:+ /// the base tree, the merge-base (via branch HEAD ancestry), and the+ /// working tree content.+ pub fn has_merge_conflicts_by_tree(+ &self,+ base: &str,+ branch_head_sha: &str,+ tree_sha: &str,+ ) -> anyhow::Result<bool> {+ let base = self.resolve_preferring_branch(base);+ let base_sha = self.rev_parse_commit(&base)?;++ let cache_head = format!("{branch_head_sha}+{tree_sha}");+ if let Some(cached) = super::sha_cache::get_merge_conflicts(self, &base_sha, &cache_head) {+ return Ok(cached);+ }++ // Cache miss — create an ephemeral commit so merge-tree can resolve+ // the merge-base. The commit is unreferenced and will be GC'd.+ let head_commit =+ 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)+ }++ /// Run merge-tree and cache the result.+ ///+ /// `base_sha` and `head_sha` are passed to `git merge-tree` (must be+ /// commit SHAs). `cache_base` and `cache_head` are used as the+ /// sha_cache key pair.+ fn run_merge_tree(+ &self,+ base_sha: &str,+ head_sha: &str,+ cache_base: &str,+ cache_head: &str,+ ) -> anyhow::Result<bool> {// Unrelated histories (no common ancestor) can't be merged — that's a conflict.- if self.merge_base(&base_sha, &head_sha)?.is_none() {- super::sha_cache::put_merge_conflicts(self, &base_sha, &head_sha, true);+ if self.merge_base(base_sha, head_sha)?.is_none() {+ super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, true);return Ok(true);}// Exit codes: 0 = clean merge, 1 = conflicts, 128+ = error (invalid ref, corrupt repo)let output =- self.run_command_output(&["merge-tree", "--write-tree", &base_sha, &head_sha])?;+ self.run_command_output(&["merge-tree", "--write-tree", base_sha, head_sha])?;if output.status.code() == Some(1) {- super::sha_cache::put_merge_conflicts(self, &base_sha, &head_sha, true);+ super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, true);return Ok(true);}if !output.status.success() {@@ -197,7 +244,7 @@ impl Repository {stderr.trim());}- super::sha_cache::put_merge_conflicts(self, &base_sha, &head_sha, false);+ super::sha_cache::put_merge_conflicts(self, cache_base, cache_head, false);Ok(false)}diff --git a/src/git/repository/sha_cache.rs b/src/git/repository/sha_cache.rsindex 3e017654c..db2677ec3 100644--- a/src/git/repository/sha_cache.rs+++ b/src/git/repository/sha_cache.rs@@ -1,10 +1,12 @@//! Persistent cache for SHA-keyed git command results.//!-//! Caches the results of expensive git operations keyed on pairs of commit-//! SHAs. Because commit SHAs are content-addressed and immutable, cached-//! entries never go stale — the result of diffing commit A against commit B-//! is the same today as it was last week. No TTL, no invalidation logic,-//! only a size bound to prevent unbounded growth.+//! Caches the results of expensive git operations keyed on pairs of+//! content-addressed SHAs. Most entries use commit SHA pairs — the result+//! of diffing commit A against commit B is the same today as last week.+//! One variant (working-tree conflict checks) uses a composite key that+//! includes a tree SHA; see [`Repository::has_merge_conflicts_by_tree`].+//! No TTL, no invalidation logic, only a size bound to prevent unbounded+//! growth.//!//! # Layout//!@@ -487,6 +489,116 @@ mod tests {assert!(repo2.has_merge_conflicts("main", "feature").unwrap());}+ #[test]+ fn test_has_merge_conflicts_by_tree_uses_composite_cache_key() {+ let test = TestRepo::with_initial_commit();++ // Create a feature branch with a staged change+ test.run_git(&["checkout", "-b", "feature"]);+ fs::write(test.root_path().join("dirty.txt"), "uncommitted\n").unwrap();+ test.run_git(&["add", "dirty.txt"]);++ let branch_head = test.git_output(&["rev-parse", "HEAD"]);+ let tree_sha = test.git_output(&["write-tree"]);++ let repo = Repository::at(test.root_path()).unwrap();++ // Call with composite keying — computes and caches+ let result = repo+ .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)+ .unwrap();++ // Verify the cache entry uses the composite key+ let dir = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);+ let entries: Vec<_> = fs::read_dir(&dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))+ .collect();+ assert_eq!(entries.len(), 1, "exactly one cache entry expected");++ let filename = entries[0].file_name().to_string_lossy().into_owned();+ assert!(+ filename.contains(&tree_sha),+ "cache filename should contain tree SHA ({tree_sha}), got: {filename}"+ );++ // Tamper with the cache and verify a fresh repo reads the tampered value+ let tampered = !result;+ fs::write(entries[0].path(), serde_json::to_string(&tampered).unwrap()).unwrap();++ let repo2 = Repository::at(test.root_path()).unwrap();+ let cached = repo2+ .has_merge_conflicts_by_tree("main", &branch_head, &tree_sha)+ .unwrap();+ assert_eq!(cached, tampered, "should read tampered value from cache");+ }++ #[test]+ fn test_has_merge_conflicts_by_tree_invalidates_on_branch_head_change() {+ let test = TestRepo::with_initial_commit();++ // Set up a common ancestor with shared.txt+ fs::write(test.root_path().join("shared.txt"), "initial\n").unwrap();+ test.run_git(&["add", "shared.txt"]);+ test.run_git(&["commit", "-m", "base: add shared.txt"]);++ // Create feature branch from this point, then diverge both branches+ test.run_git(&["checkout", "-b", "feature"]);+ fs::write(test.root_path().join("shared.txt"), "feature content\n").unwrap();+ test.run_git(&["add", "shared.txt"]);+ test.run_git(&["commit", "-m", "feature: modify shared.txt"]);++ test.run_git(&["checkout", "main"]);+ fs::write(test.root_path().join("shared.txt"), "main content\n").unwrap();+ test.run_git(&["add", "shared.txt"]);+ test.run_git(&["commit", "-m", "main: modify shared.txt"]);++ // Back to feature, stage an extra file+ test.run_git(&["checkout", "feature"]);+ fs::write(test.root_path().join("extra.txt"), "extra\n").unwrap();+ test.run_git(&["add", "extra.txt"]);++ let head_before = test.git_output(&["rev-parse", "HEAD"]);+ let tree1 = test.git_output(&["write-tree"]);++ let repo = Repository::at(test.root_path()).unwrap();++ // Before rebase: feature conflicts with main (both modified shared.txt)+ let result_before = repo+ .has_merge_conflicts_by_tree("main", &head_before, &tree1)+ .unwrap();+ assert!(result_before, "should conflict before rebase");++ // Unstage, rebase, then re-stage (rebase requires a clean index)+ test.run_git(&["reset", "HEAD", "extra.txt"]);+ fs::remove_file(test.root_path().join("extra.txt")).unwrap();+ test.run_git(&["rebase", "main", "--strategy-option=theirs"]);++ // Re-stage the same extra file+ fs::write(test.root_path().join("extra.txt"), "extra\n").unwrap();+ test.run_git(&["add", "extra.txt"]);++ let head_after = test.git_output(&["rev-parse", "HEAD"]);+ let tree2 = test.git_output(&["write-tree"]);++ assert_ne!(+ head_before, head_after,+ "branch HEAD should change after rebase"+ );++ let repo2 = Repository::at(test.root_path()).unwrap();+ let result_after = repo2+ .has_merge_conflicts_by_tree("main", &head_after, &tree2)+ .unwrap();++ // After rebase onto main, feature is based on main — no conflicts+ assert!(+ !result_after,+ "should not conflict after rebase (different branch HEAD = different cache key)"+ );+ }+#[test]fn test_merge_integration_probe_reads_cache() {let test = TestRepo::with_initial_commit();diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 78fe3284b..a0048d15b 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -2820,7 +2820,7 @@ fn test_list_maximum_status_symbols(mut repo: TestRepo) {////// This specifically tests the WorkingTreeConflicts task which:-/// 1. Uses `git stash create` to get a tree object from uncommitted changes+/// 1. Uses `git write-tree` to snapshot the index (with temp index for unstaged/untracked)/// 2. Runs merge-tree against the default branch to detect conflicts////// Both kinds of conflicts are checked in both `wt list` and `wt list --full`:@@ -2861,7 +2861,7 @@ fn test_list_working_tree_conflicts(mut repo: TestRepo) {}///-/// Even with --full, if the working tree is clean, we skip the stash-based check+/// Even with --full, if the working tree is clean, we skip the working-tree check/// and just use the commit-level conflict detection.#[rstest]fn test_list_full_clean_working_tree_uses_commit_conflicts(mut repo: TestRepo) {