Skip to content

Worktrunk is a CLI for Git worktree management, designed for parallel AI agent workflows

Sweep stale .git/wt/trash entries on wt remove (#2039)

Maximilian Roos4a7219b230ae
diff --git a/.claude/skills/writing-user-outputs/SKILL.md b/.claude/skills/writing-user-outputs/SKILL.md
index d17200691..531f93f56 100644
--- a/.claude/skills/writing-user-outputs/SKILL.md
+++ b/.claude/skills/writing-user-outputs/SKILL.md
@@ -586,6 +586,17 @@ Removed worktree for bugfix
Signs of poor temporal locality: collecting messages in a buffer, single success
message for batch operations, no progress before slow operations.
+## Defer Non-Essential Work Until After Primary Output
+
+Fire-and-forget cleanup and cache sweeps run after the command's final
+user-visible message — never before. Placing them at the start delays
+time-to-first-output with work the user didn't ask for.
+
+Worktrunk marks the boundary with `WORKTRUNK_FIRST_OUTPUT`: handlers
+early-return where output begins, so work before that return is on the hot
+path, work after it is not. See `handle_remove_command` —
+`sweep_stale_trash` runs after `handle_remove_output`.
+
## Information Display: Show Once, Not Twice
Progress messages should include all relevant details (what's being done,
diff --git a/docs/content/faq.md b/docs/content/faq.md
index 63759555a..350345154 100644
--- a/docs/content/faq.md
+++ b/docs/content/faq.md
@@ -156,6 +156,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch
### Other cleanup
+- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, CI cache, markers, hints, variables, logs, stale trash)
- `wt config shell uninstall` — removes shell integration from rc files
diff --git a/docs/content/remove.md b/docs/content/remove.md
index 8f876da35..fc26b3591 100644
--- a/docs/content/remove.md
+++ b/docs/content/remove.md
@@ -61,7 +61,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. Logs are written to `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
## Hooks
diff --git a/skills/worktrunk/reference/faq.md b/skills/worktrunk/reference/faq.md
index 32cebcc96..988cc956f 100644
--- a/skills/worktrunk/reference/faq.md
+++ b/skills/worktrunk/reference/faq.md
@@ -149,6 +149,7 @@ Use `-D` to force-delete branches with unmerged changes. Use `--no-delete-branch
### Other cleanup
+- `wt remove` — in addition to the target worktree, sweeps `.git/wt/trash/` entries older than 24 hours in the background (eventual cleanup for directories orphaned when a previous background removal was interrupted)
- `wt config state clear` — removes all worktrunk data from `.git/` (config keys, CI cache, markers, hints, variables, logs, stale trash)
- `wt config shell uninstall` — removes shell integration from rc files
diff --git a/skills/worktrunk/reference/remove.md b/skills/worktrunk/reference/remove.md
index 5533fd13e..a5cd3dd91 100644
--- a/skills/worktrunk/reference/remove.md
+++ b/skills/worktrunk/reference/remove.md
@@ -65,7 +65,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. Logs are written to `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
## Hooks
diff --git a/src/cli/mod.rs b/src/cli/mod.rs
index b00195f1e..c87485058 100644
--- a/src/cli/mod.rs
+++ b/src/cli/mod.rs
@@ -975,7 +975,9 @@ Without `--force`, removal fails if the worktree contains untracked files. Witho
## Background removal
-Removal runs in the background by default — the command returns immediately. Logs are written to `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into `.git/wt/trash/` (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached `rm -rf` finishes cleanup. Cross-filesystem worktrees fall back to `git worktree remove`. Logs: `.git/wt/logs/{branch}-remove.log`. Use `--foreground` to run in the foreground.
+
+After each `wt remove`, entries in `.git/wt/trash/` older than 24 hours are swept by a detached `rm -rf` — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
## Hooks
diff --git a/src/commands/process.rs b/src/commands/process.rs
index 42b1ce54b..28669ff13 100644
--- a/src/commands/process.rs
+++ b/src/commands/process.rs
@@ -17,11 +17,13 @@ use crate::commands::hook_filter::HookSource;
/// Internal worktrunk operations that produce log files.
///
/// These are operations performed by worktrunk itself (not user-defined hooks).
-#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::Display)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString, strum::Display, strum::EnumIter)]
#[strum(serialize_all = "kebab-case")]
pub enum InternalOp {
/// Background worktree removal (`wt remove` in background mode)
Remove,
+ /// Background cleanup of stale entries in `.git/wt/trash/`
+ TrashSweep,
}
/// Specification for a hook log file.
@@ -131,9 +133,11 @@ impl HookLog {
// internal:op
["internal", op_str] => {
let op = InternalOp::from_str(op_str).map_err(|_| {
+ let valid: Vec<_> = InternalOp::iter().map(|o| o.to_string()).collect();
cformat!(
- "Unknown internal operation: <bold>{}</>. Valid: remove",
- op_str
+ "Unknown internal operation: <bold>{}</>. Valid: {}",
+ op_str,
+ valid.join(", ")
)
})?;
Ok(Self::Internal(op))
@@ -513,6 +517,82 @@ pub fn generate_removing_path(trash_dir: &Path, worktree_path: &Path) -> PathBuf
trash_dir.join(format!("{}-{}", name, timestamp))
}
+/// How old a `.git/wt/trash/` entry must be before [`sweep_stale_trash`] deletes it.
+pub const TRASH_STALE_THRESHOLD_SECS: u64 = 24 * 60 * 60;
+
+/// Fire-and-forget cleanup of stale entries in `.git/wt/trash/`.
+///
+/// Worktree removal uses a fast path that renames the worktree into
+/// `.git/wt/trash/<name>-<timestamp>/` and deletes it in a detached background
+/// process. If that process is interrupted (SIGKILL, reboot, disk full), the
+/// renamed directory is orphaned. `wt remove` calls this function after its
+/// primary user-visible output — so the sweep never delays the progress or
+/// success message — to provide eventual cleanup: entries older than
+/// [`TRASH_STALE_THRESHOLD_SECS`] are removed by a single detached `rm -rf`.
+///
+/// Best effort: directory read failures and spawn failures are logged at debug
+/// level and otherwise ignored. The sweep is purely additive — the primary
+/// `wt remove` operation proceeds regardless of outcome.
+pub fn sweep_stale_trash(repo: &Repository) {
+ let trash_dir = repo.wt_trash_dir();
+ let stale = collect_stale_trash_entries(&trash_dir, epoch_now(), TRASH_STALE_THRESHOLD_SECS);
+ if stale.is_empty() {
+ return;
+ }
+
+ // Join all paths into a single `rm -rf` invocation so we spawn one
+ // background process regardless of how many entries are stale.
+ let escaped: Vec<String> = stale
+ .iter()
+ .map(|p| shell_escape::escape(p.to_string_lossy().as_ref().into()).into_owned())
+ .collect();
+ let command = format!("rm -rf -- {}", escaped.join(" "));
+
+ if let Err(e) = spawn_detached(
+ repo,
+ &repo.wt_dir(),
+ &command,
+ "wt",
+ &HookLog::internal(InternalOp::TrashSweep),
+ None,
+ ) {
+ log::debug!("Failed to spawn stale trash sweep: {e}");
+ }
+}
+
+/// Collect paths in `trash_dir` whose embedded timestamp is older than
+/// `threshold_secs` relative to `now`.
+///
+/// Entries whose filename can't be parsed as `<name>-<timestamp>` are skipped —
+/// the sweep only touches directories worktrunk created via
+/// [`generate_removing_path`].
+fn collect_stale_trash_entries(trash_dir: &Path, now: u64, threshold_secs: u64) -> Vec<PathBuf> {
+ let Ok(read_dir) = fs::read_dir(trash_dir) else {
+ return Vec::new();
+ };
+
+ read_dir
+ .filter_map(|entry| entry.ok())
+ .filter_map(|entry| {
+ let name = entry.file_name();
+ let timestamp = parse_trash_entry_timestamp(name.to_str()?)?;
+ let age = now.saturating_sub(timestamp);
+ (age >= threshold_secs).then(|| entry.path())
+ })
+ .collect()
+}
+
+/// Extract the Unix timestamp suffix from a trash entry filename.
+///
+/// Filenames produced by [`generate_removing_path`] have the form
+/// `<name>-<timestamp>`, where timestamp is a bare unsigned integer in Unix
+/// epoch seconds. The worktree name may contain hyphens, so splitting from the
+/// right and parsing the tail is unambiguous.
+fn parse_trash_entry_timestamp(name: &str) -> Option<u64> {
+ let (_, suffix) = name.rsplit_once('-')?;
+ suffix.parse::<u64>().ok()
+}
+
/// Build shell command for background removal of a staged (renamed) worktree.
///
/// This is used after the worktree has been renamed to a staging path,
@@ -777,6 +857,10 @@ mod tests {
// Internal operation suffix
assert_eq!(HookLog::internal(InternalOp::Remove).suffix(), "remove");
+ assert_eq!(
+ HookLog::internal(InternalOp::TrashSweep).suffix(),
+ "trash-sweep"
+ );
}
#[test]
@@ -807,7 +891,7 @@ mod tests {
assert_snapshot!(HookLog::parse("user:invalid-hook:server").unwrap_err(), @"Unknown hook type: invalid-hook. Valid: pre-switch, post-switch, pre-start, post-start, pre-commit, post-commit, pre-merge, post-merge, pre-remove, post-remove");
// Unknown internal operation
- assert_snapshot!(HookLog::parse("internal:unknown").unwrap_err(), @"Unknown internal operation: unknown. Valid: remove");
+ assert_snapshot!(HookLog::parse("internal:unknown").unwrap_err(), @"Unknown internal operation: unknown. Valid: remove, trash-sweep");
// Invalid formats: single word, two non-internal parts, missing segment
assert_snapshot!(HookLog::parse("remove").unwrap_err(), @"Invalid log spec: remove. Format: source:hook-type:name or internal:op");
@@ -861,5 +945,70 @@ mod tests {
assert_eq!(spec, "internal:remove");
let parsed = HookLog::parse(&spec).unwrap();
assert_eq!(original, parsed);
+
+ // Trash sweep roundtrip
+ let original = HookLog::internal(InternalOp::TrashSweep);
+ let spec = original.to_spec();
+ assert_eq!(spec, "internal:trash-sweep");
+ let parsed = HookLog::parse(&spec).unwrap();
+ assert_eq!(original, parsed);
+ }
+
+ #[test]
+ fn test_parse_trash_entry_timestamp() {
+ // Simple name with trailing timestamp
+ assert_eq!(
+ parse_trash_entry_timestamp("feature-1700000000"),
+ Some(1700000000)
+ );
+ // Worktree name containing hyphens — split from the right
+ assert_eq!(
+ parse_trash_entry_timestamp("my-project.feature-branch-1700000000"),
+ Some(1700000000)
+ );
+ // Missing separator or non-numeric suffix → None (sweep leaves it alone)
+ assert_eq!(parse_trash_entry_timestamp("no-timestamp"), None);
+ assert_eq!(parse_trash_entry_timestamp("notimestamp"), None);
+ assert_eq!(parse_trash_entry_timestamp(""), None);
+ }
+
+ #[test]
+ fn test_collect_stale_trash_entries() {
+ let trash = tempfile::tempdir().unwrap();
+ let now: u64 = 1_700_000_000;
+ let day = TRASH_STALE_THRESHOLD_SECS;
+
+ // Stale: 2 days old
+ let stale = trash.path().join(format!("feature-old-{}", now - 2 * day));
+ fs::create_dir(&stale).unwrap();
+ // Fresh: 1 hour old
+ let fresh = trash.path().join(format!("feature-new-{}", now - 3600));
+ fs::create_dir(&fresh).unwrap();
+ // Exactly at threshold: 1 day old (inclusive)
+ let boundary = trash.path().join(format!("feature-edge-{}", now - day));
+ fs::create_dir(&boundary).unwrap();
+ // Unparsable: no timestamp suffix — sweep ignores it
+ let foreign = trash.path().join("random-folder");
+ fs::create_dir(&foreign).unwrap();
+
+ let mut collected = collect_stale_trash_entries(trash.path(), now, day);
+ collected.sort();
+ let mut expected = vec![stale, boundary];
+ expected.sort();
+ assert_eq!(collected, expected);
+ assert!(
+ fresh.exists(),
+ "fresh entries must not appear in stale list"
+ );
+ assert!(foreign.exists(), "unparsable entries must be left alone");
+ }
+
+ #[test]
+ fn test_collect_stale_trash_entries_missing_dir() {
+ let missing = std::path::PathBuf::from("/nonexistent/wt/trash/path");
+ assert!(
+ collect_stale_trash_entries(&missing, 1_700_000_000, TRASH_STALE_THRESHOLD_SECS)
+ .is_empty()
+ );
}
}
diff --git a/src/commands/worktree/mod.rs b/src/commands/worktree/mod.rs
index 338957337..5eafc7e89 100644
--- a/src/commands/worktree/mod.rs
+++ b/src/commands/worktree/mod.rs
@@ -110,6 +110,12 @@ pub use types::{
/// On the fast path the directory disappears instantly; the caller is responsible
/// for cleaning up the staged trash entry (returned via `staged_path`).
///
+/// Called from the synchronous (foreground) removal path and from the TUI picker.
+/// The background removal path (`output::handlers::spawn_background_removal`)
+/// uses `stage_worktree_removal` directly so it can defer the `rm -rf` to a
+/// detached process. See `handle_remove_command` in `main.rs` for the full
+/// `wt remove` command flow.
+///
/// `branch_result` is the raw `delete_branch_if_safe` outcome, preserved so
/// callers can handle branch deletion failures independently:
/// - The picker ignores it (best-effort in TUI context)
diff --git a/src/main.rs b/src/main.rs
index b3baa4879..42129de54 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -706,6 +706,28 @@ fn validate_remove_targets(
plans
}
+/// Entry point for the `wt remove` command.
+///
+/// # Command flow
+///
+/// 1. **Validate** all target worktrees up front via `prepare_worktree_removal`
+/// (clean check, branch-deletion-safety check, force-flag handling).
+/// 2. **Approve hooks** (`pre-remove`, `post-remove`, `post-switch`) if
+/// running interactively and any hooks are configured.
+/// 3. **Dispatch to `handle_remove_output`** per target. For each, the output
+/// handler runs `pre-remove` hooks in the worktree, then either:
+/// - **Foreground** (`--foreground`): stop fsmonitor → rename into
+/// `.git/wt/trash/<name>-<timestamp>/` → prune metadata → delete branch
+/// → synchronous `remove_dir_all` on the staged directory.
+/// - **Background** (default): stop fsmonitor → rename + prune +
+/// synchronous branch delete → spawn detached `rm -rf` on the staged
+/// directory. Cross-filesystem or locked worktrees fall back to
+/// `git worktree remove` in the detached process.
+/// 4. **Post-remove hooks** run in the background after dispatch.
+/// 5. **Sweep stale trash** (fire-and-forget, after primary output): entries
+/// in `.git/wt/trash/` older than 24 hours are removed by a detached
+/// `rm -rf`. Runs last so it never delays the user-visible progress or
+/// success message. See [`commands::process::sweep_stale_trash`].
fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
let json_mode = args.format == SwitchFormat::Json;
let verify = resolve_verify(args.verify, args.no_verify_deprecated);
@@ -781,6 +803,10 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
let json = serde_json::json!([result.to_json()]);
println!("{}", serde_json::to_string_pretty(&json)?);
}
+ // Fire-and-forget cleanup of stale `.git/wt/trash/` entries —
+ // runs after primary output so it never delays the user-visible
+ // progress/success message.
+ commands::process::sweep_stale_trash(&repo);
Ok(())
} else {
// Multi-worktree removal: validate ALL first, then approve, then execute
@@ -831,6 +857,11 @@ fn handle_remove_command(args: RemoveArgs) -> anyhow::Result<()> {
println!("{}", serde_json::to_string_pretty(&json_items)?);
}
+ // Fire-and-forget cleanup of stale `.git/wt/trash/` entries —
+ // runs after primary output so it never delays the user-visible
+ // progress/success messages.
+ commands::process::sweep_stale_trash(&repo);
+
if !plans.errors.is_empty() {
anyhow::bail!("");
}
diff --git a/tests/integration_tests/remove.rs b/tests/integration_tests/remove.rs
index c2ddf187b..574f41a01 100644
--- a/tests/integration_tests/remove.rs
+++ b/tests/integration_tests/remove.rs
@@ -2546,6 +2546,55 @@ fn test_remove_stale_staging_dir_from_crashed_removal(mut repo: TestRepo) {
);
}
+/// `wt remove` sweeps `.git/wt/trash/` entries older than 24 hours.
+///
+/// Each run of `wt remove` fires a detached `rm -rf` on trash entries whose
+/// encoded timestamp is more than a day in the past. This provides eventual
+/// cleanup for directories orphaned when a previous background removal was
+/// interrupted. Fresh entries (from recent or in-flight removals) are left
+/// alone so concurrent removals don't race.
+#[rstest]
+fn test_remove_sweeps_stale_trash_entries(mut repo: TestRepo) {
+ let git_common_dir = crate::common::resolve_git_common_dir(repo.root_path());
+ let trash_dir = git_common_dir.join("wt/trash");
+ std::fs::create_dir_all(&trash_dir).unwrap();
+
+ // Pre-populate the trash directory with a stale entry (2 days old) and a
+ // fresh entry (just created). The stale entry should be swept; the fresh
+ // entry should survive.
+ let day = 24 * 60 * 60;
+ let stale_timestamp = crate::common::TEST_EPOCH - 2 * day;
+ let stale_entry = trash_dir.join(format!("orphan-stale-{stale_timestamp}"));
+ let fresh_entry = trash_dir.join(format!("orphan-fresh-{}", crate::common::TEST_EPOCH));
+ std::fs::create_dir(&stale_entry).unwrap();
+ std::fs::write(stale_entry.join("marker"), "leftover").unwrap();
+ std::fs::create_dir(&fresh_entry).unwrap();
+ std::fs::write(fresh_entry.join("marker"), "recent").unwrap();
+
+ // Create and remove a real worktree to trigger the sweep, which runs after
+ // the primary `wt remove` output has been printed.
+ let _ = repo.add_worktree("feature-sweep");
+ let output = repo
+ .wt_command()
+ .args(["remove", "feature-sweep"])
+ .output()
+ .unwrap();
+ assert!(
+ output.status.success(),
+ "wt remove should succeed: {}",
+ String::from_utf8_lossy(&output.stderr)
+ );
+
+ // The stale entry is removed by a detached `rm -rf` — poll for absence.
+ crate::common::wait_for("stale trash entry swept", || !stale_entry.exists());
+
+ // The fresh entry must survive — only entries older than 24 hours are swept.
+ assert!(
+ fresh_entry.exists(),
+ "fresh trash entry (age 0) must not be swept"
+ );
+}
+
/// Tests that foreground removal shows remaining directory entries when
/// `git worktree remove` fails because a directory can't be deleted.
///
diff --git a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
index 222eb670e..b345d8f4e 100644
--- a/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
+++ b/tests/snapshots/integration__integration_tests__help__help_remove_long.snap
@@ -141,7 +141,9 @@ Without --force, removal fails if the worktree contains untracked files.
Background removal
-Removal runs in the background by default — the command returns immediately. Logs are written to .git/wt/logs/{branch}-remove.log. Use --foreground to run in the foreground.
+Removal runs in the background by default — the command returns immediately. The worktree is renamed into .git/wt/trash/ (instant same-filesystem rename), git metadata is pruned, the branch is deleted, and a detached rm -rf finishes cleanup. Cross-filesystem worktrees fall back to git worktree remove. Logs: .git/wt/logs/{branch}-remove.log. Use --foreground to run in the foreground.
+
+After each wt remove, entries in .git/wt/trash/ older than 24 hours are swept by a detached rm -rf — eventual cleanup for directories orphaned when a previous background removal was interrupted (SIGKILL, reboot, disk full).
Hooks