interprex-github 3.0.0

GitHub provider for all Interprex development-platform domains
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
use std::time::Duration;

use interprex::{
    ChangeRequestHead, ChangeRequestNumber, ChangeRequestState, CheckConclusion, CheckStatus,
    CodeReviewsProvider, FindingResolution, FindingResolutionReason, FindingResolutionReply,
    FindingSeverity, Mergeability, ProviderError, Repository, ReviewActorKind, ReviewRequestTarget,
    ReviewRequestTargetInspection, ReviewTarget, ReviewTargetsProvider, ReviewTeamKind,
    ReviewThreadId,
};
use tokio::time::timeout;

use super::http_fixture::{
    assert_user_request, json_responses, provider, repository, rest_filtered_pages, server,
    status_json_responses,
};

const NOT_FOUND: &str = r#"{"message":"Not Found","documentation_url":"https://docs.github.test"}"#;

#[tokio::test]
async fn review_target_inspection_finds_a_bot_after_the_user_spelling_is_missing() {
    let (uri, requests) = status_json_responses(vec![
        ("404 Not Found", NOT_FOUND),
        (
            "200 OK",
            r#"{"node_id":"BOT_review","login":"review-bot[bot]","type":"Bot"}"#,
        ),
    ])
    .await;

    let inspection = provider(uri)
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::User("review-bot".to_owned()),
        )
        .await
        .expect("target inspection");

    assert!(matches!(
        inspection,
        ReviewRequestTargetInspection::KindMismatch(ReviewTarget::Actor(actor))
            if actor.login == "review-bot[bot]" && actor.kind == ReviewActorKind::Bot
    ));
    let requests = requests.await.expect("captured requests");
    assert_user_request(&requests[0], "GET /users/review%2Dbot ");
    assert_user_request(&requests[1], "GET /users/review%2Dbot%5Bbot%5D ");
}

#[tokio::test]
async fn user_inspection_stops_when_the_exact_spelling_exists() {
    let (uri, requests) = status_json_responses(vec![(
        "200 OK",
        r#"{"node_id":"U_review","login":"review-bot","type":"User"}"#,
    )])
    .await;

    let inspection = provider(uri)
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::User("review-bot".to_owned()),
        )
        .await
        .expect("target inspection");

    assert!(matches!(
        inspection,
        ReviewRequestTargetInspection::Matching(ReviewTarget::Actor(actor))
            if actor.login == "review-bot" && actor.kind == ReviewActorKind::User
    ));
    let requests = requests.await.expect("captured requests");
    assert_eq!(requests.len(), 1);
    assert_user_request(&requests[0], "GET /users/review%2Dbot ");
}

#[tokio::test]
async fn bot_inspection_prefers_the_canonical_suffix() {
    let (uri, requests) = status_json_responses(vec![(
        "200 OK",
        r#"{"node_id":"BOT_review","login":"review-bot[bot]","type":"Bot"}"#,
    )])
    .await;

    let inspection = provider(uri)
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::Bot("review-bot".to_owned()),
        )
        .await
        .expect("target inspection");

    assert!(matches!(
        inspection,
        ReviewRequestTargetInspection::Matching(ReviewTarget::Actor(actor))
            if actor.kind == ReviewActorKind::Bot
    ));
    let requests = requests.await.expect("captured requests");
    assert_eq!(requests.len(), 1);
    assert_user_request(&requests[0], "GET /users/review%2Dbot%5Bbot%5D ");
}

#[tokio::test]
async fn review_target_inspection_distinguishes_unresolvable_from_operational_failure() {
    let (missing_uri, missing_requests) = status_json_responses(vec![
        ("404 Not Found", NOT_FOUND),
        ("404 Not Found", NOT_FOUND),
    ])
    .await;
    assert_eq!(
        provider(missing_uri)
            .inspect_review_request_target(
                &repository(),
                &ReviewRequestTarget::User("unknown".to_owned()),
            )
            .await
            .expect("missing is an inspection outcome"),
        ReviewRequestTargetInspection::NotResolvable
    );
    assert_eq!(missing_requests.await.expect("captured requests").len(), 2);

    let (failure_uri, failure_requests) = status_json_responses(vec![(
        "500 Internal Server Error",
        r#"{"message":"service unavailable","documentation_url":"https://docs.github.test"}"#,
    )])
    .await;
    let error = provider(failure_uri)
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::User("unknown".to_owned()),
        )
        .await
        .expect_err("operational failure remains an error");
    assert!(matches!(
        error,
        ProviderError::External {
            provider: "github",
            operation: "inspect review request target",
            ..
        }
    ));
    assert_eq!(
        failure_requests.await.expect("captured requests").len(),
        1,
        "a non-404 failure must stop fallback lookup"
    );
}

#[tokio::test]
async fn review_target_inspection_normalizes_organization_teams() {
    let (uri, requests) = status_json_responses(vec![(
        "200 OK",
        r#"{"node_id":"T_maintainers","slug":"maintainers","name":"Maintainers"}"#,
    )])
    .await;
    let inspection = provider(uri)
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::Team("civitas-forge/maintainers".to_owned()),
        )
        .await
        .expect("team inspection");
    assert!(matches!(
        inspection,
        ReviewRequestTargetInspection::Matching(ReviewTarget::Team(team))
            if team.id.as_str() == "T_maintainers"
                && team.slug == "maintainers"
                && team.name == "Maintainers"
                && team.kind == ReviewTeamKind::Organization
    ));
    let requests = requests.await.expect("captured requests");
    assert_user_request(&requests[0], "GET /orgs/civitas%2Dforge/teams/maintainers ");
}

#[tokio::test]
async fn review_target_inspection_rejects_a_malformed_team_before_transport() {
    let error = provider("http://127.0.0.1:1".to_owned())
        .inspect_review_request_target(
            &repository(),
            &ReviewRequestTarget::Team("maintainers".to_owned()),
        )
        .await
        .expect_err("malformed team address");
    assert!(matches!(
        error,
        ProviderError::InvalidInput { provider: "github", ref fact }
            if fact.contains("organization/team-slug")
    ));
}

#[tokio::test]
async fn code_review_domain_lists_open_change_requests_for_a_fork_head_across_pages() {
    let route = "/repos/civitas-forge/interprex-sandbox/pulls";
    let (uri, requests) = rest_filtered_pages(
        route,
        "head=contributor%3Afeature&state=open&",
        vec![
            r#"[{"number":5,"head":{"ref":"feature","sha":"aaa","repo":{"full_name":"contributor/interprex-sandbox"}}},
                 {"number":6,"head":{"ref":"feature","sha":"bbb","repo":{"full_name":"contributor/another-sandbox"}}}]"#,
            r#"[{"number":9,"head":{"ref":"feature","sha":"ccc","repo":{"full_name":"contributor/interprex-sandbox"}}}]"#,
        ],
    )
    .await;
    let fork = Repository::new("contributor", "interprex-sandbox").expect("repository");
    let numbers = provider(uri)
        .open_change_requests(
            &repository(),
            &ChangeRequestHead::new(fork, "refs/heads/feature").expect("head"),
        )
        .await
        .expect("open change requests");
    assert_eq!(
        numbers
            .iter()
            .map(|number| number.get())
            .collect::<Vec<_>>(),
        [5, 9],
        "6 proposes the same owner's branch in another repository, which is another head"
    );
    let requests = requests.await.expect("captured requests");
    assert_user_request(
        &requests[0],
        "GET /repos/civitas-forge/interprex-sandbox/pulls?head=contributor%3Afeature&state=open&per_page=100 ",
    );
    assert!(requests[1].starts_with(
        "GET /repos/civitas-forge/interprex-sandbox/pulls?head=contributor%3Afeature&state=open&per_page=100&page=2 "
    ));
}

#[tokio::test]
async fn code_review_domain_requests_users_bots_and_teams_through_the_login_mutation() {
    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json"),
        r#"{"data":{"requestReviewsByLogin":{"pullRequest":{"id":"PR_kwDOExample"}}}}"#,
    ])
    .await;
    provider(uri)
        .request_reviewers(
            &repository(),
            ChangeRequestNumber::new(5).expect("number"),
            &[
                ReviewRequestTarget::User("alice".to_owned()),
                ReviewRequestTarget::Bot("copilot-pull-request-reviewer".to_owned()),
                ReviewRequestTarget::Team("civitas-forge/maintainers".to_owned()),
            ],
        )
        .await
        .expect("review request");
    let requests = timeout(Duration::from_secs(1), requests)
        .await
        .expect("provider sent both requests")
        .expect("captured requests");
    assert_user_request(
        &requests[0],
        "GET /repos/civitas-forge/interprex-sandbox/pulls/5 ",
    );
    assert_user_request(&requests[1], "POST /graphql ");
    let (_, body) = requests[1].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert!(
        body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("requestReviewsByLogin")
    );
    assert_eq!(body["variables"]["pullRequestId"], "PR_kwDOExample");
    assert_eq!(
        body["variables"]["userLogins"],
        serde_json::json!(["alice"])
    );
    assert_eq!(
        body["variables"]["botLogins"],
        serde_json::json!(["copilot-pull-request-reviewer[bot]"])
    );
    assert_eq!(
        body["variables"]["teamSlugs"],
        serde_json::json!(["civitas-forge/maintainers"])
    );
}

#[tokio::test]
async fn code_review_domain_resolves_the_review_handle_before_marking_ready() {
    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json"),
        r#"{"data":{"markPullRequestReadyForReview":{"pullRequest":{"id":"PR_kwDOExample","isDraft":false}}}}"#,
    ])
    .await;
    provider(uri)
        .mark_ready(&repository(), ChangeRequestNumber::new(5).expect("number"))
        .await
        .expect("mark ready");
    let requests = requests.await.expect("captured requests");
    assert_user_request(
        &requests[0],
        "GET /repos/civitas-forge/interprex-sandbox/pulls/5 ",
    );
    assert_user_request(&requests[1], "POST /graphql ");
    let (_, body) = requests[1].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert_eq!(body["variables"]["pullRequestId"], "PR_kwDOExample");
}

#[tokio::test]
async fn code_review_domain_resolves_a_scoped_review_thread_handle() {
    let (uri, request) = server(
        "200 OK",
        "application/json",
        r#"{"data":{"resolveReviewThread":{"thread":{"id":"PRRT_kwDOExample","isResolved":true}}}}"#,
    )
    .await;
    provider(uri)
        .resolve_thread(
            &repository(),
            ChangeRequestNumber::new(5).expect("number"),
            &ReviewThreadId::new("PRRT_kwDOExample").expect("thread id"),
        )
        .await
        .expect("resolve thread");
    let request = request.await.expect("captured request");
    assert_user_request(&request, "POST /graphql ");
    let (_, body) = request.split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert_eq!(body["variables"]["threadId"], "PRRT_kwDOExample");
}

#[tokio::test]
async fn code_review_domain_rejects_an_unconfirmed_thread_resolution() {
    let (uri, _request) = server(
        "200 OK",
        "application/json",
        r#"{"data":{"resolveReviewThread":{"thread":{"id":"PRRT_kwDOOther","isResolved":false}}}}"#,
    )
    .await;
    let error = provider(uri)
        .resolve_thread(
            &repository(),
            ChangeRequestNumber::new(5).expect("number"),
            &ReviewThreadId::new("PRRT_kwDOExample").expect("thread id"),
        )
        .await
        .expect_err("mismatched unresolved response must fail");

    assert!(error.to_string().contains("isResolved=false"));
    assert!(error.to_string().contains("PRRT_kwDOOther"));
}

#[tokio::test]
async fn code_review_domain_records_a_finding_resolution_before_resolving_the_thread() {
    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json").to_owned(),
        include_str!("../fixtures/code_review_reviews.json").to_owned(),
        include_str!("../fixtures/review_threads_response.json").replace(
            "\"isResolved\": true",
            "\"isResolved\": false",
        ),
        include_str!("../fixtures/review_requests_response.json").to_owned(),
        include_str!("../fixtures/review_request_timeline_second_page.json").to_owned(),
        include_str!("../fixtures/unanchored_comments.json").to_owned(),
        r#"{"data":{"addPullRequestReviewThreadReply":{"comment":{"id":"PRRC_resolution"}}}}"#
            .to_owned(),
        r#"{"data":{"resolveReviewThread":{"thread":{"id":"PRRT_kwDOSCkZoc6LuYFt","isResolved":true}}}}"#
            .to_owned(),
    ])
    .await;
    provider(uri)
        .resolve_finding(
            &repository(),
            ChangeRequestNumber::new(5).expect("number"),
            &ReviewThreadId::new("PRRT_kwDOSCkZoc6LuYFt").expect("thread id"),
            FindingResolution {
                reason: FindingResolutionReason::Invalid,
                addressing_severity: FindingSeverity::Minor,
            },
            &FindingResolutionReply::new(
                "The reported state cannot be reached through the public interface.",
            )
            .expect("resolution explanation"),
        )
        .await
        .expect("resolve finding");

    let requests = requests.await.expect("captured requests");
    assert_eq!(requests.len(), 8);
    assert_user_request(&requests[6], "POST /graphql ");
    assert_user_request(&requests[7], "POST /graphql ");
    let (_, reply_body) = requests[6]
        .split_once("\r\n\r\n")
        .expect("reply request body");
    let reply_body: serde_json::Value =
        serde_json::from_str(reply_body).expect("JSON reply request body");
    assert!(
        reply_body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("addPullRequestReviewThreadReply")
    );
    assert_eq!(reply_body["variables"]["threadId"], "PRRT_kwDOSCkZoc6LuYFt");
    let posted = reply_body["variables"]["body"]
        .as_str()
        .expect("reply Markdown");
    assert!(posted.contains("**Resolution:** Invalid"));
    assert!(posted.contains("**Addressing severity:** Minor"));
    assert!(posted.contains("<!-- interprex:finding-resolution"));
    assert!(posted.contains("\"resolution_reason\":\"INVALID\""));
    assert!(posted.contains("\"addressing_severity\":\"minor\""));

    let (_, resolve_body) = requests[7]
        .split_once("\r\n\r\n")
        .expect("resolve request body");
    let resolve_body: serde_json::Value =
        serde_json::from_str(resolve_body).expect("JSON resolve request body");
    assert_eq!(
        resolve_body["variables"]["threadId"],
        "PRRT_kwDOSCkZoc6LuYFt"
    );
}

#[tokio::test]
async fn code_review_domain_reads_one_complete_observation() {
    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json"),
        include_str!("../fixtures/code_review_reviews.json"),
        include_str!("../fixtures/review_threads_response.json"),
        include_str!("../fixtures/review_requests_response.json"),
        include_str!("../fixtures/review_request_timeline_first_page.json"),
        include_str!("../fixtures/review_request_timeline_second_page.json"),
        include_str!("../fixtures/unanchored_comments.json"),
    ])
    .await;
    let change_request = provider(uri)
        .change_request(&repository(), ChangeRequestNumber::new(5).expect("number"))
        .await
        .expect("change request");

    assert_eq!(change_request.state, ChangeRequestState::Open);
    assert_eq!(change_request.reviews.len(), 11);
    assert_eq!(
        change_request
            .reviews
            .iter()
            .filter(|item| item.state == interprex::ReviewState::Draft)
            .count(),
        1
    );
    assert_eq!(
        change_request
            .reviews
            .iter()
            .filter(|item| {
                item.author.relationship() == interprex::ReviewRelationship::ChangeAuthor
            })
            .count(),
        1
    );
    assert_eq!(
        change_request
            .reviews
            .iter()
            .filter(|item| item.author.relationship() == interprex::ReviewRelationship::Unknown)
            .count(),
        2
    );
    assert_eq!(change_request.reviews[0].findings[0].replies.len(), 1);
    assert!(
        change_request
            .reviews
            .last()
            .expect("last review")
            .findings
            .is_empty()
    );
    assert_eq!(change_request.outstanding_requests.len(), 2);
    assert_eq!(
        change_request
            .outstanding_requests
            .iter()
            .map(|request| request.requested_at)
            .collect::<Vec<_>>(),
        [
            Some(
                "2026-06-23T09:00:00Z"
                    .parse::<chrono::DateTime<chrono::Utc>>()
                    .expect("request timestamp")
            ),
            Some(
                "2026-06-23T09:15:00Z"
                    .parse::<chrono::DateTime<chrono::Utc>>()
                    .expect("request timestamp")
            ),
        ],
        "the re-request on the second timeline page supersedes the removal on the first"
    );
    assert_eq!(change_request.unanchored_comments.len(), 1);
    assert_eq!(change_request.mergeability, Mergeability::Mergeable);
    let requests = requests.await.expect("captured requests");
    assert_user_request(
        &requests[0],
        "GET /repos/civitas-forge/interprex-sandbox/pulls/5 ",
    );
    assert_user_request(
        &requests[1],
        "GET /repos/civitas-forge/interprex-sandbox/pulls/5/reviews?per_page=100 ",
    );
    assert_user_request(&requests[2], "POST /graphql ");
    assert_user_request(&requests[3], "POST /graphql ");
    assert_user_request(&requests[4], "POST /graphql ");
    assert_user_request(&requests[5], "POST /graphql ");
    assert_user_request(
        &requests[6],
        "GET /repos/civitas-forge/interprex-sandbox/issues/5/comments?per_page=100 ",
    );
    let (_, body) = requests[2].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert!(
        body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("pullRequestReview { id }")
    );
    assert!(
        !body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("databaseId")
    );
    assert!(
        body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("subjectType")
    );
    let (_, body) = requests[3].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert!(
        body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("reviewRequests")
    );
    assert!(
        body["query"]
            .as_str()
            .expect("GraphQL document")
            .contains("organization { login }")
    );
    let (_, body) = requests[4].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    let timeline_query = body["query"].as_str().expect("GraphQL document").to_owned();
    assert!(timeline_query.contains("timelineItems"));
    assert!(
        timeline_query
            .contains("itemTypes: [REVIEW_REQUESTED_EVENT, REVIEW_REQUEST_REMOVED_EVENT]")
    );
    assert!(timeline_query.contains("ReviewRequestedEvent"));
    assert!(timeline_query.contains("ReviewRequestRemovedEvent"));
    assert_eq!(body["variables"]["number"], 5);
    assert_eq!(body["variables"]["cursor"], serde_json::Value::Null);
    let (_, body) = requests[5].split_once("\r\n\r\n").expect("request body");
    let body: serde_json::Value = serde_json::from_str(body).expect("JSON request body");
    assert_eq!(body["query"], serde_json::json!(timeline_query));
    assert_eq!(body["variables"]["cursor"], "timeline-page-1");
}

#[tokio::test]
async fn code_review_domain_reads_no_timeline_without_an_outstanding_request() {
    let mut review_requests: serde_json::Value =
        serde_json::from_str(include_str!("../fixtures/review_requests_response.json"))
            .expect("review request fixture");
    review_requests["data"]["repository"]["pullRequest"]["reviewRequests"]["nodes"] =
        serde_json::json!([]);
    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json").to_owned(),
        include_str!("../fixtures/code_review_reviews.json").to_owned(),
        include_str!("../fixtures/review_threads_response.json").to_owned(),
        serde_json::to_string(&review_requests).expect("review request response"),
        include_str!("../fixtures/unanchored_comments.json").to_owned(),
    ])
    .await;

    let change_request = provider(uri)
        .change_request(&repository(), ChangeRequestNumber::new(5).expect("number"))
        .await
        .expect("change request");

    assert!(change_request.outstanding_requests.is_empty());
    let requests = requests.await.expect("captured requests");
    assert_eq!(requests.len(), 5);
    assert_user_request(
        &requests[4],
        "GET /repos/civitas-forge/interprex-sandbox/issues/5/comments?per_page=100 ",
    );
}

#[tokio::test]
async fn code_review_domain_preserves_a_standalone_thread() {
    let mut threads: serde_json::Value =
        serde_json::from_str(include_str!("../fixtures/review_threads_response.json"))
            .expect("thread fixture");
    threads["data"]["repository"]["pullRequest"]["reviewThreads"]["nodes"][0]["comments"]["nodes"]
        [0]["pullRequestReview"] = serde_json::Value::Null;
    let threads = serde_json::to_string(&threads).expect("thread response");
    let (uri, _) = json_responses(vec![
        include_str!("../fixtures/pull_request.json").to_owned(),
        include_str!("../fixtures/code_review_reviews.json").to_owned(),
        threads,
        include_str!("../fixtures/review_requests_response.json").to_owned(),
        include_str!("../fixtures/review_request_timeline_second_page.json").to_owned(),
        include_str!("../fixtures/unanchored_comments.json").to_owned(),
    ])
    .await;

    let change_request = provider(uri)
        .change_request(&repository(), ChangeRequestNumber::new(5).expect("number"))
        .await
        .expect("change request");

    assert_eq!(change_request.standalone_threads.len(), 1);
    assert_eq!(
        change_request.standalone_threads[0].id.as_str(),
        "PRRT_kwDOSCkZoc6LuYFt"
    );
    assert!(
        change_request
            .reviews
            .iter()
            .all(|item| item.findings.is_empty())
    );
}

#[tokio::test]
async fn code_review_domain_recovers_when_reviews_temporarily_lag_threads() {
    let mut lagging_reviews: Vec<serde_json::Value> =
        serde_json::from_str(include_str!("../fixtures/code_review_reviews.json"))
            .expect("review fixture");
    lagging_reviews.remove(0);
    let lagging_reviews = serde_json::to_string(&lagging_reviews).expect("review response");

    let (uri, requests) = json_responses(vec![
        include_str!("../fixtures/pull_request.json").to_owned(),
        lagging_reviews,
        include_str!("../fixtures/review_threads_response.json").to_owned(),
        include_str!("../fixtures/code_review_reviews.json").to_owned(),
        include_str!("../fixtures/review_threads_response.json").to_owned(),
        include_str!("../fixtures/review_requests_response.json").to_owned(),
        include_str!("../fixtures/review_request_timeline_second_page.json").to_owned(),
        include_str!("../fixtures/unanchored_comments.json").to_owned(),
    ])
    .await;

    let change_request = provider(uri)
        .change_request(&repository(), ChangeRequestNumber::new(5).expect("number"))
        .await
        .expect("change request");

    assert_eq!(change_request.reviews.len(), 11);
    assert_eq!(change_request.reviews[0].findings.len(), 1);
    let requests = requests.await.expect("captured requests");
    assert_eq!(requests.len(), 8);
    assert_user_request(
        &requests[3],
        "GET /repos/civitas-forge/interprex-sandbox/pulls/5/reviews?per_page=100 ",
    );
    assert_user_request(&requests[4], "POST /graphql ");
}

fn check_run_page(names: impl IntoIterator<Item = String>, total_count: usize) -> String {
    let runs = names
        .into_iter()
        .map(|name| {
            serde_json::json!({
                "name": name,
                "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
                "status": "completed",
                "conclusion": "success",
                "completed_at": "2026-08-24T10:04:00Z",
                "app": { "id": 1042, "slug": "quality-app", "name": "Quality App" },
                "html_url": "https://github.invalid/runs/1",
                "output": { "title": name, "summary": "settled" }
            })
        })
        .collect::<Vec<_>>();
    serde_json::json!({ "total_count": total_count, "check_runs": runs }).to_string()
}

#[tokio::test]
async fn code_review_domain_returns_check_runs_from_every_page() {
    let full_page = check_run_page((1..=100).map(|index| format!("check-{index}")), 101);
    // The last page repeats a name from the first page, as a second check
    // suite on the same commit does.
    let last_page = serde_json::json!({
        "total_count": 101,
        "check_runs": [{
            "name": "check-1",
            "head_sha": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
            "status": "in_progress",
            "conclusion": null,
            "completed_at": null,
            "app": { "id": 2087, "slug": "rerun-app", "name": "Rerun App" },
            "html_url": null,
            "output": { "title": null, "summary": null }
        }]
    })
    .to_string();
    let (uri, requests) = json_responses(vec![full_page, last_page]).await;

    let runs = provider(uri)
        .checks(&repository(), "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        .await
        .expect("check runs");

    assert_eq!(runs.len(), 101);
    assert_eq!(runs[0].name, "check-1");
    assert_eq!(
        runs[0]
            .via_app
            .as_ref()
            .map(|app| app.id.as_str().to_owned()),
        Some("1042".to_owned()),
        "the publishing app is the identifier a ruleset names as integration_id"
    );
    assert_eq!(
        runs[0].status,
        CheckStatus::Completed {
            conclusion: CheckConclusion::Success,
            completed_at: "2026-08-24T10:04:00Z".parse().expect("completion time"),
        }
    );
    assert_eq!(
        runs[100].name, "check-1",
        "a run sharing a name with another is returned, not collapsed into it"
    );
    assert_eq!(runs[100].status, CheckStatus::InProgress);
    assert_eq!(
        runs[100]
            .via_app
            .as_ref()
            .map(|app| app.id.as_str().to_owned()),
        Some("2087".to_owned())
    );

    let requests = timeout(Duration::from_secs(1), requests)
        .await
        .expect("provider read both pages")
        .expect("captured requests");
    assert_eq!(requests.len(), 2);
    assert_user_request(
        &requests[0],
        "GET /repos/civitas-forge/interprex-sandbox/commits/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/check-runs?per_page=100&page=1&filter=latest ",
    );
    assert_user_request(
        &requests[1],
        "GET /repos/civitas-forge/interprex-sandbox/commits/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa/check-runs?per_page=100&page=2&filter=latest ",
    );
}

#[tokio::test]
async fn code_review_domain_stops_reading_check_runs_at_the_reported_total() {
    let full_page = check_run_page((1..=100).map(|index| format!("check-{index}")), 100);
    let (uri, requests) = json_responses(vec![full_page]).await;

    let runs = provider(uri)
        .checks(&repository(), "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
        .await
        .expect("check runs");

    assert_eq!(runs.len(), 100);
    assert_eq!(
        timeout(Duration::from_secs(1), requests)
            .await
            .expect("provider read one page")
            .expect("captured requests")
            .len(),
        1
    );
}