1use crate::backends::github::GitHubBackend;
2use crate::backends::{ExternalBackend, ExternalId};
3use crate::config;
4use crate::engine::cleanup::{
5 cleanup_orphaned_worktree, remove_worktree_and_branch, resolve_repo_root,
6};
7use crate::github::http::GhHttp;
8use crate::store::{Task, TaskStatus, TaskStore};
9use crate::tmux::TmuxManager;
10use std::io::Write;
11use std::path::Path;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::Arc;
14
15enum FixAction {
20 LinkPr { store_id: i64, pr_number: u64 },
22 ReopenIssue { store_id: i64 },
24 CloseIssue { store_id: i64 },
26 SyncLabels { store_id: i64 },
28 ResetToRouted { store_id: i64 },
30 CleanWorktree { store_id: i64 },
32 RemoveOrphanedWorktree { path: String },
34 MarkDoneFromMergedPr { store_id: i64 },
36 ResetDeadReview { store_id: i64 },
38 None,
40}
41
42struct Finding {
44 severity: Severity,
45 task_id: String,
46 message: String,
47 fix: FixAction,
48}
49
50#[derive(Clone, Copy)]
51enum Severity {
52 Error,
53 Warning,
54}
55
56impl Severity {
57 fn symbol(self) -> &'static str {
58 match self {
59 Self::Error => "ERR",
60 Self::Warning => "WARN",
61 }
62 }
63}
64
65pub async fn run(full: bool, fix: bool, dry_run: bool) -> anyhow::Result<()> {
70 let store = Arc::new(crate::cli::init_store().await?);
71 let gh = GhHttp::new()?;
72 let tmux = TmuxManager::new();
73
74 let repos: Vec<String> = match config::get_current_repo() {
76 Ok(repo) => vec![repo],
77 Err(_) => {
78 let all = store.distinct_repos().await?;
79 if all.is_empty() {
80 println!("No tasks found in store.");
81 return Ok(());
82 }
83 all
84 }
85 };
86
87 let spinner_running = Arc::new(AtomicBool::new(true));
89 let spinner_flag = spinner_running.clone();
90 let spinner_task = tokio::spawn(async move {
91 let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
92 let mut i = 0usize;
93 while spinner_flag.load(Ordering::Relaxed) {
94 eprint!(
95 "\r{} Running orch service doctor…",
96 frames[i % frames.len()]
97 );
98 let _ = std::io::stderr().flush();
99 tokio::time::sleep(std::time::Duration::from_millis(80)).await;
100 i += 1;
101 }
102 eprint!("\r");
103 let _ = std::io::stderr().flush();
104 });
105
106 let result = run_checks(full, fix, dry_run, &repos, &store, &gh, &tmux).await;
107
108 spinner_running.store(false, Ordering::Relaxed);
109 let _ = spinner_task.await;
110
111 result
112}
113
114async fn run_checks(
115 full: bool,
116 fix: bool,
117 dry_run: bool,
118 repos: &[String],
119 store: &Arc<TaskStore>,
120 gh: &GhHttp,
121 tmux: &TmuxManager,
122) -> anyhow::Result<()> {
123 let mut all_findings: Vec<Finding> = Vec::new();
124
125 for repo in repos {
126 let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
127 let mut findings: Vec<Finding> = Vec::new();
128 if full {
129 let cutoff = chrono::Utc::now() - chrono::Duration::days(7);
133 let cutoff_str = cutoff.format("%Y-%m-%dT%H:%M:%SZ").to_string();
134 let all_tasks = store.list_for_doctor(repo, &cutoff_str).await?;
135
136 let recent_done_tasks: Vec<_> = all_tasks
137 .iter()
138 .filter(|t| t.status == TaskStatus::Done)
139 .collect();
140 let active_tasks: Vec<_> = all_tasks
141 .iter()
142 .filter(|t| t.status != TaskStatus::Done)
143 .collect();
144 let in_progress_tasks: Vec<_> = all_tasks
145 .iter()
146 .filter(|t| t.status == TaskStatus::InProgress)
147 .collect();
148 let in_review_tasks: Vec<_> = all_tasks
149 .iter()
150 .filter(|t| t.status == TaskStatus::InReview)
151 .collect();
152
153 let pr_numbers_to_fetch: Vec<u64> = {
155 let mut nums: Vec<u64> = recent_done_tasks
156 .iter()
157 .filter(|t| !(t.origin == "internal" && t.external_id.is_none()))
158 .filter_map(|t| t.pr_number.map(|n| n as u64))
159 .chain(
160 active_tasks
161 .iter()
162 .filter_map(|t| t.pr_number.map(|n| n as u64)),
163 )
164 .collect();
165 nums.sort_unstable();
166 nums.dedup();
167 nums
168 };
169 let pr_states = gh
170 .batch_get_pr_states(repo, &pr_numbers_to_fetch)
171 .await
172 .unwrap_or_default();
173
174 for task in &recent_done_tasks {
176 if task.origin == "internal" && task.external_id.is_none() {
177 continue;
178 }
179 if task.pr_number.is_none() && task.external_id.is_none() {
180 continue;
181 }
182 check_done_no_merged_pr(task, gh, &pr_states, &mut findings, repo).await;
183 }
184
185 for task in &recent_done_tasks {
187 check_dirty_worktree(task, &mut findings).await;
188 }
189
190 for task in &recent_done_tasks {
192 check_unpushed_commits(task, &mut findings).await;
193 }
194
195 let external_active: Vec<_> = active_tasks
198 .iter()
199 .copied()
200 .filter(|t| t.origin != "internal")
201 .collect();
202 let issue_numbers = collect_valid_external_issue_numbers(
203 external_active.iter().copied(),
204 repo,
205 "cli::doctor::run_checks(full)",
206 );
207 let issue_states = gh
208 .batch_get_issue_states(repo, &issue_numbers, "cli::doctor::run_checks(full)")
209 .await
210 .unwrap_or_default();
211 for task in &external_active {
212 check_issue_status_mismatch(task, &issue_states, &mut findings);
213 check_label_mismatch(task, &issue_states, &mut findings);
214 }
215
216 for task in &in_progress_tasks {
218 check_stale_in_progress(task, repo, tmux, &mut findings).await;
219 }
220
221 check_orphaned_worktrees(&all_tasks, &mut findings).await;
223
224 for task in &active_tasks {
226 check_pr_merged_not_done(task, &pr_states, &mut findings);
227 }
228
229 for task in &in_review_tasks {
231 check_dead_review_session(task, repo, tmux, &mut findings).await;
232 }
233 } else {
234 let active_tasks = store.list_active(repo).await?;
236
237 let open_prs: Vec<serde_json::Value> =
239 gh.list_open_pulls(repo).await.unwrap_or_default();
240
241 let mut pr_by_number: std::collections::HashMap<u64, serde_json::Value> =
243 std::collections::HashMap::new();
244 let mut pr_by_head: std::collections::HashMap<String, serde_json::Value> =
245 std::collections::HashMap::new();
246 for pr in &open_prs {
247 if let Some(n) = pr.get("number").and_then(|v| v.as_u64()) {
248 pr_by_number.insert(n, pr.clone());
249 }
250 if let Some(head) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
251 pr_by_head.insert(head.to_string(), pr.clone());
252 }
253 }
254
255 let external_active: Vec<_> = active_tasks
257 .iter()
258 .filter(|t| t.origin != "internal")
259 .collect();
260 for task in &active_tasks {
261 if task.status == TaskStatus::InProgress {
263 check_stale_in_progress(task, repo, tmux, &mut findings).await;
264 }
265
266 if task.status == TaskStatus::InReview {
268 check_dead_review_session(task, repo, tmux, &mut findings).await;
269 }
270
271 if let Some(pr_num) = task.pr_number {
273 match gh.get_pr(repo, pr_num as u64).await {
274 Ok(pr) => {
275 if pr.merged.unwrap_or(false) {
276 findings.push(Finding {
277 severity: Severity::Error,
278 task_id: task_label(task),
279 message: format!(
280 "PR #{} is merged but task status is '{}'",
281 pr_num,
282 task.status.as_str()
283 ),
284 fix: FixAction::MarkDoneFromMergedPr { store_id: task.id },
285 });
286 }
287 }
288 Err(_) => {
289 }
291 }
292 } else if !task.branch.is_empty() {
293 if let Some(pr) = pr_by_head.get(&task.branch) {
295 if task.pr_number.is_none() {
297 if let Some(n) = pr.get("number").and_then(|v| v.as_u64()) {
298 findings.push(Finding {
299 severity: Severity::Warning,
300 task_id: task_label(task),
301 message: format!(
302 "branch '{}' has open PR #{} not linked in store",
303 task.branch, n
304 ),
305 fix: FixAction::LinkPr {
306 store_id: task.id,
307 pr_number: n,
308 },
309 });
310 }
311 }
312 }
313 }
314 }
315
316 let external_issue_numbers = collect_valid_external_issue_numbers(
318 external_active.iter().copied(),
319 repo,
320 "cli::doctor::run_checks(fast)",
321 );
322 let issue_states = gh
323 .batch_get_issue_states(
324 repo,
325 &external_issue_numbers,
326 "cli::doctor::run_checks(fast)",
327 )
328 .await
329 .unwrap_or_default();
330 for task in &external_active {
331 check_issue_status_mismatch(task, &issue_states, &mut findings);
332 check_label_mismatch(task, &issue_states, &mut findings);
333 }
334
335 for pr in &open_prs {
337 let pr_num = pr.get("number").and_then(|v| v.as_u64());
338 let head = pr
339 .pointer("/head/ref")
340 .and_then(|v| v.as_str())
341 .map(|s| s.to_string());
342 let mut owned = false;
343 if let Some(n) = pr_num {
344 for t in &active_tasks {
345 if let Some(pn) = t.pr_number {
346 if pn as u64 == n {
347 owned = true;
348 break;
349 }
350 }
351 if !t.branch.is_empty() && Some(t.branch.clone()) == head {
352 owned = true;
353 break;
354 }
355 }
356 }
357 if !owned {
358 let num_str = pr_num
359 .map(|n| n.to_string())
360 .unwrap_or_else(|| "?".to_string());
361 findings.push(Finding {
362 severity: Severity::Warning,
363 task_id: format!("pr:{}", num_str),
364 message: format!("open PR with no active task: #{}", num_str),
365 fix: FixAction::None,
366 });
367 }
368 }
369
370 check_orphaned_worktrees(&active_tasks, &mut findings).await;
372 }
373
374 if repos.len() > 1 && !findings.is_empty() {
375 println!("\n=== {} ===", repo);
376 }
377
378 if (fix || dry_run) && !findings.is_empty() {
380 let errors = findings
381 .iter()
382 .filter(|f| matches!(f.severity, Severity::Error))
383 .count();
384 let warnings = findings.len() - errors;
385 for f in &findings {
386 println!("[{}] #{}: {}", f.severity.symbol(), f.task_id, f.message);
387 }
388 println!(
389 "\nFound {} issue(s): {} error(s), {} warning(s)",
390 findings.len(),
391 errors,
392 warnings,
393 );
394 apply_fixes(&findings, store, repo, &backend, gh, dry_run).await?;
395 }
396
397 all_findings.extend(findings);
398 }
399
400 if all_findings.is_empty() {
401 println!("No issues found. All task state is consistent.");
402 return Ok(());
403 }
404
405 if !fix && !dry_run {
407 let errors = all_findings
408 .iter()
409 .filter(|f| matches!(f.severity, Severity::Error))
410 .count();
411 let warnings = all_findings.len() - errors;
412
413 for f in &all_findings {
414 println!("[{}] #{}: {}", f.severity.symbol(), f.task_id, f.message);
415 }
416
417 println!(
418 "\nFound {} issue(s): {} error(s), {} warning(s)",
419 all_findings.len(),
420 errors,
421 warnings,
422 );
423
424 if errors > 0 {
425 println!("\nRun `orch service doctor --fix` to attempt automatic repairs.");
426 println!("Run `orch service doctor --dry-run` to preview what --fix would do.");
427 }
428 }
429
430 Ok(())
431}
432
433async fn check_done_no_merged_pr(
436 task: &Task,
437 gh: &GhHttp,
438 pr_states: &std::collections::HashMap<u64, (bool, String)>,
439 findings: &mut Vec<Finding>,
440 repo: &str,
441) {
442 let task_label = task_label(task);
443 let store_id = task.id;
444
445 match task.pr_number {
446 Some(pr_num) => {
447 let (merged, state) = if let Some(s) = pr_states.get(&(pr_num as u64)) {
449 s.clone()
450 } else {
451 match gh.get_pr(repo, pr_num as u64).await {
452 Ok(pr) => (pr.merged.unwrap_or(false), pr.state),
453 Err(e) => {
454 findings.push(Finding {
455 severity: Severity::Warning,
456 task_id: task_label,
457 message: format!(
458 "done with PR #{} but failed to fetch PR: {}",
459 pr_num, e
460 ),
461 fix: FixAction::None,
462 });
463 return;
464 }
465 }
466 };
467 if !merged {
468 findings.push(Finding {
469 severity: Severity::Error,
470 task_id: task_label,
471 message: format!(
472 "done but PR #{} is {} (not merged) — done is terminal, file a new task to finish the work",
473 pr_num, state
474 ),
475 fix: FixAction::None,
476 });
477 }
478 }
479 None => {
480 if !task.branch.is_empty() {
482 match gh.get_pr_number(repo, &task.branch).await {
483 Ok(Some(pr_num)) => {
484 let merged = gh
486 .get_pr(repo, pr_num)
487 .await
488 .map(|pr| pr.merged == Some(true))
489 .unwrap_or(false);
490 if merged {
491 findings.push(Finding {
493 severity: Severity::Warning,
494 task_id: task_label,
495 message: format!(
496 "done with no pr_number but branch has merged PR #{}",
497 pr_num
498 ),
499 fix: FixAction::LinkPr {
500 store_id,
501 pr_number: pr_num,
502 },
503 });
504 } else {
505 findings.push(Finding {
507 severity: Severity::Error,
508 task_id: task_label,
509 message: format!(
510 "done with no pr_number but branch has unmerged PR #{} — done is terminal, file a new task to finish the work",
511 pr_num
512 ),
513 fix: FixAction::None,
514 });
515 }
516 }
517 Ok(None) => {
518 findings.push(Finding {
519 severity: Severity::Error,
520 task_id: task_label,
521 message: describe_unrecovered_work(task).await,
522 fix: FixAction::None,
523 });
524 }
525 Err(_) => {
526 findings.push(Finding {
527 severity: Severity::Error,
528 task_id: task_label,
529 message: "done but no PR number recorded and branch lookup failed"
530 .to_string(),
531 fix: FixAction::None,
532 });
533 }
534 }
535 } else {
536 findings.push(Finding {
537 severity: Severity::Error,
538 task_id: task_label,
539 message: "done but no branch or PR recorded".to_string(),
540 fix: FixAction::None,
541 });
542 }
543 }
544 }
545}
546
547async fn describe_unrecovered_work(task: &Task) -> String {
552 const HEAD: &str = "done but no PR was ever created";
553 if task.worktree.is_empty() || task.worktree_cleaned {
554 return format!("{HEAD} and the worktree is gone — any work is lost");
555 }
556 let wt = Path::new(&task.worktree);
557 if !wt.exists() || !wt.join(".git").exists() {
558 return format!("{HEAD} and the worktree is gone — any work is lost");
559 }
560
561 let has_dirty = tokio::process::Command::new("git")
563 .args(["status", "--porcelain"])
564 .current_dir(wt)
565 .output()
566 .await
567 .map(|o| !o.stdout.is_empty())
568 .unwrap_or(false);
569
570 if has_dirty {
571 return format!("{HEAD}; uncommitted changes left in {}", task.worktree);
572 }
573
574 let has_unpushed = tokio::process::Command::new("git")
576 .args(["log", &format!("origin/{}..HEAD", task.branch), "--oneline"])
577 .current_dir(wt)
578 .output()
579 .await
580 .map(|o| !o.stdout.is_empty())
581 .unwrap_or(false);
582
583 if has_unpushed {
584 return format!("{HEAD}; unpushed commits left in {}", task.worktree);
585 }
586
587 let branch_on_remote = crate::engine::runner::git_ops::git()
589 .await
590 .args(["ls-remote", "--heads", "origin", &task.branch])
591 .current_dir(wt)
592 .output()
593 .await
594 .map(|o| !o.stdout.is_empty())
595 .unwrap_or(false);
596
597 if branch_on_remote {
598 return format!("{HEAD}; branch '{}' is pushed with no PR", task.branch);
599 }
600
601 HEAD.to_string()
602}
603
604async fn check_dirty_worktree(task: &Task, findings: &mut Vec<Finding>) {
606 if task.worktree.is_empty() || task.worktree_cleaned {
607 return;
608 }
609 let wt = Path::new(&task.worktree);
610 if !wt.exists() || !wt.join(".git").exists() {
611 return;
612 }
613 let output = tokio::process::Command::new("git")
614 .args(["status", "--porcelain"])
615 .current_dir(wt)
616 .output()
617 .await;
618 if let Ok(out) = output {
619 if !out.stdout.is_empty() {
620 findings.push(Finding {
621 severity: Severity::Error,
622 task_id: task_label(task),
623 message: format!(
624 "done but worktree has uncommitted changes: {} — done is terminal, file a new task to land them",
625 task.worktree
626 ),
627 fix: FixAction::None,
628 });
629 }
630 }
631}
632
633async fn check_unpushed_commits(task: &Task, findings: &mut Vec<Finding>) {
635 if task.worktree.is_empty() || task.worktree_cleaned || task.branch.is_empty() {
636 return;
637 }
638 let wt = Path::new(&task.worktree);
639 if !wt.exists() || !wt.join(".git").exists() {
640 return;
641 }
642 let output = tokio::process::Command::new("git")
643 .args(["log", &format!("origin/{}..HEAD", task.branch), "--oneline"])
644 .current_dir(wt)
645 .output()
646 .await;
647 if let Ok(out) = output {
648 if !out.stdout.is_empty() {
649 let count = out.stdout.iter().filter(|&&b| b == b'\n').count();
650 findings.push(Finding {
651 severity: Severity::Error,
652 task_id: task_label(task),
653 message: format!(
654 "done but {} unpushed commit(s) in worktree: {} — done is terminal, file a new task to land them",
655 count, task.worktree
656 ),
657 fix: FixAction::None,
658 });
659 }
660 }
661}
662
663fn check_issue_status_mismatch(
665 task: &Task,
666 issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
667 findings: &mut Vec<Finding>,
668) {
669 let ext_id = match &task.external_id {
670 Some(id) => id.clone(),
671 None => return,
672 };
673
674 let (state, _labels) = match issue_states.get(&ext_id) {
675 Some(v) => v,
676 None => return,
677 };
678
679 let issue_closed = state == "closed";
680 let task_done = task.status == TaskStatus::Done;
681 let task_blocked = task.status == TaskStatus::Blocked;
682
683 if issue_closed && !task_done && !task_blocked {
684 findings.push(Finding {
685 severity: Severity::Error,
686 task_id: task_label(task),
687 message: format!(
688 "GitHub issue is closed but SQLite status is '{}'",
689 task.status.as_str()
690 ),
691 fix: FixAction::ReopenIssue { store_id: task.id },
692 });
693 } else if !issue_closed && task_done {
694 findings.push(Finding {
695 severity: Severity::Warning,
696 task_id: task_label(task),
697 message: "SQLite status is 'done' but GitHub issue is still open".to_string(),
698 fix: FixAction::CloseIssue { store_id: task.id },
699 });
700 }
701}
702
703fn check_label_mismatch(
705 task: &Task,
706 issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
707 findings: &mut Vec<Finding>,
708) {
709 let ext_id = match &task.external_id {
710 Some(id) => id.clone(),
711 None => return,
712 };
713
714 let (_state, labels) = match issue_states.get(&ext_id) {
715 Some(v) => v,
716 None => return,
717 };
718
719 let expected_label = format!("status:{}", task.status.as_str());
720 let has_expected = labels.iter().any(|l| l == &expected_label);
721 let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
722
723 if !has_expected {
724 let actual = if status_labels.is_empty() {
725 "none".to_string()
726 } else {
727 status_labels
728 .iter()
729 .map(|s| s.as_str())
730 .collect::<Vec<_>>()
731 .join(", ")
732 };
733 findings.push(Finding {
734 severity: Severity::Warning,
735 task_id: task_label(task),
736 message: format!(
737 "label mismatch: SQLite='{}' but GitHub labels=[{}]",
738 task.status.as_str(),
739 actual
740 ),
741 fix: FixAction::SyncLabels { store_id: task.id },
742 });
743 }
744}
745
746async fn check_stale_in_progress(
748 task: &Task,
749 repo: &str,
750 tmux: &TmuxManager,
751 findings: &mut Vec<Finding>,
752) {
753 let task_id_str = match &task.external_id {
754 Some(id) => id.clone(),
755 None => format!("internal:{}", task.id),
756 };
757 let session = tmux.session_name(repo, &task_id_str);
758 if !tmux.session_exists(&session).await {
759 findings.push(Finding {
760 severity: Severity::Error,
761 task_id: task_label(task),
762 message: format!(
763 "status is 'in_progress' but no tmux session '{}' found",
764 session
765 ),
766 fix: FixAction::ResetToRouted { store_id: task.id },
767 });
768 }
769}
770
771async fn check_orphaned_worktrees(all_tasks: &[Task], findings: &mut Vec<Finding>) {
773 let worktrees_dir = match crate::home::worktrees_dir() {
774 Ok(d) => d,
775 Err(_) => return,
776 };
777
778 let project_dirs = match std::fs::read_dir(&worktrees_dir) {
779 Ok(d) => d,
780 Err(_) => return,
781 };
782
783 let task_by_worktree: std::collections::HashMap<&str, &Task> = all_tasks
785 .iter()
786 .filter(|t| !t.worktree.is_empty())
787 .map(|t| (t.worktree.as_str(), t))
788 .collect();
789
790 for project_entry in project_dirs {
791 let project_entry = match project_entry {
792 Ok(e) => e,
793 Err(e) => {
794 tracing::warn!(err = %e, "error reading worktrees directory entry");
795 continue;
796 }
797 };
798 if !project_entry
799 .file_type()
800 .map(|t| t.is_dir())
801 .unwrap_or(false)
802 {
803 continue;
804 }
805 let branch_dirs = match std::fs::read_dir(project_entry.path()) {
806 Ok(d) => d,
807 Err(_) => continue,
808 };
809 for branch_entry in branch_dirs {
810 let branch_entry = match branch_entry {
811 Ok(e) => e,
812 Err(e) => {
813 tracing::warn!(err = %e, "error reading project directory entry");
814 continue;
815 }
816 };
817 if !branch_entry
818 .file_type()
819 .map(|t| t.is_dir())
820 .unwrap_or(false)
821 {
822 continue;
823 }
824 let wt_path = branch_entry.path().to_string_lossy().to_string();
825
826 let owning_task = task_by_worktree.get(wt_path.as_str()).copied();
827
828 match owning_task {
829 Some(task) => {
830 if task.status == TaskStatus::Done && !task.worktree_cleaned {
831 let has_work = worktree_has_work(Path::new(&wt_path), &task.branch).await;
833 if has_work {
834 findings.push(Finding {
836 severity: Severity::Warning,
837 task_id: task_label(task),
838 message: format!("done but worktree has unsaved work: {}", wt_path),
839 fix: FixAction::None,
840 });
841 } else {
842 findings.push(Finding {
843 severity: Severity::Warning,
844 task_id: task_label(task),
845 message: format!("done but worktree not cleaned up: {}", wt_path),
846 fix: FixAction::CleanWorktree { store_id: task.id },
847 });
848 }
849 }
850 }
851 None => {
852 findings.push(Finding {
853 severity: Severity::Warning,
854 task_id: "?".to_string(),
855 message: format!("orphaned worktree (no task owns it): {}", wt_path),
856 fix: FixAction::RemoveOrphanedWorktree {
857 path: wt_path.clone(),
858 },
859 });
860 }
861 }
862 }
863 }
864}
865
866fn check_pr_merged_not_done(
868 task: &Task,
869 pr_states: &std::collections::HashMap<u64, (bool, String)>,
870 findings: &mut Vec<Finding>,
871) {
872 let pr_num = match task.pr_number {
873 Some(n) => n as u64,
874 None => return,
875 };
876
877 if let Some((merged, _)) = pr_states.get(&pr_num) {
878 if *merged {
879 findings.push(Finding {
880 severity: Severity::Error,
881 task_id: task_label(task),
882 message: format!(
883 "PR #{} is merged but task status is '{}'",
884 pr_num,
885 task.status.as_str()
886 ),
887 fix: FixAction::MarkDoneFromMergedPr { store_id: task.id },
888 });
889 }
890 }
891}
892
893async fn check_dead_review_session(
895 task: &Task,
896 repo: &str,
897 tmux: &TmuxManager,
898 findings: &mut Vec<Finding>,
899) {
900 let task_id_str = match &task.external_id {
901 Some(id) => id.clone(),
902 None => format!("internal:{}", task.id),
903 };
904 let review_task_id = format!("{}-review", task_id_str);
905 let session = tmux.session_name(repo, &review_task_id);
906 if !tmux.session_exists(&session).await {
907 findings.push(Finding {
908 severity: Severity::Error,
909 task_id: task_label(task),
910 message: format!(
911 "status is 'in_review' but no review session '{}' found",
912 session
913 ),
914 fix: FixAction::ResetDeadReview { store_id: task.id },
915 });
916 }
917}
918
919async fn worktree_has_work(wt: &Path, branch: &str) -> bool {
921 if !wt.join(".git").exists() {
922 return false;
923 }
924 let has_dirty = tokio::process::Command::new("git")
925 .args(["status", "--porcelain"])
926 .current_dir(wt)
927 .output()
928 .await
929 .map(|o| !o.stdout.is_empty())
930 .unwrap_or(false);
931 if has_dirty {
932 return true;
933 }
934 if !branch.is_empty() {
935 let has_unpushed = tokio::process::Command::new("git")
936 .args(["log", &format!("origin/{}..HEAD", branch), "--oneline"])
937 .current_dir(wt)
938 .output()
939 .await
940 .map(|o| !o.stdout.is_empty())
941 .unwrap_or(false);
942 if has_unpushed {
943 return true;
944 }
945 }
946 false
947}
948
949async fn apply_fixes(
951 findings: &[Finding],
952 store: &Arc<TaskStore>,
953 repo: &str,
954 backend: &Arc<dyn ExternalBackend>,
955 gh: &GhHttp,
956 dry_run: bool,
957) -> anyhow::Result<()> {
958 let prefix = if dry_run { "[dry-run] " } else { "" };
959 let mut fixed = 0;
960 let mut skipped = 0;
961
962 for f in findings {
963 match &f.fix {
964 FixAction::None => {
965 skipped += 1;
966 continue;
967 }
968 FixAction::LinkPr {
969 store_id,
970 pr_number,
971 } => {
972 if dry_run {
973 println!(
974 " {}would link PR #{} to task #{}",
975 prefix, pr_number, f.task_id
976 );
977 fixed += 1;
978 continue;
979 }
980
981 let _ = store
982 .set_fields(
983 *store_id,
984 &[("pr_number", serde_json::json!(*pr_number as i64))],
985 )
986 .await;
987 println!(" fixed #{}: linked PR #{}", f.task_id, pr_number);
988 fixed += 1;
989 }
990 FixAction::ReopenIssue { store_id } => {
991 let task = store.get(*store_id).await?;
992
993 if dry_run {
994 println!(
995 " {}would reopen GitHub issue + sync labels for #{}",
996 prefix, f.task_id
997 );
998 fixed += 1;
999 continue;
1000 }
1001
1002 if let Some(ref ext_id) = task.external_id {
1003 if let Err(e) = gh.reopen_issue(repo, ext_id).await {
1004 eprintln!(" fix failed for #{}: reopen failed: {}", f.task_id, e);
1005 skipped += 1;
1006 continue;
1007 }
1008 let status = task_status_to_backend_status(task.status);
1009 let _ = backend
1010 .update_status(&ExternalId(ext_id.clone()), status)
1011 .await;
1012 println!(" fixed #{}: reopened issue + synced labels", f.task_id);
1013 fixed += 1;
1014 } else {
1015 skipped += 1;
1016 }
1017 }
1018 FixAction::CloseIssue { store_id } => {
1019 let task = store.get(*store_id).await?;
1020
1021 if dry_run {
1022 println!(" {}would close GitHub issue #{}", prefix, f.task_id);
1023 fixed += 1;
1024 continue;
1025 }
1026
1027 if let Some(ref ext_id) = task.external_id {
1028 let status = crate::backends::Status::Done;
1029 if let Err(e) = backend
1030 .update_status(&ExternalId(ext_id.clone()), status)
1031 .await
1032 {
1033 eprintln!(" fix failed for #{}: {}", f.task_id, e);
1034 skipped += 1;
1035 } else {
1036 println!(" fixed #{}: closed GitHub issue", f.task_id);
1037 fixed += 1;
1038 }
1039 } else {
1040 skipped += 1;
1041 }
1042 }
1043 FixAction::SyncLabels { store_id } => {
1044 let task = store.get(*store_id).await?;
1045
1046 if dry_run {
1047 println!(
1048 " {}would sync labels to status:{} for #{}",
1049 prefix,
1050 task.status.as_str(),
1051 f.task_id
1052 );
1053 fixed += 1;
1054 continue;
1055 }
1056
1057 if let Some(ref ext_id) = task.external_id {
1058 let status = task_status_to_backend_status(task.status);
1059 if let Err(e) = backend
1060 .update_status(&ExternalId(ext_id.clone()), status)
1061 .await
1062 {
1063 eprintln!(" fix failed for #{}: {}", f.task_id, e);
1064 skipped += 1;
1065 } else {
1066 println!(" fixed #{}: synced labels", f.task_id);
1067 fixed += 1;
1068 }
1069 } else {
1070 skipped += 1;
1071 }
1072 }
1073 FixAction::ResetToRouted { store_id } => {
1074 if dry_run {
1075 println!(
1076 " {}would reset #{} to 'routed' (re-dispatch on next tick)",
1077 prefix, f.task_id
1078 );
1079 fixed += 1;
1080 continue;
1081 }
1082
1083 if let Err(e) = store.update_status(*store_id, TaskStatus::Routed).await {
1084 eprintln!(" fix failed for #{}: {}", f.task_id, e);
1085 skipped += 1;
1086 continue;
1087 }
1088
1089 let task = store.get(*store_id).await?;
1091 if let Some(ref ext_id) = task.external_id {
1092 let _ = backend
1093 .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Routed)
1094 .await;
1095 }
1096 println!(" fixed #{}: reset to routed", f.task_id);
1097 fixed += 1;
1098 }
1099 FixAction::CleanWorktree { store_id } => {
1100 let task = store.get(*store_id).await?;
1101
1102 if dry_run {
1103 println!(
1104 " {}would clean worktree + mark cleaned for #{}",
1105 prefix, f.task_id
1106 );
1107 fixed += 1;
1108 continue;
1109 }
1110
1111 let wt = Path::new(&task.worktree);
1112 if wt.exists() {
1113 match resolve_repo_root(repo).await {
1114 Ok(root) => {
1115 let branch = if task.branch.is_empty() {
1116 None
1117 } else {
1118 Some(task.branch.as_str())
1119 };
1120 let removed = remove_worktree_and_branch(
1121 &f.task_id,
1122 wt,
1123 branch,
1124 Path::new(&root),
1125 task.pr_number.is_some(), )
1127 .await;
1128 if removed {
1129 let _ = store.mark_cleaned(*store_id).await;
1130 println!(" fixed #{}: cleaned worktree", f.task_id);
1131 fixed += 1;
1132 } else {
1133 eprintln!(
1134 " fix failed for #{}: worktree removal failed",
1135 f.task_id
1136 );
1137 skipped += 1;
1138 }
1139 }
1140 Err(e) => {
1141 eprintln!(
1142 " fix failed for #{}: cannot resolve repo root: {}",
1143 f.task_id, e
1144 );
1145 skipped += 1;
1146 }
1147 }
1148 } else {
1149 let _ = store.mark_cleaned(*store_id).await;
1151 println!(
1152 " fixed #{}: marked worktree cleaned (already gone)",
1153 f.task_id
1154 );
1155 fixed += 1;
1156 }
1157 }
1158 FixAction::RemoveOrphanedWorktree { path } => {
1159 if dry_run {
1160 println!(" {}would remove orphaned worktree: {}", prefix, path);
1161 fixed += 1;
1162 continue;
1163 }
1164
1165 let removed = cleanup_orphaned_worktree(&f.task_id, Path::new(path)).await;
1166 if removed {
1167 println!(" fixed: removed orphaned worktree {}", path);
1168 fixed += 1;
1169 } else {
1170 eprintln!(" fix failed: could not remove orphaned worktree {}", path);
1171 skipped += 1;
1172 }
1173 }
1174 FixAction::MarkDoneFromMergedPr { store_id } => {
1175 let task = store.get(*store_id).await?;
1176
1177 if dry_run {
1178 println!(
1179 " {}would mark #{} done + close issue + clean worktree",
1180 prefix, f.task_id
1181 );
1182 fixed += 1;
1183 continue;
1184 }
1185
1186 if let Err(e) = store.update_status(*store_id, TaskStatus::Done).await {
1188 eprintln!(" fix failed for #{}: {}", f.task_id, e);
1189 skipped += 1;
1190 continue;
1191 }
1192
1193 if let Some(ref ext_id) = task.external_id {
1195 let _ = backend
1196 .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Done)
1197 .await;
1198 }
1199
1200 if !task.worktree.is_empty() && !task.worktree_cleaned {
1202 let wt = Path::new(&task.worktree);
1203 if wt.exists() {
1204 if let Ok(root) = resolve_repo_root(repo).await {
1205 let branch = if task.branch.is_empty() {
1206 None
1207 } else {
1208 Some(task.branch.as_str())
1209 };
1210 let removed = remove_worktree_and_branch(
1211 &f.task_id,
1212 wt,
1213 branch,
1214 Path::new(&root),
1215 true, )
1217 .await;
1218 if removed {
1219 let _ = store.mark_cleaned(*store_id).await;
1220 }
1221 }
1222 } else {
1223 let _ = store.mark_cleaned(*store_id).await;
1224 }
1225 }
1226
1227 println!(" fixed #{}: marked done + closed issue", f.task_id);
1228 fixed += 1;
1229 }
1230 FixAction::ResetDeadReview { store_id } => {
1231 if dry_run {
1232 println!(" {}would set #{} needs_review", prefix, f.task_id);
1233 fixed += 1;
1234 continue;
1235 }
1236
1237 if let Err(e) = store
1238 .update_status(*store_id, TaskStatus::NeedsReview)
1239 .await
1240 {
1241 eprintln!(" fix failed for #{}: {}", f.task_id, e);
1242 skipped += 1;
1243 continue;
1244 }
1245
1246 let task = store.get(*store_id).await?;
1248 if let Some(ref ext_id) = task.external_id {
1249 let _ = backend
1250 .update_status(
1251 &ExternalId(ext_id.clone()),
1252 crate::backends::Status::NeedsReview,
1253 )
1254 .await;
1255 }
1256 println!(
1257 " fixed #{}: reset dead review session + set needs_review",
1258 f.task_id
1259 );
1260 fixed += 1;
1261 }
1262 }
1263 }
1264
1265 let action = if dry_run { "would fix" } else { "fixed" };
1266 println!("\n{} {}, skipped {}.", action, fixed, skipped);
1267
1268 if !dry_run && skipped > 0 {
1269 println!("Reported issues with no automatic fix need a new issue or task.");
1270 }
1271
1272 Ok(())
1273}
1274
1275fn task_label(task: &Task) -> String {
1276 match &task.external_id {
1277 Some(id) => id.clone(),
1278 None => format!("internal:{}", task.id),
1279 }
1280}
1281
1282fn task_status_to_backend_status(status: TaskStatus) -> crate::backends::Status {
1283 match status {
1284 TaskStatus::New => crate::backends::Status::New,
1285 TaskStatus::Routed => crate::backends::Status::Routed,
1286 TaskStatus::InProgress => crate::backends::Status::InProgress,
1287 TaskStatus::Done => crate::backends::Status::Done,
1288 TaskStatus::Blocked => crate::backends::Status::Blocked,
1289 TaskStatus::InReview => crate::backends::Status::InReview,
1290 TaskStatus::Approved => crate::backends::Status::Approved,
1291 TaskStatus::NeedsReview => crate::backends::Status::NeedsReview,
1292 TaskStatus::Waiting => crate::backends::Status::Waiting,
1293 }
1294}
1295
1296fn collect_valid_external_issue_numbers<'a>(
1297 tasks: impl IntoIterator<Item = &'a Task>,
1298 repo: &str,
1299 caller_context: &str,
1300) -> Vec<u64> {
1301 let mut issue_numbers = Vec::new();
1302
1303 for task in tasks {
1304 let Some(external_id) = task.external_id.as_deref() else {
1305 continue;
1306 };
1307
1308 match external_id.parse::<u64>() {
1309 Ok(0) => {
1310 tracing::warn!(
1311 repo,
1312 caller_context,
1313 store_id = task.id,
1314 external_id,
1315 "dropping invalid external_id before batch issue-state query"
1316 );
1317 }
1318 Ok(issue_number) => issue_numbers.push(issue_number),
1319 Err(error) => {
1320 tracing::warn!(
1321 repo,
1322 caller_context,
1323 store_id = task.id,
1324 external_id,
1325 error = %error,
1326 "skipping non-numeric external_id in batch issue-state query"
1327 );
1328 }
1329 }
1330 }
1331
1332 issue_numbers.sort_unstable();
1333 issue_numbers.dedup();
1334 issue_numbers
1335}
1336
1337#[cfg(test)]
1338mod tests {
1339 use super::collect_valid_external_issue_numbers;
1340 use crate::store::{Task, TaskStatus};
1341
1342 fn task(id: i64, external_id: Option<&str>, origin: &str) -> Task {
1343 Task {
1344 id,
1345 external_id: external_id.map(ToOwned::to_owned),
1346 repo: "owner/repo".to_string(),
1347 origin: origin.to_string(),
1348 title: String::new(),
1349 body: String::new(),
1350 status: TaskStatus::New,
1351 source: String::new(),
1352 source_id: String::new(),
1353 author: String::new(),
1354 url: String::new(),
1355 labels: Vec::new(),
1356 agent: None,
1357 model: None,
1358 complexity: String::new(),
1359 estimate: 0,
1360 route_reason: String::new(),
1361 agent_profile: String::new(),
1362 selected_skills: String::new(),
1363 route_attempts: 0,
1364 attempts: 0,
1365 branch: String::new(),
1366 worktree: String::new(),
1367 worktree_cleaned: false,
1368 owner_node: None,
1369 summary: String::new(),
1370 last_error: String::new(),
1371 parent_id: None,
1372 block_reason: None,
1373 pr_number: None,
1374 pr_review_context: String::new(),
1375 last_review_ts: String::new(),
1376 review_ts_map: String::new(),
1377 last_comment_review_ts: String::new(),
1378 merge_conflict_retries: 0,
1379 ci_merge_failures: 0,
1380 pr_create_failures: 0,
1381 push_failures: 0,
1382 network_retries: 0,
1383 review_agent_failures: 0,
1384 review_resets: 0,
1385 review_cycles: 0,
1386 review_invocations: 0,
1387 needs_review_refires: 0,
1388 input_tokens: 0,
1389 output_tokens: 0,
1390 input_cost_usd: 0.0,
1391 output_cost_usd: 0.0,
1392 total_cost_usd: 0.0,
1393 model_reroute_chain: String::new(),
1394 limit_reroute_chain: String::new(),
1395 memory: Vec::new(),
1396 delegations: Vec::new(),
1397 auto_unblock_count: 0,
1398 auto_unblock_last_at: String::new(),
1399 auto_unblock_last_reason: String::new(),
1400 ci_recovery_count: 0,
1401 no_code_reroutes: 0,
1402 no_code_last_agent: String::new(),
1403 created_at: String::new(),
1404 updated_at: String::new(),
1405 }
1406 }
1407
1408 #[test]
1409 fn collect_valid_external_issue_numbers_filters_zero_and_non_numeric_ids() {
1410 let tasks = [
1411 task(1, Some("42"), "github"),
1412 task(2, Some("0"), "github"),
1413 task(3, Some("not-a-number"), "github"),
1414 task(4, Some("42"), "github"),
1415 ];
1416
1417 let issue_numbers =
1418 collect_valid_external_issue_numbers(tasks.iter(), "owner/repo", "test");
1419
1420 assert_eq!(issue_numbers, vec![42]);
1421 }
1422}
1423
1424#[cfg(test)]
1425mod done_is_terminal_tests {
1426 use super::*;
1427 use crate::backends::test_helpers::NoopBackend;
1428 use crate::store::{NewTask, TaskStore};
1429
1430 fn git(dir: &Path, args: &[&str]) {
1431 let ok = std::process::Command::new("git")
1432 .args(args)
1433 .current_dir(dir)
1434 .env("GIT_AUTHOR_NAME", "t")
1435 .env("GIT_AUTHOR_EMAIL", "t@example.com")
1436 .env("GIT_COMMITTER_NAME", "t")
1437 .env("GIT_COMMITTER_EMAIL", "t@example.com")
1438 .output()
1439 .expect("git runs")
1440 .status
1441 .success();
1442 assert!(ok, "git {args:?} failed");
1443 }
1444
1445 #[tokio::test]
1448 async fn fix_leaves_done_task_status_alone() {
1449 let dir = tempfile::tempdir().unwrap();
1450 let wt = dir.path();
1451 git(wt, &["init", "-b", "main"]);
1452 std::fs::write(wt.join("a.txt"), "a").unwrap();
1453 git(wt, &["add", "-A"]);
1454 git(wt, &["commit", "-m", "init"]);
1455 std::fs::write(wt.join("b.txt"), "b").unwrap();
1457
1458 let store = Arc::new(TaskStore::open_memory().await.unwrap());
1459 let store_id = store
1460 .create(&NewTask {
1461 external_id: Some("58".to_string()),
1462 repo: "owner/repo".to_string(),
1463 origin: "github".to_string(),
1464 title: "Task".to_string(),
1465 body: String::new(),
1466 source: "cron".to_string(),
1467 source_id: "code-development".to_string(),
1468 author: "bot".to_string(),
1469 url: String::new(),
1470 labels: vec![],
1471 parent_id: None,
1472 })
1473 .await
1474 .unwrap();
1475 store
1476 .set_fields(
1477 store_id,
1478 &[
1479 ("worktree", serde_json::json!(wt.display().to_string())),
1480 ("branch", serde_json::json!("main")),
1481 ],
1482 )
1483 .await
1484 .unwrap();
1485 store
1486 .update_status(store_id, TaskStatus::Done)
1487 .await
1488 .unwrap();
1489 let task = store.get(store_id).await.unwrap();
1490
1491 let mut findings = Vec::new();
1492 check_dirty_worktree(&task, &mut findings).await;
1493 check_unpushed_commits(&task, &mut findings).await;
1494 assert!(
1495 !findings.is_empty(),
1496 "a done task with uncommitted work must still be reported"
1497 );
1498 for f in &findings {
1499 assert!(
1500 matches!(f.fix, FixAction::None),
1501 "done-task finding must carry no automatic fix: {}",
1502 f.message
1503 );
1504 }
1505
1506 let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1507 let gh = GhHttp::new().unwrap();
1508 apply_fixes(&findings, &store, "owner/repo", &backend, &gh, false)
1509 .await
1510 .unwrap();
1511
1512 assert_eq!(
1513 store.get(store_id).await.unwrap().status,
1514 TaskStatus::Done,
1515 "doctor --fix must not move a done task out of done"
1516 );
1517 }
1518}