Skip to content

armgit / agtx

Public Imported from GitHub
0

πŸ„πŸΌβ€β™‚οΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.

fix: worktree cleanup correctness and stale phase status (#150)

Fynn Fluegge8c2e4b60150d
diff --git a/CLAUDE.md b/CLAUDE.md
index 9cd8fd6..0d209ef 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -74,7 +74,7 @@ src/
β”œβ”€β”€ git/
β”‚ β”œβ”€β”€ mod.rs # is_git_repo, repo_root, current_branch, diff_stat/diff_full,
β”‚ # merge_branch, check_merge_conflicts, delete_branch
-β”‚ β”œβ”€β”€ worktree.rs # Git worktree create/remove/list
+β”‚ β”œβ”€β”€ worktree.rs # Git worktree create/list, is_main_working_tree
β”‚ β”œβ”€β”€ operations.rs # GitOperations trait (mockable for testing)
β”‚ └── provider.rs # GitProviderOperations trait (GitHub PR ops)
β”œβ”€β”€ agent/
@@ -175,6 +175,36 @@ Backlog β†’ Planning β†’ Running β†’ Review β†’ Done
Backlog tasks can also skip straight to Running (`M`), and Running can be sent back to Planning (`r`).
+#### Removing a worktree
+
+`RealGitOps::remove_worktree` (`git/operations.rs`) is the only implementation any production path
+uses; all three cleanup paths β€” Review β†’ Done, force-move to Done, and task delete (`x`) β€” go through
+it, and all three run on a background thread.
+
+Three properties, none of them incidental:
+
+- **A main working tree is refused, and the refusal is a no-op returning `Ok`.** Under
+ `skip_worktree` a task's `worktree_path` *is* the project root, so this is genuinely reachable with
+ the user's own checkout as the argument. git refuses it too, but that protection is inherited
+ rather than intended, and `fs::rename` β€” what a background trash directory would use instead β€” has
+ no concept of a main working tree at all.
+- **`is_main_working_tree` checks the toplevel, not just the git dir.** `--git-dir` ==
+ `--git-common-dir` alone is not enough: the default `worktree_dir` is `.agtx/worktrees`, *inside*
+ the project, so a worktree there that has lost its `.git` link makes git walk up and answer for the
+ main repository. Without the `--show-toplevel` half, exactly the half-deleted worktrees that most
+ need removing would be refused as if they were the user's checkout.
+- **A failed removal prunes and returns `Err`.** Measured against git 2.49: a *deleted* worktree
+ directory is handled by `git worktree remove` itself (exit 0), but a worktree whose `.git` link is
+ missing, or whose directory has been replaced by a file, fails with exit 128 and stays in
+ `git worktree list` β€” and `git worktree prune` is what clears it. A locked worktree fails and prune
+ does **not** clear it, which is why the error is propagated rather than only pruned away. Callers
+ log it; swallowing the exit status is what let a stale registration sit unnoticed.
+
+`delete_task_resources` removes the worktree independently of whether a branch exists β€” a task can
+have a worktree and no branch. Branch deletion stays paired with having had a worktree on purpose: a
+task with a branch and no worktree is one that reached Done, whose branch the workflow keeps, and
+`delete_branch` is `git branch -D`.
+
### Workflow Plugins
Plugins customize the task lifecycle per phase. A plugin is a TOML file (`plugin.toml`) that defines:
- **commands**: Slash commands sent to the agent at each phase (auto-translated per agent). Supports `preresearch` (one-time setup) and `research` (default research command).
diff --git a/src/git/operations.rs b/src/git/operations.rs
index b5b1457..23f9908 100644
--- a/src/git/operations.rs
+++ b/src/git/operations.rs
@@ -1,6 +1,6 @@
//! Traits for git operations to enable testing with mocks.
-use anyhow::Result;
+use anyhow::{Context, Result};
use std::path::Path;
#[cfg(feature = "test-mocks")]
@@ -98,11 +98,46 @@ impl GitOperations for RealGitOps {
}
fn remove_worktree(&self, project_path: &Path, worktree_path: &str) -> Result<()> {
- std::process::Command::new("git")
+ let path = Path::new(worktree_path);
+
+ // Refuse a main working tree before anything else. Under `skip_worktree`
+ // a task's worktree_path *is* the project root, so this is reachable with
+ // the user's own checkout as the argument. Returning Ok matches what git
+ // does today; making it explicit is what keeps the error propagation
+ // below honest, since otherwise every skip_worktree cleanup would report
+ // a failure for an expected no-op.
+ let same_as_project = match (path.canonicalize(), project_path.canonicalize()) {
+ (Ok(a), Ok(b)) => a == b,
+ _ => false,
+ };
+ if same_as_project || super::is_main_working_tree(path) {
+ return Ok(());
+ }
+
+ let output = std::process::Command::new("git")
.current_dir(project_path)
.args(["worktree", "remove", "--force", worktree_path])
- .output()?;
- Ok(())
+ .output()
+ .context("Failed to run `git worktree remove`")?;
+
+ if output.status.success() {
+ return Ok(());
+ }
+
+ // The removal failed, so git still has this worktree registered against a
+ // path it may no longer be able to reach. Prune drops registrations whose
+ // directory is gone; without it a single failed removal leaves
+ // `git worktree list` wrong permanently, not just until the next attempt.
+ let _ = std::process::Command::new("git")
+ .current_dir(project_path)
+ .args(["worktree", "prune"])
+ .output();
+
+ anyhow::bail!(
+ "git worktree remove failed for '{}': {}",
+ worktree_path,
+ String::from_utf8_lossy(&output.stderr).trim()
+ )
}
fn worktree_exists(&self, project_path: &Path, task_slug: &str, worktree_dir: &str) -> bool {
diff --git a/src/git/worktree.rs b/src/git/worktree.rs
index 9898795..bfadd07 100644
--- a/src/git/worktree.rs
+++ b/src/git/worktree.rs
@@ -324,28 +324,60 @@ pub fn detect_main_branch(project_path: &Path) -> Result<String> {
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
-/// Remove a git worktree
-pub fn remove_worktree(project_path: &Path, task_id: &str, worktree_dir: &str) -> Result<()> {
- let wt_path = worktree_path(project_path, task_id, worktree_dir);
-
- // Remove the worktree
- let output = Command::new("git")
- .current_dir(project_path)
- .args(["worktree", "remove"])
- .arg(&wt_path)
- .args(["--force"]) // Force in case of uncommitted changes
- .output()
- .context("Failed to remove git worktree")?;
-
- if !output.status.success() {
- // Try to prune if remove failed
- Command::new("git")
- .current_dir(project_path)
- .args(["worktree", "prune"])
- .output()?;
+/// True when `path` is a repository's *main* working tree rather than a linked
+/// worktree.
+///
+/// This is the shape `skip_worktree` produces: a task's `worktree_path` is the
+/// user's own checkout, and every cleanup path then asks for that to be removed.
+/// git already refuses ("is a main working tree"), so today the protection is
+/// inherited rather than intended β€” and `fs::rename`, which a background trash
+/// would use instead, has no such concept.
+///
+/// Two conditions, and both are needed:
+///
+/// - `--git-dir` == `--git-common-dir`. A linked worktree's git dir is
+/// `{repo}/.git/worktrees/{name}` while its common dir is `{repo}/.git`.
+/// - `--show-toplevel` is `path` itself.
+///
+/// The second is not redundant. The default `worktree_dir` is `.agtx/worktrees`,
+/// *inside* the project, so a worktree there that has lost its `.git` link makes
+/// git walk up to the main repository and report the first condition as true.
+/// Without the toplevel check, exactly the half-deleted worktrees that most need
+/// removing would be refused as if they were the user's checkout.
+pub fn is_main_working_tree(path: &Path) -> bool {
+ if !path.is_dir() {
+ return false;
+ }
+ let rev_parse = |args: &[&str]| -> Option<String> {
+ let out = Command::new("git")
+ .current_dir(path)
+ .args(args)
+ .output()
+ .ok()?;
+ out.status
+ .success()
+ .then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
+ .filter(|s| !s.is_empty())
+ };
+
+ let common = rev_parse(&["rev-parse", "--path-format=absolute", "--git-common-dir"]);
+ let dir = rev_parse(&["rev-parse", "--path-format=absolute", "--git-dir"]);
+ match (common, dir) {
+ (Some(common), Some(dir)) if common == dir => {}
+ // A linked worktree, not a repository at all, or a git too old for
+ // --path-format. Not provably a main working tree, so this does not
+ // block the removal; the caller's project-root comparison is the second
+ // line of defence.
+ _ => return false,
}
- Ok(())
+ let Some(toplevel) = rev_parse(&["rev-parse", "--show-toplevel"]) else {
+ return false;
+ };
+ match (Path::new(&toplevel).canonicalize(), path.canonicalize()) {
+ (Ok(top), Ok(this)) => top == this,
+ _ => false,
+ }
}
/// Get the worktree path for a task
diff --git a/src/tui/app.rs b/src/tui/app.rs
index d45abe3..a74cc12 100644
--- a/src/tui/app.rs
+++ b/src/tui/app.rs
@@ -3949,6 +3949,14 @@ impl App {
task.status = TaskStatus::Done;
task.updated_at = chrono::Utc::now();
db.update_task(&task)?;
+
+ // Same clearing the other transitions do. Without it the card
+ // keeps whatever the last refresh saw β€” a Done task showing
+ // "Working" β€” because nothing refreshes Done to correct it.
+ self.state.stuck_task_notified.remove(&task.id);
+ self.state.stuck_task_idle_since.remove(&task.id);
+ self.state.phase_status_cache.remove(&task.id);
+
self.refresh_tasks()?;
// Cleanup in background (archive, kill tmux, remove worktree)
@@ -5622,14 +5630,29 @@ impl App {
} else {
self.state.config.cleanup_script.clone()
};
- delete_task_resources(
- &task,
- cleanup_script.as_deref(),
- project_path,
- self.state.tmux_ops.as_ref(),
- self.state.git_ops.as_ref(),
- );
+ // Drop the task from the board first, then clean up behind it.
+ // The recursive worktree delete is the whole of the freeze this
+ // used to cause, and nothing below needs the card to still exist.
db.delete_task(&task.id)?;
+
+ self.state.stuck_task_notified.remove(&task.id);
+ self.state.stuck_task_idle_since.remove(&task.id);
+ self.state.phase_status_cache.remove(&task.id);
+ self.state.pane_content_hashes.remove(&task.id);
+
+ let tmux_ops = Arc::clone(&self.state.tmux_ops);
+ let git_ops = Arc::clone(&self.state.git_ops);
+ let project_path = project_path.clone();
+ std::thread::spawn(move || {
+ delete_task_resources(
+ &task,
+ cleanup_script.as_deref(),
+ &project_path,
+ tmux_ops.as_ref(),
+ git_ops.as_ref(),
+ );
+ });
+
self.refresh_tasks()?;
}
}
@@ -7872,13 +7895,7 @@ impl App {
.board
.tasks
.iter()
- .filter(|t| {
- matches!(
- t.status,
- TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
- ) || (t.status == TaskStatus::Backlog && t.session_name.is_some())
- })
- .filter(|t| t.worktree_path.is_some() || t.session_name.is_some())
+ .filter(|t| has_live_phase_status(t))
.filter(|t| {
self.state
.phase_status_cache
@@ -8138,6 +8155,27 @@ impl App {
let now = Instant::now();
for task_status in result.statuses {
+ // The refresh ran on a thread, so the task may have moved on since
+ // it was selected. A Done task has no window, no worktree and no
+ // agent, so every PhaseStatus is meaningless for it β€” and nothing
+ // refreshes Done, so a value written here would sit on the card
+ // forever. That is how a task moved to Done kept reading "Working".
+ //
+ // Only a task that is *on the board and no longer live* is dropped.
+ // Absent means deleted or not yet reloaded, which are not the same
+ // thing, and treating them as stale would discard good results
+ // whenever this lands between a DB write and `refresh_tasks`.
+ if self
+ .state
+ .board
+ .tasks
+ .iter()
+ .any(|t| t.id == task_status.task_id && !has_live_phase_status(t))
+ {
+ self.state.phase_status_cache.remove(&task_status.task_id);
+ continue;
+ }
+
let mut phase = task_status.phase_status;
// A trust prompt outranks every liveness signal below it. The agent is
@@ -8630,6 +8668,21 @@ fn copy_back_to_project(worktree: &Path, project_root: &Path, entries: &[String]
}
}
+/// Whether a task can have a meaningful phase status right now.
+///
+/// Both halves of the refresh contract read this: `maybe_spawn_session_refresh`
+/// to decide what to poll, and `apply_session_refresh` to decide what to keep.
+/// They must agree β€” the refresh runs on a thread, so a task can leave a
+/// refreshable status between being selected and its result coming back, and
+/// nothing polls Done to correct a value written after the fact.
+fn has_live_phase_status(task: &Task) -> bool {
+ let refreshable = matches!(
+ task.status,
+ TaskStatus::Planning | TaskStatus::Running | TaskStatus::Review
+ ) || (task.status == TaskStatus::Backlog && task.session_name.is_some());
+ refreshable && (task.worktree_path.is_some() || task.session_name.is_some())
+}
+
/// Generate a URL-safe slug from task ID and title
fn generate_task_slug(task_id: &str, title: &str) -> String {
let title_slug: String = title
@@ -8679,52 +8732,6 @@ fn run_cleanup_script_for_worktree(cleanup_script: Option<&str>, worktree_path:
}
}
-/// Cleanup task resources (tmux window, cleanup script, git worktree) and mark as done
-/// Modifies the task in place, ready for database update
-fn cleanup_task_for_done(
- task: &mut Task,
- cleanup_script: Option<&str>,
- project_path: &Path,
- tmux_ops: &dyn TmuxOperations,
- git_ops: &dyn GitOperations,
-) {
- // Archive artifacts before removing worktree
- if let Some(worktree) = &task.worktree_path {
- let artifacts_dir = Path::new(worktree).join(".agtx");
- if artifacts_dir.exists() {
- let slug = task
- .branch_name
- .as_deref()
- .and_then(|b| b.rsplit_once('/').map(|(_, s)| s))
- .unwrap_or(&task.id);
- let archive_dir = project_path.join(".agtx").join("archive").join(slug);
- if let Ok(()) = std::fs::create_dir_all(&archive_dir) {
- if let Ok(entries) = std::fs::read_dir(&artifacts_dir) {
- for entry in entries.flatten() {
- let path = entry.path();
- if path.is_file() && path.extension().map_or(false, |ext| ext == "md") {
- let _ = std::fs::copy(&path, archive_dir.join(entry.file_name()));
- }
- }
- }
- }
- }
- }
-
- if let Some(session_name) = &task.session_name {
- let _ = tmux_ops.kill_window(session_name);
- }
- if let Some(worktree) = &task.worktree_path {
- run_cleanup_script_for_worktree(cleanup_script, Path::new(worktree));
- let _ = git_ops.remove_worktree(project_path, worktree);
- }
- // Keep the branch so task can be reopened later
- task.session_name = None;
- task.worktree_path = None;
- task.status = TaskStatus::Done;
- task.updated_at = chrono::Utc::now();
-}
-
/// Background-safe cleanup: archive artifacts, kill tmux window, run cleanup script, remove worktree.
/// Takes owned/cloned values so it can run in a spawned thread.
fn cleanup_task_resources(
@@ -8777,7 +8784,9 @@ fn cleanup_task_resources(
}
if let Some(worktree) = worktree_path {
run_cleanup_script_for_worktree(cleanup_script, Path::new(worktree));
- let _ = git_ops.remove_worktree(project_path, worktree);
+ if let Err(e) = git_ops.remove_worktree(project_path, worktree) {
+ tracing::warn!(worktree = %worktree, error = %e, "Failed to remove worktree");
+ }
}
}
@@ -9024,11 +9033,22 @@ fn delete_task_resources(
let _ = tmux_ops.kill_window(session_name);
}
- // Remove worktree and delete branch if exists
+ // Removing the worktree does not depend on there being a branch. Nesting the
+ // two leaked the checkout for every task that had a worktree and no branch β€”
+ // a setup that failed after `create_worktree`, or a worktree created for a
+ // research session that never reached Planning.
if let Some(ref worktree) = task.worktree_path {
+ run_cleanup_script_for_worktree(cleanup_script, Path::new(worktree));
+ if let Err(e) = git_ops.remove_worktree(project_path, worktree) {
+ tracing::warn!(worktree = %worktree, error = %e, "Failed to remove worktree");
+ }
+
+ // Deleting the branch stays paired with having had a worktree, and is not
+ // hoisted out with the removal above. A task with a branch but no worktree
+ // is one that reached Done, where the workflow keeps the branch on
+ // purpose β€” and `delete_branch` is `git branch -D`, so hoisting it would
+ // silently force-delete work the user was told was preserved.
if let Some(ref branch_name) = task.branch_name {
- run_cleanup_script_for_worktree(cleanup_script, Path::new(worktree));
- let _ = git_ops.remove_worktree(project_path, worktree);
let _ = git_ops.delete_branch(project_path, branch_name);
}
}
diff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rs
index 5221378..9f9f26f 100644
--- a/src/tui/app_tests.rs
+++ b/src/tui/app_tests.rs
@@ -1466,76 +1466,6 @@ fn test_tmux_safe_session_name_replaces_dots() {
assert!(!name.contains('.'));
}
-// =============================================================================
-// Tests for cleanup_task_for_done
-// =============================================================================
-
-/// Test cleanup_task_for_done cleans up resources
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_cleanup_task_for_done_with_resources() {
- use crate::db::Task;
-
- let mut mock_tmux = MockTmuxOperations::new();
- let mut mock_git = MockGitOperations::new();
-
- mock_tmux
- .expect_kill_window()
- .with(mockall::predicate::eq("project:task-window"))
- .times(1)
- .returning(|_| Ok(()));
-
- mock_git
- .expect_remove_worktree()
- .with(
- mockall::predicate::eq(Path::new("/project")),
- mockall::predicate::eq("/tmp/worktree"),
- )
- .times(1)
- .returning(|_, _| Ok(()));
-
- let mut task = Task::new("Test task", "claude", "project-1");
- task.session_name = Some("project:task-window".to_string());
- task.worktree_path = Some("/tmp/worktree".to_string());
- task.status = TaskStatus::Review;
-
- cleanup_task_for_done(
- &mut task,
- None,
- Path::new("/project"),
- &mock_tmux,
- &mock_git,
- );
-
- assert!(task.session_name.is_none());
- assert!(task.worktree_path.is_none());
- assert_eq!(task.status, TaskStatus::Done);
-}
-
-/// Test cleanup_task_for_done handles missing resources gracefully
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_cleanup_task_for_done_no_resources() {
- use crate::db::Task;
-
- let mock_tmux = MockTmuxOperations::new();
- let mock_git = MockGitOperations::new();
- // No expectations - functions should not be called
-
- let mut task = Task::new("Test task", "claude", "project-1");
- // No session_name or worktree_path set
-
- cleanup_task_for_done(
- &mut task,
- None,
- Path::new("/project"),
- &mock_tmux,
- &mock_git,
- );
-
- assert_eq!(task.status, TaskStatus::Done);
-}
-
// =============================================================================
// Tests for delete_task_resources
// =============================================================================
@@ -8397,6 +8327,73 @@ fn test_apply_session_refresh_ready_inserts_cache() {
assert!(!app.state.pane_content_hashes.contains_key("t1"));
}
+/// A refresh spawned while the task was in Review can land after it reached
+/// Done. Nothing refreshes Done, so whatever was written then stays on the card
+/// β€” which is how a finished task went on showing "● Working" in its footer.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_drops_results_for_a_task_that_reached_done() {
+ let mut app = make_test_app();
+
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("Finished feature", "claude", "test-project");
+ task.id = "t1".to_string();
+ // Done: cleanup has cleared both, which is exactly why no phase status can
+ // be meaningful any more.
+ task.status = TaskStatus::Done;
+ task.worktree_path = None;
+ task.session_name = None;
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ // A result from the refresh that was already in flight when it moved.
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Review,
+ PhaseStatus::Working,
+ false,
+ )],
+ };
+ app.apply_session_refresh(result);
+
+ assert!(
+ !app.state.phase_status_cache.contains_key("t1"),
+ "a Done task must not keep a phase status; the card renders it as a label"
+ );
+}
+
+/// The same guard must not throw away a live task's result.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_apply_session_refresh_keeps_results_for_a_live_task() {
+ let mut app = make_test_app();
+
+ let db = app.state.db.as_ref().unwrap();
+ let mut task = Task::new("In progress", "claude", "test-project");
+ task.id = "t1".to_string();
+ task.status = TaskStatus::Running;
+ task.worktree_path = Some("/tmp/wt".to_string());
+ db.create_task(&task).unwrap();
+ app.refresh_tasks().unwrap();
+
+ let result = SessionRefreshResult {
+ statuses: vec![make_session_task_status(
+ "t1",
+ TaskStatus::Running,
+ PhaseStatus::Working,
+ false,
+ )],
+ };
+ app.apply_session_refresh(result);
+
+ assert_eq!(
+ app.state.phase_status_cache["t1"].0,
+ PhaseStatus::Working,
+ "a Running task with a worktree still gets its status"
+ );
+}
+
// ── hook-reported status ─────────────────────────────────────────────────────
#[cfg(feature = "test-mocks")]
@@ -8638,6 +8635,10 @@ fn test_apply_session_refresh_newly_ready_notifies_orchestrator() {
let mut task = Task::new("My feature", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Planning;
+ // A Planning task always has a worktree; without one the refresh would
+ // never have selected it, and `apply_session_refresh` drops results for
+ // tasks that cannot have a live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -8914,6 +8915,10 @@ fn test_handle_review_confirm_y_starts_pr_generation() {
let mut task = Task::new("My feature", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -8951,6 +8956,10 @@ fn test_handle_review_confirm_n_moves_without_pr() {
let mut task = Task::new("My feature", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -10607,6 +10616,10 @@ fn test_stuck_task_notification_fires_after_1_min_idle() {
let mut task = Task::new("stuck task", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -10656,6 +10669,10 @@ fn test_stuck_task_notification_does_not_fire_before_1_min() {
let mut task = Task::new("pending task", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -10701,6 +10718,10 @@ fn test_stuck_task_notification_fires_once_per_phase() {
let mut task = Task::new("my task", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -10746,6 +10767,10 @@ fn test_stuck_task_notification_not_fired_without_orchestrator() {
let mut task = Task::new("my task", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -10789,6 +10814,10 @@ fn test_stuck_task_idle_since_cleared_when_not_idle() {
let mut task = Task::new("my task", "claude", "test-project");
task.id = "t1".to_string();
task.status = TaskStatus::Running;
+ // A Running task always has a worktree; the refresh only selects tasks that
+ // do, and `apply_session_refresh` drops results for ones that cannot have a
+ // live phase status.
+ task.worktree_path = Some("/tmp/test-project/.agtx/worktrees/t1".to_string());
db.create_task(&task).unwrap();
app.refresh_tasks().unwrap();
@@ -11013,7 +11042,7 @@ fn test_transform_skill_for_opencode_uses_description_from_frontmatter() {
// =============================================================================
// Tests for mock-dependent functions: is_pane_at_shell, is_agent_active,
-// collect_task_diff, cleanup_task_for_done, cleanup_task_resources,
+// collect_task_diff, cleanup_task_resources,
// delete_task_resources, save_task
// =============================================================================
@@ -11173,63 +11202,6 @@ fn test_collect_task_diff_untracked_excluded_by_prefix() {
);
}
-// --- cleanup_task_for_done ---
-
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_cleanup_task_for_done_clears_session_and_worktree() {
- let mut mock_tmux = MockTmuxOperations::new();
- mock_tmux
- .expect_kill_window()
- .withf(|name: &str| name == "proj:task-1")
- .times(1)
- .returning(|_| Ok(()));
-
- let mut mock_git = MockGitOperations::new();
- mock_git
- .expect_remove_worktree()
- .times(1)
- .returning(|_, _| Ok(()));
-
- let mut task = make_test_task("t1", "My task", TaskStatus::Review);
- task.session_name = Some("proj:task-1".to_string());
- task.worktree_path = Some("/tmp/nonexistent-wt".to_string());
-
- cleanup_task_for_done(
- &mut task,
- None,
- Path::new("/tmp/proj"),
- &mock_tmux,
- &mock_git,
- );
-
- assert_eq!(task.status, TaskStatus::Done);
- assert!(task.session_name.is_none());
- assert!(task.worktree_path.is_none());
-}
-
-#[test]
-#[cfg(feature = "test-mocks")]
-fn test_cleanup_task_for_done_no_ops_when_no_session_or_worktree() {
- // No session or worktree β†’ kill_window and remove_worktree must NOT be called
- let mock_tmux = MockTmuxOperations::new();
- let mock_git = MockGitOperations::new();
-
- let mut task = make_test_task("t2", "My task", TaskStatus::Review);
- task.session_name = None;
- task.worktree_path = None;
-
- cleanup_task_for_done(
- &mut task,
- None,
- Path::new("/tmp/proj"),
- &mock_tmux,
- &mock_git,
- );
-
- assert_eq!(task.status, TaskStatus::Done);
-}
-
/// `.agtx/status/` is runtime scratch written by agent hooks, not a phase
/// artifact. The archive step only copies top-level `.md` files, so it is
/// excluded today β€” this pins that, since a future recursive archive would
@@ -11256,7 +11228,17 @@ fn test_cleanup_does_not_archive_hook_status_files() {
task.worktree_path = Some(wt.path().to_string_lossy().to_string());
task.branch_name = Some("task/my-slug".to_string());
- cleanup_task_for_done(&mut task, None, project_dir.path(), &mock_tmux, &mock_git);
+ cleanup_task_resources(
+ &task.id,
+ &task.agent,
+ &task.branch_name,
+ &task.session_name,
+ &task.worktree_path,
+ None,
+ project_dir.path(),
+ &mock_tmux,
+ &mock_git,
+ );
let archived = project_dir
.path()
@@ -11271,7 +11253,7 @@ fn test_cleanup_does_not_archive_hook_status_files() {
#[test]
#[cfg(feature = "test-mocks")]
-fn test_cleanup_task_for_done_archives_md_files() {
+fn test_cleanup_task_resources_archives_md_files() {
use std::io::Write;
let mock_tmux = MockTmuxOperations::new();
@@ -11292,7 +11274,17 @@ fn test_cleanup_task_for_done_archives_md_files() {
task.worktree_path = Some(wt.path().to_string_lossy().to_string());
task.branch_name = Some("task/my-slug".to_string());
- cleanup_task_for_done(&mut task, None, project_dir.path(), &mock_tmux, &mock_git);
+ cleanup_task_resources(
+ &task.id,
+ &task.agent,
+ &task.branch_name,
+ &task.session_name,
+ &task.worktree_path,
+ None,
+ project_dir.path(),
+ &mock_tmux,
+ &mock_git,
+ );
// Archived file should exist under .agtx/archive/my-slug/plan.md
let archive = project_dir
@@ -11312,12 +11304,17 @@ fn test_cleanup_task_resources_kills_window_and_removes_worktree() {
let mut mock_tmux = MockTmuxOperations::new();
mock_tmux
.expect_kill_window()
+ .with(mockall::predicate::eq("proj:task-win"))
.times(1)
.returning(|_| Ok(()));
let mut mock_git = MockGitOperations::new();
mock_git
.expect_remove_worktree()
+ .with(
+ mockall::predicate::eq(Path::new("/tmp/proj")),
+ mockall::predicate::eq("/tmp/wt"),
+ )
.times(1)
.returning(|_, _| Ok(()));
@@ -11356,6 +11353,53 @@ fn test_cleanup_task_resources_noop_when_no_session_or_worktree() {
// --- delete_task_resources ---
+/// A task can have a worktree and no branch: setup that failed after
+/// `create_worktree`, or a research session that never reached Planning.
+/// Removal used to be nested inside the branch check, so those checkouts were
+/// left on disk forever.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_removes_worktree_without_a_branch() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+ mock_git
+ .expect_remove_worktree()
+ .with(
+ mockall::predicate::eq(Path::new("/tmp/proj")),
+ mockall::predicate::eq("/tmp/wt"),
+ )
+ .times(1)
+ .returning(|_, _| Ok(()));
+ // No branch, so nothing to delete.
+ mock_git.expect_delete_branch().times(0);
+
+ let mut task = make_test_task("t-nobranch", "Half-set-up task", TaskStatus::Planning);
+ task.session_name = None;
+ task.worktree_path = Some("/tmp/wt".to_string());
+ task.branch_name = None;
+
+ delete_task_resources(&task, None, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+}
+
+/// The converse is deliberately *not* symmetric. A task with a branch and no
+/// worktree is one that reached Done, where the workflow keeps the branch on
+/// purpose β€” and `delete_branch` is `git branch -D`.
+#[test]
+#[cfg(feature = "test-mocks")]
+fn test_delete_task_resources_keeps_branch_of_a_done_task() {
+ let mock_tmux = MockTmuxOperations::new();
+ let mut mock_git = MockGitOperations::new();
+ mock_git.expect_remove_worktree().times(0);
+ mock_git.expect_delete_branch().times(0);
+
+ let mut task = make_test_task("t-done", "Finished task", TaskStatus::Done);
+ task.session_name = None;
+ task.worktree_path = None;
+ task.branch_name = Some("task/finished".to_string());
+
+ delete_task_resources(&task, None, Path::new("/tmp/proj"), &mock_tmux, &mock_git);
+}
+
#[test]
#[cfg(feature = "test-mocks")]
fn test_delete_task_resources_kills_window_removes_worktree_and_deletes_branch() {
diff --git a/tests/git_tests.rs b/tests/git_tests.rs
index 9114c33..61bd722 100644
--- a/tests/git_tests.rs
+++ b/tests/git_tests.rs
@@ -1,8 +1,28 @@
use agtx::git;
+use agtx::git::{GitOperations, RealGitOps};
use std::path::PathBuf;
use std::process::Command;
use tempfile::TempDir;
+fn list_worktrees(project: &std::path::Path) -> String {
+ let out = Command::new("git")
+ .current_dir(project)
+ .args(["worktree", "list"])
+ .output()
+ .unwrap();
+ String::from_utf8_lossy(&out.stdout).to_string()
+}
+
+/// Remove a task's worktree through the implementation production actually uses.
+///
+/// `RealGitOps::remove_worktree` takes the worktree path; these tests were
+/// written against a `git::remove_worktree(project, task_id, worktree_dir)` free
+/// function that no production code ever called.
+fn remove_task_worktree(project: &std::path::Path, task_id: &str) -> anyhow::Result<()> {
+ let wt = git::worktree_path(project, task_id, git::DEFAULT_WORKTREE_DIR);
+ RealGitOps.remove_worktree(project, &wt.to_string_lossy())
+}
+
// =============================================================================
// Pure function tests (no git repo needed)
// =============================================================================
@@ -147,7 +167,7 @@ fn test_create_and_remove_worktree() {
assert!(git::worktree_exists(temp_dir.path(), "test-task"));
// Remove worktree
- git::remove_worktree(temp_dir.path(), "test-task", git::DEFAULT_WORKTREE_DIR).unwrap();
+ remove_task_worktree(temp_dir.path(), "test-task").unwrap();
// Verify it's gone
assert!(!worktree_path.exists());
@@ -240,13 +260,14 @@ fn test_create_worktree_on_non_git_directory() {
fn test_remove_worktree_nonexistent() {
let temp_dir = setup_git_repo();
- // Removing a non-existent worktree should not panic
- // (it may return Ok or Err depending on git version, but shouldn't crash)
- let result = git::remove_worktree(temp_dir.path(), "does-not-exist", git::DEFAULT_WORKTREE_DIR);
-
- // The function should complete without panicking
- // We don't assert success/failure since behavior may vary
- let _ = result;
+ // A failed removal is reported rather than swallowed. It used to return
+ // Ok(()) whatever git did, which is what let a stale registration sit in
+ // `git worktree list` unnoticed.
+ let result = remove_task_worktree(temp_dir.path(), "does-not-exist");
+ assert!(
+ result.is_err(),
+ "a removal that git rejects must not report success"
+ );
}
#[test]
@@ -287,9 +308,9 @@ fn test_create_multiple_worktrees() {
assert_ne!(path1, path3);
// Clean up
- git::remove_worktree(temp_dir.path(), "task-1", git::DEFAULT_WORKTREE_DIR).unwrap();
- git::remove_worktree(temp_dir.path(), "task-2", git::DEFAULT_WORKTREE_DIR).unwrap();
- git::remove_worktree(temp_dir.path(), "task-3", git::DEFAULT_WORKTREE_DIR).unwrap();
+ remove_task_worktree(temp_dir.path(), "task-1").unwrap();
+ remove_task_worktree(temp_dir.path(), "task-2").unwrap();
+ remove_task_worktree(temp_dir.path(), "task-3").unwrap();
assert!(!path1.exists());
assert!(!path2.exists());
@@ -307,10 +328,163 @@ fn test_worktree_with_uncommitted_changes() {
std::fs::write(worktree_path.join("dirty-file.txt"), "uncommitted content").unwrap();
// Remove should still work (with --force)
- let result = git::remove_worktree(temp_dir.path(), "dirty-task", git::DEFAULT_WORKTREE_DIR);
+ let result = remove_task_worktree(temp_dir.path(), "dirty-task");
assert!(result.is_ok());
}
+/// A removal that fails must still drop the registration it left dangling.
+/// Without the prune, one failed removal leaves `git worktree list` wrong
+/// permanently β€” not just until the next attempt.
+///
+/// Measured against git 2.49 to pick a failure this actually fixes:
+///
+/// | worktree state | `remove --force` | still listed | prune fixes |
+/// |-------------------------|------------------|--------------|-------------|
+/// | directory deleted | exit 0 | no | n/a β€” git handles it |
+/// | `.git` link missing | exit 128 | yes | **yes** |
+/// | directory now a file | exit 128 | yes | **yes** |
+/// | locked | exit 128 | yes | no β€” prune respects locks |
+///
+/// So the case worth pinning is a half-deleted tree, which is the state a
+/// crashed cleanup leaves behind β€” and the one `create_worktree` then has to
+/// decide about on the next task with that slug.
+#[test]
+fn test_remove_worktree_prunes_after_a_failed_removal() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "half-deleted").unwrap();
+
+ // Break the worktree the way an interrupted delete does: the directory is
+ // still there, its link back to the repository is not.
+ std::fs::remove_file(worktree_path.join(".git")).unwrap();
+ assert!(
+ list_worktrees(temp_dir.path()).contains("half-deleted"),
+ "precondition: git should still list the worktree"
+ );
+
+ let result = remove_task_worktree(temp_dir.path(), "half-deleted");
+ assert!(
+ result.is_err(),
+ "a removal git rejects must be reported, not swallowed"
+ );
+ assert!(
+ !list_worktrees(temp_dir.path()).contains("half-deleted"),
+ "the dangling registration must be pruned, got:\n{}",
+ list_worktrees(temp_dir.path())
+ );
+}
+
+/// Removal must unlink a symlink, never follow it into the directory it points
+/// at. This is the precondition for sharing a `node_modules` across worktrees:
+/// if cleanup followed the link, finishing one task would destroy the install
+/// every other worktree depends on β€” and the project's own.
+///
+/// The test that must never be deleted. Assert on the *shared content*, not on
+/// the worktree being gone: a version that deleted the target would still
+/// remove the worktree and still return Ok.
+#[test]
+fn test_remove_worktree_does_not_follow_symlinks_out_of_the_worktree() {
+ let temp_dir = setup_git_repo();
+ let project = temp_dir.path();
+
+ // A populated directory outside the worktree, standing in for the project's
+ // own node_modules.
+ let shared = project.join("node_modules");
+ std::fs::create_dir_all(shared.join("left-pad")).unwrap();
+ std::fs::write(shared.join("left-pad/index.js"), "module.exports = 1;").unwrap();
+
+ let worktree_path = git::create_worktree(project, "linker").unwrap();
+ std::os::unix::fs::symlink(&shared, worktree_path.join("node_modules")).unwrap();
+ assert!(worktree_path
+ .join("node_modules/left-pad/index.js")
+ .exists());
+
+ remove_task_worktree(project, "linker").unwrap();
+
+ assert!(
+ !worktree_path.exists(),
+ "the worktree itself should be gone"
+ );
+ assert!(
+ shared.join("left-pad/index.js").exists(),
+ "the shared directory the symlink pointed at must survive"
+ );
+}
+
+/// The same property for the plain recursive delete, which is what a background
+/// trash sweep would use if tranche 2 is ever built.
+#[test]
+fn test_remove_dir_all_does_not_follow_symlinks() {
+ let temp_dir = TempDir::new().unwrap();
+ let shared = temp_dir.path().join("shared");
+ std::fs::create_dir_all(&shared).unwrap();
+ std::fs::write(shared.join("pkg.txt"), "content").unwrap();
+
+ let wt = temp_dir.path().join("wt");
+ std::fs::create_dir_all(&wt).unwrap();
+ std::os::unix::fs::symlink(&shared, wt.join("node_modules")).unwrap();
+
+ std::fs::remove_dir_all(&wt).unwrap();
+
+ assert!(!wt.exists());
+ assert!(
+ shared.join("pkg.txt").exists(),
+ "remove_dir_all must unlink the symlink, not recurse through it"
+ );
+}
+
+/// Under `skip_worktree` a task's `worktree_path` *is* the project root, so
+/// every cleanup path asks for the user's own checkout to be removed. That must
+/// be a no-op β€” and it must be asserted on the directory, not the return value:
+/// a version that moved the repository aside and reported success would pass a
+/// return-value check.
+#[test]
+fn test_remove_worktree_refuses_the_main_working_tree() {
+ let temp_dir = setup_git_repo();
+ let project = temp_dir.path();
+ std::fs::write(project.join("uncommitted.txt"), "work in progress").unwrap();
+
+ let result = RealGitOps.remove_worktree(project, &project.to_string_lossy());
+
+ assert!(result.is_ok(), "refusal is a no-op, not an error");
+ assert!(project.exists(), "the project directory must survive");
+ assert!(project.join(".git").exists(), "the repository must survive");
+ assert!(
+ project.join("uncommitted.txt").exists(),
+ "uncommitted work must survive"
+ );
+}
+
+/// The guard is not just a project-root string comparison: a path that reaches
+/// the same repository by another route is still a main working tree.
+#[test]
+fn test_is_main_working_tree_distinguishes_worktrees() {
+ let temp_dir = setup_git_repo();
+ let worktree_path = git::create_worktree(temp_dir.path(), "linked").unwrap();
+
+ assert!(
+ git::is_main_working_tree(temp_dir.path()),
+ "the project root is a main working tree"
+ );
+ assert!(
+ !git::is_main_working_tree(&worktree_path),
+ "a linked worktree is not"
+ );
+ assert!(
+ !git::is_main_working_tree(&temp_dir.path().join("does-not-exist")),
+ "a missing path is not, so it does not block its own removal"
+ );
+
+ // The default worktree_dir is inside the project, so a worktree that has
+ // lost its `.git` link makes git walk up and answer for the *main*
+ // repository. Checking only `--git-dir == --git-common-dir` reports true
+ // here and refuses to remove exactly the trees that most need it.
+ std::fs::remove_file(worktree_path.join(".git")).unwrap();
+ assert!(
+ !git::is_main_working_tree(&worktree_path),
+ "a half-deleted worktree inside the project is not the main working tree"
+ );
+}
+
// =============================================================================
// initialize_worktree tests
// =============================================================================