Skip to main content

blyte_cli/
fix_round.rs

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