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