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(FocusedReviewSuggestion::to_markdown)
46                .collect::<Vec<_>>()
47                .join("\n")
48        };
49
50        format!(
51            "## Review\n\n### Project Impact\n\n{project_impact}\n\n### \
52             Suggestions\n\n{suggestions}"
53        )
54    }
55}
56
57/// One actionable focused-review finding.
58#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
59#[serde(deny_unknown_fields)]
60#[schemars(
61    title = "FocusedReviewSuggestion",
62    description = "One actionable high- or medium-severity finding scoped to the reviewed diff."
63)]
64pub struct FocusedReviewSuggestion {
65    /// Concise explanation of the issue and its practical impact.
66    #[schemars(
67        title = "details",
68        description = "Concise issue details, including relevant repository-root-relative file \
69                       and line references when available, plus the practical impact."
70    )]
71    pub details: String,
72    /// Source evidence and rationale, when a finding can be anchored.
73    #[schemars(
74        description = "Source evidence for this finding. Quote exact code from the reviewed diff, \
75                       identify the old or new side, and explain its trigger, impact, and \
76                       correction. Use null only when no reliable source anchor is available."
77    )]
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub evidence: Option<FocusedReviewEvidence>,
80    /// Severity assigned from the focused-review severity policy.
81    #[schemars(
82        title = "severity",
83        description = "Finding severity: high for correctness, security, data-loss, or \
84                       build-breaking risks; medium for concrete reliability, maintainability, \
85                       performance, or workflow risks."
86    )]
87    pub severity: FocusedReviewSeverity,
88}
89
90impl FocusedReviewSuggestion {
91    /// Applies a host-verified range and reconciles duplicate primary prose
92    /// citations. Supporting references to other lines retain their locations.
93    /// Pass zeroes when the evidence cannot be anchored.
94    pub fn resolve_evidence_range(&mut self, start_line: u32, end_line: u32) {
95        let Some(evidence) = &mut self.evidence else {
96            return;
97        };
98        let claimed_line = evidence.start_line;
99        evidence.start_line = start_line;
100        evidence.end_line = end_line;
101        self.details = self.details_with_location(claimed_line);
102    }
103
104    /// Labels missing source anchors and distinguishes unverified supporting
105    /// references from the primary evidence location.
106    fn to_markdown(&self) -> String {
107        let Some(evidence) = &self.evidence else {
108            return format!(
109                "- [{}] (unanchored): {}",
110                self.severity,
111                self.details.trim()
112            );
113        };
114        let location = if evidence.start_line == 0 {
115            format!("`{}` (unanchored)", evidence.path)
116        } else {
117            format!("`{}:{}`", evidence.path, evidence.start_line)
118        };
119        let side = match evidence.side {
120            FocusedReviewSide::New => "",
121            FocusedReviewSide::Old => " (before change)",
122        };
123
124        format!(
125            "- [{}]: {location}{side}: {} Trigger: {} Impact: {} Correction: {} Supporting \
126             references are unverified.",
127            self.severity,
128            self.details.trim(),
129            evidence.trigger.trim(),
130            evidence.impact.trim(),
131            evidence.correction.trim(),
132        )
133    }
134
135    /// Reconciles citations matching the original primary path and line.
136    fn details_with_location(&self, claimed_line: u32) -> String {
137        let details = self.details.trim();
138        let Some(evidence) = &self.evidence else {
139            return details.to_string();
140        };
141        if evidence.path.is_empty() || claimed_line == 0 {
142            return details.to_string();
143        }
144        let prefix = format!("{}:", evidence.path);
145        let mut rendered = String::new();
146        let mut copied = 0;
147        for (start, _) in details.match_indices(&prefix) {
148            if start < copied
149                || details[..start]
150                    .chars()
151                    .next_back()
152                    .is_some_and(|character| {
153                        character.is_alphanumeric()
154                            || matches!(character, '/' | '\\' | '_' | '-' | '.')
155                    })
156            {
157                continue;
158            }
159            let suffix = &details[start + prefix.len()..];
160            let mut length = suffix.bytes().take_while(u8::is_ascii_digit).count();
161            if suffix[..length].parse::<u32>().ok() != Some(claimed_line) {
162                continue;
163            }
164            // Discard unverified columns and ranges along with stale line
165            // numbers.
166            while suffix
167                .as_bytes()
168                .get(length)
169                .is_some_and(|separator| matches!(separator, b':' | b'-'))
170            {
171                let digits = suffix[length + 1..]
172                    .bytes()
173                    .take_while(u8::is_ascii_digit)
174                    .count();
175                if digits == 0 {
176                    break;
177                }
178                length += 1 + digits;
179            }
180            rendered.push_str(&details[copied..start]);
181            rendered.push_str(&evidence.path);
182            if evidence.start_line > 0 {
183                rendered.push(':');
184                rendered.push_str(&evidence.start_line.to_string());
185            }
186            copied = start + prefix.len() + length;
187        }
188        rendered.push_str(&details[copied..]);
189
190        rendered
191    }
192}
193
194/// Source citation and actionable rationale for one focused-review finding.
195#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196#[serde(deny_unknown_fields)]
197pub struct FocusedReviewEvidence {
198    /// Concrete correction that addresses the reported risk.
199    pub correction: String,
200    /// Inclusive source line, resolved by the host; zero means unanchored.
201    pub end_line: u32,
202    /// Exact source snippet without unified-diff markers.
203    pub existing_code: String,
204    /// Practical consequence when the trigger occurs.
205    pub impact: String,
206    /// Repository-root-relative POSIX path on the selected side of the diff.
207    pub path: String,
208    /// Version of the source used by the citation.
209    pub side: FocusedReviewSide,
210    /// First source line, resolved by the host; zero means unanchored.
211    pub start_line: u32,
212    /// Concrete input, state, or sequence that exposes the risk.
213    pub trigger: String,
214}
215
216/// Version of a changed file cited by a focused-review finding.
217#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
218#[serde(rename_all = "lowercase")]
219pub enum FocusedReviewSide {
220    /// Source before the change, including deleted code.
221    Old,
222    /// Source after the change, including added code.
223    New,
224}
225
226/// Supported severity levels for actionable focused-review findings.
227#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
228#[serde(rename_all = "lowercase")]
229#[schemars(
230    title = "FocusedReviewSeverity",
231    description = "Supported severity for an actionable focused-review finding."
232)]
233pub enum FocusedReviewSeverity {
234    /// Correctness, security, data-loss, or build-breaking risk.
235    High,
236    /// Concrete reliability, maintainability, performance, or workflow risk.
237    Medium,
238}
239
240impl fmt::Display for FocusedReviewSeverity {
241    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
242        formatter.write_str(match self {
243            Self::High => "High",
244            Self::Medium => "Medium",
245        })
246    }
247}
248
249/// Formats one project-impact list, using the stable empty sentinel when no
250/// impact was reported.
251fn markdown_bullets(items: &[String]) -> String {
252    if items.is_empty() {
253        return "- None".to_string();
254    }
255
256    items
257        .iter()
258        .map(|item| format!("- {}", item.trim()))
259        .collect::<Vec<_>>()
260        .join("\n")
261}
262
263#[cfg(test)]
264#[path = "review_test.rs"]
265mod tests;