rho-coding-agent 3.4.0

A fast Rust agent harness with a small footprint and opinionated defaults
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
use std::{sync::Arc, time::Duration};

use futures_util::FutureExt as _;
use pretty_assertions::assert_eq;
use rho_protocol as wire;
use rho_sdk::SessionId;
use tempfile::TempDir;

use super::{BUDGET_FLOOR, WATCHES_PER_SESSION};
use crate::app::pull_requests::{
    checkout::Checkout,
    due::QUIET_REREAD,
    gh::ReadError,
    inbox::{
        CheckCounts, LastRead, ListedPullRequest, NewsBatch, PullRequestError, PullRequestInbox,
        Watched,
    },
    interest::{LISTED_POLL, SHOWN_POLL},
    model::{
        BranchId, Budget, ChangeKey, CheckRun, CheckStatus, FetchPlan, MergeMethod, Mergeable,
        PrDetail, PrId, PrState, PrSummary, RepoId, Review, Rollup,
    },
    record::LinkOrigin,
    service::{Detailed, PullRequests, ShowRead, ShowTarget},
    state::{Change, CheckRef, CheckTally, End, Failure, Gate, News},
    test_forge::ScriptedForge,
};

/// When each test's watches begin, in unix milliseconds.
const NOW: u64 = 1_700_000_000_000;
const MINUTE: u64 = 60_000;
/// The first tick after the watches began.
const TICK: u64 = NOW + MINUTE;
const HEAD: &str = "1a2b3c4d5e6f";

struct Fixture {
    dir: TempDir,
    forge: Arc<ScriptedForge>,
    service: PullRequests,
}

impl Fixture {
    fn new() -> Self {
        let dir = tempfile::tempdir().unwrap();
        let forge = ScriptedForge::new();
        let service = PullRequests::open(dir.path(), forge.clone());
        Self {
            dir,
            forge,
            service,
        }
    }

    /// `session`'s inbox, its workspace no git repository.
    fn inbox(&self, session: &SessionId) -> PullRequestInbox {
        self.service.inbox(session, self.dir.path())
    }

    /// A second service over the same records, as after a daemon restart.
    fn reopen(&self) -> PullRequests {
        PullRequests::open(self.dir.path(), ScriptedForge::new())
    }
}

fn pr(number: u32) -> PrId {
    PrId {
        repo: RepoId {
            host: "github.com".into(),
            owner: "acme".into(),
            name: "widgets".into(),
        },
        number,
    }
}

fn target(number: u32) -> String {
    format!("acme/widgets#{number}")
}

fn url(number: u32) -> String {
    format!("https://github.com/acme/widgets/pull/{number}")
}

fn check(name: &str, status: CheckStatus) -> CheckRun {
    CheckRun {
        name: name.into(),
        workflow: None,
        status,
        url: Some(format!("https://ci.example/{name}")),
        required: None,
    }
}

/// PR `number`, open on `HEAD` and merging cleanly, with one check `ci`.
fn open(number: u32, ci: CheckStatus) -> PrDetail {
    let rollup = match ci {
        CheckStatus::Failed | CheckStatus::Cancelled => Rollup::Failing,
        CheckStatus::Running | CheckStatus::Pending => Rollup::Pending,
        CheckStatus::Passed | CheckStatus::Neutral | CheckStatus::Skipped => Rollup::Passing,
    };
    PrDetail {
        summary: PrSummary {
            id: pr(number),
            title: "Widgets".into(),
            url: url(number),
            state: PrState::Open,
            change: ChangeKey {
                updated_at: "2026-11-22T00:00:00Z".into(),
                head_oid: HEAD.into(),
                rollup,
            },
        },
        author: "me".into(),
        head: "feature".into(),
        base: "main".into(),
        body: String::new(),
        additions: 1,
        deletions: 1,
        changed_files: 1,
        review: Review::None,
        checks: vec![check("ci", ci)],
        checks_total: 1,
        posts: Vec::new(),
        older_posts: 0,
        threads: Vec::new(),
        older_threads: 0,
        mergeable: Mergeable::Yes,
        merge_methods: vec![MergeMethod::Squash],
        viewer: Some("me".into()),
        merged_by: None,
        merge_commit: None,
    }
}

/// `detail` after an edit that moves its summary's change key.
fn edited(mut detail: PrDetail) -> PrDetail {
    detail.summary.change.updated_at = "2026-11-22T00:05:00Z".into();
    detail
}

/// `detail`, merged by bob.
fn merged(detail: PrDetail) -> PrDetail {
    let mut detail = edited(detail);
    detail.summary.state = PrState::Merged;
    detail.mergeable = Mergeable::Unknown;
    detail.merged_by = Some("bob".into());
    detail.merge_commit = Some("9f8e7d6".into());
    detail
}

/// What a tick at [`TICK`] tells of PR `number`'s check `ci` failing, the
/// `seq`th news queued for its session.
fn ci_failed(number: u32, seq: u64) -> News {
    News {
        seq,
        pr: pr(number),
        url: url(number),
        head: Some(HEAD.into()),
        changes: vec![Change::ChecksFailed {
            failed: vec![CheckRef {
                name: "ci".into(),
                url: Some("https://ci.example/ci".into()),
                failure: Failure::Failed,
            }],
        }],
        end: None,
        at: TICK,
        pushed: false,
        checks: Some(CheckTally {
            failed: 1,
            ..CheckTally::default()
        }),
    }
}

fn batch(news: Vec<News>) -> NewsBatch {
    NewsBatch { news, dropped: 0 }
}

fn summaries(numbers: &[u32]) -> FetchPlan {
    FetchPlan {
        links: numbers.iter().copied().map(pr).collect(),
        ..FetchPlan::default()
    }
}

fn details(numbers: &[u32]) -> FetchPlan {
    FetchPlan {
        details: numbers.iter().copied().map(pr).collect(),
        ..FetchPlan::default()
    }
}

fn millis(duration: Duration) -> u64 {
    u64::try_from(duration.as_millis()).unwrap()
}

// Covers: a tick reads a watched PR's full detail only when the watch may
// have news, and its cheap summary otherwise
// Owner: PR poller
#[tokio::test]
async fn a_tick_reads_a_detail_only_when_the_watch_may_have_news() {
    let passing = open(12, CheckStatus::Passed);
    let running = open(12, CheckStatus::Running);
    // GitHub's rollup reads failing as soon as one check fails.
    let mut failing_while_running = open(12, CheckStatus::Failed);
    failing_while_running
        .checks
        .push(check("lint", CheckStatus::Running));
    failing_while_running.checks_total = 2;
    let cases = [
        (
            "quiet, its detail a minute old",
            passing.clone(),
            passing.clone(),
            TICK,
            vec![summaries(&[12])],
        ),
        (
            "its checks were running",
            running.clone(),
            running,
            TICK,
            vec![details(&[12])],
        ),
        (
            "a check was running though the rollup read failing",
            failing_while_running.clone(),
            failing_while_running,
            TICK,
            vec![details(&[12])],
        ),
        (
            "quiet, its detail as old as the reread period",
            passing.clone(),
            passing.clone(),
            NOW + millis(QUIET_REREAD),
            vec![details(&[12])],
        ),
        (
            "its summary moved since its detail",
            passing.clone(),
            edited(passing),
            TICK,
            vec![summaries(&[12]), details(&[12])],
        ),
    ];
    for (name, baseline, now, at, expected) in cases {
        let fixture = Fixture::new();
        fixture.forge.set(baseline);
        fixture
            .inbox(&SessionId::new())
            .watch(&target(12), NOW)
            .await
            .unwrap();
        fixture.forge.set(now);
        fixture.forge.take_asked();

        fixture.service.tick(at).await;

        assert_eq!(fixture.forge.take_asked(), expected, "{name}");
    }
}

// Covers: at the budget floor rho reads nothing from the host until the
// limit resets, and a new watch says why it can't start
// Owner: PR poller
#[tokio::test]
async fn reads_stop_at_the_budget_floor_until_it_resets() {
    let fixture = Fixture::new();
    let resets_at = i64::try_from(NOW / 1000).unwrap() + 3600;
    fixture.forge.budget(Budget {
        remaining: BUDGET_FLOOR,
        resets_at,
        cost: Some(1),
    });
    fixture.forge.set(open(12, CheckStatus::Running));
    fixture.forge.set(open(13, CheckStatus::Running));
    let inbox = fixture.inbox(&SessionId::new());
    inbox.watch(&target(12), NOW).await.unwrap();
    fixture.forge.take_asked();

    fixture.service.tick(TICK).await;
    let refused = inbox.watch(&target(13), TICK).await;

    assert_eq!(
        (fixture.forge.take_asked(), refused),
        (
            Vec::<FetchPlan>::new(),
            Err(PullRequestError::Budget {
                remaining: BUDGET_FLOOR,
                floor: BUDGET_FLOOR,
                resets_at,
            })
        )
    );

    fixture.forge.budget(Budget {
        remaining: 4999,
        resets_at: resets_at + 3600,
        cost: Some(1),
    });
    let reset = u64::try_from(resets_at).unwrap() * 1000;
    fixture.service.tick(reset).await;

    assert_eq!(fixture.forge.take_asked(), vec![details(&[12])]);
}

// Covers: sessions watching one PR share each read, and each gets the news
// Owner: PR poller
#[tokio::test]
async fn sessions_watching_one_pull_request_share_its_reads() {
    let fixture = Fixture::new();
    let (first, second) = (SessionId::new(), SessionId::new());
    fixture.forge.set(open(12, CheckStatus::Running));
    for session in [&first, &second] {
        fixture
            .inbox(session)
            .watch(&target(12), NOW)
            .await
            .unwrap();
    }
    fixture.forge.set(open(12, CheckStatus::Failed));
    fixture.forge.take_asked();

    fixture.service.tick(TICK).await;

    assert_eq!(
        (
            fixture.forge.take_asked(),
            fixture.inbox(&first).take_news(),
            fixture.inbox(&second).take_news(),
        ),
        (
            vec![details(&[12])],
            batch(vec![ci_failed(12, 0)]),
            batch(vec![ci_failed(12, 0)]),
        )
    );
}

// Covers: a watch begun on a PR another session watches does not hide from
// that watch what changed since its last read
// Owner: PR poller
#[tokio::test]
async fn a_new_watch_does_not_hide_news_from_an_older_one() {
    let fixture = Fixture::new();
    let (first, second) = (SessionId::new(), SessionId::new());
    fixture.forge.set(open(12, CheckStatus::Passed));
    fixture.inbox(&first).watch(&target(12), NOW).await.unwrap();
    fixture.forge.set(edited(open(12, CheckStatus::Failed)));
    fixture
        .inbox(&second)
        .watch(&target(12), NOW + 1)
        .await
        .unwrap();

    fixture.service.tick(TICK).await;

    assert_eq!(
        (
            fixture.inbox(&first).take_news(),
            fixture.inbox(&second).take_news(),
        ),
        (batch(vec![ci_failed(12, 0)]), NewsBatch::default())
    );
}

// Covers: one tick's news on several PRs wakes a session once, together
// Owner: PR poller
#[tokio::test]
async fn a_tick_wakes_each_session_once_with_all_its_news() {
    let fixture = Fixture::new();
    let mut wake_requests = fixture.service.take_wake_requests().unwrap();
    let session = SessionId::new();
    let inbox = fixture.inbox(&session);
    for number in [12, 13] {
        fixture.forge.set(open(number, CheckStatus::Running));
        inbox.watch(&target(number), NOW).await.unwrap();
        fixture.forge.set(open(number, CheckStatus::Failed));
    }
    let news_arrived = inbox.news_owned();

    fixture.service.tick(TICK).await;

    let mut woken = Vec::new();
    while let Ok(session) = wake_requests.try_recv() {
        woken.push(session);
    }
    assert_eq!(
        (
            woken,
            news_arrived.now_or_never().is_some(),
            inbox.take_news()
        ),
        (
            vec![session],
            true,
            batch(vec![ci_failed(12, 0), ci_failed(13, 1)])
        )
    );
}

// Covers: news on a head the agent hasn't heard of says new commits came,
// so it doesn't take earlier check results for the new head's; news on the
// head it knows doesn't.
// Owner: PR service
#[tokio::test]
async fn news_on_a_new_head_says_new_commits_came() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    let inbox = fixture.inbox(&session);
    fixture.forge.set(open(12, CheckStatus::Running));
    inbox.watch(&target(12), NOW).await.unwrap();
    fixture.forge.set(open(12, CheckStatus::Failed));
    fixture.service.tick(TICK).await;
    let mut pushed = open(12, CheckStatus::Failed);
    pushed.summary.change.head_oid = "9f8e7d6c5b4a".into();
    pushed.summary.change.updated_at = "2026-11-22T00:05:00Z".into();
    fixture.forge.set(pushed);

    fixture.service.tick(TICK + MINUTE).await;

    let told: Vec<(Option<String>, bool)> = inbox
        .take_news()
        .news
        .into_iter()
        .map(|news| (news.head, news.pushed))
        .collect();
    assert_eq!(
        told,
        vec![
            (Some(HEAD.into()), false),
            (Some("9f8e7d6c5b4a".into()), true)
        ]
    );
}

// Covers: news survives a daemon restart until a turn that carried it was
// applied; a turn that did not deliver it puts it back
// Owner: PR service
#[tokio::test]
async fn news_stays_queued_on_disk_until_acknowledged() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    fixture.forge.set(open(12, CheckStatus::Running));
    fixture
        .inbox(&session)
        .watch(&target(12), NOW)
        .await
        .unwrap();
    fixture.forge.set(open(12, CheckStatus::Failed));
    fixture.service.tick(TICK).await;
    let in_flight = fixture.inbox(&session).take_news();

    let restarted = fixture.reopen();
    let inbox = restarted.inbox(&session, fixture.dir.path());
    let taken = inbox.take_news();
    inbox.restore_news(&taken);
    let taken_again = inbox.take_news();
    inbox.acknowledge(&taken_again);
    let after_acknowledge = fixture
        .reopen()
        .inbox(&session, fixture.dir.path())
        .take_news();

    let news = batch(vec![ci_failed(12, 0)]);
    assert_eq!(
        (in_flight, taken, taken_again, after_acknowledge),
        (news.clone(), news.clone(), news, NewsBatch::default())
    );
}

/// What a refusal test sets up before the session watches PR 100.
enum Given {
    Merged,
    ReadFails(ReadError),
    Watching(u32),
    /// PR 100 named on a host that is neither github.com nor the
    /// workspace's origin's.
    ForeignHost,
}

// Covers: a watch that cannot work is refused at once, naming its cause
// Owner: PR service
#[tokio::test]
async fn a_watch_that_cannot_work_is_refused_with_its_cause() {
    let watching_25: Vec<(u32, bool)> = (1..=25).map(|number| (number, true)).collect();
    let cases = [
        (
            "merged already",
            Given::Merged,
            PullRequestError::AlreadyEnded {
                state: PrState::Merged,
            },
            vec![(100, false)],
        ),
        (
            "gh missing",
            Given::ReadFails(ReadError::NotInstalled("No such file".into())),
            PullRequestError::NotInstalled,
            Vec::new(),
        ),
        (
            "gh signed out",
            Given::ReadFails(ReadError::SignedOut("HTTP 401: Bad credentials".into())),
            PullRequestError::SignedOut {
                host: "github.com".into(),
            },
            Vec::new(),
        ),
        (
            "a 26th watch",
            Given::Watching(25),
            PullRequestError::TooManyWatches {
                limit: WATCHES_PER_SESSION,
                asked: 26,
            },
            watching_25,
        ),
        (
            "a host that is neither github.com nor origin's",
            Given::ForeignHost,
            PullRequestError::InvalidTarget(
                "rho only reads pull requests on github.com or this workspace's origin host, \
                 not ghe.example.com"
                    .into(),
            ),
            Vec::new(),
        ),
    ];
    for (name, given, error, links) in cases {
        let fixture = Fixture::new();
        let session = SessionId::new();
        let inbox = fixture.inbox(&session);
        let mut asked = target(100);
        fixture.forge.set(open(100, CheckStatus::Passed));
        match given {
            Given::Merged => fixture.forge.set(merged(open(100, CheckStatus::Passed))),
            Given::ReadFails(error) => fixture.forge.fail_next(error),
            Given::Watching(count) => {
                for number in 1..=count {
                    fixture.forge.set(open(number, CheckStatus::Passed));
                    inbox.watch(&target(number), NOW).await.unwrap();
                }
            }
            Given::ForeignHost => {
                asked = "https://ghe.example.com/acme/widgets/pull/100".to_owned();
            }
        }

        let refused = inbox.watch(&asked, NOW).await;

        let linked: Vec<(u32, bool)> = inbox
            .list(NOW)
            .into_iter()
            .map(|listed| (listed.pr.number, listed.watched))
            .collect();
        assert_eq!((refused, linked), (Err(error), links), "{name}");
    }
}

// Covers: a PR that merges ends its watch with one end news, and stays
// linked
// Owner: PR poller
#[tokio::test]
async fn an_end_drops_the_watch_and_keeps_the_link() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    let inbox = fixture.inbox(&session);
    fixture.forge.set(open(12, CheckStatus::Passed));
    inbox.watch(&target(12), NOW).await.unwrap();
    fixture.forge.set(merged(open(12, CheckStatus::Passed)));

    fixture.service.tick(TICK).await;

    assert_eq!(
        (
            inbox.list(TICK),
            fixture.service.watches(&session),
            inbox.take_news()
        ),
        (
            vec![ListedPullRequest {
                pr: pr(12),
                url: url(12),
                origin: LinkOrigin::Agent,
                watched: false,
                last_read: Some(LastRead {
                    state: PrState::Merged,
                    rollup: Rollup::Passing,
                    age: Duration::ZERO,
                }),
                trouble: None,
            }],
            false,
            batch(vec![News {
                seq: 0,
                pr: pr(12),
                url: url(12),
                head: Some(HEAD.into()),
                changes: Vec::new(),
                end: Some(End::Merged {
                    by: Some("bob".into()),
                    commit: Some("9f8e7d6".into()),
                    base: "main".into(),
                }),
                at: TICK,
                pushed: false,
                checks: Some(CheckTally {
                    passed: 1,
                    ..CheckTally::default()
                }),
            }]),
        )
    );
}

// Covers: watching a watched PR again reports it and keeps its watch, so
// news the watch owes is still told
// Owner: PR service
#[tokio::test]
async fn watching_again_keeps_the_watch_as_it_was() {
    let fixture = Fixture::new();
    let inbox = fixture.inbox(&SessionId::new());
    fixture.forge.set(open(12, CheckStatus::Running));
    let first = inbox.watch(&target(12), NOW).await;
    fixture.forge.set(open(12, CheckStatus::Failed));
    let again = inbox.watch(&target(12), NOW + 1).await;

    fixture.service.tick(TICK).await;

    let baseline = Watched {
        pr: pr(12),
        url: url(12),
        state: PrState::Open,
        head: HEAD.into(),
        checks: CheckCounts {
            total: 1,
            passed: 0,
            running: 1,
            failed: 0,
        },
        gate: Gate::All,
        gate_checks: 1,
        mergeable: Mergeable::Yes,
        comments: 0,
        unresolved_threads: 0,
        started: true,
    };
    assert_eq!(
        (first, again, inbox.take_news()),
        (
            Ok(baseline.clone()),
            Ok(Watched {
                started: false,
                ..baseline
            }),
            batch(vec![ci_failed(12, 0)]),
        )
    );
}

// Covers: a listed session's branch is looked up and its PR shown from the
// lookup's answer; a renewed list asks nothing before the listed cadence is
// due; once the lease runs out nothing is read, and what was found stays.
// Owner: PR service
#[tokio::test]
async fn a_listed_branch_is_looked_up_and_kept_after_its_lease() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    let feature = BranchId {
        repo: pr(12).repo,
        branch: "feature".into(),
    };
    fixture.forge.set(open(12, CheckStatus::Passed));
    fixture.forge.set_branch(&target(12), "feature");
    let on_feature = || Checkout::Branch(feature.clone());

    fixture.service.list(&session, on_feature(), NOW);
    fixture.service.tick(NOW).await;
    let listed = (
        fixture.forge.take_asked(),
        fixture.service.view(&session, NOW),
    );
    fixture.service.list(&session, on_feature(), NOW + MINUTE);
    fixture.service.tick(NOW + MINUTE).await;
    let renewed = (
        fixture.forge.take_asked(),
        fixture.service.view(&session, NOW + MINUTE),
    );
    let ran_out = NOW + MINUTE + 2 * millis(LISTED_POLL);
    fixture.service.tick(ran_out).await;
    let after = (
        fixture.forge.take_asked(),
        fixture.service.view(&session, ran_out),
    );

    let found = wire::SessionPullRequests::new(
        Some(wire::BranchPullRequest::new(
            Some("feature".into()),
            wire::BranchLookup::Found {
                pull_request: Box::new((&open(12, CheckStatus::Passed).summary).into()),
            },
            None,
        )),
        Vec::new(),
    );
    let lookup = FetchPlan {
        branches: vec![feature.clone()],
        ..FetchPlan::default()
    };
    assert_eq!(
        (listed, renewed, after),
        (
            (vec![lookup], found.clone()),
            (Vec::new(), found.clone()),
            (Vec::new(), found),
        )
    );
}

/// What a case's session does to PR 12 once its branch was looked up.
#[derive(Clone, Copy, Debug)]
enum Adds {
    /// Links it.
    Link,
    /// Watches it, linked before the lookup.
    WatchLinked,
}

// Covers: linking a PR in the session's repository, or starting to watch
// one it links already, looks its branch up again on the next tick, though
// the listed cadence is not due: the agent may have just opened that PR for
// its branch. Otherwise a client shows the PR as a link beside a branch
// that says it has none, for up to 5 minutes.
// Owner: PR service
#[tokio::test]
async fn a_link_or_a_new_watch_looks_the_branch_up_again() {
    for adds in [Adds::Link, Adds::WatchLinked] {
        let fixture = Fixture::new();
        let session = SessionId::new();
        let inbox = fixture.inbox(&session);
        let feature = BranchId {
            repo: pr(12).repo,
            branch: "feature".into(),
        };
        let on_feature = || Checkout::Branch(feature.clone());
        fixture.forge.set(open(12, CheckStatus::Passed));
        match adds {
            Adds::Link => {}
            Adds::WatchLinked => {
                inbox
                    .link(&target(12), LinkOrigin::User, NOW)
                    .await
                    .unwrap();
            }
        }
        fixture.service.list(&session, on_feature(), NOW);
        fixture.service.tick(NOW).await;
        let before = fixture.service.view(&session, NOW).branch;
        fixture.forge.set_branch(&target(12), "feature");
        match adds {
            Adds::Link => {
                inbox
                    .link(&target(12), LinkOrigin::Agent, NOW + MINUTE)
                    .await
                    .unwrap();
            }
            Adds::WatchLinked => {
                inbox.watch(&target(12), NOW + MINUTE).await.unwrap();
            }
        }

        fixture.service.tick(NOW + MINUTE).await;

        let lookup = |found| {
            Some(wire::BranchPullRequest::new(
                Some("feature".into()),
                found,
                None,
            ))
        };
        let found = wire::BranchLookup::Found {
            pull_request: Box::new((&open(12, CheckStatus::Passed).summary).into()),
        };
        assert_eq!(
            (before, fixture.service.view(&session, NOW + MINUTE).branch),
            (lookup(wire::BranchLookup::None), lookup(found)),
            "{adds:?}"
        );
    }
}

// Covers: a cached show of a PR a listed tick read only as a summary reads
// its detail before it answers, though the tick asked for it moments ago.
// Otherwise a panel opened just after the sidebar's poll shows no detail
// until the next tick.
// Owner: PR service
#[tokio::test]
async fn a_cached_show_reads_a_detail_the_listed_tick_did_not() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    fixture.forge.set(open(12, CheckStatus::Passed));
    fixture
        .inbox(&session)
        .link(&target(12), LinkOrigin::User, NOW)
        .await
        .unwrap();
    fixture.service.list(&session, Checkout::NotGit, NOW);
    fixture.service.tick(NOW).await;
    let shown_at = NOW + 5_000;

    let shown = fixture
        .service
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Cached,
            shown_at,
        )
        .await;

    assert_eq!(
        (shown, fixture.forge.take_asked()),
        (
            Ok(Some(Detailed {
                detail: open(12, CheckStatus::Passed),
                at: shown_at,
            })),
            vec![summaries(&[12]), details(&[12])],
        )
    );
}

// Covers: a client showing a PR its session watches, read fresh a shown
// period before the tick or moments before it, while a check fails, does
// not swallow the watch's news: the fresh read is not counted as asked,
// whether it succeeded or failed, so the next tick still reads the detail
// and wakes the session.
// Owner: PR poller
#[tokio::test]
async fn a_shown_pull_request_still_wakes_the_session_that_watches_it() {
    let failed = Detailed {
        detail: open(12, CheckStatus::Failed),
        at: TICK - millis(SHOWN_POLL),
    };
    let baseline = Detailed {
        detail: open(12, CheckStatus::Running),
        at: NOW,
    };
    let cases = [
        (
            "shown a period before the tick",
            TICK - millis(SHOWN_POLL),
            None,
            failed.clone(),
        ),
        (
            "shown moments before the tick",
            TICK - 1_000,
            None,
            Detailed {
                at: TICK - 1_000,
                ..failed
            },
        ),
        (
            "shown moments before the tick, the read failing",
            TICK - 1_000,
            Some(ReadError::Failed("timed out".into())),
            baseline,
        ),
    ];
    for (name, shown_at, read_fails, answered) in cases {
        let fixture = Fixture::new();
        let session = SessionId::new();
        let inbox = fixture.inbox(&session);
        fixture.forge.set(open(12, CheckStatus::Running));
        inbox.watch(&target(12), NOW).await.unwrap();
        fixture.forge.set(open(12, CheckStatus::Failed));
        fixture.forge.take_asked();
        if let Some(error) = read_fails {
            fixture.forge.fail_next(error);
        }

        let shown = fixture
            .service
            .show(
                &session,
                Checkout::NotGit,
                ShowTarget::Linked(pr(12)),
                ShowRead::Fresh,
                shown_at,
            )
            .await;
        fixture.service.tick(TICK).await;

        assert_eq!(
            (shown, fixture.forge.take_asked(), inbox.take_news()),
            (
                Ok(Some(answered)),
                vec![details(&[12]), details(&[12])],
                batch(vec![ci_failed(12, 0)]),
            ),
            "{name}"
        );
    }
}

// Covers: a show of a watched PR read fresh after it merged answers a later
// cached show with that merged detail, not the older one the last tick read,
// while the next tick still reads the PR and tells the watch it ended.
// Otherwise a cached show answers a pre-merge detail beside a set that says
// merged.
// Owner: PR poller
#[tokio::test]
async fn a_cached_show_answers_the_detail_a_fresh_show_read() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    let inbox = fixture.inbox(&session);
    fixture.forge.set(open(12, CheckStatus::Passed));
    inbox.watch(&target(12), NOW).await.unwrap();
    fixture.forge.set(merged(open(12, CheckStatus::Passed)));
    fixture.forge.take_asked();
    let fresh_at = NOW + 10_000;
    fixture
        .service
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Fresh,
            fresh_at,
        )
        .await
        .unwrap();

    let cached = fixture
        .service
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Cached,
            NOW + 20_000,
        )
        .await;
    fixture.service.tick(TICK).await;

    let ends: Vec<Option<End>> = inbox
        .take_news()
        .news
        .into_iter()
        .map(|news| news.end)
        .collect();
    assert_eq!(
        (cached, fixture.forge.take_asked(), ends),
        (
            Ok(Some(Detailed {
                detail: merged(open(12, CheckStatus::Passed)),
                at: fresh_at,
            })),
            vec![details(&[12]), summaries(&[12]), details(&[12])],
            vec![Some(End::Merged {
                by: Some("bob".into()),
                commit: Some("9f8e7d6".into()),
                base: "main".into(),
            })],
        )
    );
}

// Covers: a show of a watched PR that reads it at the time its judged
// detail was read answers a later cached show with its own, later-stored
// read, without reading again. Otherwise the older judged detail wins the
// tie, disagrees with the summary, and the cached show reads the forge.
// Owner: PR service
#[tokio::test]
async fn a_show_read_at_the_time_of_the_judged_detail_answers_cached_shows() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    fixture.forge.set(open(12, CheckStatus::Passed));
    fixture
        .inbox(&session)
        .watch(&target(12), NOW)
        .await
        .unwrap();
    fixture.forge.set(edited(open(12, CheckStatus::Passed)));
    fixture
        .service
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Fresh,
            NOW,
        )
        .await
        .unwrap();

    let cached = fixture
        .service
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Cached,
            NOW + 1_000,
        )
        .await;

    assert_eq!(
        (cached, fixture.forge.take_asked()),
        (
            Ok(Some(Detailed {
                detail: edited(open(12, CheckStatus::Passed)),
                at: NOW,
            })),
            vec![details(&[12]), details(&[12])],
        )
    );
}

// Covers: after a daemon restart, before any tick asked for a watched PR,
// a cached show whose read of it fails is not read again by a cached show
// within the shown cadence: the failure keeps its own time, apart from the
// tick's ask. Otherwise a failing PR is read on every show until a tick.
// Owner: PR poller
#[tokio::test]
async fn a_failed_show_after_a_restart_waits_before_reading_again() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    fixture.forge.set(open(12, CheckStatus::Passed));
    fixture
        .inbox(&session)
        .watch(&target(12), NOW)
        .await
        .unwrap();
    let forge = ScriptedForge::new();
    forge.set(open(12, CheckStatus::Passed));
    forge.fail_next(ReadError::Failed("timed out".into()));
    let restarted = PullRequests::open(fixture.dir.path(), forge.clone());

    let failed = restarted
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Cached,
            TICK,
        )
        .await;
    let again = restarted
        .show(
            &session,
            Checkout::NotGit,
            ShowTarget::Linked(pr(12)),
            ShowRead::Cached,
            TICK + 5_000,
        )
        .await;

    assert_eq!(
        (failed, again, forge.take_asked()),
        (Ok(None), Ok(None), vec![details(&[12])])
    );
}

// Covers: a PR a shown branch's lookup finds anew in a tick gets its detail
// in that tick's second query, so a panel showing the branch answers with
// it at once. Otherwise the tick publishes the lookup without the detail
// until a later one.
// Owner: PR poller
#[tokio::test]
async fn a_shown_branch_that_finds_a_pull_request_reads_its_detail() {
    let fixture = Fixture::new();
    let session = SessionId::new();
    let feature = BranchId {
        repo: pr(12).repo,
        branch: "feature".into(),
    };
    let on_feature = || Checkout::Branch(feature.clone());
    fixture.forge.set(open(12, CheckStatus::Passed));
    let before = fixture
        .service
        .show(
            &session,
            on_feature(),
            ShowTarget::Branch,
            ShowRead::Cached,
            NOW,
        )
        .await;
    fixture.forge.set_branch(&target(12), "feature");
    fixture.forge.take_asked();
    let tick = NOW + millis(SHOWN_POLL);

    fixture.service.tick(tick).await;

    let asked = fixture.forge.take_asked();
    let after = fixture
        .service
        .show(
            &session,
            on_feature(),
            ShowTarget::Branch,
            ShowRead::Cached,
            tick,
        )
        .await;
    let lookup = FetchPlan {
        branches: vec![feature.clone()],
        ..FetchPlan::default()
    };
    assert_eq!(
        (before, asked, after, fixture.forge.take_asked()),
        (
            Ok(None),
            vec![lookup, details(&[12])],
            Ok(Some(Detailed {
                detail: open(12, CheckStatus::Passed),
                at: tick,
            })),
            Vec::new(),
        )
    );
}