Skip to main content

blyte_cli/
fix_round.rs

1use std::path::{Path, PathBuf};
2
3use serde::{Deserialize, Serialize};
4
5use crate::model_review::{Concern, ModelReviewResult};
6
7/// Exact commit message instructed for a fix round with only fallbacks.
8pub const COMMIT_MESSAGE: &str = "fix: fail loudly where review found a fallback";
9
10/// Exact commit message instructed for a fix round that includes review concerns.
11pub const CONCERNS_COMMIT_MESSAGE: &str = "fix: address the review's concerns";
12
13/// A confirmed fallback sent to the implementer during a fix round.
14#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
15pub struct ConfirmedFallback {
16    pub file: String,
17    pub line: usize,
18    pub text: String,
19    pub reason: String,
20}
21
22/// Summary fields recorded for a completed fix round.
23#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24pub struct FixRoundSummary {
25    pub outcome: String,
26    pub turns: u32,
27    pub cost_usd: Option<f64>,
28    pub seconds: u64,
29    pub commits: Vec<String>,
30    /// Confirmed fallbacks in the review that stands; `None` (null) when that review did not
31    /// run or failed, so the count is not known.
32    pub fallbacks_left: Option<usize>,
33    /// Concerns in the review that stands; `None` (null) when that review did not run or failed,
34    /// so the count is not known.
35    #[serde(default)]
36    pub concerns_left: Option<usize>,
37    pub kept: bool,
38}
39
40/// Persistent state file `.wt/<id>.fixround.json`.
41#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42#[serde(tag = "state", rename_all = "snake_case")]
43pub enum FixRoundRecord {
44    Started {
45        pre_round_sha: String,
46        fallbacks_sent: Vec<ConfirmedFallback>,
47        #[serde(default)]
48        concerns_sent: Vec<Concern>,
49        started_at: u64,
50    },
51    Done {
52        #[serde(default, skip_serializing_if = "Option::is_none")]
53        pre_round_sha: Option<String>,
54        #[serde(default, skip_serializing_if = "Vec::is_empty")]
55        fallbacks_sent: Vec<ConfirmedFallback>,
56        #[serde(default, skip_serializing_if = "Vec::is_empty")]
57        concerns_sent: Vec<Concern>,
58        #[serde(default, skip_serializing_if = "Option::is_none")]
59        started_at: Option<u64>,
60        #[serde(flatten)]
61        summary: FixRoundSummary,
62    },
63}
64
65/// Path to `.wt/<id>.fixround.json`.
66pub fn record_path(wt_parent: &Path, id: &str) -> PathBuf {
67    wt_parent.join(format!("{id}.fixround.json"))
68}
69
70/// Read and parse `.wt/<id>.fixround.json`. Returns `Ok(None)` only when the file does not exist.
71pub fn load_record(path: &Path) -> Result<Option<FixRoundRecord>, String> {
72    match std::fs::read_to_string(path) {
73        Ok(raw) => serde_json::from_str(&raw)
74            .map(Some)
75            .map_err(|e| format!("cannot parse {}: {e}", path.display())),
76        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
77        Err(e) => Err(format!("cannot read {}: {e}", path.display())),
78    }
79}
80
81/// Write `.wt/<id>.fixround.json`.
82pub fn write_record(path: &Path, record: &FixRoundRecord) -> Result<(), String> {
83    if let Some(parent) = path.parent() {
84        std::fs::create_dir_all(parent)
85            .map_err(|e| format!("cannot create {}: {e}", parent.display()))?;
86    }
87    let json = serde_json::to_string_pretty(record)
88        .map_err(|e| format!("cannot serialize {}: {e}", path.display()))?;
89    std::fs::write(path, format!("{json}\n"))
90        .map_err(|e| format!("cannot write {}: {e}", path.display()))
91}
92
93/// Count verdicts equal to `"fallback"` in a model review result.
94pub fn confirmed_count(review: &ModelReviewResult) -> usize {
95    review
96        .fallbacks
97        .iter()
98        .filter(|f| f.verdict == "fallback")
99        .count()
100}
101
102/// Count confirmed fallbacks in the standing review; `None` when no review ran or it failed.
103pub fn fallbacks_left(review: Option<&ModelReviewResult>) -> Option<usize> {
104    match review {
105        Some(mr) if !mr.is_failed() => Some(confirmed_count(mr)),
106        _ => None,
107    }
108}
109
110/// Count concerns in the standing review; `None` when no review ran or it failed.
111pub fn concerns_left(review: Option<&ModelReviewResult>) -> Option<usize> {
112    match review {
113        Some(mr) if !mr.is_failed() => Some(mr.concerns.len()),
114        _ => None,
115    }
116}
117
118/// Decide whether a fix round should run after the first pass and its review.
119pub fn should_run(
120    is_research: bool,
121    outcome: &str,
122    fix_round_enabled: bool,
123    review: Option<&ModelReviewResult>,
124) -> bool {
125    if is_research || outcome != "verified" || !fix_round_enabled {
126        return false;
127    }
128    let Some(mr) = review else {
129        return false;
130    };
131    if mr.is_failed() {
132        return false;
133    }
134    confirmed_count(mr) > 0 || !mr.concerns.is_empty()
135}
136
137/// Build the task text passed to the implementer for a fix round.
138pub fn task_text(
139    original_task: &str,
140    fallbacks: &[ConfirmedFallback],
141    concerns: &[Concern],
142) -> String {
143    let mut out = String::new();
144    let commit_message = if concerns.is_empty() {
145        COMMIT_MESSAGE
146    } else {
147        CONCERNS_COMMIT_MESSAGE
148    };
149    if fallbacks.is_empty() && !concerns.is_empty() {
150        out.push_str(&format!(
151            "This work passed its check, and a review raised the concerns listed below.\n\
152             For each one, change the code or the tests so that the concern no longer holds.\n\
153             If a listed concern is wrong, leave the code as it is and say why in the final message.\n\
154             Change nothing else.\n\
155             Commit with the message `{commit_message}`.\n\n"
156        ));
157        for c in concerns {
158            out.push_str(&crate::model_review::format_concern(c));
159            out.push('\n');
160        }
161    } else {
162        out.push_str(&format!(
163            "This work passed its check, and a review found the fallbacks listed below.\n\
164             For each one, change the code so that the missing, unknown or unreadable case fails with an error that names what is missing, and update or add a test for that case.\n\
165             If a listed line is not a fallback, leave it and say why in the final message.\n\
166             Change nothing else.\n\
167             Commit with the message `{commit_message}`.\n\n"
168        ));
169        for fb in fallbacks {
170            out.push_str(&format!("{}:{} {}\n", fb.file, fb.line, fb.text));
171            out.push_str(&format!("  {}\n", fb.reason));
172        }
173        if !concerns.is_empty() {
174            out.push_str(
175                "\nThe review also raised these concerns. For each one, change the code or the tests so that the concern no longer holds; if one is wrong, leave the code as it is and say why in the final message.\n",
176            );
177            for c in concerns {
178                out.push_str(&crate::model_review::format_concern(c));
179                out.push('\n');
180            }
181        }
182    }
183    out.push_str("\n## Original task (for context; already done)\n\n");
184    out.push_str(original_task);
185    if !out.ends_with('\n') {
186        out.push('\n');
187    }
188    out
189}
190
191/// Extract confirmed fallbacks from a succeeded model review and its checks file or worktree.
192pub fn collect_confirmed_fallbacks(
193    root: &Path,
194    id: &str,
195    worktree_dir: &Path,
196    review: &ModelReviewResult,
197) -> Result<Vec<ConfirmedFallback>, String> {
198    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
199    let checks_raw = std::fs::read_to_string(&checks_path)
200        .map_err(|e| format!("cannot read {}: {e}", checks_path.display()))?;
201    let checks_val: serde_json::Value = serde_json::from_str(&checks_raw)
202        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
203    let checks_fallbacks = checks_val
204        .get("fallbacks")
205        .and_then(|v| v.as_array())
206        .ok_or_else(|| format!("missing \"fallbacks\" array in {}", checks_path.display()))?;
207
208    let mut out = Vec::new();
209    for v in review.fallbacks.iter().filter(|f| f.verdict == "fallback") {
210        let matched_text = checks_fallbacks.iter().find_map(|entry| {
211            let file = entry.get("file")?.as_str()?;
212            let line = usize::try_from(entry.get("line")?.as_u64()?).ok()?;
213            if file == v.file && line == v.line {
214                entry.get("text")?.as_str().map(str::to_string)
215            } else {
216                None
217            }
218        });
219        let text = match matched_text {
220            Some(t) => t,
221            None => read_worktree_line(worktree_dir, &v.file, v.line)?,
222        };
223        out.push(ConfirmedFallback {
224            file: v.file.clone(),
225            line: v.line,
226            text,
227            reason: v.reason.clone(),
228        });
229    }
230    Ok(out)
231}
232
233fn read_worktree_line(worktree_dir: &Path, file: &str, line: usize) -> Result<String, String> {
234    let path = worktree_dir.join(file);
235    let content = std::fs::read_to_string(&path)
236        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
237    if line == 0 {
238        return Err(format!("invalid line 0 in {}", path.display()));
239    }
240    content
241        .lines()
242        .nth(line - 1)
243        .map(|l| l.trim().to_string())
244        .ok_or_else(|| format!("line {line} not found in {}", path.display()))
245}
246
247/// Append a flag to `.wt/<id>.checks.json`.
248pub fn append_check_flag(root: &Path, id: &str, flag: &str) -> Result<(), String> {
249    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
250    let raw = std::fs::read_to_string(&checks_path)
251        .map_err(|e| format!("cannot read {}: {e}", checks_path.display()))?;
252    let mut val: serde_json::Value = serde_json::from_str(&raw)
253        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
254    let flags = val
255        .get_mut("flags")
256        .and_then(|v| v.as_array_mut())
257        .ok_or_else(|| format!("missing \"flags\" array in {}", checks_path.display()))?;
258    flags.push(serde_json::Value::String(flag.to_string()));
259    let updated = serde_json::to_string_pretty(&val)
260        .map_err(|e| format!("cannot serialize {}: {e}", checks_path.display()))?;
261    std::fs::write(&checks_path, format!("{updated}\n"))
262        .map_err(|e| format!("cannot write {}: {e}", checks_path.display()))
263}
264
265/// Flag appended to the checks file when a fix round did not produce a kept change.
266pub fn failure_flag(round_outcome: &str) -> String {
267    if round_outcome == "no_change" {
268        "fix round made no change".to_string()
269    } else {
270        format!("fix round did not pass: {round_outcome}")
271    }
272}
273
274/// Sum optional dollar costs across two passes.
275pub fn sum_costs(a: Option<f64>, b: Option<f64>) -> Option<f64> {
276    match (a, b) {
277        (Some(x), Some(y)) => Some(x + y),
278        (Some(x), None) => Some(x),
279        (None, Some(y)) => Some(y),
280        (None, None) => None,
281    }
282}
283
284/// Combine the first pass's final message with the fix round's when the round was kept.
285pub fn combined_final_message(
286    first: Option<String>,
287    round: Option<String>,
288    kept: bool,
289) -> Option<String> {
290    if !kept {
291        return first;
292    }
293    match (first, round) {
294        (Some(f), Some(r)) if !r.is_empty() => Some(format!("{f}\n\nFix round:\n{r}")),
295        (None, Some(r)) if !r.is_empty() => Some(format!("Fix round:\n{r}")),
296        (first, _) => first,
297    }
298}