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 crate::sys::tmux;
19use dashmap::{DashMap, DashSet};
20use futures::future;
21use std::collections::HashMap;
22use std::collections::HashSet;
23use std::env;
24use std::fs as std_fs;
25use std::io::ErrorKind;
26use std::path::Path;
27use std::path::PathBuf;
28use std::process::Output;
29use std::sync::Arc;
30use std::sync::LazyLock;
31use std::time::SystemTime;
32use std::time::{Duration, Instant};
33use tokio::fs;
34use tokio::process::Command;
35use tokio::time::sleep;
36use tokio::time::timeout;
37
38use crate::config;
39use crate::engine;
40use crate::engine::git::cow;
41use crate::engine::git::git_ops;
42use crate::engine::git::screenshots::SCREENSHOTS_BRANCH;
43use crate::engine::git::worktree;
44use crate::github::http::GhHttp;
45use crate::sys::home;
46
47const RECONCILIATION_LIST_TIMEOUT: Duration = Duration::from_secs(30);
52const RECONCILIATION_INTERVAL: Duration = Duration::from_mins(15);
55
56const RUN_OUTPUT_RETENTION_DAYS: i32 = 30;
57const RUN_PRUNE_INTERVAL_SECS: i64 = 24 * 60 * 60;
58const RUN_PRUNE_KV_KEY: &str = "task_runs_pruned_at";
59
60static CLEANUP_IN_FLIGHT: LazyLock<DashSet<String>> = LazyLock::new(DashSet::new);
63static RECONCILIATION_LAST_RUN: LazyLock<DashMap<String, Instant>> = LazyLock::new(DashMap::new);
65
66struct CleanupInFlightGuard {
67 repo: String,
68}
69
70impl CleanupInFlightGuard {
71 fn try_acquire(repo: &str) -> Option<Self> {
72 if CLEANUP_IN_FLIGHT.insert(repo.to_string()) {
73 Some(Self {
74 repo: repo.to_string(),
75 })
76 } else {
77 None
78 }
79 }
80}
81
82impl Drop for CleanupInFlightGuard {
83 fn drop(&mut self) {
84 CLEANUP_IN_FLIGHT.remove(&self.repo);
85 }
86}
87
88fn should_run_reconciliation(repo: &str) -> bool {
89 let now = Instant::now();
90 if let Some(mut last_run) = RECONCILIATION_LAST_RUN.get_mut(repo) {
91 if last_run.elapsed() < RECONCILIATION_INTERVAL {
92 return false;
93 }
94 *last_run = now;
95 true
96 } else {
97 RECONCILIATION_LAST_RUN.insert(repo.to_string(), now);
98 true
99 }
100}
101
102#[derive(Debug, Clone)]
104pub struct JanitorOptions {
105 pub ttl_hours: u64,
113
114 pub dry_run: bool,
118}
119
120impl Default for JanitorOptions {
121 fn default() -> Self {
122 Self {
123 ttl_hours: 24,
124 dry_run: false,
125 }
126 }
127}
128
129impl JanitorOptions {
130 pub fn from_config() -> Self {
132 let ttl_hours = config::get("workflow.worktree_janitor_ttl_hours")
133 .ok()
134 .and_then(|v| v.parse::<u64>().ok())
135 .unwrap_or(24);
136
137 let dry_run = config::get("workflow.worktree_janitor_dry_run").is_ok_and(|v| v == "true");
138
139 Self { ttl_hours, dry_run }
140 }
141}
142
143pub(crate) async fn cleanup_done_worktrees(
152 backend: &Arc<dyn ExternalBackend>,
153 repo: &str,
154 task_manager: &Arc<TaskManager>,
155 store: &Arc<TaskStore>,
156) -> anyhow::Result<()> {
157 let opts = JanitorOptions::from_config();
158 cleanup_done_worktrees_with_opts(backend, repo, task_manager, store, &opts).await
159}
160
161pub(crate) async fn prune_old_run_output(store: &TaskStore) -> anyhow::Result<()> {
163 let now = chrono::Utc::now().timestamp();
164 let last = store
165 .kv_get(RUN_PRUNE_KV_KEY)
166 .await?
167 .and_then(|v| v.parse::<i64>().ok())
168 .unwrap_or(0);
169 if now - last < RUN_PRUNE_INTERVAL_SECS {
170 return Ok(());
171 }
172 store.kv_set(RUN_PRUNE_KV_KEY, &now.to_string()).await?;
173
174 let pruned = store.prune_old_runs(RUN_OUTPUT_RETENTION_DAYS).await?;
175 if pruned > 0 {
176 tracing::info!(pruned, "cleared the output of old task runs");
177 }
178 Ok(())
179}
180
181async fn reconcile_closed_tasks(
182 task_ids: &mut Vec<String>,
183 all_tasks: &[ExternalTask],
184 task_manager: &TaskManager,
185 store: &Arc<TaskStore>,
186 repo: &str,
187) {
188 const MAX_RECONCILE_PER_CYCLE: usize = 10;
189
190 let done_set: HashSet<String> = task_ids.iter().cloned().collect();
191 let mut closed_not_in_store = Vec::new();
192 for task in all_tasks {
193 if task.state != "closed" || done_set.contains(&task.id.0) {
194 continue;
195 }
196 if bootstrap::hold_after_merge(task, store, repo).await {
197 continue;
198 }
199 closed_not_in_store.push(task);
200 }
201
202 let mut already_labeled: Vec<String> = Vec::new();
205 let mut needs_reconcile: Vec<&ExternalTask> = Vec::new();
206 for task in &closed_not_in_store {
207 if task.labels.iter().any(|l| l == "status:done") {
208 already_labeled.push(task.id.0.clone());
209 } else {
210 needs_reconcile.push(task);
211 }
212 }
213
214 if !already_labeled.is_empty() {
216 tracing::debug!(
217 count = already_labeled.len(),
218 "closed issues already labeled status:done — adding to cleanup set"
219 );
220 task_ids.extend(already_labeled);
221 }
222
223 if needs_reconcile.len() > MAX_RECONCILE_PER_CYCLE {
226 tracing::info!(
227 total = needs_reconcile.len(),
228 batch = MAX_RECONCILE_PER_CYCLE,
229 "capping closed-issue reconciliation to avoid rate-limit exhaustion"
230 );
231 }
232 let mut futs = Vec::new();
233 for task in needs_reconcile.iter().take(MAX_RECONCILE_PER_CYCLE) {
234 let id = task.id.clone();
235 let task_id_str = task.id.0.clone();
236 let labels = task.labels.clone();
237 futs.push(async move {
238 tracing::info!(
239 task_id = task_id_str,
240 labels = ?labels,
241 "closed issue with stale status label — reconciling to done and cleaning up"
242 );
243 match task_manager.update_task_status(&id, Status::Done).await {
244 Ok(()) => Some(task_id_str),
245 Err(e) => {
246 tracing::warn!(
247 task_id = task_id_str,
248 err = %e,
249 "failed to reconcile closed issue status to done"
250 );
251 None
252 }
253 }
254 });
255 }
256 let results = future::join_all(futs).await;
257 task_ids.extend(results.into_iter().flatten());
258}
259
260pub(crate) async fn cleanup_done_worktrees_with_opts(
266 backend: &Arc<dyn ExternalBackend>,
267 repo: &str,
268 task_manager: &Arc<TaskManager>,
269 store: &Arc<TaskStore>,
270 opts: &JanitorOptions,
271) -> anyhow::Result<()> {
272 let Some(_guard) = CleanupInFlightGuard::try_acquire(repo) else {
273 tracing::debug!(
274 repo = %repo,
275 "cleanup already in progress for repo — skipping overlapping run"
276 );
277 return Ok(());
278 };
279
280 let done_tasks = task_manager.list_all_by_status(Status::Done).await?;
282 tracing::debug!(count = done_tasks.len(), "checking done tasks for cleanup");
283
284 let mut task_ids: Vec<String> = done_tasks.iter().map(|t| t.id.0.clone()).collect();
286
287 if should_run_reconciliation(repo) {
299 match timeout(
300 RECONCILIATION_LIST_TIMEOUT,
301 backend.list_reconciliation_candidates(),
302 )
303 .await
304 {
305 Ok(Ok(candidates)) if !candidates.is_empty() => {
306 tracing::debug!(
307 count = candidates.len(),
308 "reconciling closed issues from candidates"
309 );
310 reconcile_closed_tasks(&mut task_ids, &candidates, task_manager, store, repo).await;
311 }
312 Ok(Ok(_)) => {
313 tracing::debug!("no reconciliation candidates found");
314 }
315 Ok(Err(e)) => {
316 tracing::warn!(err = %e, "failed to list reconciliation candidates");
317 }
318 Err(_) => {
319 tracing::warn!(
320 timeout_secs = RECONCILIATION_LIST_TIMEOUT.as_secs(),
321 retry_after_secs = RECONCILIATION_INTERVAL.as_secs(),
322 "timed out listing reconciliation candidates"
323 );
324 }
325 }
326 } else {
327 tracing::debug!(
328 retry_after_secs = RECONCILIATION_INTERVAL.as_secs(),
329 "skipping closed-issue reconciliation until interval elapses"
330 );
331 }
332
333 if let Ok(internal_done) = task_manager.list_internal_by_status(TaskStatus::Done).await {
335 task_ids.extend(internal_done.iter().map(|t| t.id.0.clone()));
336 }
337
338 tracing::debug!(
339 count = task_ids.len(),
340 "checking all terminal tasks for cleanup"
341 );
342
343 if let Err(e) = ci::sweep_ci_timer_keys(store, repo, &task_ids).await {
344 tracing::warn!(err = %e, "failed to sweep CI timer keys");
345 }
346
347 let already_cleaned = store.cleaned_external_ids(repo).await.unwrap_or_default();
352
353 let mut cleaned_any = false;
354 for task_id in &task_ids {
355 if already_cleaned.contains(task_id) {
357 continue;
358 }
359
360 match cleanup_task_worktree_with_opts(task_id, repo, store, opts).await {
361 Ok(true) => cleaned_any = true,
362 Ok(false) => {
363 }
366 Err(e) => {
367 tracing::warn!(task_id, err = %e, "worktree cleanup failed for task");
368 }
369 }
370 }
371
372 let worktrees_base = match home::worktrees_dir() {
385 Ok(base) => Some(base),
386 Err(e) => {
387 tracing::debug!(err = %e, "worktrees_dir() unavailable — skipping orphan scan");
388 None
389 }
390 };
391
392 if let Some(base) = worktrees_base {
393 let project = repo
394 .rsplit('/')
395 .next()
396 .unwrap_or(repo)
397 .trim_end_matches(".git");
398 let repo_worktrees = base.join(project);
399
400 let mut combined: HashSet<String> = HashSet::new();
402 if let Ok(tasks) = store.list_all(repo).await {
403 for t in tasks {
404 if !t.worktree.is_empty() {
405 combined.insert(t.worktree);
406 }
407 }
408 }
409
410 if let Ok(project_dir) = resolve_project_dir_for_repo(repo)
412 && let Ok(active_wts) = worktree::list_project_worktrees(&project_dir).await
413 {
414 for wt in active_wts {
415 combined.insert(wt.to_string_lossy().to_string());
416 }
417 }
418
419 if let Ok(mut entries) = fs::read_dir(&repo_worktrees).await {
421 while let Ok(Some(entry)) = entries.next_entry().await {
422 let Ok(entry_meta) = entry.metadata().await else {
423 continue;
424 };
425 if !entry_meta.is_dir() {
426 continue;
427 }
428 let wt_path = entry.path().to_string_lossy().to_string();
429 if combined.contains(&wt_path) {
430 continue;
431 }
432 tracing::info!(worktree = %wt_path, "found orphaned worktree — attempting cleanup");
433 match resolve_repo_root_for_orphaned_worktree(&entry.path()).await {
434 Ok(repo_root) => {
435 let removed = remove_worktree_and_branch(
436 "orphan-scan",
437 &entry.path(),
438 None,
439 Path::new(&repo_root),
440 false,
441 )
442 .await;
443 if removed {
444 tracing::info!(worktree = %wt_path, "orphaned worktree removed");
445 } else {
446 tracing::warn!(worktree = %wt_path, "orphaned worktree could not be removed");
447 }
448 }
449 Err(e) => {
450 tracing::warn!(worktree = %wt_path, err = %e, "could not resolve repo root for orphaned worktree");
451 }
452 }
453 }
454 }
455 }
456
457 if cleaned_any
459 && !opts.dry_run
460 && let Ok(repo_root) = resolve_repo_root(repo).await
461 {
462 const GIT_TIMEOUT: Duration = Duration::from_secs(60);
463
464 let prune_result = timeout(
466 GIT_TIMEOUT,
467 Command::new("git")
468 .args(["-C", &repo_root, "worktree", "prune"])
469 .output_with_context(),
470 )
471 .await;
472 match prune_result {
473 Ok(Ok(output)) if output.status.success() => {
474 tracing::debug!(%repo, "pruned stale worktree metadata");
475 }
476 Ok(Ok(output)) => {
477 let stderr = String::from_utf8_lossy(&output.stderr);
478 tracing::warn!(%repo, err = %stderr, "git worktree prune failed");
479 }
480 Ok(Err(e)) => {
481 tracing::warn!(%repo, err = %e, "git worktree prune failed");
482 }
483 Err(_) => {
484 tracing::warn!(%repo, "git worktree prune timed out after 60s");
485 }
486 }
487
488 let fetch_result = timeout(
493 GIT_TIMEOUT,
494 git_ops::git()
495 .await
496 .args(["-C", &repo_root, "fetch", "--prune", "origin"])
497 .output_with_context(),
498 )
499 .await;
500 match fetch_result {
501 Ok(Ok(output)) if output.status.success() => {
502 tracing::info!(%repo, "fetched origin after worktree cleanup");
503 }
504 Ok(Ok(output)) => {
505 let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
506 tracing::debug!(%repo, err = %stderr, "git fetch skipped after cleanup");
507 }
508 Ok(Err(e)) => {
509 tracing::debug!(%repo, err = %e, "git fetch failed after cleanup");
510 }
511 Err(_) => {
512 tracing::debug!(%repo, "git fetch timed out after 60s");
513 }
514 }
515 }
516
517 Ok(())
518}
519
520pub(crate) async fn cleanup_task_worktree(
530 task_id: &str,
531 repo: &str,
532 store: &Arc<TaskStore>,
533) -> anyhow::Result<()> {
534 cleanup_task_worktree_impl(task_id, repo, store, false).await
535}
536
537pub(crate) async fn cleanup_merged_pr_worktree(
539 task_id: &str,
540 repo: &str,
541 store: &Arc<TaskStore>,
542) -> anyhow::Result<()> {
543 cleanup_task_worktree_impl(task_id, repo, store, true).await
544}
545
546async fn cleanup_task_worktree_impl(
547 task_id: &str,
548 repo: &str,
549 store: &Arc<TaskStore>,
550 known_pr_merged: bool,
551) -> anyhow::Result<()> {
552 let opts = JanitorOptions {
553 ttl_hours: 0,
554 ..Default::default()
555 };
556 let cleaned =
557 cleanup_task_worktree_with_opts_impl(task_id, repo, store, &opts, known_pr_merged).await?;
558
559 if cleaned && let Ok(repo_root) = resolve_repo_root(repo).await {
564 const GIT_TIMEOUT: Duration = Duration::from_secs(60);
565 let fetch_result = timeout(
566 GIT_TIMEOUT,
567 git_ops::git()
568 .await
569 .args(["-C", &repo_root, "fetch", "--prune", "origin"])
570 .output_with_context(),
571 )
572 .await;
573 match fetch_result {
574 Ok(Ok(output)) if output.status.success() => {
575 tracing::debug!(%repo, "fetched origin after task cleanup");
576 }
577 Ok(Ok(output)) => {
578 let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
579 tracing::debug!(%repo, err = %stderr, "git fetch skipped after task cleanup");
580 }
581 Ok(Err(e)) => {
582 tracing::debug!(%repo, err = %e, "git fetch failed after task cleanup");
583 }
584 Err(_) => {
585 tracing::debug!(%repo, "git fetch timed out after 60s");
586 }
587 }
588 }
589
590 Ok(())
591}
592
593pub(crate) async fn cleanup_task_worktree_with_opts(
600 task_id: &str,
601 repo: &str,
602 store: &Arc<TaskStore>,
603 opts: &JanitorOptions,
604) -> anyhow::Result<bool> {
605 cleanup_task_worktree_with_opts_impl(task_id, repo, store, opts, false).await
606}
607
608async fn cleanup_task_worktree_with_opts_impl(
609 task_id: &str,
610 repo: &str,
611 store: &Arc<TaskStore>,
612 opts: &JanitorOptions,
613 known_pr_merged: bool,
614) -> anyhow::Result<bool> {
615 let (worktree, branch, keep_remote_branch, merged, external_id, pr_merged) =
616 store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
617 .await
618 .map_or((None, None, false, false, None, false), |t| {
619 let keep = t.status == TaskStatus::Blocked && t.pr_number.is_some();
622 let merged = t.status == TaskStatus::Done || known_pr_merged;
623 (
624 Some(t.worktree).filter(|w| !w.is_empty()),
625 Some(t.branch).filter(|b| !b.is_empty()),
626 keep,
627 merged,
628 t.external_id,
629 known_pr_merged || (t.status == TaskStatus::Done && t.pr_number.is_some()),
631 )
632 });
633
634 let worktree_path = worktree.as_ref().map(PathBuf::from);
635
636 let worktrees_base = home::worktrees_dir().unwrap_or_else(|_| PathBuf::from(".orch/worktrees"));
638
639 let worktree_to_remove = if let Some(ref wt) = worktree_path {
645 if match fs::try_exists(wt).await {
646 Ok(true) => true,
647 Ok(false) => false,
648 Err(e) => {
649 tracing::warn!(task_id, worktree = %wt.display(), err = %e, "try_exists failed on stored worktree path — trying branch-based fallback");
650 false
651 }
652 } {
653 Some(wt.clone())
654 } else {
655 if let Some(ref b) = branch {
657 let project = repo
658 .rsplit('/')
659 .next()
660 .unwrap_or(repo)
661 .trim_end_matches(".git");
662 let candidate = worktrees_base.join(project).join(b);
663 if match fs::try_exists(&candidate).await {
664 Ok(true) => true,
665 Ok(false) => false,
666 Err(e) => {
667 tracing::warn!(task_id, err = %e, "try_exists failed — assuming candidate does not exist");
668 false
669 }
670 } {
671 Some(candidate)
672 } else {
673 None
674 }
675 } else {
676 None
677 }
678 }
679 } else if let Some(ref b) = branch {
680 let project = repo
682 .rsplit('/')
683 .next()
684 .unwrap_or(repo)
685 .trim_end_matches(".git");
686 let candidate = worktrees_base.join(project).join(b);
687 if match fs::try_exists(&candidate).await {
688 Ok(true) => true,
689 Ok(false) => false,
690 Err(e) => {
691 tracing::warn!(task_id, err = %e, "try_exists failed — assuming candidate does not exist");
692 false
693 }
694 } {
695 Some(candidate)
696 } else {
697 None
698 }
699 } else {
700 None
701 };
702
703 let mut did_clean = false;
704
705 let branch_nonempty = branch.as_ref().filter(|b| !b.is_empty());
711 if worktree_to_remove.is_none() && branch_nonempty.is_none() {
712 if worktree_path
715 .as_ref()
716 .is_some_and(|p| !p.as_os_str().is_empty())
717 {
718 tracing::debug!(
719 task_id,
720 worktree = ?worktree_path,
721 "stored worktree path no longer exists on disk — marking cleaned"
722 );
723 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
724 && let Err(e) = store.mark_cleaned(store_id).await
725 {
726 tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned in store — will retry");
727 }
728 }
729 return Ok(false);
730 }
731
732 if let Some(wt) = worktree_to_remove {
733 if let Ok(rel) = wt.strip_prefix(&worktrees_base)
735 && rel.components().count() < 2
736 {
737 tracing::warn!(
738 task_id,
739 worktree = %wt.display(),
740 "refusing to clean the worktrees root or a project directory"
741 );
742 return Ok(false);
743 }
744
745 if let Some(age_hours) = worktree_age_hours(&wt).await
747 && age_hours < opts.ttl_hours
748 {
749 tracing::debug!(
750 task_id,
751 worktree = %wt.display(),
752 age_hours,
753 ttl_hours = opts.ttl_hours,
754 "worktree too young for cleanup, skipping"
755 );
756 return Ok(false);
757 }
758
759 if is_worktree_in_active_session(&wt).await {
761 tracing::warn!(
762 task_id,
763 worktree = %wt.display(),
764 "worktree is referenced by an active tmux session — skipping cleanup"
765 );
766 return Ok(false);
767 }
768
769 let gitdir_valid = worktree::validate_worktree_gitdir(&wt).await;
773
774 if opts.dry_run {
775 tracing::info!(
776 task_id,
777 worktree = %wt.display(),
778 branch = ?branch,
779 gitdir_valid,
780 "[dry-run] would remove worktree and branch"
781 );
782 } else if !gitdir_valid {
783 tracing::warn!(
784 task_id,
785 worktree = %wt.display(),
786 "worktree has broken git metadata — force-removing directory without git operations"
787 );
788 match fs::remove_dir_all(&wt).await {
789 Ok(()) => {
790 did_clean = true;
791 }
792 Err(e) => {
793 tracing::warn!(
794 task_id,
795 worktree = %wt.display(),
796 err = %e,
797 "failed to force-remove broken worktree directory"
798 );
799 }
800 }
801 } else {
802 tracing::info!(task_id, worktree = %wt.display(), "removing worktree");
803 let repo_root = match resolve_repo_root_from_worktree(&wt).await {
808 Ok(root) => root,
809 Err(_) => resolve_repo_root(repo).await?,
810 };
811 if let Some(br) = branch.as_deref().filter(|b| !b.is_empty())
812 && !pr_merged
813 && !rescue_and_notify(
814 task_id,
815 repo,
816 external_id.as_deref(),
817 Some(&wt),
818 br,
819 Path::new(&repo_root),
820 )
821 .await
822 {
823 return Ok(false);
824 }
825 if merged {
826 cow::warm_from_merged(
827 Path::new(&repo_root),
828 &worktree::project_name(Path::new(&repo_root)),
829 &wt,
830 )
831 .await;
832 }
833 let removed = if merged && remove_landed_worktree(&wt, Path::new(&repo_root)).await {
834 if let Some(br) = branch.as_deref().filter(|_| !keep_remote_branch) {
835 delete_branches(task_id, br, Path::new(&repo_root)).await;
836 }
837 true
838 } else {
839 remove_worktree_and_branch_unchecked(
840 task_id,
841 &wt,
842 branch.as_deref(),
843 Path::new(&repo_root),
844 keep_remote_branch,
845 )
846 .await
847 };
848 if removed {
849 did_clean = true;
850 } else {
851 tracing::warn!(
852 task_id,
853 worktree = %wt.display(),
854 "worktree directory still exists after removal attempt — not marking as cleaned"
855 );
856 }
857 }
858 } else if let Some(ref br) = branch {
859 if !opts.dry_run && !keep_remote_branch {
862 tracing::debug!(task_id, branch = %br, "no worktree on disk, cleaning up branch only");
863 let repo_root = resolve_repo_root(repo).await?;
865 if !pr_merged
866 && !rescue_and_notify(
867 task_id,
868 repo,
869 external_id.as_deref(),
870 None,
871 br,
872 Path::new(&repo_root),
873 )
874 .await
875 {
876 return Ok(false);
877 }
878 delete_branches(task_id, br, Path::new(&repo_root)).await;
879 did_clean = true;
880 }
881 }
882
883 if did_clean {
884 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
888 && let Err(e) = store.mark_cleaned(store_id).await
889 {
890 tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned — will retry");
891 return Ok(did_clean);
893 }
894 store_log_activity(
895 &Some(Arc::clone(store)),
896 repo,
897 task_id,
898 "branch_delete",
899 None,
900 None,
901 None,
902 None,
903 Some(&serde_json::json!({
904 "worktree": worktree_path.map(|p| p.display().to_string()),
905 "branch": branch,
906 "keep_remote_branch": keep_remote_branch,
907 })),
908 )
909 .await;
910 }
911
912 Ok(did_clean)
913}
914
915const LANDED_BASE_REF: &str = "refs/orch/landed-base";
917
918async fn remove_landed_worktree(wt: &Path, repo_root: &Path) -> bool {
925 const GIT_TIMEOUT: Duration = Duration::from_secs(60);
926 let default_branch = worktree::detect_default_branch(repo_root).await;
927 let refspec = format!("+refs/heads/{default_branch}:{LANDED_BASE_REF}");
928 let fetched = timeout(
929 GIT_TIMEOUT,
930 git_in(repo_root, &["fetch", "origin", &refspec]),
931 )
932 .await
933 .ok()
934 .flatten()
935 .is_some_and(|o| o.status.success());
936 if !fetched {
937 tracing::debug!(worktree = %wt.display(), "default branch fetch failed, skipping git-cow cleanup");
938 return false;
939 }
940 cow::remove_landed(repo_root, wt, Some(LANDED_BASE_REF)).await
941}
942
943#[derive(Debug, PartialEq, Eq)]
945pub(crate) enum Rescue {
946 Clean,
948 Pushed {
950 branch: String,
951 commits: Vec<String>,
952 },
953 Failed,
955}
956
957async fn git_in(dir: &Path, args: &[&str]) -> Option<Output> {
958 git_ops::git()
959 .await
960 .arg("-C")
961 .arg(dir)
962 .args(args)
963 .output_with_context()
964 .await
965 .ok()
966 .map(git_ops::sanitize_git_output)
967}
968
969pub(crate) async fn rescue_unpushed_work(
975 task_id: &str,
976 wt: Option<&Path>,
977 br: &str,
978 repo_root: &Path,
979) -> Rescue {
980 if let Some(wt) = wt
981 && fs::try_exists(wt.join(".git")).await.unwrap_or(false)
982 {
983 let Some(status) = git_in(wt, &["status", "--porcelain"]).await else {
984 tracing::warn!(task_id, branch = %br, "cannot read worktree status, keeping worktree");
985 return Rescue::Failed;
986 };
987 if !status.status.success() {
988 tracing::warn!(task_id, branch = %br, "git status failed, keeping worktree");
989 return Rescue::Failed;
990 }
991 if !status.stdout.is_empty() {
992 let committed = git_in(wt, &["add", "-A"])
993 .await
994 .is_some_and(|o| o.status.success())
995 && git_in(
996 wt,
997 &[
998 "-c",
999 "user.name=orch",
1000 "-c",
1001 "user.email=orch@localhost",
1002 "commit",
1003 "-m",
1004 "rescue: uncommitted changes saved by orch cleanup",
1005 ],
1006 )
1007 .await
1008 .is_some_and(|o| o.status.success());
1009 if !committed {
1010 tracing::warn!(task_id, branch = %br, "cannot commit uncommitted changes, keeping worktree");
1011 return Rescue::Failed;
1012 }
1013 }
1014 }
1015
1016 let local_ref = format!("refs/heads/{br}");
1017 let exists = git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1018 .await
1019 .is_some_and(|o| o.status.success());
1020 if !exists {
1021 return Rescue::Clean;
1022 }
1023 let default_ref = format!(
1025 "refs/heads/{}",
1026 worktree::detect_default_branch(repo_root).await
1027 );
1028 let remote_tip = git_in(repo_root, &["ls-remote", "origin", &local_ref])
1030 .await
1031 .filter(|o| o.status.success())
1032 .and_then(|o| {
1033 String::from_utf8_lossy(&o.stdout)
1034 .split_whitespace()
1035 .next()
1036 .map(str::to_string)
1037 });
1038 let remote_tip = match remote_tip {
1040 Some(tip) => {
1041 let known = git_in(repo_root, &["cat-file", "-e", &format!("{tip}^{{commit}}")])
1042 .await
1043 .is_some_and(|o| o.status.success());
1044 known.then_some(tip)
1045 }
1046 None => None,
1047 };
1048 let mut args = vec!["rev-list", "--oneline", &local_ref, "--not", "--remotes"];
1049 if let Some(tip) = remote_tip.as_deref() {
1050 args.push(tip);
1051 }
1052 let default_exists = default_ref != local_ref
1053 && git_in(
1054 repo_root,
1055 &["rev-parse", "--verify", "--quiet", &default_ref],
1056 )
1057 .await
1058 .is_some_and(|o| o.status.success());
1059 if default_exists {
1060 args.push(&default_ref);
1061 }
1062 let Some(list) = git_in(repo_root, &args)
1063 .await
1064 .filter(|o| o.status.success())
1065 else {
1066 tracing::warn!(task_id, branch = %br, "cannot list unpushed commits, keeping worktree and branch");
1067 return Rescue::Failed;
1068 };
1069 let commits: Vec<String> = String::from_utf8_lossy(&list.stdout)
1070 .lines()
1071 .map(str::to_string)
1072 .collect();
1073 if commits.is_empty() {
1074 return Rescue::Clean;
1075 }
1076
1077 let rescue = format!("rescue/{br}");
1078 let refspec = format!("{local_ref}:refs/heads/{rescue}");
1079 let pushed = git_in(
1080 repo_root,
1081 &["-c", "lfs.locksverify=false", "push", "origin", &refspec],
1082 )
1083 .await;
1084 if pushed.is_some_and(|o| o.status.success()) {
1085 let tracking = format!("refs/remotes/origin/{rescue}");
1088 if let Some(tip) = git_in(repo_root, &["rev-parse", &local_ref])
1089 .await
1090 .filter(|o| o.status.success())
1091 {
1092 let sha = String::from_utf8_lossy(&tip.stdout).trim().to_string();
1093 if !sha.is_empty() {
1094 let _ = git_in(repo_root, &["update-ref", &tracking, &sha]).await;
1095 }
1096 }
1097 tracing::warn!(task_id, branch = %br, rescue = %rescue, commits = commits.len(), "pushed unpushed commits to rescue branch");
1098 Rescue::Pushed {
1099 branch: rescue,
1100 commits,
1101 }
1102 } else {
1103 tracing::warn!(task_id, branch = %br, rescue = %rescue, "rescue push failed, keeping worktree and branch");
1104 Rescue::Failed
1105 }
1106}
1107
1108fn rescue_comment(rescue_branch: &str, commits: &[String]) -> String {
1109 let list = commits
1110 .iter()
1111 .map(|c| format!("- `{c}`"))
1112 .collect::<Vec<_>>()
1113 .join("\n");
1114 format!(
1115 "Cleanup found commits on this task's branch that were never pushed. They are saved on `{rescue_branch}`:\n\n{list}"
1116 )
1117}
1118
1119async fn rescue_and_notify(
1121 task_id: &str,
1122 repo: &str,
1123 external_id: Option<&str>,
1124 wt: Option<&Path>,
1125 br: &str,
1126 repo_root: &Path,
1127) -> bool {
1128 match rescue_unpushed_work(task_id, wt, br, repo_root).await {
1129 Rescue::Clean => true,
1130 Rescue::Failed => false,
1131 Rescue::Pushed { branch, commits } => {
1132 if let Some(number) = external_id.filter(|n| n.parse::<u64>().is_ok()) {
1133 match GhHttp::new() {
1134 Ok(gh) => {
1135 if let Err(e) = gh
1136 .add_comment(repo, number, &rescue_comment(&branch, &commits))
1137 .await
1138 {
1139 tracing::warn!(task_id, err = %e, "failed to comment on rescue branch");
1140 }
1141 }
1142 Err(e) => {
1143 tracing::warn!(task_id, err = %e, "cannot comment on rescue branch");
1144 }
1145 }
1146 }
1147 true
1148 }
1149 }
1150}
1151
1152pub(crate) async fn remove_worktree_and_branch(
1159 task_id: &str,
1160 wt: &Path,
1161 branch: Option<&str>,
1162 repo_root: &Path,
1163 keep_remote_branch: bool,
1164) -> bool {
1165 remove_worktree_and_branch_for(task_id, wt, branch, repo_root, keep_remote_branch, false).await
1166}
1167
1168pub(crate) async fn remove_worktree_and_branch_for(
1171 task_id: &str,
1172 wt: &Path,
1173 branch: Option<&str>,
1174 repo_root: &Path,
1175 keep_remote_branch: bool,
1176 pr_merged: bool,
1177) -> bool {
1178 if !pr_merged
1179 && let Some(br) = branch.filter(|b| !b.is_empty())
1180 && rescue_unpushed_work(task_id, Some(wt), br, repo_root).await == Rescue::Failed
1181 {
1182 return false;
1183 }
1184
1185 remove_worktree_and_branch_unchecked(task_id, wt, branch, repo_root, keep_remote_branch).await
1186}
1187
1188async fn remove_worktree_and_branch_unchecked(
1190 task_id: &str,
1191 wt: &Path,
1192 branch: Option<&str>,
1193 repo_root: &Path,
1194 keep_remote_branch: bool,
1195) -> bool {
1196 let wt_str = wt.to_string_lossy().to_string();
1197 let repo_root_str = repo_root.to_string_lossy();
1198
1199 let remove_result = Command::new("git")
1202 .args([
1203 "-C",
1204 repo_root_str.as_ref(),
1205 "worktree",
1206 "remove",
1207 &wt_str,
1208 "--force",
1209 ])
1210 .output_with_context()
1211 .await;
1212
1213 match remove_result {
1214 Ok(output) if output.status.success() => {
1215 const MAX_RETRIES: usize = 3;
1216 const RETRY_DELAY_MS: u64 = 2000;
1217 tracing::info!(task_id, "worktree removed (git metadata)");
1218 let mut removed = false;
1223 for attempt in 0..MAX_RETRIES {
1224 match fs::remove_dir_all(wt).await {
1225 Ok(()) => {
1226 removed = true;
1227 break;
1228 }
1229 Err(e) if e.kind() == ErrorKind::NotFound => {
1230 removed = true;
1232 break;
1233 }
1234 Err(e) if e.kind() == ErrorKind::DirectoryNotEmpty => {
1235 if attempt < MAX_RETRIES - 1 {
1236 tracing::debug!(
1237 task_id,
1238 path = %wt.display(),
1239 attempt = attempt + 1,
1240 "worktree directory not empty — retrying after delay"
1241 );
1242 sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
1243 } else {
1244 tracing::warn!(
1245 task_id,
1246 path = %wt.display(),
1247 err = %e,
1248 "failed to remove worktree directory after {} attempts (Directory not empty)",
1249 MAX_RETRIES
1250 );
1251 }
1252 }
1253 Err(e) => {
1254 tracing::warn!(task_id, path = %wt.display(), err = %e, "failed to remove worktree directory");
1255 break;
1256 }
1257 }
1258 }
1259 if removed {
1260 tracing::info!(task_id, path = %wt.display(), "worktree physical directory removed");
1261 } else {
1262 tracing::warn!(
1263 task_id,
1264 path = %wt.display(),
1265 "worktree directory still present after git worktree remove"
1266 );
1267 }
1268 }
1269 Ok(output) => {
1270 let stderr = String::from_utf8_lossy(&output.stderr);
1271 if stderr.contains("is not a working tree") {
1277 tracing::debug!(
1278 task_id,
1279 path = %wt.display(),
1280 "path is not a registered worktree (stale metadata) — removing directory and pruning"
1281 );
1282 if let Err(e) = fs::remove_dir_all(wt).await {
1283 if match fs::try_exists(wt).await {
1285 Ok(true) => true,
1286 Ok(false) => false,
1287 Err(e) => {
1288 tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree does not exist");
1289 false
1290 }
1291 } {
1292 tracing::warn!(
1293 task_id,
1294 path = %wt.display(),
1295 err = %e,
1296 "failed to remove stale worktree directory"
1297 );
1298 }
1299 } else {
1300 tracing::debug!(task_id, path = %wt.display(), "stale worktree directory removed");
1301 }
1302 if let Err(e) = Command::new("git")
1305 .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1306 .output_with_context()
1307 .await
1308 {
1309 tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1310 }
1311 } else {
1312 tracing::warn!(task_id, err = %stderr, "failed to remove worktree");
1313 }
1314 }
1315 Err(e) => {
1316 tracing::warn!(task_id, err = %e, "failed to remove worktree");
1317 }
1318 }
1319
1320 if let Err(e) = Command::new("git")
1322 .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1323 .output_with_context()
1324 .await
1325 {
1326 tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1327 }
1328
1329 if let Some(br) = branch {
1333 if keep_remote_branch {
1334 delete_local_branch(task_id, br, repo_root).await;
1335 } else {
1336 delete_branches(task_id, br, repo_root).await;
1337 }
1338 }
1339
1340 match fs::try_exists(wt).await {
1342 Ok(false) => true, Ok(true) => false, Err(e) => {
1345 tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree still present");
1346 false }
1348 }
1349}
1350
1351pub(crate) async fn local_branch_exists(repo_root: &Path, br: &str) -> bool {
1353 let local_ref = format!("refs/heads/{br}");
1354 git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1355 .await
1356 .is_some_and(|o| o.status.success())
1357}
1358
1359async fn commits_outside(repo_root: &Path, rev: &str, others: &[&str]) -> Option<u64> {
1361 let mut args = vec![
1362 "rev-list".to_string(),
1363 "--count".to_string(),
1364 rev.to_string(),
1365 ];
1366 let mut exclude = Vec::new();
1368 for other in others {
1369 let exists = Command::new("git")
1370 .args([
1371 "-C",
1372 &repo_root.to_string_lossy(),
1373 "rev-parse",
1374 "--verify",
1375 "--quiet",
1376 other,
1377 ])
1378 .output_with_context()
1379 .await
1380 .is_ok_and(|o| o.status.success());
1381 if exists {
1382 exclude.push(other.to_string());
1383 }
1384 }
1385 if !exclude.is_empty() {
1386 args.push("--not".to_string());
1387 args.extend(exclude);
1388 }
1389 let output = Command::new("git")
1390 .arg("-C")
1391 .arg(repo_root)
1392 .args(&args)
1393 .output_with_context()
1394 .await
1395 .ok()?;
1396 if !output.status.success() {
1397 return None;
1398 }
1399 String::from_utf8_lossy(&output.stdout).trim().parse().ok()
1400}
1401
1402async fn delete_local_branch(task_id: &str, br: &str, repo_root: &Path) {
1404 let default_branch = worktree::detect_default_branch(repo_root).await;
1405 let remote_ref = format!("refs/remotes/origin/{br}");
1406 let default_ref = format!("refs/remotes/origin/{default_branch}");
1407 let local_ref = format!("refs/heads/{br}");
1408 let local_default_ref = format!("refs/heads/{default_branch}");
1409 let rescue_ref = format!("refs/remotes/origin/rescue/{br}");
1410 match commits_outside(
1411 repo_root,
1412 &local_ref,
1413 &[&remote_ref, &default_ref, &local_default_ref, &rescue_ref],
1414 )
1415 .await
1416 {
1417 Some(0) => {}
1418 Some(n) => {
1419 tracing::warn!(task_id, branch = %br, unpushed = n, "local branch holds commits origin does not have, keeping it");
1420 return;
1421 }
1422 None => {
1423 tracing::debug!(task_id, branch = %br, "local branch missing or unreadable, nothing to delete");
1424 return;
1425 }
1426 }
1427 let output = Command::new("git")
1428 .args(["-C", &repo_root.to_string_lossy(), "branch", "-D", br])
1429 .output_with_context()
1430 .await;
1431 match output {
1432 Ok(o) if o.status.success() => {
1433 tracing::info!(task_id, branch = %br, "local branch deleted");
1434 }
1435 Ok(o) => {
1436 let stderr = String::from_utf8_lossy(&o.stderr);
1437 tracing::debug!(task_id, err = %stderr, "local branch delete skipped (may not exist)");
1438 }
1439 Err(e) => {
1440 tracing::warn!(task_id, err = %e, "failed to delete local branch");
1441 }
1442 }
1443}
1444
1445pub(crate) async fn delete_branches(task_id: &str, br: &str, repo_root: &Path) {
1453 if br == SCREENSHOTS_BRANCH {
1454 return;
1455 }
1456 let default_branch = worktree::detect_default_branch(repo_root).await;
1457 let _ = git_ops::git()
1458 .await
1459 .args([
1460 "-C",
1461 &repo_root.to_string_lossy(),
1462 "fetch",
1463 "origin",
1464 &default_branch,
1465 br,
1466 ])
1467 .output_with_context()
1468 .await;
1469
1470 delete_local_branch(task_id, br, repo_root).await;
1471
1472 let remote_ref = format!("refs/remotes/origin/{br}");
1473 let default_ref = format!("refs/remotes/origin/{default_branch}");
1474 match commits_outside(repo_root, &remote_ref, &[&default_ref]).await {
1475 Some(0) => {}
1476 Some(n) => {
1477 tracing::info!(task_id, branch = %br, unmerged = n, "remote branch has commits the default branch lacks, keeping it");
1478 return;
1479 }
1480 None => {
1481 tracing::debug!(task_id, branch = %br, "remote branch missing or unreadable, nothing to delete");
1482 return;
1483 }
1484 }
1485
1486 let remote_delete = git_ops::git()
1487 .await
1488 .args([
1489 "-C",
1490 &repo_root.to_string_lossy(),
1491 "-c",
1492 "lfs.locksverify=false",
1493 "push",
1494 "origin",
1495 "--delete",
1496 br,
1497 ])
1498 .output_with_context()
1499 .await;
1500
1501 match remote_delete {
1502 Ok(output) if output.status.success() => {
1503 tracing::info!(task_id, branch = %br, "remote branch deleted");
1504 git_ops::clear_push_lease(repo_root, br).await;
1505 }
1506 Ok(output) => {
1507 let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
1508 tracing::debug!(task_id, err = %stderr, "remote branch delete skipped");
1509 }
1510 Err(e) => {
1511 tracing::warn!(task_id, err = %e, "failed to delete remote branch");
1512 }
1513 }
1514}
1515
1516async fn is_worktree_in_active_session(worktree: &Path) -> bool {
1519 let Ok(panes) = tmux::default_server().pane_paths().await else {
1520 return false;
1521 };
1522 panes.iter().any(|pane| pane.starts_with(worktree))
1523}
1524
1525async fn worktree_age_hours(worktree: &Path) -> Option<u64> {
1529 let metadata = fs::metadata(worktree).await.ok()?;
1531 let modified = metadata.modified().ok()?;
1532 let age = SystemTime::now().duration_since(modified).ok()?;
1533 Some(age.as_secs() / 3600)
1534}
1535
1536pub(crate) async fn cleanup_orphaned_worktree(task_id: &str, wt: &Path) -> bool {
1542 let repo_root = match resolve_repo_root_for_orphaned_worktree(wt).await {
1543 Ok(root) => root,
1544 Err(e) => {
1545 tracing::warn!(
1546 worktree = %wt.display(),
1547 error = %e,
1548 "cannot resolve repo root for orphaned worktree"
1549 );
1550 return false;
1551 }
1552 };
1553 remove_worktree_and_branch(task_id, wt, None, Path::new(&repo_root), false).await
1554}
1555
1556pub(crate) async fn resolve_repo_root_for_orphaned_worktree(wt: &Path) -> anyhow::Result<String> {
1563 let git_file = wt.join(".git");
1564 if fs::try_exists(&git_file).await.unwrap_or(false)
1565 && let Ok(content) = fs::read_to_string(&git_file).await
1566 {
1567 for line in content.lines() {
1568 if let Some(gitdir) = line.strip_prefix("gitdir: ") {
1569 let gitdir_path = PathBuf::from(gitdir);
1573 if let Some(repo_root) = gitdir_path.parent().and_then(|p| p.parent()) {
1574 return Ok(repo_root.display().to_string());
1575 }
1576 }
1577 }
1578 }
1579
1580 let worktrees_dir = home::worktrees_dir()?;
1583 if let Ok(relative) = wt.strip_prefix(&worktrees_dir)
1584 && let Some(project_name) = relative.components().next()
1585 {
1586 let project_name = project_name.as_os_str().to_string_lossy();
1587
1588 if let Ok(paths) = config::get_project_paths() {
1589 for path_str in &paths {
1590 let path = Path::new(path_str);
1591 if let Some(name) = path.file_name()
1592 && name.to_string_lossy() == project_name
1593 {
1594 return Ok(path_str.clone());
1595 }
1596 }
1597 }
1598
1599 let parts: Vec<&str> = project_name.split('/').collect();
1601 let bare = if parts.len() == 2 {
1602 home::projects_dir()
1603 .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1604 .unwrap_or_default()
1605 } else {
1606 return Err(anyhow::anyhow!(
1607 "cannot determine owner for single-segment project name '{project_name}' — \
1608 bare repo location is ambiguous; register the project with 'owner/repo' format"
1609 ));
1610 };
1611 if fs::try_exists(&bare).await.unwrap_or(false) {
1612 return Ok(bare.display().to_string());
1613 }
1614 }
1615
1616 anyhow::bail!(
1617 "cannot resolve repo root for orphaned worktree at {} — tried .git parsing and project lookup",
1618 wt.display()
1619 )
1620}
1621
1622pub async fn resolve_repo_root_from_worktree(wt: &Path) -> anyhow::Result<String> {
1629 let git_file = wt.join(".git");
1631 if !fs::try_exists(&git_file).await.unwrap_or(false) {
1632 anyhow::bail!(".git file not found in worktree at {}", wt.display());
1633 }
1634
1635 let content = fs::read_to_string(&git_file)
1636 .await
1637 .map_err(|e| anyhow::anyhow!("failed to read .git file: {e}"))?;
1638
1639 for line in content.lines() {
1641 if let Some(gitdir) = line.strip_prefix("gitdir:") {
1642 let gitdir = gitdir.trim();
1643 let gitdir_path = Path::new(gitdir);
1647 if let Some(repo_root) = gitdir_path
1648 .parent() .and_then(|p| p.parent()) .and_then(|p| p.parent())
1651 {
1653 return Ok(repo_root.display().to_string());
1654 }
1655 }
1656 }
1657
1658 anyhow::bail!(
1659 "cannot resolve repo root from worktree .git file at {}",
1660 wt.display()
1661 )
1662}
1663
1664pub(crate) async fn resolve_repo_root(repo: &str) -> anyhow::Result<String> {
1669 let paths = config::get_project_paths().unwrap_or_default();
1671 for path_str in &paths {
1672 let path = Path::new(path_str);
1673 let orch_yml = path.join(".orch.yml");
1674 let legacy = path.join(".orchestrator.yml");
1675 let config_file = if fs::try_exists(&orch_yml).await.unwrap_or(false) {
1676 orch_yml
1677 } else if fs::try_exists(&legacy).await.unwrap_or(false) {
1678 legacy
1679 } else {
1680 continue;
1681 };
1682 if let Ok(content) = fs::read_to_string(&config_file).await
1683 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1684 && let Some(r) = doc
1685 .get("gh")
1686 .and_then(|gh| gh.get("repo"))
1687 .and_then(|r| r.as_str())
1688 && r == repo
1689 {
1690 return Ok(path_str.clone());
1691 }
1692 }
1693
1694 let parts: Vec<&str> = repo.split('/').collect();
1696 let bare = if parts.len() == 2 {
1697 home::projects_dir()
1698 .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1699 .unwrap_or_default()
1700 } else {
1701 PathBuf::new()
1702 };
1703 if fs::try_exists(&bare).await.unwrap_or(false) {
1704 return Ok(bare.display().to_string());
1705 }
1706
1707 anyhow::bail!(
1708 "cannot find local path for project {repo} — \
1709 checked {} registered project(s) and bare clone at {}",
1710 paths.len(),
1711 bare.display()
1712 )
1713}
1714
1715fn resolve_project_dir_for_repo(repo: &str) -> anyhow::Result<PathBuf> {
1720 if let Ok(dir) = env::var("PROJECT_DIR")
1722 && !dir.is_empty()
1723 {
1724 return Ok(PathBuf::from(dir));
1725 }
1726
1727 if let Ok(paths) = config::get_project_paths() {
1729 for path_str in &paths {
1730 let path = Path::new(path_str);
1731 let orch_yml = path.join(".orch.yml");
1732 let legacy = path.join(".orchestrator.yml");
1733 let config_file = if Path::new(&orch_yml).exists() {
1734 orch_yml
1735 } else if Path::new(&legacy).exists() {
1736 legacy
1737 } else {
1738 continue;
1739 };
1740 if let Ok(content) = std_fs::read_to_string(&config_file)
1741 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1742 && let Some(r) = doc
1743 .get("gh")
1744 .and_then(|gh| gh.get("repo"))
1745 .and_then(|r| r.as_str())
1746 && r == repo
1747 {
1748 return Ok(path_str.clone().into());
1749 }
1750 }
1751 }
1752
1753 anyhow::bail!("project dir not found for repo: {repo}")
1754}
1755
1756pub(crate) async fn check_merged_prs(
1761 backend: &Arc<dyn ExternalBackend>,
1762 repo: &str,
1763 store: &Arc<TaskStore>,
1764 task_manager: &Arc<TaskManager>,
1765 in_review_tasks: &[ReviewTaskSnapshot],
1766 needs_review_tasks: &[ReviewTaskSnapshot],
1767) -> anyhow::Result<()> {
1768 let mut branch_map: HashMap<String, String> = HashMap::new();
1769 let all_review_tasks: Vec<&ReviewTaskSnapshot> = in_review_tasks
1770 .iter()
1771 .chain(needs_review_tasks.iter())
1772 .collect();
1773
1774 for task in &all_review_tasks {
1775 if !task.stored.branch.is_empty() {
1776 branch_map.insert(task.external.id.0.clone(), task.stored.branch.clone());
1777 }
1778 }
1779
1780 tracing::debug!(
1781 count = all_review_tasks.len(),
1782 "checking review tasks for merged PRs"
1783 );
1784
1785 let mut task_branches: Vec<(String, String)> = Vec::new();
1789 for task in all_review_tasks {
1790 let task_id = &task.external.id.0;
1791 let branch = if let Some(b) = branch_map.get(task_id) {
1792 b.clone()
1793 } else {
1794 match store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
1795 .await
1796 .map(|t| t.branch)
1797 {
1798 Some(b) if !b.is_empty() => b,
1799 _ => {
1800 tracing::debug!(task_id, "no branch info, skipping PR check");
1801 continue;
1802 }
1803 }
1804 };
1805 task_branches.push((task_id.clone(), branch));
1806 }
1807
1808 if task_branches.is_empty() {
1809 return Ok(());
1810 }
1811
1812 let branches: Vec<String> = task_branches.iter().map(|(_, b)| b.clone()).collect();
1814 let merged_map = match backend.batch_is_pr_merged(&branches).await {
1815 Ok(map) => map,
1816 Err(e) => {
1817 tracing::warn!(
1818 err = %e,
1819 branch_count = branches.len(),
1820 "batch PR merge check failed, retrying affected branches individually"
1821 );
1822 fallback_is_pr_merged_by_branch(backend, &branches).await
1823 }
1824 };
1825
1826 for (task_id, branch) in task_branches {
1827 let is_merged = merged_map.get(&branch).copied().unwrap_or(false);
1828 if !is_merged {
1829 continue;
1830 }
1831
1832 tracing::info!(task_id, branch = %branch, "PR merged, marking task complete");
1833
1834 let stored = store::opt_store_get_task(&Some(Arc::clone(store)), repo, &task_id).await;
1835 if let Some(ref stored) = stored {
1836 let external = store_task_to_external(stored);
1837 if bootstrap::hold_after_merge(&external, store, repo).await {
1838 tracing::info!(
1839 task_id,
1840 branch = %branch,
1841 "CI bootstrap PR merged, holding done until the ruleset exists"
1842 );
1843 if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1844 tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1845 }
1846 continue;
1847 }
1848 }
1849
1850 let id = ExternalId(task_id.clone());
1851 if let Err(e) = task_manager.update_task_status(&id, Status::Done).await {
1852 tracing::warn!(task_id, err = %e, "failed to update status to done");
1853 continue;
1854 }
1855
1856 if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1857 tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1858 }
1859
1860 let comment = format!("PR merged, marking task complete{}", engine::orch_footer());
1861 if let Err(e) = backend.post_comment(&id, &comment).await {
1862 tracing::warn!(task_id, err = %e, "failed to post comment");
1863 }
1864 }
1865
1866 Ok(())
1867}
1868
1869async fn fallback_is_pr_merged_by_branch(
1870 backend: &Arc<dyn ExternalBackend>,
1871 branches: &[String],
1872) -> HashMap<String, bool> {
1873 let futs: Vec<_> = branches
1874 .iter()
1875 .map(|branch| {
1876 let backend = Arc::clone(backend);
1877 let branch = branch.clone();
1878 async move {
1879 match backend.is_pr_merged(&branch).await {
1880 Ok(is_merged) => Some((branch, is_merged)),
1881 Err(err) => {
1882 tracing::warn!(
1883 branch,
1884 err = %err,
1885 "fallback PR merge check failed for branch"
1886 );
1887 None
1888 }
1889 }
1890 }
1891 })
1892 .collect();
1893
1894 future::join_all(futs).await.into_iter().flatten().collect()
1895}
1896
1897#[derive(Debug, Clone)]
1898pub(crate) struct ReviewTaskSnapshot {
1899 pub external: ExternalTask,
1900 pub stored: Task,
1901}
1902
1903#[cfg(test)]
1904mod tests;