Skip to main content

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