Skip to main content

orch/cli/
doctor.rs

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
15/// What kind of automatic repair can be applied to a finding.
16///
17/// Nothing here moves a done task out of done. Done is terminal, so a done task
18/// that looks wrong is reported and left alone (#3780)
19enum FixAction {
20    /// PR exists but pr_number not recorded — link it in the store.
21    LinkPr { store_id: i64, pr_number: u64 },
22    /// GitHub issue is closed but task is not done — reopen issue, sync labels.
23    ReopenIssue { store_id: i64 },
24    /// Task is done but GitHub issue still open — close issue.
25    CloseIssue { store_id: i64 },
26    /// GitHub label doesn't match SQLite status — sync labels.
27    SyncLabels { store_id: i64 },
28    /// Stale in_progress — no tmux session — reset to routed.
29    ResetToRouted { store_id: i64 },
30    /// Done task with uncleaned worktree that has no uncommitted/unpushed work.
31    CleanWorktree { store_id: i64 },
32    /// Orphaned worktree with no owning task — remove directory.
33    RemoveOrphanedWorktree { path: String },
34    /// PR merged but task not done — set done, close issue, clean worktree.
35    MarkDoneFromMergedPr { store_id: i64 },
36    /// Dead review session — reset to needs_review.
37    ResetDeadReview { store_id: i64 },
38    /// No automatic fix possible.
39    None,
40}
41
42/// A single diagnostic finding from `orch service doctor`.
43struct 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
65/// Run all diagnostic checks and print findings.
66///
67/// When called outside a project directory (no `.orch.yml`), runs across all
68/// repos found in the store. When called inside a project, scopes to that repo.
69pub 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    // Resolve repos to check: current project if available, otherwise all repos in store.
75    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    // Spinner: show progress on stderr while checks run (erase with \r on done).
88    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            // Existing expensive path: load active + recent done tasks and batch GraphQL queries.
130            // Only load active tasks + done tasks from the last 7 days — avoids
131            // fetching hundreds of historical done tasks on every run.
132            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            // Batch-fetch all PR states needed for checks 1 and 8 in a single GraphQL call.
154            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            // 1. Done tasks with no merged PR (recent only — skip internal no-PR tasks)
175            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            // 2. Done tasks with dirty worktrees (recent only — filesystem check, fast)
186            for task in &recent_done_tasks {
187                check_dirty_worktree(task, &mut findings).await;
188            }
189
190            // 3. Done tasks with unpushed commits (recent only — filesystem check, fast)
191            for task in &recent_done_tasks {
192                check_unpushed_commits(task, &mut findings).await;
193            }
194
195            // 4+5. Issue status and label checks (active external tasks only).
196            // Batch-fetch all issue states and labels in a single GraphQL call.
197            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            // 6. Stale in_progress tasks (no tmux session)
217            for task in &in_progress_tasks {
218                check_stale_in_progress(task, repo, tmux, &mut findings).await;
219            }
220
221            // 7. Orphaned worktrees (needs all tasks to match worktree paths to owners)
222            check_orphaned_worktrees(&all_tasks, &mut findings).await;
223
224            // 8. PR merged but task not done (active tasks only — uses batched pr_states)
225            for task in &active_tasks {
226                check_pr_merged_not_done(task, &pr_states, &mut findings);
227            }
228
229            // 9. Dead review sessions
230            for task in &in_review_tasks {
231                check_dead_review_session(task, repo, tmux, &mut findings).await;
232            }
233        } else {
234            // Fast path: only consider active (non-done) tasks and open PRs via REST.
235            let active_tasks = store.list_active(repo).await?;
236
237            // Fetch open PRs for the repo (paginated REST call)
238            let open_prs: Vec<serde_json::Value> =
239                gh.list_open_pulls(repo).await.unwrap_or_default();
240
241            // Build lookup maps: pr_number -> pr, head_ref -> pr
242            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            // Active tasks: perform lightweight checks
256            let external_active: Vec<_> = active_tasks
257                .iter()
258                .filter(|t| t.origin != "internal")
259                .collect();
260            for task in &active_tasks {
261                // Stale in_progress
262                if task.status == TaskStatus::InProgress {
263                    check_stale_in_progress(task, repo, tmux, &mut findings).await;
264                }
265
266                // Dead review sessions
267                if task.status == TaskStatus::InReview {
268                    check_dead_review_session(task, repo, tmux, &mut findings).await;
269                }
270
271                // PR merged check for tasks that have a PR recorded — make one REST call per active task (few)
272                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                            // Ignore transient failures in fast path; the full path will surface them.
290                        }
291                    }
292                } else if !task.branch.is_empty() {
293                    // If task has a branch, check if there's an open PR for it
294                    if let Some(pr) = pr_by_head.get(&task.branch) {
295                        // PR exists and is open — link PR (warning) unless already linked
296                        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            // Batch issue state/label checks for external active tasks
317            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            // Orphaned PRs: open PRs that don't match any active task by number or head ref
336            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            // Orphaned worktrees relative to active tasks only
371            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        // Apply per-repo fixes immediately so store_id lookups are in scope.
379        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 we didn't already print+fix per-repo above (non-fix mode), print summary now.
406    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
433/// Check 1: Done task with no merged PR.
434/// `pr_states` is a pre-fetched cache of pr_number → (merged, state).
435async 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            // Use cached state; fall back to live fetch if missing (e.g. new PR since batch)
448            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            // No PR recorded — check if branch has a PR
481            if !task.branch.is_empty() {
482                match gh.get_pr_number(repo, &task.branch).await {
483                    Ok(Some(pr_num)) => {
484                        // PR exists on GitHub but not linked — check merge state
485                        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                            // PR is merged — just link it
492                            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                            // PR not merged — shouldn't be done
506                            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
547/// Describe what a done task with no PR left behind in its worktree.
548///
549/// Report only: the status stays done, so the message tells the operator what
550/// work is sitting there and would otherwise be lost (#3780)
551async 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    // Check for dirty files
562    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    // Check for unpushed commits
575    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    // Branch pushed, no PR
588    let branch_on_remote = tokio::process::Command::new("git")
589        .args(["ls-remote", "--heads", "origin", &task.branch])
590        .current_dir(wt)
591        .output()
592        .await
593        .map(|o| !o.stdout.is_empty())
594        .unwrap_or(false);
595
596    if branch_on_remote {
597        return format!("{HEAD}; branch '{}' is pushed with no PR", task.branch);
598    }
599
600    HEAD.to_string()
601}
602
603/// Check 2: Done task with dirty worktree (uncommitted changes).
604async fn check_dirty_worktree(task: &Task, findings: &mut Vec<Finding>) {
605    if task.worktree.is_empty() || task.worktree_cleaned {
606        return;
607    }
608    let wt = Path::new(&task.worktree);
609    if !wt.exists() || !wt.join(".git").exists() {
610        return;
611    }
612    let output = tokio::process::Command::new("git")
613        .args(["status", "--porcelain"])
614        .current_dir(wt)
615        .output()
616        .await;
617    if let Ok(out) = output {
618        if !out.stdout.is_empty() {
619            findings.push(Finding {
620                severity: Severity::Error,
621                task_id: task_label(task),
622                message: format!(
623                    "done but worktree has uncommitted changes: {} — done is terminal, file a new task to land them",
624                    task.worktree
625                ),
626                fix: FixAction::None,
627            });
628        }
629    }
630}
631
632/// Check 3: Done task with unpushed commits.
633async fn check_unpushed_commits(task: &Task, findings: &mut Vec<Finding>) {
634    if task.worktree.is_empty() || task.worktree_cleaned || task.branch.is_empty() {
635        return;
636    }
637    let wt = Path::new(&task.worktree);
638    if !wt.exists() || !wt.join(".git").exists() {
639        return;
640    }
641    let output = tokio::process::Command::new("git")
642        .args(["log", &format!("origin/{}..HEAD", task.branch), "--oneline"])
643        .current_dir(wt)
644        .output()
645        .await;
646    if let Ok(out) = output {
647        if !out.stdout.is_empty() {
648            let count = out.stdout.iter().filter(|&&b| b == b'\n').count();
649            findings.push(Finding {
650                severity: Severity::Error,
651                task_id: task_label(task),
652                message: format!(
653                    "done but {} unpushed commit(s) in worktree: {} — done is terminal, file a new task to land them",
654                    count, task.worktree
655                ),
656                fix: FixAction::None,
657            });
658        }
659    }
660}
661
662/// Check 4: Closed GitHub issue with non-done SQLite status (and vice versa).
663fn check_issue_status_mismatch(
664    task: &Task,
665    issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
666    findings: &mut Vec<Finding>,
667) {
668    let ext_id = match &task.external_id {
669        Some(id) => id.clone(),
670        None => return,
671    };
672
673    let (state, _labels) = match issue_states.get(&ext_id) {
674        Some(v) => v,
675        None => return,
676    };
677
678    let issue_closed = state == "closed";
679    let task_done = task.status == TaskStatus::Done;
680    let task_blocked = task.status == TaskStatus::Blocked;
681
682    if issue_closed && !task_done && !task_blocked {
683        findings.push(Finding {
684            severity: Severity::Error,
685            task_id: task_label(task),
686            message: format!(
687                "GitHub issue is closed but SQLite status is '{}'",
688                task.status.as_str()
689            ),
690            fix: FixAction::ReopenIssue { store_id: task.id },
691        });
692    } else if !issue_closed && task_done {
693        findings.push(Finding {
694            severity: Severity::Warning,
695            task_id: task_label(task),
696            message: "SQLite status is 'done' but GitHub issue is still open".to_string(),
697            fix: FixAction::CloseIssue { store_id: task.id },
698        });
699    }
700}
701
702/// Check 5: Label/status mismatch.
703fn check_label_mismatch(
704    task: &Task,
705    issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
706    findings: &mut Vec<Finding>,
707) {
708    let ext_id = match &task.external_id {
709        Some(id) => id.clone(),
710        None => return,
711    };
712
713    let (_state, labels) = match issue_states.get(&ext_id) {
714        Some(v) => v,
715        None => return,
716    };
717
718    let expected_label = format!("status:{}", task.status.as_str());
719    let has_expected = labels.iter().any(|l| l == &expected_label);
720    let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();
721
722    if !has_expected {
723        let actual = if status_labels.is_empty() {
724            "none".to_string()
725        } else {
726            status_labels
727                .iter()
728                .map(|s| s.as_str())
729                .collect::<Vec<_>>()
730                .join(", ")
731        };
732        findings.push(Finding {
733            severity: Severity::Warning,
734            task_id: task_label(task),
735            message: format!(
736                "label mismatch: SQLite='{}' but GitHub labels=[{}]",
737                task.status.as_str(),
738                actual
739            ),
740            fix: FixAction::SyncLabels { store_id: task.id },
741        });
742    }
743}
744
745/// Check 6: Stale in_progress task (no tmux session).
746async fn check_stale_in_progress(
747    task: &Task,
748    repo: &str,
749    tmux: &TmuxManager,
750    findings: &mut Vec<Finding>,
751) {
752    let task_id_str = match &task.external_id {
753        Some(id) => id.clone(),
754        None => format!("internal:{}", task.id),
755    };
756    let session = tmux.session_name(repo, &task_id_str);
757    if !tmux.session_exists(&session).await {
758        findings.push(Finding {
759            severity: Severity::Error,
760            task_id: task_label(task),
761            message: format!(
762                "status is 'in_progress' but no tmux session '{}' found",
763                session
764            ),
765            fix: FixAction::ResetToRouted { store_id: task.id },
766        });
767    }
768}
769
770/// Check 7: Orphaned worktrees.
771async fn check_orphaned_worktrees(all_tasks: &[Task], findings: &mut Vec<Finding>) {
772    let worktrees_dir = match crate::home::worktrees_dir() {
773        Ok(d) => d,
774        Err(_) => return,
775    };
776
777    let project_dirs = match std::fs::read_dir(&worktrees_dir) {
778        Ok(d) => d,
779        Err(_) => return,
780    };
781
782    // Build a HashMap for O(1) worktree-path → task lookups instead of O(T) linear scan.
783    let task_by_worktree: std::collections::HashMap<&str, &Task> = all_tasks
784        .iter()
785        .filter(|t| !t.worktree.is_empty())
786        .map(|t| (t.worktree.as_str(), t))
787        .collect();
788
789    for project_entry in project_dirs {
790        let project_entry = match project_entry {
791            Ok(e) => e,
792            Err(e) => {
793                tracing::warn!(err = %e, "error reading worktrees directory entry");
794                continue;
795            }
796        };
797        if !project_entry
798            .file_type()
799            .map(|t| t.is_dir())
800            .unwrap_or(false)
801        {
802            continue;
803        }
804        let branch_dirs = match std::fs::read_dir(project_entry.path()) {
805            Ok(d) => d,
806            Err(_) => continue,
807        };
808        for branch_entry in branch_dirs {
809            let branch_entry = match branch_entry {
810                Ok(e) => e,
811                Err(e) => {
812                    tracing::warn!(err = %e, "error reading project directory entry");
813                    continue;
814                }
815            };
816            if !branch_entry
817                .file_type()
818                .map(|t| t.is_dir())
819                .unwrap_or(false)
820            {
821                continue;
822            }
823            let wt_path = branch_entry.path().to_string_lossy().to_string();
824
825            let owning_task = task_by_worktree.get(wt_path.as_str()).copied();
826
827            match owning_task {
828                Some(task) => {
829                    if task.status == TaskStatus::Done && !task.worktree_cleaned {
830                        // Check if worktree has uncommitted/unpushed work
831                        let has_work = worktree_has_work(Path::new(&wt_path), &task.branch).await;
832                        if has_work {
833                            // Don't auto-clean — there's work to save
834                            findings.push(Finding {
835                                severity: Severity::Warning,
836                                task_id: task_label(task),
837                                message: format!("done but worktree has unsaved work: {}", wt_path),
838                                fix: FixAction::None,
839                            });
840                        } else {
841                            findings.push(Finding {
842                                severity: Severity::Warning,
843                                task_id: task_label(task),
844                                message: format!("done but worktree not cleaned up: {}", wt_path),
845                                fix: FixAction::CleanWorktree { store_id: task.id },
846                            });
847                        }
848                    }
849                }
850                None => {
851                    findings.push(Finding {
852                        severity: Severity::Warning,
853                        task_id: "?".to_string(),
854                        message: format!("orphaned worktree (no task owns it): {}", wt_path),
855                        fix: FixAction::RemoveOrphanedWorktree {
856                            path: wt_path.clone(),
857                        },
858                    });
859                }
860            }
861        }
862    }
863}
864
865/// Check 8: PR merged but task not done (uses pre-fetched pr_states cache).
866fn check_pr_merged_not_done(
867    task: &Task,
868    pr_states: &std::collections::HashMap<u64, (bool, String)>,
869    findings: &mut Vec<Finding>,
870) {
871    let pr_num = match task.pr_number {
872        Some(n) => n as u64,
873        None => return,
874    };
875
876    if let Some((merged, _)) = pr_states.get(&pr_num) {
877        if *merged {
878            findings.push(Finding {
879                severity: Severity::Error,
880                task_id: task_label(task),
881                message: format!(
882                    "PR #{} is merged but task status is '{}'",
883                    pr_num,
884                    task.status.as_str()
885                ),
886                fix: FixAction::MarkDoneFromMergedPr { store_id: task.id },
887            });
888        }
889    }
890}
891
892/// Check 9: Dead review sessions. Callers pass only in_review tasks.
893async fn check_dead_review_session(
894    task: &Task,
895    repo: &str,
896    tmux: &TmuxManager,
897    findings: &mut Vec<Finding>,
898) {
899    let task_id_str = match &task.external_id {
900        Some(id) => id.clone(),
901        None => format!("internal:{}", task.id),
902    };
903    let review_task_id = format!("{}-review", task_id_str);
904    let session = tmux.session_name(repo, &review_task_id);
905    if !tmux.session_exists(&session).await {
906        findings.push(Finding {
907            severity: Severity::Error,
908            task_id: task_label(task),
909            message: format!(
910                "status is 'in_review' but no review session '{}' found",
911                session
912            ),
913            fix: FixAction::ResetDeadReview { store_id: task.id },
914        });
915    }
916}
917
918/// Check if a worktree has uncommitted changes or unpushed commits.
919async fn worktree_has_work(wt: &Path, branch: &str) -> bool {
920    if !wt.join(".git").exists() {
921        return false;
922    }
923    let has_dirty = tokio::process::Command::new("git")
924        .args(["status", "--porcelain"])
925        .current_dir(wt)
926        .output()
927        .await
928        .map(|o| !o.stdout.is_empty())
929        .unwrap_or(false);
930    if has_dirty {
931        return true;
932    }
933    if !branch.is_empty() {
934        let has_unpushed = tokio::process::Command::new("git")
935            .args(["log", &format!("origin/{}..HEAD", branch), "--oneline"])
936            .current_dir(wt)
937            .output()
938            .await
939            .map(|o| !o.stdout.is_empty())
940            .unwrap_or(false);
941        if has_unpushed {
942            return true;
943        }
944    }
945    false
946}
947
948/// Attempt automatic fixes for known issues.
949async fn apply_fixes(
950    findings: &[Finding],
951    store: &Arc<TaskStore>,
952    repo: &str,
953    backend: &Arc<dyn ExternalBackend>,
954    gh: &GhHttp,
955    dry_run: bool,
956) -> anyhow::Result<()> {
957    let prefix = if dry_run { "[dry-run] " } else { "" };
958    let mut fixed = 0;
959    let mut skipped = 0;
960
961    for f in findings {
962        match &f.fix {
963            FixAction::None => {
964                skipped += 1;
965                continue;
966            }
967            FixAction::LinkPr {
968                store_id,
969                pr_number,
970            } => {
971                if dry_run {
972                    println!(
973                        "  {}would link PR #{} to task #{}",
974                        prefix, pr_number, f.task_id
975                    );
976                    fixed += 1;
977                    continue;
978                }
979
980                let _ = store
981                    .set_fields(
982                        *store_id,
983                        &[("pr_number", serde_json::json!(*pr_number as i64))],
984                    )
985                    .await;
986                println!("  fixed #{}: linked PR #{}", f.task_id, pr_number);
987                fixed += 1;
988            }
989            FixAction::ReopenIssue { store_id } => {
990                let task = store.get(*store_id).await?;
991
992                if dry_run {
993                    println!(
994                        "  {}would reopen GitHub issue + sync labels for #{}",
995                        prefix, f.task_id
996                    );
997                    fixed += 1;
998                    continue;
999                }
1000
1001                if let Some(ref ext_id) = task.external_id {
1002                    if let Err(e) = gh.reopen_issue(repo, ext_id).await {
1003                        eprintln!("  fix failed for #{}: reopen failed: {}", f.task_id, e);
1004                        skipped += 1;
1005                        continue;
1006                    }
1007                    let status = task_status_to_backend_status(task.status);
1008                    let _ = backend
1009                        .update_status(&ExternalId(ext_id.clone()), status)
1010                        .await;
1011                    println!("  fixed #{}: reopened issue + synced labels", f.task_id);
1012                    fixed += 1;
1013                } else {
1014                    skipped += 1;
1015                }
1016            }
1017            FixAction::CloseIssue { store_id } => {
1018                let task = store.get(*store_id).await?;
1019
1020                if dry_run {
1021                    println!("  {}would close GitHub issue #{}", prefix, f.task_id);
1022                    fixed += 1;
1023                    continue;
1024                }
1025
1026                if let Some(ref ext_id) = task.external_id {
1027                    let status = crate::backends::Status::Done;
1028                    if let Err(e) = backend
1029                        .update_status(&ExternalId(ext_id.clone()), status)
1030                        .await
1031                    {
1032                        eprintln!("  fix failed for #{}: {}", f.task_id, e);
1033                        skipped += 1;
1034                    } else {
1035                        println!("  fixed #{}: closed GitHub issue", f.task_id);
1036                        fixed += 1;
1037                    }
1038                } else {
1039                    skipped += 1;
1040                }
1041            }
1042            FixAction::SyncLabels { store_id } => {
1043                let task = store.get(*store_id).await?;
1044
1045                if dry_run {
1046                    println!(
1047                        "  {}would sync labels to status:{} for #{}",
1048                        prefix,
1049                        task.status.as_str(),
1050                        f.task_id
1051                    );
1052                    fixed += 1;
1053                    continue;
1054                }
1055
1056                if let Some(ref ext_id) = task.external_id {
1057                    let status = task_status_to_backend_status(task.status);
1058                    if let Err(e) = backend
1059                        .update_status(&ExternalId(ext_id.clone()), status)
1060                        .await
1061                    {
1062                        eprintln!("  fix failed for #{}: {}", f.task_id, e);
1063                        skipped += 1;
1064                    } else {
1065                        println!("  fixed #{}: synced labels", f.task_id);
1066                        fixed += 1;
1067                    }
1068                } else {
1069                    skipped += 1;
1070                }
1071            }
1072            FixAction::ResetToRouted { store_id } => {
1073                if dry_run {
1074                    println!(
1075                        "  {}would reset #{} to 'routed' (re-dispatch on next tick)",
1076                        prefix, f.task_id
1077                    );
1078                    fixed += 1;
1079                    continue;
1080                }
1081
1082                if let Err(e) = store.update_status(*store_id, TaskStatus::Routed).await {
1083                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
1084                    skipped += 1;
1085                    continue;
1086                }
1087
1088                // Sync labels if external
1089                let task = store.get(*store_id).await?;
1090                if let Some(ref ext_id) = task.external_id {
1091                    let _ = backend
1092                        .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Routed)
1093                        .await;
1094                }
1095                println!("  fixed #{}: reset to routed", f.task_id);
1096                fixed += 1;
1097            }
1098            FixAction::CleanWorktree { store_id } => {
1099                let task = store.get(*store_id).await?;
1100
1101                if dry_run {
1102                    println!(
1103                        "  {}would clean worktree + mark cleaned for #{}",
1104                        prefix, f.task_id
1105                    );
1106                    fixed += 1;
1107                    continue;
1108                }
1109
1110                let wt = Path::new(&task.worktree);
1111                if wt.exists() {
1112                    match resolve_repo_root(repo).await {
1113                        Ok(root) => {
1114                            let branch = if task.branch.is_empty() {
1115                                None
1116                            } else {
1117                                Some(task.branch.as_str())
1118                            };
1119                            let removed = remove_worktree_and_branch(
1120                                &f.task_id,
1121                                wt,
1122                                branch,
1123                                Path::new(&root),
1124                                task.pr_number.is_some(), // keep remote branch if PR exists
1125                            )
1126                            .await;
1127                            if removed {
1128                                let _ = store.mark_cleaned(*store_id).await;
1129                                println!("  fixed #{}: cleaned worktree", f.task_id);
1130                                fixed += 1;
1131                            } else {
1132                                eprintln!(
1133                                    "  fix failed for #{}: worktree removal failed",
1134                                    f.task_id
1135                                );
1136                                skipped += 1;
1137                            }
1138                        }
1139                        Err(e) => {
1140                            eprintln!(
1141                                "  fix failed for #{}: cannot resolve repo root: {}",
1142                                f.task_id, e
1143                            );
1144                            skipped += 1;
1145                        }
1146                    }
1147                } else {
1148                    // Directory already gone — just mark cleaned
1149                    let _ = store.mark_cleaned(*store_id).await;
1150                    println!(
1151                        "  fixed #{}: marked worktree cleaned (already gone)",
1152                        f.task_id
1153                    );
1154                    fixed += 1;
1155                }
1156            }
1157            FixAction::RemoveOrphanedWorktree { path } => {
1158                if dry_run {
1159                    println!("  {}would remove orphaned worktree: {}", prefix, path);
1160                    fixed += 1;
1161                    continue;
1162                }
1163
1164                let removed = cleanup_orphaned_worktree(&f.task_id, Path::new(path)).await;
1165                if removed {
1166                    println!("  fixed: removed orphaned worktree {}", path);
1167                    fixed += 1;
1168                } else {
1169                    eprintln!("  fix failed: could not remove orphaned worktree {}", path);
1170                    skipped += 1;
1171                }
1172            }
1173            FixAction::MarkDoneFromMergedPr { store_id } => {
1174                let task = store.get(*store_id).await?;
1175
1176                if dry_run {
1177                    println!(
1178                        "  {}would mark #{} done + close issue + clean worktree",
1179                        prefix, f.task_id
1180                    );
1181                    fixed += 1;
1182                    continue;
1183                }
1184
1185                // Set status to done
1186                if let Err(e) = store.update_status(*store_id, TaskStatus::Done).await {
1187                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
1188                    skipped += 1;
1189                    continue;
1190                }
1191
1192                // Close GitHub issue + sync labels
1193                if let Some(ref ext_id) = task.external_id {
1194                    let _ = backend
1195                        .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Done)
1196                        .await;
1197                }
1198
1199                // Clean worktree if present
1200                if !task.worktree.is_empty() && !task.worktree_cleaned {
1201                    let wt = Path::new(&task.worktree);
1202                    if wt.exists() {
1203                        if let Ok(root) = resolve_repo_root(repo).await {
1204                            let branch = if task.branch.is_empty() {
1205                                None
1206                            } else {
1207                                Some(task.branch.as_str())
1208                            };
1209                            let removed = remove_worktree_and_branch(
1210                                &f.task_id,
1211                                wt,
1212                                branch,
1213                                Path::new(&root),
1214                                true, // keep remote — PR is merged
1215                            )
1216                            .await;
1217                            if removed {
1218                                let _ = store.mark_cleaned(*store_id).await;
1219                            }
1220                        }
1221                    } else {
1222                        let _ = store.mark_cleaned(*store_id).await;
1223                    }
1224                }
1225
1226                println!("  fixed #{}: marked done + closed issue", f.task_id);
1227                fixed += 1;
1228            }
1229            FixAction::ResetDeadReview { store_id } => {
1230                if dry_run {
1231                    println!("  {}would set #{} needs_review", prefix, f.task_id);
1232                    fixed += 1;
1233                    continue;
1234                }
1235
1236                if let Err(e) = store
1237                    .update_status(*store_id, TaskStatus::NeedsReview)
1238                    .await
1239                {
1240                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
1241                    skipped += 1;
1242                    continue;
1243                }
1244
1245                // Sync labels
1246                let task = store.get(*store_id).await?;
1247                if let Some(ref ext_id) = task.external_id {
1248                    let _ = backend
1249                        .update_status(
1250                            &ExternalId(ext_id.clone()),
1251                            crate::backends::Status::NeedsReview,
1252                        )
1253                        .await;
1254                }
1255                println!(
1256                    "  fixed #{}: reset dead review session + set needs_review",
1257                    f.task_id
1258                );
1259                fixed += 1;
1260            }
1261        }
1262    }
1263
1264    let action = if dry_run { "would fix" } else { "fixed" };
1265    println!("\n{} {}, skipped {}.", action, fixed, skipped);
1266
1267    if !dry_run && skipped > 0 {
1268        println!("Reported issues with no automatic fix need a new issue or task.");
1269    }
1270
1271    Ok(())
1272}
1273
1274fn task_label(task: &Task) -> String {
1275    match &task.external_id {
1276        Some(id) => id.clone(),
1277        None => format!("internal:{}", task.id),
1278    }
1279}
1280
1281fn task_status_to_backend_status(status: TaskStatus) -> crate::backends::Status {
1282    match status {
1283        TaskStatus::New => crate::backends::Status::New,
1284        TaskStatus::Routed => crate::backends::Status::Routed,
1285        TaskStatus::InProgress => crate::backends::Status::InProgress,
1286        TaskStatus::Done => crate::backends::Status::Done,
1287        TaskStatus::Blocked => crate::backends::Status::Blocked,
1288        TaskStatus::InReview => crate::backends::Status::InReview,
1289        TaskStatus::Approved => crate::backends::Status::Approved,
1290        TaskStatus::NeedsReview => crate::backends::Status::NeedsReview,
1291        TaskStatus::Waiting => crate::backends::Status::Waiting,
1292    }
1293}
1294
1295fn collect_valid_external_issue_numbers<'a>(
1296    tasks: impl IntoIterator<Item = &'a Task>,
1297    repo: &str,
1298    caller_context: &str,
1299) -> Vec<u64> {
1300    let mut issue_numbers = Vec::new();
1301
1302    for task in tasks {
1303        let Some(external_id) = task.external_id.as_deref() else {
1304            continue;
1305        };
1306
1307        match external_id.parse::<u64>() {
1308            Ok(0) => {
1309                tracing::warn!(
1310                    repo,
1311                    caller_context,
1312                    store_id = task.id,
1313                    external_id,
1314                    "dropping invalid external_id before batch issue-state query"
1315                );
1316            }
1317            Ok(issue_number) => issue_numbers.push(issue_number),
1318            Err(error) => {
1319                tracing::warn!(
1320                    repo,
1321                    caller_context,
1322                    store_id = task.id,
1323                    external_id,
1324                    error = %error,
1325                    "skipping non-numeric external_id in batch issue-state query"
1326                );
1327            }
1328        }
1329    }
1330
1331    issue_numbers.sort_unstable();
1332    issue_numbers.dedup();
1333    issue_numbers
1334}
1335
1336#[cfg(test)]
1337mod tests {
1338    use super::collect_valid_external_issue_numbers;
1339    use crate::store::{Task, TaskStatus};
1340
1341    fn task(id: i64, external_id: Option<&str>, origin: &str) -> Task {
1342        Task {
1343            id,
1344            external_id: external_id.map(ToOwned::to_owned),
1345            repo: "owner/repo".to_string(),
1346            origin: origin.to_string(),
1347            title: String::new(),
1348            body: String::new(),
1349            status: TaskStatus::New,
1350            source: String::new(),
1351            source_id: String::new(),
1352            author: String::new(),
1353            url: String::new(),
1354            labels: Vec::new(),
1355            agent: None,
1356            model: None,
1357            complexity: String::new(),
1358            estimate: 0,
1359            route_reason: String::new(),
1360            agent_profile: String::new(),
1361            selected_skills: String::new(),
1362            route_attempts: 0,
1363            attempts: 0,
1364            branch: String::new(),
1365            worktree: String::new(),
1366            worktree_cleaned: false,
1367            owner_node: None,
1368            summary: String::new(),
1369            last_error: String::new(),
1370            parent_id: None,
1371            block_reason: None,
1372            pr_number: None,
1373            pr_review_context: String::new(),
1374            last_review_ts: String::new(),
1375            review_ts_map: String::new(),
1376            last_comment_review_ts: String::new(),
1377            merge_conflict_retries: 0,
1378            ci_merge_failures: 0,
1379            pr_create_failures: 0,
1380            push_failures: 0,
1381            network_retries: 0,
1382            review_agent_failures: 0,
1383            review_resets: 0,
1384            review_cycles: 0,
1385            review_invocations: 0,
1386            needs_review_refires: 0,
1387            input_tokens: 0,
1388            output_tokens: 0,
1389            input_cost_usd: 0.0,
1390            output_cost_usd: 0.0,
1391            total_cost_usd: 0.0,
1392            model_reroute_chain: String::new(),
1393            limit_reroute_chain: String::new(),
1394            memory: Vec::new(),
1395            delegations: Vec::new(),
1396            auto_unblock_count: 0,
1397            auto_unblock_last_at: String::new(),
1398            auto_unblock_last_reason: String::new(),
1399            ci_recovery_count: 0,
1400            no_code_reroutes: 0,
1401            no_code_last_agent: String::new(),
1402            created_at: String::new(),
1403            updated_at: String::new(),
1404        }
1405    }
1406
1407    #[test]
1408    fn collect_valid_external_issue_numbers_filters_zero_and_non_numeric_ids() {
1409        let tasks = [
1410            task(1, Some("42"), "github"),
1411            task(2, Some("0"), "github"),
1412            task(3, Some("not-a-number"), "github"),
1413            task(4, Some("42"), "github"),
1414        ];
1415
1416        let issue_numbers =
1417            collect_valid_external_issue_numbers(tasks.iter(), "owner/repo", "test");
1418
1419        assert_eq!(issue_numbers, vec![42]);
1420    }
1421}
1422
1423#[cfg(test)]
1424mod done_is_terminal_tests {
1425    use super::*;
1426    use crate::backends::test_helpers::NoopBackend;
1427    use crate::store::{NewTask, TaskStore};
1428
1429    fn git(dir: &Path, args: &[&str]) {
1430        let ok = std::process::Command::new("git")
1431            .args(args)
1432            .current_dir(dir)
1433            .env("GIT_AUTHOR_NAME", "t")
1434            .env("GIT_AUTHOR_EMAIL", "t@example.com")
1435            .env("GIT_COMMITTER_NAME", "t")
1436            .env("GIT_COMMITTER_EMAIL", "t@example.com")
1437            .output()
1438            .expect("git runs")
1439            .status
1440            .success();
1441        assert!(ok, "git {args:?} failed");
1442    }
1443
1444    /// `doctor --fix` must leave a done task done, even when its worktree still
1445    /// holds uncommitted work. Follow-up work gets a new task (#3780).
1446    #[tokio::test]
1447    async fn fix_leaves_done_task_status_alone() {
1448        let dir = tempfile::tempdir().unwrap();
1449        let wt = dir.path();
1450        git(wt, &["init", "-b", "main"]);
1451        std::fs::write(wt.join("a.txt"), "a").unwrap();
1452        git(wt, &["add", "-A"]);
1453        git(wt, &["commit", "-m", "init"]);
1454        // Uncommitted change — the state that used to trigger commit + push + needs_review.
1455        std::fs::write(wt.join("b.txt"), "b").unwrap();
1456
1457        let store = Arc::new(TaskStore::open_memory().await.unwrap());
1458        let store_id = store
1459            .create(&NewTask {
1460                external_id: Some("58".to_string()),
1461                repo: "owner/repo".to_string(),
1462                origin: "github".to_string(),
1463                title: "Task".to_string(),
1464                body: String::new(),
1465                source: "cron".to_string(),
1466                source_id: "code-development".to_string(),
1467                author: "bot".to_string(),
1468                url: String::new(),
1469                labels: vec![],
1470                parent_id: None,
1471            })
1472            .await
1473            .unwrap();
1474        store
1475            .set_fields(
1476                store_id,
1477                &[
1478                    ("worktree", serde_json::json!(wt.display().to_string())),
1479                    ("branch", serde_json::json!("main")),
1480                ],
1481            )
1482            .await
1483            .unwrap();
1484        store
1485            .update_status(store_id, TaskStatus::Done)
1486            .await
1487            .unwrap();
1488        let task = store.get(store_id).await.unwrap();
1489
1490        let mut findings = Vec::new();
1491        check_dirty_worktree(&task, &mut findings).await;
1492        check_unpushed_commits(&task, &mut findings).await;
1493        assert!(
1494            !findings.is_empty(),
1495            "a done task with uncommitted work must still be reported"
1496        );
1497        for f in &findings {
1498            assert!(
1499                matches!(f.fix, FixAction::None),
1500                "done-task finding must carry no automatic fix: {}",
1501                f.message
1502            );
1503        }
1504
1505        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
1506        let gh = GhHttp::new().unwrap();
1507        apply_fixes(&findings, &store, "owner/repo", &backend, &gh, false)
1508            .await
1509            .unwrap();
1510
1511        assert_eq!(
1512            store.get(store_id).await.unwrap().status,
1513            TaskStatus::Done,
1514            "doctor --fix must not move a done task out of done"
1515        );
1516    }
1517}