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