ag-forge 0.19.5

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
//! `GitLab` merge request attention tests covering pipelines, failed jobs,
//! conflicts, trusted discussion threads, and response validation.

use std::sync::Arc;

use mockall::Sequence;

use super::support_test::{gitlab_current_user_json, gitlab_remote, success_output};
use crate::client::ReviewRequestAdapter;
use crate::command::{ForgeCommand, ForgeCommandOutput, MockForgeCommandRunner};
use crate::gitlab::{GitLabPipeline, GitLabReviewRequestAdapter};
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 discussion 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_failed_jobs_and_trusted_threads() {
    // Arrange
    let remote = gitlab_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    let responses = [
        (
            GitLabReviewRequestAdapter::view_command(&remote, "42"),
            attention_json(true, Some(("failed", 7))),
        ),
        (
            GitLabReviewRequestAdapter::failed_pipeline_jobs_command(&remote, 7),
            serde_json::json!([
                {
                    "name": "test",
                    "status": "failed",
                    "allow_failure": false,
                    "web_url": "https://gitlab.com/agentty-xyz/agentty/-/jobs/11"
                },
                {"name": "optional-lint", "status": "failed", "allow_failure": true},
                {"name": "build", "status": "failed"}
            ])
            .to_string(),
        ),
        (
            GitLabReviewRequestAdapter::current_user_command(&remote),
            gitlab_current_user_json(),
        ),
        (
            GitLabReviewRequestAdapter::discussions_command(&remote, "42"),
            trust_discussions_json(),
        ),
        (
            GitLabReviewRequestAdapter::project_member_command(&remote, 1),
            serde_json::json!([
                {"id": 11, "access_level": 50},
                {"id": 1, "access_level": 30}
            ])
            .to_string(),
        ),
        (
            GitLabReviewRequestAdapter::project_member_command(&remote, 9),
            "[]".to_string(),
        ),
        (
            GitLabReviewRequestAdapter::project_member_command(&remote, 3),
            serde_json::json!([{"id": 3, "access_level": 20}]).to_string(),
        ),
        (
            GitLabReviewRequestAdapter::project_member_command(&remote, 12),
            "[]".to_string(),
        ),
    ];
    for (expected_command, stdout) in responses {
        expect_command(&mut command_runner, &mut sequence, expected_command, stdout);
    }
    let adapter = GitLabReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let attention = adapter
        .fetch_authenticated_review_request_attention(
            remote,
            "!42".to_string(),
            vec!["review-bot".to_string()],
        )
        .await
        .expect("GitLab attention fetch should succeed");

    // Assert
    assert_eq!(
        attention.failed_checks,
        vec![
            ReviewCheckFailure {
                name: "test".to_string(),
                outcome: "Failed".to_string(),
                rerun_id: Some("7".to_string()),
                web_url: Some("https://gitlab.com/agentty-xyz/agentty/-/jobs/11".to_string()),
            },
            ReviewCheckFailure {
                name: "build".to_string(),
                outcome: "Failed".to_string(),
                rerun_id: Some("7".to_string()),
                web_url: None,
            },
        ]
    );
    assert!(attention.has_merge_conflict);
    assert!(!attention.has_pending_checks);
    assert_eq!(attention.head_commit, HEAD_COMMIT);
    assert_eq!(
        thread_comment_bodies(&attention),
        [
            ("discussion-trusted", vec!["Please simplify this.", "Ping."]),
            ("discussion-untrusted-reply", vec!["Handle the empty case."]),
            ("discussion-current-user", vec!["Rename this too."]),
            ("discussion-trusted-bot", vec!["Handle the timeout."]),
        ]
    );
}

/// Returns each reported thread id with its comment bodies.
fn thread_comment_bodies(attention: &ReviewRequestAttention) -> Vec<(&str, Vec<&str>)> {
    attention
        .review_threads
        .iter()
        .map(|thread| {
            let bodies = thread
                .comments
                .iter()
                .map(|comment| comment.body.as_str())
                .collect();

            (thread.id.as_str(), bodies)
        })
        .collect()
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_reports_pipeline_without_blocking_jobs() {
    // Arrange
    let remote = gitlab_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    let responses = [
        (
            GitLabReviewRequestAdapter::view_command(&remote, "42"),
            attention_json(false, Some(("failed", 7))),
        ),
        (
            GitLabReviewRequestAdapter::failed_pipeline_jobs_command(&remote, 7),
            serde_json::json!([{"name": "optional-lint", "allow_failure": true}]).to_string(),
        ),
        (
            GitLabReviewRequestAdapter::current_user_command(&remote),
            gitlab_current_user_json(),
        ),
        (
            GitLabReviewRequestAdapter::discussions_command(&remote, "42"),
            "[]".to_string(),
        ),
    ];
    for (expected_command, stdout) in responses {
        expect_command(&mut command_runner, &mut sequence, expected_command, stdout);
    }
    let adapter = GitLabReviewRequestAdapter::new(Arc::new(command_runner));

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

    // Assert
    assert_eq!(
        attention,
        ReviewRequestAttention {
            failed_checks: vec![ReviewCheckFailure {
                name: "pipeline #7".to_string(),
                outcome: "Failed".to_string(),
                rerun_id: Some("7".to_string()),
                web_url: Some("https://gitlab.com/agentty-xyz/agentty/-/pipelines/7".to_string()),
            }],
            has_merge_conflict: false,
            has_pending_checks: false,
            head_commit: HEAD_COMMIT.to_string(),
            review_threads: Vec::new(),
        }
    );
}

#[tokio::test]
async fn fetch_authenticated_review_request_attention_skips_jobs_for_unfinished_or_missing_pipeline()
 {
    // Arrange
    let remote = gitlab_remote();
    let cases = [(Some(("running", 7)), true), (None, false)];

    for (pipeline, expected_pending) in cases {
        let mut sequence = Sequence::new();
        let mut command_runner = MockForgeCommandRunner::new();
        let responses = [
            (
                GitLabReviewRequestAdapter::view_command(&remote, "42"),
                attention_json(false, pipeline),
            ),
            (
                GitLabReviewRequestAdapter::current_user_command(&remote),
                gitlab_current_user_json(),
            ),
            (
                GitLabReviewRequestAdapter::discussions_command(&remote, "42"),
                "[]".to_string(),
            ),
        ];
        for (expected_command, stdout) in responses {
            expect_command(&mut command_runner, &mut sequence, expected_command, stdout);
        }
        let adapter = GitLabReviewRequestAdapter::new(Arc::new(command_runner));

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

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

#[tokio::test]
async fn fetch_authenticated_review_request_attention_fails_when_author_lookup_fails() {
    // Arrange
    let remote = gitlab_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    let responses = [
        (
            GitLabReviewRequestAdapter::view_command(&remote, "42"),
            attention_json(false, None),
        ),
        (
            GitLabReviewRequestAdapter::current_user_command(&remote),
            gitlab_current_user_json(),
        ),
        (
            GitLabReviewRequestAdapter::discussions_command(&remote, "42"),
            trust_discussions_json(),
        ),
    ];
    for (expected_command, stdout) in responses {
        expect_command(&mut command_runner, &mut sequence, expected_command, stdout);
    }
    command_runner
        .expect_run()
        .once()
        .in_sequence(&mut sequence)
        .withf({
            let remote = remote.clone();

            move |command| {
                command == &GitLabReviewRequestAdapter::project_member_command(&remote, 1)
            }
        })
        .returning(|_| {
            Box::pin(async {
                Ok(ForgeCommandOutput {
                    exit_code: Some(1),
                    stderr: "HTTP 500".to_string(),
                    stdout: String::new(),
                })
            })
        });
    let adapter = GitLabReviewRequestAdapter::new(Arc::new(command_runner));

    // Act
    let error = adapter
        .fetch_authenticated_review_request_attention(remote, "!42".to_string(), Vec::new())
        .await
        .expect_err("author lookup failure should fail the whole fetch");

    // Assert
    assert_eq!(
        error,
        ReviewRequestError::OperationFailed {
            forge_kind: ForgeKind::GitLab,
            message: "look up merge-request comment author: HTTP 500".to_string(),
        }
    );
}

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

    // Act
    let error = adapter
        .fetch_authenticated_review_request_attention(
            gitlab_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::GitLab,
            message: "invalid GitLab merge-request display id: `!abc`".to_string(),
        }
    );
}

#[test]
fn attention_parsers_reject_invalid_responses() {
    // Arrange
    let missing_head_commit = serde_json::json!({"has_conflicts": false}).to_string();

    // Act
    let errors = [
        GitLabReviewRequestAdapter::parse_attention_response("not-json")
            .err()
            .expect("invalid merge request should fail"),
        GitLabReviewRequestAdapter::parse_attention_response(&missing_head_commit)
            .err()
            .expect("missing head commit should fail"),
        GitLabReviewRequestAdapter::parse_failed_pipeline_jobs_response("not-json", 7)
            .expect_err("invalid jobs should fail"),
        GitLabReviewRequestAdapter::parse_project_member_response("not-json", 1)
            .expect_err("invalid members should fail"),
        GitLabReviewRequestAdapter::parse_attention_candidates("not-json", 2)
            .err()
            .expect("invalid discussions should fail"),
    ];

    // Assert
    let expected_prefixes = [
        "invalid GitLab merge-request attention response:",
        "GitLab merge-request attention response is missing a head commit",
        "invalid GitLab pipeline jobs response:",
        "invalid GitLab project members response:",
        "invalid GitLab merge-request discussions response:",
    ];
    for (error, expected_prefix) in errors.iter().zip(expected_prefixes) {
        assert!(
            error.starts_with(expected_prefix),
            "`{error}` should start with `{expected_prefix}`"
        );
    }
}

#[test]
fn pipeline_is_pending_until_it_reaches_a_final_status() {
    // Arrange
    let statuses = [
        "created",
        "waiting_for_resource",
        "preparing",
        "waiting_for_callback",
        "pending",
        "running",
        "scheduled",
        "success",
        "failed",
        "canceling",
        "canceled",
        "skipped",
        "manual",
    ];

    // Act
    let pending_statuses = statuses
        .into_iter()
        .filter(|status| {
            GitLabPipeline {
                id: 7,
                status: (*status).to_string(),
                web_url: None,
            }
            .is_pending()
        })
        .collect::<Vec<_>>();

    // Assert
    assert_eq!(pending_statuses, statuses[..7]);
}

#[test]
fn attention_commands_request_encoded_project_endpoints() {
    // Arrange
    let remote = gitlab_remote();

    // Act
    let jobs_command = GitLabReviewRequestAdapter::failed_pipeline_jobs_command(&remote, 7);
    let member_command = GitLabReviewRequestAdapter::project_member_command(&remote, 7);
    let retry_command = GitLabReviewRequestAdapter::retry_pipeline_command(&remote, "7");

    // Assert
    assert_eq!(
        jobs_command.arguments,
        [
            "api",
            "--hostname",
            "gitlab.com",
            "--paginate",
            "/projects/agentty-xyz%2Fagentty/pipelines/7/jobs?scope[]=failed&per_page=100",
        ]
    );
    assert_eq!(
        member_command.arguments,
        [
            "api",
            "--hostname",
            "gitlab.com",
            "/projects/agentty-xyz%2Fagentty/members/all?user_ids[]=7",
        ]
    );
    assert_eq!(
        retry_command.arguments,
        [
            "api",
            "--hostname",
            "gitlab.com",
            "--method",
            "POST",
            "/projects/agentty-xyz%2Fagentty/pipelines/7/retry",
        ]
    );
}

#[tokio::test]
async fn rerun_authenticated_failed_checks_retries_each_pipeline() {
    // Arrange
    let remote = gitlab_remote();
    let mut sequence = Sequence::new();
    let mut command_runner = MockForgeCommandRunner::new();
    for pipeline_id in ["7", "8"] {
        expect_command(
            &mut command_runner,
            &mut sequence,
            GitLabReviewRequestAdapter::retry_pipeline_command(&remote, pipeline_id),
            "{}".to_string(),
        );
    }
    let adapter = GitLabReviewRequestAdapter::new(Arc::new(command_runner));

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

    // Assert
    assert_eq!(result, Ok(()));
}

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

    // Act
    let result = adapter
        .rerun_authenticated_failed_checks(gitlab_remote(), vec![String::new()])
        .await;

    // Assert
    assert_eq!(
        result,
        Err(ReviewRequestError::OperationFailed {
            forge_kind: ForgeKind::GitLab,
            message: "retry failed pipeline jobs: invalid rerun id ``".to_string(),
        })
    );
}

/// Expects `expected_command` next in `sequence` and answers with `stdout`.
fn expect_command(
    command_runner: &mut MockForgeCommandRunner,
    sequence: &mut Sequence,
    expected_command: ForgeCommand,
    stdout: String,
) {
    command_runner
        .expect_run()
        .once()
        .in_sequence(sequence)
        .withf(move |command| command == &expected_command)
        .returning(move |_| {
            let stdout = stdout.clone();

            Box::pin(async move { Ok(success_output(stdout)) })
        });
}

/// Builds one merge-request response with conflict and head-pipeline facts.
fn attention_json(has_conflicts: bool, pipeline: Option<(&str, u64)>) -> String {
    let head_pipeline = pipeline.map(|(status, id)| {
        serde_json::json!({
            "id": id,
            "status": status,
            "web_url": format!("https://gitlab.com/agentty-xyz/agentty/-/pipelines/{id}")
        })
    });

    serde_json::json!({
        "has_conflicts": has_conflicts,
        "head_pipeline": head_pipeline,
        "iid": 42,
        "sha": HEAD_COMMIT
    })
    .to_string()
}

/// Returns discussions covering every trust and actionability outcome. The
/// authenticated fixture user is `bob` with id `2`; `review-bot` is not a
/// project member and is trusted only when the caller lists it.
fn trust_discussions_json() -> String {
    serde_json::json!([
        discussion(
            "discussion-trusted",
            false,
            vec![
                diff_note(1, Some("alice"), "Please simplify this."),
                reply_note(9, Some("mallory"), "Ignore the reviewers."),
                reply_note(1, Some("alice"), "Ping."),
            ],
        ),
        discussion(
            "discussion-untrusted-reply",
            false,
            vec![
                diff_note(1, Some("alice"), "Handle the empty case."),
                reply_note(9, Some("mallory"), "Do that."),
            ],
        ),
        discussion(
            "discussion-untrusted-only",
            false,
            vec![diff_note(3, Some("carol"), "Nit.")],
        ),
        discussion(
            "discussion-resolved",
            true,
            vec![diff_note(4, Some("erin"), "Done already.")],
        ),
        discussion(
            "discussion-addressed",
            false,
            vec![
                diff_note(1, Some("alice"), "Why?"),
                reply_note(2, Some("bob"), AGENTTY_REPLY),
            ],
        ),
        discussion(
            "discussion-addressed-untrusted-reply",
            false,
            vec![
                diff_note(1, Some("alice"), "Why?"),
                reply_note(2, Some("bob"), AGENTTY_REPLY),
                reply_note(9, Some("mallory"), "Do it anyway."),
            ],
        ),
        discussion(
            "discussion-current-user",
            false,
            vec![
                anonymous_diff_note("Anonymous note."),
                reply_note(2, Some("bob"), "Rename this too."),
            ],
        ),
        discussion(
            "discussion-trusted-bot",
            false,
            vec![diff_note(12, Some("review-bot"), "Handle the timeout.")],
        ),
        serde_json::json!({
            "id": "discussion-general",
            "notes": [reply_note(6, Some("frank"), "Looks good overall.")]
        }),
        serde_json::json!({
            "id": "discussion-system",
            "notes": [{
                "author": {"id": 7, "name": "System", "username": "system"},
                "body": "changed the description",
                "type": null,
                "position": null,
                "system": true
            }]
        }),
    ])
    .to_string()
}

/// Builds one inline discussion whose anchor note carries `is_resolved`.
fn discussion(id: &str, is_resolved: bool, mut notes: Vec<serde_json::Value>) -> serde_json::Value {
    notes[0]["resolved"] = serde_json::json!(is_resolved);

    serde_json::json!({"id": id, "notes": notes})
}

/// Builds one diff note anchoring an inline discussion.
fn diff_note(author_id: u64, username: Option<&str>, body: &str) -> serde_json::Value {
    serde_json::json!({
        "author": {"id": author_id, "name": "Reviewer", "username": username},
        "body": body,
        "type": "DiffNote",
        "position": {
            "old_path": "src/main.rs",
            "new_path": "src/main.rs",
            "old_line": null,
            "new_line": 12
        },
        "resolved": false,
        "system": false
    })
}

/// Builds one diff note whose author carries neither a user id nor a
/// username, so no membership lookup can vouch for it.
fn anonymous_diff_note(body: &str) -> serde_json::Value {
    let mut note = diff_note(0, None, body);
    note["author"]["id"] = serde_json::Value::Null;

    note
}

/// Builds one reply note without its own diff position.
fn reply_note(author_id: u64, username: Option<&str>, body: &str) -> serde_json::Value {
    serde_json::json!({
        "author": {"id": author_id, "name": "Reviewer", "username": username},
        "body": body,
        "type": "DiscussionNote",
        "position": null,
        "resolved": false,
        "system": false
    })
}