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 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.forge_kind == ForgeKind::GitHub
182            && self.state == ReviewRequestState::Open
183            && self.status_summary.as_deref().is_some_and(|summary| {
184                summary
185                    .split(", ")
186                    .any(|part| part == Self::GITHUB_READY_STATUS_COMPONENT)
187            })
188    }
189}
190
191/// Boxed async result used by review-request trait methods.
192pub type ForgeFuture<T> = Pin<Box<dyn Future<Output = T> + Send>>;
193
194/// Normalized repository remote metadata for one supported forge.
195#[derive(Clone, Debug, Eq, PartialEq)]
196pub struct ForgeRemote {
197    /// Repository worktree used when forge CLI commands need local git
198    /// context.
199    pub command_working_directory: Option<PathBuf>,
200    /// Forge family inferred from the repository remote.
201    pub forge_kind: ForgeKind,
202    /// Forge hostname used for browser and API calls.
203    ///
204    /// HTTPS remotes keep any explicit web/API port, while SSH transport ports
205    /// are stripped during remote normalization.
206    pub host: String,
207    /// Repository namespace or owner path.
208    pub namespace: String,
209    /// Repository name without a trailing `.git` suffix.
210    pub project: String,
211    /// Credential-free remote URL suitable for display and diagnostics.
212    pub repo_url: String,
213    /// Browser-openable repository URL derived from the remote.
214    pub web_url: String,
215}
216
217impl ForgeRemote {
218    /// Returns one remote copy that runs forge CLI commands from
219    /// `working_directory`.
220    #[must_use]
221    pub fn with_command_working_directory(mut self, working_directory: PathBuf) -> Self {
222        self.command_working_directory = Some(working_directory);
223
224        self
225    }
226
227    /// Returns the `<namespace>/<project>` path used by forge CLIs and URLs.
228    pub fn project_path(&self) -> String {
229        format!("{}/{}", self.namespace, self.project)
230    }
231
232    /// Returns the browser-openable URL that starts one new pull request or
233    /// review request for `source_branch` into `target_branch`.
234    ///
235    /// # Errors
236    /// Returns [`ReviewRequestError::OperationFailed`] when the stored
237    /// repository web URL is invalid or cannot be converted into a forge
238    /// review-request creation URL.
239    pub fn review_request_creation_url(
240        &self,
241        source_branch: &str,
242        target_branch: &str,
243    ) -> Result<String, ReviewRequestError> {
244        match self.forge_kind {
245            ForgeKind::GitHub => {
246                Self::github_review_request_creation_url(self, source_branch, target_branch)
247            }
248            ForgeKind::GitLab => {
249                Self::gitlab_review_request_creation_url(self, source_branch, target_branch)
250            }
251        }
252    }
253
254    /// Builds one GitHub compare URL that opens the new pull-request flow.
255    fn github_review_request_creation_url(
256        remote: &ForgeRemote,
257        source_branch: &str,
258        target_branch: &str,
259    ) -> Result<String, ReviewRequestError> {
260        let mut url = Self::parsed_remote_web_url(remote)?;
261        let compare_target = if target_branch.trim().is_empty() {
262            source_branch.to_string()
263        } else {
264            format!("{target_branch}...{source_branch}")
265        };
266
267        {
268            let mut path_segments = url
269                .path_segments_mut()
270                .map_err(|()| Self::invalid_web_url_error(remote))?;
271            path_segments.pop_if_empty();
272            path_segments.push("compare");
273            path_segments.push(&compare_target);
274        }
275
276        url.query_pairs_mut().append_pair("expand", "1");
277
278        Ok(url.into())
279    }
280
281    /// Builds one GitLab URL that opens the new merge-request flow.
282    fn gitlab_review_request_creation_url(
283        remote: &ForgeRemote,
284        source_branch: &str,
285        target_branch: &str,
286    ) -> Result<String, ReviewRequestError> {
287        let mut url = Self::parsed_remote_web_url(remote)?;
288
289        {
290            let mut path_segments = url
291                .path_segments_mut()
292                .map_err(|()| Self::invalid_web_url_error(remote))?;
293            path_segments.pop_if_empty();
294            path_segments.push("-");
295            path_segments.push("merge_requests");
296            path_segments.push("new");
297        }
298
299        url.query_pairs_mut()
300            .append_pair("merge_request[source_branch]", source_branch)
301            .append_pair("merge_request[target_branch]", target_branch);
302
303        Ok(url.into())
304    }
305
306    /// Parses the stored repository web URL for one forge remote.
307    fn parsed_remote_web_url(remote: &ForgeRemote) -> Result<Url, ReviewRequestError> {
308        Url::parse(&remote.web_url).map_err(|_| Self::invalid_web_url_error(remote))
309    }
310
311    /// Returns one normalized invalid-remote-url error for review-request
312    /// links.
313    fn invalid_web_url_error(remote: &ForgeRemote) -> ReviewRequestError {
314        ReviewRequestError::OperationFailed {
315            forge_kind: remote.forge_kind,
316            message: format!(
317                "repository remote is missing a valid web URL: `{}`",
318                remote.web_url
319            ),
320        }
321    }
322}
323
324/// One inline review comment emitted by a reviewer on a forge review thread.
325#[derive(Clone, Debug, Eq, PartialEq)]
326pub struct ReviewComment {
327    /// Forge author login or display name.
328    pub author: String,
329    /// Whether the forge reports that the authenticated user authored this
330    /// comment.
331    pub authored_by_current_user: bool,
332    /// Markdown body as authored on the forge.
333    pub body: String,
334}
335
336impl ReviewComment {
337    /// Returns whether this comment ends with an Agentty reply marker.
338    pub fn is_agentty_reply(&self) -> bool {
339        if !self.authored_by_current_user {
340            return false;
341        }
342        let Some((reply, marker)) = self.body.rsplit_once(AGENTTY_REVIEW_REPLY_MARKER_PREFIX)
343        else {
344            return false;
345        };
346        let Some(reply_token) = marker.strip_suffix(" -->") else {
347            return false;
348        };
349
350        reply.ends_with("\n\n") && Self::is_uuid_like(reply_token)
351    }
352
353    /// Returns whether `value` has the canonical hyphenated UUID shape used for
354    /// review-reply tokens.
355    fn is_uuid_like(value: &str) -> bool {
356        const GROUP_LENGTHS: [usize; 5] = [8, 4, 4, 4, 12];
357
358        value
359            .split('-')
360            .map(str::as_bytes)
361            .zip(GROUP_LENGTHS)
362            .all(|(group, expected_length)| {
363                group.len() == expected_length && group.iter().all(u8::is_ascii_hexdigit)
364            })
365            && value.matches('-').count() == GROUP_LENGTHS.len() - 1
366    }
367}
368
369/// Diff side used to anchor one inline review-thread comment.
370#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
371pub enum ReviewCommentAnchorSide {
372    /// A file-level thread that is not attached to a specific diff line.
373    File,
374    /// A thread anchored to the new/right side of the diff.
375    New,
376    /// A thread anchored to the old/left side of the diff.
377    Old,
378}
379
380/// One review thread anchored to a line of the review request diff.
381///
382/// Threads group chronological `comments` that share the same anchor. Agentty
383/// renders these in session review-comment views, grouped by file and sorted
384/// by `(path, line)` before display. Session-linked review workflows also use
385/// the native `id` to reply and resolve a thread after its fix is pushed.
386#[derive(Clone, Debug, Eq, PartialEq)]
387pub struct ReviewCommentThread {
388    /// Diff side used with `line` when placing this thread inline.
389    pub anchor_side: ReviewCommentAnchorSide,
390    /// Chronological reviewer comments attached to this thread.
391    pub comments: Vec<ReviewComment>,
392    /// Opaque forge-native thread identifier used for replies and resolution.
393    pub id: String,
394    /// Whether newer changes made the thread's original diff position stale,
395    /// when the forge exposes that state.
396    pub is_outdated: Option<bool>,
397    /// Whether the thread has been marked resolved on the forge.
398    pub is_resolved: bool,
399    /// Anchor line number on `anchor_side`, when the forge exposes one.
400    pub line: Option<u32>,
401    /// File path the thread is anchored to, relative to the repository root.
402    pub path: String,
403    /// Optional first line for a multi-line thread on `anchor_side`.
404    pub start_line: Option<u32>,
405}
406
407impl ReviewCommentThread {
408    /// Returns whether this thread has an unaddressed reviewer message.
409    ///
410    /// Outdated threads remain actionable because their forge-native thread
411    /// identifiers survive after their original line anchors become stale. An
412    /// unresolved thread whose latest comment is an Agentty reply becomes
413    /// actionable again when a reviewer adds a follow-up comment.
414    pub fn is_actionable(&self) -> bool {
415        !self.is_resolved && !self.is_addressed_by_agentty()
416    }
417
418    /// Returns whether Agentty authored the latest comment on this unresolved
419    /// thread.
420    pub fn is_addressed_by_agentty(&self) -> bool {
421        !self.is_resolved
422            && self
423                .comments
424                .last()
425                .is_some_and(ReviewComment::is_agentty_reply)
426    }
427}
428
429/// Full review-comments payload captured for one review request.
430///
431/// Separates forge-native `threads` (anchored to a file + line) from
432/// `pr_level_comments` (review-request-wide discussion comments that do not
433/// anchor to the diff). The UI renders the two categories side-by-side with a
434/// synthetic "General discussion" entry on top of the comments file tree.
435#[derive(Clone, Debug, Default, Eq, PartialEq)]
436pub struct ReviewCommentSnapshot {
437    /// Chronological review-request-wide comments that do not anchor to a file
438    /// or line.
439    pub pr_level_comments: Vec<ReviewComment>,
440    /// Inline threads grouped by the file and line they are anchored to.
441    pub threads: Vec<ReviewCommentThread>,
442}
443
444/// Input required to create a review request on one forge.
445#[derive(Clone, Debug, Eq, PartialEq)]
446pub struct CreateReviewRequestInput {
447    /// Optional body or description submitted with the review request.
448    pub body: Option<String>,
449    /// Source branch that should be reviewed.
450    pub source_branch: String,
451    /// Target branch that receives the review request.
452    pub target_branch: String,
453    /// Title shown in the forge review-request UI.
454    pub title: String,
455}
456
457/// Current remote review-request title and description.
458#[derive(Clone, Debug, Eq, PartialEq)]
459pub struct ReviewRequestMetadata {
460    /// Current body or description.
461    pub body: String,
462    /// Current title.
463    pub title: String,
464}
465
466/// One review-request field update guarded by the remote value used during
467/// semantic reconciliation.
468#[derive(Clone, Debug, Eq, PartialEq)]
469pub struct ReviewRequestMetadataFieldUpdate {
470    /// Remote value read before semantic reconciliation.
471    pub current: String,
472    /// Reconciled value to publish if the remote field is still unchanged.
473    pub desired: String,
474}
475
476/// Input required to conditionally update reconciled review-request metadata.
477#[derive(Clone, Debug, Eq, PartialEq)]
478pub struct UpdateReviewRequestInput {
479    /// Optional description update.
480    pub body: Option<ReviewRequestMetadataFieldUpdate>,
481    /// Optional title update.
482    pub title: Option<ReviewRequestMetadataFieldUpdate>,
483}
484
485/// Review-request failures normalized for actionable UI messaging.
486#[derive(Clone, Debug, Eq, PartialEq)]
487pub enum ReviewRequestError {
488    /// The required forge CLI is not available on the user's machine.
489    CliNotInstalled {
490        /// Forge family whose CLI is unavailable.
491        forge_kind: ForgeKind,
492    },
493    /// The forge CLI is installed but not authorized for the target host.
494    AuthenticationRequired {
495        /// Forge family that reported the authentication failure.
496        forge_kind: ForgeKind,
497        /// Forge host the CLI attempted to access.
498        host: String,
499        /// Original CLI error detail captured from stdout or stderr.
500        detail: Option<String>,
501    },
502    /// The forge host from the repository remote could not be resolved.
503    HostResolutionFailed {
504        /// Forge family inferred from the repository remote.
505        forge_kind: ForgeKind,
506        /// Hostname that could not be resolved.
507        host: String,
508    },
509    /// The repository remote does not map to a supported forge.
510    UnsupportedRemote {
511        /// Repository remote URL that could not be classified.
512        repo_url: String,
513    },
514    /// A forge CLI command ran but failed.
515    OperationFailed {
516        /// Forge family whose command failed.
517        forge_kind: ForgeKind,
518        /// Original CLI failure detail.
519        message: String,
520    },
521}
522
523impl ReviewRequestError {
524    /// Returns actionable user-facing copy for the failure.
525    pub fn detail_message(&self) -> String {
526        match self {
527            Self::CliNotInstalled { forge_kind } => format!(
528                "{} review requests require the `{}` CLI.\nInstall `{}` and run `{}`, then retry.",
529                forge_kind.display_name(),
530                forge_kind.cli_name(),
531                forge_kind.cli_name(),
532                forge_kind.auth_login_command(),
533            ),
534            Self::AuthenticationRequired {
535                forge_kind,
536                host,
537                detail,
538            } => Self::authentication_required_message(*forge_kind, host, detail.as_deref()),
539            Self::HostResolutionFailed { forge_kind, host } => format!(
540                "{} review requests could not reach `{host}`.\nCheck the repository remote host \
541                 and your network or DNS setup, then retry.",
542                forge_kind.display_name(),
543            ),
544            Self::UnsupportedRemote { repo_url } => format!(
545                "Review requests are only supported for GitHub and GitLab remotes.\nThis \
546                 repository remote is not supported: `{repo_url}`."
547            ),
548            Self::OperationFailed {
549                forge_kind,
550                message,
551            } => format!(
552                "{} review-request operation failed: {message}",
553                forge_kind.display_name()
554            ),
555        }
556    }
557
558    /// Returns actionable copy for one CLI authentication failure and preserves
559    /// the original CLI output when it is available.
560    fn authentication_required_message(
561        forge_kind: ForgeKind,
562        host: &str,
563        detail: Option<&str>,
564    ) -> String {
565        let mut message = format!(
566            "{} review requests require local CLI authentication for `{host}`.\nRun `{}` and \
567             retry.",
568            forge_kind.display_name(),
569            forge_kind.auth_login_command(),
570        );
571
572        if let Some(detail) = Self::non_empty_detail(detail) {
573            // Infallible: writing to a String cannot fail.
574            let _ = write!(
575                message,
576                "\n\nOriginal `{}` error:\n```text\n{detail}",
577                forge_kind.cli_name(),
578            );
579            if !detail.ends_with('\n') {
580                message.push('\n');
581            }
582            message.push_str("```");
583        }
584
585        message
586    }
587
588    /// Returns one trimmed CLI error detail when the captured output is not
589    /// empty.
590    fn non_empty_detail(detail: Option<&str>) -> Option<&str> {
591        detail.and_then(|detail| {
592            let trimmed_detail = detail.trim();
593
594            (!trimmed_detail.is_empty()).then_some(trimmed_detail)
595        })
596    }
597}
598
599#[cfg(test)]
600#[path = "model_test.rs"]
601mod tests;