1use std::fmt;
4
5use schemars::JsonSchema;
6use serde::{Deserialize, Deserializer, 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 #[serde(default, skip_serializing_if = "Vec::is_empty")]
20 #[schemars(
21 description = "Consolidation only: account for every input suggestion by its zero-based \
22 candidate_index, linking to a retained output suggestion or explaining its \
23 rejection. Every output suggestion must be referenced by at least one \
24 decision. Use an empty array for discovery."
25 )]
26 pub candidate_decisions: Vec<FocusedReviewDecision>,
27 #[schemars(
29 title = "project_impact",
30 description = "Concise statements about the diff's effects on behavior, reliability, \
31 maintainability, performance, security, or developer workflow. Use an \
32 empty array when there is no notable impact."
33 )]
34 pub project_impact: Vec<String>,
35 #[schemars(
37 title = "suggestions",
38 description = "Actionable findings scoped to the reviewed diff, ordered by severity with \
39 high severity first. Use an empty array when there are no suggestions."
40 )]
41 pub suggestions: Vec<FocusedReviewSuggestion>,
42}
43
44impl FocusedReview {
45 pub fn validate_candidate_decisions(&self, candidate_count: usize) -> Result<(), String> {
53 let mut accounted = vec![false; candidate_count];
54 let mut retained = vec![false; self.suggestions.len()];
55 for decision in &self.candidate_decisions {
56 let Some(seen) = accounted.get_mut(decision.candidate_index) else {
57 return Err("Candidate decision references an unknown input finding".into());
58 };
59 if *seen || decision.reason.trim().is_empty() {
60 return Err(
61 "Candidate decisions must be unique and explain their reasoning".into(),
62 );
63 }
64 if let Some(index) = decision.suggestion_index {
65 let Some(output) = retained.get_mut(index) else {
66 return Err("Candidate decision references an unknown output finding".into());
67 };
68 *output = true;
69 }
70 *seen = true;
71 }
72 if accounted.contains(&false) {
73 return Err(format!(
74 "Consolidation must account for all {candidate_count} candidates"
75 ));
76 }
77 if retained.contains(&false) {
78 return Err(
79 "Consolidation must link every output finding to an input candidate".into(),
80 );
81 }
82
83 Ok(())
84 }
85
86 #[must_use]
88 pub fn to_markdown(&self) -> String {
89 let project_impact = markdown_bullets(&self.project_impact);
90 let suggestions = if self.suggestions.is_empty() {
91 "- None".to_string()
92 } else {
93 self.suggestions
94 .iter()
95 .map(FocusedReviewSuggestion::to_markdown)
96 .collect::<Vec<_>>()
97 .join("\n")
98 };
99
100 format!(
101 "## Review\n\n### Project Impact\n\n{project_impact}\n\n### \
102 Suggestions\n\n{suggestions}"
103 )
104 }
105}
106
107#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
109#[serde(deny_unknown_fields)]
110#[schemars(extend("required" = ["candidate_index", "reason", "suggestion_index"]))]
111pub struct FocusedReviewDecision {
112 pub candidate_index: usize,
114 pub reason: String,
116 pub suggestion_index: Option<usize>,
120}
121
122impl<'de> Deserialize<'de> for FocusedReviewDecision {
123 fn deserialize<DeserializerType>(
124 deserializer: DeserializerType,
125 ) -> Result<Self, DeserializerType::Error>
126 where
127 DeserializerType: Deserializer<'de>,
128 {
129 let input = FocusedReviewDecisionInput::deserialize(deserializer)?;
130 let suggestion_index = match input.suggestion_index {
131 ReviewDisposition::Retained(index) => Some(index),
132 ReviewDisposition::Rejected(()) => None,
133 };
134
135 Ok(Self {
136 candidate_index: input.candidate_index,
137 reason: input.reason,
138 suggestion_index,
139 })
140 }
141}
142
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
145#[serde(deny_unknown_fields)]
146#[schemars(
147 title = "FocusedReviewSuggestion",
148 description = "One actionable high- or medium-severity finding scoped to the reviewed diff."
149)]
150pub struct FocusedReviewSuggestion {
151 #[schemars(
153 title = "details",
154 description = "Concise issue details, including relevant repository-root-relative file \
155 and line references when available, plus the practical impact."
156 )]
157 pub details: String,
158 #[schemars(
160 description = "Source evidence for this finding. Quote exact code from the reviewed diff, \
161 identify the old or new side, and explain its trigger, impact, and \
162 correction. Use null only when no reliable source anchor is available."
163 )]
164 #[serde(skip_serializing_if = "Option::is_none")]
165 pub evidence: Option<FocusedReviewEvidence>,
166 #[schemars(
168 title = "severity",
169 description = "Finding severity: high for correctness, security, data-loss, or \
170 build-breaking risks; medium for concrete reliability, maintainability, \
171 performance, or workflow risks."
172 )]
173 pub severity: FocusedReviewSeverity,
174}
175
176impl FocusedReviewSuggestion {
177 pub fn resolve_evidence_range(&mut self, start_line: u32, end_line: u32) {
181 let Some(evidence) = &mut self.evidence else {
182 return;
183 };
184 let claimed_line = evidence.start_line;
185 evidence.start_line = start_line;
186 evidence.end_line = end_line;
187 self.details = self.details_with_location(claimed_line);
188 }
189
190 fn to_markdown(&self) -> String {
193 let Some(evidence) = &self.evidence else {
194 return format!(
195 "- [{}] (unanchored): {}",
196 self.severity,
197 self.details.trim()
198 );
199 };
200 let location = if evidence.start_line == 0 {
201 format!("`{}` (unanchored)", evidence.path)
202 } else {
203 format!("`{}:{}`", evidence.path, evidence.start_line)
204 };
205 let side = match evidence.side {
206 FocusedReviewSide::New => "",
207 FocusedReviewSide::Old => " (before change)",
208 };
209
210 format!(
211 "- [{}]: {location}{side}: {} Trigger: {} Impact: {} Correction: {} Supporting \
212 references are unverified.",
213 self.severity,
214 self.details.trim(),
215 evidence.trigger.trim(),
216 evidence.impact.trim(),
217 evidence.correction.trim(),
218 )
219 }
220
221 fn details_with_location(&self, claimed_line: u32) -> String {
223 let details = self.details.trim();
224 let Some(evidence) = &self.evidence else {
225 return details.to_string();
226 };
227 if evidence.path.is_empty() || claimed_line == 0 {
228 return details.to_string();
229 }
230 let prefix = format!("{}:", evidence.path);
231 let mut rendered = String::new();
232 let mut copied = 0;
233 for (start, _) in details.match_indices(&prefix) {
234 if start < copied
235 || details[..start]
236 .chars()
237 .next_back()
238 .is_some_and(|character| {
239 character.is_alphanumeric()
240 || matches!(character, '/' | '\\' | '_' | '-' | '.')
241 })
242 {
243 continue;
244 }
245 let suffix = &details[start + prefix.len()..];
246 let mut length = suffix.bytes().take_while(u8::is_ascii_digit).count();
247 if suffix[..length].parse::<u32>().ok() != Some(claimed_line) {
248 continue;
249 }
250 while suffix
253 .as_bytes()
254 .get(length)
255 .is_some_and(|separator| matches!(separator, b':' | b'-'))
256 {
257 let digits = suffix[length + 1..]
258 .bytes()
259 .take_while(u8::is_ascii_digit)
260 .count();
261 if digits == 0 {
262 break;
263 }
264 length += 1 + digits;
265 }
266 rendered.push_str(&details[copied..start]);
267 rendered.push_str(&evidence.path);
268 if evidence.start_line > 0 {
269 rendered.push(':');
270 rendered.push_str(&evidence.start_line.to_string());
271 }
272 copied = start + prefix.len() + length;
273 }
274 rendered.push_str(&details[copied..]);
275
276 rendered
277 }
278}
279
280#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
282#[serde(deny_unknown_fields)]
283pub struct FocusedReviewEvidence {
284 pub correction: String,
286 pub end_line: u32,
288 pub existing_code: String,
290 pub impact: String,
292 pub path: String,
294 pub side: FocusedReviewSide,
296 pub start_line: u32,
298 pub trigger: String,
300}
301
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
304#[serde(rename_all = "lowercase")]
305pub enum FocusedReviewSide {
306 Old,
308 New,
310}
311
312#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
314#[serde(rename_all = "lowercase")]
315#[schemars(
316 title = "FocusedReviewSeverity",
317 description = "Supported severity for an actionable focused-review finding."
318)]
319pub enum FocusedReviewSeverity {
320 High,
322 Medium,
324}
325
326impl fmt::Display for FocusedReviewSeverity {
327 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
328 formatter.write_str(match self {
329 Self::High => "High",
330 Self::Medium => "Medium",
331 })
332 }
333}
334
335fn markdown_bullets(items: &[String]) -> String {
338 if items.is_empty() {
339 return "- None".to_string();
340 }
341
342 items
343 .iter()
344 .map(|item| format!("- {}", item.trim()))
345 .collect::<Vec<_>>()
346 .join("\n")
347}
348
349#[derive(Deserialize)]
352#[serde(deny_unknown_fields)]
353struct FocusedReviewDecisionInput {
354 candidate_index: usize,
355 reason: String,
356 suggestion_index: ReviewDisposition,
357}
358
359#[derive(Deserialize)]
362#[serde(untagged)]
363enum ReviewDisposition {
364 Retained(usize),
365 Rejected(()),
366}
367
368#[cfg(test)]
369#[path = "review_test.rs"]
370mod tests;