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