Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
refactor(cache): unify on-disk cache mechanics; add summary cache to state (#2407)
Maximilian Roos11caab2f39f0
diff --git a/Cargo.toml b/Cargo.tomlindex a9dde0689..147c481da 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -135,6 +135,10 @@ dashmap = "6.1.0"fs2 = "0.4.3"sanitize-filename = "0.6.0"schemars = { version = "1.2.1", features = ["derive"] }+# SHA-256 is used for persistent cache keys (e.g., summary diff hashes in+# `.git/wt/cache/summary/`). stdlib's `DefaultHasher` is not guaranteed+# stable across Rust versions, so we need a deterministic algorithm on disk.+sha2 = "0.11"tempfile = "3.27"wait-timeout = "0.2"@@ -168,7 +172,6 @@ vt100 = "0.16"ansi-to-html = "0.2.2"wt-perf = { path = "tests/helpers/wt-perf" }similar = "3.1.0"-sha2 = "0.11"[[bench]]name = "alias"diff --git a/src/cache.rs b/src/cache.rsnew file mode 100644index 000000000..f11909625--- /dev/null+++ b/src/cache.rs@@ -0,0 +1,350 @@+//! Shared primitives for the on-disk caches under `.git/wt/cache/`.+//!+//! Three callers use these primitives: `sha_cache` (content-addressed SHA-pair+//! results), `ci_status::cache` (branch → CI status with TTL), and `summary`+//! (branch → LLM summary with content-addressed filenames). Each owns its+//! layout, struct shape, and freshness rules — this module only owns the+//! filesystem mechanics so those rules have one implementation instead of+//! three.+//!+//! # Torn-write semantics+//!+//! Writes use a plain [`fs::write`], not temp-file-plus-rename. A crash in the+//! middle of a write produces a truncated file at the expected path, which+//! [`read_json`] rejects as corrupt JSON — indistinguishable from a cache miss+//! from the caller's perspective. Two concurrent writers for the same key+//! produce the same value for content-addressed caches (benign) and the last+//! writer wins for TTL-based ones (benign — the next read re-fetches if+//! stale). Neither case justifies the rename dance.+//!+//! # Error policy+//!+//! - [`read_json`] returns `None` on any failure (missing file, I/O error,+//! corrupt JSON) — callers treat all three as a cache miss. Corrupt JSON+//! is logged at debug.+//! - [`write_json`] degrades silently. Callers never observe cache write+//! failures because a failed write just means the next access re-computes.+//! - [`clear_one`] and [`clear_json_files`] propagate non-`NotFound` I/O+//! errors so `wt config state clear` can report truthfully when it can't+//! delete a file (e.g. permission denied). `NotFound` is counted as "already+//! gone" so concurrent clearers don't fight each other.++use std::fs;+use std::path::{Path, PathBuf};+use std::time::SystemTime;++use serde::{Serialize, de::DeserializeOwned};++use crate::git::Repository;++/// The root directory for a named cache kind.+///+/// Returns `<git-common-dir>/wt/cache/<kind>/`. All worktrunk caches live+/// here; the `kind` is the subdirectory name (e.g. `"ci-status"`,+/// `"summary"`, `"is-ancestor"`).+pub fn cache_dir(repo: &Repository, kind: &str) -> PathBuf {+ repo.wt_dir().join("cache").join(kind)+}++/// Read and deserialize a JSON cache entry.+///+/// Returns `None` on any failure. Corrupt JSON is logged at debug — a torn+/// write is indistinguishable from a cache miss at this layer.+pub fn read_json<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!("cache: corrupt entry at {}: {}", path.display(), e);+ None+ }+ }+}++/// Serialize and write a JSON cache entry, creating parent directories as+/// needed.+///+/// Degrades silently on any failure — parent dir creation, serialization,+/// or the write itself. A failed write just means the next access+/// re-computes; callers must never observe the error.+pub fn write_json<T: Serialize>(path: &Path, value: &T) {+ if let Some(parent) = path.parent()+ && let Err(e) = fs::create_dir_all(parent)+ {+ log::debug!("cache: failed to create dir {}: {}", parent.display(), e);+ return;+ }++ let Ok(json) = serde_json::to_string(value) else {+ log::debug!("cache: failed to serialize entry for {}", path.display());+ return;+ };++ if let Err(e) = fs::write(path, &json) {+ log::debug!("cache: failed to write {}: {}", path.display(), e);+ }+}++/// Read a JSON entry at `<wt-cache>/<kind>/<key>`.+///+/// Paired with [`write_with_lru`] for the flat-dir "kind + key filename"+/// layout. Returns `None` on any failure (missing file, I/O error, corrupt+/// JSON).+pub fn read<T: DeserializeOwned>(repo: &Repository, kind: &str, key: &str) -> Option<T> {+ read_json(&cache_dir(repo, kind).join(key))+}++/// Write a JSON entry at `<wt-cache>/<kind>/<key>`, then sweep the kind+/// directory so it holds at most `max_entries` top-level `.json` files.+///+/// Combines [`write_json`] with [`sweep_lru`] — the "write + bound" pattern+/// every `sha_cache` `put_*` function repeats. Degrades silently on write+/// failure; the sweep runs regardless so a torn write still triggers the+/// size bound check.+pub fn write_with_lru<T: Serialize>(+ repo: &Repository,+ kind: &str,+ key: &str,+ value: &T,+ max_entries: usize,+) {+ let dir = cache_dir(repo, kind);+ write_json(&dir.join(key), value);+ sweep_lru(&dir, max_entries);+}++/// Enforce a size bound on `dir`. If it holds more than `max` top-level+/// `.json` entries, delete the oldest-mtime files until the count is back+/// at `max`.+///+/// The fast path is a single directory listing and `count_json_files` — no+/// per-file `stat` when the cache is under the bound. Only falls through+/// to stat+sort when trimming is actually needed.+///+/// Best-effort: I/O errors during the sweep are logged at debug and ignored+/// because the cache is always an optimization over re-computation.+pub fn sweep_lru(dir: &Path, max: usize) {+ if count_json_files(dir) <= max {+ return;+ }++ let Ok(entries) = fs::read_dir(dir) else {+ return;+ };+ 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;+ }++ 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!("cache: swept {} entries from {}", excess, dir.display());+}++/// Remove a single cache entry.+///+/// Returns `Ok(true)` if a file was removed, `Ok(false)` if it was already+/// gone (a concurrent clearer, or the caller being paranoid). Propagates+/// other I/O errors with the path attached, so `wt config state clear`+/// reports "Cleared"/"No cache" truthfully instead of swallowing a+/// permission-denied failure.+pub fn clear_one(path: &Path) -> anyhow::Result<bool> {+ match fs::remove_file(path) {+ Ok(()) => Ok(true),+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),+ Err(e) => {+ Err(anyhow::Error::new(e).context(format!("failed to remove {}", path.display())))+ }+ }+}++/// Remove every top-level `.json` file in `dir`, returning the count+/// removed.+///+/// Missing directory is `Ok(0)` — the caller's cache is already empty.+/// Concurrent removal of individual entries is counted as "already gone".+/// Non-`.json` siblings (e.g. leftover `.json.tmp` from old code, or a+/// stray `README`) are left in place.+pub fn clear_json_files(dir: &Path) -> anyhow::Result<usize> {+ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),+ Err(e) => {+ return Err(anyhow::Error::new(e).context(format!("failed to read {}", dir.display())));+ }+ };++ let mut cleared = 0;+ for entry in entries.flatten() {+ let path = entry.path();+ if path.extension().is_none_or(|ext| ext != "json") {+ continue;+ }+ if clear_one(&path)? {+ cleared += 1;+ }+ }+ Ok(cleared)+}++/// Count top-level `.json` files in `dir`, returning `0` when the directory+/// is missing. Used by `wt config state get` for the `get ↔ clear` parity+/// view.+pub fn count_json_files(dir: &Path) -> usize {+ let Ok(entries) = fs::read_dir(dir) else {+ return 0;+ };+ entries+ .flatten()+ .filter(|e| e.path().extension().is_some_and(|ext| ext == "json"))+ .count()+}++#[cfg(test)]+mod tests {+ use super::*;+ use tempfile::TempDir;++ #[derive(serde::Serialize, serde::Deserialize, PartialEq, Debug)]+ struct V {+ x: u32,+ }++ #[test]+ fn test_read_write_roundtrip() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("sub/entry.json");++ // Missing file is a miss.+ assert!(read_json::<V>(&path).is_none());++ // Write creates parent dirs and round-trips.+ write_json(&path, &V { x: 42 });+ assert_eq!(read_json::<V>(&path), Some(V { x: 42 }));+ }++ #[test]+ fn test_read_corrupt_json_returns_none() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("bad.json");+ fs::write(&path, "not json {{").unwrap();+ assert!(read_json::<V>(&path).is_none());+ }++ #[test]+ fn test_clear_one_missing_returns_false() {+ let tmp = TempDir::new().unwrap();+ let path = tmp.path().join("nope.json");+ assert!(!clear_one(&path).unwrap());+ }++ #[test]+ fn test_clear_one_propagates_non_not_found() {+ let tmp = TempDir::new().unwrap();+ // Put a directory where a file is expected so remove_file returns+ // EISDIR (or similar), not NotFound.+ let path = tmp.path().join("dir.json");+ fs::create_dir(&path).unwrap();+ let err = clear_one(&path).unwrap_err();+ assert!(err.to_string().contains("failed to remove"), "got: {err}");+ }++ #[test]+ fn test_clear_json_files_counts_and_skips() {+ let tmp = TempDir::new().unwrap();+ let dir = tmp.path().join("c");+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("a.json"), "{}").unwrap();+ fs::write(dir.join("b.json"), "{}").unwrap();+ // Non-.json siblings must be skipped and left in place.+ fs::write(dir.join("README"), "stray").unwrap();+ fs::write(dir.join("a.json.tmp"), "leftover").unwrap();++ assert_eq!(clear_json_files(&dir).unwrap(), 2);+ assert!(!dir.join("a.json").exists());+ assert!(!dir.join("b.json").exists());+ assert!(dir.join("README").exists());+ assert!(dir.join("a.json.tmp").exists());+ }++ #[test]+ fn test_clear_json_files_missing_dir_is_zero() {+ let tmp = TempDir::new().unwrap();+ assert_eq!(clear_json_files(&tmp.path().join("nope")).unwrap(), 0);+ }++ #[test]+ fn test_clear_json_files_propagates_read_dir_error() {+ let tmp = TempDir::new().unwrap();+ // Put a file where a directory is expected — read_dir returns+ // NotADirectory (not NotFound).+ let path = tmp.path().join("not-a-dir");+ fs::write(&path, "file").unwrap();+ let err = clear_json_files(&path).unwrap_err();+ assert!(err.to_string().contains("failed to read"), "got: {err}");+ }++ #[test]+ fn test_count_json_files() {+ let tmp = TempDir::new().unwrap();+ let dir = tmp.path().join("c");+ fs::create_dir_all(&dir).unwrap();+ fs::write(dir.join("a.json"), "{}").unwrap();+ fs::write(dir.join("README"), "stray").unwrap();++ assert_eq!(count_json_files(&dir), 1);+ assert_eq!(count_json_files(&tmp.path().join("nope")), 0);+ }++ #[test]+ fn test_sweep_lru_trims_oldest_entries() {+ let tmp = TempDir::new().unwrap();+ let dir = tmp.path().join("c");+ fs::create_dir_all(&dir).unwrap();++ for i in 0..5 {+ fs::write(dir.join(format!("entry{i}.json")), "true").unwrap();+ 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();+ assert_eq!(remaining, ["entry2.json", "entry3.json", "entry4.json"]);+ }++ #[test]+ fn test_sweep_lru_no_op_under_bound() {+ let tmp = TempDir::new().unwrap();+ let dir = tmp.path().join("c");+ 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");+ }+}diff --git a/src/cache_dir.rs b/src/cache_dir.rsdeleted file mode 100644index f56136476..000000000--- a/src/cache_dir.rs+++ /dev/null@@ -1,119 +0,0 @@-//! Shared helpers for the `.git/wt/cache/` subdirectories.-//!-//! Worktrunk keeps several disk-backed caches under `.git/wt/cache/`:-//! `ci-status/<branch>.json` and `{kind}/<sha-pair>.json` for `sha_cache`-//! kinds. Their user-initiated clear semantics coincide: enumerate-//! `.json` files, delete them, tolerate missing dirs and concurrent-//! removal as success, surface other I/O errors so `wt config state-//! clear` cannot report a count it didn't actually achieve.--use std::fs;-use std::path::Path;--use anyhow::{Context, Result};--/// Delete all `.json` files directly inside `dir`, returning the count.-///-/// - Missing `dir` is `Ok(0)` (cache never populated).-/// - A per-file `NotFound` is skipped (another process cleared it-/// between listing and removal).-/// - Any other I/O error — `read_dir`, per-entry iteration, or-/// `remove_file` — is returned with the relevant path in context.-///-/// Only entries with exactly the `.json` extension are removed;-/// siblings like `.json.tmp` or `README` survive.-pub fn clear_json_files_in(dir: &Path) -> Result<usize> {- let entries = match fs::read_dir(dir) {- Ok(entries) => entries,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),- Err(e) => {- return Err(anyhow::Error::new(e).context(format!("failed to read {}", dir.display())));- }- };- let mut cleared = 0;- for entry in entries {- let entry = entry.with_context(|| format!("failed to read entry in {}", dir.display()))?;- let path = entry.path();- if path.extension().is_none_or(|ext| ext != "json") {- continue;- }- match fs::remove_file(&path) {- Ok(()) => cleared += 1,- Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue,- Err(e) => {- return Err(- anyhow::Error::new(e).context(format!("failed to remove {}", path.display()))- );- }- }- }- Ok(cleared)-}--#[cfg(test)]-mod tests {- use super::*;- use crate::testing::TestRepo;-- #[test]- fn test_missing_dir_returns_zero() {- let test = TestRepo::with_initial_commit();- let missing = test.root_path().join("never-existed");-- assert_eq!(clear_json_files_in(&missing).unwrap(), 0);- }-- #[test]- fn test_propagates_non_not_found_read_dir_error() {- let test = TestRepo::with_initial_commit();- // Regular file where a directory is expected → ENOTDIR.- let path = test.root_path().join("not-a-dir");- fs::write(&path, "stray").unwrap();-- let err = clear_json_files_in(&path).unwrap_err();- assert!(- err.to_string().contains("failed to read"),- "expected read-failure context, got: {err}"- );- }-- #[test]- fn test_propagates_per_file_remove_error() {- let test = TestRepo::with_initial_commit();- let dir = test.root_path().join("cache");- fs::create_dir(&dir).unwrap();- // A directory named `*.json` makes remove_file return EISDIR.- fs::create_dir(dir.join("bad.json")).unwrap();-- let err = clear_json_files_in(&dir).unwrap_err();- assert!(- err.to_string().contains("failed to remove"),- "expected remove-failure context, got: {err}"- );- }-- #[test]- fn test_skips_non_json_extensions() {- let test = TestRepo::with_initial_commit();- let dir = test.root_path().join("cache");- fs::create_dir(&dir).unwrap();- fs::write(dir.join("a.json"), "{}").unwrap();- fs::write(dir.join("a.json.tmp"), "leftover").unwrap();- fs::write(dir.join("README"), "stray").unwrap();-- let count = clear_json_files_in(&dir).unwrap();- assert_eq!(count, 1);- assert!(!dir.join("a.json").exists());- assert!(dir.join("a.json.tmp").exists());- assert!(dir.join("README").exists());- }-- #[test]- fn test_empty_dir_returns_zero() {- let test = TestRepo::with_initial_commit();- let dir = test.root_path().join("cache");- fs::create_dir(&dir).unwrap();-- assert_eq!(clear_json_files_in(&dir).unwrap(), 0);- }-}diff --git a/src/cli/config.rs b/src/cli/config.rsindex aab9c749a..13a3af601 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -604,6 +604,7 @@ pub enum StateCommand {- **Branch markers**: User-defined branch notes- **Vars**: Custom variables per branch- **CI status**: Cached GitHub/GitLab CI status per branch (30s TTL)+- **Summaries**: Cached LLM-generated branch summaries (shown in `wt list --full` and `wt switch` preview)- **Git commands cache**: SHA-keyed merge-tree, ancestry, and diff-stats results- **Hints**: One-time hints that have been shown- **Log files**: Operation and debug logs@@ -625,7 +626,7 @@ CI cache entries show status, age, and the commit SHA they were fetched for."#)]- Previous branch- All branch markers- All variables-- All caches (CI status, git commands)+- All caches (CI status, summaries, 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 069f2cd88..b8e3dc035 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -17,6 +17,7 @@//! - Branch markers (git config `worktrunk.state.<branch>.marker`)//! - Vars (git config `worktrunk.state.<branch>.vars.*`)//! - CI status cache (`.git/wt/cache/ci-status/`)+//! - Summary cache (`.git/wt/cache/summary/`)//! - Git commands cache (`.git/wt/cache/{merge-tree-conflicts,is-ancestor,…}/`)//! - Hints (git config `worktrunk.hints.*`)//! - Logs (`.git/wt/logs/`)@@ -43,7 +44,7 @@ use anyhow::Context;use color_print::cformat;use path_slash::PathExt as _;use worktrunk::config::config_path;-use worktrunk::git::{BranchRef, Repository};+use worktrunk::git::{BranchRef, Repository, sha_cache};use worktrunk::path::format_path_for_display;use worktrunk::styling::{eprintln, format_heading, format_with_gutter, info_message, println, success_message,@@ -56,6 +57,7 @@ use worktrunk::utils::epoch_now;use super::super::list::ci_status::{CachedCiStatus, CiBranchName};use crate::display::format_relative_time_short;use crate::help_pager::show_help_in_pager;+use crate::summary::CachedSummary;// ==================== Path Helpers ====================@@ -77,6 +79,20 @@ fn is_diagnostic_file(name: &str) -> bool {DIAGNOSTIC_FILES.contains(&name)}+/// Truncate a string for a display cell, counting by Unicode scalars.+///+/// Returns a shortened copy ending in `"..."` when the input exceeds+/// `max_chars` scalars, otherwise the input verbatim. Byte-slicing+/// (`&s[..n]`) panics on a multi-byte boundary — this helper is safe+/// for any UTF-8 string.+fn truncate_display(s: &str, max_chars: usize) -> String {+ if s.chars().count() <= max_chars {+ return s.to_string();+ }+ let truncated: String = s.chars().take(max_chars.saturating_sub(3)).collect();+ format!("{truncated}...")+}+/// Check if a top-level file belongs to the command audit log (`.jsonl` / `.jsonl.old`).fn is_command_log_file(name: &str) -> bool {name.ends_with(".jsonl") || name.ends_with(".jsonl.old")@@ -936,8 +952,21 @@ pub fn handle_state_clear_all() -> anyhow::Result<()> {cleared_any = true;}+ // Clear all summary cache entries+ let summary_cleared = CachedSummary::clear_all(&repo)?;+ if summary_cleared > 0 {+ eprintln!(+ "{}",+ success_message(cformat!(+ "Cleared <bold>{summary_cleared}</> summary cache entr{}",+ if summary_cleared == 1 { "y" } else { "ies" }+ ))+ );+ cleared_any = true;+ }+// Clear git commands cache (merge-tree, ancestry, diff results)- let sha_cleared = repo.clear_git_commands_cache()?;+ let sha_cleared = sha_cache::clear_all(&repo)?;if sha_cleared > 0 {eprintln!("{}",@@ -1040,22 +1069,16 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {}).collect();- // Get CI status cache- let mut ci_entries = CachedCiStatus::list_all(repo);- ci_entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });- let ci_status: Vec<serde_json::Value> = ci_entries+ // Get CI status cache (pre-sorted newest-first)+ let ci_status: Vec<serde_json::Value> = CachedCiStatus::list_all(repo).into_iter()- .map(|(branch, cached)| {+ .map(|cached| {let status = cached.status.as_ref().map(|s| -> &'static str { s.ci_status.into() });serde_json::json!({- "branch": branch,+ "branch": cached.branch,"status": status,"checked_at": cached.checked_at,"head": cached.head@@ -1063,6 +1086,18 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {}).collect();+ // Get summary cache (freshest entry per branch, pre-sorted newest-first)+ let summaries: Vec<serde_json::Value> = CachedSummary::list_all(repo)+ .into_iter()+ .map(|cached| {+ serde_json::json!({+ "branch": cached.branch,+ "summary": cached.summary,+ "generated_at": cached.generated_at,+ })+ })+ .collect();+let (command_log, hook_output, diagnostic) = partition_log_files_json(repo)?;// Get vars data (all branches) — collect into BTreeMap for sorted output@@ -1106,7 +1141,8 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {"previous_branch": previous_branch,"markers": markers,"ci_status": ci_status,- "git_commands_cache": repo.git_commands_cache_count(),+ "summaries": summaries,+ "git_commands_cache": sha_cache::count_all(repo),"vars": vars_data,"command_log": command_log,"hook_output": hook_output,@@ -1169,13 +1205,11 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {let mut rows: Vec<Vec<String>> = Vec::new();for (branch, entries) in &all_vars {for (key, value) in entries {- // Truncate long values for display- let display_value = if value.len() > 40 {- format!("{}...", &value[..37])- } else {- value.to_string()- };- rows.push(vec![branch.to_string(), key.to_string(), display_value]);+ rows.push(vec![+ branch.to_string(),+ key.to_string(),+ truncate_display(value, 40),+ ]);}}let rendered = crate::md_help::render_data_table(headers, &rows);@@ -1183,21 +1217,15 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {}writeln!(out)?;- // Show CI status cache+ // Show CI status cache (pre-sorted newest-first)writeln!(out, "{}", format_heading("CI STATUS CACHE", None))?;- let mut entries = CachedCiStatus::list_all(repo);- // Sort by age (most recent first), then by branch name for ties- entries.sort_by(|a, b| {- b.1.checked_at- .cmp(&a.1.checked_at)- .then_with(|| a.0.cmp(&b.0))- });+ let entries = CachedCiStatus::list_all(repo);if entries.is_empty() {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {let rows: Vec<Vec<String>> = entries.iter()- .map(|(branch, cached)| {+ .map(|cached| {let status = match &cached.status {Some(pr_status) => {let s: &'static str = pr_status.ci_status.into();@@ -1207,7 +1235,7 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {};let age = format_relative_time_short(cached.checked_at as i64);let head: String = cached.head.chars().take(8).collect();- vec![branch.clone(), status, age, head]+ vec![cached.branch.clone(), status, age, head]}).collect();let rendered =@@ -1216,9 +1244,28 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {}writeln!(out)?;+ // Show summary cache (LLM summaries keyed by branch + diff hash, pre-sorted newest-first)+ writeln!(out, "{}", format_heading("SUMMARY CACHE", None))?;+ let summary_entries = CachedSummary::list_all(repo);+ if summary_entries.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ let rows: Vec<Vec<String>> = summary_entries+ .iter()+ .map(|cached| {+ let subject = cached.summary.lines().next().unwrap_or("").trim();+ let age = format_relative_time_short(cached.generated_at as i64);+ vec![cached.branch.clone(), truncate_display(subject, 40), age]+ })+ .collect();+ let rendered = crate::md_help::render_data_table(&["Branch", "Summary", "Age"], &rows);+ writeln!(out, "{}", rendered.trim_end())?;+ }+ writeln!(out)?;+// Show git commands cache summarywriteln!(out, "{}", format_heading("GIT COMMANDS CACHE", None))?;- let sha_count = repo.git_commands_cache_count();+ let sha_count = sha_cache::count_all(repo);if sha_count == 0 {writeln!(out, "{}", format_with_gutter("(none)", None))?;} else {diff --git a/src/commands/list/ci_status/cache.rs b/src/commands/list/ci_status/cache.rsindex e0be43e48..7d790e7af 100644--- a/src/commands/list/ci_status/cache.rs+++ b/src/commands/list/ci_status/cache.rs@@ -1,28 +1,31 @@//! CI status caching.//!//! Caches CI status in `.git/wt/cache/ci-status/<branch>.json` to avoid-//! hitting API rate limits.+//! hitting API rate limits. Built on the shared `worktrunk::cache`+//! primitives for read/write/clear mechanics.use std::collections::hash_map::DefaultHasher;-use std::fs;use std::hash::{Hash, Hasher};use std::path::{Path, PathBuf};use serde::{Deserialize, Serialize};-use worktrunk::cache_dir::clear_json_files_in;+use worktrunk::cache;use worktrunk::git::Repository;use worktrunk::path::sanitize_for_filename;use super::PrStatus;-/// Cached CI status stored in `.git/wt/cache/ci-status/<branch>.json`+/// Subdirectory of `.git/wt/cache/` holding cached CI statuses.+const KIND: &str = "ci-status";++/// Cached CI status stored in `.git/wt/cache/ci-status/<branch>.json`.///-/// Uses file-based caching instead of git config to avoid file locking issues.-/// On Windows, concurrent `git config` writes can temporarily lock `.git/config`,-/// causing other git operations to fail with "Permission denied".+/// Uses file-based caching instead of git config to avoid file locking+/// issues on Windows where concurrent `git config` writes can lock+/// `.git/config` and cause other git operations to fail.///-/// Note: Old cache entries without the `branch` field will fail deserialization-/// and be treated as cache misses — they will be re-fetched with the new format.+/// Old cache entries without the `branch` field fail deserialization and+/// are treated as cache misses — they get re-fetched with the new format.#[derive(Debug, Clone, Serialize, Deserialize)]pub(crate) struct CachedCiStatus {/// The cached CI status (None means no CI found for this branch)@@ -48,12 +51,12 @@ impl CachedCiStatus {/// Different directories get different TTLs [30, 60) seconds, which spreads/// out cache expirations when multiple statuslines run concurrently.pub(crate) fn ttl_for_repo(repo_root: &Path) -> u64 {+ // `DefaultHasher` is fine here — the output is ephemeral (used only+ // to pick a TTL for this process), never persisted.let mut hasher = DefaultHasher::new();- // Hash the path bytes directly for consistent TTL across string representationsrepo_root.as_os_str().hash(&mut hasher);let hash = hasher.finish();- // Map hash to jitter range [0, TTL_JITTER_SECS)let jitter = hash % Self::TTL_JITTER_SECS;Self::TTL_BASE_SECS + jitter}@@ -69,158 +72,75 @@ impl CachedCiStatus {/// Get the cache directory path: `.git/wt/cache/ci-status/`fn cache_dir(repo: &Repository) -> PathBuf {- repo.wt_dir().join("cache").join("ci-status")+ cache::cache_dir(repo, KIND)}/// Get the cache file path for a branch.fn cache_file(repo: &Repository, branch: &str) -> PathBuf {- let dir = Self::cache_dir(repo);let safe_branch = sanitize_for_filename(branch);- dir.join(format!("{safe_branch}.json"))+ Self::cache_dir(repo).join(format!("{safe_branch}.json"))}/// Read cached CI status from file.pub(super) fn read(repo: &Repository, branch: &str) -> Option<Self> {- let path = Self::cache_file(repo, branch);- let json = fs::read_to_string(&path).ok()?;- serde_json::from_str(&json).ok()+ cache::read_json(&Self::cache_file(repo, branch))}/// Write CI status to cache file.///- /// Uses atomic write (write to temp file, then rename) to avoid corruption- /// and minimize lock contention on Windows.+ /// A torn write under a concurrent reader produces unparsable bytes+ /// at the expected path, which `read()` treats as a miss — the next+ /// read just re-fetches. See `worktrunk::cache` for the shared+ /// torn-write semantics.pub(super) fn write(&self, repo: &Repository, branch: &str) {- let path = Self::cache_file(repo, branch);-- // Create cache directory if needed- if let Some(parent) = path.parent()- && let Err(e) = fs::create_dir_all(parent)- {- log::debug!("Failed to create cache dir for {}: {}", branch, e);- return;- }-- let Ok(json) = serde_json::to_string(self) else {- log::debug!("Failed to serialize CI cache for {}", branch);- return;- };-- // Write to temp file first, then rename for atomic update- let temp_path = path.with_extension("json.tmp");- if let Err(e) = fs::write(&temp_path, &json) {- log::debug!("Failed to write CI cache temp file for {}: {}", branch, e);- return;- }-- // On Windows, fs::rename may fail if target exists (depending on Windows version- // and filesystem). Remove target first to ensure rename succeeds.- #[cfg(windows)]- let _ = fs::remove_file(&path);-- if let Err(e) = fs::rename(&temp_path, &path) {- log::debug!("Failed to rename CI cache file for {}: {}", branch, e);- // Clean up temp file on failure- let _ = fs::remove_file(&temp_path);- }+ cache::write_json(&Self::cache_file(repo, branch), self);}- /// List all cached CI statuses as (branch_name, cached_status) pairs.- pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {- let cache_dir = Self::cache_dir(repo);-- let entries = match fs::read_dir(&cache_dir) {- Ok(entries) => entries,- Err(_) => return Vec::new(),+ /// List all cached CI statuses, newest first with branch-name tiebreak.+ pub(crate) fn list_all(repo: &Repository) -> Vec<Self> {+ let dir = Self::cache_dir(repo);+ let Ok(entries) = std::fs::read_dir(&dir) else {+ return Vec::new();};- entries+ let mut out: Vec<Self> = entries.filter_map(|entry| {- let entry = entry.ok()?;- let path = entry.path();-- // Only process .json files (skip .json.tmp)+ let path = entry.ok()?.path();if path.extension()?.to_str()? != "json" {return None;}-- let json = fs::read_to_string(&path).ok()?;- let cached: Self = serde_json::from_str(&json).ok()?;- Some((cached.branch.clone(), cached))+ cache::read_json(&path)})- .collect()- }-- /// Remove a cache file at `path`.- ///- /// Returns `Ok(true)` if the file existed and was removed, `Ok(false)`- /// if it was already gone (either never existed, or another process- /// deleted it concurrently). Propagates other I/O errors with the- /// path in context. Shared by `clear_one` and `clear_all`.- fn remove_cache_file(path: &Path) -> anyhow::Result<bool> {- match fs::remove_file(path) {- Ok(()) => Ok(true),- Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(false),- Err(e) => {- Err(anyhow::Error::new(e).context(format!("failed to remove {}", path.display())))- }- }+ .collect();+ out.sort_by(|a, b| {+ b.checked_at+ .cmp(&a.checked_at)+ .then_with(|| a.branch.cmp(&b.branch))+ });+ out}/// Clear the cached CI status for a single branch.///- /// Returns `Ok(true)` if a cache file was removed, `Ok(false)` if none- /// existed (including the concurrent-removal case — another process- /// deleted the file between the caller deciding to clear and this call).- /// Propagates other I/O errors (permission denied, etc.) — since the- /// caller reports "Cleared"/"No cache" directly to the user, a silent- /// swallow would lie when the file exists but we can't delete it.+ /// Returns `Ok(true)` if a cache file was removed, `Ok(false)` if+ /// none existed. Propagates non-`NotFound` I/O errors so the caller+ /// can report truthfully to the user.pub(crate) fn clear_one(repo: &Repository, branch: &str) -> anyhow::Result<bool> {- Self::remove_cache_file(&Self::cache_file(repo, branch))+ cache::clear_one(&Self::cache_file(repo, branch))}- /// Clear all cached CI statuses, returns count cleared.+ /// Clear all cached CI statuses, returning the count cleared.///- /// Delegates to [`clear_json_files_in`], which documents the+ /// Delegates to [`cache::clear_json_files`], which documents the/// missing-dir / concurrent-removal / error-propagation semantics.pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {- clear_json_files_in(&Self::cache_dir(repo))+ cache::clear_json_files(&Self::cache_dir(repo))}}#[cfg(test)]mod tests {use super::*;- use worktrunk::testing::TestRepo;-- #[test]- fn test_remove_cache_file_returns_false_when_missing() {- // The concurrent-removal path for clear_all (another process deletes- // a cache file between listing and remove_file) routes through this- // helper, which reports the missing file as Ok(false) rather than- // erroring.- let test = TestRepo::with_initial_commit();- let missing = test.root_path().join("never-existed.json");-- assert!(!CachedCiStatus::remove_cache_file(&missing).unwrap());- }-- #[test]- fn test_clear_one_propagates_non_not_found_error() {- let test = TestRepo::with_initial_commit();- let repo = Repository::at(test.root_path()).unwrap();-- // Place a directory where the .json cache file should live so- // remove_file returns a non-NotFound error (EISDIR / similar).- let path = CachedCiStatus::cache_file(&repo, "feature");- fs::create_dir_all(&path).unwrap();-- let err = CachedCiStatus::clear_one(&repo, "feature").unwrap_err();- assert!(- err.to_string().contains("failed to remove"),- "expected remove-failure context, got: {err}"- );- }#[test]fn test_ttl_jitter_range_and_determinism() {diff --git a/src/commands/list/collect/mod.rs b/src/commands/list/collect/mod.rsindex f606cccf5..5d913bae9 100644--- a/src/commands/list/collect/mod.rs+++ b/src/commands/list/collect/mod.rs@@ -139,7 +139,10 @@//! ## Caching//!//! Sibling caches live under `.git/wt/cache/`. Each uses a different key scheme because-//! the underlying operations differ in what their output depends on.+//! the underlying operations differ in what their output depends on. All three share+//! [`worktrunk::cache`] for the filesystem mechanics (read, write, clear, count) so+//! there's one implementation of the torn-write semantics and error policy across+//! every kind.//!//! | Directory | Module | Key | Staleness |//! |-----------|--------|-----|-----------|@@ -149,7 +152,7 @@//! | `has-added-changes/` | `git::repository::sha_cache` | `{branch_sha}-{target_sha}.json` | Never — content-addressed |//! | `diff-stats/` | `git::repository::sha_cache` | `{base_sha}-{head_sha}.json` | Never — content-addressed |//! | `ci-status/` | `commands::list::ci_status::cache` | `{branch}.json` | TTL 30–60s + HEAD SHA check |-//! | `summaries/` | `summary` | `{branch}.json` | `diff_hash` mismatch |+//! | `summary/{branch}/` | `summary` | `{diff_hash}.json` | Miss if no file exists for the current hash; siblings pruned on write |//!//! ### Key schemes//!@@ -158,8 +161,11 @@//! checks, file-change probes, diff stats).//! - **Branch + TTL + HEAD**: external mutable state (CI API, remote refs). TTL bounds//! staleness; the HEAD check invalidates early when the branch moves.-//! - **Branch + content hash**: deterministic function of a mutable input (e.g. an LLM call-//! over a diff). Invalidates on hash mismatch.+//! - **Branch + content-addressed hash in filename**: content hash (SHA-256+//! prefix of the combined diff) lives in the filename, so a cache hit is+//! "file exists for this hash". Prune-on-write removes stale sibling hashes+//! for the branch, keeping the cache bounded at ~1 entry per branch without+//! needing an LRU sweep.//!//! ### Which tasks hit which cache//!diff --git a/src/commands/picker/summary.rs b/src/commands/picker/summary.rsindex cd07d197e..1b3fdf9ec 100644--- a/src/commands/picker/summary.rs+++ b/src/commands/picker/summary.rs@@ -119,28 +119,58 @@ mod tests {}#[test]- fn test_cache_roundtrip() {- use crate::summary::{CachedSummary, read_cache, write_cache};+ fn test_cache_roundtrip_and_prune_on_write() {+ use crate::summary::CachedSummary;let (_t, repo) = temp_repo();let branch = "feature/test-branch";- let cached = CachedSummary {++ // Empty cache → read misses.+ assert!(CachedSummary::read(&repo, branch, "deadbeef").is_none());++ let first = CachedSummary {summary: "Add tests\n\nThis adds unit tests for cache.".to_string(),- diff_hash: 12345,branch: branch.to_string(),+ generated_at: 100,};+ first.write(&repo, "deadbeef");++ let loaded = CachedSummary::read(&repo, branch, "deadbeef").unwrap();+ assert_eq!(loaded.summary, first.summary);+ assert_eq!(loaded.branch, first.branch);+ assert_eq!(loaded.generated_at, first.generated_at);++ // Different hash for the same branch is a miss (content-addressed).+ assert!(CachedSummary::read(&repo, branch, "cafebabe").is_none());- assert!(read_cache(&repo, branch).is_none());+ // Writing a second hash for the same branch prunes the old one.+ let second = CachedSummary {+ summary: "Refactor tests".to_string(),+ branch: branch.to_string(),+ generated_at: 200,+ };+ second.write(&repo, "cafebabe");++ assert!(CachedSummary::read(&repo, branch, "deadbeef").is_none());+ assert_eq!(+ CachedSummary::read(&repo, branch, "cafebabe")+ .unwrap()+ .summary,+ "Refactor tests"+ );- write_cache(&repo, branch, &cached);- let loaded = read_cache(&repo, branch).unwrap();- assert_eq!(loaded.summary, cached.summary);- assert_eq!(loaded.diff_hash, cached.diff_hash);- assert_eq!(loaded.branch, cached.branch);+ let dir =+ CachedSummary::cache_root(&repo).join(worktrunk::path::sanitize_for_filename(branch));+ let remaining: Vec<_> = fs::read_dir(&dir)+ .unwrap()+ .filter_map(|e| e.ok())+ .map(|e| e.file_name().to_string_lossy().into_owned())+ .collect();+ assert_eq!(remaining, vec!["cafebabe.json"]);}#[test]- fn test_write_cache_handles_unwritable_path() {- use crate::summary::{CachedSummary, read_cache, write_cache};+ fn test_write_handles_unwritable_path() {+ use crate::summary::CachedSummary;let (_t, repo) = temp_repo();// Block cache directory creation by placing a file where the directory should belet wt_dir = repo.wt_dir();@@ -150,12 +180,12 @@ mod tests {let cached = CachedSummary {summary: "test".to_string(),- diff_hash: 1,branch: "main".to_string(),+ generated_at: 0,};// Should not panic — just logs and returns- write_cache(&repo, "main", &cached);- assert!(read_cache(&repo, "main").is_none());+ cached.write(&repo, "deadbeef");+ assert!(CachedSummary::read(&repo, "main", "deadbeef").is_none());// Cleanup: remove the blocker file so TempDir cleanup worksfs::remove_file(&cache_parent).unwrap();@@ -163,78 +193,175 @@ mod tests {#[cfg(unix)]#[test]- fn test_write_cache_handles_write_failure() {- use crate::summary::{CachedSummary, cache_dir, read_cache, write_cache};+ fn test_write_handles_write_failure() {+ use crate::summary::CachedSummary;use std::os::unix::fs::PermissionsExt;let (_t, repo) = temp_repo();- let cache_path = cache_dir(&repo);- fs::create_dir_all(&cache_path).unwrap();- // Make directory read-only so file writes fail- fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o444)).unwrap();+ // Pre-create the branch dir (which write() would otherwise create)+ // and make it read-only so the json write fails.+ let branch_dir = CachedSummary::cache_root(&repo).join("main");+ fs::create_dir_all(&branch_dir).unwrap();+ fs::set_permissions(&branch_dir, fs::Permissions::from_mode(0o444)).unwrap();let cached = CachedSummary {summary: "test".to_string(),- diff_hash: 1,branch: "main".to_string(),+ generated_at: 0,};// Should not panic — just logs and returns- write_cache(&repo, "main", &cached);- assert!(read_cache(&repo, "main").is_none());+ cached.write(&repo, "deadbeef");+ assert!(CachedSummary::read(&repo, "main", "deadbeef").is_none());// Restore permissions so TempDir cleanup works- fs::set_permissions(&cache_path, fs::Permissions::from_mode(0o755)).unwrap();+ fs::set_permissions(&branch_dir, fs::Permissions::from_mode(0o755)).unwrap();}#[test]- fn test_cache_invalidation_by_hash() {- use crate::summary::{CachedSummary, read_cache, write_cache};+ fn test_cache_file_uses_sanitized_branch() {+ use crate::summary::CachedSummary;+ let (_t, repo) = temp_repo();+ let path = CachedSummary::cache_file(&repo, "feature/my-branch", "abc123");+ // Branch dir is sanitized.+ let parent = path+ .parent()+ .unwrap()+ .file_name()+ .unwrap()+ .to_str()+ .unwrap();+ assert!(parent.starts_with("feature-my-branch-"));+ // Filename is the raw hash.+ assert_eq!(path.file_name().unwrap().to_str().unwrap(), "abc123.json");+ }++ #[test]+ fn test_cache_root_under_git() {+ use crate::summary::CachedSummary;+ let (_t, repo) = temp_repo();+ let dir = CachedSummary::cache_root(&repo);+ assert!(dir.to_str().unwrap().contains("wt"));+ assert!(dir.to_str().unwrap().contains("summary"));+ }++ #[test]+ fn test_list_all_returns_freshest_per_branch() {+ use crate::summary::CachedSummary;let (_t, repo) = temp_repo();- let branch = "main";- let cached = CachedSummary {- summary: "Old summary".to_string(),- diff_hash: 111,- branch: branch.to_string(),- };- write_cache(&repo, branch, &cached);- let loaded = read_cache(&repo, branch).unwrap();- assert_ne!(loaded.diff_hash, 222);+ CachedSummary {+ summary: "a".to_string(),+ branch: "feature-a".to_string(),+ generated_at: 100,+ }+ .write(&repo, "aaaa");+ CachedSummary {+ summary: "b".to_string(),+ branch: "feature-b".to_string(),+ generated_at: 200,+ }+ .write(&repo, "bbbb");++ let entries = CachedSummary::list_all(&repo);+ assert_eq!(entries.len(), 2);+ let mut branches: Vec<_> = entries.iter().map(|e| e.branch.clone()).collect();+ branches.sort();+ assert_eq!(branches, vec!["feature-a", "feature-b"]);}#[test]- fn test_cache_file_uses_sanitized_branch() {- use crate::summary::cache_file;+ fn test_clear_all() {+ use crate::summary::CachedSummary;let (_t, repo) = temp_repo();- let path = cache_file(&repo, "feature/my-branch");- let filename = path.file_name().unwrap().to_str().unwrap();- assert!(filename.starts_with("feature-my-branch-"));- assert!(filename.ends_with(".json"));++ // Empty cache: zero cleared, no error.+ assert_eq!(CachedSummary::clear_all(&repo).unwrap(), 0);++ CachedSummary {+ summary: "a".to_string(),+ branch: "feature-a".to_string(),+ generated_at: 0,+ }+ .write(&repo, "aaaa");+ CachedSummary {+ summary: "b".to_string(),+ branch: "feature-b".to_string(),+ generated_at: 0,+ }+ .write(&repo, "bbbb");++ assert_eq!(CachedSummary::clear_all(&repo).unwrap(), 2);+ assert!(CachedSummary::read(&repo, "feature-a", "aaaa").is_none());+ assert!(CachedSummary::read(&repo, "feature-b", "bbbb").is_none());}#[test]- fn test_cache_dir_under_git() {- use crate::summary::cache_dir;+ fn test_clear_all_propagates_non_not_found_read_dir_error() {+ use crate::summary::CachedSummary;let (_t, repo) = temp_repo();- let dir = cache_dir(&repo);- assert!(dir.to_str().unwrap().contains("wt"));- assert!(dir.to_str().unwrap().contains("summaries"));++ // Put a regular file where the summaries root is expected so+ // read_dir returns NotADirectory (non-NotFound).+ let root = CachedSummary::cache_root(&repo);+ fs::create_dir_all(root.parent().unwrap()).unwrap();+ fs::write(&root, "not a dir").unwrap();++ let err = CachedSummary::clear_all(&repo).unwrap_err();+ assert!(+ err.to_string().contains("failed to read"),+ "expected read-failure context, got: {err}"+ );}#[test]- fn test_hash_diff_deterministic() {- use crate::summary::hash_diff;- let hash1 = hash_diff("some diff content");- let hash2 = hash_diff("some diff content");- assert_eq!(hash1, hash2);+ fn test_clear_all_propagates_per_file_remove_error() {+ use crate::summary::CachedSummary;+ let (_t, repo) = temp_repo();++ // Real entry to make the branch dir exist.+ CachedSummary {+ summary: "a".to_string(),+ branch: "feature".to_string(),+ generated_at: 0,+ }+ .write(&repo, "aaaa");++ // Replace the json file with a directory named `bad.json` so+ // remove_file returns a non-NotFound error (EISDIR / similar).+ let branch_dir = CachedSummary::cache_root(&repo).join("feature");+ for entry in fs::read_dir(&branch_dir).unwrap().flatten() {+ fs::remove_file(entry.path()).unwrap();+ }+ fs::create_dir(branch_dir.join("bad.json")).unwrap();++ let err = CachedSummary::clear_all(&repo).unwrap_err();+ assert!(+ err.to_string().contains("failed to remove"),+ "expected remove-failure context, got: {err}"+ );}#[test]- fn test_hash_diff_different_inputs() {- use crate::summary::hash_diff;- let hash1 = hash_diff("diff A");- let hash2 = hash_diff("diff B");- assert_ne!(hash1, hash2);+ fn test_clear_all_skips_non_json_and_non_dir_entries() {+ use crate::summary::CachedSummary;+ let (_t, repo) = temp_repo();++ let root = CachedSummary::cache_root(&repo);+ fs::create_dir_all(&root).unwrap();+ // Real branch dir with one entry that should be counted.+ let branch_dir = root.join("feature");+ fs::create_dir_all(&branch_dir).unwrap();+ fs::write(branch_dir.join("aaaa.json"), "{}").unwrap();+ // Non-.json siblings inside the branch dir must be skipped.+ fs::write(branch_dir.join("README"), "stray").unwrap();+ // Stray file at the root (not a branch dir) must be skipped.+ fs::write(root.join("stray.txt"), "noise").unwrap();++ let count = CachedSummary::clear_all(&repo).unwrap();+ assert_eq!(count, 1, "only the .json inside a branch dir should count");+ assert!(!branch_dir.join("aaaa.json").exists());+ assert!(branch_dir.join("README").exists());+ assert!(root.join("stray.txt").exists());}#[test]diff --git a/src/git/mod.rs b/src/git/mod.rsindex 84a003cb9..a5514474e 100644--- a/src/git/mod.rs+++ b/src/git/mod.rs@@ -61,6 +61,7 @@ pub use remove::{BranchDeletionMode, BranchDeletionOutcome, BranchDeletionResult, RemovalOutput, RemoveOptions,delete_branch_if_safe, remove_worktree_with_cleanup, stage_worktree_removal,};+pub use repository::sha_cache;pub use repository::{Branch, Repository, ResolvedWorktree, WorkingTree, set_base_path};pub use url::GitRemoteUrl;pub use url::parse_owner_repo;diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 1cfb1e8cd..0d781a8f7 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -103,7 +103,7 @@ mod config;mod diff;mod integration;mod remotes;-mod sha_cache;+pub mod sha_cache;mod working_tree;mod worktrees;@@ -652,22 +652,6 @@ impl Repository {self.git_common_dir().join("wt")}- /// Clear all cached git command results, returning the count removed.- ///- /// Propagates I/O errors so the user-initiated clear path cannot lie- /// about success; see `sha_cache`'s module docs.- pub fn clear_git_commands_cache(&self) -> anyhow::Result<usize> {- sha_cache::clear_all(self)- }-- /// Count all cached git command results without clearing.- ///- /// Surfaces the same state that `clear_git_commands_cache` would sweep,- /// for the `wt config state get` parity view.- pub fn git_commands_cache_count(&self) -> usize {- sha_cache::count_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/sha_cache.rs b/src/git/repository/sha_cache.rsindex 1a111f2dc..dfc4f02cd 100644--- a/src/git/repository/sha_cache.rs+++ b/src/git/repository/sha_cache.rs@@ -1,57 +1,22 @@//! Persistent cache for SHA-keyed git command results.//!//! 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.+//! content-addressed SHAs — 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 per-kind LRU size bound to prevent unbounded growth.//!-//! # Layout-//!-//! One file per cached entry under `.git/wt/cache/{kind}/{key}.json`,-//! where `kind` identifies the operation (`merge-tree-conflicts`,-//! `merge-add-probe`, `is-ancestor`, `has-added-changes`, `diff-stats`)-//! and `key` is the SHA-pair filename. The sibling `ci-status/` and-//! `summaries/` caches use different key schemes; see-//! `commands::list::collect` for the cross-cutting design across all-//! `.git/wt/cache/` kinds.-//!-//! 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-//!-//! Read and write paths degrade silently — corrupt JSON, I/O errors, and-//! permission denied are logged at `debug` level; reads return `None`,-//! writes are no-ops. Callers must never observe cache failures there-//! because the cache is always an optimization over re-running git.-//!-//! The user-initiated clear path ([`clear_all`], reached via-//! `wt config state clear`) propagates I/O errors instead. A failed clear-//! that reports "cleared N entries" would be a lie to the user, mirroring-//! the same bug the ci-status file cache has already fixed.--use std::fs;-use std::path::{Path, PathBuf};-use std::time::SystemTime;--use serde::{Serialize, de::DeserializeOwned};+//! Layout: `.git/wt/cache/{kind}/{key}.json` where `kind` is one of+//! `merge-tree-conflicts`, `merge-add-probe`, `is-ancestor`,+//! `has-added-changes`, or `diff-stats`. Symmetric kinds sort the SHA pair+//! so `(A, B)` and `(B, A)` hit the same entry; asymmetric kinds preserve+//! ordering. See [`crate::cache`] for read/write/clear mechanics,+//! torn-write semantics, and the user-initiated clear error policy.use super::Repository;use super::integration::MergeProbeResult;-use crate::cache_dir::clear_json_files_in;+use crate::cache;use crate::git::LineDiff;/// Maximum cached entries per task kind before the LRU sweep removes the@@ -74,14 +39,6 @@ const ALL_KINDS: &[&str] = &[KIND_DIFF_STATS,];-/// 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 {@@ -96,113 +53,28 @@ 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!("sha_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!(- "sha_cache: failed to create dir {}: {}",- parent.display(),- e- );- return;- }-- let Ok(json) = serde_json::to_string(value) else {- log::debug!(- "sha_cache: failed to serialize entry for {}",- path.display()- );- return;- };-- if let Err(e) = fs::write(path, &json) {- log::debug!("sha_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!("sha_cache: swept {} entries from {}", excess, dir.display());-}--// ============================================================================-// Public API — merge-tree conflicts (symmetric)-// ============================================================================+// 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 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)+ cache::read(repo, KIND_MERGE_TREE_CONFLICTS, &symmetric_key(sha1, sha2))}/// 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);+ cache::write_with_lru(+ repo,+ KIND_MERGE_TREE_CONFLICTS,+ &symmetric_key(sha1, sha2),+ &value,+ MAX_ENTRIES_PER_KIND,+ );}-// ============================================================================-// Public API — merge-add probe (asymmetric)-// ============================================================================+// merge-add probe (asymmetric)/// Look up a cached `merge_integration_probe(branch, target)` result.///@@ -213,8 +85,11 @@ pub(super) fn merge_add_probe(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)+ cache::read(+ repo,+ KIND_MERGE_ADD_PROBE,+ &asymmetric_key(branch_sha, target_sha),+ )}/// Store a `merge_integration_probe(branch, target)` result, triggering@@ -225,35 +100,36 @@ pub(super) fn put_merge_add_probe(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);+ cache::write_with_lru(+ repo,+ KIND_MERGE_ADD_PROBE,+ &asymmetric_key(branch_sha, target_sha),+ &value,+ MAX_ENTRIES_PER_KIND,+ );}-// ============================================================================-// Public API — is-ancestor (asymmetric)-// ============================================================================+// is-ancestor (asymmetric)/// Look up a cached `is_ancestor(base_sha, head_sha)` result.////// Asymmetric: "is base ancestor of head?" differs from "is head ancestor of base?".pub(super) fn is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str) -> Option<bool> {- let path = cache_dir(repo, KIND_IS_ANCESTOR).join(asymmetric_key(base_sha, head_sha));- read::<bool>(&path)+ cache::read(repo, KIND_IS_ANCESTOR, &asymmetric_key(base_sha, head_sha))}/// Store an `is_ancestor(base_sha, head_sha)` result.pub(super) fn put_is_ancestor(repo: &Repository, base_sha: &str, head_sha: &str, value: bool) {- let dir = cache_dir(repo, KIND_IS_ANCESTOR);- let path = dir.join(asymmetric_key(base_sha, head_sha));- write(&path, &value);- sweep_lru(&dir, MAX_ENTRIES_PER_KIND);+ cache::write_with_lru(+ repo,+ KIND_IS_ANCESTOR,+ &asymmetric_key(base_sha, head_sha),+ &value,+ MAX_ENTRIES_PER_KIND,+ );}-// ============================================================================-// Public API — has-added-changes (asymmetric)-// ============================================================================+// has-added-changes (asymmetric)/// Look up a cached `has_added_changes(branch_sha, target_sha)` result.///@@ -263,8 +139,11 @@ pub(super) fn has_added_changes(branch_sha: &str,target_sha: &str,) -> Option<bool> {- let path = cache_dir(repo, KIND_HAS_ADDED_CHANGES).join(asymmetric_key(branch_sha, target_sha));- read::<bool>(&path)+ cache::read(+ repo,+ KIND_HAS_ADDED_CHANGES,+ &asymmetric_key(branch_sha, target_sha),+ )}/// Store a `has_added_changes(branch_sha, target_sha)` result.@@ -274,46 +153,44 @@ pub(super) fn put_has_added_changes(target_sha: &str,value: bool,) {- let dir = cache_dir(repo, KIND_HAS_ADDED_CHANGES);- let path = dir.join(asymmetric_key(branch_sha, target_sha));- write(&path, &value);- sweep_lru(&dir, MAX_ENTRIES_PER_KIND);+ cache::write_with_lru(+ repo,+ KIND_HAS_ADDED_CHANGES,+ &asymmetric_key(branch_sha, target_sha),+ &value,+ MAX_ENTRIES_PER_KIND,+ );}-// ============================================================================-// Public API — diff-stats (asymmetric)-// ============================================================================+// diff-stats (asymmetric)/// Look up cached `branch_diff_stats(base_sha, head_sha)` result.////// Asymmetric: diff from merge-base(base,head)..head is directional.pub(super) fn diff_stats(repo: &Repository, base_sha: &str, head_sha: &str) -> Option<LineDiff> {- let path = cache_dir(repo, KIND_DIFF_STATS).join(asymmetric_key(base_sha, head_sha));- read::<LineDiff>(&path)+ cache::read(repo, KIND_DIFF_STATS, &asymmetric_key(base_sha, head_sha))}/// Store a `branch_diff_stats(base_sha, head_sha)` result.pub(super) fn put_diff_stats(repo: &Repository, base_sha: &str, head_sha: &str, value: LineDiff) {- let dir = cache_dir(repo, KIND_DIFF_STATS);- let path = dir.join(asymmetric_key(base_sha, head_sha));- write(&path, &value);- sweep_lru(&dir, MAX_ENTRIES_PER_KIND);+ cache::write_with_lru(+ repo,+ KIND_DIFF_STATS,+ &asymmetric_key(base_sha, head_sha),+ &value,+ MAX_ENTRIES_PER_KIND,+ );}-// ============================================================================// Maintenance-// ============================================================================-/// Clear all cached SHA-keyed entries, returning the count removed.-///-/// Called by `wt config state clear`. Delegates the per-kind-directory-/// work to [`clear_json_files_in`], which documents the-/// missing-dir / concurrent-removal / error-propagation semantics that-/// the module-level "Failure handling" section enshrines.-pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {+/// Clear all cached SHA-keyed entries, returning the count removed. Called+/// by `wt config state clear`; see [`cache::clear_json_files`] for the+/// missing-dir / concurrent-removal / error-propagation semantics.+pub fn clear_all(repo: &Repository) -> anyhow::Result<usize> {let mut cleared = 0;for kind in ALL_KINDS {- cleared += clear_json_files_in(&cache_dir(repo, kind))?;+ cleared += cache::clear_json_files(&cache::cache_dir(repo, kind))?;}Ok(cleared)}@@ -322,24 +199,17 @@ pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {////// Called by `wt config state get` to surface the same state that/// `clear_all` would sweep, preserving get ↔ clear parity.-pub(crate) fn count_all(repo: &Repository) -> usize {- let mut count = 0;- for kind in ALL_KINDS {- let dir = cache_dir(repo, kind);- let Ok(entries) = fs::read_dir(&dir) else {- continue;- };- for entry in entries.flatten() {- if entry.path().extension().is_some_and(|ext| ext == "json") {- count += 1;- }- }- }- count+pub fn count_all(repo: &Repository) -> usize {+ ALL_KINDS+ .iter()+ .map(|kind| cache::count_json_files(&cache::cache_dir(repo, kind)))+ .sum()}#[cfg(test)]mod tests {+ use std::fs;+use super::*;use crate::testing::TestRepo;@@ -416,58 +286,13 @@ mod tests {put_merge_conflicts(&repo, "aaaa", "bbbb", true);- let path = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS).join(symmetric_key("aaaa", "bbbb"));+ let path =+ cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS).join(symmetric_key("aaaa", "bbbb"));fs::write(&path, "not valid json {{{").unwrap();assert_eq!(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]@@ -487,7 +312,7 @@ mod tests {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 dir = cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())@@ -526,7 +351,7 @@ mod tests {.unwrap();// Verify the cache entry uses the composite key- let dir = cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);+ let dir = cache::cache_dir(&repo, KIND_MERGE_TREE_CONFLICTS);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())@@ -635,7 +460,7 @@ mod tests {assert!(!real.would_merge_add);// Tamper with the cache to flip the answer- let dir = cache_dir(&repo, KIND_MERGE_ADD_PROBE);+ let dir = cache::cache_dir(&repo, KIND_MERGE_ADD_PROBE);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())@@ -721,7 +546,7 @@ mod tests {assert!(!repo.is_ancestor("feature", "main").unwrap());// Tamper with cache to flip the answer- let dir = cache_dir(&repo, KIND_IS_ANCESTOR);+ let dir = cache::cache_dir(&repo, KIND_IS_ANCESTOR);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())@@ -750,7 +575,7 @@ mod tests {assert!(repo.has_added_changes("feature", "main").unwrap());// Tamper with cache to flip the answer- let dir = cache_dir(&repo, KIND_HAS_ADDED_CHANGES);+ let dir = cache::cache_dir(&repo, KIND_HAS_ADDED_CHANGES);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())@@ -781,7 +606,7 @@ mod tests {assert_eq!(real.deleted, 0);// Tamper with cache to return different stats- let dir = cache_dir(&repo, KIND_DIFF_STATS);+ let dir = cache::cache_dir(&repo, KIND_DIFF_STATS);let entries: Vec<_> = fs::read_dir(&dir).unwrap().filter_map(|e| e.ok())diff --git a/src/lib.rs b/src/lib.rsindex 4455a1364..cfd1726f4 100644--- a/src/lib.rs+++ b/src/lib.rs@@ -7,7 +7,7 @@//! with worktrunk, please [open an issue](https://github.com/max-sixty/worktrunk/issues)//! to discuss your use case.-pub mod cache_dir;+pub mod cache;pub mod command_log;pub mod config;pub mod copy;diff --git a/src/summary.rs b/src/summary.rsindex d27fda9a3..286306088 100644--- a/src/summary.rs+++ b/src/summary.rs@@ -1,14 +1,31 @@//! Shared LLM summary generation for branches.//!//! Generates branch summaries using the configured LLM command, with caching-//! in `.git/wt/cache/summaries/`. Summaries are invalidated when the combined-//! diff (branch diff + working tree diff) changes.+//! in `.git/wt/cache/summary/{sanitized_branch}/{diff_hash}.json`. The+//! combined diff (branch diff + working tree diff) is hashed with SHA-256+//! and the hex-truncated digest becomes the filename — so a cache hit is+//! just "does the file exist?" rather than parsing JSON to compare a field.//!//! Used by both `wt list --full` (Summary column) and `wt switch` (preview tab).+//!+//! # Layout and invalidation+//!+//! Content-addressed filename: a successful write to `{hash}.json` means that+//! file holds the summary for that exact diff. No TTL, no separate staleness+//! check — see [`worktrunk::cache`] for the shared torn-write semantics.+//!+//! # Prune on write+//!+//! After a successful write, the branch directory is trimmed to one entry+//! via [`cache::sweep_lru`] with a cap of 1 — same mechanism `sha_cache`+//! uses, just at a per-branch directory with a size of one. The newest-mtime+//! file (the one we just wrote) survives; older hashes are dead weight.+//!+//! Best-effort: two concurrent writers for the same branch can briefly+//! leave two entries, and a sweep racing a just-written sibling can delete+//! it. Worst case is one extra LLM call on the next invocation.-use std::collections::hash_map::DefaultHasher;use std::fs;-use std::hash::{Hash, Hasher};use std::path::{Path, PathBuf};use std::sync::LazyLock;@@ -16,10 +33,13 @@ use anstyle::Reset;use color_print::cformat;use minijinja::Environment;use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use worktrunk::cache;use worktrunk::git::Repository;use worktrunk::path::sanitize_for_filename;use worktrunk::styling::INFO_SYMBOL;use worktrunk::sync::Semaphore;+use worktrunk::utils::epoch_now;use crate::llm::{execute_llm_command, prepare_diff};@@ -29,13 +49,24 @@ use crate::llm::{execute_llm_command, prepare_diff};/// `HEAVY_OPS_SEMAPHORE` (4) but still bounded.static LLM_SEMAPHORE: LazyLock<Semaphore> = LazyLock::new(|| Semaphore::new(8));-/// Cached summary stored in `.git/wt/cache/summaries/<branch>.json`-#[derive(Serialize, Deserialize)]+/// Subdirectory of `.git/wt/cache/` holding cached summaries.+const KIND: &str = "summary";++/// Cached summary stored in `.git/wt/cache/summary/{branch}/{hash}.json`.+///+/// The diff hash lives in the filename; the branch lives in the directory+/// name. The `branch` field holds the original (un-sanitized) branch name+/// so `list_all` can surface it for display without needing to reverse+/// `sanitize_for_filename`.+#[derive(Debug, Clone, Serialize, Deserialize)]pub(crate) struct CachedSummary {pub summary: String,- pub diff_hash: u64,- /// Original branch name (useful for humans inspecting cache files)+ /// Original branch name (for display in `wt config state get`).pub branch: String,+ /// Unix timestamp when the summary was generated. Used for the "Age"+ /// column in `wt config state get`. Mirrors `CachedCiStatus::checked_at`.+ #[serde(default)]+ pub generated_at: u64,}/// Combined diff output for a branch (branch diff + working tree diff)@@ -65,64 +96,124 @@ const SUMMARY_TEMPLATE: &str = r#"<task>Write a summary of this branch's changes</diff>"#;-/// Get the cache directory for summaries-pub(crate) fn cache_dir(repo: &Repository) -> PathBuf {- repo.wt_dir().join("cache").join("summaries")-}--/// Get the cache file path for a branch-pub(crate) fn cache_file(repo: &Repository, branch: &str) -> PathBuf {- let safe_branch = sanitize_for_filename(branch);- cache_dir(repo).join(format!("{safe_branch}.json"))-}+impl CachedSummary {+ /// Root of all summary cache entries: `.git/wt/cache/summary/`.+ pub(crate) fn cache_root(repo: &Repository) -> PathBuf {+ cache::cache_dir(repo, KIND)+ }-/// Read cached summary from file-pub(crate) fn read_cache(repo: &Repository, branch: &str) -> Option<CachedSummary> {- let path = cache_file(repo, branch);- let json = fs::read_to_string(&path).ok()?;- serde_json::from_str(&json).ok()-}+ /// Per-branch directory holding one file per cached diff hash.+ fn branch_dir(repo: &Repository, branch: &str) -> PathBuf {+ Self::cache_root(repo).join(sanitize_for_filename(branch))+ }-/// Write summary to cache file (atomic write via temp file + rename)-pub(crate) fn write_cache(repo: &Repository, branch: &str, cached: &CachedSummary) {- let path = cache_file(repo, branch);+ /// Full path for a specific (branch, hash) pair.+ pub(crate) fn cache_file(repo: &Repository, branch: &str, hash: &str) -> PathBuf {+ Self::branch_dir(repo, branch).join(format!("{hash}.json"))+ }- if let Some(parent) = path.parent()- && let Err(e) = fs::create_dir_all(parent)- {- log::debug!("Failed to create summary cache dir for {}: {}", branch, e);- return;+ /// Read the cached summary for a branch at a specific diff hash.+ /// See [`worktrunk::cache::read_json`] for the miss semantics.+ pub(crate) fn read(repo: &Repository, branch: &str, hash: &str) -> Option<Self> {+ cache::read_json(&Self::cache_file(repo, branch, hash))}- let Ok(json) = serde_json::to_string(cached) else {- log::debug!("Failed to serialize summary cache for {}", branch);- return;- };+ /// Write the summary at `{branch}/{hash}.json` and prune sibling hashes+ /// for the same branch. `hash` is the SHA-256 digest of the combined+ /// diff that produced this summary.+ pub(crate) fn write(&self, repo: &Repository, hash: &str) {+ cache::write_json(&Self::cache_file(repo, &self.branch, hash), self);+ cache::sweep_lru(&Self::branch_dir(repo, &self.branch), 1);+ }- let temp_path = path.with_extension("json.tmp");- if let Err(e) = fs::write(&temp_path, &json) {- log::debug!(- "Failed to write summary cache temp file for {}: {}",- branch,- e- );- return;+ /// List one cached summary per branch — the freshest by `generated_at`+ /// when multiple entries coexist transiently from concurrent writers.+ /// Returns newest-first with branch-name tiebreak.+ pub(crate) fn list_all(repo: &Repository) -> Vec<Self> {+ let root = Self::cache_root(repo);+ let Ok(branch_dirs) = fs::read_dir(&root) else {+ return Vec::new();+ };++ let mut out: Vec<Self> = branch_dirs+ .filter_map(|e| e.ok())+ .filter_map(|entry| {+ if !entry.file_type().ok()?.is_dir() {+ return None;+ }+ freshest_entry(&entry.path())+ })+ .collect();+ out.sort_by(|a, b| {+ b.generated_at+ .cmp(&a.generated_at)+ .then_with(|| a.branch.cmp(&b.branch))+ });+ out}- #[cfg(windows)]- let _ = fs::remove_file(&path);+ /// Clear all cached summaries, returning the count of `.json` entries removed.+ ///+ /// Summaries are two levels deep (`summary/{branch}/{hash}.json`), so+ /// iterate branch subdirs and delegate per-directory cleanup to+ /// [`cache::clear_json_files`]. Non-directory entries at the root are+ /// skipped. Empty branch dirs get best-effort rmdir so the tree stays+ /// tidy.+ pub(crate) fn clear_all(repo: &Repository) -> anyhow::Result<usize> {+ let root = Self::cache_root(repo);+ let branch_dirs = match fs::read_dir(&root) {+ Ok(entries) => entries,+ Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(0),+ Err(e) => {+ return Err(+ anyhow::Error::new(e).context(format!("failed to read {}", root.display()))+ );+ }+ };- if let Err(e) = fs::rename(&temp_path, &path) {- log::debug!("Failed to rename summary cache file for {}: {}", branch, e);- let _ = fs::remove_file(&temp_path);+ let mut cleared = 0;+ for entry in branch_dirs.flatten() {+ if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {+ continue;+ }+ let dir = entry.path();+ cleared += cache::clear_json_files(&dir)?;+ let _ = fs::remove_dir(&dir);+ }+ Ok(cleared)}}-/// Hash a string to produce a cache invalidation key-pub(crate) fn hash_diff(diff: &str) -> u64 {- let mut hasher = DefaultHasher::new();- diff.hash(&mut hasher);- hasher.finish()+/// Load every `.json` cache entry in a branch directory and return the one+/// with the newest `generated_at`. Corrupt entries are skipped.+fn freshest_entry(dir: &Path) -> Option<CachedSummary> {+ fs::read_dir(dir)+ .ok()?+ .filter_map(|e| e.ok())+ .filter(|e| e.file_name().to_str().is_some_and(|s| s.ends_with(".json")))+ .filter_map(|e| cache::read_json::<CachedSummary>(&e.path()))+ .max_by_key(|s| s.generated_at)+}++/// Hash a string with SHA-256 and return the first 16 hex chars (64 bits).+///+/// 64 bits is more than enough entropy to make collisions astronomically+/// unlikely at realistic cache sizes. We truncate for shorter, friendlier+/// filenames — the full 256-bit digest would produce 64-char filenames+/// with no practical benefit.+///+/// `DefaultHasher` (previously used) is explicitly undocumented as+/// stable across Rust versions, which is unsafe for a value persisted+/// to disk. SHA-256 is deterministic across toolchains and platforms.+pub(crate) fn hash_diff(diff: &str) -> String {+ use std::fmt::Write as _;+ let mut hasher = Sha256::new();+ hasher.update(diff.as_bytes());+ let mut out = String::with_capacity(16);+ for b in hasher.finalize().iter().take(8) {+ let _ = write!(out, "{b:02x}");+ }+ out}/// Compute the combined diff for a branch (branch diff + working tree diff).@@ -208,10 +299,9 @@ pub(crate) fn generate_summary_core(let diff_hash = hash_diff(&combined.diff);- // Check cache- if let Some(cached) = read_cache(repo, branch)- && cached.diff_hash == diff_hash- {+ // Cache hit is "does the file exist?" — no JSON parse needed for the+ // staleness check because the hash lives in the filename.+ if let Some(cached) = CachedSummary::read(repo, branch, &diff_hash) {return Ok(Some(cached.summary));}@@ -226,16 +316,12 @@ pub(crate) fn generate_summary_core(let _permit = LLM_SEMAPHORE.acquire();let summary = execute_llm_command(llm_command, &prompt)?;- // Write cache- write_cache(- repo,- branch,- &CachedSummary {- summary: summary.clone(),- diff_hash,- branch: branch.to_string(),- },- );+ let cached = CachedSummary {+ summary: summary.clone(),+ branch: branch.to_string(),+ generated_at: epoch_now(),+ };+ cached.write(repo, &diff_hash);Ok(Some(summary))}@@ -289,16 +375,12 @@ mod tests {}#[test]- fn test_hash_diff_deterministic() {- let h1 = hash_diff("hello world");- let h2 = hash_diff("hello world");- assert_eq!(h1, h2);- }-- #[test]- fn test_hash_diff_different_inputs() {- let h1 = hash_diff("hello");- let h2 = hash_diff("world");- assert_ne!(h1, h2);+ fn test_hash_diff_is_sha256_prefix() {+ // SHA-256("hello world") hex prefix is "b94d27b9934d3e08".+ assert_eq!(hash_diff("hello world"), "b94d27b9934d3e08");+ // Deterministic.+ assert_eq!(hash_diff("hello world"), hash_diff("hello world"));+ // Different inputs → different hashes.+ assert_ne!(hash_diff("hello"), hash_diff("world"));}}diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex b0b439e41..88289a9e7 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -66,6 +66,28 @@ fn write_ci_cache(repo: &TestRepo, branch: &str, json: &str) {std::fs::write(&cache_file, json).unwrap();}+/// Write a summary cache entry at `.git/wt/cache/summary/{branch}/{hash}.json`.+///+/// The hash is opaque to callers — they just need a consistent key per entry —+/// so we accept an arbitrary hex-like string rather than recomputing SHA-256.+fn write_summary_cache(+ repo: &TestRepo,+ branch: &str,+ hash: &str,+ summary: &str,+ generated_at: u64,+) {+ let safe_branch = worktrunk::path::sanitize_for_filename(branch);+ let dir = repo+ .root_path()+ .join(".git/wt/cache/summary")+ .join(&safe_branch);+ std::fs::create_dir_all(&dir).unwrap();+ let body =+ format!(r#"{{"summary":"{summary}","branch":"{branch}","generated_at":{generated_at}}}"#);+ std::fs::write(dir.join(format!("{hash}.json")), body).unwrap();+}+/// Create a command for `wt config state <key> <action> [args...]`fn wt_state_cmd(repo: &TestRepo, key: &str, action: &str, args: &[&str]) -> Command {let mut cmd = wt_command();@@ -899,6 +921,9 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {std::fs::create_dir_all(&sha_cache_dir).unwrap();std::fs::write(sha_cache_dir.join("abc123-def456.json"), "true").unwrap();+ // Summary cache (content-addressed filename)+ write_summary_cache(&repo, "feature", "aaaaaaaaaaaaaaaa", "Short summary", 0);+// Logslet log_dir = git_dir.join("wt/logs");std::fs::create_dir_all(&log_dir).unwrap();@@ -914,6 +939,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 summary 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@@ -954,6 +980,12 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {!ci_cache_dir.join("feature.json").exists(),"CI cache file should be cleared");+ // Summary cache is file-based too, verify the per-branch dir is gone+ let summary_feature_dir = git_dir.join("wt/cache/summary/feature");+ assert!(+ !summary_feature_dir.exists(),+ "Summary cache dir for feature should be cleared"+ );assert!(!log_dir.exists());}@@ -1017,6 +1049,9 @@ fn test_state_get_empty(repo: TestRepo) {[36mCI STATUS CACHE[39m[107m [0m (none)+ [36mSUMMARY CACHE[39m+ [107m [0m (none)+[36mGIT COMMANDS CACHE[39m[107m [0m (none)@@ -1143,6 +1178,15 @@ fn test_state_get_comprehensive(repo: TestRepo) {std::fs::write(sha_cache_dir.join("aaaa-bbbb.json"), "{}").unwrap();std::fs::write(sha_cache_dir.join("cccc-dddd.json"), "{}").unwrap();+ // Populate summary cache so the SUMMARIES CACHE section renders rows.+ write_summary_cache(+ &repo,+ "feature",+ "aaaaaaaaaaaaaaaa",+ "Add constant-time token validation",+ TEST_EPOCH,+ );+let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());state_get_settings().bind(|| {@@ -1165,6 +1209,7 @@ fn test_state_get_json_empty(repo: TestRepo) {"hook_output": [],"markers": [],"previous_branch": null,+ "summaries": [],"trash": [],"vars": []}@@ -1211,6 +1256,15 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {std::fs::create_dir_all(&sha_cache_dir).unwrap();std::fs::write(sha_cache_dir.join("aaaa-bbbb.json"), "{}").unwrap();+ // Populate summary cache+ write_summary_cache(+ &repo,+ "feature",+ "aaaaaaaaaaaaaaaa",+ "Add constant-time token validation",+ TEST_EPOCH,+ );+let output = wt_state_get_json_cmd(&repo).output().unwrap();assert!(output.status.success());let json_str = String::from_utf8_lossy(&output.stdout);@@ -1243,6 +1297,13 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {}],"previous_branch": "feature",+ "summaries": [+ {+ "branch": "feature",+ "generated_at": 1735776000,+ "summary": "Add constant-time token validation"+ }+ ],"trash": [{"modified_at": "<MTIME>",@@ -1337,6 +1398,7 @@ fn test_state_get_json_with_logs(repo: TestRepo) {],"markers": [],"previous_branch": null,+ "summaries": [],"trash": [],"vars": []}diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex 419c6a55a..4cbca8b64 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -1924,15 +1924,15 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_/// Mock summary cache by computing the real diff hash and writing a cache entry.////// Mirrors `summary::generate_summary_core` — computes the combined diff-/// (branch + working tree), hashes it, and writes a CachedSummary JSON file.+/// (branch + working tree), SHA-256-hashes it, and writes+/// `summary/{branch}/{hash}.json` with a CachedSummary body.fn mock_summary_cache(repo: &TestRepo,branch: &str,worktree_path: Option<&std::path::Path>,summary: &str,) {- use std::collections::hash_map::DefaultHasher;- use std::hash::{Hash, Hasher};+ use sha2::{Digest, Sha256};// Compute combined diff (matching compute_combined_diff in summary.rs)let mut diff = String::new();@@ -1967,15 +1967,21 @@ fn mock_summary_cache(}}- // Hash the diff (matches summary::hash_diff)- let mut hasher = DefaultHasher::new();- diff.hash(&mut hasher);- let diff_hash = hasher.finish();+ // SHA-256 prefix (matches summary::hash_diff — first 16 hex chars).+ let mut hasher = Sha256::new();+ hasher.update(diff.as_bytes());+ let digest = hasher.finalize();+ const HEX: &[u8; 16] = b"0123456789abcdef";+ let mut diff_hash = String::with_capacity(16);+ for &b in digest.iter().take(8) {+ diff_hash.push(HEX[(b >> 4) as usize] as char);+ diff_hash.push(HEX[(b & 0xf) as usize] as char);+ }// Write cache filelet cache_json = format!(- r#"{{"summary":"{}","diff_hash":{},"branch":"{}"}}"#,- summary, diff_hash, branch+ r#"{{"summary":"{}","branch":"{}","generated_at":0}}"#,+ summary, branch);let output = repo@@ -1990,10 +1996,14 @@ fn mock_summary_cache(repo.root_path().join(&git_dir)};- let cache_dir = git_path.join("wt").join("cache").join("summaries");- std::fs::create_dir_all(&cache_dir).unwrap();let safe_branch = worktrunk::path::sanitize_for_filename(branch);- let cache_file = cache_dir.join(format!("{safe_branch}.json"));+ let branch_dir = git_path+ .join("wt")+ .join("cache")+ .join("summary")+ .join(&safe_branch);+ std::fs::create_dir_all(&branch_dir).unwrap();+ let cache_file = branch_dir.join(format!("{diff_hash}.json"));std::fs::write(&cache_file, &cache_json).unwrap();}diff --git a/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap b/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snapindex ffcd6ed36..ba876b2cc 100644--- a/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap+++ b/tests/snapshots/integration__integration_tests__config_state__state_get_comprehensive.snap@@ -25,6 +25,11 @@ expression: "String::from_utf8_lossy(&output.stdout)"─────── ────── ─── ────────feature passed now abc12345+[36mSUMMARY CACHE[39m+ Branch Summary Age+ ─────── ────────────────────────────────── ───+ feature Add constant-time token validation now+[36mGIT COMMANDS CACHE[39m[107m [0m 2 entriesdiff --git a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snapindex 8c5ed3376..e16ae663e 100644--- a/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap+++ b/tests/snapshots/integration__integration_tests__config_state__state_get_with_ci_entries.snap@@ -21,6 +21,9 @@ expression: "String::from_utf8_lossy(&output.stdout)"feature passed now abc12345main none now deadbeef+[36mSUMMARY CACHE[39m+[107m [0m (none)+[36mGIT COMMANDS CACHE[39m[107m [0m (none)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 3a528da31..ba3f00f41 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@@ -59,7 +59,7 @@ Clears all stored state:- Previous branch- All branch markers- All variables-- All caches (CI status, git commands)+- All caches (CI status, summaries, git commands)- All hints- All log files- Stale trash from worktree removal ([2m.git/wt/trash/[0m)diff --git a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snapindex 73d8ac5f3..89874eef2 100644--- a/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config_state_get.snap@@ -65,6 +65,7 @@ Shows all stored state including:- [1mBranch markers[0m: User-defined branch notes- [1mVars[0m: Custom variables per branch- [1mCI status[0m: Cached GitHub/GitLab CI status per branch (30s TTL)+- [1mSummaries[0m: Cached LLM-generated branch summaries (shown in [2mwt list --full[0m and [2mwt switch[0m preview)- [1mGit commands cache[0m: SHA-keyed merge-tree, ancestry, and diff-stats results- [1mHints[0m: One-time hints that have been shown- [1mLog files[0m: Operation and debug logs