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, Deserializer, 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    /// Per-candidate accounting supplied only during consolidation.
19    #[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    /// Concise statements describing the overall effect of the reviewed diff.
28    #[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    /// Actionable high- or medium-severity findings from the reviewed diff.
36    #[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    /// Rejects incomplete consolidation accounting before callers replace
46    /// their original findings. Indices refer to this call's input and output.
47    ///
48    /// # Errors
49    /// Returns a diagnostic for missing, duplicate, out-of-range, or
50    /// unexplained candidate decisions, or outputs without an input
51    /// disposition.
52    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    /// Formats the structured review for the terminal session transcript.
87    #[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/// Auditable disposition of one input suggestion during consolidation.
108#[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    /// Zero-based index in the supplied candidate suggestions array.
113    pub candidate_index: usize,
114    /// Source-based reason for retaining, merging, or rejecting this finding.
115    pub reason: String,
116    /// Zero-based retained output suggestion; null means rejected. Duplicate
117    /// candidates may refer to the same consolidated output suggestion. The
118    /// field must be present even for rejection.
119    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/// One actionable focused-review finding.
144#[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    /// Concise explanation of the issue and its practical impact.
152    #[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    /// Source evidence and rationale, when a finding can be anchored.
159    #[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    /// Severity assigned from the focused-review severity policy.
167    #[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    /// Applies a host-verified range and reconciles duplicate primary prose
178    /// citations. Supporting references to other lines retain their locations.
179    /// Pass zeroes when the evidence cannot be anchored.
180    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    /// Labels missing source anchors and distinguishes unverified supporting
191    /// references from the primary evidence location.
192    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    /// Reconciles citations matching the original primary path and line.
222    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            // Discard unverified columns and ranges along with stale line
251            // numbers.
252            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/// Source citation and actionable rationale for one focused-review finding.
281#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
282#[serde(deny_unknown_fields)]
283pub struct FocusedReviewEvidence {
284    /// Concrete correction that addresses the reported risk.
285    pub correction: String,
286    /// Inclusive source line, resolved by the host; zero means unanchored.
287    pub end_line: u32,
288    /// Exact source snippet without unified-diff markers.
289    pub existing_code: String,
290    /// Practical consequence when the trigger occurs.
291    pub impact: String,
292    /// Repository-root-relative POSIX path on the selected side of the diff.
293    pub path: String,
294    /// Version of the source used by the citation.
295    pub side: FocusedReviewSide,
296    /// First source line, resolved by the host; zero means unanchored.
297    pub start_line: u32,
298    /// Concrete input, state, or sequence that exposes the risk.
299    pub trigger: String,
300}
301
302/// Version of a changed file cited by a focused-review finding.
303#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
304#[serde(rename_all = "lowercase")]
305pub enum FocusedReviewSide {
306    /// Source before the change, including deleted code.
307    Old,
308    /// Source after the change, including added code.
309    New,
310}
311
312/// Supported severity levels for actionable focused-review findings.
313#[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    /// Correctness, security, data-loss, or build-breaking risk.
321    High,
322    /// Concrete reliability, maintainability, performance, or workflow risk.
323    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
335/// Formats one project-impact list, using the stable empty sentinel when no
336/// impact was reported.
337fn 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/// Wire input keeps a required disposition separate from the nullable public
350/// index so omission cannot silently reject a discovered candidate.
351#[derive(Deserialize)]
352#[serde(deny_unknown_fields)]
353struct FocusedReviewDecisionInput {
354    candidate_index: usize,
355    reason: String,
356    suggestion_index: ReviewDisposition,
357}
358
359/// Explicit wire values: an output index retains the candidate; null rejects
360/// it. The enum has no implicit missing-field default.
361#[derive(Deserialize)]
362#[serde(untagged)]
363enum ReviewDisposition {
364    Retained(usize),
365    Rejected(()),
366}
367
368#[cfg(test)]
369#[path = "review_test.rs"]
370mod tests;