ππΌββοΈ The blackboard for coding agents - agentic development environment for claude code, codex, cursor, opencode, grok and more.
Rust adeai-agentsclaudeclaude-codecodexcursorgeminigrokopencodespec-driven-developmentvibe-codingvim
feat: add support for worktree cleanup scripts (#62)
Romek0952e28a0a61
diff --git a/README.md b/README.mdindex bba2946..baf8f9d 100644--- a/README.md+++ b/README.md@@ -169,6 +169,9 @@ copy_files = ".env, .env.local, web/.env.local"# Shell command to run inside the worktree after creation and file copyinginit_script = "scripts/init_worktree.sh"++# Shell command to run inside the worktree before removal+cleanup_script = "scripts/cleanup_worktree.sh"````base_branch` controls which branch new task worktrees are created from. If omitted or empty, agtx@@ -177,6 +180,16 @@ auto-detects `main`, `master`, or falls back to the current branch.These options run during the Backlog β Research/Planning/Running transition, after worktree creationand before the agent session starts.+When a task worktree is removed, `cleanup_script` runs first (with cwd set to the worktree root).+If it exits non-zero, worktree removal is aborted and the error is logged (forced cleanup flows+continue after logging). The script receives:++- `AGTX_PROJECT_PATH`+- `AGTX_WORKTREE_PATH`+- `AGTX_TASK_ID`+- `AGTX_TASK_SLUG`+- `AGTX_TASK_BRANCH` (when available)+### Per-Phase Agent ConfigurationBy default, all phases use `default_agent`. You can override the agent for specific phases globally or per project:diff --git a/src/config/mod.rs b/src/config/mod.rsindex 51f8e8f..3b7da15 100644--- a/src/config/mod.rs+++ b/src/config/mod.rs@@ -203,6 +203,9 @@ pub struct ProjectConfig {/// Shell command to run inside the worktree after creation and file copyingpub init_script: Option<String>,+ /// Shell command to run inside the worktree before removal+ pub cleanup_script: Option<String>,+/// Workflow plugin name (e.g. "gsd", "spec-kit")pub workflow_plugin: Option<String>,}@@ -326,6 +329,7 @@ pub struct MergedConfig {pub theme: ThemeConfig,pub copy_files: Option<String>,pub init_script: Option<String>,+ pub cleanup_script: Option<String>,pub workflow_plugin: Option<String>,}@@ -354,6 +358,7 @@ impl MergedConfig {theme: global.theme.clone(),copy_files: project.copy_files.clone(),init_script: project.init_script.clone(),+ cleanup_script: project.cleanup_script.clone(),workflow_plugin: project.workflow_plugin.clone(),}}diff --git a/src/git/worktree.rs b/src/git/worktree.rsindex 4d662e0..74f3138 100644--- a/src/git/worktree.rs+++ b/src/git/worktree.rs@@ -94,6 +94,44 @@ pub const AGENT_CONFIG_DIRS: &[&str] = &[".config/opencode",];+/// Output from a shell script run inside a worktree.+#[derive(Debug)]+pub struct ScriptOutput {+ pub status: std::process::ExitStatus,+ pub stdout: String,+ pub stderr: String,+}++/// Run a shell script inside a worktree, capturing stdout/stderr.+fn run_worktree_script(+ script: &str,+ worktree_path: &Path,+ envs: &[(String, String)],+) -> Result<ScriptOutput> {+ let output = Command::new("sh")+ .arg("-c")+ .arg(script)+ .current_dir(worktree_path)+ .envs(envs.iter().map(|(k, v)| (k, v)))+ .output()+ .with_context(|| format!("Failed to run script: {}", script))?;++ Ok(ScriptOutput {+ status: output.status,+ stdout: String::from_utf8_lossy(&output.stdout).to_string(),+ stderr: String::from_utf8_lossy(&output.stderr).to_string(),+ })+}++/// Run a cleanup script inside the worktree, returning the captured output.+pub fn run_cleanup_script(+ script: &str,+ worktree_path: &Path,+ envs: &[(String, String)],+) -> Result<ScriptOutput> {+ run_worktree_script(script, worktree_path, envs)+}+/// Initialize a worktree by copying agent config dirs, user-specified files, and running an init script.////// Returns a Vec of warning messages for any issues encountered.@@ -176,25 +214,17 @@ pub fn initialize_worktree(if let Some(script) = init_script {let script = script.trim();if !script.is_empty() {- match Command::new("sh")- .arg("-c")- .arg(script)- .current_dir(worktree_path)- .output()- {+ match run_worktree_script(script, worktree_path, &[]) {Ok(result) => {if !result.status.success() {- let stderr = String::from_utf8_lossy(&result.stderr);warnings.push(format!("init_script exited with {}: {}",result.status,- stderr.trim()+ result.stderr.trim()));}}- Err(e) => {- warnings.push(format!("Failed to run init_script: {}", e));- }+ Err(e) => warnings.push(format!("Failed to run init_script: {}", e)),}}}diff --git a/src/tui/app.rs b/src/tui/app.rsindex 0d4958e..b70f264 100644--- a/src/tui/app.rs+++ b/src/tui/app.rs@@ -2630,15 +2630,18 @@ impl App {let tmux_ops = Arc::clone(&self.state.tmux_ops);let git_ops = Arc::clone(&self.state.git_ops);let task_id = task.id.clone();+ let cleanup_script = self.state.config.cleanup_script.clone();std::thread::spawn(move || {cleanup_task_resources(&task_id,&branch_name,&session_name,&worktree_path,+ cleanup_script.as_deref(),&project_path,tmux_ops.as_ref(),git_ops.as_ref(),+ true,);});}@@ -4034,10 +4037,12 @@ impl App {if let Some(task) = db.get_task(task_id)? {delete_task_resources(&task,+ self.state.config.cleanup_script.as_deref(),project_path,self.state.tmux_ops.as_ref(),self.state.git_ops.as_ref(),- );+ false,+ )?;db.delete_task(&task.id)?;self.refresh_tasks()?;}@@ -4546,15 +4551,18 @@ impl App {let git_ops = Arc::clone(&self.state.git_ops);let task_id_clone = task.id.clone();let project_path_clone = project_path.to_path_buf();+ let cleanup_script = self.state.config.cleanup_script.clone();std::thread::spawn(move || {cleanup_task_resources(&task_id_clone,&branch_name,&session_name,&worktree_path,+ cleanup_script.as_deref(),&project_path_clone,tmux_ops.as_ref(),git_ops.as_ref(),+ false,);});Ok(false)@@ -6096,13 +6104,92 @@ fn generate_task_slug(task_id: &str, title: &str) -> String {format!("{}-{}", id_prefix, title_slug)}-/// Cleanup task resources (tmux window, git worktree) and mark as done+fn build_cleanup_env(+ project_path: &Path,+ worktree_path: &Path,+ task_id: &str,+ branch_name: Option<&str>,+) -> Vec<(String, String)> {+ let slug = branch_name+ .and_then(|b| b.strip_prefix("task/"))+ .unwrap_or(task_id);++ let mut envs = vec![+ (+ "AGTX_PROJECT_PATH".to_string(),+ project_path.to_string_lossy().to_string(),+ ),+ (+ "AGTX_WORKTREE_PATH".to_string(),+ worktree_path.to_string_lossy().to_string(),+ ),+ ("AGTX_TASK_ID".to_string(), task_id.to_string()),+ ("AGTX_TASK_SLUG".to_string(), slug.to_string()),+ ];++ if let Some(branch) = branch_name {+ envs.push(("AGTX_TASK_BRANCH".to_string(), branch.to_string()));+ }++ envs+}++fn run_cleanup_script_for_worktree(+ cleanup_script: Option<&str>,+ project_path: &Path,+ worktree_path: &Path,+ task_id: &str,+ branch_name: Option<&str>,+ force_cleanup: bool,+) -> Result<()> {+ let Some(script) = cleanup_script else {+ return Ok(());+ };+ let script = script.trim();+ if script.is_empty() {+ return Ok(());+ }++ let envs = build_cleanup_env(project_path, worktree_path, task_id, branch_name);+ let output = match git::run_cleanup_script(script, worktree_path, &envs) {+ Ok(result) => result,+ Err(e) => {+ if force_cleanup {+ eprintln!("cleanup_script failed to run (forced): {}", e);+ return Ok(());+ }+ return Err(e);+ }+ };++ if !output.stdout.trim().is_empty() {+ eprintln!("cleanup_script stdout:\n{}", output.stdout.trim_end());+ }+ if !output.stderr.trim().is_empty() {+ eprintln!("cleanup_script stderr:\n{}", output.stderr.trim_end());+ }++ if !output.status.success() {+ let message = format!("cleanup_script exited with {}: {}", output.status, script);+ if force_cleanup {+ eprintln!("{}", message);+ return Ok(());+ }+ anyhow::bail!(message);+ }++ Ok(())+}++/// Cleanup task resources (tmux window, cleanup script, git worktree) and mark as done/// Modifies the task in place, ready for database updatefn cleanup_task_for_done(task: &mut Task,+ cleanup_script: Option<&str>,project_path: &Path,tmux_ops: &dyn TmuxOperations,git_ops: &dyn GitOperations,+ force_cleanup: bool,) {// Archive artifacts before removing worktreeif let Some(worktree) = &task.worktree_path {@@ -6131,7 +6218,18 @@ fn cleanup_task_for_done(let _ = tmux_ops.kill_window(session_name);}if let Some(worktree) = &task.worktree_path {- let _ = git_ops.remove_worktree(project_path, worktree);+ if let Err(e) = run_cleanup_script_for_worktree(+ cleanup_script,+ project_path,+ Path::new(worktree),+ &task.id,+ task.branch_name.as_deref(),+ force_cleanup,+ ) {+ eprintln!("cleanup_script failed: {}", e);+ } else {+ let _ = git_ops.remove_worktree(project_path, worktree);+ }}// Keep the branch so task can be reopened latertask.session_name = None;@@ -6140,16 +6238,18 @@ fn cleanup_task_for_done(task.updated_at = chrono::Utc::now();}-/// Background-safe cleanup: archive artifacts, kill tmux window, remove worktree.+/// 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(task_id: &str,branch_name: &Option<String>,session_name: &Option<String>,worktree_path: &Option<String>,+ cleanup_script: Option<&str>,project_path: &Path,tmux_ops: &dyn TmuxOperations,git_ops: &dyn GitOperations,+ force_cleanup: bool,) {// Archive artifacts before removing worktreeif let Some(worktree) = worktree_path {@@ -6177,6 +6277,17 @@ fn cleanup_task_resources(let _ = tmux_ops.kill_window(session_name);}if let Some(worktree) = worktree_path {+ if let Err(e) = run_cleanup_script_for_worktree(+ cleanup_script,+ project_path,+ Path::new(worktree),+ task_id,+ branch_name.as_deref(),+ force_cleanup,+ ) {+ eprintln!("cleanup_script failed: {}", e);+ return;+ }let _ = git_ops.remove_worktree(project_path, worktree);}}@@ -6354,26 +6465,36 @@ fn setup_task_worktree(Ok(target)}-/// Delete task resources: kill tmux window, remove worktree, delete branch+/// Delete task resources: kill tmux window, run cleanup script, remove worktree, delete branchfn delete_task_resources(task: &Task,+ cleanup_script: Option<&str>,project_path: &Path,tmux_ops: &dyn TmuxOperations,git_ops: &dyn GitOperations,-) {+ force_cleanup: bool,+) -> Result<()> {// Kill tmux window if existsif let Some(ref session_name) = task.session_name {let _ = tmux_ops.kill_window(session_name);}// Remove worktree and delete branch if exists- if task.worktree_path.is_some() {+ if let Some(ref worktree) = task.worktree_path {if let Some(ref branch_name) = task.branch_name {- let slug = branch_name.strip_prefix("task/").unwrap_or(branch_name);- let _ = git_ops.remove_worktree(project_path, slug);+ run_cleanup_script_for_worktree(+ cleanup_script,+ project_path,+ Path::new(worktree),+ &task.id,+ task.branch_name.as_deref(),+ force_cleanup,+ )?;+ let _ = git_ops.remove_worktree(project_path, worktree);let _ = git_ops.delete_branch(project_path, branch_name);}}+ Ok(())}/// Collect git diff content from a worktreediff --git a/src/tui/app_tests.rs b/src/tui/app_tests.rsindex 3a34f83..cfb9059 100644--- a/src/tui/app_tests.rs+++ b/src/tui/app_tests.rs@@ -924,7 +924,14 @@ fn test_cleanup_task_for_done_with_resources() {task.worktree_path = Some("/tmp/worktree".to_string());task.status = TaskStatus::Review;- cleanup_task_for_done(&mut task, Path::new("/project"), &mock_tmux, &mock_git);+ cleanup_task_for_done(+ &mut task,+ None,+ Path::new("/project"),+ &mock_tmux,+ &mock_git,+ false,+ );assert!(task.session_name.is_none());assert!(task.worktree_path.is_none());@@ -944,7 +951,14 @@ fn test_cleanup_task_for_done_no_resources() {let mut task = Task::new("Test task", "claude", "project-1");// No session_name or worktree_path set- cleanup_task_for_done(&mut task, Path::new("/project"), &mock_tmux, &mock_git);+ cleanup_task_for_done(+ &mut task,+ None,+ Path::new("/project"),+ &mock_tmux,+ &mock_git,+ false,+ );assert_eq!(task.status, TaskStatus::Done);}@@ -987,7 +1001,15 @@ fn test_delete_task_resources_full_cleanup() {task.worktree_path = Some("/tmp/worktree".to_string());task.branch_name = Some("task/abc-feature".to_string());- delete_task_resources(&task, Path::new("/project"), &mock_tmux, &mock_git);+ delete_task_resources(+ &task,+ None,+ Path::new("/project"),+ &mock_tmux,+ &mock_git,+ false,+ )+ .unwrap();}/// Test delete_task_resources handles task without resources@@ -1003,7 +1025,15 @@ fn test_delete_task_resources_no_resources() {let task = Task::new("Simple task", "claude", "project-1");// No session_name, worktree_path, or branch_name- delete_task_resources(&task, Path::new("/project"), &mock_tmux, &mock_git);+ delete_task_resources(+ &task,+ None,+ Path::new("/project"),+ &mock_tmux,+ &mock_git,+ false,+ )+ .unwrap();}// =============================================================================@@ -7379,7 +7409,14 @@ fn test_cleanup_task_for_done_clears_session_and_worktree() {task.session_name = Some("proj:task-1".to_string());task.worktree_path = Some("/tmp/nonexistent-wt".to_string());- cleanup_task_for_done(&mut task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);+ cleanup_task_for_done(+ &mut task,+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ false,+ );assert_eq!(task.status, TaskStatus::Done);assert!(task.session_name.is_none());@@ -7397,7 +7434,14 @@ fn test_cleanup_task_for_done_no_ops_when_no_session_or_worktree() {task.session_name = None;task.worktree_path = None;- cleanup_task_for_done(&mut task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);+ cleanup_task_for_done(+ &mut task,+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ false,+ );assert_eq!(task.status, TaskStatus::Done);}@@ -7425,7 +7469,14 @@ 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, project_dir.path(), &mock_tmux, &mock_git);+ cleanup_task_for_done(+ &mut task,+ None,+ project_dir.path(),+ &mock_tmux,+ &mock_git,+ false,+ );// Archived file should exist under .agtx/archive/my-slug/plan.mdlet archive = project_dir@@ -7459,9 +7510,11 @@ fn test_cleanup_task_resources_kills_window_and_removes_worktree() {&Some("task/branch".to_string()),&Some("proj:task-win".to_string()),&Some("/tmp/wt".to_string()),+ None,Path::new("/tmp/proj"),&mock_tmux,&mock_git,+ false,);}@@ -7476,9 +7529,11 @@ fn test_cleanup_task_resources_noop_when_no_session_or_worktree() {&None,&None,&None,+ None,Path::new("/tmp/proj"),&mock_tmux,&mock_git,+ false,);// No panic = correct (no mock calls made)}@@ -7509,7 +7564,15 @@ fn test_delete_task_resources_kills_window_removes_worktree_and_deletes_branch()task.worktree_path = Some("/tmp/wt".to_string());task.branch_name = Some("task/my-task".to_string());- delete_task_resources(&task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);+ delete_task_resources(+ &task,+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ false,+ )+ .unwrap();}#[test]@@ -7520,7 +7583,15 @@ fn test_delete_task_resources_noop_when_no_session_or_worktree() {let task = make_test_task("t2", "Nothing to clean", TaskStatus::Backlog);// session_name and worktree_path both None β no mock calls- delete_task_resources(&task, Path::new("/tmp/proj"), &mock_tmux, &mock_git);+ delete_task_resources(+ &task,+ None,+ Path::new("/tmp/proj"),+ &mock_tmux,+ &mock_git,+ false,+ )+ .unwrap();}// --- save_task ---diff --git a/tests/config_tests.rs b/tests/config_tests.rsindex 7e51bb5..b7a2697 100644--- a/tests/config_tests.rs+++ b/tests/config_tests.rs@@ -79,6 +79,7 @@ fn test_project_config_default() {assert!(config.github_url.is_none());assert!(config.copy_files.is_none());assert!(config.init_script.is_none());+ assert!(config.cleanup_script.is_none());}// === MergedConfig Tests ===@@ -96,6 +97,7 @@ fn test_merged_config_uses_global_defaults() {assert!(merged.auto_cleanup);assert!(merged.copy_files.is_none());assert!(merged.init_script.is_none());+ assert!(merged.cleanup_script.is_none());}#[test]@@ -108,6 +110,7 @@ fn test_merged_config_project_overrides() {github_url: Some("https://github.com/user/repo".to_string()),copy_files: Some(".env, .env.local".to_string()),init_script: Some("npm install".to_string()),+ cleanup_script: Some("scripts/cleanup.sh".to_string()),workflow_plugin: None,};@@ -121,6 +124,10 @@ fn test_merged_config_project_overrides() {);assert_eq!(merged.copy_files, Some(".env, .env.local".to_string()));assert_eq!(merged.init_script, Some("npm install".to_string()));+ assert_eq!(+ merged.cleanup_script,+ Some("scripts/cleanup.sh".to_string())+ );}// === FirstRunAction Tests ===diff --git a/tests/git_tests.rs b/tests/git_tests.rsindex 2290115..67ad515 100644--- a/tests/git_tests.rs+++ b/tests/git_tests.rs@@ -43,6 +43,26 @@ fn test_worktree_exists_false_for_nonexistent() {assert!(!git::worktree_exists(temp_dir.path(), "nonexistent-task"));}+#[test]+fn test_run_cleanup_script_captures_output_and_env() {+ let temp_dir = TempDir::new().unwrap();+ let envs = vec![("AGTX_TASK_ID".to_string(), "task-123".to_string())];++ let output = git::run_cleanup_script("echo $AGTX_TASK_ID", temp_dir.path(), &envs).unwrap();++ assert!(output.status.success());+ assert_eq!(output.stdout.trim(), "task-123");+}++#[test]+fn test_run_cleanup_script_nonzero_exit() {+ let temp_dir = TempDir::new().unwrap();++ let output = git::run_cleanup_script("exit 42", temp_dir.path(), &[]).unwrap();++ assert!(!output.status.success());+}+// =============================================================================// Integration tests (require git)// =============================================================================