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