1use 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
46const RECONCILIATION_LIST_TIMEOUT: Duration = Duration::from_secs(30);
51const 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
59static CLEANUP_IN_FLIGHT: LazyLock<DashSet<String>> = LazyLock::new(DashSet::new);
62static 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#[derive(Debug, Clone)]
103pub struct JanitorOptions {
104 pub ttl_hours: u64,
112
113 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 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
142pub(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
160pub(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 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 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 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
259pub(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 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 let mut task_ids: Vec<String> = done_tasks.iter().map(|t| t.id.0.clone()).collect();
285
286 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 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 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 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 }
365 Err(e) => {
366 tracing::warn!(task_id, err = %e, "worktree cleanup failed for task");
367 }
368 }
369 }
370
371 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 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 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 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 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 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 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
519pub(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
536pub(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 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
592pub(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 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 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 let worktrees_base = home::worktrees_dir().unwrap_or_else(|_| PathBuf::from(".orch/worktrees"));
637
638 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 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 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 let branch_nonempty = branch.as_ref().filter(|b| !b.is_empty());
710 if worktree_to_remove.is_none() && branch_nonempty.is_none() {
711 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 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 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 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 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 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 if !opts.dry_run && !keep_remote_branch {
861 tracing::debug!(task_id, branch = %br, "no worktree on disk, cleaning up branch only");
862 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 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 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
914const LANDED_BASE_REF: &str = "refs/orch/landed-base";
916
917async 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#[derive(Debug, PartialEq, Eq)]
944pub(crate) enum Rescue {
945 Clean,
947 Pushed {
949 branch: String,
950 commits: Vec<String>,
951 },
952 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
968pub(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 let default_ref = format!(
1024 "refs/heads/{}",
1025 worktree::detect_default_branch(repo_root).await
1026 );
1027 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 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 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
1118async 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
1151pub(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
1167pub(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
1187async 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 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 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 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 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 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 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 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 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 match fs::try_exists(wt).await {
1341 Ok(false) => true, Ok(true) => false, Err(e) => {
1344 tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree still present");
1345 false }
1347 }
1348}
1349
1350pub(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
1358async 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 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
1401async 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
1444pub(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
1515async 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 pane_path == worktree_str.as_ref()
1533 || pane_path.starts_with(&format!("{worktree_str}/"))
1534 })
1535 }
1536 _ => false,
1538 }
1539}
1540
1541async fn worktree_age_hours(worktree: &Path) -> Option<u64> {
1545 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
1552pub(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
1572pub(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 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 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 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
1638pub async fn resolve_repo_root_from_worktree(wt: &Path) -> anyhow::Result<String> {
1645 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 for line in content.lines() {
1657 if let Some(gitdir) = line.strip_prefix("gitdir:") {
1658 let gitdir = gitdir.trim();
1659 let gitdir_path = Path::new(gitdir);
1663 if let Some(repo_root) = gitdir_path
1664 .parent() .and_then(|p| p.parent()) .and_then(|p| p.parent())
1667 {
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
1680pub(crate) async fn resolve_repo_root(repo: &str) -> anyhow::Result<String> {
1685 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 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
1731fn resolve_project_dir_for_repo(repo: &str) -> anyhow::Result<PathBuf> {
1736 if let Ok(dir) = env::var("PROJECT_DIR")
1738 && !dir.is_empty()
1739 {
1740 return Ok(PathBuf::from(dir));
1741 }
1742
1743 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
1772pub(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 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 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;