Skip to main content

orch/engine/cleanup/
mod.rs

1//! Worktree cleanup and merged-PR detection.
2//!
3//! Contains the post-merge cleanup pipeline: removing git worktrees,
4//! deleting local/remote branches, pulling main, and detecting
5//! already-merged PRs so their tasks can be marked done.
6
7use crate::engine::ci;
8use crate::store::Task;
9
10use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
11use crate::cmd::CommandErrorContext;
12use crate::engine::ci_bootstrap;
13use crate::engine::tasks::{TaskManager, store_task_to_external};
14use crate::store;
15use crate::store::TaskStatus;
16use crate::store::TaskStore;
17use crate::store::store_log_activity;
18use dashmap::{DashMap, DashSet};
19use futures::future;
20use std::collections::HashMap;
21use std::collections::HashSet;
22use std::env;
23use std::fs as std_fs;
24use std::io::ErrorKind;
25use std::path::Path;
26use std::path::PathBuf;
27use std::process::Output;
28use std::sync::Arc;
29use std::sync::LazyLock;
30use std::time::SystemTime;
31use std::time::{Duration, Instant};
32use tokio::fs;
33use tokio::process::Command;
34use tokio::time::sleep;
35use tokio::time::timeout;
36
37use crate::config;
38use crate::engine;
39use crate::engine::git::cow;
40use crate::engine::git::git_ops;
41use crate::engine::git::screenshots::SCREENSHOTS_BRANCH;
42use crate::engine::git::worktree;
43use crate::github::http::GhHttp;
44use crate::home;
45
46/// Reconciliation calls can be slow on repos with many issues or during GitHub instability.
47/// Cleanup runs in a background task (tokio::spawn) so it does not block the main tick loop.
48/// 30 s gives enough headroom for paginated list_all_tasks calls while still bounding the
49/// overall background-task duration.
50const RECONCILIATION_LIST_TIMEOUT: Duration = Duration::from_secs(30);
51/// Closed-issue reconciliation is a best-effort cleanup fallback, not a per-sync requirement.
52/// Run it on a slower cadence so repeated GitHub slowness does not consume 30 s every sync.
53const RECONCILIATION_INTERVAL: Duration = Duration::from_mins(15);
54
55const RUN_OUTPUT_RETENTION_DAYS: i32 = 30;
56const RUN_PRUNE_INTERVAL_SECS: i64 = 24 * 60 * 60;
57const RUN_PRUNE_KV_KEY: &str = "task_runs_pruned_at";
58
59/// Per-repo in-flight guard for closed-issue reconciliation/cleanup.
60/// Prevents overlapping cleanup runs from piling up across sync cycles.
61static CLEANUP_IN_FLIGHT: LazyLock<DashSet<String>> = LazyLock::new(DashSet::new);
62/// Per-repo reconciliation cadence tracker.
63static RECONCILIATION_LAST_RUN: LazyLock<DashMap<String, Instant>> = LazyLock::new(DashMap::new);
64
65struct CleanupInFlightGuard {
66    repo: String,
67}
68
69impl CleanupInFlightGuard {
70    fn try_acquire(repo: &str) -> Option<Self> {
71        if CLEANUP_IN_FLIGHT.insert(repo.to_string()) {
72            Some(Self {
73                repo: repo.to_string(),
74            })
75        } else {
76            None
77        }
78    }
79}
80
81impl Drop for CleanupInFlightGuard {
82    fn drop(&mut self) {
83        CLEANUP_IN_FLIGHT.remove(&self.repo);
84    }
85}
86
87fn should_run_reconciliation(repo: &str) -> bool {
88    let now = Instant::now();
89    if let Some(mut last_run) = RECONCILIATION_LAST_RUN.get_mut(repo) {
90        if last_run.elapsed() < RECONCILIATION_INTERVAL {
91            return false;
92        }
93        *last_run = now;
94        true
95    } else {
96        RECONCILIATION_LAST_RUN.insert(repo.to_string(), now);
97        true
98    }
99}
100
101/// Options controlling the worktree janitor.
102#[derive(Debug, Clone)]
103pub struct JanitorOptions {
104    /// Minimum age (in hours) of the worktree directory before it is eligible for removal.
105    ///
106    /// A worktree whose filesystem mtime is more recent than this threshold is skipped
107    /// even if the task is already in a terminal state. This provides a safety buffer
108    /// against races (e.g. review agent still writing when the janitor runs).
109    ///
110    /// Default: 24.  Configurable via `workflow.worktree_janitor_ttl_hours` in config.
111    pub ttl_hours: u64,
112
113    /// When `true`, log what would be done but skip all destructive operations.
114    ///
115    /// Configurable via `workflow.worktree_janitor_dry_run: true` in config.
116    pub dry_run: bool,
117}
118
119impl Default for JanitorOptions {
120    fn default() -> Self {
121        Self {
122            ttl_hours: 24,
123            dry_run: false,
124        }
125    }
126}
127
128impl JanitorOptions {
129    /// Read options from the global config, falling back to defaults.
130    pub fn from_config() -> Self {
131        let ttl_hours = config::get("workflow.worktree_janitor_ttl_hours")
132            .ok()
133            .and_then(|v| v.parse::<u64>().ok())
134            .unwrap_or(24);
135
136        let dry_run = config::get("workflow.worktree_janitor_dry_run").is_ok_and(|v| v == "true");
137
138        Self { ttl_hours, dry_run }
139    }
140}
141
142/// Cleanup worktrees for completed tasks.
143///
144/// Targets tasks that are finished: status:done OR closed on GitHub
145/// (e.g. when a PR merge auto-closes the issue via "Fixes #N").
146///
147/// Note: This is a fallback. Primary cleanup happens inline in
148/// `auto_merge_pr` via `cleanup_task_worktree`. This catches edge cases
149/// where the inline cleanup missed (e.g., manual merges, auto-closed issues).
150pub(crate) async fn cleanup_done_worktrees(
151    backend: &Arc<dyn ExternalBackend>,
152    repo: &str,
153    task_manager: &Arc<TaskManager>,
154    store: &Arc<TaskStore>,
155) -> anyhow::Result<()> {
156    let opts = JanitorOptions::from_config();
157    cleanup_done_worktrees_with_opts(backend, repo, task_manager, store, &opts).await
158}
159
160/// Clear the stored output of runs for tasks done longer than `RUN_OUTPUT_RETENTION_DAYS`, once a day
161pub(crate) async fn prune_old_run_output(store: &TaskStore) -> anyhow::Result<()> {
162    let now = chrono::Utc::now().timestamp();
163    let last = store
164        .kv_get(RUN_PRUNE_KV_KEY)
165        .await?
166        .and_then(|v| v.parse::<i64>().ok())
167        .unwrap_or(0);
168    if now - last < RUN_PRUNE_INTERVAL_SECS {
169        return Ok(());
170    }
171    store.kv_set(RUN_PRUNE_KV_KEY, &now.to_string()).await?;
172
173    let pruned = store.prune_old_runs(RUN_OUTPUT_RETENTION_DAYS).await?;
174    if pruned > 0 {
175        tracing::info!(pruned, "cleared the output of old task runs");
176    }
177    Ok(())
178}
179
180async fn reconcile_closed_tasks(
181    task_ids: &mut Vec<String>,
182    all_tasks: &[ExternalTask],
183    task_manager: &TaskManager,
184    store: &Arc<TaskStore>,
185    repo: &str,
186) {
187    const MAX_RECONCILE_PER_CYCLE: usize = 10;
188
189    let done_set: HashSet<String> = task_ids.iter().cloned().collect();
190    let mut closed_not_in_store = Vec::new();
191    for task in all_tasks {
192        if task.state != "closed" || done_set.contains(&task.id.0) {
193            continue;
194        }
195        if ci_bootstrap::hold_after_merge(task, store, repo).await {
196            continue;
197        }
198        closed_not_in_store.push(task);
199    }
200
201    // Split: issues that already have status:done label just need worktree
202    // cleanup (no API call needed), vs those needing label reconciliation.
203    let mut already_labeled: Vec<String> = Vec::new();
204    let mut needs_reconcile: Vec<&ExternalTask> = Vec::new();
205    for task in &closed_not_in_store {
206        if task.labels.iter().any(|l| l == "status:done") {
207            already_labeled.push(task.id.0.clone());
208        } else {
209            needs_reconcile.push(task);
210        }
211    }
212
213    // Add already-labeled issues directly (no API call).
214    if !already_labeled.is_empty() {
215        tracing::debug!(
216            count = already_labeled.len(),
217            "closed issues already labeled status:done — adding to cleanup set"
218        );
219        task_ids.extend(already_labeled);
220    }
221
222    // Reconcile issues missing the done label — cap to avoid rate-limit
223    // exhaustion. Remaining issues will be picked up in subsequent cycles.
224    if needs_reconcile.len() > MAX_RECONCILE_PER_CYCLE {
225        tracing::info!(
226            total = needs_reconcile.len(),
227            batch = MAX_RECONCILE_PER_CYCLE,
228            "capping closed-issue reconciliation to avoid rate-limit exhaustion"
229        );
230    }
231    let mut futs = Vec::new();
232    for task in needs_reconcile.iter().take(MAX_RECONCILE_PER_CYCLE) {
233        let id = task.id.clone();
234        let task_id_str = task.id.0.clone();
235        let labels = task.labels.clone();
236        futs.push(async move {
237            tracing::info!(
238                task_id = task_id_str,
239                labels = ?labels,
240                "closed issue with stale status label — reconciling to done and cleaning up"
241            );
242            match task_manager.update_task_status(&id, Status::Done).await {
243                Ok(()) => Some(task_id_str),
244                Err(e) => {
245                    tracing::warn!(
246                        task_id = task_id_str,
247                        err = %e,
248                        "failed to reconcile closed issue status to done"
249                    );
250                    None
251                }
252            }
253        });
254    }
255    let results = future::join_all(futs).await;
256    task_ids.extend(results.into_iter().flatten());
257}
258
259/// Cleanup worktrees for completed tasks with explicit options.
260///
261/// Separated from `cleanup_done_worktrees` so that integration tests can
262/// inject specific options (e.g. `ttl_hours: 0`, `dry_run: true`) without
263/// touching the global config.
264pub(crate) async fn cleanup_done_worktrees_with_opts(
265    backend: &Arc<dyn ExternalBackend>,
266    repo: &str,
267    task_manager: &Arc<TaskManager>,
268    store: &Arc<TaskStore>,
269    opts: &JanitorOptions,
270) -> anyhow::Result<()> {
271    let Some(_guard) = CleanupInFlightGuard::try_acquire(repo) else {
272        tracing::debug!(
273            repo = %repo,
274            "cleanup already in progress for repo — skipping overlapping run"
275        );
276        return Ok(());
277    };
278
279    // Read done tasks from the store first; fall back to backend before first sync.
280    let done_tasks = task_manager.list_all_by_status(Status::Done).await?;
281    tracing::debug!(count = done_tasks.len(), "checking done tasks for cleanup");
282
283    // Collect task IDs from external done tasks.
284    let mut task_ids: Vec<String> = done_tasks.iter().map(|t| t.id.0.clone()).collect();
285
286    // Also include closed-but-not-done external tasks.
287    // When a PR merge auto-closes a GitHub issue (via "Fixes #N"), the issue
288    // state becomes "closed" but orch never updates the status label to "done".
289    // These orphaned worktrees accumulate unless we catch them here.
290    // Note: This still queries the backend because GitHub `state` (open/closed)
291    // is backend-specific and not tracked in the store.
292    //
293    // Use list_reconciliation_candidates() (closed issues only, bounded recent window) directly.
294    // list_all_tasks() fetches every issue ever created (state=all, all pages) and
295    // consistently times out on repos with many issues — it is not appropriate for
296    // a cleanup fallback path.
297    if should_run_reconciliation(repo) {
298        match timeout(
299            RECONCILIATION_LIST_TIMEOUT,
300            backend.list_reconciliation_candidates(),
301        )
302        .await
303        {
304            Ok(Ok(candidates)) if !candidates.is_empty() => {
305                tracing::debug!(
306                    count = candidates.len(),
307                    "reconciling closed issues from candidates"
308                );
309                reconcile_closed_tasks(&mut task_ids, &candidates, task_manager, store, repo).await;
310            }
311            Ok(Ok(_)) => {
312                tracing::debug!("no reconciliation candidates found");
313            }
314            Ok(Err(e)) => {
315                tracing::warn!(err = %e, "failed to list reconciliation candidates");
316            }
317            Err(_) => {
318                tracing::warn!(
319                    timeout_secs = RECONCILIATION_LIST_TIMEOUT.as_secs(),
320                    retry_after_secs = RECONCILIATION_INTERVAL.as_secs(),
321                    "timed out listing reconciliation candidates"
322                );
323            }
324        }
325    } else {
326        tracing::debug!(
327            retry_after_secs = RECONCILIATION_INTERVAL.as_secs(),
328            "skipping closed-issue reconciliation until interval elapses"
329        );
330    }
331
332    // Also include internal done tasks.
333    if let Ok(internal_done) = task_manager.list_internal_by_status(TaskStatus::Done).await {
334        task_ids.extend(internal_done.iter().map(|t| t.id.0.clone()));
335    }
336
337    tracing::debug!(
338        count = task_ids.len(),
339        "checking all terminal tasks for cleanup"
340    );
341
342    if let Err(e) = ci::sweep_ci_timer_keys(store, repo, &task_ids).await {
343        tracing::warn!(err = %e, "failed to sweep CI timer keys");
344    }
345
346    // Prefetch all cleaned external IDs in one query instead of N+1 per-task lookups.
347    // NOTE: This is now primarily a hint to skip processing, NOT a correctness
348    // guarantee — tasks with external_id NOT in the store at all (or mismatched
349    // repo) will still be cleaned by iterating all worktree directories.
350    let already_cleaned = store.cleaned_external_ids(repo).await.unwrap_or_default();
351
352    let mut cleaned_any = false;
353    for task_id in &task_ids {
354        // Skip if already cleaned (checked via prefetched set).
355        if already_cleaned.contains(task_id) {
356            continue;
357        }
358
359        match cleanup_task_worktree_with_opts(task_id, repo, store, opts).await {
360            Ok(true) => cleaned_any = true,
361            Ok(false) => {
362                // Skipped (TTL guard, tmux guard, or nothing to remove) — do not
363                // pull main; we did not change the repo state.
364            }
365            Err(e) => {
366                tracing::warn!(task_id, err = %e, "worktree cleanup failed for task");
367            }
368        }
369    }
370
371    // ── Orphaned worktree scanner ─────────────────────────────────────────────
372    //
373    // Even if every task in our list was already cleaned (or had no worktree),
374    // there may be worktree directories on disk that are not owned by any task.
375    // This happens when a task was ingested into the store but its worktree_cleaned
376    // flag was never set — e.g. because the task was never in `list_all_by_status`
377    // (unknown repo / missing from store at cleanup time), or the cleanup skipped
378    // due to TTL guard and never retried.
379    //
380    // We scan all worktree directories in this repo's worktrees subdirectory and
381    // remove any that are not referenced by an existing task. This catches the
382    // "done but worktree not cleaned" case that `orch service doctor` reports.
383    let worktrees_base = match home::worktrees_dir() {
384        Ok(base) => Some(base),
385        Err(e) => {
386            tracing::debug!(err = %e, "worktrees_dir() unavailable — skipping orphan scan");
387            None
388        }
389    };
390
391    if let Some(base) = worktrees_base {
392        let project = repo
393            .rsplit('/')
394            .next()
395            .unwrap_or(repo)
396            .trim_end_matches(".git");
397        let repo_worktrees = base.join(project);
398
399        // Build set of all known worktree paths for this repo (all statuses).
400        let mut combined: HashSet<String> = HashSet::new();
401        if let Ok(tasks) = store.list_all(repo).await {
402            for t in tasks {
403                if !t.worktree.is_empty() {
404                    combined.insert(t.worktree);
405                }
406            }
407        }
408
409        // Also include active worktrees (in case task is in-memory but has a dir).
410        if let Ok(project_dir) = resolve_project_dir_for_repo(repo)
411            && let Ok(active_wts) = worktree::list_project_worktrees(&project_dir).await
412        {
413            for wt in active_wts {
414                combined.insert(wt.to_string_lossy().to_string());
415            }
416        }
417
418        // Scan all branch directories and remove orphaned ones.
419        if let Ok(mut entries) = fs::read_dir(&repo_worktrees).await {
420            while let Ok(Some(entry)) = entries.next_entry().await {
421                let Ok(entry_meta) = entry.metadata().await else {
422                    continue;
423                };
424                if !entry_meta.is_dir() {
425                    continue;
426                }
427                let wt_path = entry.path().to_string_lossy().to_string();
428                if combined.contains(&wt_path) {
429                    continue;
430                }
431                tracing::info!(worktree = %wt_path, "found orphaned worktree — attempting cleanup");
432                match resolve_repo_root_for_orphaned_worktree(&entry.path()).await {
433                    Ok(repo_root) => {
434                        let removed = remove_worktree_and_branch(
435                            "orphan-scan",
436                            &entry.path(),
437                            None,
438                            Path::new(&repo_root),
439                            false,
440                        )
441                        .await;
442                        if removed {
443                            tracing::info!(worktree = %wt_path, "orphaned worktree removed");
444                        } else {
445                            tracing::warn!(worktree = %wt_path, "orphaned worktree could not be removed");
446                        }
447                    }
448                    Err(e) => {
449                        tracing::warn!(worktree = %wt_path, err = %e, "could not resolve repo root for orphaned worktree");
450                    }
451                }
452            }
453        }
454    }
455
456    // Prune stale worktree metadata and pull main after cleanup.
457    if cleaned_any
458        && !opts.dry_run
459        && let Ok(repo_root) = resolve_repo_root(repo).await
460    {
461        const GIT_TIMEOUT: Duration = Duration::from_secs(60);
462
463        // Prune stale .git/worktrees/ entries whose directories no longer exist.
464        let prune_result = timeout(
465            GIT_TIMEOUT,
466            Command::new("git")
467                .args(["-C", &repo_root, "worktree", "prune"])
468                .output_with_context(),
469        )
470        .await;
471        match prune_result {
472            Ok(Ok(output)) if output.status.success() => {
473                tracing::debug!(%repo, "pruned stale worktree metadata");
474            }
475            Ok(Ok(output)) => {
476                let stderr = String::from_utf8_lossy(&output.stderr);
477                tracing::warn!(%repo, err = %stderr, "git worktree prune failed");
478            }
479            Ok(Err(e)) => {
480                tracing::warn!(%repo, err = %e, "git worktree prune failed");
481            }
482            Err(_) => {
483                tracing::warn!(%repo, "git worktree prune timed out after 60s");
484            }
485        }
486
487        // Fetch instead of pull: refresh `origin/*` refs without touching
488        // the operator's checked-out branch or working tree. `pull` would
489        // operate on whatever HEAD happens to be (often a feature branch,
490        // not main) and would silently no-op on divergence.
491        let fetch_result = timeout(
492            GIT_TIMEOUT,
493            git_ops::git()
494                .await
495                .args(["-C", &repo_root, "fetch", "--prune", "origin"])
496                .output_with_context(),
497        )
498        .await;
499        match fetch_result {
500            Ok(Ok(output)) if output.status.success() => {
501                tracing::info!(%repo, "fetched origin after worktree cleanup");
502            }
503            Ok(Ok(output)) => {
504                let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
505                tracing::debug!(%repo, err = %stderr, "git fetch skipped after cleanup");
506            }
507            Ok(Err(e)) => {
508                tracing::debug!(%repo, err = %e, "git fetch failed after cleanup");
509            }
510            Err(_) => {
511                tracing::debug!(%repo, "git fetch timed out after 60s");
512            }
513        }
514    }
515
516    Ok(())
517}
518
519/// Cleanup a single task's worktree and branches.
520///
521/// Removes the git worktree, deletes local + remote branches,
522/// fetches origin to refresh remote tracking refs, and marks the task as cleaned.
523///
524/// This function is used for inline post-merge cleanup (called from
525/// auto-merge flows) and must attempt immediate removal — it constructs
526/// janitor options with `ttl_hours = 0` so the janitor age guard does not
527/// postpone removing freshly-created worktrees.
528pub(crate) async fn cleanup_task_worktree(
529    task_id: &str,
530    repo: &str,
531    store: &Arc<TaskStore>,
532) -> anyhow::Result<()> {
533    cleanup_task_worktree_impl(task_id, repo, store, false).await
534}
535
536/// Cleanup after a merged pull request, including while `hold_after_merge` keeps the task approved
537pub(crate) async fn cleanup_merged_pr_worktree(
538    task_id: &str,
539    repo: &str,
540    store: &Arc<TaskStore>,
541) -> anyhow::Result<()> {
542    cleanup_task_worktree_impl(task_id, repo, store, true).await
543}
544
545async fn cleanup_task_worktree_impl(
546    task_id: &str,
547    repo: &str,
548    store: &Arc<TaskStore>,
549    known_pr_merged: bool,
550) -> anyhow::Result<()> {
551    let opts = JanitorOptions {
552        ttl_hours: 0,
553        ..Default::default()
554    };
555    let cleaned =
556        cleanup_task_worktree_with_opts_impl(task_id, repo, store, &opts, known_pr_merged).await?;
557
558    // Fetch origin once after inline cleanup (post-merge single-task path).
559    // Only fetch if cleanup actually happened (not skipped due to active session).
560    // Fetch (not pull) so the operator's checked-out branch and working tree
561    // are never touched — see the matching comment in cleanup_orphaned_worktrees.
562    if cleaned && let Ok(repo_root) = resolve_repo_root(repo).await {
563        const GIT_TIMEOUT: Duration = Duration::from_secs(60);
564        let fetch_result = timeout(
565            GIT_TIMEOUT,
566            git_ops::git()
567                .await
568                .args(["-C", &repo_root, "fetch", "--prune", "origin"])
569                .output_with_context(),
570        )
571        .await;
572        match fetch_result {
573            Ok(Ok(output)) if output.status.success() => {
574                tracing::debug!(%repo, "fetched origin after task cleanup");
575            }
576            Ok(Ok(output)) => {
577                let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
578                tracing::debug!(%repo, err = %stderr, "git fetch skipped after task cleanup");
579            }
580            Ok(Err(e)) => {
581                tracing::debug!(%repo, err = %e, "git fetch failed after task cleanup");
582            }
583            Err(_) => {
584                tracing::debug!(%repo, "git fetch timed out after 60s");
585            }
586        }
587    }
588
589    Ok(())
590}
591
592/// Cleanup a single task's worktree and branches with explicit janitor options.
593///
594/// Returns `Ok(true)` when cleanup was actually performed and the task was
595/// marked as cleaned.  Returns `Ok(false)` when cleanup was intentionally
596/// skipped (TTL guard, active tmux session guard, or nothing on disk to remove).
597/// Returns `Err` on unexpected failures (e.g. cannot resolve the repo root).
598pub(crate) async fn cleanup_task_worktree_with_opts(
599    task_id: &str,
600    repo: &str,
601    store: &Arc<TaskStore>,
602    opts: &JanitorOptions,
603) -> anyhow::Result<bool> {
604    cleanup_task_worktree_with_opts_impl(task_id, repo, store, opts, false).await
605}
606
607async fn cleanup_task_worktree_with_opts_impl(
608    task_id: &str,
609    repo: &str,
610    store: &Arc<TaskStore>,
611    opts: &JanitorOptions,
612    known_pr_merged: bool,
613) -> anyhow::Result<bool> {
614    let (worktree, branch, keep_remote_branch, merged, external_id, pr_merged) =
615        store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
616            .await
617            .map_or((None, None, false, false, None, false), |t| {
618                // Blocked tasks with a PR should keep their remote branch so the
619                // PR stays open for human review.
620                let keep = t.status == TaskStatus::Blocked && t.pr_number.is_some();
621                let merged = t.status == TaskStatus::Done || known_pr_merged;
622                (
623                    Some(t.worktree).filter(|w| !w.is_empty()),
624                    Some(t.branch).filter(|b| !b.is_empty()),
625                    keep,
626                    merged,
627                    t.external_id,
628                    // A squash leaves the branch commits on no ref, so skip rescue when the PR merged
629                    known_pr_merged || (t.status == TaskStatus::Done && t.pr_number.is_some()),
630                )
631            });
632
633    let worktree_path = worktree.as_ref().map(PathBuf::from);
634
635    // Get worktrees base path
636    let worktrees_base = home::worktrees_dir().unwrap_or_else(|_| PathBuf::from(".orch/worktrees"));
637
638    // Determine which directory to remove.
639    //
640    // Priority:
641    //   1. stored "worktree" path, if it exists on disk.
642    //   2. Construct from worktrees_base + project name + branch, if it exists.
643    let worktree_to_remove = if let Some(ref wt) = worktree_path {
644        if match fs::try_exists(wt).await {
645            Ok(true) => true,
646            Ok(false) => false,
647            Err(e) => {
648                tracing::warn!(task_id, worktree = %wt.display(), err = %e, "try_exists failed on stored worktree path — trying branch-based fallback");
649                false
650            }
651        } {
652            Some(wt.clone())
653        } else {
654            // The recorded worktree path doesn't exist — try reconstructing from branch.
655            if let Some(ref b) = branch {
656                let project = repo
657                    .rsplit('/')
658                    .next()
659                    .unwrap_or(repo)
660                    .trim_end_matches(".git");
661                let candidate = worktrees_base.join(project).join(b);
662                if match fs::try_exists(&candidate).await {
663                    Ok(true) => true,
664                    Ok(false) => false,
665                    Err(e) => {
666                        tracing::warn!(task_id, err = %e, "try_exists failed — assuming candidate does not exist");
667                        false
668                    }
669                } {
670                    Some(candidate)
671                } else {
672                    None
673                }
674            } else {
675                None
676            }
677        }
678    } else if let Some(ref b) = branch {
679        // No worktree path in store — try branch-based path.
680        let project = repo
681            .rsplit('/')
682            .next()
683            .unwrap_or(repo)
684            .trim_end_matches(".git");
685        let candidate = worktrees_base.join(project).join(b);
686        if match fs::try_exists(&candidate).await {
687            Ok(true) => true,
688            Ok(false) => false,
689            Err(e) => {
690                tracing::warn!(task_id, err = %e, "try_exists failed — assuming candidate does not exist");
691                false
692            }
693        } {
694            Some(candidate)
695        } else {
696            None
697        }
698    } else {
699        None
700    };
701
702    let mut did_clean = false;
703
704    // If there's nothing to remove (no worktree path and no branch),
705    // treat as a no-op and return Ok(false) without attempting to
706    // resolve the repo root. Resolving the repo root can fail for
707    // projects not registered in config and that should not make
708    // cleanup a hard error when there is nothing to do.
709    let branch_nonempty = branch.as_ref().filter(|b| !b.is_empty());
710    if worktree_to_remove.is_none() && branch_nonempty.is_none() {
711        // If the stored worktree path is non-empty but doesn't exist on disk,
712        // the worktree is already gone — mark it cleaned so we stop retrying.
713        if worktree_path
714            .as_ref()
715            .is_some_and(|p| !p.as_os_str().is_empty())
716        {
717            tracing::debug!(
718                task_id,
719                worktree = ?worktree_path,
720                "stored worktree path no longer exists on disk — marking cleaned"
721            );
722            if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
723                && let Err(e) = store.mark_cleaned(store_id).await
724            {
725                tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned in store — will retry");
726            }
727        }
728        return Ok(false);
729    }
730
731    if let Some(wt) = worktree_to_remove {
732        // A task directory sits at least two levels under the base, never the base or a project dir
733        if let Ok(rel) = wt.strip_prefix(&worktrees_base)
734            && rel.components().count() < 2
735        {
736            tracing::warn!(
737                task_id,
738                worktree = %wt.display(),
739                "refusing to clean the worktrees root or a project directory"
740            );
741            return Ok(false);
742        }
743
744        // TTL guard: skip if the worktree directory is too young.
745        if let Some(age_hours) = worktree_age_hours(&wt).await
746            && age_hours < opts.ttl_hours
747        {
748            tracing::debug!(
749                task_id,
750                worktree = %wt.display(),
751                age_hours,
752                ttl_hours = opts.ttl_hours,
753                "worktree too young for cleanup, skipping"
754            );
755            return Ok(false);
756        }
757
758        // Tmux guard: skip if any active pane still has its cwd inside this worktree.
759        if is_worktree_in_active_session(&wt).await {
760            tracing::warn!(
761                task_id,
762                worktree = %wt.display(),
763                "worktree is referenced by an active tmux session — skipping cleanup"
764            );
765            return Ok(false);
766        }
767
768        // Validate git metadata before attempting any git operations.
769        // If the .git file points to a deleted gitdir the worktree is
770        // unrecoverable — force-remove the directory and skip git commands.
771        let gitdir_valid = worktree::validate_worktree_gitdir(&wt).await;
772
773        if opts.dry_run {
774            tracing::info!(
775                task_id,
776                worktree = %wt.display(),
777                branch = ?branch,
778                gitdir_valid,
779                "[dry-run] would remove worktree and branch"
780            );
781        } else if !gitdir_valid {
782            tracing::warn!(
783                task_id,
784                worktree = %wt.display(),
785                "worktree has broken git metadata — force-removing directory without git operations"
786            );
787            match fs::remove_dir_all(&wt).await {
788                Ok(()) => {
789                    did_clean = true;
790                }
791                Err(e) => {
792                    tracing::warn!(
793                        task_id,
794                        worktree = %wt.display(),
795                        err = %e,
796                        "failed to force-remove broken worktree directory"
797                    );
798                }
799            }
800        } else {
801            tracing::info!(task_id, worktree = %wt.display(), "removing worktree");
802            // Derive repo root from the worktree itself (for cross-project support).
803            // If the worktree belongs to a different project than the current repo
804            // context (e.g., internal task with worktree in another project), we can
805            // still find the repo root by examining the worktree's .git file.
806            let repo_root = match resolve_repo_root_from_worktree(&wt).await {
807                Ok(root) => root,
808                Err(_) => resolve_repo_root(repo).await?,
809            };
810            if let Some(br) = branch.as_deref().filter(|b| !b.is_empty())
811                && !pr_merged
812                && !rescue_and_notify(
813                    task_id,
814                    repo,
815                    external_id.as_deref(),
816                    Some(&wt),
817                    br,
818                    Path::new(&repo_root),
819                )
820                .await
821            {
822                return Ok(false);
823            }
824            if merged {
825                cow::warm_from_merged(
826                    Path::new(&repo_root),
827                    &worktree::project_name(Path::new(&repo_root)),
828                    &wt,
829                )
830                .await;
831            }
832            let removed = remove_worktree_and_branch_unchecked(
833                task_id,
834                &wt,
835                branch.as_deref(),
836                Path::new(&repo_root),
837                keep_remote_branch,
838            )
839            .await;
840            if removed {
841                did_clean = true;
842            } else {
843                tracing::warn!(
844                    task_id,
845                    worktree = %wt.display(),
846                    "worktree directory still exists after removal attempt — not marking as cleaned"
847                );
848            }
849        }
850    } else if let Some(ref br) = branch {
851        // Worktree directory is already gone, but the branch may still exist
852        // on the remote. Delete it to avoid orphaned branches.
853        if !opts.dry_run && !keep_remote_branch {
854            tracing::debug!(task_id, branch = %br, "no worktree on disk, cleaning up branch only");
855            // Resolve repo root lazily — branch cleanup needs it.
856            let repo_root = resolve_repo_root(repo).await?;
857            if !pr_merged
858                && !rescue_and_notify(
859                    task_id,
860                    repo,
861                    external_id.as_deref(),
862                    None,
863                    br,
864                    Path::new(&repo_root),
865                )
866                .await
867            {
868                return Ok(false);
869            }
870            delete_branches(task_id, br, Path::new(&repo_root)).await;
871            did_clean = true;
872        }
873    }
874
875    if did_clean {
876        // Mark as cleaned in store so we don't retry next tick.
877        // If resolve_task_id returns None the task is not (or no longer) in
878        // the store; that is fine — we already did the on-disk work.
879        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
880            && let Err(e) = store.mark_cleaned(store_id).await
881        {
882            tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned — will retry");
883            // Don't log activity; retry next tick will do the actual cleanup
884            return Ok(did_clean);
885        }
886        store_log_activity(
887            &Some(Arc::clone(store)),
888            repo,
889            task_id,
890            "branch_delete",
891            None,
892            None,
893            None,
894            None,
895            Some(&serde_json::json!({
896                "worktree": worktree_path.map(|p| p.display().to_string()),
897                "branch": branch,
898                "keep_remote_branch": keep_remote_branch,
899            })),
900        )
901        .await;
902    }
903
904    Ok(did_clean)
905}
906
907/// Result of saving a task branch's unpushed work before cleanup deletes it
908#[derive(Debug, PartialEq, Eq)]
909pub(crate) enum Rescue {
910    /// Every commit is on a remote ref already
911    Clean,
912    /// The commits were pushed to `rescue/<branch>`
913    Pushed {
914        branch: String,
915        commits: Vec<String>,
916    },
917    /// Git failed, so the worktree and branch must stay
918    Failed,
919}
920
921async fn git_in(dir: &Path, args: &[&str]) -> Option<Output> {
922    git_ops::git()
923        .await
924        .arg("-C")
925        .arg(dir)
926        .args(args)
927        .output_with_context()
928        .await
929        .ok()
930        .map(git_ops::sanitize_git_output)
931}
932
933/**
934 * Cleanup deletes the worktree and the local branch, which can be the only refs to commits the
935 * agent made before its run ended without a push (#3999). Uncommitted changes are committed
936 * first, then everything not on a remote ref goes to `rescue/<branch>`
937 **/
938pub(crate) async fn rescue_unpushed_work(
939    task_id: &str,
940    wt: Option<&Path>,
941    br: &str,
942    repo_root: &Path,
943) -> Rescue {
944    if let Some(wt) = wt
945        && fs::try_exists(wt.join(".git")).await.unwrap_or(false)
946    {
947        let Some(status) = git_in(wt, &["status", "--porcelain"]).await else {
948            tracing::warn!(task_id, branch = %br, "cannot read worktree status, keeping worktree");
949            return Rescue::Failed;
950        };
951        if !status.status.success() {
952            tracing::warn!(task_id, branch = %br, "git status failed, keeping worktree");
953            return Rescue::Failed;
954        }
955        if !status.stdout.is_empty() {
956            let committed = git_in(wt, &["add", "-A"])
957                .await
958                .is_some_and(|o| o.status.success())
959                && git_in(
960                    wt,
961                    &[
962                        "-c",
963                        "user.name=orch",
964                        "-c",
965                        "user.email=orch@localhost",
966                        "commit",
967                        "-m",
968                        "rescue: uncommitted changes saved by orch cleanup",
969                    ],
970                )
971                .await
972                .is_some_and(|o| o.status.success());
973            if !committed {
974                tracing::warn!(task_id, branch = %br, "cannot commit uncommitted changes, keeping worktree");
975                return Rescue::Failed;
976            }
977        }
978    }
979
980    let local_ref = format!("refs/heads/{br}");
981    let exists = git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
982        .await
983        .is_some_and(|o| o.status.success());
984    if !exists {
985        return Rescue::Clean;
986    }
987    // Commits on the local default branch survive the branch delete, so they do not count
988    let default_ref = format!(
989        "refs/heads/{}",
990        worktree::detect_default_branch(repo_root).await
991    );
992    // A bare clone has no remote-tracking refs, so ask the remote for the branch tip
993    let remote_tip = git_in(repo_root, &["ls-remote", "origin", &local_ref])
994        .await
995        .filter(|o| o.status.success())
996        .and_then(|o| {
997            String::from_utf8_lossy(&o.stdout)
998                .split_whitespace()
999                .next()
1000                .map(str::to_string)
1001        });
1002    // A tip someone else pushed may be missing locally, and rev-list fails on an unknown object
1003    let remote_tip = match remote_tip {
1004        Some(tip) => {
1005            let known = git_in(repo_root, &["cat-file", "-e", &format!("{tip}^{{commit}}")])
1006                .await
1007                .is_some_and(|o| o.status.success());
1008            known.then_some(tip)
1009        }
1010        None => None,
1011    };
1012    let mut args = vec!["rev-list", "--oneline", &local_ref, "--not", "--remotes"];
1013    if let Some(tip) = remote_tip.as_deref() {
1014        args.push(tip);
1015    }
1016    let default_exists = default_ref != local_ref
1017        && git_in(
1018            repo_root,
1019            &["rev-parse", "--verify", "--quiet", &default_ref],
1020        )
1021        .await
1022        .is_some_and(|o| o.status.success());
1023    if default_exists {
1024        args.push(&default_ref);
1025    }
1026    let Some(list) = git_in(repo_root, &args)
1027        .await
1028        .filter(|o| o.status.success())
1029    else {
1030        tracing::warn!(task_id, branch = %br, "cannot list unpushed commits, keeping worktree and branch");
1031        return Rescue::Failed;
1032    };
1033    let commits: Vec<String> = String::from_utf8_lossy(&list.stdout)
1034        .lines()
1035        .map(str::to_string)
1036        .collect();
1037    if commits.is_empty() {
1038        return Rescue::Clean;
1039    }
1040
1041    let rescue = format!("rescue/{br}");
1042    let refspec = format!("{local_ref}:refs/heads/{rescue}");
1043    let pushed = git_in(
1044        repo_root,
1045        &["-c", "lfs.locksverify=false", "push", "origin", &refspec],
1046    )
1047    .await;
1048    if pushed.is_some_and(|o| o.status.success()) {
1049        // A bare clone has no fetchspec, so push does not create the tracking ref
1050        // Point that ref at the tip we just sent so delete_local_branch can see it
1051        let tracking = format!("refs/remotes/origin/{rescue}");
1052        if let Some(tip) = git_in(repo_root, &["rev-parse", &local_ref])
1053            .await
1054            .filter(|o| o.status.success())
1055        {
1056            let sha = String::from_utf8_lossy(&tip.stdout).trim().to_string();
1057            if !sha.is_empty() {
1058                let _ = git_in(repo_root, &["update-ref", &tracking, &sha]).await;
1059            }
1060        }
1061        tracing::warn!(task_id, branch = %br, rescue = %rescue, commits = commits.len(), "pushed unpushed commits to rescue branch");
1062        Rescue::Pushed {
1063            branch: rescue,
1064            commits,
1065        }
1066    } else {
1067        tracing::warn!(task_id, branch = %br, rescue = %rescue, "rescue push failed, keeping worktree and branch");
1068        Rescue::Failed
1069    }
1070}
1071
1072fn rescue_comment(rescue_branch: &str, commits: &[String]) -> String {
1073    let list = commits
1074        .iter()
1075        .map(|c| format!("- `{c}`"))
1076        .collect::<Vec<_>>()
1077        .join("\n");
1078    format!(
1079        "Cleanup found commits on this task's branch that were never pushed. They are saved on `{rescue_branch}`:\n\n{list}"
1080    )
1081}
1082
1083/// Save unpushed work and tell the task about it. Returns false when cleanup must not go on
1084async fn rescue_and_notify(
1085    task_id: &str,
1086    repo: &str,
1087    external_id: Option<&str>,
1088    wt: Option<&Path>,
1089    br: &str,
1090    repo_root: &Path,
1091) -> bool {
1092    match rescue_unpushed_work(task_id, wt, br, repo_root).await {
1093        Rescue::Clean => true,
1094        Rescue::Failed => false,
1095        Rescue::Pushed { branch, commits } => {
1096            if let Some(number) = external_id.filter(|n| n.parse::<u64>().is_ok()) {
1097                match GhHttp::new() {
1098                    Ok(gh) => {
1099                        if let Err(e) = gh
1100                            .add_comment(repo, number, &rescue_comment(&branch, &commits))
1101                            .await
1102                        {
1103                            tracing::warn!(task_id, err = %e, "failed to comment on rescue branch");
1104                        }
1105                    }
1106                    Err(e) => {
1107                        tracing::warn!(task_id, err = %e, "cannot comment on rescue branch");
1108                    }
1109                }
1110            }
1111            true
1112        }
1113    }
1114}
1115
1116/// Remove a git worktree directory and its local + remote branches.
1117/// When `keep_remote_branch` is true, only the worktree and local branch are
1118/// removed — the remote branch stays so that any linked PR remains open
1119/// (used for blocked tasks awaiting human review).
1120/// Returns `true` if the worktree directory is gone after the call
1121/// (either we removed it or it was already absent).
1122pub(crate) async fn remove_worktree_and_branch(
1123    task_id: &str,
1124    wt: &Path,
1125    branch: Option<&str>,
1126    repo_root: &Path,
1127    keep_remote_branch: bool,
1128) -> bool {
1129    remove_worktree_and_branch_for(task_id, wt, branch, repo_root, keep_remote_branch, false).await
1130}
1131
1132/// Same as `remove_worktree_and_branch`, but a merged PR skips the rescue. A squash leaves the
1133/// branch commits on no ref, so the rescue would push a branch for work that already landed
1134pub(crate) async fn remove_worktree_and_branch_for(
1135    task_id: &str,
1136    wt: &Path,
1137    branch: Option<&str>,
1138    repo_root: &Path,
1139    keep_remote_branch: bool,
1140    pr_merged: bool,
1141) -> bool {
1142    if !pr_merged
1143        && let Some(br) = branch.filter(|b| !b.is_empty())
1144        && rescue_unpushed_work(task_id, Some(wt), br, repo_root).await == Rescue::Failed
1145    {
1146        return false;
1147    }
1148
1149    remove_worktree_and_branch_unchecked(task_id, wt, branch, repo_root, keep_remote_branch).await
1150}
1151
1152/// The caller has already rescued the branch or knows its PR merged
1153async fn remove_worktree_and_branch_unchecked(
1154    task_id: &str,
1155    wt: &Path,
1156    branch: Option<&str>,
1157    repo_root: &Path,
1158    keep_remote_branch: bool,
1159) -> bool {
1160    let wt_str = wt.to_string_lossy().to_string();
1161    let repo_root_str = repo_root.to_string_lossy();
1162
1163    // Remove worktree FIRST, then delete the branch.
1164    // Git refuses to remove a worktree if its branch is already deleted.
1165    let remove_result = Command::new("git")
1166        .args([
1167            "-C",
1168            repo_root_str.as_ref(),
1169            "worktree",
1170            "remove",
1171            &wt_str,
1172            "--force",
1173        ])
1174        .output_with_context()
1175        .await;
1176
1177    match remove_result {
1178        Ok(output) if output.status.success() => {
1179            const MAX_RETRIES: usize = 3;
1180            const RETRY_DELAY_MS: u64 = 2000;
1181            tracing::info!(task_id, "worktree removed (git metadata)");
1182            // `git worktree remove` only removes git metadata — the physical directory
1183            // with working files may remain. Clean it up with retry logic, since macOS
1184            // sometimes needs a moment to release file handles from a recently-exited
1185            // process. Retrying with a delay addresses "Directory not empty" errors.
1186            let mut removed = false;
1187            for attempt in 0..MAX_RETRIES {
1188                match fs::remove_dir_all(wt).await {
1189                    Ok(()) => {
1190                        removed = true;
1191                        break;
1192                    }
1193                    Err(e) if e.kind() == ErrorKind::NotFound => {
1194                        // Directory was already removed by git or another cleanup pass.
1195                        removed = true;
1196                        break;
1197                    }
1198                    Err(e) if e.kind() == ErrorKind::DirectoryNotEmpty => {
1199                        if attempt < MAX_RETRIES - 1 {
1200                            tracing::debug!(
1201                                task_id,
1202                                path = %wt.display(),
1203                                attempt = attempt + 1,
1204                                "worktree directory not empty — retrying after delay"
1205                            );
1206                            sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
1207                        } else {
1208                            tracing::warn!(
1209                                task_id,
1210                                path = %wt.display(),
1211                                err = %e,
1212                                "failed to remove worktree directory after {} attempts (Directory not empty)",
1213                                MAX_RETRIES
1214                            );
1215                        }
1216                    }
1217                    Err(e) => {
1218                        tracing::warn!(task_id, path = %wt.display(), err = %e, "failed to remove worktree directory");
1219                        break;
1220                    }
1221                }
1222            }
1223            if removed {
1224                tracing::info!(task_id, path = %wt.display(), "worktree physical directory removed");
1225            } else {
1226                tracing::warn!(
1227                    task_id,
1228                    path = %wt.display(),
1229                    "worktree directory still present after git worktree remove"
1230                );
1231            }
1232        }
1233        Ok(output) => {
1234            let stderr = String::from_utf8_lossy(&output.stderr);
1235            // "is not a working tree" means git's metadata is stale — the path
1236            // exists on disk but is no longer registered as a worktree. Treat
1237            // this as an already-gone worktree: physically remove the directory
1238            // and prune stale git metadata. Downgrade to debug — this is an
1239            // expected idempotency case, not a real error.
1240            if stderr.contains("is not a working tree") {
1241                tracing::debug!(
1242                    task_id,
1243                    path = %wt.display(),
1244                    "path is not a registered worktree (stale metadata) — removing directory and pruning"
1245                );
1246                if let Err(e) = fs::remove_dir_all(wt).await {
1247                    // Only warn if the directory actually still exists after removal attempt.
1248                    if match fs::try_exists(wt).await {
1249                        Ok(true) => true,
1250                        Ok(false) => false,
1251                        Err(e) => {
1252                            tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree does not exist");
1253                            false
1254                        }
1255                    } {
1256                        tracing::warn!(
1257                            task_id,
1258                            path = %wt.display(),
1259                            err = %e,
1260                            "failed to remove stale worktree directory"
1261                        );
1262                    }
1263                } else {
1264                    tracing::debug!(task_id, path = %wt.display(), "stale worktree directory removed");
1265                }
1266                // Prune stale worktree entries from git metadata so the warning
1267                // stops recurring on future `git worktree list` / cleanup cycles.
1268                if let Err(e) = Command::new("git")
1269                    .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1270                    .output_with_context()
1271                    .await
1272                {
1273                    tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1274                }
1275            } else {
1276                tracing::warn!(task_id, err = %stderr, "failed to remove worktree");
1277            }
1278        }
1279        Err(e) => {
1280            tracing::warn!(task_id, err = %e, "failed to remove worktree");
1281        }
1282    }
1283
1284    // Prune stale .git/worktrees/ entries left behind after removal.
1285    if let Err(e) = Command::new("git")
1286        .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1287        .output_with_context()
1288        .await
1289    {
1290        tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1291    }
1292
1293    // Delete local and remote branch from the main repo root (worktree is already gone).
1294    // When keep_remote_branch is set, only delete the local branch — the remote stays
1295    // so any linked PR remains open for human review.
1296    if let Some(br) = branch {
1297        if keep_remote_branch {
1298            delete_local_branch(task_id, br, repo_root).await;
1299        } else {
1300            delete_branches(task_id, br, repo_root).await;
1301        }
1302    }
1303
1304    // Definitively check: is the worktree directory actually gone?
1305    match fs::try_exists(wt).await {
1306        Ok(false) => true, // confirmed gone
1307        Ok(true) => false, // still there
1308        Err(e) => {
1309            tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree still present");
1310            false // conservative: don't claim success
1311        }
1312    }
1313}
1314
1315/// Whether `refs/heads/{br}` still exists in `repo_root`
1316pub(crate) async fn local_branch_exists(repo_root: &Path, br: &str) -> bool {
1317    let local_ref = format!("refs/heads/{br}");
1318    git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1319        .await
1320        .is_some_and(|o| o.status.success())
1321}
1322
1323/// Commits reachable from `rev` and from none of `others`. `None` when git cannot answer
1324async fn commits_outside(repo_root: &Path, rev: &str, others: &[&str]) -> Option<u64> {
1325    let mut args = vec![
1326        "rev-list".to_string(),
1327        "--count".to_string(),
1328        rev.to_string(),
1329    ];
1330    // One `--not` then every other ref, a `--not` per ref would toggle and count the wrong set
1331    let mut exclude = Vec::new();
1332    for other in others {
1333        let exists = Command::new("git")
1334            .args([
1335                "-C",
1336                &repo_root.to_string_lossy(),
1337                "rev-parse",
1338                "--verify",
1339                "--quiet",
1340                other,
1341            ])
1342            .output_with_context()
1343            .await
1344            .is_ok_and(|o| o.status.success());
1345        if exists {
1346            exclude.push(other.to_string());
1347        }
1348    }
1349    if !exclude.is_empty() {
1350        args.push("--not".to_string());
1351        args.extend(exclude);
1352    }
1353    let output = Command::new("git")
1354        .arg("-C")
1355        .arg(repo_root)
1356        .args(&args)
1357        .output_with_context()
1358        .await
1359        .ok()?;
1360    if !output.status.success() {
1361        return None;
1362    }
1363    String::from_utf8_lossy(&output.stdout).trim().parse().ok()
1364}
1365
1366/// Delete the local branch only when origin or the default branch holds every commit on it
1367async fn delete_local_branch(task_id: &str, br: &str, repo_root: &Path) {
1368    let default_branch = worktree::detect_default_branch(repo_root).await;
1369    let remote_ref = format!("refs/remotes/origin/{br}");
1370    let default_ref = format!("refs/remotes/origin/{default_branch}");
1371    let local_ref = format!("refs/heads/{br}");
1372    let local_default_ref = format!("refs/heads/{default_branch}");
1373    let rescue_ref = format!("refs/remotes/origin/rescue/{br}");
1374    match commits_outside(
1375        repo_root,
1376        &local_ref,
1377        &[&remote_ref, &default_ref, &local_default_ref, &rescue_ref],
1378    )
1379    .await
1380    {
1381        Some(0) => {}
1382        Some(n) => {
1383            tracing::warn!(task_id, branch = %br, unpushed = n, "local branch holds commits origin does not have, keeping it");
1384            return;
1385        }
1386        None => {
1387            tracing::debug!(task_id, branch = %br, "local branch missing or unreadable, nothing to delete");
1388            return;
1389        }
1390    }
1391    let output = Command::new("git")
1392        .args(["-C", &repo_root.to_string_lossy(), "branch", "-D", br])
1393        .output_with_context()
1394        .await;
1395    match output {
1396        Ok(o) if o.status.success() => {
1397            tracing::info!(task_id, branch = %br, "local branch deleted");
1398        }
1399        Ok(o) => {
1400            let stderr = String::from_utf8_lossy(&o.stderr);
1401            tracing::debug!(task_id, err = %stderr, "local branch delete skipped (may not exist)");
1402        }
1403        Err(e) => {
1404            tracing::warn!(task_id, err = %e, "failed to delete local branch");
1405        }
1406    }
1407}
1408
1409/**
1410 * Delete local and remote branches for a task, but never the only copy of a commit.
1411 * The remote branch goes only when the default branch already contains all of it, which
1412 * covers fast-forward and merge-commit merges. A squash-merged branch stays, and GitHub's
1413 * "automatically delete head branches" removes it. Every other caller (startup rebase
1414 * failure, closed-issue reconciliation, orphan sweeps) may hold unmerged work (#3781)
1415 **/
1416pub(crate) async fn delete_branches(task_id: &str, br: &str, repo_root: &Path) {
1417    if br == SCREENSHOTS_BRANCH {
1418        return;
1419    }
1420    let default_branch = worktree::detect_default_branch(repo_root).await;
1421    let _ = git_ops::git()
1422        .await
1423        .args([
1424            "-C",
1425            &repo_root.to_string_lossy(),
1426            "fetch",
1427            "origin",
1428            &default_branch,
1429            br,
1430        ])
1431        .output_with_context()
1432        .await;
1433
1434    delete_local_branch(task_id, br, repo_root).await;
1435
1436    let remote_ref = format!("refs/remotes/origin/{br}");
1437    let default_ref = format!("refs/remotes/origin/{default_branch}");
1438    match commits_outside(repo_root, &remote_ref, &[&default_ref]).await {
1439        Some(0) => {}
1440        Some(n) => {
1441            tracing::info!(task_id, branch = %br, unmerged = n, "remote branch has commits the default branch lacks, keeping it");
1442            return;
1443        }
1444        None => {
1445            tracing::debug!(task_id, branch = %br, "remote branch missing or unreadable, nothing to delete");
1446            return;
1447        }
1448    }
1449
1450    let remote_delete = git_ops::git()
1451        .await
1452        .args([
1453            "-C",
1454            &repo_root.to_string_lossy(),
1455            "-c",
1456            "lfs.locksverify=false",
1457            "push",
1458            "origin",
1459            "--delete",
1460            br,
1461        ])
1462        .output_with_context()
1463        .await;
1464
1465    match remote_delete {
1466        Ok(output) if output.status.success() => {
1467            tracing::info!(task_id, branch = %br, "remote branch deleted");
1468            git_ops::clear_push_lease(repo_root, br).await;
1469        }
1470        Ok(output) => {
1471            let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
1472            tracing::debug!(task_id, err = %stderr, "remote branch delete skipped");
1473        }
1474        Err(e) => {
1475            tracing::warn!(task_id, err = %e, "failed to delete remote branch");
1476        }
1477    }
1478}
1479
1480/// Returns `true` if any active tmux pane has its cwd inside `worktree`.
1481///
1482/// Uses `tmux list-panes -a -F '#{pane_current_path}'` to enumerate all
1483/// pane working directories across every session. If tmux is not running
1484/// (command fails), we conservatively return `false` so cleanup can proceed.
1485async fn is_worktree_in_active_session(worktree: &Path) -> bool {
1486    let output = Command::new("tmux")
1487        .args(["list-panes", "-a", "-F", "#{pane_current_path}"])
1488        .output()
1489        .await;
1490
1491    match output {
1492        Ok(o) if o.status.success() => {
1493            let worktree_str = worktree.to_string_lossy();
1494            String::from_utf8_lossy(&o.stdout).lines().any(|line| {
1495                let pane_path = line.trim();
1496                // Match exact path or any path that starts with worktree + separator.
1497                pane_path == worktree_str.as_ref()
1498                    || pane_path.starts_with(&format!("{worktree_str}/"))
1499            })
1500        }
1501        // tmux not running or no sessions — treat as safe to clean.
1502        _ => false,
1503    }
1504}
1505
1506/// Returns how many hours old the worktree directory is, based on its mtime.
1507///
1508/// Returns `None` if the directory does not exist or the mtime cannot be read.
1509async fn worktree_age_hours(worktree: &Path) -> Option<u64> {
1510    // Use tokio::fs to avoid blocking the async runtime when reading metadata.
1511    let metadata = fs::metadata(worktree).await.ok()?;
1512    let modified = metadata.modified().ok()?;
1513    let age = SystemTime::now().duration_since(modified).ok()?;
1514    Some(age.as_secs() / 3600)
1515}
1516
1517/// Resolve the repo root for an orphaned worktree and remove it.
1518///
1519/// Used by `orch service doctor --fix` and `orch service prune` to clean up worktrees that are
1520/// no longer owned by any task. Returns `true` if the worktree directory is gone
1521/// after the call.
1522pub(crate) async fn cleanup_orphaned_worktree(task_id: &str, wt: &Path) -> bool {
1523    let repo_root = match resolve_repo_root_for_orphaned_worktree(wt).await {
1524        Ok(root) => root,
1525        Err(e) => {
1526            tracing::warn!(
1527                worktree = %wt.display(),
1528                error = %e,
1529                "cannot resolve repo root for orphaned worktree"
1530            );
1531            return false;
1532        }
1533    };
1534    remove_worktree_and_branch(task_id, wt, None, Path::new(&repo_root), false).await
1535}
1536
1537/// Resolve the main git repository root for an orphaned worktree.
1538///
1539/// First tries to parse the `.git` file's `gitdir:` pointer (two levels up from
1540/// the pointer gives the bare repo root, which is the orch convention). Falls back
1541/// to looking up registered projects by directory name when the `.git` file is
1542/// absent or unparseable.
1543pub(crate) async fn resolve_repo_root_for_orphaned_worktree(wt: &Path) -> anyhow::Result<String> {
1544    let git_file = wt.join(".git");
1545    if fs::try_exists(&git_file).await.unwrap_or(false)
1546        && let Ok(content) = fs::read_to_string(&git_file).await
1547    {
1548        for line in content.lines() {
1549            if let Some(gitdir) = line.strip_prefix("gitdir: ") {
1550                // gitdir points to: <repo>/.git/worktrees/<name> (non-bare)
1551                //                or <repo>.git/worktrees/<name>   (bare)
1552                // Two levels up reaches the .git dir / bare repo root.
1553                let gitdir_path = PathBuf::from(gitdir);
1554                if let Some(repo_root) = gitdir_path.parent().and_then(|p| p.parent()) {
1555                    return Ok(repo_root.display().to_string());
1556                }
1557            }
1558        }
1559    }
1560
1561    // Fallback: look up registered projects by the project-name component of the
1562    // worktree path (format: ~/.orch/worktrees/<project>/<branch>).
1563    let worktrees_dir = home::worktrees_dir()?;
1564    if let Ok(relative) = wt.strip_prefix(&worktrees_dir)
1565        && let Some(project_name) = relative.components().next()
1566    {
1567        let project_name = project_name.as_os_str().to_string_lossy();
1568
1569        if let Ok(paths) = config::get_project_paths() {
1570            for path_str in &paths {
1571                let path = Path::new(path_str);
1572                if let Some(name) = path.file_name()
1573                    && name.to_string_lossy() == project_name
1574                {
1575                    return Ok(path_str.clone());
1576                }
1577            }
1578        }
1579
1580        // Try bare clone at ~/.orch/projects/<owner>/<project>.git
1581        let parts: Vec<&str> = project_name.split('/').collect();
1582        let bare = if parts.len() == 2 {
1583            home::projects_dir()
1584                .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1585                .unwrap_or_default()
1586        } else {
1587            return Err(anyhow::anyhow!(
1588                "cannot determine owner for single-segment project name '{project_name}' — \
1589                     bare repo location is ambiguous; register the project with 'owner/repo' format"
1590            ));
1591        };
1592        if fs::try_exists(&bare).await.unwrap_or(false) {
1593            return Ok(bare.display().to_string());
1594        }
1595    }
1596
1597    anyhow::bail!(
1598        "cannot resolve repo root for orphaned worktree at {} — tried .git parsing and project lookup",
1599        wt.display()
1600    )
1601}
1602
1603/// Resolve the main git repository root from a worktree's .git file.
1604///
1605/// For cross-project worktree cleanup, we cannot rely on `resolve_repo_root` because
1606/// the worktree may belong to a different project than the current repo context.
1607/// Instead, we extract the repo root from the worktree's `.git` file which contains
1608/// a `gitdir:` pointer to the main repo's git directory.
1609pub async fn resolve_repo_root_from_worktree(wt: &Path) -> anyhow::Result<String> {
1610    // For worktrees, .git is a file (not a directory) containing gitdir path
1611    let git_file = wt.join(".git");
1612    if !fs::try_exists(&git_file).await.unwrap_or(false) {
1613        anyhow::bail!(".git file not found in worktree at {}", wt.display());
1614    }
1615
1616    let content = fs::read_to_string(&git_file)
1617        .await
1618        .map_err(|e| anyhow::anyhow!("failed to read .git file: {e}"))?;
1619
1620    // Parse gitdir line: "gitdir: /path/to/repo/.git/worktrees/<name>"
1621    for line in content.lines() {
1622        if let Some(gitdir) = line.strip_prefix("gitdir:") {
1623            let gitdir = gitdir.trim();
1624            // The main repo is the parent of the .git directory
1625            // gitdir points to: <repo>/.git/worktrees/<name>
1626            // We need to go up 3 levels: worktrees/<name> -> .git -> repo
1627            let gitdir_path = Path::new(gitdir);
1628            if let Some(repo_root) = gitdir_path
1629                .parent() // worktrees/<name>
1630                .and_then(|p| p.parent()) // .git
1631                .and_then(|p| p.parent())
1632            // repo root
1633            {
1634                return Ok(repo_root.display().to_string());
1635            }
1636        }
1637    }
1638
1639    anyhow::bail!(
1640        "cannot resolve repo root from worktree .git file at {}",
1641        wt.display()
1642    )
1643}
1644
1645/// Resolve the main git repository root path for a project.
1646///
1647/// Looks up the local project path from config, then verifies it's a git repo.
1648/// This avoids relying on cwd (which is undefined under launchd services).
1649pub(crate) async fn resolve_repo_root(repo: &str) -> anyhow::Result<String> {
1650    // Look up the local path from registered projects
1651    let paths = config::get_project_paths().unwrap_or_default();
1652    for path_str in &paths {
1653        let path = Path::new(path_str);
1654        let orch_yml = path.join(".orch.yml");
1655        let legacy = path.join(".orchestrator.yml");
1656        let config_file = if fs::try_exists(&orch_yml).await.unwrap_or(false) {
1657            orch_yml
1658        } else if fs::try_exists(&legacy).await.unwrap_or(false) {
1659            legacy
1660        } else {
1661            continue;
1662        };
1663        if let Ok(content) = fs::read_to_string(&config_file).await
1664            && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1665            && let Some(r) = doc
1666                .get("gh")
1667                .and_then(|gh| gh.get("repo"))
1668                .and_then(|r| r.as_str())
1669            && r == repo
1670        {
1671            return Ok(path_str.clone());
1672        }
1673    }
1674
1675    // Fallback: try bare clone in ~/.orch/projects/<owner>/<repo>.git
1676    let parts: Vec<&str> = repo.split('/').collect();
1677    let bare = if parts.len() == 2 {
1678        home::projects_dir()
1679            .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1680            .unwrap_or_default()
1681    } else {
1682        PathBuf::new()
1683    };
1684    if fs::try_exists(&bare).await.unwrap_or(false) {
1685        return Ok(bare.display().to_string());
1686    }
1687
1688    anyhow::bail!(
1689        "cannot find local path for project {repo} — \
1690         checked {} registered project(s) and bare clone at {}",
1691        paths.len(),
1692        bare.display()
1693    )
1694}
1695
1696/// Resolve the project directory for a given repo string.
1697///
1698/// Replicates the logic from `TaskRunner::resolve_project_dir()` without requiring
1699/// a Runner instance. Used by the orphan scanner to enumerate active worktrees.
1700fn resolve_project_dir_for_repo(repo: &str) -> anyhow::Result<PathBuf> {
1701    // Check PROJECT_DIR env var first
1702    if let Ok(dir) = env::var("PROJECT_DIR")
1703        && !dir.is_empty()
1704    {
1705        return Ok(PathBuf::from(dir));
1706    }
1707
1708    // Look up registered projects in config
1709    if let Ok(paths) = config::get_project_paths() {
1710        for path_str in &paths {
1711            let path = Path::new(path_str);
1712            let orch_yml = path.join(".orch.yml");
1713            let legacy = path.join(".orchestrator.yml");
1714            let config_file = if Path::new(&orch_yml).exists() {
1715                orch_yml
1716            } else if Path::new(&legacy).exists() {
1717                legacy
1718            } else {
1719                continue;
1720            };
1721            if let Ok(content) = std_fs::read_to_string(&config_file)
1722                && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1723                && let Some(r) = doc
1724                    .get("gh")
1725                    .and_then(|gh| gh.get("repo"))
1726                    .and_then(|r| r.as_str())
1727                && r == repo
1728            {
1729                return Ok(path_str.clone().into());
1730            }
1731        }
1732    }
1733
1734    anyhow::bail!("project dir not found for repo: {repo}")
1735}
1736
1737/// Check for merged PRs and update task status accordingly.
1738///
1739/// Queries status:in_review and status:needs_review tasks, checks if their PR
1740/// is merged, and updates status to done if merged.
1741pub(crate) async fn check_merged_prs(
1742    backend: &Arc<dyn ExternalBackend>,
1743    repo: &str,
1744    store: &Arc<TaskStore>,
1745    task_manager: &Arc<TaskManager>,
1746    in_review_tasks: &[ReviewTaskSnapshot],
1747    needs_review_tasks: &[ReviewTaskSnapshot],
1748) -> anyhow::Result<()> {
1749    let mut branch_map: HashMap<String, String> = HashMap::new();
1750    let all_review_tasks: Vec<&ReviewTaskSnapshot> = in_review_tasks
1751        .iter()
1752        .chain(needs_review_tasks.iter())
1753        .collect();
1754
1755    for task in &all_review_tasks {
1756        if !task.stored.branch.is_empty() {
1757            branch_map.insert(task.external.id.0.clone(), task.stored.branch.clone());
1758        }
1759    }
1760
1761    tracing::debug!(
1762        count = all_review_tasks.len(),
1763        "checking review tasks for merged PRs"
1764    );
1765
1766    // Collect (task_id, branch) pairs — skip tasks with no branch recorded.
1767    // Use the pre-built branch map; fall back to store lookup only for tasks
1768    // not in the map (e.g. internal tasks, backend fallback path).
1769    let mut task_branches: Vec<(String, String)> = Vec::new();
1770    for task in all_review_tasks {
1771        let task_id = &task.external.id.0;
1772        let branch = if let Some(b) = branch_map.get(task_id) {
1773            b.clone()
1774        } else {
1775            match store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
1776                .await
1777                .map(|t| t.branch)
1778            {
1779                Some(b) if !b.is_empty() => b,
1780                _ => {
1781                    tracing::debug!(task_id, "no branch info, skipping PR check");
1782                    continue;
1783                }
1784            }
1785        };
1786        task_branches.push((task_id.clone(), branch));
1787    }
1788
1789    if task_branches.is_empty() {
1790        return Ok(());
1791    }
1792
1793    // Single GraphQL call for all branches — N REST calls → 1 GraphQL call.
1794    let branches: Vec<String> = task_branches.iter().map(|(_, b)| b.clone()).collect();
1795    let merged_map = match backend.batch_is_pr_merged(&branches).await {
1796        Ok(map) => map,
1797        Err(e) => {
1798            tracing::warn!(
1799                err = %e,
1800                branch_count = branches.len(),
1801                "batch PR merge check failed, retrying affected branches individually"
1802            );
1803            fallback_is_pr_merged_by_branch(backend, &branches).await
1804        }
1805    };
1806
1807    for (task_id, branch) in task_branches {
1808        let is_merged = merged_map.get(&branch).copied().unwrap_or(false);
1809        if !is_merged {
1810            continue;
1811        }
1812
1813        tracing::info!(task_id, branch = %branch, "PR merged, marking task complete");
1814
1815        let stored = store::opt_store_get_task(&Some(Arc::clone(store)), repo, &task_id).await;
1816        if let Some(ref stored) = stored {
1817            let external = store_task_to_external(stored);
1818            if ci_bootstrap::hold_after_merge(&external, store, repo).await {
1819                tracing::info!(
1820                    task_id,
1821                    branch = %branch,
1822                    "CI bootstrap PR merged, holding done until the ruleset exists"
1823                );
1824                if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1825                    tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1826                }
1827                continue;
1828            }
1829        }
1830
1831        let id = ExternalId(task_id.clone());
1832        if let Err(e) = task_manager.update_task_status(&id, Status::Done).await {
1833            tracing::warn!(task_id, err = %e, "failed to update status to done");
1834            continue;
1835        }
1836
1837        if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1838            tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1839        }
1840
1841        let comment = format!("PR merged, marking task complete{}", engine::orch_footer());
1842        if let Err(e) = backend.post_comment(&id, &comment).await {
1843            tracing::warn!(task_id, err = %e, "failed to post comment");
1844        }
1845    }
1846
1847    Ok(())
1848}
1849
1850async fn fallback_is_pr_merged_by_branch(
1851    backend: &Arc<dyn ExternalBackend>,
1852    branches: &[String],
1853) -> HashMap<String, bool> {
1854    let futs: Vec<_> = branches
1855        .iter()
1856        .map(|branch| {
1857            let backend = Arc::clone(backend);
1858            let branch = branch.clone();
1859            async move {
1860                match backend.is_pr_merged(&branch).await {
1861                    Ok(is_merged) => Some((branch, is_merged)),
1862                    Err(err) => {
1863                        tracing::warn!(
1864                            branch,
1865                            err = %err,
1866                            "fallback PR merge check failed for branch"
1867                        );
1868                        None
1869                    }
1870                }
1871            }
1872        })
1873        .collect();
1874
1875    future::join_all(futs).await.into_iter().flatten().collect()
1876}
1877
1878#[derive(Debug, Clone)]
1879pub(crate) struct ReviewTaskSnapshot {
1880    pub external: ExternalTask,
1881    pub stored: Task,
1882}
1883
1884#[cfg(test)]
1885mod tests;