Skip to main content

ag_forge/
model.rs

1//! Shared forge review-request types.
2
3use std::fmt;
4use std::fmt::Write as _;
5use std::future::Future;
6use std::path::PathBuf;
7use std::pin::Pin;
8use std::str::FromStr;
9
10use url::Url;
11
12/// Prefix for the per-operation identity marker Agentty appends to review
13/// thread replies.
14pub const AGENTTY_REVIEW_REPLY_MARKER_PREFIX: &str = "<!-- agentty review resolution:";
15
16/// Shared forge family enum reused by persistence and forge adapters.
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
18pub enum ForgeKind {
19    /// GitHub-hosted pull requests.
20    GitHub,
21    /// GitLab-hosted merge requests.
22    GitLab,
23}
24
25impl ForgeKind {
26    /// Returns the user-facing forge name.
27    pub fn display_name(self) -> &'static str {
28        match self {
29            Self::GitHub => "GitHub",
30            Self::GitLab => "GitLab",
31        }
32    }
33
34    /// Returns the CLI executable name used for this forge.
35    pub fn cli_name(self) -> &'static str {
36        match self {
37            Self::GitHub => "gh",
38            Self::GitLab => "glab",
39        }
40    }
41
42    /// Returns the login command users should run to authorize forge access.
43    pub fn auth_login_command(self) -> &'static str {
44        match self {
45            Self::GitHub => "gh auth login",
46            Self::GitLab => "glab auth login",
47        }
48    }
49
50    /// Returns the persisted string representation for this forge kind.
51    pub fn as_str(self) -> &'static str {
52        match self {
53            Self::GitHub => "GitHub",
54            Self::GitLab => "GitLab",
55        }
56    }
57
58    /// Returns the forge-native review-request noun shown in user-facing copy.
59    pub fn review_request_name(self) -> &'static str {
60        match self {
61            Self::GitHub => "pull request",
62            Self::GitLab => "merge request",
63        }
64    }
65
66    /// Returns the combined forge and review-request name for user-facing copy.
67    pub fn review_request_display_name(self) -> String {
68        format!("{} {}", self.display_name(), self.review_request_name())
69    }
70
71    /// Returns the short UI indicator label for one review request.
72    pub fn review_request_short_name(self) -> &'static str {
73        match self {
74            Self::GitHub => "PR",
75            Self::GitLab => "MR",
76        }
77    }
78}
79
80impl fmt::Display for ForgeKind {
81    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
82        formatter.write_str(self.as_str())
83    }
84}
85
86impl FromStr for ForgeKind {
87    type Err = String;
88
89    fn from_str(value: &str) -> Result<Self, Self::Err> {
90        match value {
91            "GitHub" => Ok(Self::GitHub),
92            "GitLab" => Ok(Self::GitLab),
93            _ => Err(format!("Unknown review-request forge: {value}")),
94        }
95    }
96}
97
98/// Returns whether `host` looks like one GitLab instance hostname.
99pub fn is_gitlab_host(host: &str) -> bool {
100    host == "gitlab.com"
101        || host.ends_with(".gitlab.com")
102        || host.starts_with("gitlab.")
103        || host.contains(".gitlab.")
104}
105
106/// Normalized remote lifecycle state for one linked review request.
107#[derive(Clone, Copy, Debug, Eq, PartialEq)]
108pub enum ReviewRequestState {
109    /// The linked review request is still open.
110    Open,
111    /// The linked review request was merged upstream.
112    Merged,
113    /// The linked review request was closed without merge.
114    Closed,
115}
116
117impl ReviewRequestState {
118    /// Returns the persisted string representation for this remote state.
119    pub fn as_str(self) -> &'static str {
120        match self {
121            Self::Open => "Open",
122            Self::Merged => "Merged",
123            Self::Closed => "Closed",
124        }
125    }
126}
127
128impl fmt::Display for ReviewRequestState {
129    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
130        formatter.write_str(self.as_str())
131    }
132}
133
134impl FromStr for ReviewRequestState {
135    type Err = String;
136
137    fn from_str(value: &str) -> Result<Self, Self::Err> {
138        match value {
139            "Open" => Ok(Self::Open),
140            "Merged" => Ok(Self::Merged),
141            "Closed" => Ok(Self::Closed),
142            _ => Err(format!("Unknown review-request state: {value}")),
143        }
144    }
145}
146
147/// Normalized remote summary for one linked review request.
148///
149/// Local session lifecycle transitions such as `Rebasing`, `Done`, and
150/// `Canceled` retain this metadata so the session can continue to reference the
151/// same remote review request. Remote terminal outcomes are stored in
152/// `state` instead of clearing the link; only an explicit unlink action or
153/// session deletion should remove this metadata.
154#[derive(Clone, Debug, Eq, PartialEq)]
155pub struct ReviewRequestSummary {
156    /// Provider display id such as GitHub `#123`.
157    pub display_id: String,
158    /// Forge family that owns the linked review request.
159    pub forge_kind: ForgeKind,
160    /// Source branch published for review.
161    pub source_branch: String,
162    /// Latest normalized remote lifecycle state.
163    pub state: ReviewRequestState,
164    /// Provider-specific condensed status text for UI display.
165    pub status_summary: Option<String>,
166    /// Target branch receiving the review request.
167    pub target_branch: String,
168    /// Remote review-request title.
169    pub title: String,
170    /// Browser-openable review-request URL.
171    pub web_url: String,
172}
173
174impl ReviewRequestSummary {
175    /// Status-summary component persisted for a GitHub PR whose checks pass
176    /// and that the viewer may merge by bypassing branch protections: either
177    /// only an approval is missing, or a conflict-free draft has no unresolved
178    /// review threads.
179    pub const GITHUB_BYPASS_READY_STATUS_COMPONENT: &str = "PR ready with bypass";
180    /// Status-summary component persisted for a GitHub PR with a clean merge
181    /// state at the latest forge refresh.
182    pub const GITHUB_READY_STATUS_COMPONENT: &str = "PR ready";
183
184    /// Returns whether the latest GitHub refresh marked this open PR ready.
185    pub fn is_github_pr_ready(&self) -> bool {
186        self.has_open_github_status_component(Self::GITHUB_READY_STATUS_COMPONENT)
187    }
188
189    /// Returns whether the latest GitHub refresh marked this open PR ready to
190    /// merge by bypassing branch protections.
191    pub fn is_github_pr_bypass_ready(&self) -> bool {
192        self.has_open_github_status_component(Self::GITHUB_BYPASS_READY_STATUS_COMPONENT)
193    }
194
195    /// Returns whether this open GitHub PR status contains `component`.
196    fn has_open_github_status_component(&self, component: &str) -> bool {
197        self.forge_kind == ForgeKind::GitHub
198            && self.state == ReviewRequestState::Open
199            && self
200                .status_summary
201                .as_deref()
202                .is_some_and(|summary| summary.split(", ").any(|part| part == component))
203    }
204}
205
206/// Boxed async result used by review-request trait methods.
207pub type ForgeFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
208
209/// Normalized repository remote metadata for one supported forge.
210#[derive(Clone, Debug, Eq, PartialEq)]
211pub struct ForgeRemote {
212    /// Repository worktree used when forge CLI commands need local git
213    /// context.
214    pub command_working_directory: Option<PathBuf>,
215    /// Forge family inferred from the repository remote.
216    pub forge_kind: ForgeKind,
217    /// Forge hostname used for browser and API calls.
218    ///
219    /// HTTPS remotes keep any explicit web/API port, while SSH transport ports
220    /// are stripped during remote normalization.
221    pub host: String,
222    /// Repository namespace or owner path.
223    pub namespace: String,
224    /// Repository name without a trailing `.git` suffix.
225    pub project: String,
226    /// Credential-free remote URL suitable for display and diagnostics.
227    pub repo_url: String,
228    /// Browser-openable repository URL derived from the remote.
229    pub web_url: String,
230}
231
232impl ForgeRemote {
233    /// Returns one remote copy that runs forge CLI commands from
234    /// `working_directory`.
235    #[must_use]
236    pub fn with_command_working_directory(mut self, working_directory: PathBuf) -> Self {
237        self.command_working_directory = Some(working_directory);
238
239        self
240    }
241
242    /// Returns the `<namespace>/<project>` path used by forge CLIs and URLs.
243    pub fn project_path(&self) -> String {
244        format!("{}/{}", self.namespace, self.project)
245    }
246
247    /// Returns the browser-openable URL that starts one new pull request or
248    /// review request for `source_branch` into `target_branch`.
249    ///
250    /// # Errors
251    /// Returns [`ReviewRequestError::OperationFailed`] when the stored
252    /// repository web URL is invalid or cannot be converted into a forge
253    /// review-request creation URL.
254    pub fn review_request_creation_url(
255        &self,
256        source_branch: &str,
257        target_branch: &str,
258    ) -> Result<String, ReviewRequestError> {
259        match self.forge_kind {
260            ForgeKind::GitHub => {
261                Self::github_review_request_creation_url(self, source_branch, target_branch)
262            }
263            ForgeKind::GitLab => {
264                Self::gitlab_review_request_creation_url(self, source_branch, target_branch)
265            }
266        }
267    }
268
269    /// Builds one GitHub compare URL that opens the new pull-request flow.
270    fn github_review_request_creation_url(
271        remote: &ForgeRemote,
272        source_branch: &str,
273        target_branch: &str,
274    ) -> Result<String, ReviewRequestError> {
275        let mut url = Self::parsed_remote_web_url(remote)?;
276        let compare_target = if target_branch.trim().is_empty() {
277            source_branch.to_string()
278        } else {
279            format!("{target_branch}...{source_branch}")
280        };
281
282        {
283            let mut path_segments = url
284                .path_segments_mut()
285                .map_err(|()| Self::invalid_web_url_error(remote))?;
286            path_segments.pop_if_empty();
287            path_segments.push("compare");
288            path_segments.push(&compare_target);
289        }
290
291        url.query_pairs_mut().append_pair("expand", "1");
292
293        Ok(url.into())
294    }
295
296    /// Builds one GitLab URL that opens the new merge-request flow.
297    fn gitlab_review_request_creation_url(
298        remote: &ForgeRemote,
299        source_branch: &str,
300        target_branch: &str,
301    ) -> Result<String, ReviewRequestError> {
302        let mut url = Self::parsed_remote_web_url(remote)?;
303
304        {
305            let mut path_segments = url
306                .path_segments_mut()
307                .map_err(|()| Self::invalid_web_url_error(remote))?;
308            path_segments.pop_if_empty();
309            path_segments.push("-");
310            path_segments.push("merge_requests");
311            path_segments.push("new");
312        }
313
314        url.query_pairs_mut()
315            .append_pair("merge_request[source_branch]", source_branch)
316            .append_pair("merge_request[target_branch]", target_branch);
317
318        Ok(url.into())
319    }
320
321    /// Parses the stored repository web URL for one forge remote.
322    fn parsed_remote_web_url(remote: &ForgeRemote) -> Result<Url, ReviewRequestError> {
323        Url::parse(&remote.web_url).map_err(|_| Self::invalid_web_url_error(remote))
324    }
325
326    /// Returns one normalized invalid-remote-url error for review-request
327    /// links.
328    fn invalid_web_url_error(remote: &ForgeRemote) -> ReviewRequestError {
329        ReviewRequestError::OperationFailed {
330            forge_kind: remote.forge_kind,
331            message: format!(
332                "repository remote is missing a valid web URL: `{}`",
333                remote.web_url
334            ),
335        }
336    }
337}
338
339/// One inline review comment emitted by a reviewer on a forge review thread.
340#[derive(Clone, Debug, Eq, PartialEq)]
341pub struct ReviewComment {
342    /// Forge author login or display name.
343    pub author: String,
344    /// Whether the forge reports that the authenticated user authored this
345    /// comment.
346    pub authored_by_current_user: bool,
347    /// Markdown body as authored on the forge.
348    pub body: String,
349}
350
351impl ReviewComment {
352    /// Returns whether this comment ends with an Agentty reply marker.
353    pub fn is_agentty_reply(&self) -> bool {
354        if !self.authored_by_current_user {
355            return false;
356        }
357        let Some((reply, marker)) = self.body.rsplit_once(AGENTTY_REVIEW_REPLY_MARKER_PREFIX)
358        else {
359            return false;
360        };
361        let Some(reply_token) = marker.strip_suffix(" -->") else {
362            return false;
363        };
364
365        reply.ends_with("\n\n") && Self::is_uuid_like(reply_token)
366    }
367
368    /// Returns whether `value` has the canonical hyphenated UUID shape used for
369    /// review-reply tokens.
370    fn is_uuid_like(value: &str) -> bool {
371        const GROUP_LENGTHS: [usize; 5] = [8, 4, 4, 4, 12];
372
373        value
374            .split('-')
375            .map(str::as_bytes)
376            .zip(GROUP_LENGTHS)
377            .all(|(group, expected_length)| {
378                group.len() == expected_length && group.iter().all(u8::is_ascii_hexdigit)
379            })
380            && value.matches('-').count() == GROUP_LENGTHS.len() - 1
381    }
382}
383
384/// Diff side used to anchor one inline review-thread comment.
385#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
386pub enum ReviewCommentAnchorSide {
387    /// A file-level thread that is not attached to a specific diff line.
388    File,
389    /// A thread anchored to the new/right side of the diff.
390    New,
391    /// A thread anchored to the old/left side of the diff.
392    Old,
393}
394
395/// One review thread anchored to a line of the review request diff.
396///
397/// Threads group chronological `comments` that share the same anchor. Agentty
398/// renders these in session review-comment views, grouped by file and sorted
399/// by `(path, line)` before display. Session-linked review workflows also use
400/// the native `id` to reply and resolve a thread after its fix is pushed.
401#[derive(Clone, Debug, Eq, PartialEq)]
402pub struct ReviewCommentThread {
403    /// Diff side used with `line` when placing this thread inline.
404    pub anchor_side: ReviewCommentAnchorSide,
405    /// Chronological reviewer comments attached to this thread.
406    pub comments: Vec<ReviewComment>,
407    /// Opaque forge-native thread identifier used for replies and resolution.
408    pub id: String,
409    /// Whether newer changes made the thread's original diff position stale,
410    /// when the forge exposes that state.
411    pub is_outdated: Option<bool>,
412    /// Whether the thread has been marked resolved on the forge.
413    pub is_resolved: bool,
414    /// Anchor line number on `anchor_side`, when the forge exposes one.
415    pub line: Option<u32>,
416    /// File path the thread is anchored to, relative to the repository root.
417    pub path: String,
418    /// Optional first line for a multi-line thread on `anchor_side`.
419    pub start_line: Option<u32>,
420}
421
422impl ReviewCommentThread {
423    /// Returns whether this thread has an unaddressed reviewer message.
424    ///
425    /// Outdated threads remain actionable because their forge-native thread
426    /// identifiers survive after their original line anchors become stale. An
427    /// unresolved thread whose latest comment is an Agentty reply becomes
428    /// actionable again when a reviewer adds a follow-up comment.
429    pub fn is_actionable(&self) -> bool {
430        !self.is_resolved && !self.is_addressed_by_agentty()
431    }
432
433    /// Returns whether Agentty authored the latest comment on this unresolved
434    /// thread.
435    pub fn is_addressed_by_agentty(&self) -> bool {
436        !self.is_resolved
437            && self
438                .comments
439                .last()
440                .is_some_and(ReviewComment::is_agentty_reply)
441    }
442}
443
444/// Full review-comments payload captured for one review request.
445///
446/// Separates forge-native `threads` (anchored to a file + line) from
447/// `pr_level_comments` (review-request-wide discussion comments that do not
448/// anchor to the diff). The UI renders the two categories side-by-side with a
449/// synthetic "General discussion" entry on top of the comments file tree.
450#[derive(Clone, Debug, Default, Eq, PartialEq)]
451pub struct ReviewCommentSnapshot {
452    /// Chronological review-request-wide comments that do not anchor to a file
453    /// or line.
454    pub pr_level_comments: Vec<ReviewComment>,
455    /// Inline threads grouped by the file and line they are anchored to.
456    pub threads: Vec<ReviewCommentThread>,
457}
458
459/// One failed check or commit status reported for a review-request head.
460#[derive(Clone, Debug, Eq, PartialEq)]
461pub struct ReviewCheckFailure {
462    /// Forge-reported check, job, or status-context name.
463    pub name: String,
464    /// Normalized failure label such as `Failure` or `Timed out`.
465    pub outcome: String,
466    /// Browser-openable details URL, when the forge reports one.
467    pub web_url: Option<String>,
468}
469
470/// Conditions on one open review request that may need follow-up work.
471///
472/// Adapters report normalized forge facts only; hosts decide whether and when
473/// to act on them.
474#[derive(Clone, Debug, Default, Eq, PartialEq)]
475pub struct ReviewRequestAttention {
476    /// Completed checks that failed for `head_commit`.
477    pub failed_checks: Vec<ReviewCheckFailure>,
478    /// Whether the forge reports conflicts with the target branch.
479    pub has_merge_conflict: bool,
480    /// Whether any check for `head_commit` is still queued or running.
481    pub has_pending_checks: bool,
482    /// Commit at the head of the source branch as seen by the forge.
483    pub head_commit: String,
484    /// Unresolved threads whose latest trusted comment awaits a response.
485    /// Trusted authors are the authenticated user and anyone the forge
486    /// reports with write-level project membership. Comments from other
487    /// authors are omitted and never decide whether a thread needs a
488    /// response.
489    pub review_threads: Vec<ReviewCommentThread>,
490}
491
492/// Input required to create a review request on one forge.
493#[derive(Clone, Debug, Eq, PartialEq)]
494pub struct CreateReviewRequestInput {
495    /// Optional body or description submitted with the review request.
496    pub body: Option<String>,
497    /// Source branch that should be reviewed.
498    pub source_branch: String,
499    /// Target branch that receives the review request.
500    pub target_branch: String,
501    /// Title shown in the forge review-request UI.
502    pub title: String,
503}
504
505/// Current remote review-request title and description.
506#[derive(Clone, Debug, Eq, PartialEq)]
507pub struct ReviewRequestMetadata {
508    /// Current body or description.
509    pub body: String,
510    /// Current title.
511    pub title: String,
512}
513
514/// One review-request field update guarded by the remote value used during
515/// semantic reconciliation.
516#[derive(Clone, Debug, Eq, PartialEq)]
517pub struct ReviewRequestMetadataFieldUpdate {
518    /// Remote value read before semantic reconciliation.
519    pub current: String,
520    /// Reconciled value to publish if the remote field is still unchanged.
521    pub desired: String,
522}
523
524/// Input required to conditionally update reconciled review-request metadata.
525#[derive(Clone, Debug, Eq, PartialEq)]
526pub struct UpdateReviewRequestInput {
527    /// Optional description update.
528    pub body: Option<ReviewRequestMetadataFieldUpdate>,
529    /// Optional title update.
530    pub title: Option<ReviewRequestMetadataFieldUpdate>,
531}
532
533/// Review-request failures normalized for actionable UI messaging.
534#[derive(Clone, Debug, Eq, PartialEq)]
535pub enum ReviewRequestError {
536    /// The required forge CLI is not available on the user's machine.
537    CliNotInstalled {
538        /// Forge family whose CLI is unavailable.
539        forge_kind: ForgeKind,
540    },
541    /// The forge CLI is installed but not authorized for the target host.
542    AuthenticationRequired {
543        /// Forge family that reported the authentication failure.
544        forge_kind: ForgeKind,
545        /// Forge host the CLI attempted to access.
546        host: String,
547        /// Original CLI error detail captured from stdout or stderr.
548        detail: Option<String>,
549    },
550    /// The forge host from the repository remote could not be resolved.
551    HostResolutionFailed {
552        /// Forge family inferred from the repository remote.
553        forge_kind: ForgeKind,
554        /// Hostname that could not be resolved.
555        host: String,
556    },
557    /// The repository remote does not map to a supported forge.
558    UnsupportedRemote {
559        /// Repository remote URL that could not be classified.
560        repo_url: String,
561    },
562    /// A forge CLI command ran but failed.
563    OperationFailed {
564        /// Forge family whose command failed.
565        forge_kind: ForgeKind,
566        /// Original CLI failure detail.
567        message: String,
568    },
569}
570
571impl ReviewRequestError {
572    /// Returns actionable user-facing copy for the failure.
573    pub fn detail_message(&self) -> String {
574        match self {
575            Self::CliNotInstalled { forge_kind } => format!(
576                "{} review requests require the `{}` CLI.\nInstall `{}` and run `{}`, then retry.",
577                forge_kind.display_name(),
578                forge_kind.cli_name(),
579                forge_kind.cli_name(),
580                forge_kind.auth_login_command(),
581            ),
582            Self::AuthenticationRequired {
583                forge_kind,
584                host,
585                detail,
586            } => Self::authentication_required_message(*forge_kind, host, detail.as_deref()),
587            Self::HostResolutionFailed { forge_kind, host } => format!(
588                "{} review requests could not reach `{host}`.\nCheck the repository remote host \
589                 and your network or DNS setup, then retry.",
590                forge_kind.display_name(),
591            ),
592            Self::UnsupportedRemote { repo_url } => format!(
593                "Review requests are only supported for GitHub and GitLab remotes.\nThis \
594                 repository remote is not supported: `{repo_url}`."
595            ),
596            Self::OperationFailed {
597                forge_kind,
598                message,
599            } => format!(
600                "{} review-request operation failed: {message}",
601                forge_kind.display_name()
602            ),
603        }
604    }
605
606    /// Returns actionable copy for one CLI authentication failure and preserves
607    /// the original CLI output when it is available.
608    fn authentication_required_message(
609        forge_kind: ForgeKind,
610        host: &str,
611        detail: Option<&str>,
612    ) -> String {
613        let mut message = format!(
614            "{} review requests require local CLI authentication for `{host}`.\nRun `{}` and \
615             retry.",
616            forge_kind.display_name(),
617            forge_kind.auth_login_command(),
618        );
619
620        // The trimmed detail never ends with a newline, so the fence always
621        // starts on its own line.
622        if let Some(detail) = Self::non_empty_detail(detail) {
623            // Infallible: writing to a String cannot fail.
624            let _ = write!(
625                message,
626                "\n\nOriginal `{}` error:\n```text\n{detail}\n```",
627                forge_kind.cli_name(),
628            );
629        }
630
631        message
632    }
633
634    /// Returns one trimmed CLI error detail when the captured output is not
635    /// empty.
636    fn non_empty_detail(detail: Option<&str>) -> Option<&str> {
637        detail.and_then(|detail| {
638            let trimmed_detail = detail.trim();
639
640            (!trimmed_detail.is_empty()).then_some(trimmed_detail)
641        })
642    }
643}
644
645#[cfg(test)]
646#[path = "model_test.rs"]
647mod tests;