Skip to main content

ag_session/
review.rs

1//! Pure focused-review parsing helpers shared across session frontends.
2
3use std::fmt;
4use std::str::FromStr;
5
6use ag_protocol::TurnPrompt;
7
8/// Durable state of one focused-review generation attempt.
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum FocusedReviewStatus {
11    /// Review generation is still running.
12    Pending,
13    /// Review generation completed and persisted its markdown.
14    Ready,
15    /// Some batches or final checks remain incomplete; retained findings are
16    /// provisional.
17    Partial,
18    /// Review generation completed without usable markdown.
19    Failed,
20}
21
22impl FocusedReviewStatus {
23    /// Classifies generated and legacy review markdown at the persistence
24    /// boundary. A history-only caveat does not mean original diff batches
25    /// were skipped.
26    #[must_use]
27    pub fn for_text(text: &str) -> Self {
28        if text
29            .rsplit_once("\n### Coverage\n")
30            .is_some_and(|(_, coverage)| coverage.trim_start().starts_with("Partial review:"))
31        {
32            Self::Partial
33        } else {
34            Self::Ready
35        }
36    }
37}
38
39impl fmt::Display for FocusedReviewStatus {
40    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
41        formatter.write_str(match self {
42            Self::Pending => "Pending",
43            Self::Ready => "Ready",
44            Self::Partial => "Partial",
45            Self::Failed => "Failed",
46        })
47    }
48}
49
50impl FromStr for FocusedReviewStatus {
51    type Err = String;
52
53    fn from_str(value: &str) -> Result<Self, Self::Err> {
54        match value {
55            "Pending" => Ok(Self::Pending),
56            "Ready" => Ok(Self::Ready),
57            "Partial" => Ok(Self::Partial),
58            "Failed" => Ok(Self::Failed),
59            _ => Err(format!("Unknown focused review status: {value}")),
60        }
61    }
62}
63
64/// Builds the agent-facing `/apply` prompt from focused-review suggestions.
65///
66/// The prompt explicitly asks the agent to verify each suggestion against the
67/// current code before making changes, then apply only suggestions that remain
68/// correct and relevant.
69pub fn build_apply_review_prompt(suggestions: &str) -> TurnPrompt {
70    let suggestions = suggestions.trim();
71    let fence = ag_protocol::diff_fence(suggestions);
72    let fenced_suggestions = format!("{fence}text\n{suggestions}\n{fence}");
73    let prompt = APPLY_REVIEW_PROMPT_TEMPLATE
74        .trim_end()
75        .replace("{{ fenced_suggestions }}", &fenced_suggestions);
76
77    TurnPrompt::from_text(prompt)
78}
79
80/// Extracts actionable suggestion content from focused-review markdown.
81///
82/// Returns `None` when the `### Suggestions` section is missing, empty, or
83/// reports `- None` with optional trailing punctuation.
84#[must_use]
85pub fn review_suggestions(review_text: &str) -> Option<String> {
86    let suggestions_header = "### Suggestions";
87    let header_start = review_text.find(suggestions_header)?;
88    let content_start = header_start + suggestions_header.len();
89    let content = &review_text[content_start..];
90    let section_end = content.find("\n### ").unwrap_or(content.len());
91    let suggestions = content[..section_end].trim();
92
93    if suggestions.is_empty() || is_no_suggestions_sentinel(suggestions) {
94        return None;
95    }
96
97    Some(suggestions.to_string())
98}
99
100/// Returns whether focused-review markdown contains suggestions that `/apply`
101/// can act on.
102#[must_use]
103pub fn has_actionable_review_suggestions(review_text: Option<&str>) -> bool {
104    review_text.and_then(review_suggestions).is_some()
105}
106
107const APPLY_REVIEW_PROMPT_TEMPLATE: &str = include_str!("template/apply_review_prompt.md");
108
109/// Returns whether a suggestions section contains only the required `None`
110/// sentinel plus optional trailing punctuation.
111fn is_no_suggestions_sentinel(suggestions: &str) -> bool {
112    suggestions.strip_prefix("- None").is_some_and(|suffix| {
113        suffix
114            .chars()
115            .all(|character| character.is_ascii_punctuation())
116    })
117}
118
119#[cfg(test)]
120#[path = "review_test.rs"]
121mod tests;