1use crate::engine::ci;
8use crate::store::Task;
9
10use crate::backends::{ExternalBackend, ExternalId, ExternalTask, Status};
11use crate::cmd::CommandErrorContext;
12use crate::engine::ci_bootstrap;
13use crate::engine::tasks::{TaskManager, store_task_to_external};
14use crate::store;
15use crate::store::TaskStatus;
16use crate::store::TaskStore;
17use crate::store::store_log_activity;
18use dashmap::{DashMap, DashSet};
19use futures::future;
20use std::collections::HashMap;
21use std::collections::HashSet;
22use std::env;
23use std::fs as std_fs;
24use std::io::ErrorKind;
25use std::path::Path;
26use std::path::PathBuf;
27use std::process::Output;
28use std::sync::Arc;
29use std::sync::LazyLock;
30use std::time::SystemTime;
31use std::time::{Duration, Instant};
32use tokio::fs;
33use tokio::process::Command;
34use tokio::time::sleep;
35use tokio::time::timeout;
36
37use crate::config;
38use crate::engine;
39use crate::engine::git::cow;
40use crate::engine::git::git_ops;
41use crate::engine::git::screenshots::SCREENSHOTS_BRANCH;
42use crate::engine::git::worktree;
43use crate::github::http::GhHttp;
44use crate::home;
45
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 ci_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 = remove_worktree_and_branch_unchecked(
833 task_id,
834 &wt,
835 branch.as_deref(),
836 Path::new(&repo_root),
837 keep_remote_branch,
838 )
839 .await;
840 if removed {
841 did_clean = true;
842 } else {
843 tracing::warn!(
844 task_id,
845 worktree = %wt.display(),
846 "worktree directory still exists after removal attempt — not marking as cleaned"
847 );
848 }
849 }
850 } else if let Some(ref br) = branch {
851 if !opts.dry_run && !keep_remote_branch {
854 tracing::debug!(task_id, branch = %br, "no worktree on disk, cleaning up branch only");
855 let repo_root = resolve_repo_root(repo).await?;
857 if !pr_merged
858 && !rescue_and_notify(
859 task_id,
860 repo,
861 external_id.as_deref(),
862 None,
863 br,
864 Path::new(&repo_root),
865 )
866 .await
867 {
868 return Ok(false);
869 }
870 delete_branches(task_id, br, Path::new(&repo_root)).await;
871 did_clean = true;
872 }
873 }
874
875 if did_clean {
876 if let Ok(Some(store_id)) = store.resolve_task_id(repo, task_id).await
880 && let Err(e) = store.mark_cleaned(store_id).await
881 {
882 tracing::warn!(task_id, err = %e, "failed to mark worktree cleaned — will retry");
883 return Ok(did_clean);
885 }
886 store_log_activity(
887 &Some(Arc::clone(store)),
888 repo,
889 task_id,
890 "branch_delete",
891 None,
892 None,
893 None,
894 None,
895 Some(&serde_json::json!({
896 "worktree": worktree_path.map(|p| p.display().to_string()),
897 "branch": branch,
898 "keep_remote_branch": keep_remote_branch,
899 })),
900 )
901 .await;
902 }
903
904 Ok(did_clean)
905}
906
907#[derive(Debug, PartialEq, Eq)]
909pub(crate) enum Rescue {
910 Clean,
912 Pushed {
914 branch: String,
915 commits: Vec<String>,
916 },
917 Failed,
919}
920
921async fn git_in(dir: &Path, args: &[&str]) -> Option<Output> {
922 git_ops::git()
923 .await
924 .arg("-C")
925 .arg(dir)
926 .args(args)
927 .output_with_context()
928 .await
929 .ok()
930 .map(git_ops::sanitize_git_output)
931}
932
933pub(crate) async fn rescue_unpushed_work(
939 task_id: &str,
940 wt: Option<&Path>,
941 br: &str,
942 repo_root: &Path,
943) -> Rescue {
944 if let Some(wt) = wt
945 && fs::try_exists(wt.join(".git")).await.unwrap_or(false)
946 {
947 let Some(status) = git_in(wt, &["status", "--porcelain"]).await else {
948 tracing::warn!(task_id, branch = %br, "cannot read worktree status, keeping worktree");
949 return Rescue::Failed;
950 };
951 if !status.status.success() {
952 tracing::warn!(task_id, branch = %br, "git status failed, keeping worktree");
953 return Rescue::Failed;
954 }
955 if !status.stdout.is_empty() {
956 let committed = git_in(wt, &["add", "-A"])
957 .await
958 .is_some_and(|o| o.status.success())
959 && git_in(
960 wt,
961 &[
962 "-c",
963 "user.name=orch",
964 "-c",
965 "user.email=orch@localhost",
966 "commit",
967 "-m",
968 "rescue: uncommitted changes saved by orch cleanup",
969 ],
970 )
971 .await
972 .is_some_and(|o| o.status.success());
973 if !committed {
974 tracing::warn!(task_id, branch = %br, "cannot commit uncommitted changes, keeping worktree");
975 return Rescue::Failed;
976 }
977 }
978 }
979
980 let local_ref = format!("refs/heads/{br}");
981 let exists = git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
982 .await
983 .is_some_and(|o| o.status.success());
984 if !exists {
985 return Rescue::Clean;
986 }
987 let default_ref = format!(
989 "refs/heads/{}",
990 worktree::detect_default_branch(repo_root).await
991 );
992 let remote_tip = git_in(repo_root, &["ls-remote", "origin", &local_ref])
994 .await
995 .filter(|o| o.status.success())
996 .and_then(|o| {
997 String::from_utf8_lossy(&o.stdout)
998 .split_whitespace()
999 .next()
1000 .map(str::to_string)
1001 });
1002 let remote_tip = match remote_tip {
1004 Some(tip) => {
1005 let known = git_in(repo_root, &["cat-file", "-e", &format!("{tip}^{{commit}}")])
1006 .await
1007 .is_some_and(|o| o.status.success());
1008 known.then_some(tip)
1009 }
1010 None => None,
1011 };
1012 let mut args = vec!["rev-list", "--oneline", &local_ref, "--not", "--remotes"];
1013 if let Some(tip) = remote_tip.as_deref() {
1014 args.push(tip);
1015 }
1016 let default_exists = default_ref != local_ref
1017 && git_in(
1018 repo_root,
1019 &["rev-parse", "--verify", "--quiet", &default_ref],
1020 )
1021 .await
1022 .is_some_and(|o| o.status.success());
1023 if default_exists {
1024 args.push(&default_ref);
1025 }
1026 let Some(list) = git_in(repo_root, &args)
1027 .await
1028 .filter(|o| o.status.success())
1029 else {
1030 tracing::warn!(task_id, branch = %br, "cannot list unpushed commits, keeping worktree and branch");
1031 return Rescue::Failed;
1032 };
1033 let commits: Vec<String> = String::from_utf8_lossy(&list.stdout)
1034 .lines()
1035 .map(str::to_string)
1036 .collect();
1037 if commits.is_empty() {
1038 return Rescue::Clean;
1039 }
1040
1041 let rescue = format!("rescue/{br}");
1042 let refspec = format!("{local_ref}:refs/heads/{rescue}");
1043 let pushed = git_in(
1044 repo_root,
1045 &["-c", "lfs.locksverify=false", "push", "origin", &refspec],
1046 )
1047 .await;
1048 if pushed.is_some_and(|o| o.status.success()) {
1049 let tracking = format!("refs/remotes/origin/{rescue}");
1052 if let Some(tip) = git_in(repo_root, &["rev-parse", &local_ref])
1053 .await
1054 .filter(|o| o.status.success())
1055 {
1056 let sha = String::from_utf8_lossy(&tip.stdout).trim().to_string();
1057 if !sha.is_empty() {
1058 let _ = git_in(repo_root, &["update-ref", &tracking, &sha]).await;
1059 }
1060 }
1061 tracing::warn!(task_id, branch = %br, rescue = %rescue, commits = commits.len(), "pushed unpushed commits to rescue branch");
1062 Rescue::Pushed {
1063 branch: rescue,
1064 commits,
1065 }
1066 } else {
1067 tracing::warn!(task_id, branch = %br, rescue = %rescue, "rescue push failed, keeping worktree and branch");
1068 Rescue::Failed
1069 }
1070}
1071
1072fn rescue_comment(rescue_branch: &str, commits: &[String]) -> String {
1073 let list = commits
1074 .iter()
1075 .map(|c| format!("- `{c}`"))
1076 .collect::<Vec<_>>()
1077 .join("\n");
1078 format!(
1079 "Cleanup found commits on this task's branch that were never pushed. They are saved on `{rescue_branch}`:\n\n{list}"
1080 )
1081}
1082
1083async fn rescue_and_notify(
1085 task_id: &str,
1086 repo: &str,
1087 external_id: Option<&str>,
1088 wt: Option<&Path>,
1089 br: &str,
1090 repo_root: &Path,
1091) -> bool {
1092 match rescue_unpushed_work(task_id, wt, br, repo_root).await {
1093 Rescue::Clean => true,
1094 Rescue::Failed => false,
1095 Rescue::Pushed { branch, commits } => {
1096 if let Some(number) = external_id.filter(|n| n.parse::<u64>().is_ok()) {
1097 match GhHttp::new() {
1098 Ok(gh) => {
1099 if let Err(e) = gh
1100 .add_comment(repo, number, &rescue_comment(&branch, &commits))
1101 .await
1102 {
1103 tracing::warn!(task_id, err = %e, "failed to comment on rescue branch");
1104 }
1105 }
1106 Err(e) => {
1107 tracing::warn!(task_id, err = %e, "cannot comment on rescue branch");
1108 }
1109 }
1110 }
1111 true
1112 }
1113 }
1114}
1115
1116pub(crate) async fn remove_worktree_and_branch(
1123 task_id: &str,
1124 wt: &Path,
1125 branch: Option<&str>,
1126 repo_root: &Path,
1127 keep_remote_branch: bool,
1128) -> bool {
1129 remove_worktree_and_branch_for(task_id, wt, branch, repo_root, keep_remote_branch, false).await
1130}
1131
1132pub(crate) async fn remove_worktree_and_branch_for(
1135 task_id: &str,
1136 wt: &Path,
1137 branch: Option<&str>,
1138 repo_root: &Path,
1139 keep_remote_branch: bool,
1140 pr_merged: bool,
1141) -> bool {
1142 if !pr_merged
1143 && let Some(br) = branch.filter(|b| !b.is_empty())
1144 && rescue_unpushed_work(task_id, Some(wt), br, repo_root).await == Rescue::Failed
1145 {
1146 return false;
1147 }
1148
1149 remove_worktree_and_branch_unchecked(task_id, wt, branch, repo_root, keep_remote_branch).await
1150}
1151
1152async fn remove_worktree_and_branch_unchecked(
1154 task_id: &str,
1155 wt: &Path,
1156 branch: Option<&str>,
1157 repo_root: &Path,
1158 keep_remote_branch: bool,
1159) -> bool {
1160 let wt_str = wt.to_string_lossy().to_string();
1161 let repo_root_str = repo_root.to_string_lossy();
1162
1163 let remove_result = Command::new("git")
1166 .args([
1167 "-C",
1168 repo_root_str.as_ref(),
1169 "worktree",
1170 "remove",
1171 &wt_str,
1172 "--force",
1173 ])
1174 .output_with_context()
1175 .await;
1176
1177 match remove_result {
1178 Ok(output) if output.status.success() => {
1179 const MAX_RETRIES: usize = 3;
1180 const RETRY_DELAY_MS: u64 = 2000;
1181 tracing::info!(task_id, "worktree removed (git metadata)");
1182 let mut removed = false;
1187 for attempt in 0..MAX_RETRIES {
1188 match fs::remove_dir_all(wt).await {
1189 Ok(()) => {
1190 removed = true;
1191 break;
1192 }
1193 Err(e) if e.kind() == ErrorKind::NotFound => {
1194 removed = true;
1196 break;
1197 }
1198 Err(e) if e.kind() == ErrorKind::DirectoryNotEmpty => {
1199 if attempt < MAX_RETRIES - 1 {
1200 tracing::debug!(
1201 task_id,
1202 path = %wt.display(),
1203 attempt = attempt + 1,
1204 "worktree directory not empty — retrying after delay"
1205 );
1206 sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
1207 } else {
1208 tracing::warn!(
1209 task_id,
1210 path = %wt.display(),
1211 err = %e,
1212 "failed to remove worktree directory after {} attempts (Directory not empty)",
1213 MAX_RETRIES
1214 );
1215 }
1216 }
1217 Err(e) => {
1218 tracing::warn!(task_id, path = %wt.display(), err = %e, "failed to remove worktree directory");
1219 break;
1220 }
1221 }
1222 }
1223 if removed {
1224 tracing::info!(task_id, path = %wt.display(), "worktree physical directory removed");
1225 } else {
1226 tracing::warn!(
1227 task_id,
1228 path = %wt.display(),
1229 "worktree directory still present after git worktree remove"
1230 );
1231 }
1232 }
1233 Ok(output) => {
1234 let stderr = String::from_utf8_lossy(&output.stderr);
1235 if stderr.contains("is not a working tree") {
1241 tracing::debug!(
1242 task_id,
1243 path = %wt.display(),
1244 "path is not a registered worktree (stale metadata) — removing directory and pruning"
1245 );
1246 if let Err(e) = fs::remove_dir_all(wt).await {
1247 if match fs::try_exists(wt).await {
1249 Ok(true) => true,
1250 Ok(false) => false,
1251 Err(e) => {
1252 tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree does not exist");
1253 false
1254 }
1255 } {
1256 tracing::warn!(
1257 task_id,
1258 path = %wt.display(),
1259 err = %e,
1260 "failed to remove stale worktree directory"
1261 );
1262 }
1263 } else {
1264 tracing::debug!(task_id, path = %wt.display(), "stale worktree directory removed");
1265 }
1266 if let Err(e) = Command::new("git")
1269 .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1270 .output_with_context()
1271 .await
1272 {
1273 tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1274 }
1275 } else {
1276 tracing::warn!(task_id, err = %stderr, "failed to remove worktree");
1277 }
1278 }
1279 Err(e) => {
1280 tracing::warn!(task_id, err = %e, "failed to remove worktree");
1281 }
1282 }
1283
1284 if let Err(e) = Command::new("git")
1286 .args(["-C", repo_root_str.as_ref(), "worktree", "prune"])
1287 .output_with_context()
1288 .await
1289 {
1290 tracing::warn!(task_id, err = %e, "git worktree prune failed — stale metadata may persist");
1291 }
1292
1293 if let Some(br) = branch {
1297 if keep_remote_branch {
1298 delete_local_branch(task_id, br, repo_root).await;
1299 } else {
1300 delete_branches(task_id, br, repo_root).await;
1301 }
1302 }
1303
1304 match fs::try_exists(wt).await {
1306 Ok(false) => true, Ok(true) => false, Err(e) => {
1309 tracing::warn!(task_id, err = %e, "try_exists failed — assuming worktree still present");
1310 false }
1312 }
1313}
1314
1315pub(crate) async fn local_branch_exists(repo_root: &Path, br: &str) -> bool {
1317 let local_ref = format!("refs/heads/{br}");
1318 git_in(repo_root, &["rev-parse", "--verify", "--quiet", &local_ref])
1319 .await
1320 .is_some_and(|o| o.status.success())
1321}
1322
1323async fn commits_outside(repo_root: &Path, rev: &str, others: &[&str]) -> Option<u64> {
1325 let mut args = vec![
1326 "rev-list".to_string(),
1327 "--count".to_string(),
1328 rev.to_string(),
1329 ];
1330 let mut exclude = Vec::new();
1332 for other in others {
1333 let exists = Command::new("git")
1334 .args([
1335 "-C",
1336 &repo_root.to_string_lossy(),
1337 "rev-parse",
1338 "--verify",
1339 "--quiet",
1340 other,
1341 ])
1342 .output_with_context()
1343 .await
1344 .is_ok_and(|o| o.status.success());
1345 if exists {
1346 exclude.push(other.to_string());
1347 }
1348 }
1349 if !exclude.is_empty() {
1350 args.push("--not".to_string());
1351 args.extend(exclude);
1352 }
1353 let output = Command::new("git")
1354 .arg("-C")
1355 .arg(repo_root)
1356 .args(&args)
1357 .output_with_context()
1358 .await
1359 .ok()?;
1360 if !output.status.success() {
1361 return None;
1362 }
1363 String::from_utf8_lossy(&output.stdout).trim().parse().ok()
1364}
1365
1366async fn delete_local_branch(task_id: &str, br: &str, repo_root: &Path) {
1368 let default_branch = worktree::detect_default_branch(repo_root).await;
1369 let remote_ref = format!("refs/remotes/origin/{br}");
1370 let default_ref = format!("refs/remotes/origin/{default_branch}");
1371 let local_ref = format!("refs/heads/{br}");
1372 let local_default_ref = format!("refs/heads/{default_branch}");
1373 let rescue_ref = format!("refs/remotes/origin/rescue/{br}");
1374 match commits_outside(
1375 repo_root,
1376 &local_ref,
1377 &[&remote_ref, &default_ref, &local_default_ref, &rescue_ref],
1378 )
1379 .await
1380 {
1381 Some(0) => {}
1382 Some(n) => {
1383 tracing::warn!(task_id, branch = %br, unpushed = n, "local branch holds commits origin does not have, keeping it");
1384 return;
1385 }
1386 None => {
1387 tracing::debug!(task_id, branch = %br, "local branch missing or unreadable, nothing to delete");
1388 return;
1389 }
1390 }
1391 let output = Command::new("git")
1392 .args(["-C", &repo_root.to_string_lossy(), "branch", "-D", br])
1393 .output_with_context()
1394 .await;
1395 match output {
1396 Ok(o) if o.status.success() => {
1397 tracing::info!(task_id, branch = %br, "local branch deleted");
1398 }
1399 Ok(o) => {
1400 let stderr = String::from_utf8_lossy(&o.stderr);
1401 tracing::debug!(task_id, err = %stderr, "local branch delete skipped (may not exist)");
1402 }
1403 Err(e) => {
1404 tracing::warn!(task_id, err = %e, "failed to delete local branch");
1405 }
1406 }
1407}
1408
1409pub(crate) async fn delete_branches(task_id: &str, br: &str, repo_root: &Path) {
1417 if br == SCREENSHOTS_BRANCH {
1418 return;
1419 }
1420 let default_branch = worktree::detect_default_branch(repo_root).await;
1421 let _ = git_ops::git()
1422 .await
1423 .args([
1424 "-C",
1425 &repo_root.to_string_lossy(),
1426 "fetch",
1427 "origin",
1428 &default_branch,
1429 br,
1430 ])
1431 .output_with_context()
1432 .await;
1433
1434 delete_local_branch(task_id, br, repo_root).await;
1435
1436 let remote_ref = format!("refs/remotes/origin/{br}");
1437 let default_ref = format!("refs/remotes/origin/{default_branch}");
1438 match commits_outside(repo_root, &remote_ref, &[&default_ref]).await {
1439 Some(0) => {}
1440 Some(n) => {
1441 tracing::info!(task_id, branch = %br, unmerged = n, "remote branch has commits the default branch lacks, keeping it");
1442 return;
1443 }
1444 None => {
1445 tracing::debug!(task_id, branch = %br, "remote branch missing or unreadable, nothing to delete");
1446 return;
1447 }
1448 }
1449
1450 let remote_delete = git_ops::git()
1451 .await
1452 .args([
1453 "-C",
1454 &repo_root.to_string_lossy(),
1455 "-c",
1456 "lfs.locksverify=false",
1457 "push",
1458 "origin",
1459 "--delete",
1460 br,
1461 ])
1462 .output_with_context()
1463 .await;
1464
1465 match remote_delete {
1466 Ok(output) if output.status.success() => {
1467 tracing::info!(task_id, branch = %br, "remote branch deleted");
1468 git_ops::clear_push_lease(repo_root, br).await;
1469 }
1470 Ok(output) => {
1471 let stderr = git_ops::sanitize_push_error(&String::from_utf8_lossy(&output.stderr));
1472 tracing::debug!(task_id, err = %stderr, "remote branch delete skipped");
1473 }
1474 Err(e) => {
1475 tracing::warn!(task_id, err = %e, "failed to delete remote branch");
1476 }
1477 }
1478}
1479
1480async fn is_worktree_in_active_session(worktree: &Path) -> bool {
1486 let output = Command::new("tmux")
1487 .args(["list-panes", "-a", "-F", "#{pane_current_path}"])
1488 .output()
1489 .await;
1490
1491 match output {
1492 Ok(o) if o.status.success() => {
1493 let worktree_str = worktree.to_string_lossy();
1494 String::from_utf8_lossy(&o.stdout).lines().any(|line| {
1495 let pane_path = line.trim();
1496 pane_path == worktree_str.as_ref()
1498 || pane_path.starts_with(&format!("{worktree_str}/"))
1499 })
1500 }
1501 _ => false,
1503 }
1504}
1505
1506async fn worktree_age_hours(worktree: &Path) -> Option<u64> {
1510 let metadata = fs::metadata(worktree).await.ok()?;
1512 let modified = metadata.modified().ok()?;
1513 let age = SystemTime::now().duration_since(modified).ok()?;
1514 Some(age.as_secs() / 3600)
1515}
1516
1517pub(crate) async fn cleanup_orphaned_worktree(task_id: &str, wt: &Path) -> bool {
1523 let repo_root = match resolve_repo_root_for_orphaned_worktree(wt).await {
1524 Ok(root) => root,
1525 Err(e) => {
1526 tracing::warn!(
1527 worktree = %wt.display(),
1528 error = %e,
1529 "cannot resolve repo root for orphaned worktree"
1530 );
1531 return false;
1532 }
1533 };
1534 remove_worktree_and_branch(task_id, wt, None, Path::new(&repo_root), false).await
1535}
1536
1537pub(crate) async fn resolve_repo_root_for_orphaned_worktree(wt: &Path) -> anyhow::Result<String> {
1544 let git_file = wt.join(".git");
1545 if fs::try_exists(&git_file).await.unwrap_or(false)
1546 && let Ok(content) = fs::read_to_string(&git_file).await
1547 {
1548 for line in content.lines() {
1549 if let Some(gitdir) = line.strip_prefix("gitdir: ") {
1550 let gitdir_path = PathBuf::from(gitdir);
1554 if let Some(repo_root) = gitdir_path.parent().and_then(|p| p.parent()) {
1555 return Ok(repo_root.display().to_string());
1556 }
1557 }
1558 }
1559 }
1560
1561 let worktrees_dir = home::worktrees_dir()?;
1564 if let Ok(relative) = wt.strip_prefix(&worktrees_dir)
1565 && let Some(project_name) = relative.components().next()
1566 {
1567 let project_name = project_name.as_os_str().to_string_lossy();
1568
1569 if let Ok(paths) = config::get_project_paths() {
1570 for path_str in &paths {
1571 let path = Path::new(path_str);
1572 if let Some(name) = path.file_name()
1573 && name.to_string_lossy() == project_name
1574 {
1575 return Ok(path_str.clone());
1576 }
1577 }
1578 }
1579
1580 let parts: Vec<&str> = project_name.split('/').collect();
1582 let bare = if parts.len() == 2 {
1583 home::projects_dir()
1584 .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1585 .unwrap_or_default()
1586 } else {
1587 return Err(anyhow::anyhow!(
1588 "cannot determine owner for single-segment project name '{project_name}' — \
1589 bare repo location is ambiguous; register the project with 'owner/repo' format"
1590 ));
1591 };
1592 if fs::try_exists(&bare).await.unwrap_or(false) {
1593 return Ok(bare.display().to_string());
1594 }
1595 }
1596
1597 anyhow::bail!(
1598 "cannot resolve repo root for orphaned worktree at {} — tried .git parsing and project lookup",
1599 wt.display()
1600 )
1601}
1602
1603pub async fn resolve_repo_root_from_worktree(wt: &Path) -> anyhow::Result<String> {
1610 let git_file = wt.join(".git");
1612 if !fs::try_exists(&git_file).await.unwrap_or(false) {
1613 anyhow::bail!(".git file not found in worktree at {}", wt.display());
1614 }
1615
1616 let content = fs::read_to_string(&git_file)
1617 .await
1618 .map_err(|e| anyhow::anyhow!("failed to read .git file: {e}"))?;
1619
1620 for line in content.lines() {
1622 if let Some(gitdir) = line.strip_prefix("gitdir:") {
1623 let gitdir = gitdir.trim();
1624 let gitdir_path = Path::new(gitdir);
1628 if let Some(repo_root) = gitdir_path
1629 .parent() .and_then(|p| p.parent()) .and_then(|p| p.parent())
1632 {
1634 return Ok(repo_root.display().to_string());
1635 }
1636 }
1637 }
1638
1639 anyhow::bail!(
1640 "cannot resolve repo root from worktree .git file at {}",
1641 wt.display()
1642 )
1643}
1644
1645pub(crate) async fn resolve_repo_root(repo: &str) -> anyhow::Result<String> {
1650 let paths = config::get_project_paths().unwrap_or_default();
1652 for path_str in &paths {
1653 let path = Path::new(path_str);
1654 let orch_yml = path.join(".orch.yml");
1655 let legacy = path.join(".orchestrator.yml");
1656 let config_file = if fs::try_exists(&orch_yml).await.unwrap_or(false) {
1657 orch_yml
1658 } else if fs::try_exists(&legacy).await.unwrap_or(false) {
1659 legacy
1660 } else {
1661 continue;
1662 };
1663 if let Ok(content) = fs::read_to_string(&config_file).await
1664 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1665 && let Some(r) = doc
1666 .get("gh")
1667 .and_then(|gh| gh.get("repo"))
1668 .and_then(|r| r.as_str())
1669 && r == repo
1670 {
1671 return Ok(path_str.clone());
1672 }
1673 }
1674
1675 let parts: Vec<&str> = repo.split('/').collect();
1677 let bare = if parts.len() == 2 {
1678 home::projects_dir()
1679 .map(|d| d.join(parts[0]).join(format!("{}.git", parts[1])))
1680 .unwrap_or_default()
1681 } else {
1682 PathBuf::new()
1683 };
1684 if fs::try_exists(&bare).await.unwrap_or(false) {
1685 return Ok(bare.display().to_string());
1686 }
1687
1688 anyhow::bail!(
1689 "cannot find local path for project {repo} — \
1690 checked {} registered project(s) and bare clone at {}",
1691 paths.len(),
1692 bare.display()
1693 )
1694}
1695
1696fn resolve_project_dir_for_repo(repo: &str) -> anyhow::Result<PathBuf> {
1701 if let Ok(dir) = env::var("PROJECT_DIR")
1703 && !dir.is_empty()
1704 {
1705 return Ok(PathBuf::from(dir));
1706 }
1707
1708 if let Ok(paths) = config::get_project_paths() {
1710 for path_str in &paths {
1711 let path = Path::new(path_str);
1712 let orch_yml = path.join(".orch.yml");
1713 let legacy = path.join(".orchestrator.yml");
1714 let config_file = if Path::new(&orch_yml).exists() {
1715 orch_yml
1716 } else if Path::new(&legacy).exists() {
1717 legacy
1718 } else {
1719 continue;
1720 };
1721 if let Ok(content) = std_fs::read_to_string(&config_file)
1722 && let Ok(doc) = serde_norway::from_str::<serde_norway::Value>(&content)
1723 && let Some(r) = doc
1724 .get("gh")
1725 .and_then(|gh| gh.get("repo"))
1726 .and_then(|r| r.as_str())
1727 && r == repo
1728 {
1729 return Ok(path_str.clone().into());
1730 }
1731 }
1732 }
1733
1734 anyhow::bail!("project dir not found for repo: {repo}")
1735}
1736
1737pub(crate) async fn check_merged_prs(
1742 backend: &Arc<dyn ExternalBackend>,
1743 repo: &str,
1744 store: &Arc<TaskStore>,
1745 task_manager: &Arc<TaskManager>,
1746 in_review_tasks: &[ReviewTaskSnapshot],
1747 needs_review_tasks: &[ReviewTaskSnapshot],
1748) -> anyhow::Result<()> {
1749 let mut branch_map: HashMap<String, String> = HashMap::new();
1750 let all_review_tasks: Vec<&ReviewTaskSnapshot> = in_review_tasks
1751 .iter()
1752 .chain(needs_review_tasks.iter())
1753 .collect();
1754
1755 for task in &all_review_tasks {
1756 if !task.stored.branch.is_empty() {
1757 branch_map.insert(task.external.id.0.clone(), task.stored.branch.clone());
1758 }
1759 }
1760
1761 tracing::debug!(
1762 count = all_review_tasks.len(),
1763 "checking review tasks for merged PRs"
1764 );
1765
1766 let mut task_branches: Vec<(String, String)> = Vec::new();
1770 for task in all_review_tasks {
1771 let task_id = &task.external.id.0;
1772 let branch = if let Some(b) = branch_map.get(task_id) {
1773 b.clone()
1774 } else {
1775 match store::opt_store_get_task(&Some(Arc::clone(store)), repo, task_id)
1776 .await
1777 .map(|t| t.branch)
1778 {
1779 Some(b) if !b.is_empty() => b,
1780 _ => {
1781 tracing::debug!(task_id, "no branch info, skipping PR check");
1782 continue;
1783 }
1784 }
1785 };
1786 task_branches.push((task_id.clone(), branch));
1787 }
1788
1789 if task_branches.is_empty() {
1790 return Ok(());
1791 }
1792
1793 let branches: Vec<String> = task_branches.iter().map(|(_, b)| b.clone()).collect();
1795 let merged_map = match backend.batch_is_pr_merged(&branches).await {
1796 Ok(map) => map,
1797 Err(e) => {
1798 tracing::warn!(
1799 err = %e,
1800 branch_count = branches.len(),
1801 "batch PR merge check failed, retrying affected branches individually"
1802 );
1803 fallback_is_pr_merged_by_branch(backend, &branches).await
1804 }
1805 };
1806
1807 for (task_id, branch) in task_branches {
1808 let is_merged = merged_map.get(&branch).copied().unwrap_or(false);
1809 if !is_merged {
1810 continue;
1811 }
1812
1813 tracing::info!(task_id, branch = %branch, "PR merged, marking task complete");
1814
1815 let stored = store::opt_store_get_task(&Some(Arc::clone(store)), repo, &task_id).await;
1816 if let Some(ref stored) = stored {
1817 let external = store_task_to_external(stored);
1818 if ci_bootstrap::hold_after_merge(&external, store, repo).await {
1819 tracing::info!(
1820 task_id,
1821 branch = %branch,
1822 "CI bootstrap PR merged, holding done until the ruleset exists"
1823 );
1824 if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1825 tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1826 }
1827 continue;
1828 }
1829 }
1830
1831 let id = ExternalId(task_id.clone());
1832 if let Err(e) = task_manager.update_task_status(&id, Status::Done).await {
1833 tracing::warn!(task_id, err = %e, "failed to update status to done");
1834 continue;
1835 }
1836
1837 if let Err(e) = cleanup_merged_pr_worktree(&task_id, repo, store).await {
1838 tracing::warn!(task_id, err = %e, "worktree cleanup after merge failed");
1839 }
1840
1841 let comment = format!("PR merged, marking task complete{}", engine::orch_footer());
1842 if let Err(e) = backend.post_comment(&id, &comment).await {
1843 tracing::warn!(task_id, err = %e, "failed to post comment");
1844 }
1845 }
1846
1847 Ok(())
1848}
1849
1850async fn fallback_is_pr_merged_by_branch(
1851 backend: &Arc<dyn ExternalBackend>,
1852 branches: &[String],
1853) -> HashMap<String, bool> {
1854 let futs: Vec<_> = branches
1855 .iter()
1856 .map(|branch| {
1857 let backend = Arc::clone(backend);
1858 let branch = branch.clone();
1859 async move {
1860 match backend.is_pr_merged(&branch).await {
1861 Ok(is_merged) => Some((branch, is_merged)),
1862 Err(err) => {
1863 tracing::warn!(
1864 branch,
1865 err = %err,
1866 "fallback PR merge check failed for branch"
1867 );
1868 None
1869 }
1870 }
1871 }
1872 })
1873 .collect();
1874
1875 future::join_all(futs).await.into_iter().flatten().collect()
1876}
1877
1878#[derive(Debug, Clone)]
1879pub(crate) struct ReviewTaskSnapshot {
1880 pub external: ExternalTask,
1881 pub stored: Task,
1882}
1883
1884#[cfg(test)]
1885mod tests;