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 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::sys::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 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 = if merged && remove_landed_worktree(&wt, Path::new(&repo_root)).await {
833                if let Some(br) = branch.as_deref().filter(|_| !keep_remote_branch) {
834                    delete_branches(task_id, br, Path::new(&repo_root)).await;
835                }
836                true
837            } else {
838                remove_worktree_and_branch_unchecked(
839                    task_id,
840                    &wt,
841                    branch.as_deref(),
842                    Path::new(&repo_root),
843                    keep_remote_branch,
844                )
845                .await
846            };
847            if removed {
848                did_clean = true;
849            } else {
850                tracing::warn!(
851                    task_id,
852                    worktree = %wt.display(),
853                    "worktree directory still exists after removal attempt — not marking as cleaned"
854                );
855            }
856        }
857    } else if let Some(ref br) = branch {
858        // Worktree directory is already gone, but the branch may still exist
859        // on the remote. Delete it to avoid orphaned branches.
860        if !opts.dry_run && !keep_remote_branch {
861            tracing::debug!(task_id, branch = %br, "no worktree on disk, cleaning up branch only");
862            // Resolve repo root lazily — branch cleanup needs it.
863            let repo_root = resolve_repo_root(repo).await?;
864            if !pr_merged
865                && !rescue_and_notify(
866                    task_id,
867                    repo,
868                    external_id.as_deref(),
869                    None,
870                    br,
871                    Path::new(&repo_root),
872                )
873                .await
874            {
875                return Ok(false);
876            }
877            delete_branches(task_id, br, Path::new(&repo_root)).await;
878            did_clean = true;
879        }
880    }
881
882    if did_clean {
883        // Mark as cleaned in store so we don't retry next tick.
884        // If resolve_task_id returns None the task is not (or no longer) in
885        // the store; that is fine — we already did the on-disk work.
886        if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
887            && let Err(e) = store.mark_cleaned(store_id).await
888        {
889            tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned — will retry");
890            // Don't log activity; retry next tick will do the actual cleanup
891            return Ok(did_clean);
892        }
893        store_log_activity(
894            &Some(Arc::clone(store)),
895            repo,
896            task_id,
897            "branch_delete",
898            None,
899            None,
900            None,
901            None,
902            Some(&serde_json::json!({
903                "worktree": worktree_path.map(|p| p.display().to_string()),
904                "branch": branch,
905                "keep_remote_branch": keep_remote_branch,
906            })),
907        )
908        .await;
909    }
910
911    Ok(did_clean)
912}
913
914// Where the step after a merge keeps the fetched tip of the default branch
915const LANDED_BASE_REF: &str = "refs/orch/landed-base";
916
917/**
918 * Fetch the default branch into a ref of orch's own and let git-cow compare the worktree with it.
919 * A bare clone has no fetch refspec, so a plain fetch moves only FETCH_HEAD and its local default
920 * branch stays where the clone left it. FETCH_HEAD is not used because another fetch in the same
921 * repository can point it at a task branch
922 **/
923async fn remove_landed_worktree(wt: &Path, repo_root: &Path) -> bool {
924    const GIT_TIMEOUT: Duration = Duration::from_secs(60);
925    let default_branch = worktree::detect_default_branch(repo_root).await;
926    let refspec = format!("+refs/heads/{default_branch}:{LANDED_BASE_REF}");
927    let fetched = timeout(
928        GIT_TIMEOUT,
929        git_in(repo_root, &["fetch", "origin", &refspec]),
930    )
931    .await
932    .ok()
933    .flatten()
934    .is_some_and(|o| o.status.success());
935    if !fetched {
936        tracing::debug!(worktree = %wt.display(), "default branch fetch failed, skipping git-cow cleanup");
937        return false;
938    }
939    cow::remove_landed(repo_root, wt, Some(LANDED_BASE_REF)).await
940}
941
942/// Result of saving a task branch's unpushed work before cleanup deletes it
943#[derive(Debug, PartialEq, Eq)]
944pub(crate) enum Rescue {
945    /// Every commit is on a remote ref already
946    Clean,
947    /// The commits were pushed to `rescue/<branch>`
948    Pushed {
949        branch: String,
950        commits: Vec<String>,
951    },
952    /// Git failed, so the worktree and branch must stay
953    Failed,
954}
955
956async fn git_in(dir: &Path, args: &[&str]) -> Option<Output> {
957    git_ops::git()
958        .await
959        .arg("-C")
960        .arg(dir)
961        .args(args)
962        .output_with_context()
963        .await
964        .ok()
965        .map(git_ops::sanitize_git_output)
966}
967
968/**
969 * Cleanup deletes the worktree and the local branch, which can be the only refs to commits the
970 * agent made before its run ended without a push (#3999). Uncommitted changes are committed
971 * first, then everything not on a remote ref goes to `rescue/<branch>`
972 **/
973pub(crate) async fn rescue_unpushed_work(
974    task_id: &str,
975    wt: Option<&Path>,
976    br: &str,
977    repo_root: &Path,
978) -> Rescue {
979    if let Some(wt) = wt
980        && fs::try_exists(wt.join(".git")).await.unwrap_or(false)
981    {
982        let Some(status) = git_in(wt, &["status", "--porcelain"]).await else {
983            tracing::warn!(task_id, branch = %br, "cannot read worktree status, keeping worktree");
984            return Rescue::Failed;
985        };
986        if !status.status.success() {
987            tracing::warn!(task_id, branch = %br, "git status failed, keeping worktree");
988            return Rescue::Failed;
989        }
990        if !status.stdout.is_empty() {
991            let committed = git_in(wt, &["add", "-A"])
992                .await
993                .is_some_and(|o| o.status.success())
994                && git_in(
995                    wt,
996                    &[
997                        "-c",
998                        "user.name=orch",
999                        "-c",
1000                        "user.email=orch@localhost",
1001                        "commit",
1002                        "-m",
1003                        "rescue: uncommitted changes saved by orch cleanup",
1004                    ],
1005                )
1006                .await
1007                .is_some_and(|o| o.status.success());
1008            if !committed {
1009                tracing::warn!(task_id, branch = %br, "cannot commit uncommitted changes, keeping worktree");
1010                return Rescue::Failed;
1011            }
1012        }
1013    }
1014
1015    let local_ref = format!("refs/heads/{br}");
1016    let exists = git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1017        .await
1018        .is_some_and(|o| o.status.success());
1019    if !exists {
1020        return Rescue::Clean;
1021    }
1022    // Commits on the local default branch survive the branch delete, so they do not count
1023    let default_ref = format!(
1024        "refs/heads/{}",
1025        worktree::detect_default_branch(repo_root).await
1026    );
1027    // A bare clone has no remote-tracking refs, so ask the remote for the branch tip
1028    let remote_tip = git_in(repo_root, &["ls-remote", "origin", &local_ref])
1029        .await
1030        .filter(|o| o.status.success())
1031        .and_then(|o| {
1032            String::from_utf8_lossy(&o.stdout)
1033                .split_whitespace()
1034                .next()
1035                .map(str::to_string)
1036        });
1037    // A tip someone else pushed may be missing locally, and rev-list fails on an unknown object
1038    let remote_tip = match remote_tip {
1039        Some(tip) => {
1040            let known = git_in(repo_root, &["cat-file", "-e", &format!("{tip}^{{commit}}")])
1041                .await
1042                .is_some_and(|o| o.status.success());
1043            known.then_some(tip)
1044        }
1045        None => None,
1046    };
1047    let mut args = vec!["rev-list", "--oneline", &local_ref, "--not", "--remotes"];
1048    if let Some(tip) = remote_tip.as_deref() {
1049        args.push(tip);
1050    }
1051    let default_exists = default_ref != local_ref
1052        && git_in(
1053            repo_root,
1054            &["rev-parse", "--verify", "--quiet", &default_ref],
1055        )
1056        .await
1057        .is_some_and(|o| o.status.success());
1058    if default_exists {
1059        args.push(&default_ref);
1060    }
1061    let Some(list) = git_in(repo_root, &args)
1062        .await
1063        .filter(|o| o.status.success())
1064    else {
1065        tracing::warn!(task_id, branch = %br, "cannot list unpushed commits, keeping worktree and branch");
1066        return Rescue::Failed;
1067    };
1068    let commits: Vec<String> = String::from_utf8_lossy(&list.stdout)
1069        .lines()
1070        .map(str::to_string)
1071        .collect();
1072    if commits.is_empty() {
1073        return Rescue::Clean;
1074    }
1075
1076    let rescue = format!("rescue/{br}");
1077    let refspec = format!("{local_ref}:refs/heads/{rescue}");
1078    let pushed = git_in(
1079        repo_root,
1080        &["-c", "lfs.locksverify=false", "push", "origin", &refspec],
1081    )
1082    .await;
1083    if pushed.is_some_and(|o| o.status.success()) {
1084        // A bare clone has no fetchspec, so push does not create the tracking ref
1085        // Point that ref at the tip we just sent so delete_local_branch can see it
1086        let tracking = format!("refs/remotes/origin/{rescue}");
1087        if let Some(tip) = git_in(repo_root, &["rev-parse", &local_ref])
1088            .await
1089            .filter(|o| o.status.success())
1090        {
1091            let sha = String::from_utf8_lossy(&tip.stdout).trim().to_string();
1092            if !sha.is_empty() {
1093                let _ = git_in(repo_root, &["update-ref", &tracking, &sha]).await;
1094            }
1095        }
1096        tracing::warn!(task_id, branch = %br, rescue = %rescue, commits = commits.len(), "pushed unpushed commits to rescue branch");
1097        Rescue::Pushed {
1098            branch: rescue,
1099            commits,
1100        }
1101    } else {
1102        tracing::warn!(task_id, branch = %br, rescue = %rescue, "rescue push failed, keeping worktree and branch");
1103        Rescue::Failed
1104    }
1105}
1106
1107fn rescue_comment(rescue_branch: &str, commits: &[String]) -> String {
1108    let list = commits
1109        .iter()
1110        .map(|c| format!("- `{c}`"))
1111        .collect::<Vec<_>>()
1112        .join("\n");
1113    format!(
1114        "Cleanup found commits on this task's branch that were never pushed. They are saved on `{rescue_branch}`:\n\n{list}"
1115    )
1116}
1117
1118/// Save unpushed work and tell the task about it. Returns false when cleanup must not go on
1119async fn rescue_and_notify(
1120    task_id: &str,
1121    repo: &str,
1122    external_id: Option<&str>,
1123    wt: Option<&Path>,
1124    br: &str,
1125    repo_root: &Path,
1126) -> bool {
1127    match rescue_unpushed_work(task_id, wt, br, repo_root).await {
1128        Rescue::Clean => true,
1129        Rescue::Failed => false,
1130        Rescue::Pushed { branch, commits } => {
1131            if let Some(number) = external_id.filter(|n| n.parse::<u64>().is_ok()) {
1132                match GhHttp::new() {
1133                    Ok(gh) => {
1134                        if let Err(e) = gh
1135                            .add_comment(repo, number, &rescue_comment(&branch, &commits))
1136                            .await
1137                        {
1138                            tracing::warn!(task_id, err = %e, "failed to comment on rescue branch");
1139                        }
1140                    }
1141                    Err(e) => {
1142                        tracing::warn!(task_id, err = %e, "cannot comment on rescue branch");
1143                    }
1144                }
1145            }
1146            true
1147        }
1148    }
1149}
1150
1151/// Remove a git worktree directory and its local + remote branches.
1152/// When `keep_remote_branch` is true, only the worktree and local branch are
1153/// removed — the remote branch stays so that any linked PR remains open
1154/// (used for blocked tasks awaiting human review).
1155/// Returns `true` if the worktree directory is gone after the call
1156/// (either we removed it or it was already absent).
1157pub(crate) async fn remove_worktree_and_branch(
1158    task_id: &str,
1159    wt: &Path,
1160    branch: Option<&str>,
1161    repo_root: &Path,
1162    keep_remote_branch: bool,
1163) -> bool {
1164    remove_worktree_and_branch_for(task_id, wt, branch, repo_root, keep_remote_branch, false).await
1165}
1166
1167/// Same as `remove_worktree_and_branch`, but a merged PR skips the rescue. A squash leaves the
1168/// branch commits on no ref, so the rescue would push a branch for work that already landed
1169pub(crate) async fn remove_worktree_and_branch_for(
1170    task_id: &str,
1171    wt: &Path,
1172    branch: Option<&str>,
1173    repo_root: &Path,
1174    keep_remote_branch: bool,
1175    pr_merged: bool,
1176) -> bool {
1177    if !pr_merged
1178        && let Some(br) = branch.filter(|b| !b.is_empty())
1179        && rescue_unpushed_work(task_id, Some(wt), br, repo_root).await == Rescue::Failed
1180    {
1181        return false;
1182    }
1183
1184    remove_worktree_and_branch_unchecked(task_id, wt, branch, repo_root, keep_remote_branch).await
1185}
1186
1187/// The caller has already rescued the branch or knows its PR merged
1188async fn remove_worktree_and_branch_unchecked(
1189    task_id: &str,
1190    wt: &Path,
1191    branch: Option<&str>,
1192    repo_root: &Path,
1193    keep_remote_branch: bool,
1194) -> bool {
1195    let wt_str = wt.to_string_lossy().to_string();
1196    let repo_root_str = repo_root.to_string_lossy();
1197
1198    // Remove worktree FIRST, then delete the branch.
1199    // Git refuses to remove a worktree if its branch is already deleted.
1200    let remove_result = Command::new("git")
1201        .args([
1202            "-C",
1203            repo_root_str.as_ref(),
1204            "worktree",
1205            "remove",
1206            &wt_str,
1207            "--force",
1208        ])
1209        .output_with_context()
1210        .await;
1211
1212    match remove_result {
1213        Ok(output) if output.status.success() => {
1214            const MAX_RETRIES: usize = 3;
1215            const RETRY_DELAY_MS: u64 = 2000;
1216            tracing::info!(task_id, "worktree removed (git metadata)");
1217            // `git worktree remove` only removes git metadata — the physical directory
1218            // with working files may remain. Clean it up with retry logic, since macOS
1219            // sometimes needs a moment to release file handles from a recently-exited
1220            // process. Retrying with a delay addresses "Directory not empty" errors.
1221            let mut removed = false;
1222            for attempt in 0..MAX_RETRIES {
1223                match fs::remove_dir_all(wt).await {
1224                    Ok(()) => {
1225                        removed = true;
1226                        break;
1227                    }
1228                    Err(e) if e.kind() == ErrorKind::NotFound => {
1229                        // Directory was already removed by git or another cleanup pass.
1230                        removed = true;
1231                        break;
1232                    }
1233                    Err(e) if e.kind() == ErrorKind::DirectoryNotEmpty => {
1234                        if attempt < MAX_RETRIES - 1 {
1235                            tracing::debug!(
1236                                task_id,
1237                                path = %wt.display(),
1238                                attempt = attempt + 1,
1239                                "worktree directory not empty — retrying after delay"
1240                            );
1241                            sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
1242                        } else {
1243                            tracing::warn!(
1244                                task_id,
1245                                path = %wt.display(),
1246                                err = %e,
1247                                "failed to remove worktree directory after {} attempts (Directory not empty)",
1248                                MAX_RETRIES
1249                            );
1250                        }
1251                    }
1252                    Err(e) => {
1253                        tracing::warn!(task_id, path = %wt.display(), err = %e, "failed to remove worktree directory");
1254                        break;
1255                    }
1256                }
1257            }
1258            if removed {
1259                tracing::info!(task_id, path = %wt.display(), "worktree physical directory removed");
1260            } else {
1261                tracing::warn!(
1262                    task_id,
1263                    path = %wt.display(),
1264                    "worktree directory still present after git worktree remove"
1265                );
1266            }
1267        }
1268        Ok(output) => {
1269            let stderr = String::from_utf8_lossy(&output.stderr);
1270            // "is not a working tree" means git's metadata is stale — the path
1271            // exists on disk but is no longer registered as a worktree. Treat
1272            // this as an already-gone worktree: physically remove the directory
1273            // and prune stale git metadata. Downgrade to debug — this is an
1274            // expected idempotency case, not a real error.
1275            if stderr.contains("is not a working tree") {
1276                tracing::debug!(
1277                    task_id,
1278                    path = %wt.display(),
1279                    "path is not a registered worktree (stale metadata) — removing directory and pruning"
1280                );
1281                if let Err(e) = fs::remove_dir_all(wt).await {
1282                    // Only warn if the directory actually still exists after removal attempt.
1283                    if match fs::try_exists(wt).await {
1284                        Ok(true) => true,
1285                        Ok(false) => false,
1286                        Err(e) => {
1287                            tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree does not exist");
1288                            false
1289                        }
1290                    } {
1291                        tracing::warn!(
1292                            task_id,
1293                            path = %wt.display(),
1294                            err = %e,
1295                            "failed to remove stale worktree directory"
1296                        );
1297                    }
1298                } else {
1299                    tracing::debug!(task_id, path = %wt.display(), "stale worktree directory removed");
1300                }
1301                // Prune stale worktree entries from git metadata so the warning
1302                // stops recurring on future `git worktree list` / cleanup cycles.
1303                if let Err(e) = Command::new("git")
1304                    .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1305                    .output_with_context()
1306                    .await
1307                {
1308                    tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1309                }
1310            } else {
1311                tracing::warn!(task_id, err = %stderr, "failed to remove worktree");
1312            }
1313        }
1314        Err(e) => {
1315            tracing::warn!(task_id, err = %e, "failed to remove worktree");
1316        }
1317    }
1318
1319    // Prune stale .git/worktrees/ entries left behind after removal.
1320    if let Err(e) = Command::new("git")
1321        .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1322        .output_with_context()
1323        .await
1324    {
1325        tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1326    }
1327
1328    // Delete local and remote branch from the main repo root (worktree is already gone).
1329    // When keep_remote_branch is set, only delete the local branch — the remote stays
1330    // so any linked PR remains open for human review.
1331    if let Some(br) = branch {
1332        if keep_remote_branch {
1333            delete_local_branch(task_id, br, repo_root).await;
1334        } else {
1335            delete_branches(task_id, br, repo_root).await;
1336        }
1337    }
1338
1339    // Definitively check: is the worktree directory actually gone?
1340    match fs::try_exists(wt).await {
1341        Ok(false) => true, // confirmed gone
1342        Ok(true) => false, // still there
1343        Err(e) => {
1344            tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree still present");
1345            false // conservative: don't claim success
1346        }
1347    }
1348}
1349
1350/// Whether `refs/heads/{br}` still exists in `repo_root`
1351pub(crate) async fn local_branch_exists(repo_root: &Path, br: &str) -> bool {
1352    let local_ref = format!("refs/heads/{br}");
1353    git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1354        .await
1355        .is_some_and(|o| o.status.success())
1356}
1357
1358/// Commits reachable from `rev` and from none of `others`. `None` when git cannot answer
1359async fn commits_outside(repo_root: &Path, rev: &str, others: &[&str]) -> Option<u64> {
1360    let mut args = vec![
1361        "rev-list".to_string(),
1362        "--count".to_string(),
1363        rev.to_string(),
1364    ];
1365    // One `--not` then every other ref, a `--not` per ref would toggle and count the wrong set
1366    let mut exclude = Vec::new();
1367    for other in others {
1368        let exists = Command::new("git")
1369            .args([
1370                "-C",
1371                &repo_root.to_string_lossy(),
1372                "rev-parse",
1373                "--verify",
1374                "--quiet",
1375                other,
1376            ])
1377            .output_with_context()
1378            .await
1379            .is_ok_and(|o| o.status.success());
1380        if exists {
1381            exclude.push(other.to_string());
1382        }
1383    }
1384    if !exclude.is_empty() {
1385        args.push("--not".to_string());
1386        args.extend(exclude);
1387    }
1388    let output = Command::new("git")
1389        .arg("-C")
1390        .arg(repo_root)
1391        .args(&args)
1392        .output_with_context()
1393        .await
1394        .ok()?;
1395    if !output.status.success() {
1396        return None;
1397    }
1398    String::from_utf8_lossy(&output.stdout).trim().parse().ok()
1399}
1400
1401/// Delete the local branch only when origin or the default branch holds every commit on it
1402async fn delete_local_branch(task_id: &str, br: &str, repo_root: &Path) {
1403    let default_branch = worktree::detect_default_branch(repo_root).await;
1404    let remote_ref = format!("refs/remotes/origin/{br}");
1405    let default_ref = format!("refs/remotes/origin/{default_branch}");
1406    let local_ref = format!("refs/heads/{br}");
1407    let local_default_ref = format!("refs/heads/{default_branch}");
1408    let rescue_ref = format!("refs/remotes/origin/rescue/{br}");
1409    match commits_outside(
1410        repo_root,
1411        &local_ref,
1412        &[&remote_ref, &default_ref, &local_default_ref, &rescue_ref],
1413    )
1414    .await
1415    {
1416        Some(0) => {}
1417        Some(n) => {
1418            tracing::warn!(task_id, branch = %br, unpushed = n, "local branch holds commits origin does not have, keeping it");
1419            return;
1420        }
1421        None => {
1422            tracing::debug!(task_id, branch = %br, "local branch missing or unreadable, nothing to delete");
1423            return;
1424        }
1425    }
1426    let output = Command::new("git")
1427        .args(["-C", &repo_root.to_string_lossy(), "branch", "-D", br])
1428        .output_with_context()
1429        .await;
1430    match output {
1431        Ok(o) if o.status.success() => {
1432            tracing::info!(task_id, branch = %br, "local branch deleted");
1433        }
1434        Ok(o) => {
1435            let stderr = String::from_utf8_lossy(&o.stderr);
1436            tracing::debug!(task_id, err = %stderr, "local branch delete skipped (may not exist)");
1437        }
1438        Err(e) => {
1439            tracing::warn!(task_id, err = %e, "failed to delete local branch");
1440        }
1441    }
1442}
1443
1444/**
1445 * Delete local and remote branches for a task, but never the only copy of a commit.
1446 * The remote branch goes only when the default branch already contains all of it, which
1447 * covers fast-forward and merge-commit merges. A squash-merged branch stays, and GitHub's
1448 * "automatically delete head branches" removes it. Every other caller (startup rebase
1449 * failure, closed-issue reconciliation, orphan sweeps) may hold unmerged work (#3781)
1450 **/
1451pub(crate) async fn delete_branches(task_id: &str, br: &str, repo_root: &Path) {
1452    if br == SCREENSHOTS_BRANCH {
1453        return;
1454    }
1455    let default_branch = worktree::detect_default_branch(repo_root).await;
1456    let _ = git_ops::git()
1457        .await
1458        .args([
1459            "-C",
1460            &repo_root.to_string_lossy(),
1461            "fetch",
1462            "origin",
1463            &default_branch,
1464            br,
1465        ])
1466        .output_with_context()
1467        .await;
1468
1469    delete_local_branch(task_id, br, repo_root).await;
1470
1471    let remote_ref = format!("refs/remotes/origin/{br}");
1472    let default_ref = format!("refs/remotes/origin/{default_branch}");
1473    match commits_outside(repo_root, &remote_ref, &[&default_ref]).await {
1474        Some(0) => {}
1475        Some(n) => {
1476            tracing::info!(task_id, branch = %br, unmerged = n, "remote branch has commits the default branch lacks, keeping it");
1477            return;
1478        }
1479        None => {
1480            tracing::debug!(task_id, branch = %br, "remote branch missing or unreadable, nothing to delete");
1481            return;
1482        }
1483    }
1484
1485    let remote_delete = git_ops::git()
1486        .await
1487        .args([
1488            "-C",
1489            &repo_root.to_string_lossy(),
1490            "-c",
1491            "lfs.locksverify=false",
1492            "push",
1493            "origin",
1494            "--delete",
1495            br,
1496        ])
1497        .output_with_context()
1498        .await;
1499
1500    match remote_delete {
1501        Ok(output) if output.status.success() => {
1502            tracing::info!(task_id, branch = %br, "remote branch deleted");
1503            git_ops::clear_push_lease(repo_root, br).await;
1504        }
1505        Ok(output) => {
1506            let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
1507            tracing::debug!(task_id, err = %stderr, "remote branch delete skipped");
1508        }
1509        Err(e) => {
1510            tracing::warn!(task_id, err = %e, "failed to delete remote branch");
1511        }
1512    }
1513}
1514
1515/// Returns `true` if any active tmux pane has its cwd inside `worktree`.
1516///
1517/// Uses `tmux list-panes -a -F '#{pane_current_path}'` to enumerate all
1518/// pane working directories across every session. If tmux is not running
1519/// (command fails), we conservatively return `false` so cleanup can proceed.
1520async fn is_worktree_in_active_session(worktree: &Path) -> bool {
1521    let output = Command::new("tmux")
1522        .args(["list-panes", "-a", "-F", "#{pane_current_path}"])
1523        .output()
1524        .await;
1525
1526    match output {
1527        Ok(o) if o.status.success() => {
1528            let worktree_str = worktree.to_string_lossy();
1529            String::from_utf8_lossy(&o.stdout).lines().any(|line| {
1530                let pane_path = line.trim();
1531                // Match exact path or any path that starts with worktree + separator.
1532                pane_path == worktree_str.as_ref()
1533                    || pane_path.starts_with(&format!("{worktree_str}/"))
1534            })
1535        }
1536        // tmux not running or no sessions — treat as safe to clean.
1537        _ => false,
1538    }
1539}
1540
1541/// Returns how many hours old the worktree directory is, based on its mtime.
1542///
1543/// Returns `None` if the directory does not exist or the mtime cannot be read.
1544async fn worktree_age_hours(worktree: &Path) -> Option<u64> {
1545    // Use tokio::fs to avoid blocking the async runtime when reading metadata.
1546    let metadata = fs::metadata(worktree).await.ok()?;
1547    let modified = metadata.modified().ok()?;
1548    let age = SystemTime::now().duration_since(modified).ok()?;
1549    Some(age.as_secs() / 3600)
1550}
1551
1552/// Resolve the repo root for an orphaned worktree and remove it.
1553///
1554/// Used by `orch service doctor --fix` and `orch service prune` to clean up worktrees that are
1555/// no longer owned by any task. Returns `true` if the worktree directory is gone
1556/// after the call.
1557pub(crate) async fn cleanup_orphaned_worktree(task_id: &str, wt: &Path) -> bool {
1558    let repo_root = match resolve_repo_root_for_orphaned_worktree(wt).await {
1559        Ok(root) => root,
1560        Err(e) => {
1561            tracing::warn!(
1562                worktree = %wt.display(),
1563                error = %e,
1564                "cannot resolve repo root for orphaned worktree"
1565            );
1566            return false;
1567        }
1568    };
1569    remove_worktree_and_branch(task_id, wt, None, Path::new(&repo_root), false).await
1570}
1571
1572/// Resolve the main git repository root for an orphaned worktree.
1573///
1574/// First tries to parse the `.git` file's `gitdir:` pointer (two levels up from
1575/// the pointer gives the bare repo root, which is the orch convention). Falls back
1576/// to looking up registered projects by directory name when the `.git` file is
1577/// absent or unparseable.
1578pub(crate) async fn resolve_repo_root_for_orphaned_worktree(wt: &Path) -> anyhow::Result<String> {
1579    let git_file = wt.join(".git");
1580    if fs::try_exists(&git_file).await.unwrap_or(false)
1581        && let Ok(content) = fs::read_to_string(&git_file).await
1582    {
1583        for line in content.lines() {
1584            if let Some(gitdir) = line.strip_prefix("gitdir: ") {
1585                // gitdir points to: <repo>/.git/worktrees/<name> (non-bare)
1586                //                or <repo>.git/worktrees/<name>   (bare)
1587                // Two levels up reaches the .git dir / bare repo root.
1588                let gitdir_path = PathBuf::from(gitdir);
1589                if let Some(repo_root) = gitdir_path.parent().and_then(|p| p.parent()) {
1590                    return Ok(repo_root.display().to_string());
1591                }
1592            }
1593        }
1594    }
1595
1596    // Fallback: look up registered projects by the project-name component of the
1597    // worktree path (format: ~/.orch/worktrees/<project>/<branch>).
1598    let worktrees_dir = home::worktrees_dir()?;
1599    if let Ok(relative) = wt.strip_prefix(&worktrees_dir)
1600        && let Some(project_name) = relative.components().next()
1601    {
1602        let project_name = project_name.as_os_str().to_string_lossy();
1603
1604        if let Ok(paths) = config::get_project_paths() {
1605            for path_str in &paths {
1606                let path = Path::new(path_str);
1607                if let Some(name) = path.file_name()
1608                    && name.to_string_lossy() == project_name
1609                {
1610                    return Ok(path_str.clone());
1611                }
1612            }
1613        }
1614
1615        // Try bare clone at ~/.orch/projects/<owner>/<project>.git
1616        let parts: Vec<&str> = project_name.split('/').collect();
1617        let bare = if parts.len() == 2 {
1618            home::projects_dir()
1619                .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1620                .unwrap_or_default()
1621        } else {
1622            return Err(anyhow::anyhow!(
1623                "cannot determine owner for single-segment project name '{project_name}' — \
1624                     bare repo location is ambiguous; register the project with 'owner/repo' format"
1625            ));
1626        };
1627        if fs::try_exists(&bare).await.unwrap_or(false) {
1628            return Ok(bare.display().to_string());
1629        }
1630    }
1631
1632    anyhow::bail!(
1633        "cannot resolve repo root for orphaned worktree at {} — tried .git parsing and project lookup",
1634        wt.display()
1635    )
1636}
1637
1638/// Resolve the main git repository root from a worktree's .git file.
1639///
1640/// For cross-project worktree cleanup, we cannot rely on `resolve_repo_root` because
1641/// the worktree may belong to a different project than the current repo context.
1642/// Instead, we extract the repo root from the worktree's `.git` file which contains
1643/// a `gitdir:` pointer to the main repo's git directory.
1644pub async fn resolve_repo_root_from_worktree(wt: &Path) -> anyhow::Result<String> {
1645    // For worktrees, .git is a file (not a directory) containing gitdir path
1646    let git_file = wt.join(".git");
1647    if !fs::try_exists(&git_file).await.unwrap_or(false) {
1648        anyhow::bail!(".git file not found in worktree at {}", wt.display());
1649    }
1650
1651    let content = fs::read_to_string(&git_file)
1652        .await
1653        .map_err(|e| anyhow::anyhow!("failed to read .git file: {e}"))?;
1654
1655    // Parse gitdir line: "gitdir: /path/to/repo/.git/worktrees/<name>"
1656    for line in content.lines() {
1657        if let Some(gitdir) = line.strip_prefix("gitdir:") {
1658            let gitdir = gitdir.trim();
1659            // The main repo is the parent of the .git directory
1660            // gitdir points to: <repo>/.git/worktrees/<name>
1661            // We need to go up 3 levels: worktrees/<name> -> .git -> repo
1662            let gitdir_path = Path::new(gitdir);
1663            if let Some(repo_root) = gitdir_path
1664                .parent() // worktrees/<name>
1665                .and_then(|p| p.parent()) // .git
1666                .and_then(|p| p.parent())
1667            // repo root
1668            {
1669                return Ok(repo_root.display().to_string());
1670            }
1671        }
1672    }
1673
1674    anyhow::bail!(
1675        "cannot resolve repo root from worktree .git file at {}",
1676        wt.display()
1677    )
1678}
1679
1680/// Resolve the main git repository root path for a project.
1681///
1682/// Looks up the local project path from config, then verifies it's a git repo.
1683/// This avoids relying on cwd (which is undefined under launchd services).
1684pub(crate) async fn resolve_repo_root(repo: &str) -> anyhow::Result<String> {
1685    // Look up the local path from registered projects
1686    let paths = config::get_project_paths().unwrap_or_default();
1687    for path_str in &paths {
1688        let path = Path::new(path_str);
1689        let orch_yml = path.join(".orch.yml");
1690        let legacy = path.join(".orchestrator.yml");
1691        let config_file = if fs::try_exists(&orch_yml).await.unwrap_or(false) {
1692            orch_yml
1693        } else if fs::try_exists(&legacy).await.unwrap_or(false) {
1694            legacy
1695        } else {
1696            continue;
1697        };
1698        if let Ok(content) = fs::read_to_string(&config_file).await
1699            && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1700            && let Some(r) = doc
1701                .get("gh")
1702                .and_then(|gh| gh.get("repo"))
1703                .and_then(|r| r.as_str())
1704            && r == repo
1705        {
1706            return Ok(path_str.clone());
1707        }
1708    }
1709
1710    // Fallback: try bare clone in ~/.orch/projects/<owner>/<repo>.git
1711    let parts: Vec<&str> = repo.split('/').collect();
1712    let bare = if parts.len() == 2 {
1713        home::projects_dir()
1714            .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1715            .unwrap_or_default()
1716    } else {
1717        PathBuf::new()
1718    };
1719    if fs::try_exists(&bare).await.unwrap_or(false) {
1720        return Ok(bare.display().to_string());
1721    }
1722
1723    anyhow::bail!(
1724        "cannot find local path for project {repo} — \
1725         checked {} registered project(s) and bare clone at {}",
1726        paths.len(),
1727        bare.display()
1728    )
1729}
1730
1731/// Resolve the project directory for a given repo string.
1732///
1733/// Replicates the logic from `TaskRunner::resolve_project_dir()` without requiring
1734/// a Runner instance. Used by the orphan scanner to enumerate active worktrees.
1735fn resolve_project_dir_for_repo(repo: &str) -> anyhow::Result<PathBuf> {
1736    // Check PROJECT_DIR env var first
1737    if let Ok(dir) = env::var("PROJECT_DIR")
1738        && !dir.is_empty()
1739    {
1740        return Ok(PathBuf::from(dir));
1741    }
1742
1743    // Look up registered projects in config
1744    if let Ok(paths) = config::get_project_paths() {
1745        for path_str in &paths {
1746            let path = Path::new(path_str);
1747            let orch_yml = path.join(".orch.yml");
1748            let legacy = path.join(".orchestrator.yml");
1749            let config_file = if Path::new(&orch_yml).exists() {
1750                orch_yml
1751            } else if Path::new(&legacy).exists() {
1752                legacy
1753            } else {
1754                continue;
1755            };
1756            if let Ok(content) = std_fs::read_to_string(&config_file)
1757                && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1758                && let Some(r) = doc
1759                    .get("gh")
1760                    .and_then(|gh| gh.get("repo"))
1761                    .and_then(|r| r.as_str())
1762                && r == repo
1763            {
1764                return Ok(path_str.clone().into());
1765            }
1766        }
1767    }
1768
1769    anyhow::bail!("project dir not found for repo: {repo}")
1770}
1771
1772/// Check for merged PRs and update task status accordingly.
1773///
1774/// Queries status:in_review and status:needs_review tasks, checks if their PR
1775/// is merged, and updates status to done if merged.
1776pub(crate) async fn check_merged_prs(
1777    backend: &Arc<dyn ExternalBackend>,
1778    repo: &str,
1779    store: &Arc<TaskStore>,
1780    task_manager: &Arc<TaskManager>,
1781    in_review_tasks: &[ReviewTaskSnapshot],
1782    needs_review_tasks: &[ReviewTaskSnapshot],
1783) -> anyhow::Result<()> {
1784    let mut branch_map: HashMap<String, String> = HashMap::new();
1785    let all_review_tasks: Vec<&ReviewTaskSnapshot> = in_review_tasks
1786        .iter()
1787        .chain(needs_review_tasks.iter())
1788        .collect();
1789
1790    for task in &all_review_tasks {
1791        if !task.stored.branch.is_empty() {
1792            branch_map.insert(task.external.id.0.clone(), task.stored.branch.clone());
1793        }
1794    }
1795
1796    tracing::debug!(
1797        count = all_review_tasks.len(),
1798        "checking review tasks for merged PRs"
1799    );
1800
1801    // Collect (task_id, branch) pairs — skip tasks with no branch recorded.
1802    // Use the pre-built branch map; fall back to store lookup only for tasks
1803    // not in the map (e.g. internal tasks, backend fallback path).
1804    let mut task_branches: Vec<(String, String)> = Vec::new();
1805    for task in all_review_tasks {
1806        let task_id = &task.external.id.0;
1807        let branch = if let Some(b) = branch_map.get(task_id) {
1808            b.clone()
1809        } else {
1810            match store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
1811                .await
1812                .map(|t| t.branch)
1813            {
1814                Some(b) if !b.is_empty() => b,
1815                _ => {
1816                    tracing::debug!(task_id, "no branch info, skipping PR check");
1817                    continue;
1818                }
1819            }
1820        };
1821        task_branches.push((task_id.clone(), branch));
1822    }
1823
1824    if task_branches.is_empty() {
1825        return Ok(());
1826    }
1827
1828    // Single GraphQL call for all branches — N REST calls → 1 GraphQL call.
1829    let branches: Vec<String> = task_branches.iter().map(|(_, b)| b.clone()).collect();
1830    let merged_map = match backend.batch_is_pr_merged(&branches).await {
1831        Ok(map) => map,
1832        Err(e) => {
1833            tracing::warn!(
1834                err = %e,
1835                branch_count = branches.len(),
1836                "batch PR merge check failed, retrying affected branches individually"
1837            );
1838            fallback_is_pr_merged_by_branch(backend, &branches).await
1839        }
1840    };
1841
1842    for (task_id, branch) in task_branches {
1843        let is_merged = merged_map.get(&branch).copied().unwrap_or(false);
1844        if !is_merged {
1845            continue;
1846        }
1847
1848        tracing::info!(task_id, branch = %branch, "PR merged, marking task complete");
1849
1850        let stored = store::opt_store_get_task(&Some(Arc::clone(store)), repo, &task_id).await;
1851        if let Some(ref stored) = stored {
1852            let external = store_task_to_external(stored);
1853            if bootstrap::hold_after_merge(&external, store, repo).await {
1854                tracing::info!(
1855                    task_id,
1856                    branch = %branch,
1857                    "CI bootstrap PR merged, holding done until the ruleset exists"
1858                );
1859                if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1860                    tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1861                }
1862                continue;
1863            }
1864        }
1865
1866        let id = ExternalId(task_id.clone());
1867        if let Err(e) = task_manager.update_task_status(&id, Status::Done).await {
1868            tracing::warn!(task_id, err = %e, "failed to update status to done");
1869            continue;
1870        }
1871
1872        if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1873            tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1874        }
1875
1876        let comment = format!("PR merged, marking task complete{}", engine::orch_footer());
1877        if let Err(e) = backend.post_comment(&id, &comment).await {
1878            tracing::warn!(task_id, err = %e, "failed to post comment");
1879        }
1880    }
1881
1882    Ok(())
1883}
1884
1885async fn fallback_is_pr_merged_by_branch(
1886    backend: &Arc<dyn ExternalBackend>,
1887    branches: &[String],
1888) -> HashMap<String, bool> {
1889    let futs: Vec<_> = branches
1890        .iter()
1891        .map(|branch| {
1892            let backend = Arc::clone(backend);
1893            let branch = branch.clone();
1894            async move {
1895                match backend.is_pr_merged(&branch).await {
1896                    Ok(is_merged) => Some((branch, is_merged)),
1897                    Err(err) => {
1898                        tracing::warn!(
1899                            branch,
1900                            err = %err,
1901                            "fallback PR merge check failed for branch"
1902                        );
1903                        None
1904                    }
1905                }
1906            }
1907        })
1908        .collect();
1909
1910    future::join_all(futs).await.into_iter().flatten().collect()
1911}
1912
1913#[derive(Debug, Clone)]
1914pub(crate) struct ReviewTaskSnapshot {
1915    pub external: ExternalTask,
1916    pub stored: Task,
1917}
1918
1919#[cfg(test)]
1920mod tests;