thirdshift 0.13.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
//! The Pass seam: what a Pass's gates, which
//! decide before any work whether it is skipped, read and change of GitHub,
//! what an Architect run's conclusion after its Architecture review does,
//! viewing and labelling the issue the review ended on, and what a pass
//! does outside itself around them: recording its skip or its start,
//! checking its Harness, pulling the Launch directory, running the
//! Architecture review session, and dispatching the issue it ends on.
//! [`LaunchAndGitHub`] does each through `gh`, the Ready issue search, the
//! interrupt flag, the progress lines, the logs, the Harness check, the
//! Launch directory, the review's worktree and its [`Sessions`], and
//! [`run::run_to_end`]; [`InMemory`], in tests, from memory, recording each
//! call.

use std::fmt::Display;
use std::path::PathBuf;

use crate::github::{DraftAdvisory, SecurityRecord, SecurityRecords};
use crate::security::reproduction::Reproduction;
use anyhow::Result;

use crate::asks::{Asks, Flags};
use crate::config::UserConfig;
use crate::github::{GitHub, Issue, ListedIssue};
use crate::harness::Choice;
use crate::interrupt;
use crate::issue::{IssueUrl, Repo};
use crate::labels::{Edit, Label};
use crate::launch::{BaseBranch, LaunchDirectory};
use crate::logs::{self, Pass, Work};
use crate::progress;
use crate::ready::{self, ReadyIssue};
use crate::run::{self, Ended, StartedBy};
use crate::session::{Kind, Logs, Purpose, Sessions};
use crate::worktree::ReviewWorktree;

/// What a pass dispatches, as `thirdshift <Issue URL>` would run it, but on
/// the pass's Base branch `base`, whatever the Launch directory has checked
/// out.
pub enum Dispatch<'a> {
    SecurityFix {
        issue: &'a IssueUrl,
        is_spec: bool,
        base: &'a str,
    },
    /// An Architect run's Architect plan.
    ArchitectPlan { plan: &'a IssueUrl, base: &'a str },
    /// The Ready issue a Pickup run took, a Spec or not, as `is_spec` says.
    ReadyIssue {
        issue: &'a IssueUrl,
        is_spec: bool,
        base: &'a str,
    },
}

/// What a pass's gates, and an Architect run's conclusion, read and change of
/// its repository on GitHub, whether the run is interrupted, and where their
/// progress lines go; and what the pass records in the logs, the check of
/// its Harness, the Launch directory's pull, the Architecture review
/// session, and the run it dispatches.
pub trait Outside {
    /// Every open issue in the repository labelled `label`.
    fn open_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>>;
    /// Every closed issue in the repository labelled `label`.
    fn closed_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>>;
    /// `issue`'s title, state, labels and when it was created.
    fn issue(&mut self, issue: &IssueUrl) -> Result<Issue>;
    /// Make `edit`.
    fn apply(&mut self, edit: &Edit) -> Result<()>;
    /// Whether the run was interrupted.
    fn interrupted(&mut self) -> bool;
    /// The repository's lowest-numbered Ready issue, if it has one, by the
    /// Ready issue search, with its lines on the issues passed over.
    fn ready_issue(&mut self) -> Result<Option<ReadyIssue>>;
    /// Hand on the progress line `line`.
    fn step(&mut self, line: String);
    /// Record that `pass` was skipped for `reason`.
    fn skipped(&mut self, pass: Pass, reason: &dyn Display);
    /// Check the Harness, Model and Effort the pass's sessions, and the run
    /// it dispatches, run on, failing if they can't run.
    fn check_harness(&mut self) -> Result<()>;
    /// Record that the pass started `work`, on the Harness it checked.
    fn started(&mut self, work: Work);
    /// Request the prepared Base branch's checkout update: only a warning
    /// if it cannot fast-forward to its sampled origin commit.
    fn pull(&mut self);
    /// Run the Architecture review session of the Base branch `base` on
    /// `prompt`, on the Harness the pass checked, to its final message,
    /// handing on the progress line `starting` once it is ready to start it,
    /// then `conclude` on this seam and that message, while the session is
    /// still open: a failure of `conclude` after a session left background
    /// work to be killed names that work too. Returns what `conclude` came
    /// to, with the session's Session log, if it has one.
    fn review<T>(
        &mut self,
        base: &str,
        starting: String,
        prompt: &str,
        conclude: impl FnOnce(&mut Self, Option<&str>) -> Result<T>,
    ) -> (Result<T>, Option<PathBuf>);
    /// Check Node.js before a Security audit needs its validators.
    fn check_node(&mut self) -> Result<()>;
    /// Audit the Base branch in a disposable checkout and validate its artifacts.
    fn audit(&mut self, base: &str) -> crate::security::audit::Attempt;
    /// Private advisory or issue records in every state.
    fn security_records(&mut self) -> Result<SecurityRecords>;
    /// Whether origin's prepared Base branch is the last completed audit's commit.
    fn base_unchanged_since_security_audit(&mut self) -> Result<bool>;
    /// Record one finding in the repository's private storage.
    fn create_security_record(
        &mut self,
        records: &SecurityRecords,
        finding: &DraftAdvisory,
    ) -> Result<SecurityRecord>;
    /// Reproduce the finding read from this record, in a fresh checkout.
    fn reproduce(
        &mut self,
        record: &SecurityRecord,
        number: usize,
    ) -> (Result<Reproduction>, Option<PathBuf>);
    /// Write only a completed reproduction to its private record.
    fn update_security_record(
        &mut self,
        record: &SecurityRecord,
        reproduction: &Reproduction,
    ) -> Result<()>;
    fn publish_security_fix(
        &mut self,
        base: &str,
        record: &SecurityRecord,
        url: &str,
    ) -> (Result<IssueUrl>, Option<PathBuf>);
    fn link_security_fix(&mut self, record: &SecurityRecord, issue: &IssueUrl) -> Result<()>;
    /// Record the dispatch's ending in its private record, even after interruption.
    fn record_security_fix_ending(
        &mut self,
        record: &SecurityRecord,
        issue: &IssueUrl,
        succeeded: bool,
    ) -> Result<()>;
    /// Run `dispatch` to its end, on the Harness the pass checked.
    fn dispatch(&mut self, dispatch: Dispatch) -> Ended;
}

/// The repository `repo` on GitHub, from its Launch directory `launch`, with
/// the logs, the pass's Harness choice `harness`, and the command's `flags`
/// and the User config `config`, which ask the run it dispatches.
pub struct LaunchAndGitHub<'a> {
    pub launch: &'a LaunchDirectory,
    pub base: &'a BaseBranch,
    pub repo: &'a Repo,
    /// Settled on the Harness's names for its Model and Effort once
    /// checked.
    pub harness: &'a mut Choice,
    pub flags: &'a Flags,
    pub config: &'a UserConfig,
}

impl Outside for LaunchAndGitHub<'_> {
    fn open_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>> {
        GitHub::new().open_issues_labelled(&self.repo.slug(), label)
    }

    fn closed_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>> {
        GitHub::new().closed_issues_labelled(&self.repo.slug(), label)
    }

    fn issue(&mut self, issue: &IssueUrl) -> Result<Issue> {
        GitHub::new().issue(issue)
    }

    fn apply(&mut self, edit: &Edit) -> Result<()> {
        edit.apply(&GitHub::new())
    }

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

    fn ready_issue(&mut self) -> Result<Option<ReadyIssue>> {
        ready::first(self.launch.git(), self.repo, self.config.pickup_wait)
    }

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

    fn skipped(&mut self, pass: Pass, reason: &dyn Display) {
        logs::skipped(pass, self.repo, reason);
    }

    fn check_harness(&mut self) -> Result<()> {
        self.harness.check()
    }

    fn started(&mut self, work: Work) {
        logs::started(work, self.harness);
    }

    fn pull(&mut self) {
        self.base.pull();
    }

    /// The session runs in its own worktree, detached at `base`'s head on
    /// origin, which is removed once `conclude` is done.
    fn review<T>(
        &mut self,
        base: &str,
        starting: String,
        prompt: &str,
        conclude: impl FnOnce(&mut Self, Option<&str>) -> Result<T>,
    ) -> (Result<T>, Option<PathBuf>) {
        let worktree = match ReviewWorktree::create(self.launch.git(), &self.repo.name, base) {
            Ok(worktree) => worktree,
            Err(error) => return (Err(error), None),
        };
        let logs = Logs::of_architect_run(self.repo);
        // Cloned, so the conclusion can take the seam itself.
        let harness = self.harness.clone();
        let concluded = Sessions::within(&logs, worktree.path(), &harness, |sessions| {
            progress::step(starting);
            let final_message = sessions.run_to_final_message(
                Purpose::Ordinary,
                Kind::ArchitectureReview,
                prompt,
            )?;
            conclude(self, final_message.as_deref())
        });
        // Removed once the review is concluded.
        drop(worktree);
        concluded
    }

    fn check_node(&mut self) -> Result<()> {
        crate::security::audit::check_node()
    }

    fn audit(&mut self, base: &str) -> crate::security::audit::Attempt {
        logs::stage(logs::Stage::SecurityAudit);
        crate::security::audit::run(self.launch.git(), self.repo, base, self.harness)
    }

    fn security_records(&mut self) -> Result<SecurityRecords> {
        GitHub::new().security_records(&self.repo.slug())
    }

    fn base_unchanged_since_security_audit(&mut self) -> Result<bool> {
        Ok(
            crate::security::audit::last_commit(self.repo, self.base.name())?.as_deref()
                == Some(self.base.origin_commit()),
        )
    }

    fn create_security_record(
        &mut self,
        records: &SecurityRecords,
        finding: &DraftAdvisory,
    ) -> Result<SecurityRecord> {
        GitHub::new().create_security_record(&self.repo.slug(), records, finding)
    }

    fn reproduce(
        &mut self,
        record: &SecurityRecord,
        number: usize,
    ) -> (Result<Reproduction>, Option<PathBuf>) {
        logs::stage(logs::Stage::SecurityReproduction);
        crate::security::reproduction::run(
            self.launch.git(),
            self.repo,
            record,
            number,
            self.harness,
        )
    }

    fn update_security_record(
        &mut self,
        record: &SecurityRecord,
        reproduction: &Reproduction,
    ) -> Result<()> {
        GitHub::new().update_security_record(&self.repo.slug(), record, reproduction)
    }

    /// The run's asks are the Architect plan's or the Ready issue's, from
    /// the command's flags and the User config, on the checked Harness.
    fn dispatch(&mut self, dispatch: Dispatch) -> Ended {
        let (issue, asks, base, is_spec) = match dispatch {
            Dispatch::SecurityFix {
                issue,
                is_spec,
                base,
            }
            | Dispatch::ReadyIssue {
                issue,
                is_spec,
                base,
            } => (
                issue,
                Asks::of_ready_issue(issue, is_spec, self.flags, self.config),
                base,
                is_spec,
            ),
            Dispatch::ArchitectPlan { plan, base } => (
                plan,
                Asks::of_architect_plan(plan, self.flags, self.config),
                base,
                false, // The Run's launch checks discover an Architect plan's Tickets.
            ),
        };
        let mut asks = Asks {
            harness: self.harness.clone(),
            ..asks
        };
        logs::dispatching(
            if is_spec {
                Work::SpecRun(issue)
            } else {
                Work::Run(issue)
            },
            self.harness,
        );
        let ended = run::run_to_end(issue, &mut asks, StartedBy::Dispatch { base });
        logs::dispatch_ended(&ended);
        ended
    }

    fn publish_security_fix(
        &mut self,
        base: &str,
        record: &SecurityRecord,
        url: &str,
    ) -> (Result<IssueUrl>, Option<PathBuf>) {
        logs::stage(logs::Stage::SecurityFixPublishing);
        crate::security::fixing::publish(
            self.launch.git(),
            self.repo,
            base,
            record,
            url,
            self.harness,
        )
    }

    fn link_security_fix(&mut self, record: &SecurityRecord, issue: &IssueUrl) -> Result<()> {
        GitHub::new().link_security_fix(&self.repo.slug(), record, issue)
    }

    fn record_security_fix_ending(
        &mut self,
        record: &SecurityRecord,
        issue: &IssueUrl,
        succeeded: bool,
    ) -> Result<()> {
        GitHub::new().completion().record_security_fix_ending(
            &self.repo.slug(),
            record,
            issue,
            succeeded,
        )
    }
}

#[cfg(test)]
pub use in_memory::{Call, InMemory, PR_URL, ready_for_review, widgets};

#[cfg(test)]
mod in_memory {
    use std::fmt::Display;
    use std::path::PathBuf;

    use anyhow::{Result, anyhow, bail};

    use super::{Dispatch, Outside};
    use crate::github::{DraftAdvisory, SecurityRecord, SecurityRecords};
    use crate::github::{Issue, ListedIssue};
    use crate::issue::{IssueUrl, Repo};
    use crate::labels::{Edit, Label, Labels};
    use crate::logs::{Pass, Work};
    use crate::ready::ReadyIssue;
    use crate::run::{Ended, Goal, Reached};
    use crate::security::reproduction::{Outcome, Reproduction};
    use serde_json::{Value, json};

    /// A call a pass made outside itself, in the order it made it.
    #[derive(Debug, PartialEq, Eq)]
    pub enum Call {
        /// They listed the open issues with this label.
        Open(&'static str),
        /// They listed the closed issues with this label.
        Closed(&'static str),
        /// They viewed this issue.
        View(u64),
        /// They applied an Edit to this issue, taking `off` off it and
        /// putting `on` on it, which leaves it with `labels`.
        Edit {
            issue: u64,
            off: Vec<&'static str>,
            on: Vec<&'static str>,
            labels: Vec<String>,
        },
        /// They asked for the Ready issue.
        ReadySearch,
        /// They handed on this progress line.
        Step(String),
        /// It recorded that it was skipped, for this reason.
        Skipped(String),
        /// It checked its Harness, Model and Effort.
        HarnessCheck,
        /// It checked Node.js for the Security audit validators.
        NodeCheck,
        /// It ran and validated the Security audit of this Base branch.
        SecurityAudit(String),
        /// It listed private advisories in every state.
        AdvisoryList,
        /// It compared the Base branch with the completed audit history.
        AuditHistory,
        /// It recorded this fingerprint privately.
        CreateAdvisory(String),
        /// It tried to reproduce this private record, in sequence.
        Reproduce(String),
        /// It wrote a completed reproduction to this private record.
        UpdateSecurityRecord(String),
        PublishSecurityFix(String),
        LinkSecurityFix(u64),
        SecurityFixEnding {
            issue: u64,
            succeeded: bool,
        },
        DispatchSecurityFix {
            issue: u64,
            is_spec: bool,
            base: String,
        },
        /// It recorded that it started work: on this issue, for a Pickup
        /// run, or on its repository, for an Architect run.
        Started(Option<u64>),
        /// It requested the prepared Base branch's checkout update.
        Pull,
        /// It ran the Architecture review session of this Base branch on
        /// this prompt, handing on its starting line next.
        Review {
            base: String,
            prompt: String,
        },
        /// It dispatched this Ready issue, a Spec or not, on this Base
        /// branch.
        DispatchReadyIssue {
            issue: u64,
            is_spec: bool,
            base: String,
        },
        /// It dispatched this Architect plan on this Base branch.
        DispatchPlan {
            plan: u64,
            base: String,
        },
    }

    /// A repository in memory: its issues, filed by label, open or
    /// closed, the issues it can view, the Ready issue search's answer, the
    /// issues whose Edits fail, and whether the run was interrupted; with
    /// whether the Harness check fails, how the Architecture review session
    /// ends, and how a dispatched run ends.
    pub struct InMemory {
        /// Each issue, filed under the label a listing finds it by.
        filed: Vec<Filed>,
        /// Each issue it can view, by number. Viewing any other fails.
        viewable: Vec<(u64, Issue)>,
        /// Whether the run was interrupted.
        interrupted: bool,
        /// Whether listing the closed issues fails.
        closed_listing_fails: bool,
        /// The number of each issue an Edit to fails.
        failing_edits: Vec<u64>,
        /// The Ready issue search's answer: the issue, and whether it is a
        /// Spec.
        ready: Option<(ListedIssue, bool)>,
        /// Whether the Harness check fails.
        harness_failing: bool,
        node_failing: bool,
        audit_findings: Vec<DraftAdvisory>,
        audit_error: Option<String>,
        advisories: Vec<Value>,
        finding_issues: Option<Vec<Value>>,
        unchanged_base: bool,
        /// The Architecture review session's final message, if it has one,
        /// or the cause it fails with.
        review: Result<Option<String>, String>,
        /// The Architecture review session's Session log.
        session_log: Option<PathBuf>,
        /// How the run dispatched ends.
        ending: Option<Ended>,
        /// Every call made, in order.
        pub calls: Vec<Call>,
    }

    /// A repository with no issue, whose Harness check passes and whose
    /// Architecture review session ends with no final message and no
    /// Session log.
    impl Default for InMemory {
        fn default() -> Self {
            InMemory {
                filed: Vec::new(),
                viewable: Vec::new(),
                interrupted: false,
                closed_listing_fails: false,
                failing_edits: Vec::new(),
                ready: None,
                harness_failing: false,
                node_failing: false,
                audit_findings: Vec::new(),
                audit_error: None,
                advisories: Vec::new(),
                finding_issues: None,
                unchanged_base: false,
                review: Ok(None),
                session_log: None,
                ending: None,
                calls: Vec::new(),
            }
        }
    }

    /// An issue filed under a label.
    struct Filed {
        /// The label, as spelled.
        under: String,
        open: bool,
        listed: ListedIssue,
    }

    impl InMemory {
        /// Add issue `number`, open or not, labelled `labels` and filed
        /// under each.
        pub fn issue(mut self, number: u64, open: bool, labels: &[&str]) -> Self {
            for label in labels {
                self = self.filed(label, number, open, labels);
            }
            self
        }

        /// Add issue `number`, open or not, labelled `labels`, filed only
        /// under `under`, whether it has that label or not: as a listing
        /// gives an issue whose labels changed since it was listed.
        pub fn filed(mut self, under: &str, number: u64, open: bool, labels: &[&str]) -> Self {
            self.filed.push(Filed {
                under: under.to_string(),
                open,
                listed: listed(number, labels),
            });
            self
        }

        /// Let issue `number` be viewed, as `issue`.
        pub fn viewable(mut self, number: u64, issue: Issue) -> Self {
            self.viewable.push((number, issue));
            self
        }

        /// Have the run interrupted.
        pub fn interrupted(mut self) -> Self {
            self.interrupted = true;
            self
        }

        /// Make listing the closed issues fail.
        pub fn closed_listing_failing(mut self) -> Self {
            self.closed_listing_fails = true;
            self
        }

        /// Make an Edit to issue `number` fail.
        pub fn edit_failing(mut self, number: u64) -> Self {
            self.failing_edits.push(number);
            self
        }

        /// Make the Ready issue search find issue `number`, a Spec or not.
        pub fn ready(mut self, number: u64, is_spec: bool) -> Self {
            self.ready = Some((listed(number, &[]), is_spec));
            self
        }

        /// Make the Harness check fail.
        pub fn harness_failing(mut self) -> Self {
            self.harness_failing = true;
            self
        }

        pub fn node_failing(mut self) -> Self {
            self.node_failing = true;
            self
        }

        pub fn audited(mut self, findings: Vec<DraftAdvisory>) -> Self {
            self.audit_findings = findings;
            self
        }

        pub fn audit_failing(mut self, cause: &str) -> Self {
            self.audit_error = Some(cause.to_string());
            self
        }

        pub fn advisories(mut self, advisories: Vec<Value>) -> Self {
            self.advisories = advisories;
            self
        }

        pub fn finding_issues(mut self, issues: Vec<Value>) -> Self {
            self.finding_issues = Some(issues);
            self
        }

        pub fn unchanged_base(mut self) -> Self {
            self.unchanged_base = true;
            self
        }

        /// Have the Architecture review session end with `final_message`.
        pub fn reviewed(mut self, final_message: &str) -> Self {
            self.review = Ok(Some(final_message.to_string()));
            self
        }

        /// Make the Architecture review session fail with `cause`, before
        /// any conclusion.
        pub fn review_failing(mut self, cause: &str) -> Self {
            self.review = Err(cause.to_string());
            self
        }

        /// Have the Architecture review session logged at `log`.
        pub fn session_log(mut self, log: &str) -> Self {
            self.session_log = Some(PathBuf::from(log));
            self
        }

        /// Have the run dispatched end as `ending`.
        pub fn dispatched_ending(mut self, ending: Ended) -> Self {
            self.ending = Some(ending);
            self
        }

        /// The issues, open or not as `open` says, filed under `label`.
        fn labelled(&self, label: Label, open: bool) -> Vec<ListedIssue> {
            self.filed
                .iter()
                .filter(|filed| filed.open == open && label.is_named(&filed.under))
                .map(|filed| filed.listed.clone())
                .collect()
        }
    }

    impl Outside for InMemory {
        fn open_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>> {
            self.calls.push(Call::Open(label.name()));
            Ok(self.labelled(label, true))
        }

        fn closed_issues(&mut self, label: Label) -> Result<Vec<ListedIssue>> {
            self.calls.push(Call::Closed(label.name()));
            if self.closed_listing_fails {
                bail!("gh: could not list the closed issues");
            }
            Ok(self.labelled(label, false))
        }

        fn issue(&mut self, issue: &IssueUrl) -> Result<Issue> {
            self.calls.push(Call::View(issue.number));
            match self
                .viewable
                .iter()
                .find(|(number, _)| *number == issue.number)
            {
                Some((_, viewed)) => Ok(viewed.clone()),
                None => bail!(
                    "gh: Could not resolve to an issue with the number of {}",
                    issue.number
                ),
            }
        }

        fn apply(&mut self, edit: &Edit) -> Result<()> {
            let (off, on) = edit.changes();
            self.calls.push(Call::Edit {
                issue: edit.issue().number,
                off: off.iter().map(|label| label.name()).collect(),
                on: on.iter().map(|label| label.name()).collect(),
                labels: edit.labels_after().names().map(String::from).collect(),
            });
            if self.failing_edits.contains(&edit.issue().number) {
                bail!("gh: could not edit #{}", edit.issue().number);
            }
            Ok(())
        }

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

        fn ready_issue(&mut self) -> Result<Option<ReadyIssue>> {
            self.calls.push(Call::ReadySearch);
            Ok(self.ready.clone().map(|(listed, is_spec)| ReadyIssue {
                listed,
                is_spec,
                claim_generation: 0,
            }))
        }

        fn step(&mut self, line: String) {
            self.calls.push(Call::Step(line));
        }

        fn skipped(&mut self, _: Pass, reason: &dyn Display) {
            self.calls.push(Call::Skipped(reason.to_string()));
        }

        fn check_harness(&mut self) -> Result<()> {
            self.calls.push(Call::HarnessCheck);
            if self.harness_failing {
                bail!("claude is not on PATH");
            }
            Ok(())
        }

        fn started(&mut self, work: Work) {
            let issue = match work {
                Work::Run(issue)
                | Work::BaseFix(issue)
                | Work::SpecRun(issue)
                | Work::PickupRun(issue) => Some(issue.number),
                Work::ArchitectRun(_) | Work::SecurityRun(_) => None,
            };
            self.calls.push(Call::Started(issue));
        }

        fn pull(&mut self) {
            self.calls.push(Call::Pull);
        }

        fn review<T>(
            &mut self,
            base: &str,
            starting: String,
            prompt: &str,
            conclude: impl FnOnce(&mut Self, Option<&str>) -> Result<T>,
        ) -> (Result<T>, Option<PathBuf>) {
            self.calls.push(Call::Review {
                base: base.to_string(),
                prompt: prompt.to_string(),
            });
            self.calls.push(Call::Step(starting));
            let log = self.session_log.clone();
            match self.review.clone() {
                Ok(final_message) => (conclude(self, final_message.as_deref()), log),
                Err(cause) => (Err(anyhow!(cause)), log),
            }
        }

        fn check_node(&mut self) -> Result<()> {
            self.calls.push(Call::NodeCheck);
            if self.node_failing {
                bail!("Node.js is required");
            }
            Ok(())
        }

        fn audit(&mut self, base: &str) -> crate::security::audit::Attempt {
            self.calls.push(Call::SecurityAudit(base.to_string()));
            let audited = match self.audit_error.take() {
                Some(cause) => Err(anyhow!(cause)),
                None => Ok(crate::security::audit::Audited {
                    findings: std::mem::take(&mut self.audit_findings),
                }),
            };
            crate::security::audit::Attempt {
                started: true,
                outcome: audited,
                log: self.session_log.clone(),
            }
        }

        fn security_records(&mut self) -> Result<SecurityRecords> {
            self.calls.push(Call::AdvisoryList);
            Ok(match &self.finding_issues {
                Some(issues) => SecurityRecords::issues(issues.clone()),
                None => SecurityRecords::advisories(self.advisories.clone()),
            })
        }

        fn base_unchanged_since_security_audit(&mut self) -> Result<bool> {
            self.calls.push(Call::AuditHistory);
            Ok(self.unchanged_base)
        }

        fn create_security_record(
            &mut self,
            records: &SecurityRecords,
            finding: &DraftAdvisory,
        ) -> Result<SecurityRecord> {
            self.calls
                .push(Call::CreateAdvisory(finding.fingerprint.clone()));
            let value = if let Some(issues) = &mut self.finding_issues {
                let number = issues
                    .iter()
                    .filter_map(|issue| issue["number"].as_u64())
                    .max()
                    .unwrap_or(0)
                    + 1;
                let issue = json!({
                    "number": number, "body": finding.description, "state": "OPEN",
                    "title": finding.summary, "labels": [{"name": "security-finding"}, {"name": "needs-triage"}],
                    "html_url": format!("https://github.com/acme/widgets/issues/{number}")
                });
                issues.push(issue.clone());
                issue
            } else {
                let advisory = json!({
                    "ghsa_id": finding.fingerprint,
                    "description": finding.description, "state": "draft",
                    "summary": finding.summary,
                    "html_url": format!("https://github.com/acme/widgets/security/advisories/{}", finding.fingerprint),
                    "severity": null
                });
                self.advisories.push(advisory.clone());
                advisory
            };
            records.decode_created(value)
        }

        fn reproduce(
            &mut self,
            record: &SecurityRecord,
            _number: usize,
        ) -> (Result<Reproduction>, Option<PathBuf>) {
            self.calls.push(Call::Reproduce(record.name()));
            (
                Ok(Reproduction {
                    outcome: Outcome::NotReproduced,
                    notes: "Not reproduced with a local fixture".into(),
                    test: "bounded_fixture()".into(),
                }),
                self.session_log.clone(),
            )
        }

        fn update_security_record(
            &mut self,
            record: &SecurityRecord,
            _reproduction: &Reproduction,
        ) -> Result<()> {
            self.calls.push(Call::UpdateSecurityRecord(record.name()));
            Ok(())
        }

        fn dispatch(&mut self, dispatch: Dispatch) -> Ended {
            self.calls.push(match dispatch {
                Dispatch::SecurityFix {
                    issue,
                    is_spec,
                    base,
                } => Call::DispatchSecurityFix {
                    issue: issue.number,
                    is_spec,
                    base: base.into(),
                },
                Dispatch::ArchitectPlan { plan, base } => Call::DispatchPlan {
                    plan: plan.number,
                    base: base.to_string(),
                },
                Dispatch::ReadyIssue {
                    issue,
                    is_spec,
                    base,
                } => Call::DispatchReadyIssue {
                    issue: issue.number,
                    is_spec,
                    base: base.to_string(),
                },
            });
            self.ending
                .take()
                .expect("a dispatch, with no ending scripted for it")
        }

        fn publish_security_fix(
            &mut self,
            _base: &str,
            record: &SecurityRecord,
            _url: &str,
        ) -> (Result<IssueUrl>, Option<PathBuf>) {
            self.calls.push(Call::PublishSecurityFix(record.name()));
            (
                Ok(IssueUrl::parse("https://github.com/acme/widgets/issues/8").unwrap()),
                self.session_log.clone(),
            )
        }

        fn link_security_fix(&mut self, _record: &SecurityRecord, issue: &IssueUrl) -> Result<()> {
            self.calls.push(Call::LinkSecurityFix(issue.number));
            Ok(())
        }

        fn record_security_fix_ending(
            &mut self,
            _record: &SecurityRecord,
            issue: &IssueUrl,
            succeeded: bool,
        ) -> Result<()> {
            self.calls.push(Call::SecurityFixEnding {
                issue: issue.number,
                succeeded,
            });
            Ok(())
        }
    }

    /// Issue `number` in `acme/widgets` as a listing gives it, labelled
    /// `labels`.
    fn listed(number: u64, labels: &[&str]) -> ListedIssue {
        ListedIssue {
            issue: IssueUrl::parse(&format!("https://github.com/acme/widgets/issues/{number}"))
                .unwrap(),
            title: format!("Issue {number}"),
            labels: labels.iter().copied().collect::<Labels>(),
        }
    }

    /// The repository every pass is on, whose issues [`InMemory`] has.
    pub fn widgets() -> Repo {
        Repo {
            owner: "acme".to_string(),
            name: "widgets".to_string(),
        }
    }

    pub const PR_URL: &str = "https://github.com/acme/widgets/pull/12";

    /// A dispatched run that ended ready for review on [`PR_URL`].
    pub fn ready_for_review() -> Ended {
        Ended {
            outcome: Ok(Reached {
                pr_url: PR_URL.to_string(),
                goal: Goal::ReadyForReview,
                log: None,
                ticket_lines: Vec::new(),
            }),
            base_fix: None,
            advice: Vec::new(),
        }
    }
}