Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Consolidate cache management under `wt config cache`
Maximilian Roos59ab9295135e
diff --git a/README.md b/README.mdindex 255352e31..ae9ec995f 100644--- a/README.md+++ b/README.md@@ -799,13 +799,13 @@ wt config — Manage configuration and shell integrationUsage: config <COMMAND>Commands:- shell Shell integration setup- create Create global configuration file- show Show configuration files & locations- refresh-cache Refresh default branch from remote- status Manage branch status markers- approvals Manage command approvals- help Print this message or the help of the given subcommand(s)+ shell Shell integration setup+ create Create global configuration file+ show Show configuration files & locations+ cache Manage caches (CI status, default branch)+ status Manage branch status markers+ approvals Manage command approvals+ help Print this message or the help of the given subcommand(s)Options:-h, --helpdiff --git a/src/cli.rs b/src/cli.rsindex fb9d9f629..80db6b68a 100644--- a/src/cli.rs+++ b/src/cli.rs@@ -287,14 +287,11 @@ If a config file doesn't exist, shows defaults that would be used."#)]Show,- /// Refresh default branch from remote- #[command(- after_long_help = r#"Queries the remote to determine the default branch and caches the result.--Use when the remote default branch has changed. The cached value is used by-`wt merge`, `wt list`, and other commands that reference the default branch."#- )]- RefreshCache,+ /// Manage caches (CI status, default branch)+ Cache {+ #[command(subcommand)]+ action: CacheCommand,+ },/// Manage branch status markersStatus {@@ -373,6 +370,34 @@ Stored in git config under `worktrunk.status.<branch>`."#},}+#[derive(Subcommand)]+pub enum CacheCommand {+ /// Show cached data+ #[command(after_long_help = r#"Shows all cached data including:++- **Default branch**: Cached result of querying remote for default branch+- **CI status**: Cached GitHub/GitLab CI status per branch (30s TTL)++CI cache entries show status, age, and the commit SHA they were fetched for."#)]+ Show,++ /// Clear cached data+ Clear {+ /// Cache type: 'ci' or 'default-branch' (omit for all)+ #[arg(value_parser = ["ci", "default-branch"])]+ cache_type: Option<String>,+ },++ /// Refresh default branch from remote+ #[command(+ after_long_help = r#"Queries the remote to determine the default branch and caches the result.++Use when the remote default branch has changed. The cached value is used by+`wt merge`, `wt list`, and other commands that reference the default branch."#+ )]+ Refresh,+}+/// Workflow building blocks#[derive(Subcommand)]pub enum StepCommand {diff --git a/src/commands/config.rs b/src/commands/config.rsindex a17b97c74..ec9a41c12 100644--- a/src/commands/config.rs+++ b/src/commands/config.rs@@ -12,6 +12,7 @@ use worktrunk::styling::{};use super::configure_shell::{ConfigAction, scan_shell_configs};+use super::list::ci_status::CachedCiStatus;use crate::help_pager::show_help_in_pager;use crate::output;@@ -363,26 +364,6 @@ fn get_global_config_path() -> Option<PathBuf> {Some(strategy.config_dir().join("worktrunk").join("config.toml"))}-/// Handle the config refresh-cache command-pub fn handle_config_refresh_cache() -> anyhow::Result<()> {- let repo = Repository::current();-- // Display progress message- crate::output::progress(format!(- "{CYAN}Querying remote for default branch...{CYAN:#}"- ))?;-- // Refresh the cache (this will make a network call)- let branch = repo.refresh_default_branch()?;-- // Display success message- crate::output::success(format!(- "{GREEN}Cache refreshed: {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN:#}"- ))?;-- Ok(())-}-/// Handle the config status set commandpub fn handle_config_status_set(value: String, branch: Option<String>) -> anyhow::Result<()> {let repo = Repository::current();@@ -454,3 +435,107 @@ pub fn handle_config_status_unset(target: String) -> anyhow::Result<()> {Ok(())}++/// Handle the cache show command+pub fn handle_cache_show() -> anyhow::Result<()> {+ use worktrunk::styling::HINT;++ let repo = Repository::current();++ // Show default branch cache+ crate::output::info(format!("{HINT}Default branch cache:{HINT:#}"))?;+ match repo.default_branch() {+ Ok(branch) => crate::output::raw(format!(" {branch}"))?,+ Err(_) => crate::output::raw(" (not cached)")?,+ }+ crate::output::blank()?;++ // Show CI status cache+ crate::output::info(format!("{HINT}CI status cache:{HINT:#}"))?;++ let entries = CachedCiStatus::list_all(&repo);+ if entries.is_empty() {+ crate::output::raw(" (no CI cache entries)")?;+ return Ok(());+ }++ let now_secs = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_secs())+ .unwrap_or(0);++ for (branch, cached) in entries {+ let status = serde_json::to_string(&cached.status.ci_status)+ .map(|s| s.trim_matches('"').to_string())+ .unwrap_or_else(|_| "unknown".to_string());+ let age = now_secs.saturating_sub(cached.checked_at);+ let head: String = cached.head.chars().take(8).collect();++ crate::output::raw(format!(" {branch}: {status} (age: {age}s, head: {head})"))?;+ }++ Ok(())+}++/// Handle the cache clear command+pub fn handle_cache_clear(cache_type: Option<String>) -> anyhow::Result<()> {+ let repo = Repository::current();++ match cache_type.as_deref() {+ Some("ci") => {+ let cleared = CachedCiStatus::clear_all(&repo);+ if cleared == 0 {+ crate::output::info("No CI cache entries to clear")?;+ } else {+ crate::output::success(format!(+ "{GREEN}Cleared {GREEN_BOLD}{cleared}{GREEN_BOLD:#}{GREEN} CI cache entr{}{GREEN:#}",+ if cleared == 1 { "y" } else { "ies" }+ ))?;+ }+ }+ Some("default-branch") => {+ if repo+ .run_command(&["config", "--unset", "worktrunk.defaultBranch"])+ .is_ok()+ {+ crate::output::success(format!("{GREEN}Cleared default branch cache{GREEN:#}"))?;+ } else {+ crate::output::info("No default branch cache to clear")?;+ }+ }+ None => {+ let cleared_default = repo+ .run_command(&["config", "--unset", "worktrunk.defaultBranch"])+ .is_ok();+ let cleared_ci = CachedCiStatus::clear_all(&repo) > 0;++ if cleared_default || cleared_ci {+ crate::output::success(format!("{GREEN}Cleared all caches{GREEN:#}"))?;+ } else {+ crate::output::info("No caches to clear")?;+ }+ }+ Some(unknown) => {+ anyhow::bail!("Unknown cache type: {unknown}. Valid types: ci, default-branch");+ }+ }++ Ok(())+}++/// Handle the cache refresh command (refreshes default branch)+pub fn handle_cache_refresh() -> anyhow::Result<()> {+ let repo = Repository::current();++ crate::output::progress(format!(+ "{CYAN}Querying remote for default branch...{CYAN:#}"+ ))?;++ let branch = repo.refresh_default_branch()?;++ crate::output::success(format!(+ "{GREEN}Cache refreshed: {GREEN_BOLD}{branch}{GREEN_BOLD:#}{GREEN:#}"+ ))?;++ Ok(())+}diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex 9aa9750e1..3eeb6636d 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -1,5 +1,6 @@use serde::{Deserialize, Serialize, de::DeserializeOwned};use std::process::Command;+use worktrunk::git::Repository;/// Extract owner from a git remote URL (works for GitHub, GitLab, Bitbucket, etc.)///@@ -186,6 +187,124 @@ pub struct PrStatus {pub url: Option<String>,}+/// Cached CI status stored in git config+#[derive(Debug, Clone, Serialize, Deserialize)]+pub(crate) struct CachedCiStatus {+ /// The cached CI status+ pub status: PrStatus,+ /// Unix timestamp when the status was fetched+ pub checked_at: u64,+ /// The HEAD commit SHA when the status was fetched+ pub head: String,+}++impl CachedCiStatus {+ /// Cache TTL in seconds.+ ///+ /// At 300ms polling interval, 30s TTL means ~100 polls per cache entry.+ /// This reduces API calls by 99% while keeping status reasonably fresh.+ pub const TTL_SECS: u64 = 30;++ /// Escape branch name for use in git config key.+ ///+ /// Git config uses dots as section separators, so branch names like+ /// "feature.test" would create subsections. We escape dots to avoid this.+ pub(crate) fn escape_branch(branch: &str) -> String {+ branch.replace('.', "%2E")+ }++ /// Unescape branch name from git config key.+ pub(crate) fn unescape_branch(escaped: &str) -> String {+ escaped.replace("%2E", ".")+ }++ /// Check if the cache is still valid+ fn is_valid(&self, current_head: &str, now_secs: u64) -> bool {+ // Cache is valid if:+ // 1. HEAD hasn't changed (same commit)+ // 2. TTL hasn't expired+ self.head == current_head && now_secs.saturating_sub(self.checked_at) < Self::TTL_SECS+ }++ /// Read cached CI status from git config+ fn read(branch: &str, repo_root: &str) -> Option<Self> {+ let config_key = format!("worktrunk.ci.{}", Self::escape_branch(branch));+ let output = Command::new("git")+ .args(["config", "--get", &config_key])+ .current_dir(repo_root)+ .output()+ .ok()?;++ if !output.status.success() {+ return None;+ }++ let json = String::from_utf8(output.stdout).ok()?;+ serde_json::from_str(json.trim()).ok()+ }++ /// Write CI status to git config cache+ fn write(&self, branch: &str, repo_root: &str) {+ let config_key = format!("worktrunk.ci.{}", Self::escape_branch(branch));+ let Ok(json) = serde_json::to_string(self) else {+ log::debug!("Failed to serialize CI cache for {}", branch);+ return;+ };+ if let Err(e) = Command::new("git")+ .args(["config", &config_key, &json])+ .current_dir(repo_root)+ .output()+ {+ log::debug!("Failed to write CI cache for {}: {}", branch, e);+ }+ }++ /// Clear cached CI status from git config+ fn clear(branch: &str, repo_root: &str) {+ let config_key = format!("worktrunk.ci.{}", Self::escape_branch(branch));+ // Ignore errors - key may not exist, which is fine+ let _ = Command::new("git")+ .args(["config", "--unset", &config_key])+ .current_dir(repo_root)+ .output();+ }++ /// List all cached CI statuses as (branch_name, cached_status) pairs+ pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {+ let output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.ci\."])+ .unwrap_or_default();++ output+ .lines()+ .filter_map(|line| {+ let (key, json) = line.split_once(' ')?;+ let escaped = key.strip_prefix("worktrunk.ci.")?;+ let branch = Self::unescape_branch(escaped);+ let cached: Self = serde_json::from_str(json).ok()?;+ Some((branch, cached))+ })+ .collect()+ }++ /// Clear all cached CI statuses, returns count cleared+ pub(crate) fn clear_all(repo: &Repository) -> usize {+ let output = repo+ .run_command(&["config", "--get-regexp", r"^worktrunk\.ci\."])+ .unwrap_or_default();++ let mut cleared = 0;+ for line in output.lines() {+ if let Some(key) = line.split_whitespace().next()+ && repo.run_command(&["config", "--unset", key]).is_ok()+ {+ cleared += 1;+ }+ }+ cleared+ }+}+impl CiStatus {/// Get the ANSI color for this CI status.///@@ -253,6 +372,10 @@ impl PrStatus {/// First tries to find PR/MR status, then falls back to workflow/pipeline runs/// Returns None if no CI found or CLI tools unavailable///+ /// # Caching+ /// Results are cached in git config (`worktrunk.ci.{branch}`) for 30 seconds to avoid+ /// hitting GitHub API rate limits. Cache is invalidated when HEAD changes (new commits).+ ////// # Fork Support/// Runs gh commands from the repository directory to enable auto-detection of/// upstream repositories for forks. This ensures PRs opened against upstream@@ -265,6 +388,48 @@ impl PrStatus {// (including upstream repos for forks)let repo_root = repo_path.to_str().expect("repo path is not valid UTF-8");+ // Check cache first to avoid hitting API rate limits+ use std::time::{SystemTime, UNIX_EPOCH};+ let now_secs = SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs();++ if let Some(cached) = CachedCiStatus::read(branch, repo_root) {+ if cached.is_valid(local_head, now_secs) {+ log::debug!(+ "Using cached CI status for {} (age={}s)",+ branch,+ now_secs - cached.checked_at+ );+ return Some(cached.status);+ }+ log::debug!(+ "Cache expired for {} (age={}s, head_match={})",+ branch,+ now_secs - cached.checked_at,+ cached.head == local_head+ );+ }++ // Cache miss or expired - fetch fresh status+ let status = Self::detect_uncached(branch, local_head, repo_root);++ // Update cache+ if let Some(ref status) = status {+ let cached = CachedCiStatus {+ status: status.clone(),+ checked_at: now_secs,+ head: local_head.to_string(),+ };+ cached.write(branch, repo_root);+ } else {+ // Clear stale cache if no CI found+ CachedCiStatus::clear(branch, repo_root);+ }++ status+ }++ /// Detect CI status without caching (internal implementation)+ fn detect_uncached(branch: &str, local_head: &str, repo_root: &str) -> Option<Self> {// Try GitHub PR firstif let Some(status) = Self::detect_github(branch, local_head, repo_root) {return Some(status);diff --git a/src/commands/list/mod.rs b/src/commands/list/mod.rsindex c4d35930c..bb6ed6c72 100644--- a/src/commands/list/mod.rs+++ b/src/commands/list/mod.rs@@ -16,7 +16,7 @@//! 2. **Default branch lookup** (~1-5ms)//! - Reads cached value from `.git/refs/remotes/origin/HEAD`//! - Falls back to `git remote show origin` if not cached (~100-300ms network)-//! - Refresh with `wt config refresh-cache`+//! - Refresh with `wt config cache refresh`//!//! 3. **Sort worktrees** (<1ms)//! - Orders by: current → main → rest alphabetically@@ -95,7 +95,7 @@//! This is a git-native cache stored in `.git/refs/remotes/origin/HEAD`. All other data is//! fetched fresh on each `wt list` invocation.//!-//! Refresh with: `wt config refresh-cache`+//! Refresh with: `wt config cache refresh`//!//! ## Performance Characteristics//!diff --git a/src/commands/mod.rs b/src/commands/mod.rsindex fe620638f..b73726b29 100644--- a/src/commands/mod.rs+++ b/src/commands/mod.rs@@ -18,8 +18,8 @@ pub mod statusline;pub mod worktree;pub use config::{- handle_config_create, handle_config_refresh_cache, handle_config_show,- handle_config_status_set, handle_config_status_unset,+ handle_cache_clear, handle_cache_refresh, handle_cache_show, handle_config_create,+ handle_config_show, handle_config_status_set, handle_config_status_unset,};pub use configure_shell::{ConfigAction, handle_configure_shell, handle_unconfigure_shell};pub use init::handle_init;diff --git a/src/git/repository/mod.rs b/src/git/repository/mod.rsindex de80f13e2..4c0e322a2 100644--- a/src/git/repository/mod.rs+++ b/src/git/repository/mod.rs@@ -323,7 +323,7 @@ impl Repository {// Fallback: No remote or remote query failed, try to infer locally// TODO: Show message to user when using inference fallback:// "No remote configured. Using inferred default branch: {branch}"- // "To cache the default branch, set up a remote and run: wt config refresh-cache"+ // "To cache the default branch, set up a remote and run: wt config cache refresh"// Problem: git.rs is in lib crate, output module is in binary.// Options: (1) Return info about whether fallback was used, let callers show message// (2) Add messages in specific commands (merge.rs, worktree.rs)diff --git a/src/main.rs b/src/main.rsindex a2c33b70a..23c348382 100644--- a/src/main.rs+++ b/src/main.rs@@ -24,17 +24,18 @@ use commands::command_executor::CommandContext;use commands::handle_select;use commands::worktree::{SwitchResult, handle_push};use commands::{- ConfigAction, RebaseResult, SquashResult, handle_config_create, handle_config_refresh_cache,- handle_config_show, handle_config_status_set, handle_config_status_unset,- handle_configure_shell, handle_init, handle_list, handle_merge, handle_rebase, handle_remove,- handle_squash, handle_standalone_add_approvals, handle_standalone_clear_approvals,- handle_standalone_commit, handle_standalone_run_hook, handle_switch, handle_unconfigure_shell,+ ConfigAction, RebaseResult, SquashResult, handle_cache_clear, handle_cache_refresh,+ handle_cache_show, handle_config_create, handle_config_show, handle_config_status_set,+ handle_config_status_unset, handle_configure_shell, handle_init, handle_list, handle_merge,+ handle_rebase, handle_remove, handle_squash, handle_standalone_add_approvals,+ handle_standalone_clear_approvals, handle_standalone_commit, handle_standalone_run_hook,+ handle_switch, handle_unconfigure_shell,};use output::{execute_user_command, handle_remove_output, handle_switch_output};use cli::{- ApprovalsCommand, BetaCommand, Cli, Commands, ConfigCommand, ConfigShellCommand, StatusAction,- StepCommand,+ ApprovalsCommand, BetaCommand, CacheCommand, Cli, Commands, ConfigCommand, ConfigShellCommand,+ StatusAction, StepCommand,};use worktrunk::HookType;@@ -473,7 +474,11 @@ fn main() {}ConfigCommand::Create => handle_config_create(),ConfigCommand::Show => handle_config_show(),- ConfigCommand::RefreshCache => handle_config_refresh_cache(),+ ConfigCommand::Cache { action } => match action {+ CacheCommand::Show => handle_cache_show(),+ CacheCommand::Clear { cache_type } => handle_cache_clear(cache_type),+ CacheCommand::Refresh => handle_cache_refresh(),+ },ConfigCommand::Status { action } => match action {StatusAction::Set { value, branch } => handle_config_status_set(value, branch),StatusAction::Unset { target } => handle_config_status_unset(target),diff --git a/tests/integration_tests/help.rs b/tests/integration_tests/help.rsindex e4e88573b..5f7a02bfb 100644--- a/tests/integration_tests/help.rs+++ b/tests/integration_tests/help.rs@@ -73,14 +73,6 @@ fn help_config_show() {snapshot_help("help_config_show", &["config", "show", "--help"]);}-#[test]-fn help_config_refresh_cache() {- snapshot_help(- "help_config_refresh_cache",- &["config", "refresh-cache", "--help"],- );-}-#[test]fn help_config_status_set() {snapshot_help(diff --git a/tests/snapshots/integration__integration_tests__help__help_config.snap b/tests/snapshots/integration__integration_tests__help__help_config.snapindex 15787f142..c3cbb867c 100644--- a/tests/snapshots/integration__integration_tests__help__help_config.snap+++ b/tests/snapshots/integration__integration_tests__help__help_config.snap@@ -21,12 +21,12 @@ wt config - Manage configuration and shell integrationUsage: wt config [OPTIONS] <COMMAND>Commands:- shell Shell integration setup- create Create global configuration file- show Show configuration files & locations- refresh-cache Refresh default branch from remote- status Manage branch status markers- approvals Manage command approvals+ shell Shell integration setup+ create Create global configuration file+ show Show configuration files & locations+ cache Manage caches (CI status, default branch)+ status Manage branch status markers+ approvals Manage command approvalsOptions:-h, --helpdiff --git a/tests/snapshots/integration__integration_tests__help__help_config_refresh_cache.snap b/tests/snapshots/integration__integration_tests__help__help_config_refresh_cache.snapdeleted file mode 100644index 2dd3459ac..000000000--- a/tests/snapshots/integration__integration_tests__help__help_config_refresh_cache.snap+++ /dev/null@@ -1,41 +0,0 @@-----source: tests/integration_tests/help.rs-info:- program: wt- args:- - config- - refresh-cache- - "--help"- env:- CLICOLOR_FORCE: "1"- COLUMNS: "150"- GIT_EDITOR: ""- WORKTRUNK_BIN: ""- WORKTRUNK_CONFIG_PATH: /nonexistent/test/config.toml-----success: true-exit_code: 0------ stdout ------------ stderr ------wt config refresh-cache - Refresh default branch from remote-Usage: wt config refresh-cache [OPTIONS]--Options:- -h, --help- Print help (see a summary with '-h')--Global Options:- -C <path>- Working directory for this command-- --config <path>- User config file path-- -v, --verbose- Show commands and debug info--Queries the remote to determine the default branch and caches the result.--Use when the remote default branch has changed. The cached value is used by-[2mwt merge[0m, [2mwt list[0m, and other commands that reference the default branch.