ag-forge 0.19.4

Agentty is an ADE (Agentic Development Environment) for structured, controllable AI-assisted software development.
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
//! `GitHub` review-request attention tests covering check pagination,
//! conflicts, pending checks, and trusted bot comments.

use std::sync::Arc;

use mockall::Sequence;

use super::support_test::{
    ReviewThreadFixture, associated_review_comment_node, current_user_review_comment_node,
    failure_output, github_remote, review_comment_node, review_threads_page, success_output,
    thread_comments_page,
};
use crate::client::ReviewRequestAdapter;
use crate::command::MockForgeCommandRunner;
use crate::github::GitHubReviewRequestAdapter;
use crate::model::{ForgeKind, ReviewCheckFailure, ReviewRequestAttention, ReviewRequestError};

/// Head commit reported by the attention fixtures.
const HEAD_COMMIT: &str = "0123456789abcdef0123456789abcdef01234567";
/// Agentty reply marker body used to mark a thread addressed.
const AGENTTY_REPLY: &str =
    "No change needed.\n\n<!-- agentty review resolution:123e4567-e89b-12d3-a456-426614174000 -->";

#[tokio::test]
async fn fetch_authenticated_review_request_attention_reports_checks_conflicts_and_trusted_threads()
{
    // Arrange
    let remote = github_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| command == &GitHubReviewRequestAdapter::attention_command(&remote, "42")
        })
        .returning(|_| {
            Box::pin(async {
                Ok(success_output(attention_json(
                    "CONFLICTING",
                    &mixed_check_contexts(),
                )))
            })
        });
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| {
                command == &GitHubReviewRequestAdapter::review_threads_command(&remote, "42")
            }
        })
        .returning(|_| Box::pin(async { Ok(success_output(trust_review_threads_json())) }));
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let attention = adapter
        .fetch_authenticated_review_request_attention(remote, "#42".to_string(), Vec::new())
        .await
        .expect("GitHub attention fetch should succeed");

    // Assert
    assert_eq!(attention.failed_checks, mixed_check_failures());
    assert!(attention.has_merge_conflict);
    assert!(attention.has_pending_checks);
    assert_eq!(attention.head_commit, HEAD_COMMIT);
    let thread_ids = attention
        .review_threads
        .iter()
        .map(|thread| thread.id.as_str())
        .collect::<Vec<_>>();
    assert_eq!(
        thread_ids,
        ["thread-trusted", "thread-untrusted-reply", "thread-viewer"]
    );
    let thread_bodies = attention
        .review_threads
        .iter()
        .map(|thread| {
            thread
                .comments
                .iter()
                .map(|comment| comment.body.as_str())
                .collect::<Vec<_>>()
        })
        .collect::<Vec<_>>();
    assert_eq!(
        thread_bodies,
        [
            vec!["Fix this.", "Agreed, please fix."],
            vec!["Handle the empty case."],
            vec!["Also rename this."],
        ]
    );
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_trusts_comments_from_later_thread_pages() {
    // Arrange
    let remote = github_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| command == &GitHubReviewRequestAdapter::attention_command(&remote, "42")
        })
        .returning(|_| Box::pin(async { Ok(success_output(attention_json("MERGEABLE", &[]))) }));
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| {
                command == &GitHubReviewRequestAdapter::review_threads_command(&remote, "42")
            }
        })
        .returning(|_| {
            Box::pin(async {
                Ok(success_output(
                    serde_json::json!([review_threads_page(vec![thread_fixture(
                        "thread-large",
                        false,
                        true,
                        vec![review_comment_node(Some("mallory"), "First page")],
                    )])])
                    .to_string(),
                ))
            })
        });
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| {
                command
                    == &GitHubReviewRequestAdapter::thread_comments_command(&remote, "thread-large")
            }
        })
        .returning(|_| {
            Box::pin(async {
                Ok(success_output(
                    serde_json::json!([
                        thread_comments_page(vec![review_comment_node(
                            Some("mallory"),
                            "First page"
                        )]),
                        thread_comments_page(vec![associated_review_comment_node(
                            "alice",
                            "MEMBER",
                            "Second page"
                        )]),
                    ])
                    .to_string(),
                ))
            })
        });
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let attention = adapter
        .fetch_authenticated_review_request_attention(remote, "42".to_string(), Vec::new())
        .await
        .expect("oversized review thread should load all comments");

    // Assert
    assert_eq!(attention.failed_checks, Vec::new());
    assert!(!attention.has_merge_conflict);
    assert!(!attention.has_pending_checks);
    assert_eq!(attention.review_threads.len(), 1);
    assert_eq!(attention.review_threads[0].comments.len(), 1);
    assert_eq!(attention.review_threads[0].comments[0].author, "alice");
    assert_eq!(attention.review_threads[0].comments[0].body, "Second page");
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_rejects_invalid_display_id() {
    // Arrange
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(MockForgeCommandRunner::new()));

    // Act
    let error = adapter
        .fetch_authenticated_review_request_attention(
            github_remote(),
            "#abc".to_string(),
            Vec::new(),
        )
        .await
        .expect_err("invalid display id should fail before running commands");

    // Assert
    assert_eq!(
        error,
        ReviewRequestError::OperationFailed {
            forge_kind: ForgeKind::GitHub,
            message: "invalid GitHub pull-request display id: `#abc`".to_string(),
        }
    );
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_reports_missing_pull_request() {
    // Arrange
    let remote = github_remote();
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner.expect_run().once().returning(|_| {
        Box::pin(async {
            Ok(success_output(
                r#"[{"data":{"repository":{"pullRequest":null}}}]"#.to_string(),
            ))
        })
    });
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let error = adapter
        .fetch_authenticated_review_request_attention(remote, "#42".to_string(), Vec::new())
        .await
        .expect_err("missing pull request should fail");

    // Assert
    assert_eq!(
        error,
        ReviewRequestError::OperationFailed {
            forge_kind: ForgeKind::GitHub,
            message: "GitHub pull-request attention response is missing a pull request".to_string(),
        }
    );
}

#[test]
fn parse_attention_pages_rejects_invalid_json_and_empty_page_lists() {
    // Arrange
    let invalid_stdout = "not-json";
    let empty_stdout = "[]";

    // Act
    let invalid_error = GitHubReviewRequestAdapter::parse_attention_pages(invalid_stdout, &[])
        .expect_err("invalid JSON should fail");
    let empty_error = GitHubReviewRequestAdapter::parse_attention_pages(empty_stdout, &[])
        .expect_err("a response without pages should fail");

    // Assert
    assert!(invalid_error.starts_with("invalid GitHub pull-request attention response:"));
    assert_eq!(
        empty_error,
        "GitHub pull-request attention response contains no pages"
    );
}

#[test]
fn parse_attention_pages_combines_checks_beyond_the_first_page() {
    // Arrange
    let first_page_contexts = (0..100)
        .map(|index| {
            check_run(
                &format!("passing-{index}"),
                "COMPLETED",
                Some("SUCCESS"),
                None,
            )
        })
        .collect::<Vec<_>>();
    let cases = [
        (
            vec![check_run("late-build", "IN_PROGRESS", None, None)],
            "MERGEABLE",
            true,
            Vec::new(),
        ),
        (
            vec![check_run("late-test", "COMPLETED", Some("FAILURE"), None)],
            "CONFLICTING",
            false,
            vec![ReviewCheckFailure {
                name: "late-test".to_string(),
                outcome: "Failure".to_string(),
                rerun_id: None,
                web_url: None,
            }],
        ),
    ];

    for (later_contexts, later_mergeable, expected_pending, expected_failures) in cases {
        let stdout = attention_pages_json(&[
            attention_page(HEAD_COMMIT, "MERGEABLE", &first_page_contexts),
            attention_page(HEAD_COMMIT, later_mergeable, &later_contexts),
        ]);

        // Act
        let attention = GitHubReviewRequestAdapter::parse_attention_pages(&stdout, &[])
            .expect("paginated attention response should parse");

        // Assert
        assert_eq!(attention.has_pending_checks, expected_pending);
        assert_eq!(attention.failed_checks, expected_failures);
        assert_eq!(
            attention.has_merge_conflict,
            later_mergeable == "CONFLICTING"
        );
        assert_eq!(attention.head_commit, HEAD_COMMIT);
    }
}

#[test]
fn parse_attention_pages_reads_rerun_ids_only_from_github_actions_run_urls() {
    // Arrange
    let mut other_app_run = check_run(
        "other-app",
        "COMPLETED",
        Some("FAILURE"),
        Some("https://github.com/agentty-xyz/agentty/actions/runs/5/job/1"),
    );
    other_app_run["checkSuite"] = serde_json::json!({"app": {"slug": "other-ci"}});
    let contexts = [
        actions_check_run(
            "job-url",
            Some("https://github.com/agentty-xyz/agentty/actions/runs/101/job/9"),
        ),
        actions_check_run(
            "run-url",
            Some("https://github.com/agentty-xyz/agentty/actions/runs/202?pr=1"),
        ),
        actions_check_run(
            "plain-url",
            Some("https://github.com/agentty-xyz/agentty/runs/3"),
        ),
        actions_check_run(
            "non-numeric",
            Some("https://github.com/agentty-xyz/agentty/actions/runs/latest"),
        ),
        actions_check_run(
            "empty-id",
            Some("https://github.com/agentty-xyz/agentty/actions/runs/"),
        ),
        actions_check_run("no-url", None),
        other_app_run,
    ];
    let stdout = attention_json("MERGEABLE", &contexts);

    // Act
    let attention = GitHubReviewRequestAdapter::parse_attention_pages(&stdout, &[])
        .expect("attention response should parse");

    // Assert
    let rerun_ids = attention
        .failed_checks
        .iter()
        .map(|failure| (failure.name.as_str(), failure.rerun_id.as_deref()))
        .collect::<Vec<_>>();
    assert_eq!(
        rerun_ids,
        [
            ("job-url", Some("101")),
            ("run-url", Some("202")),
            ("plain-url", None),
            ("non-numeric", None),
            ("empty-id", None),
            ("no-url", None),
            ("other-app", None),
        ]
    );
}

#[test]
fn parse_attention_pages_rejects_a_head_commit_that_changed_between_pages() {
    // Arrange
    let stdout = attention_pages_json(&[
        attention_page(HEAD_COMMIT, "MERGEABLE", &[]),
        attention_page(
            "fedcba9876543210fedcba9876543210fedcba98",
            "MERGEABLE",
            &[check_run("test", "COMPLETED", Some("FAILURE"), None)],
        ),
    ]);

    // Act
    let error = GitHubReviewRequestAdapter::parse_attention_pages(&stdout, &[])
        .expect_err("checks from two head commits should not be combined");

    // Assert
    assert_eq!(
        error,
        "GitHub pull-request head commit changed while its checks were loading"
    );
}

#[test]
fn parse_attention_pages_without_check_rollup_reports_no_checks() {
    // Arrange
    let stdout = serde_json::json!([{
        "data": {"repository": {"pullRequest": {
            "headRefOid": HEAD_COMMIT,
            "mergeable": "UNKNOWN",
            "statusCheckRollup": null
        }}}
    }])
    .to_string();

    // Act
    let attention = GitHubReviewRequestAdapter::parse_attention_pages(&stdout, &[])
        .expect("attention without checks should parse");

    // Assert
    assert_eq!(
        attention,
        ReviewRequestAttention {
            head_commit: HEAD_COMMIT.to_string(),
            ..ReviewRequestAttention::default()
        }
    );
}

#[test]
fn parse_attention_pages_reports_pending_checks_per_context_kind() {
    // Arrange
    let cases = [
        (
            vec![status_context(Some("ci/pending"), "PENDING", None)],
            true,
        ),
        (vec![check_run("build", "QUEUED", None, None)], true),
        (
            vec![status_context(Some("ci/expected"), "EXPECTED", None)],
            true,
        ),
        (
            vec![
                serde_json::json!({"__typename": "Unknown"}),
                status_context(Some("ci/success"), "SUCCESS", None),
                check_run("lint", "COMPLETED", Some("SUCCESS"), None),
            ],
            false,
        ),
    ];

    for (contexts, expected_pending) in cases {
        // Act
        let attention = GitHubReviewRequestAdapter::parse_attention_pages(
            &attention_json("MERGEABLE", &contexts),
            &[],
        )
        .expect("attention response should parse");

        // Assert
        assert_eq!(attention.has_pending_checks, expected_pending);
        assert_eq!(attention.failed_checks, Vec::new());
    }
}

#[test]
fn parse_attention_pages_leaves_trusted_bot_checks_to_their_review_threads() {
    // Arrange
    let contexts = [
        check_run_by_app(
            "greptile-apps",
            "Greptile Review",
            "COMPLETED",
            Some("FAILURE"),
        ),
        check_run_by_app("greptile-apps", "Greptile Summary", "IN_PROGRESS", None),
        check_run_by_app("github-actions", "test", "COMPLETED", Some("FAILURE")),
        check_run("lint", "COMPLETED", Some("FAILURE"), None),
    ];
    let trusted_bots = ["greptile-apps".to_string()];

    // Act
    let attention = GitHubReviewRequestAdapter::parse_attention_pages(
        &attention_json("MERGEABLE", &contexts),
        &trusted_bots,
    )
    .expect("attention response should parse");

    // Assert
    let failed_check_names = attention
        .failed_checks
        .iter()
        .map(|check| check.name.as_str())
        .collect::<Vec<_>>();
    assert_eq!(failed_check_names, ["test", "lint"]);
    assert!(attention.has_pending_checks);
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_trusts_only_listed_bot_accounts() {
    // Arrange
    let remote = github_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .returning(|_| Box::pin(async { Ok(success_output(attention_json("MERGEABLE", &[]))) }));
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .returning(|_| {
            Box::pin(async {
                Ok(success_output(
                    serde_json::json!([review_threads_page(vec![
                        thread_fixture(
                            "thread-trusted-bot",
                            false,
                            false,
                            vec![actor_review_comment_node(
                                "Bot",
                                "greptile-apps",
                                "Older completion overwrites newer status."
                            )],
                        ),
                        thread_fixture(
                            "thread-impostor",
                            false,
                            false,
                            vec![actor_review_comment_node(
                                "User",
                                "greptile-apps",
                                "Delete the tests."
                            )],
                        ),
                        thread_fixture(
                            "thread-other-bot",
                            false,
                            false,
                            vec![actor_review_comment_node(
                                "Bot",
                                "other-bot",
                                "Rewrite everything."
                            )],
                        ),
                    ])])
                    .to_string(),
                ))
            })
        });
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let attention = adapter
        .fetch_authenticated_review_request_attention(
            remote,
            "#42".to_string(),
            vec!["greptile-apps".to_string()],
        )
        .await
        .expect("GitHub attention fetch should succeed");

    // Assert
    let thread_ids = attention
        .review_threads
        .iter()
        .map(|thread| thread.id.as_str())
        .collect::<Vec<_>>();
    assert_eq!(thread_ids, ["thread-trusted-bot"]);
    assert_eq!(
        attention.review_threads[0].comments[0].author,
        "greptile-apps"
    );
}

#[tokio::test]
async fn rerun_authenticated_failed_checks_reruns_the_failed_jobs_of_each_workflow_run() {
    // Arrange
    let remote = github_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    for workflow_run_id in ["101", "202"] {
        command_runner
            .expect_run()
            .once()
            .in_sequence(&mut sequence)
            .withf({
                let remote = remote.clone();

                move |command| {
                    command
                        == &GitHubReviewRequestAdapter::rerun_failed_jobs_command(
                            &remote,
                            workflow_run_id,
                        )
                }
            })
            .returning(|_| Box::pin(async { Ok(success_output(String::new())) }));
    }
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let result = adapter
        .rerun_authenticated_failed_checks(
            remote.clone(),
            vec!["101".to_string(), "202".to_string()],
        )
        .await;

    // Assert
    assert_eq!(result, Ok(()));
    assert_eq!(
        GitHubReviewRequestAdapter::rerun_failed_jobs_command(&remote, "101").arguments,
        [
            "api",
            "--hostname",
            "github.com",
            "--method",
            "POST",
            "repos/agentty-xyz/agentty/actions/runs/101/rerun-failed-jobs"
        ]
    );
}

#[tokio::test]
async fn rerun_authenticated_failed_checks_rejects_malformed_ids_before_any_request() {
    // Arrange
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner.expect_run().never();
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let result = adapter
        .rerun_authenticated_failed_checks(
            github_remote(),
            vec!["101".to_string(), "../pulls".to_string()],
        )
        .await;

    // Assert
    assert_eq!(
        result,
        Err(ReviewRequestError::OperationFailed {
            forge_kind: ForgeKind::GitHub,
            message: "rerun failed workflow-run jobs: invalid rerun id `../pulls`".to_string(),
        })
    );
}

#[tokio::test]
async fn rerun_authenticated_failed_checks_reports_a_rejected_rerun() {
    // Arrange
    let mut command_runner = MockForgeCommandRunner::new();
    command_runner
        .expect_run()
        .once()
        .returning(|_| Box::pin(async { Ok(failure_output("HTTP 403: Forbidden".to_string())) }));
    let adapter = GitHubReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let result = adapter
        .rerun_authenticated_failed_checks(github_remote(), vec!["101".to_string()])
        .await;

    // Assert
    let error = result.expect_err("a rejected rerun should fail");
    assert!(
        error
            .detail_message()
            .contains("rerun failed workflow-run jobs: HTTP 403: Forbidden"),
        "unexpected error: {error:?}"
    );
}

#[test]
fn attention_command_paginates_every_check_context_page() {
    // Arrange
    let remote = github_remote();

    // Act
    let command = GitHubReviewRequestAdapter::attention_command(&remote, "42");

    // Assert
    assert_eq!(command.executable, "gh");
    assert_eq!(
        command.arguments[..6],
        [
            "api",
            "--hostname",
            "github.com",
            "graphql",
            "--paginate",
            "--slurp"
        ]
    );
    assert!(command.arguments.iter().any(|argument| {
        argument.starts_with("query=")
            && argument.contains("$endCursor: String")
            && argument.contains("headRefOid mergeable")
            && argument.contains("contexts(first: 100, after: $endCursor)")
            && argument.contains("pageInfo { hasNextPage endCursor }")
    }));
    assert!(
        command
            .arguments
            .iter()
            .any(|argument| argument == "number=42")
    );
}

/// Builds a one-page attention response for `mergeable` and check
/// `contexts`.
fn attention_json(mergeable: &str, contexts: &[serde_json::Value]) -> String {
    attention_pages_json(&[attention_page(HEAD_COMMIT, mergeable, contexts)])
}

/// Combines attention pages the way `gh api graphql --paginate --slurp`
/// does.
fn attention_pages_json(pages: &[serde_json::Value]) -> String {
    serde_json::Value::Array(pages.to_vec()).to_string()
}

/// Builds one attention page for `head_commit`, `mergeable`, and check
/// `contexts`.
fn attention_page(
    head_commit: &str,
    mergeable: &str,
    contexts: &[serde_json::Value],
) -> serde_json::Value {
    serde_json::json!({
        "data": {"repository": {"pullRequest": {
            "headRefOid": head_commit,
            "mergeable": mergeable,
            "statusCheckRollup": {"contexts": {
                "nodes": contexts,
                "pageInfo": {"hasNextPage": false, "endCursor": null}
            }}
        }}}
    })
}

/// Returns the failures normalized from [`mixed_check_contexts`]; only the
/// GitHub Actions check run with a workflow run id carries a rerun id.
fn mixed_check_failures() -> Vec<ReviewCheckFailure> {
    vec![
        ReviewCheckFailure {
            name: "test".to_string(),
            outcome: "Failure".to_string(),
            rerun_id: Some("101".to_string()),
            web_url: Some(
                "https://github.com/agentty-xyz/agentty/actions/runs/101/job/1".to_string(),
            ),
        },
        ReviewCheckFailure {
            name: "slow".to_string(),
            outcome: "Timed out".to_string(),
            rerun_id: None,
            web_url: None,
        },
        ReviewCheckFailure {
            name: "boot".to_string(),
            outcome: "Startup failure".to_string(),
            rerun_id: None,
            web_url: None,
        },
        ReviewCheckFailure {
            name: "ci/legacy".to_string(),
            outcome: "Error".to_string(),
            rerun_id: None,
            web_url: Some("https://ci.example.com/build/7".to_string()),
        },
        ReviewCheckFailure {
            name: String::new(),
            outcome: "Failure".to_string(),
            rerun_id: None,
            web_url: None,
        },
    ]
}

/// Returns check runs and commit statuses covering every normalized outcome.
fn mixed_check_contexts() -> Vec<serde_json::Value> {
    vec![
        actions_check_run(
            "test",
            Some("https://github.com/agentty-xyz/agentty/actions/runs/101/job/1"),
        ),
        check_run("slow", "COMPLETED", Some("TIMED_OUT"), Some("")),
        check_run("boot", "COMPLETED", Some("STARTUP_FAILURE"), None),
        check_run("build", "IN_PROGRESS", None, None),
        check_run("canceled", "COMPLETED", Some("CANCELLED"), None),
        check_run("lint", "COMPLETED", Some("SUCCESS"), None),
        check_run("unfinished", "COMPLETED", None, None),
        status_context(
            Some("ci/legacy"),
            "ERROR",
            Some("https://ci.example.com/build/7"),
        ),
        status_context(None, "FAILURE", None),
        status_context(Some("ci/pending"), "PENDING", None),
        status_context(Some("ci/expected"), "EXPECTED", None),
        serde_json::Value::Null,
        serde_json::json!({"__typename": "Unknown"}),
    ]
}

/// Builds one GraphQL check-run context node.
fn check_run(
    name: &str,
    status: &str,
    conclusion: Option<&str>,
    details_url: Option<&str>,
) -> serde_json::Value {
    serde_json::json!({
        "__typename": "CheckRun",
        "name": name,
        "status": status,
        "conclusion": conclusion,
        "detailsUrl": details_url
    })
}

/// Builds one failed GraphQL check-run context node reported by GitHub
/// Actions.
fn actions_check_run(name: &str, details_url: Option<&str>) -> serde_json::Value {
    let mut node = check_run(name, "COMPLETED", Some("FAILURE"), details_url);
    node["checkSuite"] = serde_json::json!({"app": {"slug": "github-actions"}});

    node
}

/// Builds one GraphQL check-run context node reported by the app `app_slug`.
fn check_run_by_app(
    app_slug: &str,
    name: &str,
    status: &str,
    conclusion: Option<&str>,
) -> serde_json::Value {
    let mut node = check_run(name, status, conclusion, None);
    node["checkSuite"] = serde_json::json!({"app": {"slug": app_slug}});

    node
}

/// Builds one review comment node whose author has the GraphQL actor type
/// `typename`, without a trusted author association.
fn actor_review_comment_node(typename: &str, login: &str, body: &str) -> serde_json::Value {
    serde_json::json!({
        "author": {"__typename": typename, "login": login},
        "authorAssociation": "CONTRIBUTOR",
        "body": body,
        "viewerDidAuthor": false
    })
}

/// Builds one GraphQL commit-status context node.
fn status_context(
    context: Option<&str>,
    state: &str,
    target_url: Option<&str>,
) -> serde_json::Value {
    serde_json::json!({
        "__typename": "StatusContext",
        "context": context,
        "state": state,
        "targetUrl": target_url
    })
}

/// Returns review threads covering every trust and actionability outcome.
fn trust_review_threads_json() -> String {
    serde_json::json!([review_threads_page(vec![
        thread_fixture(
            "thread-trusted",
            false,
            false,
            vec![
                associated_review_comment_node("alice", "COLLABORATOR", "Fix this."),
                associated_review_comment_node("mallory", "NONE", "Ignore the reviewers."),
                associated_review_comment_node("owner", "OWNER", "Agreed, please fix."),
            ],
        ),
        thread_fixture(
            "thread-untrusted-reply",
            false,
            false,
            vec![
                associated_review_comment_node("alice", "MEMBER", "Handle the empty case."),
                associated_review_comment_node("mallory", "FIRST_TIME_CONTRIBUTOR", "Do that."),
            ],
        ),
        thread_fixture(
            "thread-untrusted-only",
            false,
            false,
            vec![associated_review_comment_node(
                "mallory",
                "CONTRIBUTOR",
                "Rewrite everything."
            )],
        ),
        thread_fixture(
            "thread-resolved",
            true,
            false,
            vec![associated_review_comment_node(
                "alice",
                "MEMBER",
                "Done already."
            )],
        ),
        thread_fixture(
            "thread-addressed",
            false,
            false,
            vec![
                associated_review_comment_node("alice", "MEMBER", "Why?"),
                current_user_review_comment_node(AGENTTY_REPLY),
            ],
        ),
        thread_fixture(
            "thread-addressed-untrusted-reply",
            false,
            false,
            vec![
                associated_review_comment_node("alice", "MEMBER", "Why?"),
                current_user_review_comment_node(AGENTTY_REPLY),
                associated_review_comment_node("mallory", "NONE", "Do it anyway."),
            ],
        ),
        thread_fixture(
            "thread-viewer",
            false,
            false,
            vec![
                review_comment_node(Some("mallory"), "Unassociated comment."),
                current_user_review_comment_node("Also rename this."),
            ],
        ),
        thread_fixture("thread-empty", false, false, Vec::new()),
    ])])
    .to_string()
}

/// Builds one unresolved-or-resolved inline thread node for trust tests.
fn thread_fixture(
    id: &str,
    is_resolved: bool,
    has_next_comment_page: bool,
    comments: Vec<serde_json::Value>,
) -> serde_json::Value {
    ReviewThreadFixture {
        comments,
        diff_side: "RIGHT",
        has_next_comment_page,
        id,
        is_resolved,
        line: Some(7),
        path: "src/lib.rs",
        subject_type: "LINE",
    }
    .into_node()
}