Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
feat(config): show trash and git commands cache in state get (#2292)
Maximilian Roos271ddddc582f
diff --git a/src/cli/config.rs b/src/cli/config.rsindex 9932f4656..fd05557c0 100644--- a/src/cli/config.rs+++ b/src/cli/config.rs@@ -527,8 +527,12 @@ 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)+- **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+- **Trash**: Staged worktree directories awaiting background deletion++Every category that `wt config state clear` sweeps is shown here.CI cache entries show status, age, and the commit SHA they were fetched for."#)]Get {diff --git a/src/commands/config/state.rs b/src/commands/config/state.rsindex ce26b1d00..0859d535d 100644--- a/src/commands/config/state.rs+++ b/src/commands/config/state.rs@@ -1,7 +1,30 @@//! State management commands.//!-//! Commands for getting, setting, and clearing stored state like default branch,-//! previous branch, CI status, markers, and logs.+//! Commands for getting, setting, and clearing stored state. State lives in+//! git config (under `worktrunk.*`) and in the `.git/wt/` directory tree.+//!+//! # `state get` ↔ `state clear` parity+//!+//! The aggregate `wt config state get` (`handle_state_show`) MUST surface every+//! category that the aggregate `wt config state clear` (`handle_state_clear_all`)+//! removes. A user should never be able to run `state clear` and have something+//! disappear that `state get` never mentioned.+//!+//! Categories covered by both paths:+//!+//! - Default branch cache (git config `worktrunk.default_branch.*`)+//! - Previous branch (git config `worktrunk.history`)+//! - Branch markers (git config `worktrunk.state.<branch>.marker`)+//! - Vars (git config `worktrunk.state.<branch>.vars.*`)+//! - CI status cache (`.git/wt/cache/ci-status/`)+//! - Git commands cache (`.git/wt/cache/{merge-tree-conflicts,is-ancestor,…}/`)+//! - Hints (git config `worktrunk.hints.*`)+//! - Logs (`.git/wt/logs/`)+//! - Trash (`.git/wt/trash/`)+//!+//! When adding a new category, update BOTH `handle_state_show` and+//! `handle_state_clear_all`, plus the `after_long_help` blocks for `state get`+//! and `state clear` in `src/cli/config.rs`, in the same change.//!//! # Log layout invariant//!@@ -126,6 +149,51 @@ fn sort_hook_entries(entries: &mut [HookOutputEntry]) {});}+/// A top-level entry staged under `wt_trash_dir()`.+///+/// Worktree removal renames directories into `.git/wt/trash/<name>-<timestamp>`+/// and a background `rm -rf` cleans them up; entries still present here are+/// awaiting (or escaped) that sweep.+struct TrashEntry {+ /// Filename, e.g. `myproject.feature-1234567890`.+ name: String,+ /// Absolute path, forward-slashed for cross-platform display.+ path: String,+ metadata: std::fs::Metadata,+}++/// List top-level entries under `wt_trash_dir()`.+///+/// Only the first level matters — each entry is one staged worktree (a+/// directory) or a stray file. Sorted by mtime (newest first) with name as+/// tie-breaker. Individual dirent/metadata failures are skipped: `state get`+/// is a read-only inspector and can race with the background `rm -rf`, so a+/// partial listing is more useful than a hard failure.+fn list_trash_entries(repo: &Repository) -> anyhow::Result<Vec<TrashEntry>> {+ let trash_dir = repo.wt_trash_dir();+ if !trash_dir.exists() {+ return Ok(Vec::new());+ }++ let mut out: Vec<TrashEntry> = std::fs::read_dir(&trash_dir)?+ .filter_map(|entry| entry.ok())+ .filter_map(|entry| {+ let metadata = entry.metadata().ok()?;+ Some(TrashEntry {+ name: entry.file_name().to_string_lossy().into_owned(),+ path: entry.path().to_slash_lossy().into_owned(),+ metadata,+ })+ })+ .collect();+ out.sort_by(|a, b| {+ let a_time = a.metadata.modified().ok();+ let b_time = b.metadata.modified().ok();+ b_time.cmp(&a_time).then_with(|| a.name.cmp(&b.name))+ });+ Ok(out)+}+/// Clear stale entries from the wt/trash directory.////// Worktree removal renames directories into `.git/wt/trash/` for instant UX,@@ -1035,16 +1103,36 @@ fn handle_state_show_json(repo: &Repository) -> anyhow::Result<()> {// Get hintslet hints = repo.list_shown_hints();+ // Get trash entries+ let trash: Vec<serde_json::Value> = list_trash_entries(repo)?+ .iter()+ .map(|e| {+ let modified_at = e+ .metadata+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| d.as_secs());+ serde_json::json!({+ "name": e.name,+ "path": e.path,+ "modified_at": modified_at,+ })+ })+ .collect();+let output = serde_json::json!({"default_branch": default_branch,"previous_branch": previous_branch,"markers": markers,"ci_status": ci_status,+ "git_commands_cache": repo.git_commands_cache_count(),"vars": vars_data,"command_log": command_log,"hook_output": hook_output,"diagnostic": diagnostic,- "hints": hints+ "hints": hints,+ "trash": trash,});println!("{}", serde_json::to_string_pretty(&output)?);@@ -1148,6 +1236,21 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {}writeln!(out)?;+ // Show git commands cache summary+ writeln!(out, "{}", format_heading("GIT COMMANDS CACHE", None))?;+ let sha_count = repo.git_commands_cache_count();+ if sha_count == 0 {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ let label = if sha_count == 1 { "entry" } else { "entries" };+ writeln!(+ out,+ "{}",+ format_with_gutter(&format!("{sha_count} {label}"), None)+ )?;+ }+ writeln!(out)?;+// Show hintswriteln!(out, "{}", format_heading("HINTS", None))?;let hints = repo.list_shown_hints();@@ -1162,6 +1265,36 @@ fn handle_state_show_table(repo: &Repository) -> anyhow::Result<()> {// Show log filesrender_all_log_sections(&mut out, repo)?;+ writeln!(out)?;++ // Show trash (staged worktree removals awaiting background delete)+ let trash_dir = repo.wt_trash_dir();+ let trash_display = format_path_for_display(&trash_dir);+ writeln!(+ out,+ "{}",+ format_heading("TRASH", Some(&format!("@ {trash_display}")))+ )?;+ let trash = list_trash_entries(repo)?;+ if trash.is_empty() {+ writeln!(out, "{}", format_with_gutter("(none)", None))?;+ } else {+ let rows: Vec<Vec<String>> = trash+ .iter()+ .map(|e| {+ let age = e+ .metadata+ .modified()+ .ok()+ .and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())+ .map(|d| format_relative_time_short(d.as_secs() as i64))+ .unwrap_or_else(|| "?".to_string());+ vec![e.name.clone(), age]+ })+ .collect();+ let rendered = crate::md_help::render_data_table(&["Entry", "Age"], &rows);+ writeln!(out, "{}", rendered.trim_end())?;+ }// Display through pager; fall back to direct stdout if pager unavailableif let Err(e) = show_help_in_pager(&out, true) {diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex 1fc05f7c4..fa2154d4a 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -628,6 +628,14 @@ impl Repository {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 21ae1395a..a19db8295 100644--- a/src/git/repository/sha_cache.rs+++ b/src/git/repository/sha_cache.rs@@ -317,6 +317,26 @@ pub(crate) fn clear_all(repo: &Repository) -> usize {cleared}+/// Count all cached SHA-keyed entries across every kind.+///+/// 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+}+#[cfg(test)]mod tests {use super::*;diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex 91a4bd7bc..f8d619956 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -914,6 +914,9 @@ fn test_state_get_empty(repo: TestRepo) {[36mCI STATUS CACHE[39m[107m [0m (none)+ [36mGIT COMMANDS CACHE[39m+ [107m [0m (none)+[36mHINTS[39m[107m [0m (none)@@ -925,6 +928,9 @@ fn test_state_get_empty(repo: TestRepo) {[36mDIAGNOSTIC[39m @ <PATH>[107m [0m (none)++ [36mTRASH[39m @ _REPO_/.git/wt/trash+ [107m [0m (none)");});}@@ -1023,6 +1029,17 @@ fn test_state_get_comprehensive(repo: TestRepo) {"remove output",);+ // Create trash entries (staged worktree removals)+ let trash_dir = git_dir.join("wt/trash");+ std::fs::create_dir_all(trash_dir.join("myproject.feature-1234567890")).unwrap();+ std::fs::create_dir_all(trash_dir.join("myproject.bugfix-9999999999")).unwrap();++ // Create git commands cache entries (SHA-keyed caches)+ let sha_cache_dir = git_dir.join("wt/cache/merge-tree-conflicts");+ std::fs::create_dir_all(&sha_cache_dir).unwrap();+ std::fs::write(sha_cache_dir.join("aaaa-bbbb.json"), "{}").unwrap();+ std::fs::write(sha_cache_dir.join("cccc-dddd.json"), "{}").unwrap();+let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());state_get_settings().bind(|| {@@ -1040,10 +1057,12 @@ fn test_state_get_json_empty(repo: TestRepo) {"command_log": [],"default_branch": "main","diagnostic": [],+ "git_commands_cache": 0,"hints": [],"hook_output": [],"markers": [],"previous_branch": null,+ "trash": [],"vars": []}"#);@@ -1082,40 +1101,62 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {),);+ // Populate trash + git commands cache for parity coverage+ let git_dir = repo.root_path().join(".git");+ std::fs::create_dir_all(git_dir.join("wt/trash/myproject.feature-1234567890")).unwrap();+ let sha_cache_dir = git_dir.join("wt/cache/is-ancestor");+ std::fs::create_dir_all(&sha_cache_dir).unwrap();+ std::fs::write(sha_cache_dir.join("aaaa-bbbb.json"), "{}").unwrap();+let output = wt_state_get_json_cmd(&repo).output().unwrap();assert!(output.status.success());- assert_snapshot!(String::from_utf8_lossy(&output.stdout), @r#"- {- "ci_status": [- {- "branch": "feature",- "checked_at": 1735776000,- "head": "abc12345def67890",- "status": "passed"- }- ],- "command_log": [],- "default_branch": "main",- "diagnostic": [],- "hints": [],- "hook_output": [],- "markers": [- {- "branch": "feature",- "marker": "🚧 WIP",- "set_at": 1735776000- }- ],- "previous_branch": "feature",- "vars": [+ let json_str = String::from_utf8_lossy(&output.stdout);+ let json: serde_json::Value = serde_json::from_str(&json_str).unwrap();+ let normalized = serde_json::to_string_pretty(&json).unwrap();+ let mut settings = insta::Settings::clone_current();+ settings.add_filter(r#""modified_at": \d+"#, r#""modified_at": "<MTIME>""#);+ settings.bind(|| {+ assert_snapshot!(normalized, @r#"{- "branch": "main",- "key": "env",- "value": "staging"+ "ci_status": [+ {+ "branch": "feature",+ "checked_at": 1735776000,+ "head": "abc12345def67890",+ "status": "passed"+ }+ ],+ "command_log": [],+ "default_branch": "main",+ "diagnostic": [],+ "git_commands_cache": 1,+ "hints": [],+ "hook_output": [],+ "markers": [+ {+ "branch": "feature",+ "marker": "🚧 WIP",+ "set_at": 1735776000+ }+ ],+ "previous_branch": "feature",+ "trash": [+ {+ "modified_at": "<MTIME>",+ "name": "myproject.feature-1234567890",+ "path": "_REPO_/.git/wt/trash/myproject.feature-1234567890"+ }+ ],+ "vars": [+ {+ "branch": "main",+ "key": "env",+ "value": "staging"+ }+ ]}- ]- }- "#);+ "#);+ });}#[rstest]@@ -1167,6 +1208,7 @@ fn test_state_get_json_with_logs(repo: TestRepo) {],"default_branch": "main","diagnostic": [],+ "git_commands_cache": 0,"hints": [],"hook_output": [{@@ -1192,6 +1234,7 @@ fn test_state_get_json_with_logs(repo: TestRepo) {],"markers": [],"previous_branch": null,+ "trash": [],"vars": []}"#);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 074369682..ffcd6ed36 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,9 @@ expression: "String::from_utf8_lossy(&output.stdout)"─────── ────── ─── ────────feature passed now abc12345+[36mGIT COMMANDS CACHE[39m+[107m [0m 2 entries+[36mHINTS[39m[107m [0m (none)@@ -39,3 +42,9 @@ expression: "String::from_utf8_lossy(&output.stdout)"[36mDIAGNOSTIC[39m @ <PATH>[107m [0m (none)++[36mTRASH[39m @ _REPO_/.git/wt/trash+ Entry Age+ ──────────────────────────── ──────+ myproject.bugfix-9999999999 future+ myproject.feature-1234567890 futurediff --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 421d82227..8c5ed3376 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+[36mGIT COMMANDS CACHE[39m+[107m [0m (none)+[36mHINTS[39m[107m [0m (none)@@ -32,3 +35,6 @@ expression: "String::from_utf8_lossy(&output.stdout)"[36mDIAGNOSTIC[39m @ <PATH>[107m [0m (none)++[36mTRASH[39m @ _REPO_/.git/wt/trash+[107m [0m (none)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 8eef642a5..50812dacc 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,8 +65,12 @@ 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)+- [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+- [1mTrash[0m: Staged worktree directories awaiting background deletion++Every category that [2mwt config state clear[0m sweeps is shown here.CI cache entries show status, age, and the commit SHA they were fetched for.