use std::fmt;
use schemars::JsonSchema;
use serde::{Deserialize, Deserializer, Serialize};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
title = "FocusedReview",
description = "Structured focused-review result. Project impact describes the overall effect \
of the diff, while suggestions contains only actionable high- or \
medium-severity findings."
)]
pub struct FocusedReview {
#[serde(default, skip_serializing_if = "Vec::is_empty")]
#[schemars(
description = "Consolidation only: account for every input suggestion by its zero-based \
candidate_index, linking to a retained output suggestion or explaining its \
rejection. Every output suggestion must be referenced by at least one \
decision. Use an empty array for discovery."
)]
pub candidate_decisions: Vec<FocusedReviewDecision>,
#[schemars(
title = "project_impact",
description = "Concise statements about the diff's effects on behavior, reliability, \
maintainability, performance, security, or developer workflow. Use an \
empty array when there is no notable impact."
)]
pub project_impact: Vec<String>,
#[schemars(
title = "suggestions",
description = "Actionable findings scoped to the reviewed diff, ordered by severity with \
high severity first. Use an empty array when there are no suggestions."
)]
pub suggestions: Vec<FocusedReviewSuggestion>,
}
impl FocusedReview {
pub fn validate_candidate_decisions(&self, candidate_count: usize) -> Result<(), String> {
let mut accounted = vec![false; candidate_count];
let mut retained = vec![false; self.suggestions.len()];
for decision in &self.candidate_decisions {
let Some(seen) = accounted.get_mut(decision.candidate_index) else {
return Err("Candidate decision references an unknown input finding".into());
};
if *seen || decision.reason.trim().is_empty() {
return Err(
"Candidate decisions must be unique and explain their reasoning".into(),
);
}
if let Some(index) = decision.suggestion_index {
let Some(output) = retained.get_mut(index) else {
return Err("Candidate decision references an unknown output finding".into());
};
*output = true;
}
*seen = true;
}
if accounted.contains(&false) {
return Err(format!(
"Consolidation must account for all {candidate_count} candidates"
));
}
if retained.contains(&false) {
return Err(
"Consolidation must link every output finding to an input candidate".into(),
);
}
Ok(())
}
#[must_use]
pub fn to_markdown(&self) -> String {
let project_impact = markdown_bullets(&self.project_impact);
let suggestions = if self.suggestions.is_empty() {
"- None".to_string()
} else {
self.suggestions
.iter()
.map(FocusedReviewSuggestion::to_markdown)
.collect::<Vec<_>>()
.join("\n")
};
format!(
"## Review\n\n### Project Impact\n\n{project_impact}\n\n### \
Suggestions\n\n{suggestions}"
)
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(extend("required" = ["candidate_index", "reason", "suggestion_index"]))]
pub struct FocusedReviewDecision {
pub candidate_index: usize,
pub reason: String,
pub suggestion_index: Option<usize>,
}
impl<'de> Deserialize<'de> for FocusedReviewDecision {
fn deserialize<DeserializerType>(
deserializer: DeserializerType,
) -> Result<Self, DeserializerType::Error>
where
DeserializerType: Deserializer<'de>,
{
let input = FocusedReviewDecisionInput::deserialize(deserializer)?;
let suggestion_index = match input.suggestion_index {
ReviewDisposition::Retained(index) => Some(index),
ReviewDisposition::Rejected(()) => None,
};
Ok(Self {
candidate_index: input.candidate_index,
reason: input.reason,
suggestion_index,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
#[schemars(
title = "FocusedReviewSuggestion",
description = "One actionable high- or medium-severity finding scoped to the reviewed diff."
)]
pub struct FocusedReviewSuggestion {
#[schemars(
title = "details",
description = "Concise issue details, including relevant repository-root-relative file \
and line references when available, plus the practical impact."
)]
pub details: String,
#[schemars(
description = "Source evidence for this finding. Quote exact code from the reviewed diff, \
identify the old or new side, and explain its trigger, impact, and \
correction. Use null only when no reliable source anchor is available."
)]
#[serde(skip_serializing_if = "Option::is_none")]
pub evidence: Option<FocusedReviewEvidence>,
#[schemars(
title = "severity",
description = "Finding severity: high for correctness, security, data-loss, or \
build-breaking risks; medium for concrete reliability, maintainability, \
performance, or workflow risks."
)]
pub severity: FocusedReviewSeverity,
}
impl FocusedReviewSuggestion {
pub fn resolve_evidence_range(&mut self, start_line: u32, end_line: u32) {
let Some(evidence) = &mut self.evidence else {
return;
};
let claimed_line = evidence.start_line;
evidence.start_line = start_line;
evidence.end_line = end_line;
self.details = self.details_with_location(claimed_line);
}
fn to_markdown(&self) -> String {
let Some(evidence) = &self.evidence else {
return format!(
"- [{}] (unanchored): {}",
self.severity,
self.details.trim()
);
};
let location = if evidence.start_line == 0 {
format!("`{}` (unanchored)", evidence.path)
} else {
format!("`{}:{}`", evidence.path, evidence.start_line)
};
let side = match evidence.side {
FocusedReviewSide::New => "",
FocusedReviewSide::Old => " (before change)",
};
format!(
"- [{}]: {location}{side}: {} Trigger: {} Impact: {} Correction: {} Supporting \
references are unverified.",
self.severity,
self.details.trim(),
evidence.trigger.trim(),
evidence.impact.trim(),
evidence.correction.trim(),
)
}
fn details_with_location(&self, claimed_line: u32) -> String {
let details = self.details.trim();
let Some(evidence) = &self.evidence else {
return details.to_string();
};
if evidence.path.is_empty() || claimed_line == 0 {
return details.to_string();
}
let prefix = format!("{}:", evidence.path);
let mut rendered = String::new();
let mut copied = 0;
for (start, _) in details.match_indices(&prefix) {
if start < copied
|| details[..start]
.chars()
.next_back()
.is_some_and(|character| {
character.is_alphanumeric()
|| matches!(character, '/' | '\\' | '_' | '-' | '.')
})
{
continue;
}
let suffix = &details[start + prefix.len()..];
let mut length = suffix.bytes().take_while(u8::is_ascii_digit).count();
if suffix[..length].parse::<u32>().ok() != Some(claimed_line) {
continue;
}
while suffix
.as_bytes()
.get(length)
.is_some_and(|separator| matches!(separator, b':' | b'-'))
{
let digits = suffix[length + 1..]
.bytes()
.take_while(u8::is_ascii_digit)
.count();
if digits == 0 {
break;
}
length += 1 + digits;
}
rendered.push_str(&details[copied..start]);
rendered.push_str(&evidence.path);
if evidence.start_line > 0 {
rendered.push(':');
rendered.push_str(&evidence.start_line.to_string());
}
copied = start + prefix.len() + length;
}
rendered.push_str(&details[copied..]);
rendered
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(deny_unknown_fields)]
pub struct FocusedReviewEvidence {
pub correction: String,
pub end_line: u32,
pub existing_code: String,
pub impact: String,
pub path: String,
pub side: FocusedReviewSide,
pub start_line: u32,
pub trigger: String,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
pub enum FocusedReviewSide {
Old,
New,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, JsonSchema)]
#[serde(rename_all = "lowercase")]
#[schemars(
title = "FocusedReviewSeverity",
description = "Supported severity for an actionable focused-review finding."
)]
pub enum FocusedReviewSeverity {
High,
Medium,
}
impl fmt::Display for FocusedReviewSeverity {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(match self {
Self::High => "High",
Self::Medium => "Medium",
})
}
}
fn markdown_bullets(items: &[String]) -> String {
if items.is_empty() {
return "- None".to_string();
}
items
.iter()
.map(|item| format!("- {}", item.trim()))
.collect::<Vec<_>>()
.join("\n")
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct FocusedReviewDecisionInput {
candidate_index: usize,
reason: String,
suggestion_index: ReviewDisposition,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum ReviewDisposition {
Retained(usize),
Rejected(()),
}
#[cfg(test)]
#[path = "review_test.rs"]
mod tests;