1use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Serialize};
7
8#[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 #[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 #[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 #[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#[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 #[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 #[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 #[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 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 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
196#[serde(deny_unknown_fields)]
197pub struct FocusedReviewEvidence {
198 pub correction: String,
200 pub end_line: u32,
202 pub existing_code: String,
204 pub impact: String,
206 pub path: String,
208 pub side: FocusedReviewSide,
210 pub start_line: u32,
212 pub trigger: String,
214}
215
216#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
218#[serde(rename_all = "lowercase")]
219pub enum FocusedReviewSide {
220 Old,
222 New,
224}
225
226#[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 High,
236 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
249fn 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;