Skip to main content

blyte_cli/
model_review.rs

1use std::path::Path;
2use std::process::Command;
3
4#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
5pub struct Concern {
6    pub file: String,
7    pub line: Option<u64>,
8    pub severity: String,
9    pub text: String,
10}
11
12pub const SYSTEM_PROMPT: &str = "\
13You are a senior software engineer performing a first review of a code diff against a task specification.
14Review the diff against the task. Raise only concrete problems a reviewer must look at:
15- the task's requirements not met
16- a behaviour or edge case the task names but the code or tests miss
17- changes outside what the task asks for
18- tests that could pass with a wrong implementation
19- risky commands or deleted tests
20
21Do not make style comments.
22Raise at most 10 concerns.
23Answer with only a JSON array of objects with the following schema:
24[{\"file\": \"<path>\", \"line\": <line number or null>, \"severity\": \"high\" | \"medium\" | \"low\", \"text\": \"<description>\"}]
25Return [] when there is nothing to raise. Do not include any text or markdown outside the JSON array.";
26
27/// System prompt + user message. The user message holds, in this order: the task text
28/// (under "## Task"), `git diff --stat`, and the full diff (under "## Diff"), the diff cut to
29/// 200_000 characters with a final line "[diff truncated]" if longer.
30pub fn build_request(task: &str, stat: &str, diff: &str) -> blyte_provider::Request {
31    let diff_text = if diff.chars().count() > 200_000 {
32        let cutoff = diff
33            .char_indices()
34            .nth(200_000)
35            .map(|(i, _)| i)
36            .unwrap_or(diff.len());
37        let mut s = diff[..cutoff].to_string();
38        if !s.ends_with('\n') {
39            s.push('\n');
40        }
41        s.push_str("[diff truncated]\n");
42        s
43    } else {
44        diff.to_string()
45    };
46
47    let mut user_msg = String::new();
48    user_msg.push_str("## Task\n");
49    user_msg.push_str(task);
50    if !user_msg.ends_with('\n') {
51        user_msg.push('\n');
52    }
53    user_msg.push('\n');
54
55    let stat_trimmed = stat.trim();
56    if !stat_trimmed.is_empty() {
57        user_msg.push_str(stat_trimmed);
58        user_msg.push_str("\n\n");
59    }
60
61    user_msg.push_str("## Diff\n");
62    user_msg.push_str(&diff_text);
63    if !user_msg.ends_with('\n') {
64        user_msg.push('\n');
65    }
66
67    blyte_provider::Request {
68        system: SYSTEM_PROMPT.to_string(),
69        messages: vec![blyte_provider::Message::User(user_msg)],
70        tools: Vec::new(),
71        max_output_tokens: Some(32_000),
72        timeout: None,
73    }
74}
75
76/// Parse the model's text. It is asked for a JSON array of
77/// {"file","line","severity","text"} with severity one of "high","medium","low",
78/// and `[]` when there is nothing to raise. Accept the array bare or inside a ```json fence,
79/// with surrounding prose. Unknown severities become "low"; entries without "text" are dropped.
80/// Empty or whitespace-only text → Err("empty response").
81/// Unparseable text → Err(String) with the first 200 characters of the text.
82pub fn parse(text: &str) -> Result<Vec<Concern>, String> {
83    if text.trim().is_empty() {
84        return Err("empty response".to_string());
85    }
86    let candidate = extract_json_candidate(text);
87    let value: serde_json::Value = match candidate {
88        Some(s) => match serde_json::from_str(s) {
89            Ok(v) => v,
90            Err(_) => {
91                if let (Some(start), Some(end)) = (text.find('['), text.rfind(']')) {
92                    if end >= start {
93                        match serde_json::from_str(&text[start..=end]) {
94                            Ok(v) => v,
95                            Err(_) => return Err(first_200(text)),
96                        }
97                    } else {
98                        return Err(first_200(text));
99                    }
100                } else {
101                    return Err(first_200(text));
102                }
103            }
104        },
105        None => return Err(first_200(text)),
106    };
107
108    let array = match value {
109        serde_json::Value::Array(arr) => arr,
110        serde_json::Value::Object(mut map) => {
111            if let Some(serde_json::Value::Array(arr)) = map.remove("concerns") {
112                arr
113            } else {
114                return Err(first_200(text));
115            }
116        }
117        _ => return Err(first_200(text)),
118    };
119
120    let mut concerns = Vec::new();
121    for item in array {
122        let Some(obj) = item.as_object() else {
123            continue;
124        };
125        let text_val = match obj.get("text").and_then(|t| t.as_str()) {
126            Some(t) => t.to_string(),
127            None => continue,
128        };
129        let file = obj
130            .get("file")
131            .and_then(|f| f.as_str())
132            .unwrap_or("")
133            .to_string();
134        let line = obj.get("line").and_then(|l| {
135            l.as_u64()
136                .or_else(|| l.as_str().and_then(|s| s.parse::<u64>().ok()))
137        });
138        let severity = match obj.get("severity").and_then(|s| s.as_str()) {
139            Some(s) if s.eq_ignore_ascii_case("high") => "high".to_string(),
140            Some(s) if s.eq_ignore_ascii_case("medium") => "medium".to_string(),
141            Some(s) if s.eq_ignore_ascii_case("low") => "low".to_string(),
142            _ => "low".to_string(),
143        };
144        concerns.push(Concern {
145            file,
146            line,
147            severity,
148            text: text_val,
149        });
150    }
151
152    Ok(concerns)
153}
154
155fn first_200(text: &str) -> String {
156    text.chars().take(200).collect()
157}
158
159fn extract_json_candidate(text: &str) -> Option<&str> {
160    if let Some(start) = text.find("```json") {
161        let content_start = start + 7;
162        if let Some(end) = text[content_start..].find("```") {
163            return Some(text[content_start..content_start + end].trim());
164        }
165    }
166    if let Some(start) = text.find("```") {
167        let after_fence = &text[start + 3..];
168        let content_start = if let Some(nl) = after_fence.find('\n') {
169            nl + 1
170        } else {
171            0
172        };
173        if let Some(end) = after_fence[content_start..].find("```") {
174            return Some(after_fence[content_start..content_start + end].trim());
175        }
176    }
177    if let Some(start) = text.find('[') {
178        if let Some(end) = text.rfind(']') {
179            if end >= start {
180                return Some(&text[start..=end]);
181            }
182        }
183    }
184    None
185}
186
187fn severity_rank(sev: &str) -> u8 {
188    match sev.to_ascii_lowercase().as_str() {
189        "high" => 0,
190        "medium" => 1,
191        "low" => 2,
192        _ => 3,
193    }
194}
195
196pub fn parse_error_message(err: &str, finish: Option<&str>) -> String {
197    match finish {
198        Some(reason) if !reason.is_empty() => format!("{err} (finish reason: {reason})"),
199        _ => err.to_string(),
200    }
201}
202
203pub fn sort_concerns(concerns: &mut [Concern]) {
204    concerns.sort_by_key(|c| severity_rank(&c.severity));
205}
206
207pub fn format_concern(c: &Concern) -> String {
208    if let Some(line) = c.line {
209        format!("[{}] {}:{} {}", c.severity, c.file, line, c.text)
210    } else {
211        format!("[{}] {} {}", c.severity, c.file, c.text)
212    }
213}
214
215pub fn run(root: &Path, id: &str, base: &str, wt: &Path) {
216    let start_path = root.join(".wt").join(format!("{id}.start.json"));
217    let task_text = match read_task_text(root, &start_path) {
218        Some(t) => t,
219        None => {
220            println!("== model review");
221            println!("skipped: task file not found");
222            return;
223        }
224    };
225
226    let stat_out = Command::new("git")
227        .args(["diff", "--stat", &format!("{base}..HEAD")])
228        .current_dir(wt)
229        .output()
230        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
231        .unwrap_or_default();
232
233    let diff_out = Command::new("git")
234        .args(["diff", &format!("{base}..HEAD")])
235        .current_dir(wt)
236        .output()
237        .map(|o| String::from_utf8_lossy(&o.stdout).to_string())
238        .unwrap_or_default();
239
240    if let Some(env_path) = crate::env_file::default_path() {
241        let _ = crate::env_file::load(&env_path);
242    }
243
244    let repo_config = match crate::config::load_with_fallback(root) {
245        Ok(Some((cfg, _))) => Some(cfg),
246        Ok(None) => None,
247        Err(e) => {
248            println!("== model review");
249            println!("error: {e}");
250            return;
251        }
252    };
253    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
254    let model = dispatch_cfg.model.as_deref();
255
256    // One call over a whole diff at high effort can take minutes; allow 10 unless the user set a limit.
257    if std::env::var_os("BLYTE_MODEL_TIMEOUT_SECS").is_none() {
258        std::env::set_var("BLYTE_MODEL_TIMEOUT_SECS", "600");
259    }
260    let provider = match blyte_provider::resolve_provider(model) {
261        Ok(p) => p,
262        Err(blyte_provider::ProviderError::MissingKey(key)) => {
263            println!("== model review");
264            println!("skipped: no API key (set {key})");
265            return;
266        }
267        Err(e) => {
268            println!("== model review");
269            println!("error: {e}");
270            return;
271        }
272    };
273    let model_id = provider.model_id();
274
275    let req = build_request(&task_text, &stat_out, &diff_out);
276    let resp = match provider.complete(&req) {
277        Ok(r) => r,
278        Err(e) => {
279            println!("== model review");
280            println!("error: {e}");
281            save_review(root, id, &model_id, None, Vec::new(), Some(e.to_string()));
282            return;
283        }
284    };
285
286    let cost_usd = blyte_provider::pricing(&model_id).map(|p| p.cost(&resp.usage));
287
288    let concerns = match parse(&resp.text) {
289        Ok(mut c) => {
290            sort_concerns(&mut c);
291            c
292        }
293        Err(e) => {
294            let err_msg = parse_error_message(&e, resp.finish_reason.as_deref());
295            println!("== model review");
296            println!("error: {err_msg}");
297            save_review(root, id, &model_id, cost_usd, Vec::new(), Some(err_msg));
298            return;
299        }
300    };
301
302    let cost_str = match cost_usd {
303        Some(c) => format!("${c:.4}"),
304        None => "?".to_string(),
305    };
306    println!("== model review (trial: {model_id}, {cost_str})");
307    if concerns.is_empty() {
308        println!("nothing raised");
309    } else {
310        for c in &concerns {
311            println!("{}", format_concern(c));
312        }
313    }
314
315    save_review(root, id, &model_id, cost_usd, concerns, None);
316}
317
318fn read_task_text(root: &Path, start_path: &Path) -> Option<String> {
319    let content = std::fs::read_to_string(start_path).ok()?;
320    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
321    let task_file_str = val.get("task_file")?.as_str()?;
322    let task_path = Path::new(task_file_str);
323    if task_path.is_absolute() {
324        std::fs::read_to_string(task_path).ok()
325    } else {
326        std::fs::read_to_string(root.join(task_path))
327            .or_else(|_| std::fs::read_to_string(task_path))
328            .ok()
329    }
330}
331
332fn save_review(
333    root: &Path,
334    id: &str,
335    model: &str,
336    cost_usd: Option<f64>,
337    concerns: Vec<Concern>,
338    error: Option<String>,
339) {
340    let wt_dir = root.join(".wt");
341    let _ = std::fs::create_dir_all(&wt_dir);
342    let review_path = wt_dir.join(format!("{id}.model-review.json"));
343    let ts = std::time::SystemTime::now()
344        .duration_since(std::time::UNIX_EPOCH)
345        .map(|d| d.as_secs())
346        .unwrap_or(0);
347    let record = serde_json::json!({
348        "model": model,
349        "cost_usd": cost_usd,
350        "concerns": concerns,
351        "ts": ts,
352        "error": error,
353    });
354    if let Ok(json_str) = serde_json::to_string_pretty(&record) {
355        let _ = std::fs::write(&review_path, json_str + "\n");
356    }
357}
358
359#[cfg(test)]
360mod tests {
361    use super::*;
362
363    #[test]
364    fn test_parse_empty() {
365        let res = parse("[]").expect("parse should succeed");
366        assert!(res.is_empty());
367    }
368
369    #[test]
370    fn test_parse_empty_or_whitespace() {
371        assert_eq!(parse(""), Err("empty response".to_string()));
372        assert_eq!(parse("  \n"), Err("empty response".to_string()));
373    }
374
375    #[test]
376    fn test_parse_error_message() {
377        assert_eq!(
378            parse_error_message("empty response", Some("MAX_TOKENS")),
379            "empty response (finish reason: MAX_TOKENS)"
380        );
381        assert_eq!(
382            parse_error_message("empty response", None),
383            "empty response"
384        );
385    }
386
387    #[test]
388    fn test_parse_fenced_with_prose() {
389        let input = r#"
390Here is the review of the diff against the task:
391```json
392[
393  {
394    "file": "crates/blyte-cli/src/foo.rs",
395    "line": 42,
396    "severity": "high",
397    "text": "Task requires error handling here"
398  },
399  {
400    "file": "crates/blyte-cli/src/bar.rs",
401    "line": 100,
402    "severity": "medium",
403    "text": "Missing edge case check"
404  }
405]
406```
407Overall looks okay otherwise.
408"#;
409        let concerns = parse(input).expect("parse should succeed");
410        assert_eq!(concerns.len(), 2);
411        assert_eq!(concerns[0].file, "crates/blyte-cli/src/foo.rs");
412        assert_eq!(concerns[0].line, Some(42));
413        assert_eq!(concerns[0].severity, "high");
414        assert_eq!(concerns[0].text, "Task requires error handling here");
415        assert_eq!(concerns[1].file, "crates/blyte-cli/src/bar.rs");
416        assert_eq!(concerns[1].line, Some(100));
417        assert_eq!(concerns[1].severity, "medium");
418        assert_eq!(concerns[1].text, "Missing edge case check");
419    }
420
421    #[test]
422    fn test_parse_normalization_and_filtering() {
423        let input = r#"[
424            {
425                "file": "crates/a.rs",
426                "line": null,
427                "severity": "critical",
428                "text": "A severe issue"
429            },
430            {
431                "file": "crates/b.rs",
432                "line": 10,
433                "severity": "high"
434            }
435        ]"#;
436        let concerns = parse(input).expect("parse should succeed");
437        assert_eq!(concerns.len(), 1);
438        assert_eq!(concerns[0].file, "crates/a.rs");
439        assert_eq!(concerns[0].line, None);
440        assert_eq!(concerns[0].severity, "low");
441        assert_eq!(concerns[0].text, "A severe issue");
442    }
443
444    #[test]
445    fn test_parse_not_json() {
446        let err = parse("not json").expect_err("should return Err");
447        assert!(err.contains("not json"));
448    }
449
450    #[test]
451    fn test_parse_long_unparseable_truncated_to_200() {
452        let input = "not json ".repeat(30);
453        assert!(input.chars().count() > 200);
454        let err = parse(&input).expect_err("should return Err");
455        assert_eq!(err.chars().count(), 200);
456        assert!(input.starts_with(&err));
457    }
458
459    #[test]
460    fn test_build_request_diff_truncation() {
461        let task = "Implement feature X with full test coverage.";
462        let stat = " src/main.rs | 100 ++\n 1 file changed";
463        let diff = "a".repeat(300_000);
464
465        let req = build_request(task, stat, &diff);
466        assert_eq!(req.max_output_tokens, Some(32_000));
467        assert!(req.tools.is_empty(), "tools should be empty");
468        assert_eq!(req.messages.len(), 1);
469
470        let blyte_provider::Message::User(ref msg) = req.messages[0] else {
471            panic!("expected user message");
472        };
473
474        assert!(
475            msg.contains("[diff truncated]"),
476            "must contain [diff truncated]"
477        );
478        assert!(msg.len() < 210_000, "user message length was {}", msg.len());
479
480        let task_pos = msg.find(task).expect("task text missing");
481        let diff_pos = msg.find("## Diff").expect("diff header missing");
482        assert!(task_pos < diff_pos, "task text must appear before diff");
483    }
484
485    #[test]
486    fn test_build_request_max_output_tokens() {
487        let req = build_request("task", "stat", "diff");
488        assert_eq!(req.max_output_tokens, Some(32_000));
489    }
490
491    #[test]
492    fn test_concerns_sort_and_format() {
493        let mut concerns = vec![
494            Concern {
495                file: "low.rs".to_string(),
496                line: Some(1),
497                severity: "low".to_string(),
498                text: "low issue".to_string(),
499            },
500            Concern {
501                file: "high.rs".to_string(),
502                line: None,
503                severity: "high".to_string(),
504                text: "high issue".to_string(),
505            },
506            Concern {
507                file: "med.rs".to_string(),
508                line: Some(2),
509                severity: "medium".to_string(),
510                text: "medium issue".to_string(),
511            },
512        ];
513
514        sort_concerns(&mut concerns);
515
516        assert_eq!(concerns[0].severity, "high");
517        assert_eq!(concerns[1].severity, "medium");
518        assert_eq!(concerns[2].severity, "low");
519
520        assert_eq!(format_concern(&concerns[0]), "[high] high.rs high issue");
521        assert_eq!(
522            format_concern(&concerns[1]),
523            "[medium] med.rs:2 medium issue"
524        );
525        assert_eq!(format_concern(&concerns[2]), "[low] low.rs:1 low issue");
526    }
527
528    #[test]
529    fn test_save_review_record() {
530        let dir = tempfile::tempdir().unwrap();
531        let concerns = vec![Concern {
532            file: "foo.rs".to_string(),
533            line: Some(5),
534            severity: "high".to_string(),
535            text: "problem".to_string(),
536        }];
537        save_review(
538            dir.path(),
539            "T1",
540            "gemini/gemini-3.8-flash",
541            Some(0.0012),
542            concerns,
543            None,
544        );
545        let path = dir.path().join(".wt/T1.model-review.json");
546        assert!(path.is_file());
547        let content = std::fs::read_to_string(&path).unwrap();
548        let val: serde_json::Value = serde_json::from_str(&content).unwrap();
549        assert_eq!(val["model"], "gemini/gemini-3.8-flash");
550        assert_eq!(val["cost_usd"], 0.0012);
551        assert_eq!(val["concerns"].as_array().unwrap().len(), 1);
552        assert!(val["error"].is_null());
553        assert!(val["ts"].as_u64().unwrap() > 0);
554    }
555}