Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Show relative paths in wt list & fix CI cache Windows flakiness (#252)
Maximilian Roosf215a466b043
diff --git a/docs/demos/wt-select/CLAUDE.md b/docs/demos/wt-select/CLAUDE.mdindex bc8328062..b65f8a985 100644--- a/docs/demos/wt-select/CLAUDE.md+++ b/docs/demos/wt-select/CLAUDE.md@@ -51,8 +51,8 @@ Special setup tricks:## CI Cache Trick-CI status is cached in git config. To show CI without GitHub access:-1. Write fake cache entries directly to git config+CI status is cached in `.git/wt-cache/ci-status/<branch>.json` files. To show CI without GitHub access:+1. Write fake cache entries directly to the cache files2. Use **future timestamp** (1 hour ahead) so cache never expires3. VHS recording reads cached statusdiff --git a/docs/demos/wt-select/build b/docs/demos/wt-select/buildindex d220c0e51..3cbd3f149 100755--- a/docs/demos/wt-select/build+++ b/docs/demos/wt-select/build@@ -39,9 +39,9 @@ The setup process:CI CACHE TRICK==============-The CI status is cached in git config (`worktrunk.state.{branch}.ci-status`). To show CI+The CI status is cached in `.git/wt-cache/ci-status/<branch>.json` files. To show CIstatus without actual GitHub/GitLab access, we:-1. Write fake CI cache entries directly to git config+1. Write fake CI cache entries directly to the cache files2. Use a future timestamp (1 hour ahead) so the cache never expires during recording3. VHS recording runs `wt select` which reads the cached CI status@@ -345,9 +345,9 @@ fn validate_template(template: &str) -> Result<(), String> {def add_ci_status(env: DemoEnv):- """Add fake CI status to git config for demo.+ """Add fake CI status to file-based cache for demo.- CI status is cached in git config as worktrunk.state.{branch}.ci-status with JSON value.+ CI status is cached in .git/wt-cache/ci-status/<branch>.json files.The cache uses a future timestamp to prevent expiration during VHS recording."""import json@@ -403,10 +403,12 @@ def add_ci_status(env: DemoEnv):}print("Adding CI status cache...")+ # Write to file-based cache at .git/wt-cache/ci-status/<branch>.json+ cache_dir = env.repo / ".git" / "wt-cache" / "ci-status"+ cache_dir.mkdir(parents=True, exist_ok=True)for branch, config in ci_configs.items():- config_key = f"worktrunk.state.{branch}.ci-status"- config_json = json.dumps(config)- git(["-C", str(env.repo), "config", config_key, config_json])+ cache_file = cache_dir / f"{branch}.json"+ cache_file.write_text(json.dumps(config))def main():diff --git a/src/commands/list/ci_status.rs b/src/commands/list/ci_status.rsindex ec9fac3b7..89c675ab8 100644--- a/src/commands/list/ci_status.rs+++ b/src/commands/list/ci_status.rs@@ -1,4 +1,6 @@use serde::{Deserialize, Serialize, de::DeserializeOwned};+use std::fs;+use std::path::{Path, PathBuf};use std::process::Command;use worktrunk::git::Repository;use worktrunk::shell_exec::run;@@ -1031,7 +1033,11 @@ pub struct PrStatus {pub url: Option<String>,}-/// Cached CI status stored in git config+/// 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".#[derive(Debug, Clone, Serialize, Deserialize)]pub(crate) struct CachedCiStatus {/// The cached CI status (None means no CI found for this branch)@@ -1076,13 +1082,10 @@ impl CachedCiStatus {self.head == current_head && now_secs.saturating_sub(self.checked_at) < ttl}- /// Read cached CI status from git config.- ///- /// Key format: `worktrunk.state.<branch>.ci-status`- fn read(branch: &str, repo_root: &str) -> Option<Self> {- let config_key = format!("worktrunk.state.{branch}.ci-status");+ /// Get the cache directory path: `.git/wt-cache/ci-status/`+ fn cache_dir(repo_root: &str) -> Option<PathBuf> {let mut cmd = Command::new("git");- cmd.args(["config", "--get", &config_key])+ cmd.args(["rev-parse", "--git-common-dir"]).current_dir(repo_root);let output = run(&mut cmd, None).ok()?;@@ -1090,69 +1093,161 @@ impl CachedCiStatus {return None;}- let json = String::from_utf8(output.stdout).ok()?;- serde_json::from_str(json.trim()).ok()+ let git_dir = String::from_utf8(output.stdout).ok()?;+ let git_dir = git_dir.trim();++ // Handle relative paths from git rev-parse+ let git_path = if Path::new(git_dir).is_absolute() {+ PathBuf::from(git_dir)+ } else {+ PathBuf::from(repo_root).join(git_dir)+ };++ Some(git_path.join("wt-cache").join("ci-status"))}- /// Write CI status to git config cache.+ /// Sanitize branch name for use as a filename.+ /// Handles Windows reserved names, control characters, and invalid filename characters.+ fn sanitize_branch_for_filename(branch: &str) -> String {+ let mut result: String = branch+ .chars()+ .map(|c| match c {+ // Windows/Unix invalid filename characters+ '/' | '\\' | '<' | '>' | ':' | '"' | '|' | '?' | '*' => '-',+ // Control characters (0x00-0x1F)+ c if c.is_control() => '-',+ _ => c,+ })+ .collect();++ // Trim trailing dots and spaces (Windows silently strips these)+ while result.ends_with('.') || result.ends_with(' ') {+ result.pop();+ }++ // Handle Windows reserved names (case-insensitive)+ // CON, PRN, AUX, NUL, COM1-9, LPT1-9+ let upper = result.to_uppercase();+ let is_reserved = matches!(upper.as_str(), "CON" | "PRN" | "AUX" | "NUL")+ || (upper.len() == 4+ && (upper.starts_with("COM") || upper.starts_with("LPT"))+ && upper.chars().last().is_some_and(|c| c.is_ascii_digit()));++ if is_reserved {+ format!("_{result}")+ } else if result.is_empty() {+ "_empty".to_string()+ } else {+ result+ }+ }++ /// Get the cache file path for a branch.+ fn cache_file(branch: &str, repo_root: &str) -> Option<PathBuf> {+ let dir = Self::cache_dir(repo_root)?;+ let safe_branch = Self::sanitize_branch_for_filename(branch);+ Some(dir.join(format!("{safe_branch}.json")))+ }++ /// Read cached CI status from file.+ fn read(branch: &str, repo_root: &str) -> Option<Self> {+ let path = Self::cache_file(branch, repo_root)?;+ let json = fs::read_to_string(&path).ok()?;+ serde_json::from_str(&json).ok()+ }++ /// Write CI status to cache file.///- /// Key format: `worktrunk.state.<branch>.ci-status`+ /// Uses atomic write (write to temp file, then rename) to avoid corruption+ /// and minimize lock contention on Windows.fn write(&self, branch: &str, repo_root: &str) {- let config_key = format!("worktrunk.state.{branch}.ci-status");+ let Some(path) = Self::cache_file(branch, repo_root) else {+ log::debug!("Failed to get cache path for {}", branch);+ return;+ };++ // 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;};- let mut cmd = Command::new("git");- cmd.args(["config", &config_key, &json])- .current_dir(repo_root);- if let Err(e) = run(&mut cmd, None) {- log::debug!("Failed to write CI cache for {}: {}", branch, e);++ // 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;+ }++ 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);}}/// List all cached CI statuses as (branch_name, cached_status) pairs.- ///- /// Key format: `worktrunk.state.<branch>.ci-status`pub(crate) fn list_all(repo: &Repository) -> Vec<(String, Self)> {- let output = repo- .run_command(&[- "config",- "--get-regexp",- r"^worktrunk\.state\..+\.ci-status$",- ])- .unwrap_or_default();-- output- .lines()- .filter_map(|line| {- let (key, json) = line.split_once(' ')?;- let branch = key- .strip_prefix("worktrunk.state.")?- .strip_suffix(".ci-status")?;- let cached: Self = serde_json::from_str(json).ok()?;- Some((branch.to_string(), cached))+ let repo_root = match repo.worktree_root() {+ Ok(path) => path,+ Err(_) => return Vec::new(),+ };++ let Some(cache_dir) = Self::cache_dir(repo_root.to_str().unwrap_or_default()) else {+ return Vec::new();+ };++ let entries = match fs::read_dir(&cache_dir) {+ Ok(entries) => entries,+ Err(_) => return Vec::new(),+ };++ entries+ .filter_map(|entry| {+ let entry = entry.ok()?;+ let path = entry.path();++ // Only process .json files (skip .json.tmp)+ if path.extension()?.to_str()? != "json" {+ return None;+ }++ let branch = path.file_stem()?.to_str()?.to_string();+ let json = fs::read_to_string(&path).ok()?;+ let cached: Self = serde_json::from_str(&json).ok()?;+ Some((branch, cached))}).collect()}/// Clear all cached CI statuses, returns count cleared.- ///- /// Key format: `worktrunk.state.<branch>.ci-status`pub(crate) fn clear_all(repo: &Repository) -> usize {- let output = repo- .run_command(&[- "config",- "--get-regexp",- r"^worktrunk\.state\..+\.ci-status$",- ])- .unwrap_or_default();+ let repo_root = match repo.worktree_root() {+ Ok(path) => path,+ Err(_) => return 0,+ };++ let Some(cache_dir) = Self::cache_dir(repo_root.to_str().unwrap_or_default()) else {+ return 0;+ };++ let entries = match fs::read_dir(&cache_dir) {+ Ok(entries) => entries,+ Err(_) => return 0,+ };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()- {+ for entry in entries.flatten() {+ let path = entry.path();+ // Only remove .json files+ if path.extension().is_some_and(|ext| ext == "json") && fs::remove_file(&path).is_ok() {cleared += 1;}}diff --git a/src/commands/merge.rs b/src/commands/merge.rsindex 622e20889..f23807c87 100644--- a/src/commands/merge.rs+++ b/src/commands/merge.rs@@ -232,6 +232,12 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {// STEP 2: Remove worktree via shared remove output handler so final message matches wt removelet worktree_root = repo.worktree_root()?;+ // After a successful merge, compute integration reason from main_path+ let main_repo = worktrunk::git::Repository::at(&destination_path);+ let effective_target = main_repo.effective_integration_target(&target_branch);+ let mut provider =+ worktrunk::git::LazyGitIntegration::new(&main_repo, ¤t_branch, &effective_target);+ let integration_reason = worktrunk::git::check_integration(&mut provider);let remove_result = RemoveResult::RemovedWorktree {main_path: destination_path.clone(),worktree_path: worktree_root,@@ -239,6 +245,7 @@ pub fn handle_merge(opts: MergeOptions<'_>) -> anyhow::Result<()> {branch_name: Some(current_branch.clone()),deletion_mode: BranchDeletionMode::SafeDelete,target_branch: Some(target_branch.clone()),+ integration_reason,};// Run hooks during merge removal (pass through verify flag)// Approval was handled at the gate (MergeCommandCollector)diff --git a/src/commands/repository_ext.rs b/src/commands/repository_ext.rsindex 1e9b355e8..7d8f11560 100644--- a/src/commands/repository_ext.rs+++ b/src/commands/repository_ext.rs@@ -142,6 +142,23 @@ impl RepositoryCliExt for Repository {_ => default_branch,};+ // Pre-compute integration reason to avoid race conditions when removing+ // multiple worktrees in background mode. Background git processes can hold+ // locks that cause subsequent integration checks to fail.+ let integration_reason = if deletion_mode.should_keep() || deletion_mode.is_force() {+ // Skip integration check if user explicitly controls branch deletion+ None+ } else if let Some(ref target) = target_branch {+ // Use main_path repo for integration check (may be different from current repo)+ let main_repo = Repository::at(&main_path);+ let effective_target = main_repo.effective_integration_target(target);+ let mut provider =+ worktrunk::git::LazyGitIntegration::new(&main_repo, branch_name, &effective_target);+ worktrunk::git::check_integration(&mut provider)+ } else {+ None+ };+Ok(RemoveResult::RemovedWorktree {main_path,worktree_path,@@ -149,6 +166,7 @@ impl RepositoryCliExt for Repository {branch_name: Some(branch_name.to_string()),deletion_mode,target_branch,+ integration_reason,})}@@ -188,6 +206,20 @@ impl RepositoryCliExt for Repository {_ => default_branch,};+ // Pre-compute integration reason (same logic as remove_worktree_by_name)+ let integration_reason =+ if deletion_mode.should_keep() || deletion_mode.is_force() || branch_name.is_none() {+ None+ } else if let (Some(target), Some(bn)) = (&target_branch, &branch_name) {+ let main_repo = Repository::at(&main_path);+ let effective_target = main_repo.effective_integration_target(target);+ let mut provider =+ worktrunk::git::LazyGitIntegration::new(&main_repo, bn, &effective_target);+ worktrunk::git::check_integration(&mut provider)+ } else {+ None+ };+Ok(RemoveResult::RemovedWorktree {main_path,worktree_path: current_path,@@ -195,6 +227,7 @@ impl RepositoryCliExt for Repository {branch_name,deletion_mode,target_branch,+ integration_reason,})}diff --git a/src/commands/worktree.rs b/src/commands/worktree.rsindex 20fdb14f8..0087245c0 100644--- a/src/commands/worktree.rs+++ b/src/commands/worktree.rs@@ -423,6 +423,11 @@ pub enum RemoveResult {branch_name: Option<String>,deletion_mode: BranchDeletionMode,target_branch: Option<String>,+ /// Pre-computed integration reason (if branch is integrated with target).+ /// Computed upfront to avoid race conditions when removing multiple worktrees+ /// in background mode (background git operations can hold locks that cause+ /// subsequent integration checks to fail).+ integration_reason: Option<worktrunk::git::IntegrationReason>,},/// Branch exists but has no worktree - attempt branch deletion onlyBranchOnly {@@ -786,6 +791,7 @@ pub fn handle_remove_by_path(branch_name: branch,deletion_mode: BranchDeletionMode::Keep, // Can't delete branch for detached worktreetarget_branch: None,+ integration_reason: None, // Not applicable for detached worktrees})}@@ -1179,6 +1185,7 @@ mod tests {branch_name: Some("feature".to_string()),deletion_mode: BranchDeletionMode::SafeDelete,target_branch: Some("main".to_string()),+ integration_reason: Some(worktrunk::git::IntegrationReason::SameCommit),};match result {RemoveResult::RemovedWorktree {@@ -1188,6 +1195,7 @@ mod tests {branch_name,deletion_mode,target_branch,+ integration_reason,} => {assert_eq!(main_path.to_str().unwrap(), "/main");assert_eq!(worktree_path.to_str().unwrap(), "/worktree");@@ -1196,6 +1204,7 @@ mod tests {assert!(!deletion_mode.should_keep());assert!(!deletion_mode.is_force());assert_eq!(target_branch.as_deref(), Some("main"));+ assert!(integration_reason.is_some());}_ => panic!("Expected RemovedWorktree variant"),}@@ -1229,6 +1238,7 @@ mod tests {branch_name: None, // Detached HEADdeletion_mode: BranchDeletionMode::ForceDelete,target_branch: None,+ integration_reason: None, // Force delete skips integration check};match result {RemoveResult::RemovedWorktree {diff --git a/src/output/handlers.rs b/src/output/handlers.rsindex 0ff184c19..7845b1c33 100644--- a/src/output/handlers.rs+++ b/src/output/handlers.rs@@ -429,6 +429,7 @@ pub fn handle_remove_output(branch_name,deletion_mode,target_branch,+ integration_reason,} => handle_removed_worktree_output(main_path,worktree_path,@@ -436,6 +437,7 @@ pub fn handle_remove_output(branch_name.as_deref(),*deletion_mode,target_branch.as_deref(),+ *integration_reason,branch,background,verify,@@ -498,6 +500,7 @@ fn handle_removed_worktree_output(branch_name: Option<&str>,deletion_mode: BranchDeletionMode,target_branch: Option<&str>,+ pre_computed_integration: Option<IntegrationReason>,branch: Option<&str>,background: bool,verify: bool,@@ -564,8 +567,8 @@ fn handle_removed_worktree_output(if background {// Background mode: spawn detached process- // Determine outcome upfront (check once, not in background script)- // Only show effective_target in message if we had a meaningful target (not tautological "HEAD" fallback)+ // Use pre-computed integration reason to avoid race conditions when removing+ // multiple worktrees (background processes can hold git locks)let (outcome, effective_target) = if deletion_mode.should_keep() {(BranchDeletionOutcome::NotDeleted,@@ -577,20 +580,12 @@ fn handle_removed_worktree_output(target_branch.map(String::from),)} else {- // Check if branch is integrated- let check_target = target_branch.unwrap_or("HEAD");- let deletion_repo = worktrunk::git::Repository::at(main_path);- let IntegrationResult {- reason,- effective_target,- } = get_integration_reason(&deletion_repo, branch_name, check_target);- // Only use effective_target for display if we had a real target (not "HEAD" fallback)- let display_target = target_branch.map(|_| effective_target);- let outcome = match reason {+ // Use pre-computed integration reason+ let outcome = match pre_computed_integration {Some(r) => BranchDeletionOutcome::Integrated(r),None => BranchDeletionOutcome::NotDeleted,};- (outcome, display_target)+ (outcome, target_branch.map(String::from))};let should_delete_branch = matches!(diff --git a/tests/integration_tests/config_state.rs b/tests/integration_tests/config_state.rsindex ee9e3893c..24994b9d3 100644--- a/tests/integration_tests/config_state.rs+++ b/tests/integration_tests/config_state.rs@@ -3,6 +3,21 @@ use insta::assert_snapshot;use rstest::rstest;use std::process::Command;+/// Write CI status to the file-based cache at .git/wt-cache/ci-status/<branch>.json+fn write_ci_cache(repo: &TestRepo, branch: &str, json: &str) {+ let git_dir = repo.root_path().join(".git");+ let cache_dir = git_dir.join("wt-cache").join("ci-status");+ std::fs::create_dir_all(&cache_dir).unwrap();++ // Sanitize branch name for filename+ let safe_branch: String = branch+ .chars()+ .map(|c| if c == '/' || c == '\\' { '-' } else { c })+ .collect();+ let cache_file = cache_dir.join(format!("{safe_branch}.json"));+ std::fs::write(&cache_file, json).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();@@ -491,14 +506,12 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {// Marker (using JSON format)repo.set_marker("main", "🚧");- // CI cache- repo.git_command(&[- "config",- "worktrunk.state.feature.ci-status",+ // CI cache (file-based)+ write_ci_cache(+ &repo,+ "feature",r#"{"checked_at":1704067200,"head":"abc123"}"#,- ])- .status()- .unwrap();+ );// Logslet git_dir = repo.root_path().join(".git");@@ -527,13 +540,11 @@ fn test_state_clear_all_comprehensive(repo: TestRepo) {.code()== Some(1));+ // CI cache is now file-based, verify the cache file is cleared+ let ci_cache_dir = git_dir.join("wt-cache").join("ci-status");assert!(- repo.git_command(&["config", "--get", "worktrunk.state.feature.ci-status"])- .output()- .unwrap()- .status- .code()- == Some(1)+ !ci_cache_dir.join("feature.json").exists(),+ "CI cache file should be cleared");assert!(!log_dir.exists());}@@ -578,29 +589,27 @@ fn test_state_get_empty(repo: TestRepo) {#[rstest]fn test_state_get_with_ci_entries(repo: TestRepo) {// Add CI cache entries - use TEST_EPOCH for deterministic age=0s in snapshots- repo.git_command(&[- "config",- "worktrunk.state.feature.ci-status",- &format!(r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#),- ])- .status()- .unwrap();+ write_ci_cache(+ &repo,+ "feature",+ &format!(+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#+ ),+ );- repo.git_command(&[- "config",- "worktrunk.state.bugfix.ci-status",- &format!(r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":true}},"checked_at":{TEST_EPOCH},"head":"111222333444555"}}"#),- ])- .status()- .unwrap();+ write_ci_cache(+ &repo,+ "bugfix",+ &format!(+ r#"{{"status":{{"ci_status":"failed","source":"branch","is_stale":true}},"checked_at":{TEST_EPOCH},"head":"111222333444555"}}"#+ ),+ );- repo.git_command(&[- "config",- "worktrunk.state.main.ci-status",+ write_ci_cache(+ &repo,+ "main",&format!(r#"{{"status":null,"checked_at":{TEST_EPOCH},"head":"deadbeef12345678"}}"#),- ])- .status()- .unwrap();+ );let output = wt_state_get_cmd(&repo).output().unwrap();assert!(output.status.success());@@ -630,14 +639,14 @@ fn test_state_get_comprehensive(repo: TestRepo) {.status().unwrap();- // Set up CI cache- repo.git_command(&[- "config",- "worktrunk.state.feature.ci-status",- &format!(r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#),- ])- .status()- .unwrap();+ // Set up CI cache (file-based)+ write_ci_cache(+ &repo,+ "feature",+ &format!(+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#+ ),+ );// Create log fileslet git_dir = repo.root_path().join(".git");@@ -682,14 +691,14 @@ fn test_state_get_json_comprehensive(repo: TestRepo) {.status().unwrap();- // Set up CI cache- repo.git_command(&[- "config",- "worktrunk.state.feature.ci-status",- &format!(r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#),- ])- .status()- .unwrap();+ // Set up CI cache (file-based)+ write_ci_cache(+ &repo,+ "feature",+ &format!(+ r#"{{"status":{{"ci_status":"passed","source":"pull-request","is_stale":false}},"checked_at":{TEST_EPOCH},"head":"abc12345def67890"}}"#+ ),+ );let output = wt_state_get_json_cmd(&repo).output().unwrap();assert!(output.status.success());diff --git a/tests/integration_tests/list.rs b/tests/integration_tests/list.rsindex a334f3501..41462beb1 100644--- a/tests/integration_tests/list.rs+++ b/tests/integration_tests/list.rs@@ -1653,7 +1653,7 @@ fn run_git(repo: &TestRepo, args: &[&str], cwd: &std::path::Path) {cmd.args(args).current_dir(cwd).output().unwrap();}-/// Mock CI status by writing to git config cache+/// Mock CI status by writing to file-based cachefn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_stale: bool) {// Get HEAD commit for the branchlet mut cmd = Command::new("git");@@ -1678,14 +1678,34 @@ fn mock_ci_status(repo: &TestRepo, branch: &str, status: &str, source: &str, is_head);- // Write to git config using subsection format (branch name is subsection, no escaping needed)- let config_key = format!("worktrunk.state.{branch}.ci-status");+ // Get git common dir for cache locationlet mut cmd = Command::new("git");repo.configure_git_cmd(&mut cmd);- cmd.args(["config", &config_key, &cache_json])+ let output = cmd+ .args(["rev-parse", "--git-common-dir"]).current_dir(repo.root_path()).output().unwrap();+ let git_dir = String::from_utf8_lossy(&output.stdout).trim().to_string();++ // Resolve relative path if needed+ let git_path = if std::path::Path::new(&git_dir).is_absolute() {+ std::path::PathBuf::from(&git_dir)+ } else {+ repo.root_path().join(&git_dir)+ };++ // Create cache directory and write file+ let cache_dir = git_path.join("wt-cache").join("ci-status");+ std::fs::create_dir_all(&cache_dir).unwrap();++ // Sanitize branch name for filename (replace / and \ with -)+ let safe_branch: String = branch+ .chars()+ .map(|c| if c == '/' || c == '\\' { '-' } else { c })+ .collect();+ let cache_file = cache_dir.join(format!("{safe_branch}.json"));+ std::fs::write(&cache_file, &cache_json).unwrap();}/// Generate README example: Basic `wt list` output