thirdshift 0.22.0

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
//! Delivery: publication and recovery shared by Process Steps and the Spec PR.
//! The Ticket and Spec runs' Process files own their sequences, sharing the push,
//! marking the pull request ready, the Repair loop that keeps it mergeable
//! and green, the Self-merge in a Merge run and its steps after the merge,
//! and the Failed run path when any of these fails.
//!
//! Its steps reach the worktree, the sessions, the Repair loop, GitHub, the
//! interrupt and the progress lines only through [`Outside`], and the Failed
//! run path, which runs once the sessions have ended, only through
//! [`FailedOutside`]: [`InWorktree`] and [`OnFailure`] do each for real;
//! `Scripted`, in tests, from a script, recording each call.

use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use chrono::{DateTime, Utc};

mod repair_loop;
mod stage;

pub(crate) use repair_loop::MAX_REPAIRS;

/// Tightening policies inherited by dispatched Runs and their child Tickets.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Limits {
    pub repair_cap: usize,
    pub protected_paths: Vec<String>,
}

impl Default for Limits {
    fn default() -> Self {
        Self {
            repair_cap: MAX_REPAIRS,
            protected_paths: Vec::new(),
        }
    }
}

use crate::pull_request::{AlreadyMerged, Identified, MergeAttempt, PullRequest};

use crate::base_fix::{self, BaseFix};
use crate::child_run::ChildAsks;
use crate::ci::{self, Ci, FailedChecks};
use crate::failed_run::{FailedRun, interrupted_or, is_hold};
use crate::git::Git;
use crate::github::GitHub;
use crate::harness::Choice;
use crate::interrupt;
use crate::issue::IssueUrl;
use crate::processes::builtin::Step;
use crate::progress;
use crate::prompt;
use crate::recovery::{self, Preservation, Recovery};
use crate::run::{Goal, Reached, Resolution};
use crate::run_ending::Cause;
use crate::security::review::{Hold as SecurityHold, Outcome as SecurityOutcome, step};
use crate::session::{Kind, Logs, Sessions};
use crate::skills;
use crate::trust::{self, IssueText};
use crate::worktree::{ForeignCommits, Merge, PendingMerge, Preserved, Worktree};

use repair_loop::{Repair, Upstream};
use stage::{CommandLog, CommandRecord, Stage, Tracker};
/// A Delivery of the pull request for `issue`, the Run's issue or the Spec,
/// into the Base branch `base`, to `goal`.
pub struct Delivery<'a> {
    /// Whether the opening session is followed by a guidance Security review.
    pub security_review: bool,
    /// What the Run hands on to every child Run, a Base fix or a Ticket's
    /// Run, whose Harness, Model and Effort its own sessions run on too.
    pub child_asks: &'a ChildAsks,
    pub issue: &'a IssueUrl,
    pub base: &'a str,
    pub goal: Goal,
    /// The one Base fix the Delivery may start, or wait on, when its only red
    /// checks are Inherited failures.
    pub base_fix: &'a mut BaseFix,
    /// Where its Session traces go.
    pub logs: &'a Logs,
    /// When the Run began: an untrusted edit to `issue` made since then
    /// starts no further session.
    pub started: DateTime<Utc>,
    /// The most Repair sessions this Delivery starts. A Ticket run uses
    /// [`MAX_REPAIRS`]. A Custom process may set a lower cap.
    pub repair_cap: usize,
    /// Globs checked against the change before a Self-merge. A match holds
    /// the merge. Empty for a Ticket run.
    pub protected_paths: &'a [String],
}

/// The session a Delivery opens with, given its prompt.
pub struct Opening {
    pub session: OpeningSession,
    pub prompt: String,
}

/// Which session a Delivery opens with.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum OpeningSession {
    /// A Run's implement session.
    Implementation,
    /// A bug Ticket run diagnoses before implementing, and may need information.
    BugDiagnosis,
    /// A Spec run's Spec review, once its Tickets have landed.
    SpecReview,
}

impl OpeningSession {
    /// The session's kind.
    pub fn kind(self) -> Kind {
        match self {
            Self::Implementation | Self::BugDiagnosis => Kind::Implementation,
            Self::SpecReview => Kind::SpecReview,
        }
    }

    fn stage(self) -> Stage {
        match self {
            Self::Implementation | Self::BugDiagnosis => Stage::Implementation,
            Self::SpecReview => Stage::SpecReview,
        }
    }
}

impl Delivery<'_> {
    /// A newly authored Base branch repair has no issue or adopted PR head.
    /// Its opening session shares Delivery's failure preservation and merge gates.
    pub(crate) fn base_ci_fix(
        self,
        worktree: Worktree,
        pull_request: &mut PullRequest,
        title: &str,
        failed: &[crate::github::Check],
    ) -> Result<Reached, FailedRun> {
        let context = RepairContext::BaseBranch(self.base);
        let body = format!(
            "Repairs CI on `{}`.\n\n{}",
            self.base,
            ci::description_check_list(failed)
        );
        let mut outcome = self.fix_with(
            worktree,
            pull_request,
            context,
            Stage::RepairSession,
            |outside, goal| {
                let worktree = outside.worktree;
                outside.session(
                    Kind::Implementation,
                    &prompt::base_ci_fix(outside.base, worktree.branch(), failed),
                )?;
                outside.push()?;
                outside.pull_request.open_if_absent(title, &body)?;
                let identified = outside
                    .pull_request
                    .info()
                    .context("Base CI fix has no PR")?;
                let pr = crate::review::PullRequestUrl::parse(&identified.url)?;
                let _held =
                    crate::review::Reservation::take(worktree.launch(), &GitHub::new(), &pr)?
                        .context("Base CI fix PR is already reserved")?;
                crate::logs::pull_request(&pr.url);
                outside.write_built_with(&outside.child_asks.harness.clone())?;
                outside.stage(Stage::PullRequestReadiness);
                outside.mark_pr_ready(None)?;
                outside.take_to_goal(&pr.url, goal)?;
                if goal == Goal::Merged {
                    delete_branch_after_merge(outside, worktree.branch());
                }
                Ok(Resolution::PullRequest { url: pr.url, goal })
            },
        );
        // The opening session can fail before normal publication. Preservation
        // has already pushed its work; give that attempt a draft and Recovery
        // identity so later Passes do not start it from the Base branch again.
        if let Err(failed) = &mut outcome
            && pull_request.info().is_none()
        {
            if let Err(error) = pull_request.open_failed_fix(title, &body) {
                progress::warn(
                    &error,
                    format_args!("could not open the failed Base CI repair as a draft"),
                );
            }
            if let Some(pr) = pull_request.info() {
                crate::logs::pull_request(&pr.url);
                failed.pr_url = Some(pr.url);
            }
        }
        outcome
    }

    /// An existing PR enters Delivery directly; no implementation or initial
    /// review runs, and closing-issue context is refreshed before every Repair.
    pub fn fix_run(
        self,
        worktree: Worktree,
        pull_request: &mut PullRequest,
        pr: &crate::review::PullRequestUrl,
        steps: Vec<Step>,
    ) -> Result<Reached, FailedRun> {
        if !matches!(steps.as_slice(), [Step::Delivery, Step::SelfMerge]) {
            return Err(anyhow::anyhow!("fix-run must deliver then self-merge").into());
        }
        let context = RepairContext::PullRequest(pr);
        let started = self.started;
        self.fix_with(
            worktree,
            pull_request,
            context,
            Stage::Push,
            |outside, goal| {
                let worktree = outside.worktree;
                hand_over_pull_request(
                    pr,
                    outside.base,
                    worktree.branch(),
                    worktree.path(),
                    false,
                    started,
                )?;
                outside.push()?;
                outside.stage(Stage::PullRequestReadiness);
                let pr = outside.mark_pr_ready(None)?;
                outside.take_to_goal(&pr.url, goal)?;
                if goal == Goal::Merged {
                    delete_branch_after_merge(outside, worktree.branch());
                }
                Ok(Resolution::PullRequest { url: pr.url, goal })
            },
        )
    }

    /// Fix entry points share checked sessions, failure preservation, adapters
    /// and completion accounting while retaining their own opening steps.
    fn fix_with(
        self,
        worktree: Worktree,
        pull_request: &mut PullRequest,
        context: RepairContext<'_>,
        first: Stage,
        steps: impl FnOnce(&mut InWorktree<'_>, Goal) -> Result<Resolution>,
    ) -> Result<Reached, FailedRun> {
        let tracker = Tracker::new(first, CommandLog);
        run_checked(
            CheckedRun {
                logs: self.logs,
                started: self.started,
                harness: &self.child_asks.harness,
                security_review: None,
                security_review_default: None,
                base: self.base,
                context,
            },
            worktree.for_fix_run(),
            pull_request,
            &tracker,
            |resolution, log| Reached {
                resolution,
                log,
                ticket_lines: Vec::new(),
            },
            |merged, log| Reached {
                resolution: Resolution::PullRequest {
                    url: merged.pr.url.clone(),
                    goal: Goal::Merged,
                },
                log,
                ticket_lines: Vec::new(),
            },
            |tracker, worktree, pull_request, sessions| {
                let mut outside = InWorktree {
                    tracker,
                    issue: self.issue,
                    worktree,
                    base: self.base,
                    base_fix: self.base_fix,
                    child_asks: self.child_asks,
                    sessions,
                    pull_request,
                    repair_cap: self.repair_cap,
                    protected_paths: self.protected_paths,
                    context,
                };
                steps(&mut outside, self.goal)
            },
        )
    }

    /// Take the Spec PR from the branch checked out in `worktree` to the
    /// goal. First fast-forward the branch to origin.
    /// Then run the Spec review and optional Security
    /// review, push the branch, for
    /// any commit the session left unpushed, write the line that says what it
    /// was built with in the pull request's body, only warning if that fails,
    /// restore the optional Tickets checklist, and mark the pull request ready,
    /// failing unless it exists, is open and targets the Base branch. Then keep it mergeable
    /// and its CI green through the Repair loop, and for [`Goal::Merged`],
    /// Self-merge it. 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`. Any failure goes through the Failed
    /// run path, which keeps the worktree if its work did not reach origin;
    /// otherwise it is cleaned up when this returns. A gate observing an
    /// already merged PR completes as merged only if that head includes all
    /// local work; no further publication or PR mutations are performed.
    pub fn spec_review(
        self,
        worktree: Worktree,
        prompt: String,
        pull_request: &mut PullRequest,
        checklist: &str,
        steps: Vec<Step>,
    ) -> Result<Reached, FailedRun> {
        self.deliver_steps(
            worktree,
            Opening {
                session: OpeningSession::SpecReview,
                prompt,
            },
            pull_request,
            Some(checklist),
            steps,
        )
    }

    /// Execute the compiled Ticket process inside the same checked session
    /// and Failed ticket run lifecycle as the original Ticket run.
    pub fn ticket_run(
        self,
        worktree: Worktree,
        opening: Opening,
        pull_request: &mut PullRequest,
    ) -> Result<Reached, FailedRun> {
        let steps = crate::processes::ticket::steps()?;
        self.deliver_steps(worktree, opening, pull_request, None, steps)
    }

    fn deliver_steps(
        self,
        worktree: Worktree,
        opening: Opening,
        pull_request: &mut PullRequest,
        checklist: Option<&str>,
        steps: Vec<Step>,
    ) -> Result<Reached, FailedRun> {
        let tracker = Tracker::new(opening.session.stage(), CommandLog);
        let logs = self.logs;
        let issue = self.issue;
        let started = self.started;
        let base = self.base;
        let goal = self.goal;
        let security_review = self.security_review;
        let repair_cap = self.repair_cap;
        let protected_paths = self.protected_paths;
        let child_asks = self.child_asks;
        let base_fix = self.base_fix;
        let context = RepairContext::Issue(issue);
        run_checked(
            CheckedRun {
                logs,
                started,
                harness: &child_asks.harness,
                security_review: child_asks.security_review_harness.as_ref(),
                security_review_default: child_asks.security_review_default.as_ref(),
                base,
                context,
            },
            worktree,
            pull_request,
            &tracker,
            |resolution, log| Reached {
                resolution,
                log,
                ticket_lines: Vec::new(),
            },
            |merged, log| Reached {
                resolution: Resolution::PullRequest {
                    url: merged.pr.url.clone(),
                    goal: Goal::Merged,
                },
                log,
                ticket_lines: Vec::new(),
            },
            |tracker, worktree, pull_request, sessions| {
                let route = Route {
                    security_review,
                    issue,
                    base,
                    branch: worktree.branch(),
                    goal,
                    harness: &child_asks.harness,
                };
                let mut outside = InWorktree {
                    tracker,
                    issue,
                    worktree,
                    base,
                    base_fix,
                    child_asks,
                    sessions,
                    pull_request,
                    repair_cap,
                    protected_paths,
                    context,
                };
                route.process_steps(&mut outside, &opening, steps, checklist)
            },
        )
    }

    /// Publish the Issue branch already produced by a Custom process. There
    /// is no opening or Security review session: the Process's Steps did
    /// the work. Carry their review outcome into readiness and Self-merge.
    /// Push, open a draft pull request when the branch has none,
    /// write the Built-with line, mark it ready, and keep it mergeable and
    /// its CI green through the Repair loop. For [`Goal::Merged`], Self-merge
    /// it, unless a protected path holds that merge. Repairs run on
    /// [`Delivery::child_asks`]'s Harness, up to [`Delivery::repair_cap`].
    /// Any failure goes through the Failed run path.
    pub fn publish(
        self,
        worktree: Worktree,
        pull_request: &mut PullRequest,
        reviews: &[SecurityOutcome],
        checklist: Option<&str>,
    ) -> Result<String, FailedRun> {
        let tracker = Tracker::new(Stage::Push, CommandLog);
        let logs = self.logs;
        let issue = self.issue;
        let started = self.started;
        let base = self.base;
        let goal = self.goal;
        let repair_cap = self.repair_cap;
        let protected_paths = self.protected_paths;
        let child_asks = self.child_asks;
        let base_fix = self.base_fix;
        let context = RepairContext::Issue(issue);
        run_checked(
            CheckedRun {
                logs,
                started,
                harness: &child_asks.harness,
                security_review: child_asks.security_review_harness.as_ref(),
                security_review_default: child_asks.security_review_default.as_ref(),
                base,
                context,
            },
            worktree,
            pull_request,
            &tracker,
            |url, _log| url,
            |merged, _log| merged.pr.url.clone(),
            |tracker, worktree, pull_request, sessions| {
                publish_steps(
                    &mut InWorktree {
                        tracker,
                        issue,
                        worktree,
                        base,
                        base_fix,
                        child_asks,
                        sessions,
                        pull_request,
                        repair_cap,
                        protected_paths,
                        context,
                    },
                    goal,
                    reviews,
                    checklist,
                )
            },
        )
    }
}

/// One context choice follows Delivery through session refresh and Repairs.
#[derive(Clone, Copy)]
enum RepairContext<'a> {
    Issue(&'a IssueUrl),
    PullRequest(&'a crate::review::PullRequestUrl),
    BaseBranch(&'a str),
}

impl<'a> RepairContext<'a> {
    fn subject(self) -> prompt::RepairSubject<'a> {
        match self {
            Self::Issue(issue) => prompt::RepairSubject::Issue(issue),
            Self::PullRequest(pr) => prompt::RepairSubject::PullRequest(&pr.url),
            Self::BaseBranch(base) => prompt::RepairSubject::BaseBranch(base),
        }
    }
}

/// What the shared Delivery envelope checks before each session and names
/// when a failure preserves the work: the issue, when the run began, where
/// its sessions are logged, the harnesses they run on, and the Base branch.
struct CheckedRun<'a> {
    context: RepairContext<'a>,
    logs: &'a Logs,
    started: DateTime<Utc>,
    harness: &'a Choice,
    security_review: Option<&'a Choice>,
    security_review_default: Option<&'a Choice>,
    base: &'a str,
}

/// The shared Delivery envelope: check for an untrusted edit before each
/// session, run `steps`, and on failure either accept an already-merged pull
/// request whose head includes the local work or take the Failed run path.
fn run_checked<T, S>(
    checked: CheckedRun<'_>,
    worktree: Worktree,
    pull_request: &mut PullRequest,
    tracker: &Tracker,
    on_ok: impl FnOnce(T, Option<PathBuf>) -> S,
    on_merged: impl FnOnce(&AlreadyMerged, Option<PathBuf>) -> S,
    steps: impl FnOnce(&Tracker, &Worktree, &mut PullRequest, &Sessions) -> Result<T>,
) -> Result<S, FailedRun> {
    let CheckedRun {
        logs,
        started,
        harness,
        security_review,
        security_review_default,
        base,
        context,
    } = checked;
    pull_request.begin_delivery();
    let path = worktree.path().to_path_buf();
    let branch = worktree.branch().to_string();
    let before_each = move || match context {
        RepairContext::PullRequest(pr) => {
            hand_over_pull_request(pr, base, &branch, &path, true, started)
        }
        RepairContext::Issue(issue) => {
            no_untrusted_edit_since(issue, started, "Ticket run")?;
            hand_over_issue(issue, &path)
        }
        RepairContext::BaseBranch(_) => Ok(()),
    };
    let (delivered, log) = Sessions::checked_within(
        logs,
        worktree.path(),
        harness,
        security_review,
        security_review_default,
        &before_each,
        |sessions| steps(tracker, &worktree, pull_request, sessions),
    );
    let result = match delivered {
        Ok(value) => Ok(on_ok(value, log)),
        Err(error) => {
            if let Some(merged) = error.downcast_ref::<AlreadyMerged>()
                && worktree.fully_landed_at(&merged.head).unwrap_or(false)
            {
                progress::step("the pull request was merged while Delivery was running");
                Ok(on_merged(merged, log))
            } else {
                let stopped_at = stopped_at(tracker, &error);
                let path = worktree.path().to_path_buf();
                let mut outside = OnFailure {
                    base,
                    worktree,
                    pull_request,
                };
                Err(fail(&mut outside, stopped_at, path, log, error))
            }
        }
    };
    crate::logs::unaddressed_findings(pull_request.unaddressed_findings());
    result
}

/// [`Delivery::publish`]'s steps: push, open a draft when none exists, write
/// what it was built with, mark the pull request ready, and take it to `goal`
/// through the Repair loop. A merged goal then deletes the branch and closes
/// the issue, as a Ticket run's Self-merge does.
fn publish_steps(
    outside: &mut InWorktree<'_>,
    goal: Goal,
    reviews: &[SecurityOutcome],
    checklist: Option<&str>,
) -> Result<String> {
    outside.tracker.enter(Stage::Push);
    outside.pull_request.ensure_actionable(false)?;
    outside
        .worktree
        .push_if_actionable(&mut || outside.pull_request.ensure_actionable(false))?;
    let title = GitHub::new().issue_title(outside.issue)?;
    let body = format!("Closes #{}", outside.issue.number);
    outside.pull_request.open_if_absent(&title, &body)?;
    if let Err(error) = outside
        .pull_request
        .write_built_with(&outside.child_asks.harness)
    {
        progress::warn(
            &error,
            format_args!("could not write the Built-with line in the pull request's body"),
        );
    }
    outside.tracker.enter(Stage::PullRequestReadiness);
    let pr = outside.pull_request.mark_ready(checklist)?;
    take_reviewed_to_goal(outside, &pr.url, goal, reviews)?;
    if goal == Goal::Merged {
        let branch = outside.worktree.branch().to_string();
        Route {
            security_review: false,
            issue: outside.issue,
            base: outside.base,
            branch: &branch,
            goal,
            harness: &outside.child_asks.harness,
        }
        .after_merge(outside, &pr);
    }
    Ok(pr.url)
}

/// The steps of a Delivery of the pull request for `issue`, from `branch`
/// into the Base branch `base`, to `goal`, its sessions run on `harness`.
struct Route<'a> {
    security_review: bool,
    issue: &'a IssueUrl,
    base: &'a str,
    branch: &'a str,
    goal: Goal,
    harness: &'a Choice,
}

impl Route<'_> {
    /// The file supplies the sequence. Delivery and its adjacent Self-merge
    /// share one Repair loop, just as in a Custom process.
    fn process_steps(
        &self,
        outside: &mut impl Outside,
        opening: &Opening,
        steps: Vec<Step>,
        checklist: Option<&str>,
    ) -> Result<Resolution> {
        let mut steps = steps.into_iter().peekable();
        let mut review = None;
        let mut resolution = None;
        while let Some(step) = steps.next() {
            match step {
                Step::Implement => {
                    if let Some(early) = self.implement(outside, opening)? {
                        return Ok(early);
                    }
                }
                Step::SpecReview => {
                    outside.catch_up()?;
                    outside.stage(Stage::SpecReview);
                    outside.session(Kind::SpecReview, &opening.prompt)?;
                }
                Step::SecurityReview => review = self.review(outside)?,
                Step::Delivery => {
                    let goal = if matches!(steps.peek(), Some(Step::SelfMerge)) {
                        steps.next();
                        self.goal
                    } else {
                        Goal::ReadyForReview
                    };
                    let pr = self.publish(outside, checklist)?;
                    resolution = Some(self.finish(outside, pr, goal, review.as_slice())?);
                }
                Step::SelfMerge => anyhow::bail!("self-merge must directly follow delivery"),
            }
        }
        resolution.context("Built-in process ended without delivery")
    }

    fn implement(
        &self,
        outside: &mut impl Outside,
        opening: &Opening,
    ) -> Result<Option<Resolution>> {
        let session = opening.session;
        outside.stage(session.stage());
        if let crate::implement::Completed::NotReproduced(comment_url) =
            crate::implement::run(self.issue, opening, |prompt| {
                outside.session(session.kind(), prompt)
            })?
        {
            outside.confirm_needs_info()?;
            return Ok(Some(Resolution::NotReproduced { comment_url }));
        }
        Ok(None)
    }

    fn review(&self, outside: &mut impl Outside) -> Result<Option<SecurityOutcome>> {
        self.security_review
            .then(|| {
                outside.stage(Stage::SecurityReview);
                outside.security_review(&prompt::security_review(
                    self.issue,
                    self.base,
                    self.branch,
                ))
            })
            .transpose()
    }

    fn publish(&self, outside: &mut impl Outside, checklist: Option<&str>) -> Result<Identified> {
        outside.stage(Stage::Push);
        outside.push()?;
        self.write_built_with(outside);
        outside.stage(Stage::PullRequestReadiness);
        outside.mark_pr_ready(checklist)
    }

    fn finish(
        &self,
        outside: &mut impl Outside,
        pr: Identified,
        goal: Goal,
        reviews: &[SecurityOutcome],
    ) -> Result<Resolution> {
        take_reviewed_to_goal(outside, &pr.url, goal, reviews)?;
        if goal == Goal::Merged {
            self.after_merge(outside, &pr);
        }
        Ok(Resolution::PullRequest { url: pr.url, goal })
    }

    /// Write the line that says the pull request was built with the Harness
    /// in its body, in place of any thirdshift wrote there before, only
    /// warning if that fails, as the work is done without it. Nothing if
    /// there is no pull request: marking it ready says so.
    fn write_built_with(&self, outside: &mut impl Outside) {
        if let Err(error) = outside.write_built_with(self.harness) {
            outside.warn(
                &error,
                "could not write the Built-with line in the pull request's body".into(),
            );
        }
    }

    /// The Self-merge's steps after the merge of `pr`: delete the Issue
    /// branch on origin, and close the issue unless it is closed already.
    /// GitHub may close it too, a moment after the merge, or may not, so
    /// thirdshift does not wait to see. The merge can't be undone, so these
    /// never fail the Run, and an interrupt no longer stops it: a step that
    /// fails is tried once more if an interrupt was requested, then is a
    /// warning naming the fix to make by hand.
    fn after_merge(&self, outside: &mut impl Outside, pr: &Identified) {
        delete_branch_after_merge(outside, self.branch);
        let comment = format!(
            "Closed by #{}, merged into {} by a thirdshift Ticket run with Self-merge.",
            pr.number, self.base
        );
        if let Err(error) = retry_if_interrupted(outside, |outside| {
            self.close_unless_closed(outside, &comment)
        }) {
            let issue = self.issue;
            outside.warn(
                &error,
                format!(
                    "could not close issue #{number} ({url}), so if it is still open, close it by hand: \
                     gh issue close {number} --repo {repo} --comment '{quoted}'",
                    number = issue.number,
                    url = issue.url,
                    repo = issue.repo_slug(),
                    quoted = comment.replace('\'', r"'\''")
                ),
            );
        }
    }

    /// Close the issue with `comment`, unless it is closed already.
    fn close_unless_closed(&self, outside: &mut impl Outside, comment: &str) -> Result<()> {
        if !outside.issue_is_open()? {
            return Ok(());
        }
        outside.step(format!("closing issue #{}", self.issue.number));
        outside.close_issue(comment)
    }
}

fn delete_branch_after_merge(outside: &mut impl Outside, branch: &str) {
    if let Err(error) = retry_if_interrupted(outside, |outside| outside.delete_branch()) {
        outside.warn(
            &error,
            format!("could not delete {branch} on origin, so delete it by hand: git push origin --delete {branch}"),
        );
    }
}

/// Run `step` through `outside`, and once more if it failed with an
/// interrupt requested: Ctrl-C in a terminal also kills the git or gh the
/// step was running.
fn retry_if_interrupted<O: Outside>(
    outside: &mut O,
    step: impl Fn(&mut O) -> Result<()>,
) -> Result<()> {
    match step(outside) {
        Err(_) if outside.interrupted() => step(outside),
        done => done,
    }
}

/// Take the Run down the Failed run path through `outside`, once its
/// sessions have ended with `error`: commit and push the work, and send an
/// open PR back to draft. An interrupt, if one was requested, is the error
/// instead: it can surface as some other error, such as a killed git. A
/// `PolicyRefusal`, `SecurityHold` or `MergeHold` neither pushes nor converts, so the PR stays ready on the
/// head whose CI was watched. Problems along the way are reported, not
/// raised, so the error is what the Run fails with. Worktree owns preservation
/// and retains work that may not have reached origin. `log` is the most recent
/// Session trace, if a session created one, which the Failed run reports unless
/// the error is a Security hold with its review's own Session trace: a hold is
/// raised only after the Repair loop, whose sessions may have run since.
/// `stopped_at` is the stage its recovery lines report; `worktree`, where work
/// preserved only locally is.
fn fail(
    outside: &mut impl FailedOutside,
    stopped_at: recovery::Stage,
    worktree: PathBuf,
    log: Option<PathBuf>,
    error: anyhow::Error,
) -> FailedRun {
    let interrupted = outside.interrupted();
    let error = interrupted_or(error, interrupted);
    // The cause as stderr gives it, down to what a session left running, cut
    // to its first line: the reason goes in the failure commit's subject.
    let reason = Cause::of(&error).first_line().to_string();
    // Everything is already on origin: the Repair loop pushed the head.
    let keep_ready = is_hold(&error);
    let log = error
        .downcast_ref::<SecurityHold>()
        .and_then(SecurityHold::log)
        .map(Path::to_path_buf)
        .or(log);
    let preservation = if keep_ready {
        Preservation::Remote
    } else {
        let preserved = outside.preserve_failed_run(&reason);
        recovery::preservation_of(preserved, |line| outside.step(line))
    };
    let pr_url = match outside.finish_pr(keep_ready) {
        Ok(pr_url) => pr_url,
        Err(problem) => {
            outside.step(format!("could not convert the PR to a draft: {problem:#}"));
            None
        }
    };
    let mut recovery = Recovery::new(stopped_at, preservation);
    recovery.record_worktree(worktree);
    FailedRun {
        recovery: Some(Box::new(recovery)),
        error,
        pr_url,
        log,
        interrupted,
        ticket_lines: Vec::new(),
    }
}

/// The stage a Delivery that failed with `error` stopped at, from
/// `tracker`: its Security review if the error is a Security hold, found once
/// the pull request was ready.
fn stopped_at(tracker: &Tracker<impl CommandRecord>, error: &anyhow::Error) -> recovery::Stage {
    if error.is::<SecurityHold>() {
        tracker.stop_at_security_review();
    }
    tracker.stopped_at()
}

/// Every review's public outcome reaches the PR. Any Security hold prevents
/// Self-merge, while readiness still includes repairing conflicts and CI.
fn take_reviewed_to_goal(
    outside: &mut impl Outside,
    pr_url: &str,
    goal: Goal,
    reviews: &[SecurityOutcome],
) -> Result<()> {
    let entry = reviews
        .iter()
        .map(SecurityOutcome::entry)
        .collect::<Vec<_>>()
        .join("\n");
    if !reviews.is_empty()
        && let Err(error) = outside.record_security_review(&entry)
    {
        outside.warn(
            &error,
            "could not write the Security review outcome in the pull request's body".to_string(),
        );
    }
    let hold = reviews.iter().find_map(SecurityOutcome::hold);
    outside.take_to_goal(
        pr_url,
        if hold.is_some() {
            Goal::ReadyForReview
        } else {
            goal
        },
    )?;
    if let Some(hold) = hold {
        outside.step(hold.to_string());
        if goal == Goal::Merged {
            return Err(hold.into());
        }
    }
    Ok(())
}

/// What a Delivery's steps do or read outside the Delivery, within its
/// sessions' scope.
trait Outside {
    /// Enter `stage`, before the step it names.
    fn stage(&mut self, stage: Stage);
    /// Fast-forward the Issue branch to its head on origin.
    fn catch_up(&mut self) -> Result<()>;
    /// Run a session of `kind` given `prompt`.
    fn session(&mut self, kind: Kind, prompt: &str) -> Result<Option<String>>;
    fn confirm_needs_info(&mut self) -> Result<()>;
    /// Run the Security review given `prompt`, with its Session trace, its
    /// Resume's if it got one, if it started a session.
    fn security_review(&mut self, prompt: &str) -> Result<SecurityOutcome>;
    fn record_security_review(&mut self, entry: &str) -> Result<()>;
    /// Push the Issue branch.
    fn push(&mut self) -> Result<()>;
    /// Write the annotation through the captured pull request module.
    fn write_built_with(&mut self, choice: &Choice) -> Result<()>;
    /// Validate and mark the captured pull request ready.
    fn mark_pr_ready(&mut self, checklist: Option<&str>) -> Result<Identified>;
    /// Take the ready pull request at `pr_url` to `goal` through the Repair
    /// loop.
    fn take_to_goal(&mut self, pr_url: &str, goal: Goal) -> Result<()>;
    /// Delete the Issue branch on origin.
    fn delete_branch(&mut self) -> Result<()>;
    /// Whether the issue is open.
    fn issue_is_open(&mut self) -> Result<bool>;
    /// Close the issue with `comment`.
    fn close_issue(&mut self, comment: &str) -> Result<()>;
    /// Whether an interrupt was requested.
    fn interrupted(&mut self) -> bool;
    /// Hand on the progress line `line`.
    fn step(&mut self, line: String);
    /// Hand on `error`, then the warning `warning` saying what to do about it
    /// by hand.
    fn warn(&mut self, error: &anyhow::Error, warning: String);
}

/// What the Failed run path does or reads outside the Delivery, once its
/// sessions have ended.
trait FailedOutside {
    /// Preserve the Failed run's work for `reason`, retaining it locally if
    /// preservation fails.
    fn preserve_failed_run(&mut self, reason: &str) -> Result<Preserved>;
    /// Finish the captured PR through completion operations after preservation.
    fn finish_pr(&mut self, keep_ready: bool) -> Result<Option<String>>;
    /// Whether an interrupt was requested.
    fn interrupted(&mut self) -> bool;
    /// Hand on the progress line `line`.
    fn step(&mut self, line: String);
}

/// Fail with [`UntrustedEdit`] if `issue` has had an edit to its body or
/// title, since its Run `started`, by an account that is not a Trusted
/// account: a session started now would work from text no Trusted account
/// wrote.
pub(crate) fn no_untrusted_edit_since(
    issue: &IssueUrl,
    started: DateTime<Utc>,
    run_name: &'static str,
) -> Result<()> {
    match trust::untrusted_edit(&GitHub::new(), issue, Some(started))? {
        Some(text) => Err(UntrustedEdit {
            number: issue.number,
            text,
            run_name,
        }
        .into()),
        None => Ok(()),
    }
}

/// Write `issue` to [`prompt::ISSUE_FILE`] in `worktree`, kept out of git,
/// for the session about to start to work from: its title, its body and only
/// the comments of Trusted accounts, as [`GitHub::issue_for_session`] gives
/// them. Written again before each session, so each has the latest.
pub(crate) fn hand_over_issue(issue: &IssueUrl, worktree: &Path) -> Result<()> {
    skills::exclude(&Git::new(worktree), &format!("/{}", prompt::ISSUE_FILE))?;
    let text = GitHub::new().issue_for_session(issue)?;
    let path = worktree.join(prompt::ISSUE_FILE);
    fs::write(&path, text).with_context(|| format!("could not write {}", path.display()))
}

fn hand_over_pull_request(
    pr: &crate::review::PullRequestUrl,
    base: &str,
    branch: &str,
    worktree: &Path,
    ready: bool,
    started: DateTime<Utc>,
) -> Result<()> {
    let github = GitHub::new();
    let snapshot = github.fix_pull_request(pr)?;
    anyhow::ensure!(
        snapshot.base == base && snapshot.branch == branch,
        "pull request changed during Fix run"
    );
    if ready {
        let current = github
            .pr_snapshot(&pr.issue, &pr.url)?
            .context("pull request disappeared during Fix run")?;
        anyhow::ensure!(
            !current.pr.is_draft,
            "pull request became draft during Fix run"
        );
    }
    let input = github.review_input(pr, &snapshot)?;
    // The Repair session works from these issues and can push. Stop before
    // writing them when an untrusted account has edited one since the run
    // started, the same gate a Ticket run applies to its own issue.
    for issue in &input.closing_issues {
        no_untrusted_edit_since(issue, started, "Fix run")?;
    }
    skills::exclude(&Git::new(worktree), "/.thirdshift-review-input.md")?;
    crate::processes::review::write_review_input(
        &worktree.join(".thirdshift-review-input.md"),
        &input.markdown,
    )
}

/// Issue `number`'s `text` was edited during its Run by an account that is
/// not a Trusted account, so the Run starts no further session.
#[derive(Debug)]
pub(crate) struct UntrustedEdit {
    number: u64,
    text: IssueText,
    run_name: &'static str,
}

impl std::fmt::Display for UntrustedEdit {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "#{} {} edited since the {} started by an account that is not a Trusted account; starting no further session",
            self.number, self.text, self.run_name
        )
    }
}

impl std::error::Error for UntrustedEdit {}

/// A Delivery's worktree, its sessions, its Base fix, and its issue and pull
/// request on GitHub.
struct InWorktree<'a> {
    context: RepairContext<'a>,
    tracker: &'a Tracker,
    issue: &'a IssueUrl,
    worktree: &'a Worktree,
    base: &'a str,
    base_fix: &'a mut BaseFix,
    /// What a Base fix it starts is handed.
    child_asks: &'a ChildAsks,
    sessions: &'a Sessions<'a>,
    pull_request: &'a mut PullRequest,
    repair_cap: usize,
    protected_paths: &'a [String],
}

impl Outside for InWorktree<'_> {
    fn stage(&mut self, stage: Stage) {
        self.tracker.enter(stage);
    }

    fn catch_up(&mut self) -> Result<()> {
        self.worktree.fast_forward_to_origin()
    }

    fn session(&mut self, kind: Kind, prompt: &str) -> Result<Option<String>> {
        let final_message = self.sessions.run(kind, prompt)?;
        self.pull_request.ensure_actionable(false)?;
        Ok(final_message)
    }

    fn confirm_needs_info(&mut self) -> Result<()> {
        crate::implement::confirm_needs_info(&GitHub::new().issue_labels(self.issue)?)
    }

    fn security_review(&mut self, prompt: &str) -> Result<SecurityOutcome> {
        step::Step {
            sessions: self.sessions,
            worktree: self.worktree,
            issue: self.issue,
            base: self.base,
        }
        .run(self.pull_request, prompt)
    }

    fn record_security_review(&mut self, entry: &str) -> Result<()> {
        self.pull_request.record_security_review(entry)
    }

    fn push(&mut self) -> Result<()> {
        self.pull_request.ensure_actionable(false)?;
        self.worktree
            .push_if_actionable(&mut || self.pull_request.ensure_actionable(false))
    }

    fn write_built_with(&mut self, choice: &Choice) -> Result<()> {
        self.pull_request.write_built_with(choice)
    }

    fn mark_pr_ready(&mut self, checklist: Option<&str>) -> Result<Identified> {
        self.pull_request.mark_ready(checklist)
    }

    fn take_to_goal(&mut self, pr_url: &str, goal: Goal) -> Result<()> {
        let mut outside = RunOutside {
            tracker: self.tracker,
            issue: self.issue,
            worktree: self.worktree,
            base: self.base,
            pr_url,
            base_fix: self.base_fix,
            child_asks: self.child_asks,
            sessions: self.sessions,
            pull_request: self.pull_request,
            ci_watch: ci::Watch::new(self.issue),
            protected_paths: self.protected_paths,
            context: self.context,
        };
        repair_loop::take_to_goal(&mut outside, self.base, goal, self.repair_cap)?;
        // Ticket/Spec and Base CI Deliveries began with agent-authored or
        // reviewed work. Preserve exact-head evidence for a later Fix run.
        // An adopted PR cannot acquire that authority merely by passing CI.
        if goal == Goal::ReadyForReview
            && !matches!(self.context, RepairContext::PullRequest(_))
            && let Err(error) = self.record_delivered_head(pr_url)
        {
            progress::warn(
                &error,
                format_args!("could not record the delivered agent head"),
            );
        }
        Ok(())
    }

    fn delete_branch(&mut self) -> Result<()> {
        self.worktree.delete_from_origin()
    }

    fn issue_is_open(&mut self) -> Result<bool> {
        GitHub::new().completion().issue_is_open(self.issue)
    }

    fn close_issue(&mut self, comment: &str) -> Result<()> {
        GitHub::new().completion().close_issue(self.issue, comment)
    }

    fn interrupted(&mut self) -> bool {
        interrupt::requested()
    }

    fn step(&mut self, line: String) {
        progress::step(line);
    }

    fn warn(&mut self, error: &anyhow::Error, warning: String) {
        progress::warn(error, format_args!("{warning}"));
    }
}

impl InWorktree<'_> {
    fn record_delivered_head(&mut self, pr_url: &str) -> Result<()> {
        self.pull_request.ensure_actionable(true)?;
        let head = self.worktree.head()?;
        let pr = crate::review::PullRequestUrl::parse(pr_url)?;
        let marker = serde_json::json!({"authored_head": head});
        GitHub::new().comment_review(
            &pr,
            &format!("Delivery completed on agent-authored or reviewed head {head}.\n\n<!-- thirdshift-review {marker} -->\n"),
        )
    }
}

/// A failed Delivery's worktree and its pull request on GitHub. Worktree
/// owns preservation and the cleanup decision when this is dropped.
struct OnFailure<'a> {
    base: &'a str,
    worktree: Worktree,
    pull_request: &'a mut PullRequest,
}

impl FailedOutside for OnFailure<'_> {
    fn preserve_failed_run(&mut self, reason: &str) -> Result<Preserved> {
        if let Err(error) = self.pull_request.ensure_preservable() {
            self.worktree.retain_local();
            return Err(error);
        }
        self.worktree
            .preserve_failed_run(self.base, reason, &mut || {
                self.pull_request.ensure_preservable()
            })
    }

    fn finish_pr(&mut self, keep_ready: bool) -> Result<Option<String>> {
        self.pull_request.finish_failed_run(keep_ready)
    }

    fn interrupted(&mut self) -> bool {
        interrupt::requested()
    }

    fn step(&mut self, line: String) {
        progress::step(line);
    }
}

/// What a Run's Repair loop reaches outside itself: the Run's worktree, its
/// Repair sessions, its Base fix, its issue and its pull request.
struct RunOutside<'a> {
    context: RepairContext<'a>,
    tracker: &'a Tracker,
    issue: &'a IssueUrl,
    worktree: &'a Worktree,
    base: &'a str,
    pr_url: &'a str,
    base_fix: &'a mut BaseFix,
    /// What a Base fix it starts is handed.
    child_asks: &'a ChildAsks,
    sessions: &'a Sessions<'a>,
    pull_request: &'a mut PullRequest,
    ci_watch: ci::Watch<'a>,
    /// Globs that hold Self-merge when a changed path matches. Empty when
    /// this Delivery has nothing to hold.
    protected_paths: &'a [String],
}

impl RunOutside<'_> {
    /// A Repair or Base fix may have reported a new Harness version. Refresh
    /// attribution while the PR is still actionable, before any Self-merge.
    fn refresh_built_with(&mut self) -> Result<()> {
        self.pull_request.ensure_actionable(true)?;
        if let Err(error) = self.pull_request.write_built_with(&self.child_asks.harness) {
            progress::warn(
                &error,
                format_args!("could not write the Built-with line in the pull request's body"),
            );
        }
        Ok(())
    }
}

impl repair_loop::Outside for RunOutside<'_> {
    type Pending = PendingMerge;

    fn stage(&mut self, stage: Stage) {
        self.tracker.enter(stage);
    }

    fn merge_base_branch(&mut self) -> Result<Merge> {
        self.pull_request.ensure_actionable(true)?;
        self.worktree.merge_base_branch(self.base)
    }

    fn merge_new_commits(&mut self, observed: ForeignCommits) -> Result<Merge> {
        self.worktree.merge_new_commits(observed)
    }

    fn ensure_merged(&mut self, pending: &PendingMerge) -> Result<()> {
        self.worktree.ensure_merged(pending)
    }

    fn push(&mut self) -> Result<()> {
        self.pull_request.ensure_actionable(true)?;
        self.worktree
            .push_if_actionable(&mut || self.pull_request.ensure_actionable(true))
    }

    fn head(&mut self) -> Result<String> {
        self.worktree.head()
    }

    fn same_tree_as(&mut self, commit: &str) -> Result<bool> {
        self.worktree.same_tree_as(commit)
    }

    fn base_branch_moved(&mut self) -> Result<bool> {
        self.worktree.base_branch_moved(self.base)
    }

    fn new_commits_on_origin(&mut self) -> Result<ForeignCommits> {
        self.pull_request.ensure_actionable(true)?;
        self.worktree.new_commits_on_origin()
    }

    fn assess_ci(&mut self, head: &str, base_commit: Option<&str>) -> Result<Ci> {
        self.ci_watch.assess(
            head,
            base_commit,
            &mut || self.pull_request.ensure_actionable(true),
            &mut |watched| Ok(self.worktree.new_commits_on_origin()?.origin_head() != watched),
        )
    }

    fn ci_fix_completed(&mut self, head: String, failed: FailedChecks) {
        self.ci_watch.after_repair(head, failed);
    }

    fn repair(&mut self, kind: Kind, repair: Repair) -> Result<()> {
        let (base, pr_url) = (self.base, self.pr_url);
        let subject = self.context.subject();
        let branch = self.worktree.branch();
        let prompt = match repair {
            Repair::Conflict(Upstream::BaseBranch) => {
                prompt::conflict_repair(subject, base, branch, pr_url)
            }
            Repair::Conflict(Upstream::IssueBranch) => {
                prompt::conflict_repair(subject, branch, branch, pr_url)
            }
            Repair::CiFix(failed) => prompt::ci_fix_repair(subject, base, branch, pr_url, failed),
            Repair::Review { from } => prompt::review_repair(subject, branch, pr_url, from),
        };
        self.pull_request.ensure_actionable(true)?;
        let result = self.sessions.run(kind, &prompt);
        let refreshed = self.refresh_built_with();
        result.and(refreshed)
    }

    fn sees_inherited_failures(&mut self) -> bool {
        self.base_fix.sees_inherited_failures()
    }

    fn base_fix(&mut self, base_commit: &str, failed: &FailedChecks) -> Result<()> {
        let outside = base_fix::LaunchAndGitHub {
            launch: self.worktree.launch(),
            issue: self.issue,
            asks: self.child_asks,
            spec_pr: self.pull_request.spec_pr().cloned(),
        };
        let result = self
            .base_fix
            .fix(outside, self.pr_url, self.base, base_commit, failed);
        let refreshed = self.refresh_built_with();
        result.and(refreshed)
    }

    fn pr_mergeable(&mut self) -> Result<bool> {
        self.pull_request.is_mergeable()
    }

    fn ensure_pr_ready_and_mergeable(&mut self) -> Result<()> {
        self.pull_request.ensure_ready_and_mergeable()
    }

    fn merge(&mut self, head: &str) -> Result<MergeAttempt> {
        self.pull_request.merge(head)
    }

    fn merge_hold(&mut self) -> Result<Option<String>> {
        if self.protected_paths.is_empty() {
            return Ok(None);
        }
        let spec = format!("origin/{}...HEAD", self.base);
        // `--no-renames`: include both endpoints of a move, because removing
        // a protected source still touches it. `-z`: names stay unquoted,
        // so `secrets/kéy.txt` still matches `secrets/**`.
        // Line splitting would also cut a name holding a newline in two.
        let listed = Git::new(self.worktree.path()).run_bytes(&[
            "diff",
            "--no-renames",
            "--name-only",
            "-z",
            &spec,
        ])?;
        Ok(protected_hold(
            self.protected_paths,
            listed
                .split(|byte| *byte == 0)
                .filter(|name| !name.is_empty()),
        ))
    }

    fn interrupt_requested(&mut self) -> bool {
        interrupt::requested()
    }

    fn progress(&mut self, line: String) {
        progress::step(line);
    }
}

/// The protected paths among `paths`, named in the hold a Self-merge reports.
/// None when nothing matches. Paths are raw diff bytes, so names git would
/// quote still match. `*` stays inside one path segment, `**` crosses
/// segments, and `?` is one character other than `/`.
fn protected_hold<'a>(
    patterns: &[String],
    paths: impl Iterator<Item = &'a [u8]>,
) -> Option<String> {
    let mut matched: Vec<&[u8]> = paths
        .filter(|path| {
            patterns
                .iter()
                .any(|pattern| glob_match(pattern.as_bytes(), path))
        })
        .collect();
    if matched.is_empty() {
        return None;
    }
    matched.sort_unstable();
    matched.dedup();
    let listed = matched
        .iter()
        .map(|path| String::from_utf8_lossy(path))
        .collect::<Vec<_>>()
        .join(", ");
    Some(if matched.len() == 1 {
        format!(
            "protected path {listed} holds the Self-merge; the pull request stays ready for review"
        )
    } else {
        format!(
            "protected paths {listed} hold the Self-merge; the pull request stays ready for review"
        )
    })
}

/// Whether `pattern` matches the whole of `path`.
fn glob_match(pattern: &[u8], path: &[u8]) -> bool {
    let mut pattern_at = 0;
    let mut path_at = 0;
    while pattern_at < pattern.len() {
        if pattern[pattern_at] == b'*' && pattern.get(pattern_at + 1) == Some(&b'*') {
            pattern_at += 2;
            if pattern.get(pattern_at) == Some(&b'/') {
                pattern_at += 1;
            }
            if pattern_at == pattern.len() {
                return true;
            }
            // The rest of the pattern starts at a segment boundary. `**` does
            // not match inside a name, so `**/key.txt` is not `mykey.txt`.
            let mut rest = path_at;
            loop {
                if glob_match(&pattern[pattern_at..], &path[rest..]) {
                    return true;
                }
                if rest >= path.len() {
                    return false;
                }
                while rest < path.len() && path[rest] != b'/' {
                    rest += 1;
                }
                if rest == path.len() {
                    return false;
                }
                rest += 1;
            }
        } else if pattern[pattern_at] == b'*' {
            pattern_at += 1;
            loop {
                if glob_match(&pattern[pattern_at..], &path[path_at..]) {
                    return true;
                }
                if path_at == path.len() || path[path_at] == b'/' {
                    return false;
                }
                path_at += 1;
            }
        } else if pattern[pattern_at] == b'?' {
            if path_at == path.len() || path[path_at] == b'/' {
                return false;
            }
            pattern_at += 1;
            path_at += utf8_char_len(&path[path_at..]);
        } else {
            if path_at == path.len() || pattern[pattern_at] != path[path_at] {
                return false;
            }
            pattern_at += 1;
            path_at += 1;
        }
    }
    path_at == path.len()
}

/// Bytes of the UTF-8 character at the start of `bytes`. A lone non-UTF-8
/// byte counts as one, so `?` still advances.
fn utf8_char_len(bytes: &[u8]) -> usize {
    let width = match bytes[0] {
        0x00..=0x7F => 1,
        0xC0..=0xDF => 2,
        0xE0..=0xEF => 3,
        0xF0..=0xF7 => 4,
        _ => return 1,
    };
    if bytes.len() >= width && bytes[1..width].iter().all(|byte| byte & 0xC0 == 0x80) {
        width
    } else {
        1
    }
}

#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
mod tests;