agentty 0.13.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
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
//! Published-branch post-turn synchronization for session workers.

use std::path::PathBuf;
use std::str::FromStr;
use std::sync::{Arc, Mutex};

use ag_forge as forge;
use ag_git::GitClient;
use ag_protocol::ReviewCommentOutcome;
use tokio::sync::{OwnedMutexGuard, mpsc};
use uuid::Uuid;

use super::SessionTaskService;
use crate::app::session::{
    Clock, SessionError, remote_branch_name_from_upstream_ref, unix_timestamp_from_system_time,
};
use crate::app::{AppEvent, branch_publish};
use crate::domain::session::{
    PublishBranchAction, PublishedBranchSyncStatus, ReviewRequest, ReviewRequestState, SessionId,
};
use crate::domain::session_message::SessionTranscript;
use crate::domain::transcript_notice::TranscriptNotice;
use crate::infra::db::AppRepositories;

/// Owned inputs required to start one detached published-branch auto-push.
pub(super) struct PublishedBranchAutoPushStartInput {
    /// Reducer event sender used to publish auto-push progress and completion.
    pub(super) app_event_tx: mpsc::UnboundedSender<AppEvent>,
    /// Per-session guard retained until the detached push finishes.
    pub(super) branch_operation_guard: OwnedMutexGuard<()>,
    /// Clock used to timestamp optional review-request metadata refresh.
    pub(super) clock: Arc<dyn Clock>,
    /// Repository bundle used to resolve and persist branch-publish state.
    pub(super) db: AppRepositories,
    /// Session worktree folder pushed to its tracked upstream branch.
    pub(super) folder: PathBuf,
    /// Git boundary used for the remote push operation.
    pub(super) git_client: Arc<dyn GitClient>,
    /// Published upstream reference that provides the remote branch target.
    pub(super) published_upstream_ref: String,
    /// Fixed review-thread outcomes eligible for post-push forge updates.
    pub(super) review_comment_outcomes: Vec<ReviewCommentOutcome>,
    /// Forge boundary used for optional linked PR/MR metadata refresh.
    pub(super) review_request_client: Arc<dyn forge::ReviewRequestClient>,
    /// Optional auto-commit message used to refresh linked PR/MR metadata.
    pub(super) review_request_commit_message: Option<String>,
    /// Session id whose branch is being pushed.
    pub(super) session_id: SessionId,
    /// Per-app session update versions shared with the main runtime.
    pub(super) session_update_versions: crate::app::service::SessionUpdateVersionMap,
    /// Shared typed transcript snapshot mirrored to the render layer.
    pub(super) transcript: Arc<Mutex<SessionTranscript>>,
}

/// Starts one detached auto-push task for a session that already tracks a
/// published upstream branch.
pub(super) fn start_published_branch_auto_push(input: PublishedBranchAutoPushStartInput) {
    let branch_operation_guard = input.branch_operation_guard;
    let sync_operation_id = Uuid::new_v4().to_string();
    let review_request_metadata_sync =
        input
            .review_request_commit_message
            .map(|commit_message| ReviewRequestMetadataSyncInput {
                clock: Arc::clone(&input.clock),
                commit_message: Some(commit_message),
                review_request_client: Arc::clone(&input.review_request_client),
            });
    let review_comment_resolution =
        (!input.review_comment_outcomes.is_empty()).then(|| ReviewCommentResolutionInput {
            outcomes: input.review_comment_outcomes,
            review_request_client: Arc::clone(&input.review_request_client),
        });

    let _ = input
        .app_event_tx
        .send(AppEvent::PublishedBranchSyncUpdated {
            persistent_notice: None,
            session_id: input.session_id.clone(),
            sync_operation_id: sync_operation_id.clone(),
            sync_status: PublishedBranchSyncStatus::InProgress,
        });

    let auto_push_input = PublishedBranchAutoPushInput {
        app_event_tx: input.app_event_tx,
        db: input.db,
        folder: input.folder,
        git_client: input.git_client,
        published_upstream_ref: input.published_upstream_ref,
        review_comment_resolution,
        review_request_metadata_sync,
        session_id: input.session_id,
        session_update_versions: input.session_update_versions,
        sync_operation_id,
        transcript: input.transcript,
    };
    tokio::spawn(async move {
        let _branch_operation_guard = branch_operation_guard;
        run_published_branch_auto_push_task(auto_push_input).await;
    });
}

/// Owned inputs needed by one detached published-branch auto-push task across
/// session workflows.
pub(super) struct PublishedBranchAutoPushInput {
    /// Reducer event sender used to publish auto-push progress and completion.
    pub(super) app_event_tx: mpsc::UnboundedSender<AppEvent>,
    /// Repository bundle used to resolve and persist branch-publish state.
    pub(super) db: AppRepositories,
    /// Session worktree folder pushed to its tracked upstream branch.
    pub(super) folder: PathBuf,
    /// Git boundary used for the remote push operation.
    pub(super) git_client: Arc<dyn GitClient>,
    /// Published upstream reference that provides the remote branch target.
    pub(super) published_upstream_ref: String,
    /// Optional review-thread outcomes applied only after a successful push.
    pub(super) review_comment_resolution: Option<ReviewCommentResolutionInput>,
    /// Optional metadata sync payload used after a successful post-turn push.
    pub(super) review_request_metadata_sync: Option<ReviewRequestMetadataSyncInput>,
    /// Session id whose branch is being pushed.
    pub(super) session_id: SessionId,
    /// Per-app session update versions shared with the main runtime.
    pub(super) session_update_versions: crate::app::service::SessionUpdateVersionMap,
    /// Auto-push operation id used to ignore stale completion updates.
    pub(super) sync_operation_id: String,
    /// Shared typed transcript snapshot mirrored to the render layer.
    pub(super) transcript: Arc<Mutex<SessionTranscript>>,
}

/// Owned dependencies for one optional linked PR/MR metadata sync after push.
pub(super) struct ReviewRequestMetadataSyncInput {
    /// Clock used to timestamp the refreshed review-request summary.
    pub(super) clock: Arc<dyn Clock>,
    /// Known auto-commit message, or `None` to resolve it after the push.
    pub(super) commit_message: Option<String>,
    /// Forge boundary used to refresh linked PR/MR metadata after a push.
    pub(super) review_request_client: Arc<dyn forge::ReviewRequestClient>,
}

/// Owned dependencies for forge thread replies and resolution after push.
pub(super) struct ReviewCommentResolutionInput {
    /// Fixed, allowlisted outcomes reported by the completed agent turn.
    pub(super) outcomes: Vec<ReviewCommentOutcome>,
    /// Forge boundary used to post replies and resolve review threads.
    pub(super) review_request_client: Arc<dyn forge::ReviewRequestClient>,
}

/// Runs one detached auto-push for a previously published session branch and
/// reports its state through the app event pipeline.
pub(super) async fn run_published_branch_auto_push(input: PublishedBranchAutoPushInput) {
    run_published_branch_auto_push_task(input).await;
}

/// Executes one detached published-branch auto-push from owned task inputs.
async fn run_published_branch_auto_push_task(input: PublishedBranchAutoPushInput) {
    let remote_branch_name = remote_branch_name_from_upstream_ref(&input.published_upstream_ref);
    let push_result = branch_publish::push_session_branch_to_remote(
        &input.db,
        input.folder.clone(),
        Arc::clone(&input.git_client),
        PublishBranchAction::Push,
        &input.session_id,
        Some(remote_branch_name.as_str()),
        Some(&input.published_upstream_ref),
    )
    .await;

    match push_result {
        Ok(_) => {
            if let Some(metadata_sync_input) = input.review_request_metadata_sync.as_ref() {
                sync_linked_review_request_metadata_after_push(&input, metadata_sync_input).await;
            }
            if let Some(resolution_input) = input.review_comment_resolution.as_ref() {
                resolve_review_comments_after_push(&input, resolution_input).await;
            }

            let message = TranscriptNotice::BranchPush
                .format("Auto-pushed published branch after completed turn.");

            let _ = input
                .app_event_tx
                .send(AppEvent::PublishedBranchSyncUpdated {
                    persistent_notice: Some(message),
                    session_id: input.session_id,
                    sync_operation_id: input.sync_operation_id,
                    sync_status: PublishedBranchSyncStatus::Succeeded,
                });
        }
        Err(failure) => {
            let message = TranscriptNotice::BranchPushError.format(failure.message);

            let _ = input
                .app_event_tx
                .send(AppEvent::PublishedBranchSyncUpdated {
                    persistent_notice: Some(message),
                    session_id: input.session_id,
                    sync_operation_id: input.sync_operation_id,
                    sync_status: PublishedBranchSyncStatus::Failed,
                });
        }
    }
}

/// Posts agent-authored replies and resolves their allowlisted review threads
/// after the updated branch is visible on the forge.
async fn resolve_review_comments_after_push(
    input: &PublishedBranchAutoPushInput,
    resolution_input: &ReviewCommentResolutionInput,
) {
    let linked_review_request = match load_open_review_request(input).await {
        Ok(Some(linked_review_request)) => linked_review_request,
        Ok(None) => return,
        Err(error) => {
            append_review_comment_resolution_notice(input, 0, resolution_input.outcomes.len())
                .await;
            tracing::warn!(
                session_id = %input.session_id,
                %error,
                "failed to load linked review request for review-thread resolution"
            );

            return;
        }
    };
    let repo_url = match input.git_client.repo_url(input.folder.clone()).await {
        Ok(repo_url) => repo_url,
        Err(error) => {
            append_review_comment_resolution_notice(input, 0, resolution_input.outcomes.len())
                .await;
            tracing::warn!(
                session_id = %input.session_id,
                %error,
                "failed to resolve repository remote for review-thread resolution"
            );

            return;
        }
    };
    let remote = match resolution_input
        .review_request_client
        .detect_remote(repo_url)
        .map(|remote| remote.with_command_working_directory(input.folder.clone()))
    {
        Ok(remote) => remote,
        Err(error) => {
            append_review_comment_resolution_notice(input, 0, resolution_input.outcomes.len())
                .await;
            let error_detail = error.detail_message();
            tracing::warn!(
                session_id = %input.session_id,
                error = %error_detail,
                "failed to detect forge remote for review-thread resolution"
            );

            return;
        }
    };

    let mut resolved_count = 0;
    for outcome in &resolution_input.outcomes {
        let reply_result = resolution_input
            .review_request_client
            .reply_to_thread(
                remote.clone(),
                linked_review_request.summary.display_id.clone(),
                outcome.thread_id.clone(),
                outcome.reply.clone(),
            )
            .await;
        if let Err(error) = reply_result {
            let error_detail = error.detail_message();
            tracing::warn!(
                session_id = %input.session_id,
                thread_id = %outcome.thread_id,
                error = %error_detail,
                "failed to reply to resolved review thread"
            );

            continue;
        }

        let resolve_result = resolution_input
            .review_request_client
            .resolve_thread(
                remote.clone(),
                linked_review_request.summary.display_id.clone(),
                outcome.thread_id.clone(),
            )
            .await;
        match resolve_result {
            Ok(()) => resolved_count += 1,
            Err(error) => {
                let error_detail = error.detail_message();
                tracing::warn!(
                    session_id = %input.session_id,
                    thread_id = %outcome.thread_id,
                    error = %error_detail,
                    "failed to resolve replied review thread"
                );
            }
        }
    }

    append_review_comment_resolution_notice(input, resolved_count, resolution_input.outcomes.len())
        .await;
}

/// Appends a concise durable result for post-push review-thread updates.
async fn append_review_comment_resolution_notice(
    input: &PublishedBranchAutoPushInput,
    resolved_count: usize,
    total_count: usize,
) {
    let message = if resolved_count == total_count {
        TranscriptNotice::ReviewComments.format(format!(
            "Replied to and resolved {resolved_count} review thread(s)."
        ))
    } else {
        TranscriptNotice::ReviewCommentsWarning.format(format!(
            "Resolved {resolved_count} of {total_count} review thread(s). Reopen review comments \
             to retry the remaining threads."
        ))
    };
    SessionTaskService::append_workflow_notice(
        &input.transcript,
        &input.db,
        &input.app_event_tx,
        &input.session_update_versions,
        &input.session_id,
        &message,
    )
    .await;
}

/// Syncs linked open review-request metadata after the new commit has reached
/// the already-published remote branch.
async fn sync_linked_review_request_metadata_after_push(
    input: &PublishedBranchAutoPushInput,
    metadata_sync_input: &ReviewRequestMetadataSyncInput,
) {
    let linked_review_request = match load_open_review_request(input).await {
        Ok(Some(linked_review_request)) => linked_review_request,
        Ok(None) => return,
        Err(error) => {
            append_review_request_sync_warning(input, error).await;

            return;
        }
    };
    let commit_message = match metadata_sync_input.commit_message.as_deref() {
        Some(commit_message) => commit_message.to_string(),
        None => match input
            .git_client
            .head_commit_message(input.folder.clone())
            .await
        {
            Ok(Some(commit_message)) => commit_message,
            Ok(None) => return,
            Err(error) => {
                append_review_request_sync_warning(
                    input,
                    SessionError::Workflow(format!(
                        "Failed to resolve the session commit message: {error}"
                    )),
                )
                .await;

                return;
            }
        },
    };
    let Some(update_input) = review_request_update_input(&commit_message) else {
        return;
    };

    let result = sync_review_request_metadata(
        input,
        metadata_sync_input,
        &linked_review_request,
        update_input,
    )
    .await;
    if let Err(error) = result {
        append_review_request_sync_warning(input, error).await;
    }
}

/// Builds an update payload from one canonical session commit message.
fn review_request_update_input(commit_message: &str) -> Option<forge::UpdateReviewRequestInput> {
    let review_request_commit_message =
        crate::app::review_request::parse_review_request_commit_message(commit_message)?;

    Some(forge::UpdateReviewRequestInput {
        body: review_request_commit_message.body,
        title: review_request_commit_message.title,
    })
}

/// Loads the linked review request when it is still open.
async fn load_open_review_request(
    input: &PublishedBranchAutoPushInput,
) -> Result<Option<ReviewRequest>, SessionError> {
    let review_request = input
        .db
        .reviews()
        .load_session_review_request(&input.session_id)
        .await
        .map_err(SessionError::from)?
        .and_then(review_request_from_row);

    Ok(review_request
        .filter(|review_request| review_request.summary.state == ReviewRequestState::Open))
}

/// Converts one persisted review-request row into the domain model used by
/// session workflows.
fn review_request_from_row(
    row: crate::infra::db::SessionReviewRequestRow,
) -> Option<ReviewRequest> {
    Some(ReviewRequest {
        last_refreshed_at: row.last_refreshed_at,
        summary: forge::ReviewRequestSummary {
            display_id: row.display_id,
            forge_kind: forge::ForgeKind::from_str(&row.forge_kind).ok()?,
            source_branch: row.source_branch,
            state: ReviewRequestState::from_str(&row.state).ok()?,
            status_summary: row.status_summary,
            target_branch: row.target_branch,
            title: row.title,
            web_url: row.web_url,
        },
    })
}

/// Runs the forge metadata sync and persists the refreshed review-request
/// summary when the provider call succeeds.
async fn sync_review_request_metadata(
    input: &PublishedBranchAutoPushInput,
    metadata_sync_input: &ReviewRequestMetadataSyncInput,
    linked_review_request: &ReviewRequest,
    update_input: forge::UpdateReviewRequestInput,
) -> Result<(), SessionError> {
    let repo_url = input
        .git_client
        .repo_url(input.folder.clone())
        .await
        .map_err(|error| {
            SessionError::Workflow(format!(
                "Failed to resolve repository remote for review-request metadata sync: {error}"
            ))
        })?;
    let remote = metadata_sync_input
        .review_request_client
        .detect_remote(repo_url)
        .map(|remote| remote.with_command_working_directory(input.folder.clone()))
        .map_err(|error| SessionError::Workflow(error.detail_message()))?;
    let summary = metadata_sync_input
        .review_request_client
        .sync_review_request_metadata(
            remote,
            linked_review_request.summary.display_id.clone(),
            update_input,
        )
        .await
        .map_err(|error| SessionError::Workflow(error.detail_message()))?;
    let review_request = ReviewRequest {
        last_refreshed_at: unix_timestamp_from_system_time(
            metadata_sync_input.clock.now_system_time(),
        ),
        summary,
    };

    input
        .db
        .reviews()
        .update_session_review_request(&input.session_id, Some(review_request))
        .await?;
    SessionTaskService::emit_session_updated(
        &input.app_event_tx,
        &input.session_update_versions,
        &input.session_id,
    );
    let _ = input.app_event_tx.send(AppEvent::RefreshSessions);

    Ok(())
}

/// Appends one metadata-sync warning to the session transcript.
async fn append_review_request_sync_warning(
    input: &PublishedBranchAutoPushInput,
    error: SessionError,
) {
    warn_review_request_metadata_sync(input, &error.to_string());
    let message = TranscriptNotice::ReviewRequestSyncWarning.format(format!(
        "Failed to update linked review-request metadata: {error}"
    ));
    SessionTaskService::append_workflow_notice(
        &input.transcript,
        &input.db,
        &input.app_event_tx,
        &input.session_update_versions,
        &input.session_id,
        &message,
    )
    .await;
}

/// Logs a best-effort review-request metadata sync warning.
fn warn_review_request_metadata_sync(input: &PublishedBranchAutoPushInput, error: &str) {
    tracing::warn!(
        session_id = %input.session_id,
        error,
        "failed to sync linked review-request metadata"
    );
}

#[cfg(test)]
mod tests {
    use ag_forge::MockReviewRequestClient;
    use ag_git::{GitError, MockGitClient};

    use super::*;

    #[tokio::test]
    async fn review_comment_resolution_reports_reply_and_resolution_failures() {
        // Arrange
        let db = linked_review_request_db().await;
        let mut git_client = MockGitClient::new();
        git_client.expect_repo_url().once().returning(|_| {
            Box::pin(async { Ok("https://github.com/agentty-xyz/agentty.git".to_string()) })
        });
        let mut review_request_client = MockReviewRequestClient::new();
        review_request_client
            .expect_detect_remote()
            .once()
            .returning(|_| Ok(github_remote()));
        review_request_client
            .expect_reply_to_thread()
            .withf(|_, _, thread_id, _| thread_id == "reply-fails")
            .once()
            .returning(|_, _, _, _| {
                Box::pin(async {
                    Err(forge::ReviewRequestError::OperationFailed {
                        forge_kind: forge::ForgeKind::GitHub,
                        message: "reply rejected".to_string(),
                    })
                })
            });
        review_request_client
            .expect_reply_to_thread()
            .withf(|_, _, thread_id, _| thread_id == "resolve-fails")
            .once()
            .returning(|_, _, _, _| Box::pin(async { Ok(()) }));
        review_request_client
            .expect_resolve_thread()
            .withf(|_, _, thread_id| thread_id == "resolve-fails")
            .once()
            .returning(|_, _, _| {
                Box::pin(async {
                    Err(forge::ReviewRequestError::OperationFailed {
                        forge_kind: forge::ForgeKind::GitHub,
                        message: "resolve rejected".to_string(),
                    })
                })
            });
        let (input, transcript) = resolution_test_input(
            db,
            git_client,
            review_request_client,
            vec![fixed_outcome("reply-fails"), fixed_outcome("resolve-fails")],
        );
        let resolution_input = input
            .review_comment_resolution
            .as_ref()
            .expect("resolution input should exist");

        // Act
        resolve_review_comments_after_push(&input, resolution_input).await;

        // Assert
        assert_eq!(
            last_transcript_message(&transcript),
            "[Review Comments Warning] Resolved 0 of 2 review thread(s). Reopen review comments \
             to retry the remaining threads."
        );
    }

    #[tokio::test]
    async fn review_comment_resolution_reports_repository_remote_failure() {
        // Arrange
        let db = linked_review_request_db().await;
        let mut git_client = MockGitClient::new();
        git_client.expect_repo_url().once().returning(|_| {
            Box::pin(async {
                Err(GitError::CommandFailed {
                    command: "git remote get-url origin".to_string(),
                    stderr: "missing remote".to_string(),
                })
            })
        });
        let (input, transcript) = resolution_test_input(
            db,
            git_client,
            MockReviewRequestClient::new(),
            vec![fixed_outcome("thread-1")],
        );
        let resolution_input = input
            .review_comment_resolution
            .as_ref()
            .expect("resolution input should exist");

        // Act
        resolve_review_comments_after_push(&input, resolution_input).await;

        // Assert
        assert_eq!(
            last_transcript_message(&transcript),
            "[Review Comments Warning] Resolved 0 of 1 review thread(s). Reopen review comments \
             to retry the remaining threads."
        );
    }

    #[tokio::test]
    async fn review_comment_resolution_reports_remote_detection_failure() {
        // Arrange
        let db = linked_review_request_db().await;
        let mut git_client = MockGitClient::new();
        git_client
            .expect_repo_url()
            .once()
            .returning(|_| Box::pin(async { Ok("ssh://example.com/owner/repo.git".to_string()) }));
        let mut review_request_client = MockReviewRequestClient::new();
        review_request_client
            .expect_detect_remote()
            .once()
            .returning(|repo_url| Err(forge::ReviewRequestError::UnsupportedRemote { repo_url }));
        let (input, transcript) = resolution_test_input(
            db,
            git_client,
            review_request_client,
            vec![fixed_outcome("thread-1")],
        );
        let resolution_input = input
            .review_comment_resolution
            .as_ref()
            .expect("resolution input should exist");

        // Act
        resolve_review_comments_after_push(&input, resolution_input).await;

        // Assert
        assert_eq!(
            last_transcript_message(&transcript),
            "[Review Comments Warning] Resolved 0 of 1 review thread(s). Reopen review comments \
             to retry the remaining threads."
        );
    }

    #[tokio::test]
    async fn review_comment_resolution_skips_sessions_without_open_linked_review() {
        // Arrange
        let db = AppRepositories::in_memory().await;
        insert_session(&db).await;
        let mut git_client = MockGitClient::new();
        git_client.expect_repo_url().never();
        let (input, transcript) = resolution_test_input(
            db,
            git_client,
            MockReviewRequestClient::new(),
            vec![fixed_outcome("thread-1")],
        );
        let resolution_input = input
            .review_comment_resolution
            .as_ref()
            .expect("resolution input should exist");

        // Act
        resolve_review_comments_after_push(&input, resolution_input).await;

        // Assert
        assert!(transcript.lock().expect("transcript lock").is_empty());
    }

    #[tokio::test]
    async fn review_comment_resolution_reports_linked_review_load_failure() {
        // Arrange
        let (db, pool) = AppRepositories::in_memory_with_pool().await;
        insert_session(&db).await;
        pool.close().await;
        let mut git_client = MockGitClient::new();
        git_client.expect_repo_url().never();
        let (input, transcript) = resolution_test_input(
            db,
            git_client,
            MockReviewRequestClient::new(),
            vec![fixed_outcome("thread-1")],
        );
        let resolution_input = input
            .review_comment_resolution
            .as_ref()
            .expect("resolution input should exist");

        // Act
        resolve_review_comments_after_push(&input, resolution_input).await;

        // Assert
        assert_eq!(
            last_transcript_message(&transcript),
            "[Review Comments Warning] Resolved 0 of 1 review thread(s). Reopen review comments \
             to retry the remaining threads."
        );
    }

    /// Builds one detached-push input for direct review-resolution tests.
    fn resolution_test_input(
        db: AppRepositories,
        git_client: MockGitClient,
        review_request_client: MockReviewRequestClient,
        outcomes: Vec<ReviewCommentOutcome>,
    ) -> (PublishedBranchAutoPushInput, Arc<Mutex<SessionTranscript>>) {
        let transcript = Arc::new(Mutex::new(SessionTranscript::default()));
        let input = PublishedBranchAutoPushInput {
            app_event_tx: mpsc::unbounded_channel().0,
            db,
            folder: PathBuf::from("/tmp/project"),
            git_client: Arc::new(git_client),
            published_upstream_ref: "origin/wt/session-id".to_string(),
            review_comment_resolution: Some(ReviewCommentResolutionInput {
                outcomes,
                review_request_client: Arc::new(review_request_client),
            }),
            review_request_metadata_sync: None,
            session_id: "session-id".into(),
            session_update_versions: Arc::default(),
            sync_operation_id: "sync-id".to_string(),
            transcript: Arc::clone(&transcript),
        };

        (input, transcript)
    }

    /// Builds one fixed outcome accepted by the post-turn allowlist.
    fn fixed_outcome(thread_id: &str) -> ReviewCommentOutcome {
        ReviewCommentOutcome {
            reply: format!("Addressed {thread_id}."),
            resolution: ag_protocol::ReviewCommentResolution::Fixed,
            thread_id: thread_id.to_string(),
        }
    }

    /// Inserts one session linked to an open GitHub pull request.
    async fn linked_review_request_db() -> AppRepositories {
        let db = AppRepositories::in_memory().await;
        insert_session(&db).await;
        db.reviews()
            .update_session_review_request(
                "session-id",
                Some(ReviewRequest {
                    last_refreshed_at: 100,
                    summary: forge::ReviewRequestSummary {
                        display_id: "#42".to_string(),
                        forge_kind: forge::ForgeKind::GitHub,
                        source_branch: "wt/session-id".to_string(),
                        state: ReviewRequestState::Open,
                        status_summary: None,
                        target_branch: "main".to_string(),
                        title: "Review title".to_string(),
                        web_url: "https://github.com/agentty-xyz/agentty/pull/42".to_string(),
                    },
                }),
            )
            .await
            .expect("failed to link review request");

        db
    }

    /// Inserts the session row required by review and transcript stores.
    async fn insert_session(db: &AppRepositories) {
        let project_id = db
            .projects()
            .upsert_project("/tmp/project", Some("main".to_string()))
            .await
            .expect("failed to insert project");
        db.sessions()
            .insert_session(
                "session-id",
                "gemini-3-flash-preview",
                "main",
                "Review",
                project_id,
            )
            .await
            .expect("failed to insert session");
    }

    /// Returns one GitHub remote used by the forge mock.
    fn github_remote() -> forge::ForgeRemote {
        forge::ForgeRemote {
            command_working_directory: None,
            forge_kind: forge::ForgeKind::GitHub,
            host: "github.com".to_string(),
            namespace: "agentty-xyz".to_string(),
            project: "agentty".to_string(),
            repo_url: "https://github.com/agentty-xyz/agentty.git".to_string(),
            web_url: "https://github.com/agentty-xyz/agentty".to_string(),
        }
    }

    /// Reads the latest live transcript message.
    fn last_transcript_message(transcript: &Arc<Mutex<SessionTranscript>>) -> String {
        transcript
            .lock()
            .expect("transcript lock")
            .messages()
            .last()
            .expect("workflow notice")
            .content
            .trim()
            .to_string()
    }
}