orch-cli 0.91.1

Orch, the agent orchestration engine: runs coding agents on tasks and cron jobs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
use crate::backends::github::GitHubBackend;
use crate::backends::{ExternalBackend, ExternalId};
use crate::config;
use crate::engine::cleanup::{
    cleanup_orphaned_worktree, remove_worktree_and_branch, resolve_repo_root,
};
use crate::github::http::GhHttp;
use crate::store::{Task, TaskStatus, TaskStore};
use crate::tmux::TmuxManager;
use std::io::Write;
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

/// What kind of automatic repair can be applied to a finding.
///
/// Nothing here moves a done task out of done. Done is terminal, so a done task
/// that looks wrong is reported and left alone (#3780)
enum FixAction {
    /// PR exists but pr_number not recorded — link it in the store.
    LinkPr { store_id: i64, pr_number: u64 },
    /// GitHub issue is closed but task is not done — reopen issue, sync labels.
    ReopenIssue { store_id: i64 },
    /// Task is done but GitHub issue still open — close issue.
    CloseIssue { store_id: i64 },
    /// GitHub label doesn't match SQLite status — sync labels.
    SyncLabels { store_id: i64 },
    /// Stale in_progress — no tmux session — reset to routed.
    ResetToRouted { store_id: i64 },
    /// Done task with uncleaned worktree that has no uncommitted/unpushed work.
    CleanWorktree { store_id: i64 },
    /// Orphaned worktree with no owning task — remove directory.
    RemoveOrphanedWorktree { path: String },
    /// PR merged but task not done — set done, close issue, clean worktree.
    MarkDoneFromMergedPr { store_id: i64 },
    /// Dead review session — reset to needs_review.
    ResetDeadReview { store_id: i64 },
    /// No automatic fix possible.
    None,
}

/// A single diagnostic finding from `orch service doctor`.
struct Finding {
    severity: Severity,
    task_id: String,
    message: String,
    fix: FixAction,
}

#[derive(Clone, Copy)]
enum Severity {
    Error,
    Warning,
}

impl Severity {
    fn symbol(self) -> &'static str {
        match self {
            Self::Error => "ERR",
            Self::Warning => "WARN",
        }
    }
}

/// Run all diagnostic checks and print findings.
///
/// When called outside a project directory (no `.orch.yml`), runs across all
/// repos found in the store. When called inside a project, scopes to that repo.
pub async fn run(full: bool, fix: bool, dry_run: bool) -> anyhow::Result<()> {
    let store = Arc::new(crate::cli::init_store().await?);
    let gh = GhHttp::new()?;
    let tmux = TmuxManager::new();

    // Resolve repos to check: current project if available, otherwise all repos in store.
    let repos: Vec<String> = match config::get_current_repo() {
        Ok(repo) => vec![repo],
        Err(_) => {
            let all = store.distinct_repos().await?;
            if all.is_empty() {
                println!("No tasks found in store.");
                return Ok(());
            }
            all
        }
    };

    // Spinner: show progress on stderr while checks run (erase with \r on done).
    let spinner_running = Arc::new(AtomicBool::new(true));
    let spinner_flag = spinner_running.clone();
    let spinner_task = tokio::spawn(async move {
        let frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
        let mut i = 0usize;
        while spinner_flag.load(Ordering::Relaxed) {
            eprint!(
                "\r{} Running orch service doctor…",
                frames[i % frames.len()]
            );
            let _ = std::io::stderr().flush();
            tokio::time::sleep(std::time::Duration::from_millis(80)).await;
            i += 1;
        }
        eprint!("\r");
        let _ = std::io::stderr().flush();
    });

    let result = run_checks(full, fix, dry_run, &repos, &store, &gh, &tmux).await;

    spinner_running.store(false, Ordering::Relaxed);
    let _ = spinner_task.await;

    result
}

async fn run_checks(
    full: bool,
    fix: bool,
    dry_run: bool,
    repos: &[String],
    store: &Arc<TaskStore>,
    gh: &GhHttp,
    tmux: &TmuxManager,
) -> anyhow::Result<()> {
    let mut all_findings: Vec<Finding> = Vec::new();

    for repo in repos {
        let backend: Arc<dyn ExternalBackend> = Arc::new(GitHubBackend::new(repo.clone())?);
        let mut findings: Vec<Finding> = Vec::new();
        if full {
            // Existing expensive path: load active + recent done tasks and batch GraphQL queries.
            // Only load active tasks + done tasks from the last 7 days — avoids
            // fetching hundreds of historical done tasks on every run.
            let cutoff = chrono::Utc::now() - chrono::Duration::days(7);
            let cutoff_str = cutoff.format("%Y-%m-%dT%H:%M:%SZ").to_string();
            let all_tasks = store.list_for_doctor(repo, &cutoff_str).await?;

            let recent_done_tasks: Vec<_> = all_tasks
                .iter()
                .filter(|t| t.status == TaskStatus::Done)
                .collect();
            let active_tasks: Vec<_> = all_tasks
                .iter()
                .filter(|t| t.status != TaskStatus::Done)
                .collect();
            let in_progress_tasks: Vec<_> = all_tasks
                .iter()
                .filter(|t| t.status == TaskStatus::InProgress)
                .collect();
            let in_review_tasks: Vec<_> = all_tasks
                .iter()
                .filter(|t| t.status == TaskStatus::InReview)
                .collect();

            // Batch-fetch all PR states needed for checks 1 and 8 in a single GraphQL call.
            let pr_numbers_to_fetch: Vec<u64> = {
                let mut nums: Vec<u64> = recent_done_tasks
                    .iter()
                    .filter(|t| !(t.origin == "internal" && t.external_id.is_none()))
                    .filter_map(|t| t.pr_number.map(|n| n as u64))
                    .chain(
                        active_tasks
                            .iter()
                            .filter_map(|t| t.pr_number.map(|n| n as u64)),
                    )
                    .collect();
                nums.sort_unstable();
                nums.dedup();
                nums
            };
            let pr_states = gh
                .batch_get_pr_states(repo, &pr_numbers_to_fetch)
                .await
                .unwrap_or_default();

            // 1. Done tasks with no merged PR (recent only — skip internal no-PR tasks)
            for task in &recent_done_tasks {
                if task.origin == "internal" && task.external_id.is_none() {
                    continue;
                }
                if task.pr_number.is_none() && task.external_id.is_none() {
                    continue;
                }
                check_done_no_merged_pr(task, gh, &pr_states, &mut findings, repo).await;
            }

            // 2. Done tasks with dirty worktrees (recent only — filesystem check, fast)
            for task in &recent_done_tasks {
                check_dirty_worktree(task, &mut findings).await;
            }

            // 3. Done tasks with unpushed commits (recent only — filesystem check, fast)
            for task in &recent_done_tasks {
                check_unpushed_commits(task, &mut findings).await;
            }

            // 4+5. Issue status and label checks (active external tasks only).
            // Batch-fetch all issue states and labels in a single GraphQL call.
            let external_active: Vec<_> = active_tasks
                .iter()
                .copied()
                .filter(|t| t.origin != "internal")
                .collect();
            let issue_numbers = collect_valid_external_issue_numbers(
                external_active.iter().copied(),
                repo,
                "cli::doctor::run_checks(full)",
            );
            let issue_states = gh
                .batch_get_issue_states(repo, &issue_numbers, "cli::doctor::run_checks(full)")
                .await
                .unwrap_or_default();
            for task in &external_active {
                check_issue_status_mismatch(task, &issue_states, &mut findings);
                check_label_mismatch(task, &issue_states, &mut findings);
            }

            // 6. Stale in_progress tasks (no tmux session)
            for task in &in_progress_tasks {
                check_stale_in_progress(task, repo, tmux, &mut findings).await;
            }

            // 7. Orphaned worktrees (needs all tasks to match worktree paths to owners)
            check_orphaned_worktrees(&all_tasks, &mut findings).await;

            // 8. PR merged but task not done (active tasks only — uses batched pr_states)
            for task in &active_tasks {
                check_pr_merged_not_done(task, &pr_states, &mut findings);
            }

            // 9. Dead review sessions
            for task in &in_review_tasks {
                check_dead_review_session(task, repo, tmux, &mut findings).await;
            }
        } else {
            // Fast path: only consider active (non-done) tasks and open PRs via REST.
            let active_tasks = store.list_active(repo).await?;

            // Fetch open PRs for the repo (paginated REST call)
            let open_prs: Vec<serde_json::Value> =
                gh.list_open_pulls(repo).await.unwrap_or_default();

            // Build lookup maps: pr_number -> pr, head_ref -> pr
            let mut pr_by_number: std::collections::HashMap<u64, serde_json::Value> =
                std::collections::HashMap::new();
            let mut pr_by_head: std::collections::HashMap<String, serde_json::Value> =
                std::collections::HashMap::new();
            for pr in &open_prs {
                if let Some(n) = pr.get("number").and_then(|v| v.as_u64()) {
                    pr_by_number.insert(n, pr.clone());
                }
                if let Some(head) = pr.pointer("/head/ref").and_then(|v| v.as_str()) {
                    pr_by_head.insert(head.to_string(), pr.clone());
                }
            }

            // Active tasks: perform lightweight checks
            let external_active: Vec<_> = active_tasks
                .iter()
                .filter(|t| t.origin != "internal")
                .collect();
            for task in &active_tasks {
                // Stale in_progress
                if task.status == TaskStatus::InProgress {
                    check_stale_in_progress(task, repo, tmux, &mut findings).await;
                }

                // Dead review sessions
                if task.status == TaskStatus::InReview {
                    check_dead_review_session(task, repo, tmux, &mut findings).await;
                }

                // PR merged check for tasks that have a PR recorded — make one REST call per active task (few)
                if let Some(pr_num) = task.pr_number {
                    match gh.get_pr(repo, pr_num as u64).await {
                        Ok(pr) => {
                            if pr.merged.unwrap_or(false) {
                                findings.push(Finding {
                                    severity: Severity::Error,
                                    task_id: task_label(task),
                                    message: format!(
                                        "PR #{} is merged but task status is '{}'",
                                        pr_num,
                                        task.status.as_str()
                                    ),
                                    fix: FixAction::MarkDoneFromMergedPr { store_id: task.id },
                                });
                            }
                        }
                        Err(_) => {
                            // Ignore transient failures in fast path; the full path will surface them.
                        }
                    }
                } else if !task.branch.is_empty() {
                    // If task has a branch, check if there's an open PR for it
                    if let Some(pr) = pr_by_head.get(&task.branch) {
                        // PR exists and is open — link PR (warning) unless already linked
                        if task.pr_number.is_none() {
                            if let Some(n) = pr.get("number").and_then(|v| v.as_u64()) {
                                findings.push(Finding {
                                    severity: Severity::Warning,
                                    task_id: task_label(task),
                                    message: format!(
                                        "branch '{}' has open PR #{} not linked in store",
                                        task.branch, n
                                    ),
                                    fix: FixAction::LinkPr {
                                        store_id: task.id,
                                        pr_number: n,
                                    },
                                });
                            }
                        }
                    }
                }
            }

            // Batch issue state/label checks for external active tasks
            let external_issue_numbers = collect_valid_external_issue_numbers(
                external_active.iter().copied(),
                repo,
                "cli::doctor::run_checks(fast)",
            );
            let issue_states = gh
                .batch_get_issue_states(
                    repo,
                    &external_issue_numbers,
                    "cli::doctor::run_checks(fast)",
                )
                .await
                .unwrap_or_default();
            for task in &external_active {
                check_issue_status_mismatch(task, &issue_states, &mut findings);
                check_label_mismatch(task, &issue_states, &mut findings);
            }

            // Orphaned PRs: open PRs that don't match any active task by number or head ref
            for pr in &open_prs {
                let pr_num = pr.get("number").and_then(|v| v.as_u64());
                let head = pr
                    .pointer("/head/ref")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string());
                let mut owned = false;
                if let Some(n) = pr_num {
                    for t in &active_tasks {
                        if let Some(pn) = t.pr_number {
                            if pn as u64 == n {
                                owned = true;
                                break;
                            }
                        }
                        if !t.branch.is_empty() && Some(t.branch.clone()) == head {
                            owned = true;
                            break;
                        }
                    }
                }
                if !owned {
                    let num_str = pr_num
                        .map(|n| n.to_string())
                        .unwrap_or_else(|| "?".to_string());
                    findings.push(Finding {
                        severity: Severity::Warning,
                        task_id: format!("pr:{}", num_str),
                        message: format!("open PR with no active task: #{}", num_str),
                        fix: FixAction::None,
                    });
                }
            }

            // Orphaned worktrees relative to active tasks only
            check_orphaned_worktrees(&active_tasks, &mut findings).await;
        }

        if repos.len() > 1 && !findings.is_empty() {
            println!("\n=== {} ===", repo);
        }

        // Apply per-repo fixes immediately so store_id lookups are in scope.
        if (fix || dry_run) && !findings.is_empty() {
            let errors = findings
                .iter()
                .filter(|f| matches!(f.severity, Severity::Error))
                .count();
            let warnings = findings.len() - errors;
            for f in &findings {
                println!("[{}] #{}: {}", f.severity.symbol(), f.task_id, f.message);
            }
            println!(
                "\nFound {} issue(s): {} error(s), {} warning(s)",
                findings.len(),
                errors,
                warnings,
            );
            apply_fixes(&findings, store, repo, &backend, gh, dry_run).await?;
        }

        all_findings.extend(findings);
    }

    if all_findings.is_empty() {
        println!("No issues found. All task state is consistent.");
        return Ok(());
    }

    // If we didn't already print+fix per-repo above (non-fix mode), print summary now.
    if !fix && !dry_run {
        let errors = all_findings
            .iter()
            .filter(|f| matches!(f.severity, Severity::Error))
            .count();
        let warnings = all_findings.len() - errors;

        for f in &all_findings {
            println!("[{}] #{}: {}", f.severity.symbol(), f.task_id, f.message);
        }

        println!(
            "\nFound {} issue(s): {} error(s), {} warning(s)",
            all_findings.len(),
            errors,
            warnings,
        );

        if errors > 0 {
            println!("\nRun `orch service doctor --fix` to attempt automatic repairs.");
            println!("Run `orch service doctor --dry-run` to preview what --fix would do.");
        }
    }

    Ok(())
}

/// Check 1: Done task with no merged PR.
/// `pr_states` is a pre-fetched cache of pr_number → (merged, state).
async fn check_done_no_merged_pr(
    task: &Task,
    gh: &GhHttp,
    pr_states: &std::collections::HashMap<u64, (bool, String)>,
    findings: &mut Vec<Finding>,
    repo: &str,
) {
    let task_label = task_label(task);
    let store_id = task.id;

    match task.pr_number {
        Some(pr_num) => {
            // Use cached state; fall back to live fetch if missing (e.g. new PR since batch)
            let (merged, state) = if let Some(s) = pr_states.get(&(pr_num as u64)) {
                s.clone()
            } else {
                match gh.get_pr(repo, pr_num as u64).await {
                    Ok(pr) => (pr.merged.unwrap_or(false), pr.state),
                    Err(e) => {
                        findings.push(Finding {
                            severity: Severity::Warning,
                            task_id: task_label,
                            message: format!(
                                "done with PR #{} but failed to fetch PR: {}",
                                pr_num, e
                            ),
                            fix: FixAction::None,
                        });
                        return;
                    }
                }
            };
            if !merged {
                findings.push(Finding {
                    severity: Severity::Error,
                    task_id: task_label,
                    message: format!(
                        "done but PR #{} is {} (not merged) — done is terminal, file a new task to finish the work",
                        pr_num, state
                    ),
                    fix: FixAction::None,
                });
            }
        }
        None => {
            // No PR recorded — check if branch has a PR
            if !task.branch.is_empty() {
                match gh.get_pr_number(repo, &task.branch).await {
                    Ok(Some(pr_num)) => {
                        // PR exists on GitHub but not linked — check merge state
                        let merged = gh
                            .get_pr(repo, pr_num)
                            .await
                            .map(|pr| pr.merged == Some(true))
                            .unwrap_or(false);
                        if merged {
                            // PR is merged — just link it
                            findings.push(Finding {
                                severity: Severity::Warning,
                                task_id: task_label,
                                message: format!(
                                    "done with no pr_number but branch has merged PR #{}",
                                    pr_num
                                ),
                                fix: FixAction::LinkPr {
                                    store_id,
                                    pr_number: pr_num,
                                },
                            });
                        } else {
                            // PR not merged — shouldn't be done
                            findings.push(Finding {
                                severity: Severity::Error,
                                task_id: task_label,
                                message: format!(
                                    "done with no pr_number but branch has unmerged PR #{} — done is terminal, file a new task to finish the work",
                                    pr_num
                                ),
                                fix: FixAction::None,
                            });
                        }
                    }
                    Ok(None) => {
                        findings.push(Finding {
                            severity: Severity::Error,
                            task_id: task_label,
                            message: describe_unrecovered_work(task).await,
                            fix: FixAction::None,
                        });
                    }
                    Err(_) => {
                        findings.push(Finding {
                            severity: Severity::Error,
                            task_id: task_label,
                            message: "done but no PR number recorded and branch lookup failed"
                                .to_string(),
                            fix: FixAction::None,
                        });
                    }
                }
            } else {
                findings.push(Finding {
                    severity: Severity::Error,
                    task_id: task_label,
                    message: "done but no branch or PR recorded".to_string(),
                    fix: FixAction::None,
                });
            }
        }
    }
}

/// Describe what a done task with no PR left behind in its worktree.
///
/// Report only: the status stays done, so the message tells the operator what
/// work is sitting there and would otherwise be lost (#3780)
async fn describe_unrecovered_work(task: &Task) -> String {
    const HEAD: &str = "done but no PR was ever created";
    if task.worktree.is_empty() || task.worktree_cleaned {
        return format!("{HEAD} and the worktree is gone — any work is lost");
    }
    let wt = Path::new(&task.worktree);
    if !wt.exists() || !wt.join(".git").exists() {
        return format!("{HEAD} and the worktree is gone — any work is lost");
    }

    // Check for dirty files
    let has_dirty = tokio::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(wt)
        .output()
        .await
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false);

    if has_dirty {
        return format!("{HEAD}; uncommitted changes left in {}", task.worktree);
    }

    // Check for unpushed commits
    let has_unpushed = tokio::process::Command::new("git")
        .args(["log", &format!("origin/{}..HEAD", task.branch), "--oneline"])
        .current_dir(wt)
        .output()
        .await
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false);

    if has_unpushed {
        return format!("{HEAD}; unpushed commits left in {}", task.worktree);
    }

    // Branch pushed, no PR
    let branch_on_remote = tokio::process::Command::new("git")
        .args(["ls-remote", "--heads", "origin", &task.branch])
        .current_dir(wt)
        .output()
        .await
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false);

    if branch_on_remote {
        return format!("{HEAD}; branch '{}' is pushed with no PR", task.branch);
    }

    HEAD.to_string()
}

/// Check 2: Done task with dirty worktree (uncommitted changes).
async fn check_dirty_worktree(task: &Task, findings: &mut Vec<Finding>) {
    if task.worktree.is_empty() || task.worktree_cleaned {
        return;
    }
    let wt = Path::new(&task.worktree);
    if !wt.exists() || !wt.join(".git").exists() {
        return;
    }
    let output = tokio::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(wt)
        .output()
        .await;
    if let Ok(out) = output {
        if !out.stdout.is_empty() {
            findings.push(Finding {
                severity: Severity::Error,
                task_id: task_label(task),
                message: format!(
                    "done but worktree has uncommitted changes: {} — done is terminal, file a new task to land them",
                    task.worktree
                ),
                fix: FixAction::None,
            });
        }
    }
}

/// Check 3: Done task with unpushed commits.
async fn check_unpushed_commits(task: &Task, findings: &mut Vec<Finding>) {
    if task.worktree.is_empty() || task.worktree_cleaned || task.branch.is_empty() {
        return;
    }
    let wt = Path::new(&task.worktree);
    if !wt.exists() || !wt.join(".git").exists() {
        return;
    }
    let output = tokio::process::Command::new("git")
        .args(["log", &format!("origin/{}..HEAD", task.branch), "--oneline"])
        .current_dir(wt)
        .output()
        .await;
    if let Ok(out) = output {
        if !out.stdout.is_empty() {
            let count = out.stdout.iter().filter(|&&b| b == b'\n').count();
            findings.push(Finding {
                severity: Severity::Error,
                task_id: task_label(task),
                message: format!(
                    "done but {} unpushed commit(s) in worktree: {} — done is terminal, file a new task to land them",
                    count, task.worktree
                ),
                fix: FixAction::None,
            });
        }
    }
}

/// Check 4: Closed GitHub issue with non-done SQLite status (and vice versa).
fn check_issue_status_mismatch(
    task: &Task,
    issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
    findings: &mut Vec<Finding>,
) {
    let ext_id = match &task.external_id {
        Some(id) => id.clone(),
        None => return,
    };

    let (state, _labels) = match issue_states.get(&ext_id) {
        Some(v) => v,
        None => return,
    };

    let issue_closed = state == "closed";
    let task_done = task.status == TaskStatus::Done;
    let task_blocked = task.status == TaskStatus::Blocked;

    if issue_closed && !task_done && !task_blocked {
        findings.push(Finding {
            severity: Severity::Error,
            task_id: task_label(task),
            message: format!(
                "GitHub issue is closed but SQLite status is '{}'",
                task.status.as_str()
            ),
            fix: FixAction::ReopenIssue { store_id: task.id },
        });
    } else if !issue_closed && task_done {
        findings.push(Finding {
            severity: Severity::Warning,
            task_id: task_label(task),
            message: "SQLite status is 'done' but GitHub issue is still open".to_string(),
            fix: FixAction::CloseIssue { store_id: task.id },
        });
    }
}

/// Check 5: Label/status mismatch.
fn check_label_mismatch(
    task: &Task,
    issue_states: &std::collections::HashMap<String, (String, Vec<String>)>,
    findings: &mut Vec<Finding>,
) {
    let ext_id = match &task.external_id {
        Some(id) => id.clone(),
        None => return,
    };

    let (_state, labels) = match issue_states.get(&ext_id) {
        Some(v) => v,
        None => return,
    };

    let expected_label = format!("status:{}", task.status.as_str());
    let has_expected = labels.iter().any(|l| l == &expected_label);
    let status_labels: Vec<_> = labels.iter().filter(|l| l.starts_with("status:")).collect();

    if !has_expected {
        let actual = if status_labels.is_empty() {
            "none".to_string()
        } else {
            status_labels
                .iter()
                .map(|s| s.as_str())
                .collect::<Vec<_>>()
                .join(", ")
        };
        findings.push(Finding {
            severity: Severity::Warning,
            task_id: task_label(task),
            message: format!(
                "label mismatch: SQLite='{}' but GitHub labels=[{}]",
                task.status.as_str(),
                actual
            ),
            fix: FixAction::SyncLabels { store_id: task.id },
        });
    }
}

/// Check 6: Stale in_progress task (no tmux session).
async fn check_stale_in_progress(
    task: &Task,
    repo: &str,
    tmux: &TmuxManager,
    findings: &mut Vec<Finding>,
) {
    let task_id_str = match &task.external_id {
        Some(id) => id.clone(),
        None => format!("internal:{}", task.id),
    };
    let session = tmux.session_name(repo, &task_id_str);
    if !tmux.session_exists(&session).await {
        findings.push(Finding {
            severity: Severity::Error,
            task_id: task_label(task),
            message: format!(
                "status is 'in_progress' but no tmux session '{}' found",
                session
            ),
            fix: FixAction::ResetToRouted { store_id: task.id },
        });
    }
}

/// Check 7: Orphaned worktrees.
async fn check_orphaned_worktrees(all_tasks: &[Task], findings: &mut Vec<Finding>) {
    let worktrees_dir = match crate::home::worktrees_dir() {
        Ok(d) => d,
        Err(_) => return,
    };

    let project_dirs = match std::fs::read_dir(&worktrees_dir) {
        Ok(d) => d,
        Err(_) => return,
    };

    // Build a HashMap for O(1) worktree-path → task lookups instead of O(T) linear scan.
    let task_by_worktree: std::collections::HashMap<&str, &Task> = all_tasks
        .iter()
        .filter(|t| !t.worktree.is_empty())
        .map(|t| (t.worktree.as_str(), t))
        .collect();

    for project_entry in project_dirs {
        let project_entry = match project_entry {
            Ok(e) => e,
            Err(e) => {
                tracing::warn!(err = %e, "error reading worktrees directory entry");
                continue;
            }
        };
        if !project_entry
            .file_type()
            .map(|t| t.is_dir())
            .unwrap_or(false)
        {
            continue;
        }
        let branch_dirs = match std::fs::read_dir(project_entry.path()) {
            Ok(d) => d,
            Err(_) => continue,
        };
        for branch_entry in branch_dirs {
            let branch_entry = match branch_entry {
                Ok(e) => e,
                Err(e) => {
                    tracing::warn!(err = %e, "error reading project directory entry");
                    continue;
                }
            };
            if !branch_entry
                .file_type()
                .map(|t| t.is_dir())
                .unwrap_or(false)
            {
                continue;
            }
            let wt_path = branch_entry.path().to_string_lossy().to_string();

            let owning_task = task_by_worktree.get(wt_path.as_str()).copied();

            match owning_task {
                Some(task) => {
                    if task.status == TaskStatus::Done && !task.worktree_cleaned {
                        // Check if worktree has uncommitted/unpushed work
                        let has_work = worktree_has_work(Path::new(&wt_path), &task.branch).await;
                        if has_work {
                            // Don't auto-clean — there's work to save
                            findings.push(Finding {
                                severity: Severity::Warning,
                                task_id: task_label(task),
                                message: format!("done but worktree has unsaved work: {}", wt_path),
                                fix: FixAction::None,
                            });
                        } else {
                            findings.push(Finding {
                                severity: Severity::Warning,
                                task_id: task_label(task),
                                message: format!("done but worktree not cleaned up: {}", wt_path),
                                fix: FixAction::CleanWorktree { store_id: task.id },
                            });
                        }
                    }
                }
                None => {
                    findings.push(Finding {
                        severity: Severity::Warning,
                        task_id: "?".to_string(),
                        message: format!("orphaned worktree (no task owns it): {}", wt_path),
                        fix: FixAction::RemoveOrphanedWorktree {
                            path: wt_path.clone(),
                        },
                    });
                }
            }
        }
    }
}

/// Check 8: PR merged but task not done (uses pre-fetched pr_states cache).
fn check_pr_merged_not_done(
    task: &Task,
    pr_states: &std::collections::HashMap<u64, (bool, String)>,
    findings: &mut Vec<Finding>,
) {
    let pr_num = match task.pr_number {
        Some(n) => n as u64,
        None => return,
    };

    if let Some((merged, _)) = pr_states.get(&pr_num) {
        if *merged {
            findings.push(Finding {
                severity: Severity::Error,
                task_id: task_label(task),
                message: format!(
                    "PR #{} is merged but task status is '{}'",
                    pr_num,
                    task.status.as_str()
                ),
                fix: FixAction::MarkDoneFromMergedPr { store_id: task.id },
            });
        }
    }
}

/// Check 9: Dead review sessions.
async fn check_dead_review_session(
    task: &Task,
    repo: &str,
    tmux: &TmuxManager,
    findings: &mut Vec<Finding>,
) {
    if !task.review_session_expected {
        return;
    }
    let task_id_str = match &task.external_id {
        Some(id) => id.clone(),
        None => format!("internal:{}", task.id),
    };
    let review_task_id = format!("{}-review", task_id_str);
    let session = tmux.session_name(repo, &review_task_id);
    if !tmux.session_exists(&session).await {
        findings.push(Finding {
            severity: Severity::Error,
            task_id: task_label(task),
            message: format!(
                "status is 'in_review' with review_session_expected but no review session '{}' found",
                session
            ),
            fix: FixAction::ResetDeadReview { store_id: task.id },
        });
    }
}

/// Check if a worktree has uncommitted changes or unpushed commits.
async fn worktree_has_work(wt: &Path, branch: &str) -> bool {
    if !wt.join(".git").exists() {
        return false;
    }
    let has_dirty = tokio::process::Command::new("git")
        .args(["status", "--porcelain"])
        .current_dir(wt)
        .output()
        .await
        .map(|o| !o.stdout.is_empty())
        .unwrap_or(false);
    if has_dirty {
        return true;
    }
    if !branch.is_empty() {
        let has_unpushed = tokio::process::Command::new("git")
            .args(["log", &format!("origin/{}..HEAD", branch), "--oneline"])
            .current_dir(wt)
            .output()
            .await
            .map(|o| !o.stdout.is_empty())
            .unwrap_or(false);
        if has_unpushed {
            return true;
        }
    }
    false
}

/// Attempt automatic fixes for known issues.
async fn apply_fixes(
    findings: &[Finding],
    store: &Arc<TaskStore>,
    repo: &str,
    backend: &Arc<dyn ExternalBackend>,
    gh: &GhHttp,
    dry_run: bool,
) -> anyhow::Result<()> {
    let prefix = if dry_run { "[dry-run] " } else { "" };
    let mut fixed = 0;
    let mut skipped = 0;

    for f in findings {
        match &f.fix {
            FixAction::None => {
                skipped += 1;
                continue;
            }
            FixAction::LinkPr {
                store_id,
                pr_number,
            } => {
                if dry_run {
                    println!(
                        "  {}would link PR #{} to task #{}",
                        prefix, pr_number, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                let _ = store
                    .set_fields(
                        *store_id,
                        &[("pr_number", serde_json::json!(*pr_number as i64))],
                    )
                    .await;
                println!("  fixed #{}: linked PR #{}", f.task_id, pr_number);
                fixed += 1;
            }
            FixAction::ReopenIssue { store_id } => {
                let task = store.get(*store_id).await?;

                if dry_run {
                    println!(
                        "  {}would reopen GitHub issue + sync labels for #{}",
                        prefix, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                if let Some(ref ext_id) = task.external_id {
                    if let Err(e) = gh.reopen_issue(repo, ext_id).await {
                        eprintln!("  fix failed for #{}: reopen failed: {}", f.task_id, e);
                        skipped += 1;
                        continue;
                    }
                    let status = task_status_to_backend_status(task.status);
                    let _ = backend
                        .update_status(&ExternalId(ext_id.clone()), status)
                        .await;
                    println!("  fixed #{}: reopened issue + synced labels", f.task_id);
                    fixed += 1;
                } else {
                    skipped += 1;
                }
            }
            FixAction::CloseIssue { store_id } => {
                let task = store.get(*store_id).await?;

                if dry_run {
                    println!("  {}would close GitHub issue #{}", prefix, f.task_id);
                    fixed += 1;
                    continue;
                }

                if let Some(ref ext_id) = task.external_id {
                    let status = crate::backends::Status::Done;
                    if let Err(e) = backend
                        .update_status(&ExternalId(ext_id.clone()), status)
                        .await
                    {
                        eprintln!("  fix failed for #{}: {}", f.task_id, e);
                        skipped += 1;
                    } else {
                        println!("  fixed #{}: closed GitHub issue", f.task_id);
                        fixed += 1;
                    }
                } else {
                    skipped += 1;
                }
            }
            FixAction::SyncLabels { store_id } => {
                let task = store.get(*store_id).await?;

                if dry_run {
                    println!(
                        "  {}would sync labels to status:{} for #{}",
                        prefix,
                        task.status.as_str(),
                        f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                if let Some(ref ext_id) = task.external_id {
                    let status = task_status_to_backend_status(task.status);
                    if let Err(e) = backend
                        .update_status(&ExternalId(ext_id.clone()), status)
                        .await
                    {
                        eprintln!("  fix failed for #{}: {}", f.task_id, e);
                        skipped += 1;
                    } else {
                        println!("  fixed #{}: synced labels", f.task_id);
                        fixed += 1;
                    }
                } else {
                    skipped += 1;
                }
            }
            FixAction::ResetToRouted { store_id } => {
                if dry_run {
                    println!(
                        "  {}would reset #{} to 'routed' (re-dispatch on next tick)",
                        prefix, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                if let Err(e) = store.update_status(*store_id, TaskStatus::Routed).await {
                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
                    skipped += 1;
                    continue;
                }

                // Sync labels if external
                let task = store.get(*store_id).await?;
                if let Some(ref ext_id) = task.external_id {
                    let _ = backend
                        .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Routed)
                        .await;
                }
                println!("  fixed #{}: reset to routed", f.task_id);
                fixed += 1;
            }
            FixAction::CleanWorktree { store_id } => {
                let task = store.get(*store_id).await?;

                if dry_run {
                    println!(
                        "  {}would clean worktree + mark cleaned for #{}",
                        prefix, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                let wt = Path::new(&task.worktree);
                if wt.exists() {
                    match resolve_repo_root(repo).await {
                        Ok(root) => {
                            let branch = if task.branch.is_empty() {
                                None
                            } else {
                                Some(task.branch.as_str())
                            };
                            let removed = remove_worktree_and_branch(
                                &f.task_id,
                                wt,
                                branch,
                                Path::new(&root),
                                task.pr_number.is_some(), // keep remote branch if PR exists
                            )
                            .await;
                            if removed {
                                let _ = store.mark_cleaned(*store_id).await;
                                println!("  fixed #{}: cleaned worktree", f.task_id);
                                fixed += 1;
                            } else {
                                eprintln!(
                                    "  fix failed for #{}: worktree removal failed",
                                    f.task_id
                                );
                                skipped += 1;
                            }
                        }
                        Err(e) => {
                            eprintln!(
                                "  fix failed for #{}: cannot resolve repo root: {}",
                                f.task_id, e
                            );
                            skipped += 1;
                        }
                    }
                } else {
                    // Directory already gone — just mark cleaned
                    let _ = store.mark_cleaned(*store_id).await;
                    println!(
                        "  fixed #{}: marked worktree cleaned (already gone)",
                        f.task_id
                    );
                    fixed += 1;
                }
            }
            FixAction::RemoveOrphanedWorktree { path } => {
                if dry_run {
                    println!("  {}would remove orphaned worktree: {}", prefix, path);
                    fixed += 1;
                    continue;
                }

                let removed = cleanup_orphaned_worktree(&f.task_id, Path::new(path)).await;
                if removed {
                    println!("  fixed: removed orphaned worktree {}", path);
                    fixed += 1;
                } else {
                    eprintln!("  fix failed: could not remove orphaned worktree {}", path);
                    skipped += 1;
                }
            }
            FixAction::MarkDoneFromMergedPr { store_id } => {
                let task = store.get(*store_id).await?;

                if dry_run {
                    println!(
                        "  {}would mark #{} done + close issue + clean worktree",
                        prefix, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                // Set status to done
                if let Err(e) = store.update_status(*store_id, TaskStatus::Done).await {
                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
                    skipped += 1;
                    continue;
                }

                // Close GitHub issue + sync labels
                if let Some(ref ext_id) = task.external_id {
                    let _ = backend
                        .update_status(&ExternalId(ext_id.clone()), crate::backends::Status::Done)
                        .await;
                }

                // Clean worktree if present
                if !task.worktree.is_empty() && !task.worktree_cleaned {
                    let wt = Path::new(&task.worktree);
                    if wt.exists() {
                        if let Ok(root) = resolve_repo_root(repo).await {
                            let branch = if task.branch.is_empty() {
                                None
                            } else {
                                Some(task.branch.as_str())
                            };
                            let removed = remove_worktree_and_branch(
                                &f.task_id,
                                wt,
                                branch,
                                Path::new(&root),
                                true, // keep remote — PR is merged
                            )
                            .await;
                            if removed {
                                let _ = store.mark_cleaned(*store_id).await;
                            }
                        }
                    } else {
                        let _ = store.mark_cleaned(*store_id).await;
                    }
                }

                println!("  fixed #{}: marked done + closed issue", f.task_id);
                fixed += 1;
            }
            FixAction::ResetDeadReview { store_id } => {
                if dry_run {
                    println!(
                        "  {}would reset #{} review_session_expected=0 + set needs_review",
                        prefix, f.task_id
                    );
                    fixed += 1;
                    continue;
                }

                // Reset review_session_expected and set status to needs_review
                let _ = store
                    .set_fields(
                        *store_id,
                        &[("review_session_expected", serde_json::json!(false))],
                    )
                    .await;
                if let Err(e) = store
                    .update_status(*store_id, TaskStatus::NeedsReview)
                    .await
                {
                    eprintln!("  fix failed for #{}: {}", f.task_id, e);
                    skipped += 1;
                    continue;
                }

                // Sync labels
                let task = store.get(*store_id).await?;
                if let Some(ref ext_id) = task.external_id {
                    let _ = backend
                        .update_status(
                            &ExternalId(ext_id.clone()),
                            crate::backends::Status::NeedsReview,
                        )
                        .await;
                }
                println!(
                    "  fixed #{}: reset review session + set needs_review",
                    f.task_id
                );
                fixed += 1;
            }
        }
    }

    let action = if dry_run { "would fix" } else { "fixed" };
    println!("\n{} {}, skipped {}.", action, fixed, skipped);

    if !dry_run && skipped > 0 {
        println!("Reported issues with no automatic fix need a new issue or task.");
    }

    Ok(())
}

fn task_label(task: &Task) -> String {
    match &task.external_id {
        Some(id) => id.clone(),
        None => format!("internal:{}", task.id),
    }
}

fn task_status_to_backend_status(status: TaskStatus) -> crate::backends::Status {
    match status {
        TaskStatus::New => crate::backends::Status::New,
        TaskStatus::Routed => crate::backends::Status::Routed,
        TaskStatus::InProgress => crate::backends::Status::InProgress,
        TaskStatus::Done => crate::backends::Status::Done,
        TaskStatus::Blocked => crate::backends::Status::Blocked,
        TaskStatus::InReview => crate::backends::Status::InReview,
        TaskStatus::NeedsReview => crate::backends::Status::NeedsReview,
        TaskStatus::Waiting => crate::backends::Status::Waiting,
    }
}

fn collect_valid_external_issue_numbers<'a>(
    tasks: impl IntoIterator<Item = &'a Task>,
    repo: &str,
    caller_context: &str,
) -> Vec<u64> {
    let mut issue_numbers = Vec::new();

    for task in tasks {
        let Some(external_id) = task.external_id.as_deref() else {
            continue;
        };

        match external_id.parse::<u64>() {
            Ok(0) => {
                tracing::warn!(
                    repo,
                    caller_context,
                    store_id = task.id,
                    external_id,
                    "dropping invalid external_id before batch issue-state query"
                );
            }
            Ok(issue_number) => issue_numbers.push(issue_number),
            Err(error) => {
                tracing::warn!(
                    repo,
                    caller_context,
                    store_id = task.id,
                    external_id,
                    error = %error,
                    "skipping non-numeric external_id in batch issue-state query"
                );
            }
        }
    }

    issue_numbers.sort_unstable();
    issue_numbers.dedup();
    issue_numbers
}

#[cfg(test)]
mod tests {
    use super::collect_valid_external_issue_numbers;
    use crate::store::{Task, TaskStatus};

    fn task(id: i64, external_id: Option<&str>, origin: &str) -> Task {
        Task {
            id,
            external_id: external_id.map(ToOwned::to_owned),
            repo: "owner/repo".to_string(),
            origin: origin.to_string(),
            title: String::new(),
            body: String::new(),
            status: TaskStatus::New,
            source: String::new(),
            source_id: String::new(),
            author: String::new(),
            url: String::new(),
            labels: Vec::new(),
            agent: None,
            model: None,
            complexity: String::new(),
            estimate: 0,
            route_reason: String::new(),
            agent_profile: String::new(),
            selected_skills: String::new(),
            route_attempts: 0,
            attempts: 0,
            branch: String::new(),
            worktree: String::new(),
            worktree_cleaned: false,
            summary: String::new(),
            last_error: String::new(),
            parent_id: None,
            block_reason: None,
            pr_number: None,
            pr_review_context: String::new(),
            last_review_ts: String::new(),
            review_ts_map: String::new(),
            last_comment_review_ts: String::new(),
            merge_conflict_retries: 0,
            ci_merge_failures: 0,
            pr_create_failures: 0,
            push_failures: 0,
            network_retries: 0,
            review_agent_failures: 0,
            review_cycles: 0,
            review_invocations: 0,
            review_session_expected: false,
            needs_review_refires: 0,
            input_tokens: 0,
            output_tokens: 0,
            input_cost_usd: 0.0,
            output_cost_usd: 0.0,
            total_cost_usd: 0.0,
            model_reroute_chain: String::new(),
            limit_reroute_chain: String::new(),
            memory: Vec::new(),
            delegations: Vec::new(),
            auto_unblock_count: 0,
            auto_unblock_last_at: String::new(),
            auto_unblock_last_reason: String::new(),
            ci_recovery_count: 0,
            no_code_reroutes: 0,
            no_code_last_agent: String::new(),
            created_at: String::new(),
            updated_at: String::new(),
        }
    }

    #[test]
    fn collect_valid_external_issue_numbers_filters_zero_and_non_numeric_ids() {
        let tasks = [
            task(1, Some("42"), "github"),
            task(2, Some("0"), "github"),
            task(3, Some("not-a-number"), "github"),
            task(4, Some("42"), "github"),
        ];

        let issue_numbers =
            collect_valid_external_issue_numbers(tasks.iter(), "owner/repo", "test");

        assert_eq!(issue_numbers, vec![42]);
    }
}

#[cfg(test)]
mod done_is_terminal_tests {
    use super::*;
    use crate::backends::test_helpers::NoopBackend;
    use crate::store::{NewTask, TaskStore};

    fn git(dir: &Path, args: &[&str]) {
        let ok = std::process::Command::new("git")
            .args(args)
            .current_dir(dir)
            .env("GIT_AUTHOR_NAME", "t")
            .env("GIT_AUTHOR_EMAIL", "t@example.com")
            .env("GIT_COMMITTER_NAME", "t")
            .env("GIT_COMMITTER_EMAIL", "t@example.com")
            .output()
            .expect("git runs")
            .status
            .success();
        assert!(ok, "git {args:?} failed");
    }

    /// `doctor --fix` must leave a done task done, even when its worktree still
    /// holds uncommitted work. Follow-up work gets a new task (#3780).
    #[tokio::test]
    async fn fix_leaves_done_task_status_alone() {
        let dir = tempfile::tempdir().unwrap();
        let wt = dir.path();
        git(wt, &["init", "-b", "main"]);
        std::fs::write(wt.join("a.txt"), "a").unwrap();
        git(wt, &["add", "-A"]);
        git(wt, &["commit", "-m", "init"]);
        // Uncommitted change — the state that used to trigger commit + push + needs_review.
        std::fs::write(wt.join("b.txt"), "b").unwrap();

        let store = Arc::new(TaskStore::open_memory().await.unwrap());
        let store_id = store
            .create(&NewTask {
                external_id: Some("58".to_string()),
                repo: "owner/repo".to_string(),
                origin: "github".to_string(),
                title: "Task".to_string(),
                body: String::new(),
                source: "cron".to_string(),
                source_id: "code-development".to_string(),
                author: "bot".to_string(),
                url: String::new(),
                labels: vec![],
                parent_id: None,
            })
            .await
            .unwrap();
        store
            .set_fields(
                store_id,
                &[
                    ("worktree", serde_json::json!(wt.display().to_string())),
                    ("branch", serde_json::json!("main")),
                ],
            )
            .await
            .unwrap();
        store
            .update_status(store_id, TaskStatus::Done)
            .await
            .unwrap();
        let task = store.get(store_id).await.unwrap();

        let mut findings = Vec::new();
        check_dirty_worktree(&task, &mut findings).await;
        check_unpushed_commits(&task, &mut findings).await;
        assert!(
            !findings.is_empty(),
            "a done task with uncommitted work must still be reported"
        );
        for f in &findings {
            assert!(
                matches!(f.fix, FixAction::None),
                "done-task finding must carry no automatic fix: {}",
                f.message
            );
        }

        let backend: Arc<dyn ExternalBackend> = Arc::new(NoopBackend);
        let gh = GhHttp::new().unwrap();
        apply_fixes(&findings, &store, "owner/repo", &backend, &gh, false)
            .await
            .unwrap();

        assert_eq!(
            store.get(store_id).await.unwrap().status,
            TaskStatus::Done,
            "doctor --fix must not move a done task out of done"
        );
    }
}