Skip to main content

ag_protocol/
review.rs

1//! Structured focused-review response contract and display formatting.
2
3use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8/// Structured result returned by a focused-review utility prompt.
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
10#[serde(deny_unknown_fields)]
11#[schemars(
12    title = "FocusedReview",
13    description = "Structured focused-review result. Project impact describes the overall effect \
14                   of the diff, while suggestions contains only actionable high- or \
15                   medium-severity findings."
16)]
17pub struct FocusedReview {
18    /// Concise statements describing the overall effect of the reviewed diff.
19    #[schemars(
20        title = "project_impact",
21        description = "Concise statements about the diff's effects on behavior, reliability, \
22                       maintainability, performance, security, or developer workflow. Use an \
23                       empty array when there is no notable impact."
24    )]
25    pub project_impact: Vec<String>,
26    /// Actionable high- or medium-severity findings from the reviewed diff.
27    #[schemars(
28        title = "suggestions",
29        description = "Actionable findings scoped to the reviewed diff, ordered by severity with \
30                       high severity first. Use an empty array when there are no suggestions."
31    )]
32    pub suggestions: Vec<FocusedReviewSuggestion>,
33}
34
35impl FocusedReview {
36    /// Formats the structured review for the terminal session transcript.
37    #[must_use]
38    pub fn to_markdown(&self) -> String {
39        let project_impact = markdown_bullets(&self.project_impact);
40        let suggestions = if self.suggestions.is_empty() {
41            "- None".to_string()
42        } else {
43            self.suggestions
44                .iter()
45                .map(|suggestion| {
46                    format!("- [{}]: {}", suggestion.severity, suggestion.details.trim())
47                })
48                .collect::<Vec<_>>()
49                .join("\n")
50        };
51
52        format!(
53            "## Review\n\n### Project Impact\n\n{project_impact}\n\n### \
54             Suggestions\n\n{suggestions}"
55        )
56    }
57}
58
59/// One actionable focused-review finding.
60#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
61#[serde(deny_unknown_fields)]
62#[schemars(
63    title = "FocusedReviewSuggestion",
64    description = "One actionable high- or medium-severity finding scoped to the reviewed diff."
65)]
66pub struct FocusedReviewSuggestion {
67    /// Concise explanation of the issue and its practical impact.
68    #[schemars(
69        title = "details",
70        description = "Concise issue details, including relevant repository-root-relative file \
71                       and line references when available, plus the practical impact."
72    )]
73    pub details: String,
74    /// Severity assigned from the focused-review severity policy.
75    #[schemars(
76        title = "severity",
77        description = "Finding severity: high for correctness, security, data-loss, or \
78                       build-breaking risks; medium for concrete reliability, maintainability, \
79                       performance, or workflow risks."
80    )]
81    pub severity: FocusedReviewSeverity,
82}
83
84/// Supported severity levels for actionable focused-review findings.
85#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
86#[serde(rename_all = "lowercase")]
87#[schemars(
88    title = "FocusedReviewSeverity",
89    description = "Supported severity for an actionable focused-review finding."
90)]
91pub enum FocusedReviewSeverity {
92    /// Correctness, security, data-loss, or build-breaking risk.
93    High,
94    /// Concrete reliability, maintainability, performance, or workflow risk.
95    Medium,
96}
97
98impl fmt::Display for FocusedReviewSeverity {
99    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
100        formatter.write_str(match self {
101            Self::High => "High",
102            Self::Medium => "Medium",
103        })
104    }
105}
106
107/// Formats one project-impact list, using the stable empty sentinel when no
108/// impact was reported.
109fn markdown_bullets(items: &[String]) -> String {
110    if items.is_empty() {
111        return "- None".to_string();
112    }
113
114    items
115        .iter()
116        .map(|item| format!("- {}", item.trim()))
117        .collect::<Vec<_>>()
118        .join("\n")
119}
120
121#[cfg(test)]
122mod tests {
123    use super::*;
124
125    #[test]
126    fn focused_review_formats_structured_fields_as_markdown() {
127        // Arrange
128        let review = FocusedReview {
129            project_impact: vec!["Improves review reliability.".to_string()],
130            suggestions: vec![
131                FocusedReviewSuggestion {
132                    details: "Fix the stale cache check.".to_string(),
133                    severity: FocusedReviewSeverity::High,
134                },
135                FocusedReviewSuggestion {
136                    details: "Deduplicate the parsing path.".to_string(),
137                    severity: FocusedReviewSeverity::Medium,
138                },
139            ],
140        };
141
142        // Act
143        let markdown = review.to_markdown();
144
145        // Assert
146        assert_eq!(
147            markdown,
148            "## Review\n\n### Project Impact\n\n- Improves review reliability.\n\n### \
149             Suggestions\n\n- [High]: Fix the stale cache check.\n- [Medium]: Deduplicate the \
150             parsing path."
151        );
152    }
153
154    #[test]
155    fn focused_review_formats_empty_arrays_with_none_sentinels() {
156        // Arrange
157        let review = FocusedReview {
158            project_impact: Vec::new(),
159            suggestions: Vec::new(),
160        };
161
162        // Act
163        let markdown = review.to_markdown();
164
165        // Assert
166        assert_eq!(
167            markdown,
168            "## Review\n\n### Project Impact\n\n- None\n\n### Suggestions\n\n- None"
169        );
170    }
171
172    #[test]
173    fn focused_review_severity_serializes_as_lowercase() {
174        // Arrange
175        let severity = FocusedReviewSeverity::High;
176
177        // Act
178        let serialized = serde_json::to_string(&severity).expect("severity should serialize");
179        let deserialized = serde_json::from_str::<FocusedReviewSeverity>(&serialized)
180            .expect("severity should deserialize");
181
182        // Assert
183        assert_eq!(serialized, "\"high\"");
184        assert_eq!(deserialized, severity);
185    }
186}