magi-cli 0.120.0

Blind multi-agent implementation competition: N agents implement, M judges rank blind, deliberate, vote privately, winner survives double review + E2E gate
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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
//! Follow-up tasks for the findings a merged run left open.
//!
//! A run can hand off after its review budget is spent with findings still
//! open (and, with `land_approval` off, merge unattended). Those findings
//! live in the pull request body, which nobody reads after the merge. This
//! module files them as queue tasks instead, once the merge is confirmed.
//!
//! What is filed: every Major-or-above finding of the last review round, and
//! every finding of a seat whose final vote was reject (a vote carries no
//! per-finding reasoning, so the seat's Minor/Nit findings come along). Other
//! Minor/Nit findings are only listed, in the pull-request comment.
//!
//! Best-effort by construction, like `bump::after_merge`: [`after_merge`]
//! returns `()`, records every failure as a run event and never touches
//! `status`.

use anyhow::Result;

use crate::queue::{FollowUp, Queue, Source, Task};
use crate::run::{FollowupRecord, RunState};
use crate::verdict::{Finding, ReviewVote};

/// Node name carried by [`Source::Agent`] on a filed follow-up.
pub const NODE: &str = "followup";

/// A task of this generation (or deeper) does not file follow-ups of its own.
pub const MAX_FOLLOWUP_GENERATION: u32 = 2;

/// Two findings in one file this many lines apart are one defect.
const LINE_WINDOW: u32 = 5;

/// What one pass did.
#[derive(Debug, Default, PartialEq, Eq)]
pub struct Outcome {
    /// Task ids created by this pass.
    pub filed: Vec<String>,
    /// Findings selected but not filed (cap reached), as ids.
    pub capped: Vec<String>,
    /// Minor/Nit findings of the last round that were only listed.
    pub unfiled: Vec<String>,
    /// Findings not filed because another task already covers them, as
    /// `(finding id, covering task id)`. Recomputed from the queue each pass.
    pub covered: Vec<(String, String)>,
}

/// File follow-ups for a run that just merged, and comment on the pull
/// request. Never fails: problems become run events.
pub async fn after_merge(state: &mut RunState, pr_url: &str) {
    let queue = Queue::open();
    let release = state.config.graph.release_deputy_followups;
    // The deputy's tasks are settled first and again after filing, so the
    // outcome is the same whichever side got to the queue first.
    settle_deputy_tasks(state, pr_url, &queue, release);
    let outcome = if state.config.graph.file_followups {
        match file(state, pr_url, &queue) {
            Ok(o) => o,
            Err(e) => {
                state.event(NODE, format!("follow-up filing failed: {e:#}"));
                return;
            }
        }
    } else {
        Outcome::default()
    };
    if state.config.graph.file_followups && !release {
        settle_deputy_tasks(state, pr_url, &queue, false);
    }
    if outcome.filed.is_empty()
        && (state.followup_commented
            || (state.followups.is_empty()
                && outcome.covered.is_empty()
                && state.deputy_followups.is_empty()))
    {
        return;
    }
    let body = comment_body(state, &outcome);
    match crate::bump::gh_pr_comment(state, pr_url, &body).await {
        Ok(()) => state.followup_commented = true,
        Err(e) => state.event(NODE, format!("follow-up comment not posted: {e:#}")),
    }
}

/// Reason prefixes that mark a deputy task this module already judged and
/// left held. Both stop a second pass from rewriting the reason again.
const SUPERSEDED: &str = "[superseded] ";
const CAPPED: &str = "[generation cap] ";

/// A task the merge approval's deputy filed for run `run` that is still held
/// for pull request `pr_url`: the only kind [`settle_deputy_tasks`] touches.
/// Concrete identifiers only - the filer is the deputy seat of this run and
/// the hold reason names the pull request - never text similarity alone.
fn is_deputy_candidate(t: &Task, run: &str, pr_url: &str) -> bool {
    t.status == crate::queue::TaskStatus::Held
        && t.followup.is_none()
        && matches!(&t.source, Source::Agent { run: r, node }
            if r == run && node == crate::deputy::NODE)
        && t.hold_reason.as_deref().is_some_and(|r| {
            !r.starts_with(SUPERSEDED) && !r.starts_with(CAPPED) && names_pr(r, pr_url)
        })
}

/// Does deputy task `t` talk about finding `f`: its id as a word, a
/// `file:line` within [`LINE_WINDOW`] of the finding, or the finding's title
/// (normalized; contained only when long enough not to match by accident).
fn task_matches_finding(t: &Task, f: &Finding) -> bool {
    let text = format!("{}\n{}", t.title, t.instruction);
    if names_word(&text, &f.id) {
        return true;
    }
    if let (Some(file), Some(line)) = (&f.file, f.line)
        && text.match_indices(file.as_str()).any(|(i, _)| {
            text[i + file.len()..]
                .strip_prefix(':')
                .map(|r| {
                    r.chars()
                        .take_while(char::is_ascii_digit)
                        .collect::<String>()
                })
                .and_then(|d| d.parse::<u32>().ok())
                .is_some_and(|n| n.abs_diff(line) <= LINE_WINDOW)
        })
    {
        return true;
    }
    let (nt, nf) = (normalize(&t.title), normalize(&f.title));
    !nf.is_empty() && (nt == nf || (nf.split(' ').count() >= 3 && nt.contains(&nf)))
}

/// The follow-up depth of the task the run served; see [`file`].
fn parent_generation(state: &mut RunState, queue: &Queue, origin_task: Option<&str>) -> u32 {
    match state.followup_generation {
        Some(g) => g,
        None => match origin_task.map(|t| queue.get(t)) {
            Some(Ok(t)) => {
                let g = t.followup.map_or(0, |f| f.generation);
                state.followup_generation = Some(g);
                g
            }
            Some(Err(_)) => MAX_FOLLOWUP_GENERATION,
            None => 0,
        },
    }
}

/// Reconcile the follow-up tasks the merge approval's deputy filed (held,
/// reason naming this pull request) with the automatic ones, once the merge
/// is confirmed. Idempotent, and the same whichever side reached the queue
/// first:
///
/// - a deputy task that covers a finding an automatic follow-up already
///   covers (same finding, same file within [`LINE_WINDOW`] lines, or the same
///   normalized title) never runs twice: if the automatic one is queued the
///   owner's task wins and the automatic one is held with the reason, else
///   the deputy task stays held with a `[superseded]` reason. Nothing is
///   deleted;
/// - otherwise, with `release`, the task is released in the same queue write
///   that stamps it with a [`FollowUp`] (so it is released once, counts
///   toward the generation cap, and covers its findings for [`file`]);
/// - a task at the generation cap stays held with a `[generation cap]`
///   reason.
///
/// Only [`is_deputy_candidate`] tasks are touched, re-checked under the
/// queue's lock. Best-effort: failures are run events.
pub fn settle_deputy_tasks(state: &mut RunState, pr_url: &str, queue: &Queue, release: bool) {
    let tasks = queue.list();
    // The queue is the record: restore what a crash after the write lost.
    for t in &tasks {
        if t.followup.as_ref().is_some_and(|f| f.run == state.id)
            && matches!(&t.source, Source::Agent { node, .. } if node == crate::deputy::NODE)
            && !state.deputy_followups.contains(&t.id)
        {
            state.deputy_followups.push(t.id.clone());
        }
    }
    let cands: Vec<&Task> = tasks
        .iter()
        .filter(|t| is_deputy_candidate(t, &state.id, pr_url))
        .collect();
    if cands.is_empty() {
        return;
    }
    let chosen = state
        .reviews
        .last()
        .map(|r| select(r).0)
        .unwrap_or_default();
    let groups = group_findings(chosen);
    let autos: Vec<&Task> = tasks
        .iter()
        .filter(|t| {
            t.followup.as_ref().is_some_and(|f| f.run == state.id)
                && matches!(&t.source, Source::Agent { node, .. } if node == NODE)
        })
        .collect();
    let origin_task = state.origin.as_ref().and_then(|o| o.task.clone());
    let mut gen_of_parent = None;
    for cand in cands {
        // Findings the task covers, widened to whole defect groups.
        let matched: Vec<String> = groups
            .iter()
            .filter(|g| g.iter().any(|f| task_matches_finding(cand, f)))
            .flat_map(|g| g.iter().map(|f| f.id.clone()))
            .collect();
        let rivals: Vec<&&Task> = autos
            .iter()
            .filter(|a| {
                a.followup
                    .as_ref()
                    .is_some_and(|f| f.findings.iter().any(|x| matched.contains(x)))
            })
            .collect();
        if release {
            let parent_gen = *gen_of_parent
                .get_or_insert_with(|| parent_generation(state, queue, origin_task.as_deref()));
            if parent_gen >= MAX_FOLLOWUP_GENERATION {
                let why = format!(
                    "{CAPPED}generation {parent_gen} reached, not released after {pr_url} merged; was: {}",
                    cand.hold_reason.as_deref().unwrap_or_default()
                );
                mark_held(state, queue, cand, why, pr_url, "generation cap");
                continue;
            }
        }
        if !rivals.is_empty() {
            // Hold every idle rival under its claim, so the daemon cannot be
            // between reading it and starting it. Any rival that is not
            // idle, or cannot be claimed, means the automatic path owns the
            // finding and the deputy task is the one left held.
            let mut guards = Vec::new();
            let mut blocker: Option<&Task> = None;
            let takeover = format!(
                "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {pr_url}",
                cand.id
            );
            // Held by an earlier pass of this same takeover that could not
            // finish (or be rolled back): it is ours to restore on failure.
            let mut carried: Vec<String> = Vec::new();
            if release {
                for a in &rivals {
                    let ours = a.status == crate::queue::TaskStatus::Held
                        && a.hold_reason.as_deref() == Some(takeover.as_str());
                    if a.status == crate::queue::TaskStatus::Held && !ours {
                        continue;
                    }
                    match queue.claim(&a.id) {
                        Ok(g) => {
                            if ours {
                                carried.push(a.id.clone());
                            }
                            guards.push((a.id.clone(), g));
                        }
                        Err(_) => {
                            blocker = Some(a);
                            break;
                        }
                    }
                }
                if blocker.is_none() {
                    blocker = rivals.iter().map(|a| &***a).find(|a| {
                        !matches!(
                            queue.get(&a.id).map(|t| t.status),
                            Ok(crate::queue::TaskStatus::Queued | crate::queue::TaskStatus::Held)
                        )
                    });
                }
            } else {
                blocker = Some(&***rivals.first().expect("non-empty"));
            }
            if let Some(a) = blocker {
                // A hold left by an interrupted takeover is not covered by
                // the blocker: give it back before superseding the deputy.
                let mut stuck = false;
                for r in &rivals {
                    let held_by_us = queue.get(&r.id).is_ok_and(|t| {
                        t.status == crate::queue::TaskStatus::Held
                            && t.hold_reason.as_deref() == Some(takeover.as_str())
                    });
                    if !held_by_us {
                        continue;
                    }
                    let _own;
                    if !guards.iter().any(|(g, _)| g == &r.id) {
                        match queue.claim(&r.id) {
                            Ok(g) => _own = g,
                            Err(_) => {
                                stuck = true;
                                continue;
                            }
                        }
                    }
                    stuck |= !restore_takeover_hold(state, queue, &r.id, &takeover, &cand.id);
                }
                drop(guards);
                if stuck {
                    continue;
                }
                let why = format!(
                    "{SUPERSEDED}follow-up task {} ({:?}) already covers {} of {pr_url}; was: {}",
                    a.id,
                    a.status,
                    matched.join(", "),
                    cand.hold_reason.as_deref().unwrap_or_default()
                );
                mark_held(state, queue, cand, why, pr_url, "superseded");
                continue;
            }
            // The owner's task wins; the idle automatic ones are held. Only
            // when every one is confirmed held is the deputy task released.
            let mut failed: Option<String> = None;
            // What each held task looked like before, for a rollback.
            let mut done: Vec<(String, Task, String)> = Vec::new();
            for (id, _guard) in &guards {
                if carried.contains(id) {
                    continue;
                }
                let why = takeover.clone();
                let mut before: Option<Task> = None;
                let held = queue.modify(id, |t| {
                    if t.status != crate::queue::TaskStatus::Queued {
                        return false;
                    }
                    before = Some(t.clone());
                    t.hold_manual(Some(why.clone()));
                    true
                });
                match held {
                    Ok(true) => {
                        done.extend(before.map(|b| (id.clone(), b, why)));
                        state.event(
                            NODE,
                            format!(
                                "follow-up task {id} held: superseded by deputy task {}",
                                cand.id
                            ),
                        );
                    }
                    Ok(false) => {
                        failed = Some(id.clone());
                        break;
                    }
                    Err(e) => {
                        state.event(NODE, format!("could not hold follow-up {id}: {e:#}"));
                        failed = Some(id.clone());
                        break;
                    }
                }
            }
            if let Some(id) = failed {
                // Give back what was already held, still under its claim, so
                // the automatic path keeps covering every finding. Only a
                // task still carrying our hold is touched.
                let mut stuck = false;
                for tid in &carried {
                    stuck |= !restore_takeover_hold(state, queue, tid, &takeover, &cand.id);
                }
                for (tid, before, why) in done.into_iter().rev() {
                    let back = queue.modify(&tid, |t| {
                        if t.status != crate::queue::TaskStatus::Held
                            || t.hold_reason.as_deref() != Some(why.as_str())
                        {
                            return false;
                        }
                        *t = before;
                        true
                    });
                    match back {
                        Ok(true) => state.event(
                            NODE,
                            format!(
                                "follow-up task {tid} restored: deputy task {} could not take it over",
                                cand.id
                            ),
                        ),
                        Ok(false) => {}
                        Err(e) => {
                            stuck = true;
                            state.event(
                                NODE,
                                format!(
                                    "rollback of {tid} failed, deputy task {} left as a candidate for the next settle: {e:#}",
                                    cand.id
                                ),
                            );
                        }
                    }
                }
                drop(guards);
                if stuck {
                    continue;
                }
                let why = format!(
                    "{SUPERSEDED}follow-up task {id} could not be held, so it may still run for {} of {pr_url}; was: {}",
                    matched.join(", "),
                    cand.hold_reason.as_deref().unwrap_or_default()
                );
                mark_held(state, queue, cand, why, pr_url, "superseded");
                continue;
            }
        } else if !release {
            continue;
        }
        let parent_gen = gen_of_parent.expect("computed when releasing");
        let stamp = FollowUp {
            run: state.id.clone(),
            origin_task: origin_task.clone(),
            pr: pr_url.to_owned(),
            findings: matched,
            generation: parent_gen + 1,
        };
        let id = cand.id.clone();
        let run = state.id.clone();
        let result = queue.modify(&id, |t| {
            if !is_deputy_candidate(t, &run, pr_url) {
                return false;
            }
            t.release();
            t.followup = Some(stamp);
            true
        });
        match result {
            Ok(true) => {
                if !state.deputy_followups.contains(&id) {
                    state.deputy_followups.push(id.clone());
                }
                state.event(
                    NODE,
                    format!("released deputy follow-up task {id} after {pr_url} merged"),
                );
            }
            Ok(false) => {}
            Err(e) => state.event(NODE, format!("could not release deputy task {id}: {e:#}")),
        }
    }
}

/// Give a follow-up task held by an interrupted takeover back to the
/// automatic path. `false` when the write failed (the caller keeps the deputy
/// task a candidate); a task no longer carrying `takeover` is left alone.
fn restore_takeover_hold(
    state: &mut RunState,
    queue: &Queue,
    tid: &str,
    takeover: &str,
    cand_id: &str,
) -> bool {
    let back = queue.modify(tid, |t| {
        if t.status != crate::queue::TaskStatus::Held || t.hold_reason.as_deref() != Some(takeover)
        {
            return false;
        }
        // No snapshot survives a restart; an automatic follow-up is filed
        // Queued with nothing else set.
        t.status = crate::queue::TaskStatus::Queued;
        t.held_at = None;
        t.hold_reason = None;
        t.hold_source = None;
        true
    });
    match back {
        Ok(true) => {
            state.event(
                NODE,
                format!(
                    "follow-up task {tid} restored: deputy task {cand_id} could not take it over"
                ),
            );
            true
        }
        Ok(false) => true,
        Err(e) => {
            state.event(
                NODE,
                format!(
                    "rollback of {tid} failed, deputy task {cand_id} left as a candidate for the next settle: {e:#}"
                ),
            );
            false
        }
    }
}

/// Rewrite a still-candidate deputy task's hold reason, leaving it held.
fn mark_held(
    state: &mut RunState,
    queue: &Queue,
    cand: &Task,
    why: String,
    pr_url: &str,
    kind: &str,
) {
    let run = state.id.clone();
    let reason = why.clone();
    match queue.modify(&cand.id, |t| {
        if !is_deputy_candidate(t, &run, pr_url) {
            return false;
        }
        t.hold_reason = Some(reason);
        true
    }) {
        Ok(true) => state.event(
            NODE,
            format!("deputy task {} left held ({kind}): {why}", cand.id),
        ),
        Ok(false) => {}
        Err(e) => state.event(
            NODE,
            format!("could not mark deputy task {}: {e:#}", cand.id),
        ),
    }
}

/// Findings the last review round leaves to be followed up, and the ids of
/// those only listed: every Major-or-above finding, plus all findings of a
/// seat whose final vote was reject.
fn select(round: &crate::run::ReviewRound) -> (Vec<Finding>, Vec<String>) {
    let rejecters: Vec<usize> = round
        .final_votes()
        .into_iter()
        .filter(|(_, _, v)| *v == ReviewVote::Reject)
        .map(|(seat, _, _)| seat)
        .collect();
    let (mut chosen, mut unfiled) = (Vec::new(), Vec::new());
    for rec in &round.reviews {
        let rejected = rejecters.contains(&rec.reviewer);
        for f in &rec.findings {
            if f.severity.blocks() || rejected {
                chosen.push(f.clone());
            } else {
                unfiled.push(f.id.clone());
            }
        }
    }
    (chosen, unfiled)
}

/// The deterministic half of [`after_merge`]: select, group, and file into
/// `queue`. Records the event and the run's own bookkeeping; the caller
/// saves the state.
pub fn file(state: &mut RunState, pr_url: &str, queue: &Queue) -> Result<Outcome> {
    let mut out = Outcome::default();
    let Some(round) = state.reviews.last().cloned() else {
        return Ok(out);
    };
    let (chosen, unfiled) = select(&round);
    out.unfiled = unfiled;
    if chosen.is_empty() {
        return Ok(out);
    }

    let origin_task = state.origin.as_ref().and_then(|o| o.task.clone());
    // The depth recorded when the run started wins; the queue is only a
    // fallback for runs that predate it, and an unknown depth is read as
    // unbounded-until-proven-otherwise only when there is no origin task.
    let parent_gen = parent_generation(state, queue, origin_task.as_deref());
    if parent_gen >= MAX_FOLLOWUP_GENERATION {
        out.capped = chosen.iter().map(|f| f.id.clone()).collect();
        state.event(
            NODE,
            format!(
                "generation cap reached ({parent_gen}); not filing follow-ups for open finding(s): {}",
                out.capped.join(", ")
            ),
        );
        return Ok(out);
    }

    let mut done: Vec<String> = state
        .followups
        .iter()
        .flat_map(|r| r.findings.iter().cloned())
        .collect();
    for t in queue.list() {
        if let Some(f) = t.followup
            && f.run == state.id
        {
            done.extend(f.findings.iter().cloned());
            let by_deputy =
                matches!(&t.source, Source::Agent { node, .. } if node == crate::deputy::NODE);
            if !by_deputy && !state.followups.iter().any(|r| r.task == t.id) {
                state.followups.push(FollowupRecord {
                    task: t.id,
                    findings: f.findings,
                });
            }
        }
    }

    let tasks = queue.list();
    let origin_chat = state.origin_chat.clone().or_else(|| {
        let tasks = queue.list();
        let parent = origin_task
            .as_deref()
            .and_then(|id| tasks.iter().find(|t| t.id == id))?;
        crate::consult::chat_talk_of(&tasks, parent)
    });
    let mut failure = None;
    for group in group_findings(chosen) {
        let ids: Vec<String> = group.iter().map(|f| f.id.clone()).collect();
        let own = task_id(&state.id, &ids);
        let covers: Vec<Option<String>> = ids
            .iter()
            .map(|id| covering_task(&tasks, &own, &state.id, pr_url, id))
            .collect();
        if covers.iter().all(Option::is_some) {
            for (id, by) in ids.iter().zip(covers.into_iter().flatten()) {
                state.event(
                    NODE,
                    format!("not filing follow-up for {id}: already covered by task {by}"),
                );
                out.covered.push((id.clone(), by));
            }
            continue;
        }
        if ids.iter().any(|id| done.contains(id)) {
            continue;
        }
        let mut task = build_task(state, pr_url, origin_task.clone(), &group, parent_gen + 1);
        task.origin_chat = origin_chat.clone();
        match queue.create_new(&mut task) {
            Ok(created) => {
                if created {
                    out.filed.push(task.id.clone());
                }
                state.followups.push(FollowupRecord {
                    task: task.id,
                    findings: ids,
                });
            }
            Err(e) => {
                failure = Some(e);
                break;
            }
        }
    }
    if !out.filed.is_empty() {
        state.event(
            NODE,
            format!(
                "filed {} follow-up task(s): ids {}",
                out.filed.len(),
                out.filed.join(", ")
            ),
        );
    }
    if let Some(e) = failure {
        state.event(NODE, format!("follow-up filing stopped: {e:#}"));
    }
    Ok(out)
}

/// The id of a task, other than `own`, that already covers finding `id` of
/// run `run` merged as `pr_url`, whatever its status. Concrete identifiers
/// only: a follow-up of the same run listing the finding, or an instruction
/// naming both the finding id and the pull request (URL or `#<number>`).
fn covering_task(tasks: &[Task], own: &str, run: &str, pr_url: &str, id: &str) -> Option<String> {
    tasks
        .iter()
        .find(|t| {
            t.id != own
                && (t
                    .followup
                    .as_ref()
                    .is_some_and(|f| f.run == run && f.findings.iter().any(|x| x == id))
                    || (names_word(&t.instruction, id) && names_pr(&t.instruction, pr_url)))
        })
        .map(|t| t.id.clone())
}

/// ASCII only: an id is often followed directly by prose in another script
/// (`R3-1-1を修正`), which must not read as part of the id.
fn is_name_char(c: char) -> bool {
    c.is_ascii_alphanumeric() || matches!(c, '_' | '-')
}

/// `needle` in `text` with no name character on either side.
fn names_word(text: &str, needle: &str) -> bool {
    !needle.is_empty()
        && text.match_indices(needle).any(|(i, _)| {
            let before = text[..i].chars().next_back();
            let after = text[i + needle.len()..].chars().next();
            before.is_none_or(|c| !is_name_char(c)) && after.is_none_or(|c| !is_name_char(c))
        })
}

/// Does `text` name the pull request by its URL or its `#<number>` form,
/// with no further digit (or name character before `#`) so `#47` is not `#473`?
fn names_pr(text: &str, pr_url: &str) -> bool {
    let url = pr_url.trim_end_matches('/');
    let digit_after = |rest: &str| rest.chars().next().is_some_and(|c| c.is_ascii_digit());
    if !url.is_empty()
        && text
            .match_indices(url)
            .any(|(i, _)| !digit_after(&text[i + url.len()..]))
    {
        return true;
    }
    let Some(n) = url
        .rsplit('/')
        .next()
        .filter(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
    else {
        return false;
    };
    let tag = format!("#{n}");
    text.match_indices(&tag).any(|(i, _)| {
        let before = text[..i].chars().next_back();
        before.is_none_or(|c| !is_name_char(c)) && !digit_after(&text[i + tag.len()..])
    })
}

/// Group findings that are the same defect: same file with lines within
/// [`LINE_WINDOW`] of each other, or, with no file, the same normalized
/// title. Deterministic, so a re-run groups identically.
fn group_findings(mut findings: Vec<Finding>) -> Vec<Vec<Finding>> {
    findings.sort_by(|a, b| (&a.file, a.line, &a.id).cmp(&(&b.file, b.line, &b.id)));
    let mut groups: Vec<Vec<Finding>> = Vec::new();
    for f in findings {
        let hit = groups
            .iter()
            .position(|g| g.iter().any(|o| same_defect(o, &f)));
        match hit {
            Some(i) => groups[i].push(f),
            None => groups.push(vec![f]),
        }
    }
    for g in &mut groups {
        g.sort_by(|a, b| a.id.cmp(&b.id));
    }
    groups
}

fn same_defect(a: &Finding, b: &Finding) -> bool {
    match (&a.file, &b.file) {
        (Some(x), Some(y)) => {
            x == y
                && match (a.line, b.line) {
                    (Some(l), Some(m)) => l.abs_diff(m) <= LINE_WINDOW,
                    (None, None) => true,
                    _ => false,
                }
        }
        (None, None) => normalize(&a.title) == normalize(&b.title),
        _ => false,
    }
}

fn normalize(title: &str) -> String {
    title
        .to_lowercase()
        .split(|c: char| !c.is_alphanumeric())
        .filter(|w| !w.is_empty())
        .collect::<Vec<_>>()
        .join(" ")
}

/// Deterministic id: the run id plus a hash of the group's finding ids, so
/// two passes name the same task and [`Queue::create_new`] can refuse the
/// second. Ends in a `-` segment like every id, so `queue::short` works.
fn task_id(run: &str, ids: &[String]) -> String {
    let mut h: u64 = 0xcbf2_9ce4_8422_2325;
    for b in ids.join("+").bytes() {
        h ^= u64::from(b);
        h = h.wrapping_mul(0x0100_0000_01b3);
    }
    format!("{run}-f{:05x}", h & 0xf_ffff)
}

fn location(f: &Finding) -> String {
    match (&f.file, f.line) {
        (Some(p), Some(l)) => format!("{p}:{l}"),
        (Some(p), None) => p.clone(),
        _ => "(no location)".to_owned(),
    }
}

fn build_task(
    state: &RunState,
    pr_url: &str,
    origin_task: Option<String>,
    group: &[Finding],
    generation: u32,
) -> Task {
    let ids: Vec<String> = group.iter().map(|f| f.id.clone()).collect();
    let first = &group[0];
    let title = format!(
        "follow-up: {} ({})",
        crate::queue::title_from(&first.title, 80),
        location(first)
    );
    let mut s = format!(
        "This is a follow-up to a change that was already merged: run {run} merged \
         {pr_url} while the review finding(s) below were still open. Branch from the \
         current main - do not use the merged branch - and fix the defect described, \
         keeping the change small. If a finding no longer applies to current main, say so \
         and change nothing for it.\n\n\
         Merged run: {run}\nPull request: {pr_url}\n",
        run = state.id,
    );
    if let Some(t) = &origin_task {
        s.push_str(&format!("Original task: {t}\n"));
    }
    s.push_str("\n## Findings\n");
    for f in group {
        s.push_str(&format!(
            "\n### {} [{:?}] {}\n\nLocation: {}\n\n{}\n",
            f.id,
            f.severity,
            f.title,
            location(f),
            f.detail.trim()
        ));
    }
    let mut task = Task::new(
        title,
        s,
        state.repo.clone(),
        Source::Agent {
            run: state.id.clone(),
            node: NODE.to_owned(),
        },
    );
    task.id = task_id(&state.id, &ids);
    task.solo = true;
    task.followup = Some(FollowUp {
        run: state.id.clone(),
        origin_task,
        pr: pr_url.to_owned(),
        findings: ids,
        generation,
    });
    task
}

fn comment_body(state: &RunState, out: &Outcome) -> String {
    let mut s = format!(
        "<!-- magi-followup run={} -->\nThis pull request merged with review findings still open.",
        state.id
    );
    if state.followups.is_empty() {
        if !out.covered.is_empty() || state.deputy_followups.is_empty() {
            s.push_str(" Each is already covered by another task:\n");
        }
    } else {
        s.push_str(" They were filed as follow-up tasks:\n\n");
        for r in &state.followups {
            s.push_str(&format!("- `{}`: {}\n", r.task, r.findings.join(", ")));
        }
        if !out.covered.is_empty() {
            s.push_str("\nNot filed, already covered:\n");
        }
    }
    if !out.covered.is_empty() {
        s.push('\n');
    }
    for (id, by) in &out.covered {
        s.push_str(&format!("- {id}: already covered by task `{by}`\n"));
    }
    if !state.deputy_followups.is_empty() {
        s.push_str(
            "\nFollow-up tasks filed by the approval deputy and released after the merge:\n\n",
        );
        for id in &state.deputy_followups {
            s.push_str(&format!("- `{id}`\n"));
        }
    }
    if !out.unfiled.is_empty() {
        s.push_str(&format!(
            "\nMinor/nit findings that were only listed, not filed: {}\n",
            out.unfiled.join(", ")
        ));
    }
    s
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::config::Config;
    use crate::queue::Queue;
    use crate::run::ReviewRecord;
    use crate::run::{Origin, ReviewRound, RunState};
    use crate::verdict::{Finding, ReviewVote, Severity};
    use std::path::PathBuf;

    fn finding(id: &str, sev: Severity, file: &str, line: u32) -> Finding {
        Finding {
            id: id.to_owned(),
            severity: sev,
            file: Some(file.to_owned()),
            line: Some(line),
            title: format!("title {id}"),
            detail: format!("detail of {id}"),
        }
    }

    fn record(seat: usize, findings: Vec<Finding>, vote: ReviewVote) -> ReviewRecord {
        ReviewRecord {
            attempts: 0,
            reviewer: seat,
            agent: "alpha".to_owned(),
            summary: String::new(),
            findings,
            vote: Some(vote),
            failed: None,
            duration_ms: 0,
        }
    }

    fn round(reviews: Vec<ReviewRecord>) -> ReviewRound {
        ReviewRound {
            round: 3,
            head: "deadbee".to_owned(),
            verified_head: None,
            verified_at: None,
            reviews,
            e2e: Vec::new(),
            verify_retried: false,
            e2e_deferred: false,
            e2e_defer_reason: None,
            fix: None,
            blocking: 0,
            answered: 2,
            expected: 2,
            clean: false,
            progressed: false,
            vote_split: false,
            reconsideration: Vec::new(),
            verdict: None,
        }
    }

    fn merged(reviews: Vec<ReviewRecord>) -> RunState {
        let mut s = RunState::new(
            PathBuf::from("/repo"),
            "main".to_owned(),
            "abc1234".to_owned(),
            "do it".to_owned(),
            Config::default(),
        );
        s.reviews.push(round(reviews));
        s
    }

    fn two_seats() -> Vec<ReviewRecord> {
        vec![
            record(
                1,
                vec![
                    finding("R3-1-1", Severity::Major, "src/waiter.rs", 211),
                    finding("R3-1-2", Severity::Minor, "src/a.rs", 1),
                ],
                ReviewVote::Reject,
            ),
            record(
                2,
                vec![
                    finding("R3-2-1", Severity::Major, "src/waiter.rs", 213),
                    finding("R3-2-2", Severity::Nit, "src/b.rs", 9),
                ],
                ReviewVote::Approve,
            ),
        ]
    }

    #[test]
    fn one_task_per_distinct_defect_with_the_findings_in_full() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        let out = file(&mut s, "https://example.invalid/o/r/pull/9", &q).unwrap();
        // waiter.rs pair is one defect; seat 1 rejected so its Minor is filed
        // too; seat 2's Nit is only listed.
        assert_eq!(out.filed.len(), 2, "{out:?}");
        assert_eq!(out.unfiled, vec!["R3-2-2".to_owned()]);
        let tasks = q.list();
        let t = tasks
            .iter()
            .find(|t| t.followup.as_ref().unwrap().findings.len() == 2)
            .unwrap();
        assert!(t.solo);
        assert_eq!(t.followup.as_ref().unwrap().generation, 1);
        assert_eq!(
            t.source,
            Source::Agent {
                run: s.id.clone(),
                node: NODE.to_owned()
            }
        );
        for needle in [
            "R3-1-1",
            "R3-2-1",
            "src/waiter.rs:211",
            "detail of R3-2-1",
            "pull/9",
            &s.id,
            "current main",
        ] {
            assert!(
                t.instruction.contains(needle),
                "{needle}: {}",
                t.instruction
            );
        }
        assert!(
            s.events
                .iter()
                .any(|e| e.message.contains("filed 2 follow-up"))
        );
        assert_eq!(s.followups.len(), 2);
    }

    #[test]
    fn filing_twice_does_not_duplicate() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        file(&mut s, "u", &q).unwrap();
        let again = file(&mut s, "u", &q).unwrap();
        assert!(again.filed.is_empty());
        assert_eq!(q.list().len(), 2);
        // Even with the run's own record lost, the queue says what exists.
        s.followups.clear();
        let third = file(&mut s, "u", &q).unwrap();
        assert!(third.filed.is_empty());
        assert_eq!(q.list().len(), 2);
        assert_eq!(s.followups.len(), 2, "records are restored from the queue");
    }

    #[test]
    fn a_clean_merge_files_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(vec![record(
            1,
            vec![finding("R1-1-1", Severity::Minor, "a.rs", 1)],
            ReviewVote::Approve,
        )]);
        let out = file(&mut s, "u", &q).unwrap();
        assert!(out.filed.is_empty());
        assert!(q.list().is_empty());
        assert!(s.followups.is_empty());
    }

    #[test]
    fn a_failing_queue_is_an_error_event_not_a_status_change() {
        let dir = tempfile::tempdir().unwrap();
        let root = dir.path().join("queue");
        std::fs::write(&root, "not a directory").unwrap();
        let q = Queue::at(root);
        let mut s = merged(two_seats());
        s.status = crate::run::RunStatus::Merged;
        let _ = file(&mut s, "u", &q);
        assert_eq!(s.status, crate::run::RunStatus::Merged);
        assert!(
            s.events
                .iter()
                .any(|e| e.node == NODE && e.message.contains("stopped"))
        );
        assert!(s.followups.is_empty());
    }

    #[test]
    fn the_generation_cap_stops_the_chain() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut parent = Task::new(
            "p".to_owned(),
            "i".to_owned(),
            PathBuf::from("/repo"),
            Source::Human,
        );
        parent.followup = Some(FollowUp {
            run: "r0".to_owned(),
            origin_task: None,
            pr: "u".to_owned(),
            findings: vec!["R1-1-1".to_owned()],
            generation: MAX_FOLLOWUP_GENERATION,
        });
        q.put(&mut parent).unwrap();
        let mut s = merged(two_seats());
        s.origin = Some(Origin {
            by: crate::run::StartedBy::Operator,
            task: Some(parent.id.clone()),
        });
        s.origin = Some(Origin {
            by: crate::run::StartedBy::Operator,
            task: Some("gone".to_owned()),
        });
        s.followup_generation = Some(MAX_FOLLOWUP_GENERATION);
        let out = file(&mut s, "u", &q).unwrap();
        assert!(out.filed.is_empty());
        assert!(!out.capped.is_empty());
        assert_eq!(q.list().len(), 1);
        assert!(
            s.events
                .iter()
                .any(|e| e.message.contains("generation cap"))
        );
    }

    #[test]
    fn a_deeper_task_files_one_generation_further() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut parent = Task::new(
            "p".to_owned(),
            "i".to_owned(),
            PathBuf::from("/repo"),
            Source::Human,
        );
        q.put(&mut parent).unwrap();
        let mut s = merged(two_seats());
        s.origin = Some(Origin {
            by: crate::run::StartedBy::Operator,
            task: Some(parent.id.clone()),
        });
        file(&mut s, "u", &q).unwrap();
        let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
        assert_eq!(t.followup.unwrap().origin_task, Some(parent.id));
    }

    #[test]
    fn the_chat_is_inherited_from_the_run_even_when_the_parent_is_gone() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.origin = Some(Origin {
            by: crate::run::StartedBy::Operator,
            task: Some("gone".to_owned()),
        });
        s.followup_generation = Some(1);
        s.origin_chat = Some("talk-1".to_owned());
        file(&mut s, "u", &q).unwrap();
        let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
        assert_eq!(t.origin_chat.as_deref(), Some("talk-1"));
    }

    #[test]
    fn a_parent_without_the_field_passes_on_what_its_ancestry_resolves() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut parent = Task::new(
            "p".to_owned(),
            "i".to_owned(),
            PathBuf::from("/repo"),
            Source::Agent {
                run: "talk-2".to_owned(),
                node: crate::queue::CHAT_NODE.to_owned(),
            },
        );
        parent.origin_chat = None;
        q.put(&mut parent).unwrap();
        let mut s = merged(two_seats());
        s.origin = Some(Origin {
            by: crate::run::StartedBy::Operator,
            task: Some(parent.id.clone()),
        });
        file(&mut s, "u", &q).unwrap();
        let t = q.list().into_iter().find(|t| t.followup.is_some()).unwrap();
        assert_eq!(t.origin_chat.as_deref(), Some("talk-2"));
    }

    const PR: &str = "https://github.com/o/r/pull/473";

    fn manual(text: &str) -> Task {
        Task::new(
            "manual".to_owned(),
            text.to_owned(),
            PathBuf::from("/repo"),
            Source::Human,
        )
    }

    /// File follow-ups with one manual task already in the queue.
    fn filed_with(text: &str) -> (Outcome, RunState, Queue, String, tempfile::TempDir) {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut t = manual(text);
        t.status = crate::queue::TaskStatus::Done;
        q.put(&mut t).unwrap();
        let mut s = merged(two_seats());
        let out = file(&mut s, PR, &q).unwrap();
        (out, s, q, t.id, dir)
    }

    #[test]
    fn a_task_naming_the_pr_url_and_ids_covers_the_group() {
        let (out, s, _q, id, _d) = filed_with(&format!("Fix R3-1-1 and R3-2-1 from {PR}"));
        // the waiter.rs group is covered; the other seat-1 Minor is still filed
        assert_eq!(out.filed.len(), 1, "{out:?}");
        assert_eq!(
            out.covered,
            vec![
                ("R3-1-1".to_owned(), id.clone()),
                ("R3-2-1".to_owned(), id.clone())
            ]
        );
        assert!(out.capped.is_empty());
        assert!(
            s.events
                .iter()
                .any(|e| e.message.contains("already covered"))
        );
        let body = comment_body(&s, &out);
        assert!(body.contains(&format!("R3-1-1: already covered by task `{id}`")));
    }

    #[test]
    fn the_hash_form_covers_but_a_prefix_number_does_not() {
        let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in PR #473");
        assert_eq!(out.covered.len(), 2);
        let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in #47");
        assert!(out.covered.is_empty());
        assert_eq!(out.filed.len(), 2);
        let (out, ..) = filed_with("R3-1-1 R3-2-1 fixed in #4731");
        assert!(out.covered.is_empty());
    }

    #[test]
    fn an_id_without_the_pr_does_not_cover() {
        let (out, ..) = filed_with("R3-1-1 and R3-2-1 are bad");
        assert!(out.covered.is_empty());
        assert_eq!(out.filed.len(), 2);
    }

    #[test]
    fn an_id_prefix_does_not_cover() {
        let (out, ..) = filed_with(&format!("R3-1-10 R3-2-10 in {PR}"));
        assert!(out.covered.is_empty());
    }

    #[test]
    fn partial_coverage_still_files() {
        let (out, ..) = filed_with(&format!("R3-1-1 in {PR}"));
        assert!(out.covered.is_empty());
        assert_eq!(out.filed.len(), 2);
    }

    #[test]
    fn another_followups_findings_cover() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        let mut other = manual("x");
        other.followup = Some(FollowUp {
            run: s.id.clone(),
            origin_task: None,
            pr: PR.to_owned(),
            findings: vec!["R3-1-1".to_owned(), "R3-2-1".to_owned()],
            generation: 1,
        });
        q.put(&mut other).unwrap();
        let out = file(&mut s, PR, &q).unwrap();
        assert_eq!(out.covered.len(), 2, "{out:?}");
        assert_eq!(out.filed.len(), 1);
    }

    #[test]
    fn github_text_fixed_followup_comment_passes() {
        let state = merged(two_seats());
        let body = comment_body(&state, &Outcome::default());
        assert!(crate::github_text::check("", &body).is_empty());
    }

    #[test]
    fn a_fully_covered_comment_lists_only_the_covered() {
        let (out, mut s, ..) = filed_with(&format!("R3-1-1 R3-2-1 {PR}"));
        s.followups.clear();
        let body = comment_body(&s, &out);
        assert!(body.contains("already covered by task"));
        assert!(!body.contains("filed as follow-up"));
    }

    #[test]
    fn an_id_next_to_japanese_prose_still_covers() {
        let (out, ..) = filed_with("PR #473 の R3-1-1を修正、R3-2-1も対応");
        assert_eq!(out.covered.len(), 2, "{out:?}");
    }

    // ---- deputy tasks released after the merge ----

    fn deputy_task(run: &str, title: &str, text: &str, reason: &str) -> Task {
        let mut t = Task::new(
            title.to_owned(),
            text.to_owned(),
            PathBuf::from("/repo"),
            Source::Agent {
                run: run.to_owned(),
                node: crate::deputy::NODE.to_owned(),
            },
        );
        t.hold_manual(Some(reason.to_owned()));
        t
    }

    fn status_of(q: &Queue, id: &str) -> crate::queue::TaskStatus {
        q.get(id).unwrap().status
    }

    #[test]
    fn a_deputy_task_is_released_once_and_stamped() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        let mut t = deputy_task(
            &s.id,
            "Unrelated work",
            "do the thing",
            &format!("after {PR}"),
        );
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Queued);
        assert!(got.hold_reason.is_none());
        let f = got.followup.unwrap();
        assert_eq!((f.run.as_str(), f.generation), (s.id.as_str(), 1));
        assert_eq!(s.deputy_followups, vec![t.id.clone()]);
        let events = s.events.len();
        // A second pass, or a restart that lost the run's record, changes nothing.
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(s.events.len(), events);
        s.deputy_followups.clear();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(
            s.deputy_followups,
            vec![t.id.clone()],
            "rebuilt from the queue"
        );
        assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Queued);
    }

    #[test]
    fn unrelated_held_tasks_are_never_released() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        let mut other_run = deputy_task("someone-else", "a", "b", &format!("after {PR}"));
        let mut other_pr = deputy_task(&s.id, "c", "d", "after https://github.com/o/r/pull/4731");
        let mut no_reason = deputy_task(&s.id, "e", "f", "x");
        no_reason.hold_reason = None;
        let mut human = manual("g");
        human.hold_manual(Some(format!("waiting for {PR}")));
        let mut queued = deputy_task(&s.id, "h", "i", &format!("after {PR}"));
        queued.release();
        let ids: Vec<String> = [
            &mut other_run,
            &mut other_pr,
            &mut no_reason,
            &mut human,
            &mut queued,
        ]
        .into_iter()
        .map(|t| {
            q.put(t).unwrap();
            t.id.clone()
        })
        .collect();
        settle_deputy_tasks(&mut s, PR, &q, true);
        for id in &ids[..4] {
            assert_eq!(status_of(&q, id), crate::queue::TaskStatus::Held, "{id}");
            assert!(q.get(id).unwrap().followup.is_none());
        }
        assert!(s.deputy_followups.is_empty());
    }

    #[test]
    fn the_switch_off_leaves_the_task_held() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        let mut t = deputy_task(&s.id, "x", "y", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, false);
        assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Held);
    }

    #[test]
    fn the_generation_cap_applies_to_released_tasks() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(MAX_FOLLOWUP_GENERATION);
        let mut t = deputy_task(&s.id, "x", "y", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Held);
        assert!(got.hold_reason.unwrap().starts_with(CAPPED));
        let events = s.events.len();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(s.events.len(), events, "marked once");
        let mut s2 = merged(two_seats());
        s2.followup_generation = Some(MAX_FOLLOWUP_GENERATION - 1);
        let mut t2 = deputy_task(&s2.id, "x", "y", &format!("after {PR}"));
        q.put(&mut t2).unwrap();
        settle_deputy_tasks(&mut s2, PR, &q, true);
        assert_eq!(
            q.get(&t2.id).unwrap().followup.unwrap().generation,
            MAX_FOLLOWUP_GENERATION
        );
    }

    #[test]
    fn deputy_first_the_owners_task_runs_and_the_automatic_one_is_not_filed() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        let mut t = deputy_task(
            &s.id,
            "Fix the waiter",
            "R3-1-1 at src/waiter.rs:212 loses replies",
            &format!("after {PR}"),
        );
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        let out = file(&mut s, PR, &q).unwrap();
        assert_eq!(out.covered.len(), 2, "{out:?}");
        // Only the seat-1 Minor group is filed; the waiter.rs defect has one task.
        assert_eq!(out.filed.len(), 1, "{out:?}");
        let runnable: Vec<_> = q
            .list()
            .into_iter()
            .filter(|t| {
                t.status == crate::queue::TaskStatus::Queued
                    && t.followup
                        .as_ref()
                        .is_some_and(|f| f.findings.iter().any(|x| x == "R3-1-1"))
            })
            .collect();
        assert_eq!(runnable.len(), 1);
        assert_eq!(runnable[0].id, t.id);
    }

    #[test]
    fn followup_first_a_queued_automatic_task_gives_way_to_the_owners() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let mut t = deputy_task(
            &s.id,
            "Waiter replies",
            "see R3-2-1",
            &format!("after {PR}"),
        );
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        let all = q.list();
        let live: Vec<_> = all
            .iter()
            .filter(|t| {
                t.status == crate::queue::TaskStatus::Queued
                    && t.followup
                        .as_ref()
                        .is_some_and(|f| f.findings.iter().any(|x| x == "R3-2-1"))
            })
            .collect();
        assert_eq!(live.len(), 1);
        assert_eq!(live[0].id, t.id);
        let dropped = all
            .iter()
            .find(|a| {
                a.id != t.id
                    && a.followup
                        .as_ref()
                        .is_some_and(|f| f.findings.iter().any(|x| x == "R3-2-1"))
            })
            .unwrap();
        assert_eq!(dropped.status, crate::queue::TaskStatus::Held);
        assert!(
            dropped
                .hold_reason
                .as_ref()
                .unwrap()
                .starts_with(SUPERSEDED)
        );
    }

    #[test]
    fn followup_first_a_finished_automatic_task_supersedes_the_deputys() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        for mut a in q.list() {
            a.status = crate::queue::TaskStatus::Done;
            q.put(&mut a).unwrap();
        }
        // Matched by the finding's title, not its id.
        let mut t = deputy_task(&s.id, "title R3-1-1", "no ids here", &format!("after {PR}"));
        t.instruction = "nothing".to_owned();
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Held);
        assert!(got.followup.is_none());
        let reason = got.hold_reason.unwrap();
        assert!(reason.starts_with(SUPERSEDED), "{reason}");
        assert!(reason.contains(PR));
        let events = s.events.len();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(s.events.len(), events, "judged once");
    }

    #[test]
    fn a_held_deputy_task_is_superseded_by_a_later_filing_when_the_switch_is_off() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        let mut t = deputy_task(&s.id, "x", "R3-1-1 here", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, false);
        assert!(
            !q.get(&t.id)
                .unwrap()
                .hold_reason
                .unwrap()
                .starts_with(SUPERSEDED)
        );
        file(&mut s, PR, &q).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, false);
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Held);
        assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
    }

    #[test]
    fn the_comment_lists_released_deputy_tasks() {
        let mut s = merged(two_seats());
        s.deputy_followups.push("abcd-1".to_owned());
        let body = comment_body(&s, &Outcome::default());
        assert!(body.contains("`abcd-1`"));
        assert!(!body.contains("already covered"));
        assert!(crate::github_text::check("", &body).is_empty());
    }

    #[test]
    fn a_deputy_task_over_two_automatic_ones_holds_both() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(status_of(&q, &t.id), crate::queue::TaskStatus::Queued);
        let live = q
            .list()
            .into_iter()
            .filter(|x| x.status == crate::queue::TaskStatus::Queued)
            .count();
        assert_eq!(live, 1, "only the owner's task still runs");
    }

    #[test]
    fn a_claimed_automatic_task_is_not_touched_and_the_deputys_stays_held() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let auto = q
            .list()
            .into_iter()
            .find(|x| {
                x.followup
                    .as_ref()
                    .is_some_and(|f| f.findings.iter().any(|i| i == "R3-1-1"))
            })
            .unwrap();
        let _claim = q.claim(&auto.id).unwrap();
        let mut t = deputy_task(&s.id, "x", "R3-1-1", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(status_of(&q, &auto.id), crate::queue::TaskStatus::Queued);
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Held);
        assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
    }

    #[test]
    fn a_failed_hold_restores_the_automatic_tasks_already_held() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let autos = q.list();
        assert_eq!(autos.len(), 2);
        let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        // Make the save of the second automatic task fail.
        let last = autos.last().unwrap().id.clone();
        let tmp = dir.path().join("queue").join(format!("{last}.json.tmp"));
        std::fs::create_dir_all(&tmp).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        for a in &autos {
            let got = q.get(&a.id).unwrap();
            assert_eq!(got.status, crate::queue::TaskStatus::Queued, "{}", a.id);
            assert_eq!(got.attempts, a.attempts);
        }
        let got = q.get(&t.id).unwrap();
        assert_eq!(got.status, crate::queue::TaskStatus::Held);
        assert!(got.hold_reason.unwrap().starts_with(SUPERSEDED));
    }

    #[test]
    fn a_hold_left_by_an_earlier_failed_pass_is_restored_on_the_next_failure() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let autos = q.list();
        let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        // The first auto task is left held by an earlier, interrupted pass.
        let why = format!(
            "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {PR}",
            t.id
        );
        q.modify(&autos[0].id, |x| {
            x.hold_manual(Some(why));
            true
        })
        .unwrap();
        let tmp = dir
            .path()
            .join("queue")
            .join(format!("{}.json.tmp", autos[1].id));
        std::fs::create_dir_all(&tmp).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        for a in &autos {
            let got = q.get(&a.id).unwrap();
            assert_eq!(got.status, crate::queue::TaskStatus::Queued, "{}", a.id);
            assert!(got.hold_reason.is_none());
        }
        assert!(
            q.get(&t.id)
                .unwrap()
                .hold_reason
                .unwrap()
                .starts_with(SUPERSEDED)
        );
    }

    #[test]
    fn a_blocked_takeover_restores_a_hold_left_by_an_earlier_pass() {
        let dir = tempfile::tempdir().unwrap();
        let q = Queue::at(dir.path().join("queue"));
        let mut s = merged(two_seats());
        s.followup_generation = Some(0);
        file(&mut s, PR, &q).unwrap();
        let autos = q.list();
        let mut t = deputy_task(&s.id, "both", "R3-1-1 and R3-1-2", &format!("after {PR}"));
        q.put(&mut t).unwrap();
        let why = format!(
            "{SUPERSEDED}the owner's approval deputy filed task {} for the same finding(s) of {PR}",
            t.id
        );
        q.modify(&autos[0].id, |x| {
            x.hold_manual(Some(why));
            true
        })
        .unwrap();
        let _claim = q.claim(&autos[1].id).unwrap();
        settle_deputy_tasks(&mut s, PR, &q, true);
        assert_eq!(
            status_of(&q, &autos[0].id),
            crate::queue::TaskStatus::Queued
        );
        assert!(
            q.get(&t.id)
                .unwrap()
                .hold_reason
                .unwrap()
                .starts_with(SUPERSEDED)
        );
    }
}