Skip to main content

ag_forge/
client.rs

1//! Public review-request trait boundary and production client wiring.
2
3use std::sync::Arc;
4
5use ag_telemetry::{Context, FutureExt as _, Outcome, Span, TraceContextExt};
6
7use super::{
8    CreateReviewRequestInput, ForgeCommandRunner, ForgeFuture, ForgeKind, ForgeOperation,
9    ForgeRemote, GitHubReviewRequestAdapter, GitLabReviewRequestAdapter, MergeReviewRequestInput,
10    RealForgeCommandRunner, ReviewCommentSnapshot, ReviewRequestAttention, ReviewRequestError,
11    ReviewRequestMergeOutcome, ReviewRequestMetadata, ReviewRequestSummary,
12    UpdateReviewRequestInput, detect_remote,
13};
14
15/// Async boundary used by app orchestration for forge review requests.
16///
17/// The app layer depends on this narrow contract so provider-specific request
18/// formats remain isolated inside concrete adapters.
19#[cfg_attr(any(test, feature = "test-utils"), mockall::automock)]
20pub trait ReviewRequestClient: Send + Sync {
21    /// Detects whether `repo_url` belongs to one supported forge.
22    ///
23    /// # Errors
24    /// Returns [`ReviewRequestError::UnsupportedRemote`] when the remote does
25    /// not map to a supported forge.
26    fn detect_remote(&self, repo_url: String) -> Result<ForgeRemote, ReviewRequestError>;
27
28    /// Finds an existing review request for `source_branch`.
29    ///
30    /// # Errors
31    /// Returns a provider-specific review-request error when the forge lookup
32    /// cannot be completed.
33    fn find_by_source_branch(
34        &self,
35        remote: ForgeRemote,
36        source_branch: String,
37    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>>;
38
39    /// Creates a new review request from `input`.
40    ///
41    /// # Errors
42    /// Returns a provider-specific review-request error when creation fails.
43    fn create_review_request(
44        &self,
45        remote: ForgeRemote,
46        input: CreateReviewRequestInput,
47    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
48
49    /// Refreshes one existing review request by provider display id.
50    ///
51    /// # Errors
52    /// Returns a provider-specific review-request error when refresh fails.
53    fn refresh_review_request(
54        &self,
55        remote: ForgeRemote,
56        display_id: String,
57    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
58
59    /// Loads the current title and body of one existing review request.
60    ///
61    /// # Errors
62    /// Returns a provider-specific review-request error when metadata lookup
63    /// fails.
64    fn review_request_metadata(
65        &self,
66        remote: ForgeRemote,
67        display_id: String,
68    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>>;
69
70    /// Best-effort syncs reconciled metadata after rechecking that the remote
71    /// fields match the values used during evaluation.
72    ///
73    /// The provider CLI update is not atomic with the recheck, so a later
74    /// concurrent manual edit can still be overwritten.
75    ///
76    /// # Errors
77    /// Returns a provider-specific review-request error when metadata lookup,
78    /// update, or refresh fails.
79    fn sync_review_request_metadata(
80        &self,
81        remote: ForgeRemote,
82        display_id: String,
83        input: UpdateReviewRequestInput,
84    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
85
86    /// Merges one open review request whose latest refresh reported the
87    /// readiness `input.mode` names, or adds it to its target branch's merge
88    /// queue.
89    ///
90    /// The forge state is read again first, and the merge is refused unless
91    /// it still allows `input.mode`: open, not queued, at
92    /// `input.expected_head_commit` when one is given, and ready (or ready
93    /// with bypass) by the same rules a refresh reports. A draft is marked
94    /// ready for review before it merges. GitLab merge requests are always
95    /// refused.
96    ///
97    /// # Errors
98    /// Returns a provider-specific review-request error when a forge command
99    /// fails. A draft marked ready for review before the failure stays ready
100    /// for review, and the error says so.
101    fn merge_review_request(
102        &self,
103        remote: ForgeRemote,
104        input: MergeReviewRequestInput,
105    ) -> ForgeFuture<Result<ReviewRequestMergeOutcome, ReviewRequestError>>;
106
107    /// Returns the browser-openable URL for one review request.
108    ///
109    /// # Errors
110    /// Returns [`ReviewRequestError::OperationFailed`] when the summary does
111    /// not carry a web URL.
112    fn review_request_web_url(
113        &self,
114        review_request: &ReviewRequestSummary,
115    ) -> Result<String, ReviewRequestError>;
116
117    /// Fetches the review-comment snapshot for one open review request.
118    ///
119    /// Returns both inline threads and review-request-wide comments. Threads
120    /// are grouped by `path` and sorted by `(path, line)` by callers; adapters
121    /// return what the forge reports without enforcing an ordering.
122    ///
123    /// # Errors
124    /// Returns a provider-specific review-request error when the snapshot fetch
125    /// cannot be completed (including authentication and host failures).
126    fn fetch_review_comment_snapshot(
127        &self,
128        remote: ForgeRemote,
129        display_id: String,
130    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>>;
131
132    /// Fetches the conditions on one open review request that may need
133    /// follow-up work: failed and pending checks for its head commit, merge
134    /// conflicts with its target branch, and unresolved review threads
135    /// awaiting a response from trusted authors.
136    ///
137    /// `trusted_bots` lists review-bot logins whose comments count as
138    /// trusted and whose own failed checks are left to their review threads.
139    /// GitHub matches bot accounts by login, never users with the same name;
140    /// GitLab matches note author usernames.
141    ///
142    /// # Errors
143    /// Returns a provider-specific review-request error when any forge lookup
144    /// cannot be completed, including the author-trust lookups, so callers
145    /// never act on partial facts.
146    fn fetch_review_request_attention(
147        &self,
148        remote: ForgeRemote,
149        display_id: String,
150        trusted_bots: Vec<String>,
151    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>>;
152
153    /// Reruns the failed jobs of each workflow run or pipeline named by
154    /// `rerun_ids`, taken from
155    /// [`ReviewCheckFailure::rerun_id`](crate::ReviewCheckFailure::rerun_id).
156    ///
157    /// Each distinct id is rerun once, in order, so several failed checks
158    /// from one workflow run or pipeline request one rerun.
159    ///
160    /// # Errors
161    /// Returns a provider-specific review-request error when an id is
162    /// malformed or the forge rejects a rerun. Reruns requested before the
163    /// failing one are not reverted.
164    fn rerun_failed_checks(
165        &self,
166        remote: ForgeRemote,
167        rerun_ids: Vec<String>,
168    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
169
170    /// Adds one reply to an existing review thread.
171    ///
172    /// # Errors
173    /// Returns a provider-specific review-request error when the reply cannot
174    /// be posted.
175    fn reply_to_thread(
176        &self,
177        remote: ForgeRemote,
178        display_id: String,
179        thread_id: String,
180        body: String,
181    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
182
183    /// Marks one existing review thread resolved.
184    ///
185    /// # Errors
186    /// Returns a provider-specific review-request error when the thread cannot
187    /// be resolved.
188    fn resolve_thread(
189        &self,
190        remote: ForgeRemote,
191        display_id: String,
192        thread_id: String,
193    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
194}
195
196/// Production [`ReviewRequestClient`] that routes to forge-specific adapters.
197pub struct RealReviewRequestClient {
198    command_runner: Arc<dyn ForgeCommandRunner>,
199}
200
201impl RealReviewRequestClient {
202    /// Builds one review-request client from a forge command runner.
203    pub(crate) fn new(command_runner: Arc<dyn ForgeCommandRunner>) -> Self {
204        Self { command_runner }
205    }
206
207    /// Runs `call` on an authenticated adapter selected for `remote`.
208    ///
209    /// `operation` names the public method in the execution context so its
210    /// `forge.command` spans are attributable. Beneath an active trace, the
211    /// authentication check that precedes every call records
212    /// `forge.auth_check`.
213    fn call_with_authenticated_adapter<T>(
214        &self,
215        remote: ForgeRemote,
216        operation: &'static str,
217        call: impl FnOnce(
218            Arc<dyn ReviewRequestAdapter>,
219            ForgeRemote,
220        ) -> ForgeFuture<Result<T, ReviewRequestError>>
221        + Send
222        + 'static,
223    ) -> ForgeFuture<Result<T, ReviewRequestError>>
224    where
225        T: Send + 'static,
226    {
227        let adapter = self.adapter_for(remote.forge_kind);
228
229        Box::pin(async move {
230            let context = Context::current().with_value(ForgeOperation(operation));
231
232            async move {
233                Self::check_authentication(adapter.ensure_authenticated(&remote), &remote).await?;
234
235                call(adapter, remote).await
236            }
237            .with_context(context)
238            .await
239        })
240    }
241
242    /// Awaits one adapter authentication check, inside a `forge.auth_check`
243    /// span when the current context is traced.
244    async fn check_authentication(
245        check: ForgeFuture<Result<(), ReviewRequestError>>,
246        remote: &ForgeRemote,
247    ) -> Result<(), ReviewRequestError> {
248        if !Context::current().has_active_span() {
249            return check.await;
250        }
251
252        let span = Span::child("forge.auth_check");
253        span.attribute("agentty.forge.kind", remote.forge_kind.as_str());
254
255        span.run(check, |_| Outcome::Failed).await
256    }
257
258    /// Returns one adapter implementation for `forge_kind`.
259    fn adapter_for(&self, forge_kind: ForgeKind) -> Arc<dyn ReviewRequestAdapter> {
260        match forge_kind {
261            ForgeKind::GitHub => Arc::new(GitHubReviewRequestAdapter::new(Arc::clone(
262                &self.command_runner,
263            ))),
264            ForgeKind::GitLab => Arc::new(GitLabReviewRequestAdapter::new(Arc::clone(
265                &self.command_runner,
266            ))),
267        }
268    }
269}
270
271impl Default for RealReviewRequestClient {
272    fn default() -> Self {
273        Self::new(Arc::new(RealForgeCommandRunner))
274    }
275}
276
277impl ReviewRequestClient for RealReviewRequestClient {
278    fn detect_remote(&self, repo_url: String) -> Result<ForgeRemote, ReviewRequestError> {
279        detect_remote(&repo_url)
280    }
281
282    fn find_by_source_branch(
283        &self,
284        remote: ForgeRemote,
285        source_branch: String,
286    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>> {
287        self.call_with_authenticated_adapter(
288            remote,
289            "find_by_source_branch",
290            move |adapter, remote| {
291                adapter.find_authenticated_by_source_branch(remote, source_branch)
292            },
293        )
294    }
295
296    fn create_review_request(
297        &self,
298        remote: ForgeRemote,
299        input: CreateReviewRequestInput,
300    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
301        self.call_with_authenticated_adapter(
302            remote,
303            "create_review_request",
304            move |adapter, remote| adapter.create_authenticated_review_request(remote, input),
305        )
306    }
307
308    fn refresh_review_request(
309        &self,
310        remote: ForgeRemote,
311        display_id: String,
312    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
313        self.call_with_authenticated_adapter(
314            remote,
315            "refresh_review_request",
316            move |adapter, remote| adapter.refresh_authenticated_review_request(remote, display_id),
317        )
318    }
319
320    fn review_request_metadata(
321        &self,
322        remote: ForgeRemote,
323        display_id: String,
324    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>> {
325        self.call_with_authenticated_adapter(
326            remote,
327            "review_request_metadata",
328            move |adapter, remote| {
329                adapter.authenticated_review_request_metadata(remote, display_id)
330            },
331        )
332    }
333
334    fn sync_review_request_metadata(
335        &self,
336        remote: ForgeRemote,
337        display_id: String,
338        input: UpdateReviewRequestInput,
339    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>> {
340        self.call_with_authenticated_adapter(
341            remote,
342            "sync_review_request_metadata",
343            move |adapter, remote| {
344                adapter.sync_authenticated_review_request_metadata(remote, display_id, input)
345            },
346        )
347    }
348
349    fn merge_review_request(
350        &self,
351        remote: ForgeRemote,
352        input: MergeReviewRequestInput,
353    ) -> ForgeFuture<Result<ReviewRequestMergeOutcome, ReviewRequestError>> {
354        self.call_with_authenticated_adapter(
355            remote,
356            "merge_review_request",
357            move |adapter, remote| adapter.merge_authenticated_review_request(remote, input),
358        )
359    }
360
361    fn review_request_web_url(
362        &self,
363        review_request: &ReviewRequestSummary,
364    ) -> Result<String, ReviewRequestError> {
365        if review_request.web_url.trim().is_empty() {
366            return Err(ReviewRequestError::OperationFailed {
367                forge_kind: review_request.forge_kind,
368                message: "review request summary is missing a web URL".to_string(),
369            });
370        }
371
372        Ok(review_request.web_url.clone())
373    }
374
375    fn fetch_review_comment_snapshot(
376        &self,
377        remote: ForgeRemote,
378        display_id: String,
379    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>> {
380        self.call_with_authenticated_adapter(
381            remote,
382            "fetch_review_comment_snapshot",
383            move |adapter, remote| {
384                adapter.fetch_authenticated_review_comment_snapshot(remote, display_id)
385            },
386        )
387    }
388
389    fn fetch_review_request_attention(
390        &self,
391        remote: ForgeRemote,
392        display_id: String,
393        trusted_bots: Vec<String>,
394    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>> {
395        self.call_with_authenticated_adapter(
396            remote,
397            "fetch_review_request_attention",
398            move |adapter, remote| {
399                adapter.fetch_authenticated_review_request_attention(
400                    remote,
401                    display_id,
402                    trusted_bots,
403                )
404            },
405        )
406    }
407
408    fn rerun_failed_checks(
409        &self,
410        remote: ForgeRemote,
411        rerun_ids: Vec<String>,
412    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
413        let mut distinct_rerun_ids = Vec::with_capacity(rerun_ids.len());
414        for rerun_id in rerun_ids {
415            if !distinct_rerun_ids.contains(&rerun_id) {
416                distinct_rerun_ids.push(rerun_id);
417            }
418        }
419
420        self.call_with_authenticated_adapter(
421            remote,
422            "rerun_failed_checks",
423            move |adapter, remote| {
424                adapter.rerun_authenticated_failed_checks(remote, distinct_rerun_ids)
425            },
426        )
427    }
428
429    fn reply_to_thread(
430        &self,
431        remote: ForgeRemote,
432        display_id: String,
433        thread_id: String,
434        body: String,
435    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
436        self.call_with_authenticated_adapter(remote, "reply_to_thread", move |adapter, remote| {
437            adapter.reply_to_authenticated_thread(remote, display_id, thread_id, body)
438        })
439    }
440
441    fn resolve_thread(
442        &self,
443        remote: ForgeRemote,
444        display_id: String,
445        thread_id: String,
446    ) -> ForgeFuture<Result<(), ReviewRequestError>> {
447        self.call_with_authenticated_adapter(remote, "resolve_thread", move |adapter, remote| {
448            adapter.resolve_authenticated_thread(remote, display_id, thread_id)
449        })
450    }
451}
452
453/// Provider-specific operation boundary used after client-level authentication.
454///
455/// The production client selects one implementation, calls
456/// [`ReviewRequestAdapter::ensure_authenticated`] once, and then invokes the
457/// requested operation without provider-specific dispatch in each public
458/// method.
459pub(crate) trait ReviewRequestAdapter: Send + Sync {
460    /// Verifies that CLI authentication succeeds for `remote`.
461    ///
462    /// # Errors
463    /// Returns a provider-specific review-request error when the forge CLI is
464    /// unavailable, unauthenticated, or cannot resolve the target host.
465    fn ensure_authenticated(
466        &self,
467        remote: &ForgeRemote,
468    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
469
470    /// Finds one review request after the production client has authenticated.
471    fn find_authenticated_by_source_branch(
472        &self,
473        remote: ForgeRemote,
474        source_branch: String,
475    ) -> ForgeFuture<Result<Option<ReviewRequestSummary>, ReviewRequestError>>;
476
477    /// Creates one review request after the production client has
478    /// authenticated.
479    fn create_authenticated_review_request(
480        &self,
481        remote: ForgeRemote,
482        input: CreateReviewRequestInput,
483    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
484
485    /// Refreshes one existing review request after authentication.
486    fn refresh_authenticated_review_request(
487        &self,
488        remote: ForgeRemote,
489        display_id: String,
490    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
491
492    /// Loads current review-request metadata after authentication.
493    fn authenticated_review_request_metadata(
494        &self,
495        remote: ForgeRemote,
496        display_id: String,
497    ) -> ForgeFuture<Result<ReviewRequestMetadata, ReviewRequestError>>;
498
499    /// Synchronizes review-request metadata after authentication.
500    fn sync_authenticated_review_request_metadata(
501        &self,
502        remote: ForgeRemote,
503        display_id: String,
504        input: UpdateReviewRequestInput,
505    ) -> ForgeFuture<Result<ReviewRequestSummary, ReviewRequestError>>;
506
507    /// Merges or queues one review request after authentication.
508    fn merge_authenticated_review_request(
509        &self,
510        remote: ForgeRemote,
511        input: MergeReviewRequestInput,
512    ) -> ForgeFuture<Result<ReviewRequestMergeOutcome, ReviewRequestError>>;
513
514    /// Fetches a review-comment snapshot after authentication.
515    fn fetch_authenticated_review_comment_snapshot(
516        &self,
517        remote: ForgeRemote,
518        display_id: String,
519    ) -> ForgeFuture<Result<ReviewCommentSnapshot, ReviewRequestError>>;
520
521    /// Fetches review-request attention facts after authentication, trusting
522    /// the review bots named by `trusted_bots`.
523    fn fetch_authenticated_review_request_attention(
524        &self,
525        remote: ForgeRemote,
526        display_id: String,
527        trusted_bots: Vec<String>,
528    ) -> ForgeFuture<Result<ReviewRequestAttention, ReviewRequestError>>;
529
530    /// Reruns the failed jobs of each distinct workflow run or pipeline in
531    /// `rerun_ids` after authentication.
532    fn rerun_authenticated_failed_checks(
533        &self,
534        remote: ForgeRemote,
535        rerun_ids: Vec<String>,
536    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
537
538    /// Adds one reply after authentication.
539    fn reply_to_authenticated_thread(
540        &self,
541        remote: ForgeRemote,
542        display_id: String,
543        thread_id: String,
544        body: String,
545    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
546
547    /// Resolves one review thread after authentication.
548    fn resolve_authenticated_thread(
549        &self,
550        remote: ForgeRemote,
551        display_id: String,
552        thread_id: String,
553    ) -> ForgeFuture<Result<(), ReviewRequestError>>;
554}
555
556#[cfg(test)]
557#[path = "client_test.rs"]
558mod tests;