Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows
Reclaim stale temporary indexes with age-based cleanup (#4469)
jonah-osmo90da2475b06c
diff --git a/docs/src/content/docs/faq.md b/docs/src/content/docs/faq.mdindex 93070c18f..57357b4dd 100644--- a/docs/src/content/docs/faq.md+++ b/docs/src/content/docs/faq.md@@ -173,7 +173,7 @@ The OpenCode path follows `$OPENCODE_CONFIG_DIR` > `$XDG_CONFIG_HOME/opencode` >### 6. Temporary files (automatic)-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories. Later commands that create a temporary index reclaim index copies and their lock files older than one hour; object directories left by an interrupted process may still need manual cleanup.### What Worktrunk does NOT creatediff --git a/plugins/worktrunk/skills/worktrunk/reference/faq.md b/plugins/worktrunk/skills/worktrunk/reference/faq.mdindex 76543bf91..c1697b578 100644--- a/plugins/worktrunk/skills/worktrunk/reference/faq.md+++ b/plugins/worktrunk/skills/worktrunk/reference/faq.md@@ -169,7 +169,7 @@ The OpenCode path follows `$OPENCODE_CONFIG_DIR` > `$XDG_CONFIG_HOME/opencode` >### 6. Temporary files (automatic)-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories. Later commands that create a temporary index reclaim index copies and their lock files older than one hour; object directories left by an interrupted process may still need manual cleanup.### What Worktrunk does NOT creatediff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.mdindex 76543bf91..c1697b578 100644--- a/skills/worktrunk/reference/faq.md+++ b/skills/worktrunk/reference/faq.md@@ -169,7 +169,7 @@ The OpenCode path follows `$OPENCODE_CONFIG_DIR` > `$XDG_CONFIG_HOME/opencode` >### 6. Temporary files (automatic)-Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories; an interrupted process can leave one behind for manual cleanup.+Worktrunk creates temporary Git index copies named `$TMPDIR/worktrunk-temp-index-*`. `wt list`, `wt list statusline`, `wt step diff`, `wt step commit --dry-run`, and `wt switch` use them to inspect staged or working-tree state without changing the real index. `wt list` also creates a `$TMPDIR/worktrunk-list-objects-*` directory so its merge probes do not add unreachable objects to the repository. When the system temp directory is unavailable, both fall back to Git's metadata: `worktrunk-list-objects-*` under the Git common directory and `worktrunk-temp-index-*` under the worktree's Git directory. A normal exit removes these files and directories. Later commands that create a temporary index reclaim index copies and their lock files older than one hour; object directories left by an interrupted process may still need manual cleanup.### What Worktrunk does NOT creatediff --git a/src/commands/step/commit.rs b/src/commands/step/commit.rsindex 62af63075..1d2b1d264 100644--- a/src/commands/step/commit.rs+++ b/src/commands/step/commit.rs@@ -83,6 +83,9 @@ fn preview_commit(let commit_config = env.resolved().commit_generation.clone();let wt = env.repo.worktree_at(&env.worktree_path);+ let ctx = env.context(yes);+ let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;+// For --dry-run, stage to a copy of the index so the preview reflects what a real// run would send. --show-prompt skips this — it's the cheap "what's already staged"// path. StageMode::None has nothing to stage, so we use the existing index as-is.@@ -100,9 +103,6 @@ fn preview_commit(};let staging_index = temp_index.as_ref();- let ctx = env.context(yes);- let project_append = resolve_template_for_preview(&ctx, &commit_config, dry_run)?;-let prompt = crate::llm::build_commit_prompt(&commit_config,&wt,diff --git a/src/git/repository/working_tree.rs b/src/git/repository/working_tree.rsindex f32b1bd39..28cf63690 100644--- a/src/git/repository/working_tree.rs+++ b/src/git/repository/working_tree.rs@@ -3,6 +3,8 @@use std::collections::HashSet;use std::ffi::OsString;use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::time::{Duration, SystemTime};use anyhow::{Context, bail};use dashmap::mapref::entry::Entry;@@ -16,6 +18,40 @@ use super::{GitError, LineDiff, Repository};use crate::git::{CommandError, PlumbingDiff};const TEMP_INDEX_PREFIX: &str = "worktrunk-temp-index-";+const TEMP_INDEX_MAX_AGE: Duration = Duration::from_secs(60 * 60);++/// Reclaim index copies and Git's `.lock` siblings left by abrupt exits.+/// Age is a retention policy, not proof that an owner has exited: a suspended+/// operation or Git filter lasting over an hour can lose its scratch index.+/// Keep indexes out of interactive approval waits. Cleanup is best-effort;+/// normal exits still remove each index through `TempPath`.+fn sweep_stale_temp_indexes(dir: &Path) {+ let Ok(entries) = std::fs::read_dir(dir) else {+ return;+ };+ let now = SystemTime::now();+ for entry in entries.filter_map(Result::ok) {+ if !entry+ .file_name()+ .to_str()+ .is_some_and(|name| name.starts_with(TEMP_INDEX_PREFIX))+ {+ continue;+ }+ let expired = entry+ .metadata()+ .ok()+ .and_then(|metadata| metadata.modified().ok())+ .and_then(|modified| now.duration_since(modified).ok())+ .is_some_and(|age| age >= TEMP_INDEX_MAX_AGE);+ if expired && let Err(error) = std::fs::remove_file(entry.path()) {+ tracing::debug!(+ "Failed to remove stale temporary index {}: {error}",+ entry.path().display()+ );+ }+ }+}/// A squash safety backup: an immutable snapshot of the index and the ref/// whose reflog retains it. The backup commit's parent is the pre-squash HEAD.@@ -1085,11 +1121,19 @@ impl<'a> WorkingTree<'a> {// closes and removes the 0-byte file before Git creates a valid index.let mut builder = tempfile::Builder::new();builder.prefix(TEMP_INDEX_PREFIX);+ // Parallel probes don't wait for the one caller doing this sweep.+ static SWEPT_SYSTEM_TEMP: AtomicBool = AtomicBool::new(false);+ if !SWEPT_SYSTEM_TEMP.swap(true, Ordering::Relaxed) {+ sweep_stale_temp_indexes(&std::env::temp_dir());+ }let mut temp_file = match builder.tempfile() {Ok(file) => file,- Err(temp_error) => builder.tempfile_in(&git_dir).context(format!(- "Failed to create temporary index in the system temp directory or Git directory; system temp error: {temp_error}"- ))?,+ Err(temp_error) => {+ sweep_stale_temp_indexes(&git_dir);+ builder.tempfile_in(&git_dir).context(format!(+ "Failed to create temporary index in the system temp directory or Git directory; system temp error: {temp_error}"+ ))?+ }};let mut real_index_file = match std::fs::File::open(&real_index) {Ok(file) => Some(file),@@ -1494,6 +1538,45 @@ mod tests {use crate::shell_exec::Cmd;use crate::testing::TestRepo;+ #[test]+ fn sweep_stale_temp_indexes_preserves_recent_and_unrelated_entries() {+ use super::{TEMP_INDEX_MAX_AGE, sweep_stale_temp_indexes};+ use std::time::{Duration, SystemTime};++ let dir = crate::testing::test_tempdir();+ let now = SystemTime::now();+ let old = now - TEMP_INDEX_MAX_AGE - Duration::from_secs(60);+ for (name, modified) in [+ ("worktrunk-temp-index-old", old),+ ("worktrunk-temp-index-old.lock", old),+ ("worktrunk-temp-index-recent", now),+ ("worktrunk-temp-index-recent.lock", now),+ ("worktrunk-temp-index-future", now + TEMP_INDEX_MAX_AGE),+ ("unrelated", old),+ ] {+ let file = std::fs::File::create(dir.path().join(name)).unwrap();+ file.set_times(std::fs::FileTimes::new().set_modified(modified))+ .unwrap();+ }++ sweep_stale_temp_indexes(dir.path());+ let mut remaining: Vec<_> = std::fs::read_dir(dir.path())+ .unwrap()+ .map(|entry| entry.unwrap().file_name().into_string().unwrap())+ .collect();+ remaining.sort();+ assert_eq!(+ remaining,+ [+ "unrelated",+ "worktrunk-temp-index-future",+ "worktrunk-temp-index-recent",+ "worktrunk-temp-index-recent.lock",+ ]+ );+ sweep_stale_temp_indexes(&dir.path().join("missing"));+ }+#[test]fn lock_reason_errors_when_locked_is_unreadable() {let mut test = TestRepo::with_initial_commit();diff --git a/tests/integration_tests/approval_pty.rs b/tests/integration_tests/approval_pty.rsindex 27119920e..edd41a58d 100644--- a/tests/integration_tests/approval_pty.rs+++ b/tests/integration_tests/approval_pty.rs@@ -8,7 +8,9 @@//! to simulate interactive terminals. The non-PTY tests in `approval_ui.rs` verify the//! error case (non-TTY environments).-use crate::common::pty::{build_pty_command, exec_cmd_in_pty, exec_cmd_in_pty_prompted};+use crate::common::pty::{+ build_pty_command, exec_cmd_in_pty, exec_cmd_in_pty_prompted, exec_cmd_in_pty_prompted_with,+};use crate::common::{TestRepo, add_pty_binary_path_filters, add_pty_filters, repo, wt_bin};use insta::assert_snapshot;use rstest::rstest;@@ -673,6 +675,62 @@ command = "tee {prompt_capture_str} > /dev/null && echo 'feat: accept guidance'");}+/// A dry-run waits for approval before creating its temporary index, so an+/// unattended prompt cannot leave that index eligible for age-based cleanup.+#[rstest]+fn test_commit_dry_run_creates_index_after_approval(repo: TestRepo) {+ repo.write_project_config(+ r#"+[commit.generation]+template-append = "Use conventional commits"+"#,+ );+ repo.commit("Add project commit append");+ std::fs::write(repo.root_path().join("new-file.txt"), "new content").unwrap();+ let index_before = repo.git_output(&["write-tree"]);+ let head_before = repo.git_output(&["rev-parse", "HEAD"]);++ let temp_dir = worktrunk::testing::test_tempdir();+ let prompt_capture = repo.home_path().join("captured-prompt.txt");+ repo.write_test_config(&format!(+ r#"+[commit.generation]+command = "tee {} > /dev/null && echo 'feat: preview guidance'"+"#,+ prompt_capture.display()+ ));+ let mut env_vars = test_env_vars_with_shell(&repo);+ env_vars.push(("TMPDIR".into(), temp_dir.path().display().to_string()));+ env_vars.push(("GIT_PAGER".into(), "cat".into()));+ let cmd = build_pty_command(+ wt_bin().to_str().unwrap(),+ &["step", "commit", "--dry-run"],+ repo.root_path(),+ &env_vars,+ None,+ );+ let mut files_at_approval = Vec::new();+ let (output, exit_code) = exec_cmd_in_pty_prompted_with(cmd, &["y\n"], "[y/N", |_| {+ files_at_approval = std::fs::read_dir(temp_dir.path())+ .unwrap()+ .map(|entry| entry.unwrap().path())+ .collect();+ });++ assert_eq!(exit_code, 0, "Dry-run should succeed. Output:\n{output}");+ assert!(+ files_at_approval.is_empty(),+ "Approval should precede temporary-index creation: {files_at_approval:?}"+ );+ let captured = std::fs::read_to_string(&prompt_capture).unwrap();+ assert!(+ captured.contains("Use conventional commits") && captured.contains("+new content"),+ "Approved guidance and staged changes should reach the LLM:\n{captured}"+ );+ assert_eq!(repo.git_output(&["write-tree"]), index_before);+ assert_eq!(repo.git_output(&["rev-parse", "HEAD"]), head_before);+}+/// Declining the append prompt continues without it — the LLM receives the/// rest of the prompt as if no project append were configured.#[rstest]diff --git a/tests/integration_tests/step_diff.rs b/tests/integration_tests/step_diff.rsindex f0daeca9f..118830dbe 100644--- a/tests/integration_tests/step_diff.rs+++ b/tests/integration_tests/step_diff.rs@@ -127,6 +127,129 @@ fn test_step_diff_index_unchanged(mut repo: TestRepo) {);}+/// Cleanup is wired into index creation in both storage locations.+#[cfg(unix)]+#[rstest]+#[case(false)]+#[case(true)]+fn test_step_diff_sweeps_stale_indexes(repo: TestRepo, #[case] fallback: bool) {+ let scratch = worktrunk::testing::test_tempdir();+ let temp_dir = if fallback {+ scratch.path().join("missing")+ } else {+ scratch.path().to_path_buf()+ };+ let index_dir = if fallback {+ repo.root_path().join(".git")+ } else {+ temp_dir.clone()+ };+ let orphan = index_dir.join("worktrunk-temp-index-AbC123");+ let file = fs::File::create(&orphan).unwrap();+ file.set_times(std::fs::FileTimes::new().set_modified(std::time::SystemTime::UNIX_EPOCH))+ .unwrap();+ drop(file);+ // A matching directory cannot be removed as a file; cleanup must continue.+ let obstacle = index_dir.join("worktrunk-temp-index-directory");+ fs::create_dir(&obstacle).unwrap();+ fs::File::open(&obstacle)+ .unwrap()+ .set_times(std::fs::FileTimes::new().set_modified(std::time::SystemTime::UNIX_EPOCH))+ .unwrap();+ let real_index = repo.root_path().join(".git/index");+ let before = fs::read(&real_index).unwrap();+ fs::write(+ repo.root_path().join("untracked.txt"),+ "untracked content\n",+ )+ .unwrap();++ let output = repo+ .wt_command()+ .args(["step", "diff", "--", "--name-only"])+ .env("TMPDIR", &temp_dir)+ .env("RUST_LOG", "debug")+ .output()+ .unwrap();++ assert!(+ output.status.success(),+ "{}",+ String::from_utf8_lossy(&output.stderr)+ );+ assert!(+ String::from_utf8_lossy(&output.stderr).contains(&format!(+ "Failed to remove stale temporary index {}:",+ obstacle.display()+ )),+ "cleanup failure should be visible in debug logging"+ );+ assert_eq!(+ String::from_utf8(output.stdout).unwrap().trim(),+ "untracked.txt"+ );+ assert!(!orphan.exists(), "stale index must be reclaimed");+ assert!(obstacle.is_dir(), "cleanup must not remove directories");+ assert_eq!(fs::read(real_index).unwrap(), before);+ assert!(+ fs::read_dir(index_dir).unwrap().all(|entry| {+ let entry = entry.unwrap();+ entry.path() == obstacle+ || !entry+ .file_name()+ .to_string_lossy()+ .starts_with("worktrunk-temp-index-")+ }),+ "normal exit must remove the new index too"+ );+}++/// When neither storage location is writable, diff fails without touching the index.+#[cfg(unix)]+#[rstest]+fn test_step_diff_preserves_index_when_temp_index_creation_fails(repo: TestRepo) {+ use std::os::unix::fs::PermissionsExt;++ struct RestorePermissions<'a>(&'a Path, fs::Permissions);+ impl Drop for RestorePermissions<'_> {+ fn drop(&mut self) {+ let _ = fs::set_permissions(self.0, self.1.clone());+ }+ }++ let git_dir = repo.root_path().join(".git");+ let real_index = git_dir.join("index");+ let before = fs::read(&real_index).unwrap();+ fs::write(+ repo.root_path().join("untracked.txt"),+ "untracked content\n",+ )+ .unwrap();+ let permissions = fs::metadata(&git_dir).unwrap().permissions();+ let read_only = fs::Permissions::from_mode(permissions.mode() & !0o222);+ let restore = RestorePermissions(&git_dir, permissions);+ fs::set_permissions(&git_dir, read_only).unwrap();++ let scratch = worktrunk::testing::test_tempdir();+ let output = repo+ .wt_command()+ .args(["step", "diff"])+ .env("TMPDIR", scratch.path().join("missing"))+ .output()+ .unwrap();+ drop(restore);++ let stderr = String::from_utf8_lossy(&output.stderr);+ assert!(!output.status.success(), "diff unexpectedly succeeded");+ assert!(+ stderr.contains(+ "Failed to create temporary index in the system temp directory or Git directory"+ ),+ "{stderr}"+ );+ assert_eq!(fs::read(real_index).unwrap(), before);+}+/// Explicit target branch#[rstest]fn test_step_diff_explicit_target(mut repo: TestRepo) {