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