Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Persistent cache for merge-tree and integration probe results (#2085)
Maximilian Roos7003edb72b02
diff --git a/docs/content/faq.md b/docs/content/faq.mdindex b9f984f50..cc9297efc 100644--- a/docs/content/faq.md+++ b/docs/content/faq.md@@ -114,7 +114,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`| Location | Purpose | Created by ||----------|---------|------------|| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |-| `.git/wt/cache/ci-status/*.json` | CI status cache (~1KB each) | `wt list` when `gh` or `glab` CLI is installed |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, merge-tree, and integration probe results | `wt list`, `wt merge`, `wt remove` || `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` || `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands || `.git/wt/logs/verbose.log` | Debug log for issue reporting | Running with `-vv` |@@ -123,7 +123,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`None of this is tracked by git or pushed to remotes.-**To remove:** `wt config state clear` removes all worktrunk data — config keys, CI cache, markers, hints, variables, logs, and stale trash.+**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.### What Worktrunk does NOT create@@ -157,7 +157,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch### Other cleanup- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)-- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, CI cache, markers, hints, variables, logs, stale trash)+- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell uninstall` — removes shell integration from rc filesSee [What files does Worktrunk create?](#what-files-does-worktrunk-create) for details.diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 3490d7206..b66b430ec 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -107,7 +107,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`| Location | Purpose | Created by ||----------|---------|------------|| `git config worktrunk.*` | Cached default branch, switch history, branch markers, custom variables | Various commands |-| `.git/wt/cache/ci-status/*.json` | CI status cache (~1KB each) | `wt list` when `gh` or `glab` CLI is installed |+| `.git/wt/cache/{kind}/*.json` | Cached CI status, merge-tree, and integration probe results | `wt list`, `wt merge`, `wt remove` || `.git/wt/logs/{branch}/**/*.log` | Background hook output (nested per branch) | Hooks, background `wt remove` || `.git/wt/logs/commands.jsonl` | Command audit log (~2MB max) | Hooks, LLM commands || `.git/wt/logs/verbose.log` | Debug log for issue reporting | Running with `-vv` |@@ -116,7 +116,7 @@ Worktrunk stores small amounts of cache and log data in the repository's `.git/`None of this is tracked by git or pushed to remotes.-**To remove:** `wt config state clear` removes all worktrunk data — config keys, CI cache, markers, hints, variables, logs, and stale trash.+**To remove:** `wt config state clear` removes all worktrunk data — config keys, caches, markers, hints, variables, logs, and stale trash.### What Worktrunk does NOT create@@ -152,7 +152,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch### Other cleanup- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)-- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, CI cache, markers, hints, variables, logs, stale trash)+- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, caches, markers, hints, variables, logs, stale trash)- `wt config shell uninstall` — removes shell integration from rc filesSee [What files does Worktrunk create?](#what-files-does-worktrunk-create) for details.diff --git a/src/cli/config.rs b/src/cli/config.rsindex 34081ee71..69cdb23d0 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -532,7 +532,7 @@ CI cache entries show status, age, and the commit SHA they were fetched for."#)]- Previous branch- All branch markers- All variables-- All CI status cache+- All caches (CI status, git commands)- All hints- All log files- Stale trash from worktree removal (`.git/wt/trash/`)diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex 33bc38fa6..ccd6d1074 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -886,6 +886,19 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {cleared_any = true;}+ // Clear git commands cache (merge-tree, patch-id results)+ let probe_cleared = repo.clear_git_commands_cache();+ if probe_cleared > 0 {+ eprintln!(+ "{}",+ success_message(cformat!(+ "Cleared <bold>{probe_cleared}</> git commands cache entr{}",+ if probe_cleared == 1 { "y" } else { "ies" }+ ))+ );+ cleared_any = true;+ }+// Clear all vars datalet vars_cleared = clear_all_vars(&repo)?;if vars_cleared > 0 {diff --git a/src/git/repository/integration.rs b/src/git/repository/integration.rsindex 0d37a5fbe..d89edc748 100644--- a/src/git/repository/integration.rs+++ b/src/git/repository/integration.rs@@ -5,6 +5,7 @@use anyhow::Context;use dashmap::mapref::entry::Entry;+use serde::{Deserialize, Serialize};use super::Repository;use crate::git::{IntegrationReason, check_integration, compute_integration_lazy};@@ -15,7 +16,7 @@ use crate::shell_exec::Cmd;/// Encapsulates the two-step sequence: first try `merge-tree --write-tree` to/// check if merging would add anything, then fall back to patch-id matching/// when merge-tree conflicts.-#[derive(Debug, Clone, Copy, PartialEq, Eq)]+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]pub struct MergeProbeResult {/// Whether merging the branch into target would change the target's tree./// Always `true` when merge-tree conflicts (conservative).@@ -143,21 +144,38 @@ 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)?;++ if let Some(cached) = super::probe_cache::get_merge_conflicts(self, &base_sha, &head_sha) {+ return Ok(cached);+ }+// Unrelated histories (no common ancestor) can't be merged — that's a conflict.- if self.merge_base(&base, &head)?.is_none() {+ if self.merge_base(&base_sha, &head_sha)?.is_none() {+ super::probe_cache::put_merge_conflicts(self, &base_sha, &head_sha, 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, &head])?;+ let output =+ self.run_command_output(&["merge-tree", "--write-tree", &base_sha, &head_sha])?;if output.status.code() == Some(1) {+ super::probe_cache::put_merge_conflicts(self, &base_sha, &head_sha, true);return Ok(true);}if !output.status.success() {let stderr = String::from_utf8_lossy(&output.stderr);- anyhow::bail!("git merge-tree failed for {base} {head}: {}", stderr.trim());+ anyhow::bail!(+ "git merge-tree failed for {base_sha} {head_sha}: {}",+ stderr.trim()+ );}+ super::probe_cache::put_merge_conflicts(self, &base_sha, &head_sha, false);Ok(false)}@@ -266,35 +284,54 @@ impl Repository {let branch = self.resolve_preferring_branch(branch);let target = self.resolve_preferring_branch(target);+ // Resolve refs to commit SHAs for the persistent cache key.+ // The probe result depends only on the two committed trees (the+ // patch-id fallback reads commits in merge_base..target, also a+ // pure function of the two SHAs). Asymmetric key: branch first,+ // then target, because the merge-tree result is compared against+ // target's tree.+ let branch_sha = self.rev_parse_commit(&branch)?;+ let target_sha = self.rev_parse_commit(&target)?;++ if let Some(cached) =+ super::probe_cache::get_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, &branch)?.is_none() {- return Ok(MergeProbeResult {+ if self.merge_base(&target_sha, &branch_sha)?.is_none() {+ let result = MergeProbeResult {would_merge_add: true,is_patch_id_match: false,- });+ };+ super::probe_cache::put_merge_add_probe(self, &branch_sha, &target_sha, result);+ return Ok(result);}- let merge_result = self.would_merge_add_to_target(&branch, &target)?;- match merge_result {- Some(would_add) => Ok(MergeProbeResult {+ 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,is_patch_id_match: false,- }),+ },None => {// merge-tree conflicted — try patch-id fallback.// 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, &target)+ .is_squash_merged_via_patch_id(&branch_sha, &target_sha).unwrap_or(false);- Ok(MergeProbeResult {+ MergeProbeResult {would_merge_add: true,is_patch_id_match: matched,- })+ }}- }+ };+ super::probe_cache::put_merge_add_probe(self, &branch_sha, &target_sha, result);+ Ok(result)}/// Determine the effective target for integration checks.@@ -376,6 +413,23 @@ impl Repository {}}+ /// 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 `probe_cache` to convert ref names into+ /// stable SHA-based cache keys before looking up cached merge-tree results.+ 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())+ }+ }+ }+/// Check if a branch is integrated into a target.////// This is a convenience method that combines [`compute_integration_lazy()`] anddiff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 5079ae966..5f5e97f4e 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -92,6 +92,7 @@ mod branches;mod config;mod diff;mod integration;+mod probe_cache;mod remotes;mod working_tree;mod worktrees;@@ -245,6 +246,11 @@ pub(super) struct RepoCache {/// 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 `probe_cache` by SHA.+ pub(super) commit_shas: DashMap<String, String>,+// ========== Per-worktree values (keyed by path) ==========/// Per-worktree git directory: worktree_path -> canonicalized git dir/// (e.g., `.git/worktrees/<name>` for linked worktrees, `.git` for main)@@ -566,6 +572,11 @@ impl Repository {self.git_common_dir().join("wt")}+ /// Clear all cached git command results, returning the count removed.+ pub fn clear_git_commands_cache(&self) -> usize {+ probe_cache::clear_all(self)+ }+/// Get the directory where worktrunk background logs are stored.////// Returns `<git-common-dir>/wt/logs/` (typically `.git/wt/logs/`).diff --git a/src/git/repository/probe_cache.rs b/src/git/repository/probe_cache.rsnew file mode 100644index 000000000..dba3485c9--- /dev/null+++ b/src/git/repository/probe_cache.rs@@ -0,0 +1,443 @@+//! Persistent cache for SHA-keyed git merge probes.+//!+//! Caches the results of expensive merge-tree / patch-id operations keyed+//! on pairs of commit SHAs. Because commit SHAs are content-addressed and+//! immutable, cached entries never go stale — the result of merging commit+//! A into commit B is the same today as it was last week. No TTL, no+//! invalidation logic, only a size bound to prevent unbounded growth.+//!+//! # Layout+//!+//! One file per cached entry under `.git/wt/cache/{kind}/{key}.json`,+//! where `kind` is the task kind (`merge-tree-conflicts`,+//! `merge-add-probe`) and `key` is the SHA-pair filename. This is the+//! same top-level layout as `ci-status/` and `summaries/`.+//!+//! Symmetric kinds (merge-tree-conflicts) sort the SHA pair so+//! `merge-tree(A, B)` and `merge-tree(B, A)` hit the same entry.+//! Asymmetric kinds (merge-add-probe) preserve ordering because the+//! merge-tree result is compared against `target`'s tree, so swapping+//! arguments changes the answer.+//!+//! # Concurrency+//!+//! Two concurrent writers racing on the same key produce the same value+//! (same SHA inputs), so a torn write is benign — `read()` treats corrupt+//! JSON as a miss. The LRU sweep may also race — `fs::remove_file`+//! failures are ignored because the goal is best-effort size bounding.+//!+//! # Failure handling+//!+//! All cache failures (corrupt JSON, I/O errors, permission denied) are+//! logged at `debug` level and degrade silently: reads return `None`,+//! writes are no-ops. Callers must never observe cache failures.++use std::fs;+use std::path::{Path, PathBuf};+use std::time::SystemTime;++use serde::{Serialize, de::DeserializeOwned};++use super::Repository;+use super::integration::MergeProbeResult;++/// Maximum cached entries per task kind before the LRU sweep removes the+/// oldest entries. 5000 entries × ~80 bytes ≈ 400 KB per kind — small+/// enough to ignore, large enough to cover years of typical use.+const MAX_ENTRIES_PER_KIND: usize = 5000;++const KIND_MERGE_TREE_CONFLICTS: &str = "merge-tree-conflicts";+const KIND_MERGE_ADD_PROBE: &str = "merge-add-probe";++/// Get the cache directory for a given task kind.+///+/// Each kind is a top-level directory under `.git/wt/cache/`, consistent+/// with `ci-status/` and `summaries/`.+fn cache_dir(repo: &Repository, kind: &str) -> PathBuf {+ repo.wt_dir().join("cache").join(kind)+}++/// Build a symmetric filename from a SHA pair (order-independent).+fn symmetric_key(sha1: &str, sha2: &str) -> String {+ if sha1 <= sha2 {+ format!("{sha1}-{sha2}.json")+ } else {+ format!("{sha2}-{sha1}.json")+ }+}++/// Build an asymmetric filename from a SHA pair (order preserved).+fn asymmetric_key(first: &str, second: &str) -> String {+ format!("{first}-{second}.json")+}++/// Read and deserialize a cache entry. Returns `None` on any failure.+fn read<T: DeserializeOwned>(path: &Path) -> Option<T> {+ let json = fs::read_to_string(path).ok()?;+ match serde_json::from_str::<T>(&json) {+ Ok(value) => Some(value),+ Err(e) => {+ log::debug!("probe_cache: corrupt entry at {}: {}", path.display(), e);+ None+ }+ }+}++/// Serialize and write a cache entry. A half-written file is handled by+/// `read()` (corrupt JSON → `None`), so plain `fs::write` is sufficient.+fn write<T: Serialize>(path: &Path, value: &T) {+ if let Some(parent) = path.parent()+ && let Err(e) = fs::create_dir_all(parent)+ {+ log::debug!(+ "probe_cache: failed to create dir {}: {}",+ parent.display(),+ e+ );+ return;+ }++ let Ok(json) = serde_json::to_string(value) else {+ log::debug!(+ "probe_cache: failed to serialize entry for {}",+ path.display()+ );+ return;+ };++ if let Err(e) = fs::write(path, &json) {+ log::debug!("probe_cache: failed to write {}: {}", path.display(), e);+ }+}++/// Enforce a size bound on `dir`. If it holds more than `max` JSON+/// entries, delete the oldest-mtime files until the count is back at+/// `max`.+///+/// Runs after every `put`. The cheap path (`count <= max`) avoids any+/// per-file stat and is a single directory listing.+///+/// `max` is a parameter rather than hard-coded to `MAX_ENTRIES_PER_KIND`+/// so tests can exercise the trim logic without creating thousands of+/// files.+fn sweep_lru(dir: &Path, max: usize) {+ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };++ // Fast path: collect DirEntry objects without statting. We only check+ // filename suffix to skip `.json.tmp` and other unrelated files.+ let json_entries: Vec<_> = entries+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))+ .collect();++ if json_entries.len() <= max {+ return;+ }++ // Over the bound — stat each entry to sort by mtime and trim the+ // oldest.+ let mut with_mtime: Vec<(PathBuf, SystemTime)> = json_entries+ .into_iter()+ .filter_map(|e| {+ let mtime = e.metadata().ok()?.modified().ok()?;+ Some((e.path(), mtime))+ })+ .collect();+ with_mtime.sort_by_key(|(_, mtime)| *mtime);++ let excess = with_mtime.len().saturating_sub(max);+ for (path, _) in with_mtime.iter().take(excess) {+ let _ = fs::remove_file(path);+ }+ log::debug!(+ "probe_cache: swept {} entries from {}",+ excess,+ dir.display()+ );+}++// ============================================================================+// Public API — merge-tree conflicts (symmetric)+// ============================================================================++/// Look up a cached `has_merge_conflicts(sha1, sha2)` result.+///+/// The key is order-independent: `(A, B)` and `(B, A)` hit the same entry.+pub(super) fn get_merge_conflicts(repo: &Repository, sha1: &str, sha2: &str) -> Option<bool> {+ let path = cache_dir(repo, KIND_MERGE_TREE_CONFLICTS).join(symmetric_key(sha1, sha2));+ read::<bool>(&path)+}++/// Store a `has_merge_conflicts(sha1, sha2)` result, triggering an LRU+/// sweep if the per-kind entry bound is exceeded.+pub(super) fn put_merge_conflicts(repo: &Repository, sha1: &str, sha2: &str, value: bool) {+ let dir = cache_dir(repo, KIND_MERGE_TREE_CONFLICTS);+ let path = dir.join(symmetric_key(sha1, sha2));+ write(&path, &value);+ sweep_lru(&dir, MAX_ENTRIES_PER_KIND);+}++// ============================================================================+// Public API — merge-add probe (asymmetric)+// ============================================================================++/// Look up a cached `merge_integration_probe(branch, target)` result.+///+/// The key is order-dependent: the merge result is compared against+/// `target`'s tree, so swapping arguments changes the semantics.+pub(super) fn get_merge_add_probe(+ repo: &Repository,+ branch_sha: &str,+ target_sha: &str,+) -> Option<MergeProbeResult> {+ let path = cache_dir(repo, KIND_MERGE_ADD_PROBE).join(asymmetric_key(branch_sha, target_sha));+ read::<MergeProbeResult>(&path)+}++/// Store a `merge_integration_probe(branch, target)` result, triggering+/// an LRU sweep if the per-kind entry bound is exceeded.+pub(super) fn put_merge_add_probe(+ repo: &Repository,+ branch_sha: &str,+ target_sha: &str,+ value: MergeProbeResult,+) {+ let dir = cache_dir(repo, KIND_MERGE_ADD_PROBE);+ let path = dir.join(asymmetric_key(branch_sha, target_sha));+ write(&path, &value);+ sweep_lru(&dir, MAX_ENTRIES_PER_KIND);+}++// ============================================================================+// Maintenance+// ============================================================================++/// Clear all cached merge-probe entries, returning the count removed.+///+/// Called by `wt config state clear` to give users a clean slate.+pub(crate) fn clear_all(repo: &Repository) -> usize {+ let mut cleared = 0;+ for kind in [KIND_MERGE_TREE_CONFLICTS, KIND_MERGE_ADD_PROBE] {+ let dir = cache_dir(repo, kind);+ let Ok(entries) = fs::read_dir(&dir) else {+ continue;+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().is_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {+ cleared += 1;+ }+ }+ }+ cleared+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::testing::TestRepo;++ // Key formatting++ #[test]+ fn test_symmetric_key_sorts_pair() {+ assert_eq!(symmetric_key("aaaa", "bbbb"), "aaaa-bbbb.json");+ assert_eq!(symmetric_key("bbbb", "aaaa"), "aaaa-bbbb.json");+ assert_eq!(+ symmetric_key("deadbeef", "deadbeef"),+ "deadbeef-deadbeef.json"+ );+ }++ #[test]+ fn test_asymmetric_key_preserves_order() {+ assert_eq!(asymmetric_key("aaaa", "bbbb"), "aaaa-bbbb.json");+ assert_eq!(asymmetric_key("bbbb", "aaaa"), "bbbb-aaaa.json");+ }++ // Round-trip file I/O++ #[test]+ fn test_merge_conflicts_roundtrip() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ assert_eq!(get_merge_conflicts(&repo, "aaaa", "bbbb"), None);++ put_merge_conflicts(&repo, "aaaa", "bbbb", true);+ assert_eq!(get_merge_conflicts(&repo, "aaaa", "bbbb"), Some(true));++ // Symmetric: swapped args hit the same entry+ assert_eq!(get_merge_conflicts(&repo, "bbbb", "aaaa"), Some(true));++ // Overwrite with a new value+ put_merge_conflicts(&repo, "aaaa", "bbbb", false);+ assert_eq!(get_merge_conflicts(&repo, "aaaa", "bbbb"), Some(false));+ }++ #[test]+ fn test_merge_add_probe_roundtrip() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ assert_eq!(get_merge_add_probe(&repo, "aaaa", "bbbb"), None);++ let value = MergeProbeResult {+ would_merge_add: true,+ is_patch_id_match: false,+ };+ put_merge_add_probe(&repo, "aaaa", "bbbb", value);+ assert_eq!(get_merge_add_probe(&repo, "aaaa", "bbbb"), Some(value));++ // Asymmetric: swapped args miss+ assert_eq!(get_merge_add_probe(&repo, "bbbb", "aaaa"), None);+ }++ #[test]+ fn test_kinds_are_isolated() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ put_merge_conflicts(&repo, "aaaa", "bbbb", true);+ // Same SHA pair in a different kind is a separate entry+ assert_eq!(get_merge_add_probe(&repo, "aaaa", "bbbb"), None);+ }++ #[test]+ fn test_corrupt_entry_returns_none() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();++ put_merge_conflicts(&repo, "aaaa", "bbbb", true);++ let path = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS).join(symmetric_key("aaaa", "bbbb"));+ fs::write(&path, "not valid json {{{").unwrap();++ assert_eq!(get_merge_conflicts(&repo, "aaaa", "bbbb"), None);+ }++ // LRU sweep++ #[test]+ fn test_sweep_lru_trims_oldest_entries() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let dir = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);+ fs::create_dir_all(&dir).unwrap();++ // Create 5 entries with monotonically increasing mtimes+ for i in 0..5 {+ let path = dir.join(format!("entry{i}.json"));+ fs::write(&path, "true").unwrap();+ // Brief sleep to ensure distinct mtimes+ std::thread::sleep(std::time::Duration::from_millis(10));+ }++ sweep_lru(&dir, 3);++ let mut remaining: Vec<_> = fs::read_dir(&dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .collect();+ remaining.sort();+ // The 2 oldest (entry0, entry1) should have been deleted+ assert_eq!(remaining, ["entry2.json", "entry3.json", "entry4.json"]);+ }++ #[test]+ fn test_sweep_lru_no_op_under_bound() {+ let test = TestRepo::with_initial_commit();+ let repo = Repository::at(test.root_path()).unwrap();+ let dir = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);+ fs::create_dir_all(&dir).unwrap();++ for i in 0..3 {+ fs::write(dir.join(format!("entry{i}.json")), "true").unwrap();+ }++ sweep_lru(&dir, 5);++ let count = fs::read_dir(&dir).unwrap().count();+ assert_eq!(count, 3, "should not delete anything when under bound");+ }++ // Cache consultation by has_merge_conflicts++ #[test]+ fn test_has_merge_conflicts_reads_cache() {+ let test = TestRepo::with_initial_commit();++ // Create a feature branch with a clean merge (no conflicts)+ test.run_git(&["checkout", "-b", "feature"]);+ fs::write(test.root_path().join("new.txt"), "content\n").unwrap();+ test.run_git(&["add", "new.txt"]);+ test.run_git(&["commit", "-m", "Add file"]);+ test.run_git(&["checkout", "main"]);++ let repo = Repository::at(test.root_path()).unwrap();++ // First call: real computation — clean merge → false+ assert!(!repo.has_merge_conflicts("main", "feature").unwrap());++ // Tamper with the cache file to return the wrong answer+ 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");+ fs::write(entries[0].path(), "true").unwrap();++ // Second call: reads the tampered value from cache+ // Note: we need a fresh Repository so the in-memory RepoCache doesn't+ // interfere (resolved_refs, merge_base, etc. are all keyed by ref name+ // and would bypass the cache for the same invocation — but+ // rev_parse_commit is cached per command, and on a fresh Repo the SHAs+ // will resolve identically to the first run).+ let repo2 = Repository::at(test.root_path()).unwrap();+ assert!(repo2.has_merge_conflicts("main", "feature").unwrap());+ }++ #[test]+ fn test_merge_integration_probe_reads_cache() {+ let test = TestRepo::with_initial_commit();++ // Create a feature branch that's already merged (fast-forward)+ test.run_git(&["checkout", "-b", "feature"]);+ fs::write(test.root_path().join("new.txt"), "content\n").unwrap();+ test.run_git(&["add", "new.txt"]);+ test.run_git(&["commit", "-m", "Feature"]);+ test.run_git(&["checkout", "main"]);+ test.run_git(&["merge", "feature"]);++ let repo = Repository::at(test.root_path()).unwrap();++ // First call: feature is fully integrated → would_merge_add=false+ let real = repo.merge_integration_probe("feature", "main").unwrap();+ assert!(!real.would_merge_add);++ // Tamper with the cache to flip the answer+ let dir = cache_dir(&repo, KIND_MERGE_ADD_PROBE);+ 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 tampered = MergeProbeResult {+ would_merge_add: true,+ is_patch_id_match: true,+ };+ fs::write(entries[0].path(), serde_json::to_string(&tampered).unwrap()).unwrap();++ // Fresh repo reads the tampered cache+ let repo2 = Repository::at(test.root_path()).unwrap();+ let cached = repo2.merge_integration_probe("feature", "main").unwrap();+ assert!(cached.would_merge_add);+ assert!(cached.is_patch_id_match);+ }+}diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex e3bfe2f18..4f54dbdf5 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -791,8 +791,13 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {.run().unwrap();- // Logs+ // Git commands cache (probe cache)let git_dir = repo.root_path().join(".git");+ let probe_dir = git_dir.join("wt/cache/merge-tree-conflicts");+ std::fs::create_dir_all(&probe_dir).unwrap();+ std::fs::write(probe_dir.join("abc123-def456.json"), "true").unwrap();++ // Logslet log_dir = git_dir.join("wt/logs");std::fs::create_dir_all(&log_dir).unwrap();write_log_at(@@ -807,6 +812,7 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {[32m✓[39m [32mCleared previous branch[39m[32m✓[39m [32mCleared [1m1[22m marker[39m[32m✓[39m [32mCleared [1m1[22m CI cache entry[39m+ [32m✓[39m [32mCleared [1m1[22m git commands cache entry[39m[32m✓[39m [32mCleared [1m1[22m variable[39m[32m✓[39m [32mCleared [1m1[22m log file[39m");diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snapindex 749ab02e8..5a58056ef 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_clear.snap@@ -58,7 +58,7 @@ Clears all stored state:- Previous branch- All branch markers- All variables-- All CI status cache+- All caches (CI status, git commands)- All hints- All log files- Stale trash from worktree removal ([2m.git/wt/trash/[0m)