thirdshift 0.10.1

Turn a GitHub issue into a ready-for-review pull request, unattended
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
//! The Repair loop: what keeps a Delivery's ready pull request mergeable
//! and its CI green, within its Repair and upstream-move budgets, and, in a
//! Merge run, merges it, going round again after a failed merge until it
//! merges or is a Policy refusal. It reaches the Issue branch, CI, the
//! Repair sessions, the Base fix and the pull request only through
//! [`Outside`].

use anyhow::{Result, bail};

use crate::pull_request::MergeAttempt;

use crate::ci::{self, Ci, FailedChecks};
use crate::failed_run::PolicyRefusal;
use crate::run::Goal;
use crate::worktree::{ForeignCommits, Merge};

/// Which upstream a conflict Repair resolves a merge of.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum Upstream {
    /// The Base branch on origin.
    BaseBranch,
    /// The Issue branch on origin, with Foreign commits on it.
    IssueBranch,
}

/// A Repair, by what it is.
pub(super) enum Repair<'a> {
    /// Resolve a conflicted merge of this upstream.
    Conflict(Upstream),
    /// Fix the branch's own failures among these failed checks.
    CiFix(&'a FailedChecks),
    /// Review the Foreign commits merged in on top of this commit, the head
    /// the Run last knew as its own.
    Review { from: &'a str },
}

/// What the Repair loop does or reads outside itself.
pub(super) trait Outside {
    /// A merge left in progress for a conflict Repair.
    type Pending;

    /// Merge the Base branch, fetched from origin, into the Issue branch,
    /// returning the selected commit or the merge left pending if it conflicted.
    fn merge_base_branch(&mut self) -> Result<Merge<Self::Pending>>;
    /// Consume a Foreign commit observation, merging its sampled origin head.
    fn merge_new_commits(&mut self, observed: ForeignCommits) -> Result<Merge<Self::Pending>>;
    /// Fail unless the merge `pending` was finished.
    fn ensure_merged(&mut self, pending: &Self::Pending) -> Result<()>;
    /// Push the Issue branch.
    fn push(&mut self) -> Result<()>;
    /// The Issue branch's head commit.
    fn head(&mut self) -> Result<String>;
    /// Whether the Base branch on origin has commits the Issue branch has
    /// not merged yet.
    fn base_branch_moved(&mut self) -> Result<bool>;
    /// Observe the sampled origin and local heads and the oldest-first
    /// Foreign commits between them, without merging.
    fn new_commits_on_origin(&mut self) -> Result<ForeignCommits>;

    /// Watch CI on `head`, comparing its failed checks with those on
    /// `base_commit`, if given.
    fn watch(&mut self, head: &str, base_commit: Option<&str>) -> Result<Ci>;
    /// The Check re-run of `head`, after a CI-fix Repair given `failed` left
    /// it unchanged: `None` if there is none to watch.
    fn rerun(
        &mut self,
        head: &str,
        base_commit: Option<&str>,
        failed: &FailedChecks,
    ) -> Result<Option<Ci>>;

    /// Start the Repair session `kind`, as in `repair-1`, for `repair`.
    fn repair(&mut self, kind: &str, repair: Repair) -> Result<()>;

    /// Whether the Run compares its red checks with the Base branch's, so
    /// that some may be Inherited failures.
    fn sees_inherited_failures(&mut self) -> bool;
    /// Take the Base fix for the Inherited failures in `failed`, which also
    /// fail on the Base branch at `base_commit`, returning once the Run is to
    /// go round again.
    fn base_fix(&mut self, base_commit: &str, failed: &FailedChecks) -> Result<()>;

    /// Fail unless the pull request is open, ready for review and mergeable.
    fn ensure_pr_ready_and_mergeable(&mut self) -> Result<()>;
    /// Merge the pull request at `head`.
    fn merge(&mut self, head: &str) -> Result<MergeAttempt>;

    /// Whether an interrupt was requested.
    fn interrupt_requested(&mut self) -> bool;
    /// Write the progress line `line`.
    fn progress(&mut self, line: String);
}

/// Take the ready pull request, whose Base branch is `base`, to `goal`
/// through `outside`. Keep it mergeable and its CI green through the Repair
/// loop (see [`RepairLoop::rounds`]), then check it is still open, ready and
/// mergeable, and for [`Goal::Merged`], merge it at the head whose CI was
/// last watched. A merge that fails goes back round the Repair loop and is
/// tried again on the new head; if that round finds nothing to fix, this
/// fails with a [`PolicyRefusal`]. Returns once the pull request has
/// reached `goal`; fails as interrupted if an interrupt was requested before
/// the merge.
pub(super) fn take_to_goal(outside: &mut impl Outside, base: &str, goal: Goal) -> Result<()> {
    let mut repair_loop = RepairLoop {
        outside,
        base,
        goal,
        budgets: Budgets::default(),
    };
    let mut watched = repair_loop.rounds()?;
    loop {
        let outside = &mut *repair_loop.outside;
        outside.ensure_pr_ready_and_mergeable()?;
        if outside.interrupt_requested() {
            bail!("interrupted");
        }
        if goal == Goal::ReadyForReview {
            return Ok(());
        }
        outside.progress(format!("merging the PR into {base}"));
        let error = match outside.merge(&watched)? {
            MergeAttempt::Merged => return Ok(()),
            MergeAttempt::Refused(error) => error,
        };
        outside.progress(format!("the merge failed: {error:#}"));
        match repair_loop.round_after_failed_merge(&watched)? {
            Round::NewHead(head) => watched = head,
            Round::NothingToFix => {
                // Only a PR still ready and mergeable is left ready.
                repair_loop.outside.ensure_pr_ready_and_mergeable()?;
                return Err(error.context(PolicyRefusal));
            }
        }
    }
}

/// The most Repair sessions a Delivery starts, conflict, CI-fix and review
/// combined.
const MAX_REPAIRS: usize = 5;

/// The most times a Delivery goes round again because the Base branch moved while
/// CI ran or since a merge was tried, or, in a Merge run, because Foreign
/// commits arrived, whether or not the merge that follows needs a Repair. A
/// clean merge of the Base branch uses no Repair, so without this a busy Base
/// branch could keep a Delivery going forever.
const MAX_UPSTREAM_MOVES: usize = 5;

/// What a Delivery has spent of its Repair and upstream-move budgets,
/// across every round of the Repair loop, those after a failed merge
/// included.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
struct Budgets {
    repairs: usize,
    upstream_moves: usize,
}

impl Budgets {
    /// Counts the Repair about to start, returning its kind, `repair-<n>`,
    /// and its progress line, or fails if it would be one too many.
    fn next_repair(&mut self, cause: &str) -> Result<(String, String)> {
        if self.repairs == MAX_REPAIRS {
            bail!("repairs exhausted: {cause}");
        }
        self.repairs += 1;
        let line = format!("{cause}; starting Repair {} of {MAX_REPAIRS}", self.repairs);
        Ok((format!("repair-{}", self.repairs), line))
    }

    /// Counts a round taken because `upstream` moved, or fails if it would
    /// be one too many.
    fn count_upstream_move(&mut self, upstream: &str) -> Result<()> {
        if self.upstream_moves == MAX_UPSTREAM_MOVES {
            bail!("{upstream} kept moving: merged it again {MAX_UPSTREAM_MOVES} times");
        }
        self.upstream_moves += 1;
        Ok(())
    }

    /// Counts a round taken because `origin/<base>` moved `when`, returning
    /// its progress line.
    fn count_base_move(&mut self, base: &str, when: &str) -> Result<String> {
        let upstream = format!("origin/{base}");
        self.count_upstream_move(&upstream)?;
        Ok(format!("{upstream} moved {when}; merging it again"))
    }

    /// Counts a round taken because the Issue branch on origin, `upstream`,
    /// has new commits, returning its progress line.
    fn count_foreign_commits(&mut self, upstream: &str) -> Result<String> {
        self.count_upstream_move(upstream)?;
        Ok(format!("{upstream} has new commits; merging them in"))
    }
}

/// What a round of the Repair loop after a failed merge came to.
enum Round {
    /// A head whose CI was found green or absent, to try the merge on.
    NewHead(String),
    /// The same head, with no Repair and no upstream move: a policy refusal.
    NothingToFix,
}

/// Keeps the PR mergeable and its CI green, within the Delivery's budgets.
struct RepairLoop<'a, O> {
    outside: &'a mut O,
    base: &'a str,
    goal: Goal,
    budgets: Budgets,
}

impl<O: Outside> RepairLoop<'_, O> {
    /// Start the next Repair, `repair`, for `cause`, counting it against the
    /// Repair cap.
    fn repair(&mut self, cause: &str, repair: Repair) -> Result<()> {
        let (kind, line) = self.budgets.next_repair(cause)?;
        self.outside.progress(line);
        self.outside.repair(&kind, repair)
    }

    /// Count a round taken because the Base branch moved `when`.
    fn count_base_move(&mut self, when: &str) -> Result<()> {
        let line = self.budgets.count_base_move(self.base, when)?;
        self.outside.progress(line);
        Ok(())
    }

    /// In a Merge run, first take in any Foreign commits. Then merge the
    /// Base branch (never rebase), push, and watch CI on the head commit,
    /// starting a Repair session for a conflict or red
    /// CI and then going round again, since the Base branch may have moved
    /// meanwhile. Green or absent CI also goes round again if the Base branch
    /// moved while CI ran, or, in a Merge run, if Foreign commits arrived.
    /// A red check that also fails on the Base branch commit the head last
    /// merged in is an Inherited failure, which no Repair is started for: the
    /// CI-fix Repair is given the branch's own failures, and when there are
    /// none, the loop goes round again if the Base branch moved since, counted
    /// as a Base move, and otherwise once its Base fix has returned, or fails
    /// with the Base fix's cause. A Run that sees no Inherited failures
    /// compares with no Base branch commit.
    /// If, after a CI-fix Repair and the Base branch merged again, the head
    /// is still the one whose CI failed, it gets its Check re-run instead of
    /// a watch, whatever the Repair concluded. CI then
    /// green, or red only on Inherited failures, is taken as from any watch.
    /// Returns the head commit whose CI was last watched and found green or
    /// absent. Fails with a Declined CI fix if that Check re-run leaves a
    /// check of the branch's own red, or there can be none, and once a Repair
    /// beyond `MAX_REPAIRS`, or a round beyond `MAX_UPSTREAM_MOVES`, would be
    /// needed.
    fn rounds(&mut self) -> Result<String> {
        let base = self.base;
        // The head the last CI-fix Repair was given, with its failed checks.
        let mut handed_to_repair: Option<(String, FailedChecks)> = None;
        loop {
            if self.goal == Goal::Merged {
                self.take_in_foreign_commits()?;
            }
            let base_commit = match self.outside.merge_base_branch()? {
                Merge::Clean { commit } => commit,
                Merge::Conflicted(pending) => {
                    self.repair("conflict", Repair::Conflict(Upstream::BaseBranch))?;
                    self.outside.ensure_merged(&pending)?;
                    continue;
                }
            };
            self.outside.push()?;
            let head = self.outside.head()?;
            let compared_with = self
                .outside
                .sees_inherited_failures()
                .then_some(base_commit.as_str());
            let unchanged = handed_to_repair
                .take()
                .filter(|(handed, _)| *handed == head);
            let ci = match unchanged {
                None => self.outside.watch(&head, compared_with)?,
                // A Declined CI fix, unless the head's one Check re-run turns
                // the branch's own checks green: it gets no second Repair.
                Some((_, failed)) => match self.outside.rerun(&head, compared_with, &failed)? {
                    Some(ci) if !ci.has_own_failures() => ci,
                    _ => bail!(
                        "CI red on {} and the Repair found nothing to fix on the branch",
                        ci::short(&head)
                    ),
                },
            };
            match ci {
                Ci::Absent | Ci::Passed => {
                    if self.outside.base_branch_moved()? {
                        self.count_base_move("while CI ran")?;
                    } else if self.goal == Goal::ReadyForReview
                        || self.outside.new_commits_on_origin()?.commits().is_empty()
                    {
                        return Ok(head);
                    }
                }
                Ci::Failed(failed) => {
                    if !failed.inherited.is_empty() {
                        self.outside.progress(format!(
                            "Inherited failures (also failing on {base} at {}): {}",
                            ci::short(&base_commit),
                            ci::check_names(&failed.inherited)
                        ));
                    }
                    if failed.own.is_empty() {
                        // Someone may have fixed the Base branch since.
                        if self.outside.base_branch_moved()? {
                            self.count_base_move("while CI ran")?;
                            continue;
                        }
                        self.outside.base_fix(&base_commit, &failed)?;
                        continue;
                    }
                    self.repair("CI red", Repair::CiFix(&failed))?;
                    handed_to_repair = Some((head, failed));
                }
            }
        }
    }

    /// Fetch the Issue branch from origin and merge in any Foreign commits on
    /// it (never rebase), counting that as a round and handing a conflict to
    /// a conflict Repair. Then a review Repair reviews them from the head the
    /// Run last knew as its own, the local head before the merge. Goes round
    /// again until origin has nothing new, since more may land during either
    /// Repair, and the push after them would be rejected.
    fn take_in_foreign_commits(&mut self) -> Result<()> {
        loop {
            let foreign = self.outside.new_commits_on_origin()?;
            if foreign.commits().is_empty() {
                return Ok(());
            }
            let upstream = foreign.upstream().to_string();
            let own_head = foreign.local_head().to_string();
            let line = self.budgets.count_foreign_commits(&upstream)?;
            self.outside.progress(line);
            for sha in foreign.commits() {
                self.outside
                    .progress(format!("merging new commit {sha} from {upstream}"));
            }
            if let Merge::Conflicted(pending) = self.outside.merge_new_commits(foreign)? {
                self.repair(
                    &format!("conflict with new commits on {upstream}"),
                    Repair::Conflict(Upstream::IssueBranch),
                )?;
                self.outside.ensure_merged(&pending)?;
            }
            self.repair(
                &format!("new commits on {upstream} to review"),
                Repair::Review { from: &own_head },
            )?;
        }
    }

    /// Go round again after a merge of `watched` failed, counting a Base
    /// branch that moved since as an upstream move. GitHub's error text is never
    /// consulted.
    fn round_after_failed_merge(&mut self, watched: &str) -> Result<Round> {
        let before = self.budgets;
        if self.outside.base_branch_moved()? {
            self.count_base_move("since the merge was tried")?;
        }
        let head = self.rounds()?;
        Ok(if head == watched && self.budgets == before {
            Round::NothingToFix
        } else {
            Round::NewHead(head)
        })
    }
}

#[cfg(test)]
mod tests {
    use std::collections::VecDeque;

    use anyhow::anyhow;

    use super::*;
    use crate::github::{Check, CheckState};

    /// What the Repair loop did outside itself, in the order it did it.
    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Did {
        /// Merged the Base branch in.
        MergeBase,
        /// Merged the new commits on origin in.
        MergeNewCommits(String),
        /// Checked the pending merge of this upstream was finished.
        CheckMerged(&'static str),
        Push,
        /// Watched CI on this head, compared with this Base branch commit.
        Watch(String, Option<String>),
        /// Gave this head its Check re-run of these checks of its own.
        Rerun(String, Option<String>, Vec<String>),
        /// Started the Repair session of this kind for this Repair.
        Repair(String, Started),
        /// Took the Base fix for these Inherited failures, at this Base
        /// branch commit.
        BaseFix(String, Vec<String>),
        /// Checked the PR is open, ready and mergeable.
        CheckPr,
        /// Merged the PR at this head.
        Merge(String),
        /// Wrote this progress line.
        Line(String),
    }

    /// A Repair as the scripted adapter records it.
    #[derive(Debug, Clone, PartialEq, Eq)]
    enum Started {
        Conflict(Upstream),
        /// A CI fix given these failed checks of the branch's own, and these
        /// Inherited failures.
        CiFix(Vec<String>, Vec<String>),
        /// A review from this commit.
        Review(String),
    }

    /// How CI on a head ends, as a script gives it.
    enum Is {
        Absent,
        Passed,
        /// Red on these checks of the branch's own, and these Inherited
        /// failures.
        Failed(&'static [&'static str], &'static [&'static str]),
    }

    impl Is {
        /// CI as the loop sees it, built fresh.
        fn ci(&self) -> Ci {
            let checks = |names: &[&str]| -> Vec<Check> {
                names
                    .iter()
                    .map(|name| Check {
                        name: name.to_string(),
                        state: CheckState::Failed,
                        url: None,
                        job: None,
                    })
                    .collect()
            };
            match self {
                Is::Absent => Ci::Absent,
                Is::Passed => Ci::Passed,
                Is::Failed(own, inherited) => Ci::Failed(FailedChecks {
                    own: checks(own),
                    inherited: checks(inherited),
                    on_base: checks(inherited),
                }),
            }
        }
    }

    /// What the outside world answers, call by call. A head or Base branch
    /// commit stays the last one given; a merge is clean, the Base branch
    /// unmoved, origin without new commits and a Base fix returns, unless
    /// scripted otherwise.
    #[derive(Default)]
    struct Script {
        heads: VecDeque<&'static str>,
        base_commits: VecDeque<&'static str>,
        /// For each merge of the Base branch, whether it conflicts.
        base_conflicts: VecDeque<bool>,
        /// For each merge of new commits on origin, whether it conflicts.
        new_commit_conflicts: VecDeque<bool>,
        base_moved: VecDeque<bool>,
        new_commits: VecDeque<ForeignCommits>,
        watches: VecDeque<Is>,
        reruns: VecDeque<Option<Is>>,
        /// For each Base fix, the cause it fails with, if it does.
        base_fixes: VecDeque<Option<&'static str>>,
        /// For each merge, the error it fails with, if it does.
        merges: VecDeque<Option<&'static str>>,
        merge_gate_error: Option<&'static str>,
        sees_no_inherited_failures: bool,
        interrupted: bool,
    }

    /// The outside world as `script` answers it, with what the loop did there
    /// recorded in `did`.
    struct Scripted {
        script: Script,
        did: Vec<Did>,
    }

    /// The next of `answers`, keeping the last one for every call after it.
    fn sticky(answers: &mut VecDeque<&'static str>, what: &str) -> String {
        let answer = if answers.len() > 1 {
            answers.pop_front()
        } else {
            answers.front().copied()
        };
        answer
            .unwrap_or_else(|| panic!("no {what} scripted"))
            .to_string()
    }

    /// The names of `checks`.
    fn names(checks: &[Check]) -> Vec<String> {
        checks.iter().map(|check| check.name.clone()).collect()
    }

    impl Outside for Scripted {
        /// The upstream whose merge is pending.
        type Pending = &'static str;

        fn merge_base_branch(&mut self) -> Result<Merge<&'static str>> {
            self.did.push(Did::MergeBase);
            let conflicted = self.script.base_conflicts.pop_front().unwrap_or(false);
            if conflicted {
                return Ok(Merge::Conflicted("origin/main"));
            }
            let commit = if self.script.base_commits.is_empty() {
                "b1".to_string()
            } else {
                sticky(&mut self.script.base_commits, "Base branch commit")
            };
            Ok(Merge::Clean { commit })
        }

        fn merge_new_commits(&mut self, observed: ForeignCommits) -> Result<Merge<&'static str>> {
            self.did
                .push(Did::MergeNewCommits(observed.origin_head().to_string()));
            let conflicted = self
                .script
                .new_commit_conflicts
                .pop_front()
                .unwrap_or(false);
            Ok(if conflicted {
                Merge::Conflicted("origin/issue-7")
            } else {
                Merge::Clean {
                    commit: observed.origin_head().to_string(),
                }
            })
        }

        fn ensure_merged(&mut self, pending: &&'static str) -> Result<()> {
            self.did.push(Did::CheckMerged(pending));
            Ok(())
        }

        fn push(&mut self) -> Result<()> {
            self.did.push(Did::Push);
            Ok(())
        }

        fn head(&mut self) -> Result<String> {
            Ok(sticky(&mut self.script.heads, "head"))
        }

        fn base_branch_moved(&mut self) -> Result<bool> {
            Ok(self.script.base_moved.pop_front().unwrap_or(false))
        }

        fn new_commits_on_origin(&mut self) -> Result<ForeignCommits> {
            Ok(self
                .script
                .new_commits
                .pop_front()
                .unwrap_or_else(|| ForeignCommits::fixture("h1", &[])))
        }

        fn watch(&mut self, head: &str, base_commit: Option<&str>) -> Result<Ci> {
            self.did
                .push(Did::Watch(head.to_string(), base_commit.map(String::from)));
            let is = self.script.watches.pop_front().expect("no watch scripted");
            Ok(is.ci())
        }

        fn rerun(
            &mut self,
            head: &str,
            base_commit: Option<&str>,
            failed: &FailedChecks,
        ) -> Result<Option<Ci>> {
            self.did.push(Did::Rerun(
                head.to_string(),
                base_commit.map(String::from),
                names(&failed.own),
            ));
            let is = self.script.reruns.pop_front().expect("no re-run scripted");
            Ok(is.map(|is| is.ci()))
        }

        fn repair(&mut self, kind: &str, repair: Repair) -> Result<()> {
            let started = match repair {
                Repair::Conflict(upstream) => Started::Conflict(upstream),
                Repair::CiFix(failed) => {
                    Started::CiFix(names(&failed.own), names(&failed.inherited))
                }
                Repair::Review { from } => Started::Review(from.to_string()),
            };
            self.did.push(Did::Repair(kind.to_string(), started));
            Ok(())
        }

        fn sees_inherited_failures(&mut self) -> bool {
            !self.script.sees_no_inherited_failures
        }

        fn base_fix(&mut self, base_commit: &str, failed: &FailedChecks) -> Result<()> {
            self.did.push(Did::BaseFix(
                base_commit.to_string(),
                names(&failed.inherited),
            ));
            match self.script.base_fixes.pop_front().flatten() {
                Some(cause) => Err(anyhow!(cause)),
                None => Ok(()),
            }
        }

        fn ensure_pr_ready_and_mergeable(&mut self) -> Result<()> {
            self.did.push(Did::CheckPr);
            Ok(())
        }

        fn merge(&mut self, head: &str) -> Result<MergeAttempt> {
            if let Some(error) = self.script.merge_gate_error {
                bail!(error);
            }
            self.did.push(Did::Merge(head.to_string()));
            match self.script.merges.pop_front().expect("no merge scripted") {
                Some(error) => Ok(MergeAttempt::Refused(anyhow!(error))),
                None => Ok(MergeAttempt::Merged),
            }
        }

        fn interrupt_requested(&mut self) -> bool {
            self.script.interrupted
        }

        fn progress(&mut self, line: String) {
            self.did.push(Did::Line(line));
        }
    }

    /// Take a PR into `main` to `goal` against `script`: what it came to,
    /// and what the loop did.
    fn deliver(goal: Goal, script: Script) -> (Result<()>, Vec<Did>) {
        let mut outside = Scripted {
            script,
            did: Vec::new(),
        };
        let delivered = take_to_goal(&mut outside, "main", goal);
        (delivered, outside.did)
    }

    /// `answers` as a script's queue.
    fn script<T>(answers: impl IntoIterator<Item = T>) -> VecDeque<T> {
        answers.into_iter().collect()
    }

    /// The progress line `line`.
    fn line(line: &str) -> Did {
        Did::Line(line.to_string())
    }

    /// A watch of CI on `head`, compared with the Base branch commit `b1`.
    fn watch(head: &str) -> Did {
        Did::Watch(head.to_string(), Some("b1".to_string()))
    }

    /// The Repair session `repair-<n>` for `started`.
    fn repair(n: usize, started: Started) -> Did {
        Did::Repair(format!("repair-{n}"), started)
    }

    /// A CI-fix Repair given the branch's own failures `own`, and the
    /// Inherited failures `inherited`.
    fn ci_fix(own: &[&str], inherited: &[&str]) -> Started {
        let names = |checks: &[&str]| checks.iter().map(|name| name.to_string()).collect();
        Started::CiFix(names(own), names(inherited))
    }

    /// A round from the merge of the Base branch to the watch of `head`.
    fn round(head: &str) -> [Did; 3] {
        [Did::MergeBase, Did::Push, watch(head)]
    }

    /// The Self-merge of `head`, after the PR check.
    fn merge(head: &str) -> [Did; 3] {
        [
            Did::CheckPr,
            line("merging the PR into main"),
            Did::Merge(head.to_string()),
        ]
    }

    /// The progress lines among `did`.
    fn lines(did: &[Did]) -> Vec<&str> {
        did.iter()
            .filter_map(|did| match did {
                Did::Line(line) => Some(line.as_str()),
                _ => None,
            })
            .collect()
    }

    /// The cause `delivered` failed with, every context included.
    fn cause(delivered: Result<()>) -> String {
        format!("{:#}", delivered.unwrap_err())
    }

    #[test]
    fn green_or_absent_ci_with_nothing_moved_reaches_the_goal() {
        for is in [Is::Passed, Is::Absent] {
            let (delivered, did) = deliver(
                Goal::Merged,
                Script {
                    heads: script(["h1"]),
                    watches: script([is]),
                    merges: script([None]),
                    ..Script::default()
                },
            );

            delivered.unwrap();
            assert_eq!(did, [round("h1").as_slice(), &merge("h1")].concat());
        }
    }

    #[test]
    fn a_run_left_ready_for_review_never_merges_or_takes_in_foreign_commits() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1"]),
                new_commits: script([
                    ForeignCommits::fixture("h1", &["f1"]),
                    ForeignCommits::fixture("h1", &["f1"]),
                ]),
                watches: script([Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(did, [round("h1").as_slice(), &[Did::CheckPr]].concat());
    }

    #[test]
    fn a_conflict_with_the_base_branch_is_handed_to_a_conflict_repair_then_round_again() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1"]),
                base_conflicts: script([true]),
                watches: script([Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                &[
                    Did::MergeBase,
                    line("conflict; starting Repair 1 of 5"),
                    repair(1, Started::Conflict(Upstream::BaseBranch)),
                    Did::CheckMerged("origin/main"),
                ][..],
                &round("h1"),
                &[Did::CheckPr],
            ]
            .concat()
        );
    }

    #[test]
    fn red_ci_is_handed_to_a_ci_fix_repair_with_only_its_own_failures_and_the_new_head_watched() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1", "h2"]),
                watches: script([Is::Failed(&["test"], &["lint"]), Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                &round("h1")[..],
                &[
                    line("Inherited failures (also failing on main at b1): lint"),
                    line("CI red; starting Repair 1 of 5"),
                    repair(1, ci_fix(&["test"], &["lint"])),
                ],
                &round("h2"),
                &[Did::CheckPr],
            ]
            .concat()
        );
    }

    /// What the loop does up to the Check re-run of `h1`, after a CI-fix
    /// Repair given its failed `test` left it unchanged.
    fn up_to_the_rerun() -> Vec<Did> {
        [
            &round("h1")[..],
            &[
                line("CI red; starting Repair 1 of 5"),
                repair(1, ci_fix(&["test"], &[])),
                Did::MergeBase,
                Did::Push,
                Did::Rerun(
                    "h1".to_string(),
                    Some("b1".to_string()),
                    vec!["test".to_string()],
                ),
            ],
        ]
        .concat()
    }

    #[test]
    fn an_unchanged_head_after_a_ci_fix_repair_gets_its_check_re_run_and_green_reaches_the_goal() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Failed(&["test"], &[])]),
                reruns: script([Some(Is::Passed)]),
                merges: script([None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(did, [up_to_the_rerun(), merge("h1").into()].concat());
    }

    #[test]
    fn watch_and_check_re_run_use_the_commit_returned_by_their_base_merge() {
        for rerun_base in ["sampled-base", "rewound-base"] {
            let (delivered, did) = deliver(
                Goal::ReadyForReview,
                Script {
                    heads: script(["unchanged-head"]),
                    base_commits: script(["sampled-base", rerun_base]),
                    watches: script([Is::Failed(&["test"], &[])]),
                    reruns: script([Some(Is::Passed)]),
                    ..Script::default()
                },
            );

            delivered.unwrap();
            assert!(did.contains(&Did::Watch(
                "unchanged-head".to_string(),
                Some("sampled-base".to_string())
            )));
            assert!(did.contains(&Did::Rerun(
                "unchanged-head".to_string(),
                Some(rerun_base.to_string()),
                vec!["test".to_string()]
            )));
        }
    }

    #[test]
    fn a_check_re_run_red_only_on_inherited_failures_is_taken_as_from_any_watch() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Failed(&["test"], &[]), Is::Passed]),
                reruns: script([Some(Is::Failed(&[], &["lint"]))]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                up_to_the_rerun(),
                vec![
                    line("Inherited failures (also failing on main at b1): lint"),
                    Did::BaseFix("b1".to_string(), vec!["lint".to_string()]),
                ],
                round("h1").into(),
                vec![Did::CheckPr],
            ]
            .concat()
        );
    }

    #[test]
    fn a_check_re_run_red_on_its_own_checks_or_impossible_is_a_declined_ci_fix() {
        for rerun in [Some(Is::Failed(&["test"], &[])), None] {
            let (delivered, did) = deliver(
                Goal::Merged,
                Script {
                    heads: script(["h1"]),
                    watches: script([Is::Failed(&["test"], &[])]),
                    reruns: script([rerun]),
                    ..Script::default()
                },
            );

            assert_eq!(
                cause(delivered),
                "CI red on h1 and the Repair found nothing to fix on the branch"
            );
            assert_eq!(did, up_to_the_rerun());
        }
    }

    /// What the loop does up to and including the Inherited failures line
    /// for `test` on `h1`.
    fn up_to_inherited_failures() -> Vec<Did> {
        [
            &round("h1")[..],
            &[line(
                "Inherited failures (also failing on main at b1): test",
            )],
        ]
        .concat()
    }

    #[test]
    fn inherited_failures_only_go_round_again_as_a_base_move_if_the_base_branch_moved() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1", "h2"]),
                base_commits: script(["b1", "b2"]),
                base_moved: script([true]),
                watches: script([Is::Failed(&[], &["test"]), Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                up_to_inherited_failures(),
                vec![
                    line("origin/main moved while CI ran; merging it again"),
                    Did::MergeBase,
                    Did::Push,
                    Did::Watch("h2".to_string(), Some("b2".to_string())),
                    Did::CheckPr,
                ],
            ]
            .concat()
        );
    }

    #[test]
    fn inherited_failures_only_take_the_base_fix_then_go_round_again() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Failed(&[], &["test"]), Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                up_to_inherited_failures(),
                vec![Did::BaseFix("b1".to_string(), vec!["test".to_string()])],
                round("h1").into(),
                vec![Did::CheckPr],
            ]
            .concat()
        );
    }

    #[test]
    fn a_failed_base_fix_is_the_runs_cause() {
        let fails = "CI red on test, which also fails on main at b1; fix main first";
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Failed(&[], &["test"])]),
                base_fixes: script([Some(fails)]),
                ..Script::default()
            },
        );

        assert_eq!(cause(delivered), fails);
        assert_eq!(
            did,
            [
                up_to_inherited_failures(),
                vec![Did::BaseFix("b1".to_string(), vec!["test".to_string()])],
            ]
            .concat()
        );
    }

    #[test]
    fn a_run_that_sees_no_inherited_failures_watches_ci_with_no_base_branch_commit() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Passed]),
                sees_no_inherited_failures: true,
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                Did::MergeBase,
                Did::Push,
                Did::Watch("h1".to_string(), None),
                Did::CheckPr
            ]
        );
    }

    #[test]
    fn the_base_branch_moving_while_ci_ran_goes_round_again_as_a_base_move() {
        let (delivered, did) = deliver(
            Goal::ReadyForReview,
            Script {
                heads: script(["h1", "h2"]),
                base_moved: script([true]),
                watches: script([Is::Passed, Is::Passed]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                &round("h1")[..],
                &[line("origin/main moved while CI ran; merging it again")],
                &round("h2"),
                &[Did::CheckPr],
            ]
            .concat()
        );
    }

    /// What the loop does to take in the Foreign commit `sha`, merged
    /// cleanly on top of `own_head`, as Repair `n`.
    fn foreign_commit(sha: &str, own_head: &str, n: usize) -> Vec<Did> {
        vec![
            line("origin/issue-7 has new commits; merging them in"),
            line(&format!("merging new commit {sha} from origin/issue-7")),
            Did::MergeNewCommits(sha.to_string()),
            line(&format!(
                "new commits on origin/issue-7 to review; starting Repair {n} of 5"
            )),
            repair(n, Started::Review(own_head.to_string())),
        ]
    }

    #[test]
    fn a_merge_run_merges_foreign_commits_in_and_reviews_them_while_origin_has_more() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h3"]),
                new_commits: script([
                    ForeignCommits::fixture("h1", &["f1", "f2"]),
                    ForeignCommits::fixture("h2", &["f3"]),
                ]),
                watches: script([Is::Passed]),
                merges: script([None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                vec![
                    line("origin/issue-7 has new commits; merging them in"),
                    line("merging new commit f1 from origin/issue-7"),
                    line("merging new commit f2 from origin/issue-7"),
                    Did::MergeNewCommits("f2".to_string()),
                    line("new commits on origin/issue-7 to review; starting Repair 1 of 5"),
                    repair(1, Started::Review("h1".to_string())),
                ],
                foreign_commit("f3", "h2", 2),
                round("h3").into(),
                merge("h3").into(),
            ]
            .concat()
        );
    }

    #[test]
    fn foreign_commits_that_arrive_while_ci_ran_go_round_again() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1", "h2"]),
                new_commits: script([
                    ForeignCommits::fixture("h1", &[]),
                    ForeignCommits::fixture("h1", &["f1"]),
                    ForeignCommits::fixture("h1", &["f1"]),
                ]),
                watches: script([Is::Passed, Is::Passed]),
                merges: script([None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                round("h1").into(),
                foreign_commit("f1", "h1", 1),
                round("h2").into(),
                merge("h2").into(),
            ]
            .concat()
        );
    }

    #[test]
    fn a_conflict_with_foreign_commits_is_handed_to_a_conflict_repair_then_reviewed() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h2"]),
                new_commits: script([ForeignCommits::fixture("h1", &["f1"])]),
                new_commit_conflicts: script([true]),
                watches: script([Is::Passed]),
                merges: script([None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                vec![
                    line("origin/issue-7 has new commits; merging them in"),
                    line("merging new commit f1 from origin/issue-7"),
                    Did::MergeNewCommits("f1".to_string()),
                    line("conflict with new commits on origin/issue-7; starting Repair 1 of 5"),
                    repair(1, Started::Conflict(Upstream::IssueBranch)),
                    Did::CheckMerged("origin/issue-7"),
                    line("new commits on origin/issue-7 to review; starting Repair 2 of 5"),
                    repair(2, Started::Review("h1".to_string())),
                ],
                round("h2").into(),
                merge("h2").into(),
            ]
            .concat()
        );
    }

    #[test]
    fn every_kind_of_repair_shares_one_cap_and_the_one_too_many_fails_with_its_cause() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1", "h2", "h3", "h4"]),
                new_commits: script([ForeignCommits::fixture("h0", &["f1"])]),
                base_conflicts: script([true]),
                watches: script([
                    Is::Failed(&["test"], &[]),
                    Is::Failed(&["test"], &[]),
                    Is::Failed(&["test"], &[]),
                    Is::Failed(&["test"], &[]),
                ]),
                ..Script::default()
            },
        );

        assert_eq!(cause(delivered), "repairs exhausted: CI red");
        assert_eq!(
            lines(&did),
            [
                "origin/issue-7 has new commits; merging them in",
                "merging new commit f1 from origin/issue-7",
                "new commits on origin/issue-7 to review; starting Repair 1 of 5",
                "conflict; starting Repair 2 of 5",
                "CI red; starting Repair 3 of 5",
                "CI red; starting Repair 4 of 5",
                "CI red; starting Repair 5 of 5",
            ]
        );
        assert_eq!(did.last(), Some(&watch("h4")));
    }

    #[test]
    fn base_moves_and_foreign_commits_share_one_upstream_move_budget() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                new_commits: script([ForeignCommits::fixture("h0", &["f1"])]),
                base_moved: script([true; 5]),
                watches: script((0..5).map(|_| Is::Passed)),
                ..Script::default()
            },
        );

        assert_eq!(
            cause(delivered),
            "origin/main kept moving: merged it again 5 times"
        );
        assert_eq!(
            lines(&did),
            [
                "origin/issue-7 has new commits; merging them in",
                "merging new commit f1 from origin/issue-7",
                "new commits on origin/issue-7 to review; starting Repair 1 of 5",
                "origin/main moved while CI ran; merging it again",
                "origin/main moved while CI ran; merging it again",
                "origin/main moved while CI ran; merging it again",
                "origin/main moved while CI ran; merging it again",
            ]
        );
    }

    #[test]
    fn a_sixth_foreign_batch_is_refused_before_its_merge() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                new_commits: script(
                    (1..=6).map(|n| ForeignCommits::fixture(&format!("h{n}"), &[&format!("f{n}")])),
                ),
                ..Script::default()
            },
        );

        assert_eq!(
            cause(delivered),
            "origin/issue-7 kept moving: merged it again 5 times"
        );
        let merged: Vec<_> = did
            .iter()
            .filter_map(|did| match did {
                Did::MergeNewCommits(head) => Some(head.as_str()),
                _ => None,
            })
            .collect();
        assert_eq!(merged, ["f1", "f2", "f3", "f4", "f5"]);
    }

    #[test]
    fn review_budget_refusal_still_follows_the_allowed_foreign_merge() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1", "h2", "h3", "h4", "h5"]),
                watches: script((0..5).map(|_| Is::Failed(&["test"], &[]))),
                new_commits: script(
                    (0..5)
                        .map(|_| ForeignCommits::fixture("own", &[]))
                        .chain([ForeignCommits::fixture("h6", &["f1"])]),
                ),
                ..Script::default()
            },
        );

        assert_eq!(
            cause(delivered),
            "repairs exhausted: new commits on origin/issue-7 to review"
        );
        assert_eq!(did.last(), Some(&Did::MergeNewCommits("f1".to_string())));
        assert!(
            !did.iter()
                .any(|did| matches!(did, Did::Repair(_, Started::Review(_))))
        );
    }

    #[test]
    fn a_terminal_pre_merge_gate_error_never_enters_another_round_or_policy_refusal() {
        let (ended, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Passed]),
                merge_gate_error: Some("PR targets develop, not main"),
                ..Script::default()
            },
        );
        let error = ended.unwrap_err();
        assert_eq!(error.to_string(), "PR targets develop, not main");
        assert!(!error.is::<PolicyRefusal>());
        assert_eq!(
            did.iter()
                .filter(|call| matches!(call, Did::Watch(..)))
                .count(),
            1
        );
        assert!(
            !did.iter()
                .any(|call| matches!(call, Did::Merge(..) | Did::Repair(..)))
        );
    }

    #[test]
    fn a_failed_merge_goes_round_again_counting_a_base_move_and_retries_on_the_new_head() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1", "h2"]),
                base_moved: script([false, true, false]),
                watches: script([Is::Passed, Is::Passed]),
                merges: script([Some("Base branch was modified"), None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            did,
            [
                &round("h1")[..],
                &merge("h1"),
                &[
                    line("the merge failed: Base branch was modified"),
                    line("origin/main moved since the merge was tried; merging it again"),
                ],
                &round("h2"),
                &merge("h2"),
            ]
            .concat()
        );
    }

    #[test]
    fn failed_merges_that_keep_moving_the_base_branch_spend_its_budget_and_are_no_policy_refusal() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1", "h2"]),
                // Still after CI, then moved since the merge was tried.
                base_moved: script([false, true].repeat(6)),
                watches: script((0..6).map(|_| Is::Passed)),
                merges: script((0..6).map(|_| Some("Base branch was modified"))),
                ..Script::default()
            },
        );

        let error = delivered.unwrap_err();
        assert!(!error.is::<PolicyRefusal>(), "{error:#}");
        assert_eq!(
            format!("{error:#}"),
            "origin/main kept moving: merged it again 5 times"
        );
        assert_eq!(
            did.iter()
                .filter(|did| matches!(did, Did::Merge(_)))
                .count(),
            6
        );
        assert_eq!(
            lines(&did)
                .iter()
                .filter(|line| line.starts_with("origin/main moved since the merge"))
                .count(),
            5
        );
    }

    #[test]
    fn a_failed_merge_whose_round_finds_nothing_to_fix_is_a_policy_refusal() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Passed, Is::Passed]),
                merges: script([Some("refused by a ruleset")]),
                ..Script::default()
            },
        );

        let error = delivered.unwrap_err();
        assert!(error.is::<PolicyRefusal>(), "{error:#}");
        assert_eq!(
            did,
            [
                &round("h1")[..],
                &merge("h1"),
                &[line("the merge failed: refused by a ruleset")],
                &round("h1"),
                &[Did::CheckPr],
            ]
            .concat()
        );
    }

    #[test]
    fn a_failed_merge_whose_round_needed_a_repair_retries_on_the_same_head() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                base_conflicts: script([false, true]),
                watches: script([Is::Passed, Is::Passed]),
                merges: script([Some("not mergeable"), None]),
                ..Script::default()
            },
        );

        delivered.unwrap();
        assert_eq!(
            lines(&did),
            [
                "merging the PR into main",
                "the merge failed: not mergeable",
                "conflict; starting Repair 1 of 5",
                "merging the PR into main",
            ]
        );
        assert_eq!(did.last(), Some(&Did::Merge("h1".to_string())));
    }

    #[test]
    fn an_interrupt_before_the_merge_fails_as_interrupted() {
        let (delivered, did) = deliver(
            Goal::Merged,
            Script {
                heads: script(["h1"]),
                watches: script([Is::Passed]),
                interrupted: true,
                ..Script::default()
            },
        );

        assert_eq!(cause(delivered), "interrupted");
        assert_eq!(did, [round("h1").as_slice(), &[Did::CheckPr]].concat());
    }

    #[test]
    fn repairs_of_every_kind_share_one_cap_and_the_one_too_many_names_its_cause() {
        let mut budgets = Budgets::default();
        for n in 1..=MAX_REPAIRS {
            let cause = if n % 2 == 0 { "conflict" } else { "CI red" };
            assert_eq!(
                budgets.next_repair(cause).unwrap(),
                (
                    format!("repair-{n}"),
                    format!("{cause}; starting Repair {n} of {MAX_REPAIRS}")
                )
            );
        }

        for cause in ["new commits on origin/issue-7 to review", "conflict"] {
            let error = budgets.next_repair(cause).unwrap_err();
            assert_eq!(error.to_string(), format!("repairs exhausted: {cause}"));
        }
        assert_eq!(budgets.repairs, MAX_REPAIRS);
    }

    #[test]
    fn upstream_moves_of_the_base_or_the_issue_branch_share_one_budget() {
        let mut budgets = Budgets::default();
        for _ in 1..MAX_UPSTREAM_MOVES {
            assert_eq!(
                budgets.count_base_move("main", "while CI ran").unwrap(),
                "origin/main moved while CI ran; merging it again"
            );
        }
        assert_eq!(
            budgets.count_foreign_commits("origin/issue-7").unwrap(),
            "origin/issue-7 has new commits; merging them in"
        );

        let error = budgets.count_base_move("main", "while CI ran").unwrap_err();
        assert_eq!(
            error.to_string(),
            format!("origin/main kept moving: merged it again {MAX_UPSTREAM_MOVES} times")
        );
        let error = budgets.count_foreign_commits("origin/issue-7").unwrap_err();
        assert_eq!(
            error.to_string(),
            format!("origin/issue-7 kept moving: merged it again {MAX_UPSTREAM_MOVES} times")
        );
    }

    #[test]
    fn the_repair_cap_and_the_upstream_move_budget_are_spent_apart() {
        let mut budgets = Budgets::default();
        for _ in 0..MAX_REPAIRS {
            budgets.next_repair("CI red").unwrap();
        }

        for _ in 0..MAX_UPSTREAM_MOVES {
            budgets.count_base_move("main", "while CI ran").unwrap();
        }
        assert_eq!(
            budgets,
            Budgets {
                repairs: MAX_REPAIRS,
                upstream_moves: MAX_UPSTREAM_MOVES
            }
        );
    }
}