blyte 0.66.1

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
use std::path::Path;
use std::process::Command;

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct Concern {
    pub file: String,
    pub line: Option<u64>,
    pub severity: String,
    pub text: String,
}

#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct FallbackVerdict {
    pub file: String,
    pub line: usize,
    pub verdict: String,
    pub reason: String,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParsedReview {
    pub concerns: Vec<Concern>,
    pub fallbacks: Vec<FallbackVerdict>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct SavedModelReview {
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub cost_usd: Option<f64>,
    #[serde(default)]
    pub concerns: Vec<Concern>,
    #[serde(default)]
    pub fallbacks: Vec<FallbackVerdict>,
    #[serde(default)]
    pub ts: u64,
    #[serde(default)]
    pub error: Option<String>,
}

#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct ModelReviewResult {
    pub status: String,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<String>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cost_usd: Option<f64>,
    #[serde(default)]
    pub concerns: Vec<Concern>,
    #[serde(default)]
    pub fallbacks: Vec<FallbackVerdict>,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub error: Option<String>,
}

impl ModelReviewResult {
    pub fn ok(model: String, cost_usd: Option<f64>, concerns: Vec<Concern>) -> Self {
        Self {
            status: "ok".to_string(),
            model: Some(model),
            cost_usd,
            concerns,
            fallbacks: Vec::new(),
            error: None,
        }
    }

    pub fn with_fallbacks(mut self, fallbacks: Vec<FallbackVerdict>) -> Self {
        self.fallbacks = fallbacks;
        self
    }

    pub fn failed(model: Option<String>, cost_usd: Option<f64>, error: impl Into<String>) -> Self {
        Self {
            status: "failed".to_string(),
            model,
            cost_usd,
            concerns: Vec::new(),
            fallbacks: Vec::new(),
            error: Some(error.into()),
        }
    }

    pub fn has_findings(&self) -> bool {
        !self.is_failed() && !self.concerns.is_empty()
    }

    pub fn is_failed(&self) -> bool {
        self.status != "ok"
            || self.error.is_some()
            || self.model.as_deref().is_none_or(|m| m.trim().is_empty())
    }

    pub fn validate(&self) -> Result<(), String> {
        if self.status == "ok" {
            if self.error.is_some() {
                return Err("status \"ok\" cannot carry an error".to_string());
            }
            if self.model.as_deref().is_none_or(|m| m.trim().is_empty()) {
                return Err("status \"ok\" is missing model".to_string());
            }
            Ok(())
        } else if self.error.as_deref().is_none_or(|e| e.trim().is_empty()) {
            Err(format!("status {:?} is missing error", self.status))
        } else {
            Ok(())
        }
    }

    pub fn failure_detail(&self) -> String {
        if let Some(err) = self.error.as_deref().filter(|s| !s.trim().is_empty()) {
            return err.to_string();
        }
        let raw = serde_json::to_string(self)
            .map(|s| first_200(&s))
            .unwrap_or_else(|e| format!("status={:?} ({e})", self.status));
        if self.status == "ok" && self.model.as_deref().is_none_or(|m| m.trim().is_empty()) {
            format!("malformed model review result (missing model): {raw}")
        } else {
            format!("malformed model review result (missing error): {raw}")
        }
    }

    pub fn waits_in_queue(&self) -> bool {
        self.has_findings() || self.is_failed()
    }

    pub fn flag(&self) -> Option<String> {
        if self.is_failed() {
            let reason = self.failure_detail();
            return Some(sanitize_flag(format!("model review failed: {reason}")));
        }
        if self.has_findings() {
            let first = format_concern(&self.concerns[0]);
            let msg = if self.concerns.len() == 1 {
                format!("model review (1 concern): {first}")
            } else {
                format!(
                    "model review ({} concerns): {first} (and {} more)",
                    self.concerns.len(),
                    self.concerns.len() - 1
                )
            };
            return Some(sanitize_flag(msg));
        }
        None
    }
}

fn sanitize_flag(flag: String) -> String {
    let single_line = flag.lines().next().unwrap_or("").to_string();
    if single_line.chars().count() > 200 {
        single_line.chars().take(200).collect()
    } else {
        single_line
    }
}

pub const SYSTEM_PROMPT: &str = "\
You are a senior software engineer performing a first review of a code diff against a task specification.
Review the diff against the task. Raise only concrete problems a reviewer must look at:
- the task's requirements not met
- a behaviour or edge case the task names but the code or tests miss
- changes outside what the task asks for
- tests that could pass with a wrong implementation
- risky commands or deleted tests

Do not make style comments.
Raise at most 10 concerns.
Answer with only a JSON object with the following schema:
{\"concerns\": [{\"file\": \"<path>\", \"line\": <line number or null>, \"severity\": \"high\" | \"medium\" | \"low\", \"text\": \"<description>\"}], \"fallbacks\": [{\"file\": \"<path>\", \"line\": <line number>, \"verdict\": \"fallback\" | \"not_fallback\", \"reason\": \"<one sentence>\"}]}
Return {\"concerns\": [], \"fallbacks\": []} when there is nothing to raise and no fallback candidates were listed. Do not include any text or markdown outside the JSON object.";

/// System prompt + user message. The user message holds, in this order: the task text
/// (under "## Task"), `git diff --stat`, the full diff (under "## Diff"), and when
/// fallback candidates are present, a section listing each candidate and the fallback definition.
pub fn build_request(
    task: &str,
    stat: &str,
    diff: &str,
    candidates: &[crate::fallback_check::Finding],
) -> blyte_provider::Request {
    let diff_text = if diff.chars().count() > 200_000 {
        let cutoff = diff
            .char_indices()
            .nth(200_000)
            .map(|(i, _)| i)
            .unwrap_or(diff.len());
        let mut s = diff[..cutoff].to_string();
        if !s.ends_with('\n') {
            s.push('\n');
        }
        s.push_str("[diff truncated]\n");
        s
    } else {
        diff.to_string()
    };

    let mut user_msg = String::new();
    user_msg.push_str("## Task\n");
    user_msg.push_str(task);
    if !user_msg.ends_with('\n') {
        user_msg.push('\n');
    }
    user_msg.push('\n');

    let stat_trimmed = stat.trim();
    if !stat_trimmed.is_empty() {
        user_msg.push_str(stat_trimmed);
        user_msg.push_str("\n\n");
    }

    user_msg.push_str("## Diff\n");
    user_msg.push_str(&diff_text);
    if !user_msg.ends_with('\n') {
        user_msg.push('\n');
    }

    if !candidates.is_empty() {
        user_msg.push_str("\n## Fallback candidates\n");
        user_msg.push_str(
            "Judge each candidate below as \"fallback\" or \"not_fallback\" and return one entry in \"fallbacks\" for every candidate listed.\n\
A fallback is code that substitutes a default, a guess, an empty result or a silent skip when something is missing, unknown or unreadable, instead of failing with an error that names it.\n\
Decide each one with this test, and apply it the same way to every candidate: when the operation on the line fails, or the value it reads is absent, does the program carry on with a substitute value? If it does, the verdict is \"fallback\". That includes a wrapper that turns an error into true, false or an empty list, whoever calls it, and a filesystem or command call (such as resolving a path) whose failure is replaced by the unresolved input.\n\
The verdict is \"not_fallback\" only when one of these holds, and the reason must say which: (1) the value is optional by design and the line only chooses how its absence is shown or defaulted, with no failed operation behind it; (2) the substitute is a default that the task or a comment in the code states is intended; (3) the operation cannot fail or be absent at this point because the code has already checked it.\n\
Whether the line existed before this change, or was only moved, does not change the verdict.\n\n",
        );
        for c in candidates {
            user_msg.push_str(&format!(
                "- {}:{} [{}] {}\n",
                c.file, c.line, c.pattern, c.text
            ));
        }
    }

    blyte_provider::Request {
        system: SYSTEM_PROMPT.to_string(),
        messages: vec![blyte_provider::Message::User(user_msg)],
        tools: Vec::new(),
        max_output_tokens: Some(32_000),
        timeout: None,
    }
}

/// Parse the model's JSON object reply `{"concerns": [...], "fallbacks": [...]}`.
/// A bare array is a parse error. An unknown fallback verdict is a parse error.
/// When `expect_fallbacks` is true, a missing `"fallbacks"` key is a parse error.
/// Empty or whitespace-only text → Err("empty response").
pub fn parse(text: &str, expect_fallbacks: bool) -> Result<ParsedReview, String> {
    if text.trim().is_empty() {
        return Err("empty response".to_string());
    }
    let candidate = extract_json_candidate(text);
    let value: serde_json::Value = match candidate {
        Some(s) => match serde_json::from_str(s) {
            Ok(v) => v,
            Err(_) => {
                if let (Some(start), Some(end)) = (text.find('{'), text.rfind('}')) {
                    if end >= start {
                        match serde_json::from_str(&text[start..=end]) {
                            Ok(v) => v,
                            Err(_) => return Err(first_200(text)),
                        }
                    } else {
                        return Err(first_200(text));
                    }
                } else {
                    return Err(first_200(text));
                }
            }
        },
        None => return Err(first_200(text)),
    };

    let mut map = match value {
        serde_json::Value::Object(map) => map,
        serde_json::Value::Array(_) => {
            return Err(format!(
                "expected JSON object, got bare array: {}",
                first_200(text)
            ));
        }
        _ => return Err(first_200(text)),
    };

    let concerns_arr = match map.remove("concerns") {
        Some(serde_json::Value::Array(arr)) => arr,
        _ => {
            return Err(format!(
                "missing or invalid \"concerns\" array: {}",
                first_200(text)
            ));
        }
    };

    let fallbacks_arr = match map.remove("fallbacks") {
        Some(serde_json::Value::Array(arr)) => arr,
        Some(_) => {
            return Err(format!(
                "invalid \"fallbacks\" field (expected array): {}",
                first_200(text)
            ));
        }
        None => {
            if expect_fallbacks {
                return Err(format!(
                    "missing \"fallbacks\" key in model review response: {}",
                    first_200(text)
                ));
            }
            Vec::new()
        }
    };

    let mut concerns = Vec::new();
    for item in concerns_arr {
        let Some(obj) = item.as_object() else {
            continue;
        };
        let text_val = match obj.get("text").and_then(|t| t.as_str()) {
            Some(t) => t.to_string(),
            None => continue,
        };
        let file = obj
            .get("file")
            .and_then(|f| f.as_str())
            .unwrap_or("")
            .to_string();
        let line = obj.get("line").and_then(|l| {
            l.as_u64()
                .or_else(|| l.as_str().and_then(|s| s.parse::<u64>().ok()))
        });
        let severity = match obj.get("severity").and_then(|s| s.as_str()) {
            Some(s) if s.eq_ignore_ascii_case("high") => "high".to_string(),
            Some(s) if s.eq_ignore_ascii_case("medium") => "medium".to_string(),
            Some(s) if s.eq_ignore_ascii_case("low") => "low".to_string(),
            _ => "low".to_string(),
        };
        concerns.push(Concern {
            file,
            line,
            severity,
            text: text_val,
        });
    }

    let mut fallbacks = Vec::with_capacity(fallbacks_arr.len());
    for item in fallbacks_arr {
        let Some(obj) = item.as_object() else {
            return Err(format!(
                "invalid fallback entry (expected object): {}",
                first_200(text)
            ));
        };
        let Some(file) = obj.get("file").and_then(|v| v.as_str()) else {
            return Err(format!(
                "fallback entry missing \"file\": {}",
                first_200(text)
            ));
        };
        let Some(line) = obj
            .get("line")
            .and_then(|v| {
                v.as_u64()
                    .or_else(|| v.as_str().and_then(|s| s.parse::<u64>().ok()))
            })
            .and_then(|n| usize::try_from(n).ok())
        else {
            return Err(format!(
                "fallback entry missing valid \"line\": {}",
                first_200(text)
            ));
        };
        let Some(verdict) = obj.get("verdict").and_then(|v| v.as_str()) else {
            return Err(format!(
                "fallback entry missing \"verdict\": {}",
                first_200(text)
            ));
        };
        if verdict != "fallback" && verdict != "not_fallback" {
            return Err(format!(
                "unknown fallback verdict {verdict:?} (expected \"fallback\" or \"not_fallback\"): {}",
                first_200(text)
            ));
        }
        let Some(reason) = obj.get("reason").and_then(|v| v.as_str()) else {
            return Err(format!(
                "fallback entry missing \"reason\": {}",
                first_200(text)
            ));
        };
        fallbacks.push(FallbackVerdict {
            file: file.to_string(),
            line,
            verdict: verdict.to_string(),
            reason: reason.to_string(),
        });
    }

    Ok(ParsedReview {
        concerns,
        fallbacks,
    })
}

fn first_200(text: &str) -> String {
    text.chars().take(200).collect()
}

fn extract_json_candidate(text: &str) -> Option<&str> {
    if let Some(start) = text.find("```json") {
        let content_start = start + 7;
        if let Some(end) = text[content_start..].find("```") {
            return Some(text[content_start..content_start + end].trim());
        }
    }
    if let Some(start) = text.find("```") {
        let after_fence = &text[start + 3..];
        let content_start = if let Some(nl) = after_fence.find('\n') {
            nl + 1
        } else {
            0
        };
        if let Some(end) = after_fence[content_start..].find("```") {
            return Some(after_fence[content_start..content_start + end].trim());
        }
    }
    let trimmed = text.trim();
    if trimmed.starts_with('[') {
        return Some(trimmed);
    }
    if let Some(start) = text.find('{') {
        if let Some(end) = text.rfind('}') {
            if end >= start {
                return Some(&text[start..=end]);
            }
        }
    }
    None
}

fn severity_rank(sev: &str) -> u8 {
    match sev.to_ascii_lowercase().as_str() {
        "high" => 0,
        "medium" => 1,
        "low" => 2,
        _ => 3,
    }
}

pub fn parse_error_message(err: &str, finish: Option<&str>) -> String {
    match finish {
        Some(reason) if !reason.is_empty() => format!("{err} (finish reason: {reason})"),
        _ => err.to_string(),
    }
}

pub fn sort_concerns(concerns: &mut [Concern]) {
    concerns.sort_by_key(|c| severity_rank(&c.severity));
}

pub fn format_concern(c: &Concern) -> String {
    if let Some(line) = c.line {
        format!("[{}] {}:{} {}", c.severity, c.file, line, c.text)
    } else {
        format!("[{}] {} {}", c.severity, c.file, c.text)
    }
}

pub fn run(root: &Path, id: &str, base: &str, wt: &Path) -> ModelReviewResult {
    let start_path = root.join(".wt").join(format!("{id}.start.json"));
    let task_text = match read_task_text(root, &start_path) {
        Some(t) => t,
        None => {
            return finish_failed(root, id, None, None, "task file not found");
        }
    };

    if let Some(env_path) = crate::env_file::default_path() {
        let _ = crate::env_file::load(&env_path);
    }

    let repo_config = match crate::config::load_with_fallback(root) {
        Ok(Some((cfg, _))) => Some(cfg),
        Ok(None) => None,
        Err(e) => {
            return finish_failed(root, id, None, None, e);
        }
    };
    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
    let model = dispatch_cfg.model.as_deref();

    // One call over a whole diff at high effort can take minutes; allow 10 unless the user set a limit.
    if std::env::var_os("BLYTE_MODEL_TIMEOUT_SECS").is_none() {
        std::env::set_var("BLYTE_MODEL_TIMEOUT_SECS", "600");
    }
    let provider = match blyte_provider::resolve_provider(model) {
        Ok(p) => p,
        Err(blyte_provider::ProviderError::MissingKey(key)) => {
            return finish_failed(root, id, None, None, format!("no API key (set {key})"));
        }
        Err(e) => {
            return finish_failed(root, id, None, None, e.to_string());
        }
    };

    run_with_task_and_provider(root, id, base, wt, &task_text, provider.as_ref())
}

pub fn run_with_provider(
    root: &Path,
    id: &str,
    base: &str,
    wt: &Path,
    provider: &dyn blyte_provider::Provider,
) -> ModelReviewResult {
    let start_path = root.join(".wt").join(format!("{id}.start.json"));
    let task_text = match read_task_text(root, &start_path) {
        Some(t) => t,
        None => {
            return finish_failed(
                root,
                id,
                Some(provider.model_id()),
                None,
                "task file not found",
            );
        }
    };
    run_with_task_and_provider(root, id, base, wt, &task_text, provider)
}

fn is_max_tokens(finish_reason: Option<&str>) -> bool {
    finish_reason.is_some_and(|r| r.eq_ignore_ascii_case("MAX_TOKENS"))
}

fn sum_costs(a: Option<f64>, b: Option<f64>) -> Option<f64> {
    match (a, b) {
        (Some(x), Some(y)) => Some(x + y),
        (Some(x), None) => Some(x),
        (None, Some(y)) => Some(y),
        (None, None) => None,
    }
}

fn read_start_session(root: &Path, id: &str) -> Option<String> {
    let start_path = root.join(".wt").join(format!("{id}.start.json"));
    let content = std::fs::read_to_string(&start_path).ok()?;
    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
    val.get("session")
        .and_then(|v| v.as_str())
        .map(str::to_string)
}

fn resolve_review_session(root: &Path, id: &str) -> Option<String> {
    crate::usage_log::session_from(
        std::env::var("BLYTE_SESSION").ok(),
        read_start_session(root, id),
    )
}

fn record_model_review_usage(
    root: &Path,
    id: &str,
    session: Option<&str>,
    model_id: &str,
    usage: &blyte_provider::Usage,
    cost_usd: Option<f64>,
) {
    let Some(path) = crate::usage_log::default_path() else {
        return;
    };
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let entry = crate::usage_log::Entry {
        ts,
        repo: crate::usage_log::repo_of(root),
        session: session.map(str::to_string),
        dispatch: Some(id.to_string()),
        research: false,
        model: model_id.to_string(),
        outcome: "model_review".to_string(),
        turns: 1,
        input: usage.input,
        cached: usage.cached,
        output: usage.output,
        thinking: usage.thinking,
        cost_usd,
    };
    if let Err(err) = crate::usage_log::append(&path, &entry) {
        eprintln!("warning: usage log: {err}");
    }
}

fn run_with_task_and_provider(
    root: &Path,
    id: &str,
    base: &str,
    wt: &Path,
    task_text: &str,
    provider: &dyn blyte_provider::Provider,
) -> ModelReviewResult {
    let model_id = provider.model_id();
    let review_session = resolve_review_session(root, id);

    let stat_out = match Command::new("git")
        .args(["diff", "--stat", &format!("{base}..HEAD")])
        .current_dir(wt)
        .output()
    {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
        Ok(o) => {
            let err = format!(
                "git diff --stat failed: {}",
                String::from_utf8_lossy(&o.stderr).trim()
            );
            return finish_failed(root, id, Some(model_id), None, err);
        }
        Err(e) => {
            let err = format!("git diff --stat failed: {e}");
            return finish_failed(root, id, Some(model_id), None, err);
        }
    };

    let diff_out = match Command::new("git")
        .args(["diff", &format!("{base}..HEAD")])
        .current_dir(wt)
        .output()
    {
        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).to_string(),
        Ok(o) => {
            let err = format!(
                "git diff failed: {}",
                String::from_utf8_lossy(&o.stderr).trim()
            );
            return finish_failed(root, id, Some(model_id), None, err);
        }
        Err(e) => {
            let err = format!("git diff failed: {e}");
            return finish_failed(root, id, Some(model_id), None, err);
        }
    };

    let candidates = crate::fallback_check::added_fallbacks(&diff_out);
    let expect_fallbacks = !candidates.is_empty();
    let req = build_request(task_text, &stat_out, &diff_out, &candidates);
    let resp = match provider.complete(&req) {
        Ok(r) => r,
        Err(e) => {
            return finish_failed(root, id, Some(model_id), None, e.to_string());
        }
    };

    let cost1 = blyte_provider::pricing(&model_id).map(|p| p.cost(&resp.usage));
    record_model_review_usage(
        root,
        id,
        review_session.as_deref(),
        &model_id,
        &resp.usage,
        cost1,
    );

    let (parsed, total_cost) = match parse(&resp.text, expect_fallbacks) {
        Ok(p) => (p, cost1),
        Err(_) if is_max_tokens(resp.finish_reason.as_deref()) => {
            let mut retry_req = req.clone();
            retry_req.max_output_tokens = retry_req.max_output_tokens.map(|n| n.saturating_mul(2));
            let resp2 = match provider.complete(&retry_req) {
                Ok(r) => r,
                Err(e2) => {
                    let err_msg = format!("{e2} (after one retry)");
                    return finish_failed(root, id, Some(model_id), cost1, err_msg);
                }
            };
            let cost2 = blyte_provider::pricing(&model_id).map(|p| p.cost(&resp2.usage));
            record_model_review_usage(
                root,
                id,
                review_session.as_deref(),
                &model_id,
                &resp2.usage,
                cost2,
            );
            let total_cost = sum_costs(cost1, cost2);
            match parse(&resp2.text, expect_fallbacks) {
                Ok(p) => (p, total_cost),
                Err(e2) => {
                    let err_msg = format!(
                        "{} (after one retry)",
                        parse_error_message(&e2, resp2.finish_reason.as_deref())
                    );
                    return finish_failed(root, id, Some(model_id), total_cost, err_msg);
                }
            }
        }
        Err(e) => {
            let err_msg = parse_error_message(&e, resp.finish_reason.as_deref());
            return finish_failed(root, id, Some(model_id), cost1, err_msg);
        }
    };

    let mut concerns = parsed.concerns;
    sort_concerns(&mut concerns);
    let fallbacks = parsed.fallbacks;

    if let Err(save_err) = save_review(
        root,
        id,
        Some(&model_id),
        total_cost,
        concerns.clone(),
        fallbacks.clone(),
        None,
    ) {
        return ModelReviewResult::failed(Some(model_id), total_cost, save_err);
    }
    ModelReviewResult::ok(model_id, total_cost, concerns).with_fallbacks(fallbacks)
}

pub fn format_result(result: &ModelReviewResult) -> String {
    let mut out = String::new();
    if result.is_failed() {
        let err = result.failure_detail();
        out.push_str("== model review\n");
        if err == "task file not found" || err.starts_with("no API key (set ") {
            out.push_str(&format!("skipped: {err}\n"));
        } else {
            out.push_str(&format!("error: {err}\n"));
        }
        return out;
    }

    let Some(model_id) = result.model.as_deref().filter(|m| !m.trim().is_empty()) else {
        let err = result.failure_detail();
        out.push_str("== model review\n");
        out.push_str(&format!("error: {err}\n"));
        return out;
    };
    let cost_str = match result.cost_usd {
        Some(c) => format!("${c:.4}"),
        None => "price unknown".to_string(),
    };
    out.push_str(&format!(
        "== model review (trial: {model_id}, {cost_str})\n"
    ));
    if result.concerns.is_empty() {
        out.push_str("nothing raised\n");
    } else {
        for c in &result.concerns {
            out.push_str(&format!("{}\n", format_concern(c)));
        }
    }
    if !result.fallbacks.is_empty() {
        let confirmed: Vec<&FallbackVerdict> = result
            .fallbacks
            .iter()
            .filter(|f| f.verdict == "fallback")
            .collect();
        let dismissed = result
            .fallbacks
            .iter()
            .filter(|f| f.verdict == "not_fallback")
            .count();
        if !confirmed.is_empty() {
            out.push_str(&format!("confirmed fallbacks ({}):\n", confirmed.len()));
            for f in confirmed {
                out.push_str(&format!("  {}:{} {}\n", f.file, f.line, f.reason));
            }
        }
        out.push_str(&format!("fallback candidates dismissed: {dismissed}\n"));
    }
    out
}

pub fn print_result(result: &ModelReviewResult) {
    print!("{}", format_result(result));
}

pub fn load_saved_review(path: &Path) -> Result<SavedModelReview, String> {
    let raw = std::fs::read_to_string(path)
        .map_err(|e| format!("cannot read {}: {e}", path.display()))?;
    serde_json::from_str(&raw).map_err(|e| format!("cannot parse {}: {e}", path.display()))
}

fn read_task_text(root: &Path, start_path: &Path) -> Option<String> {
    let content = std::fs::read_to_string(start_path).ok()?;
    let val: serde_json::Value = serde_json::from_str(&content).ok()?;
    let task_file_str = val.get("task_file")?.as_str()?;
    let task_path = Path::new(task_file_str);
    if task_path.is_absolute() {
        std::fs::read_to_string(task_path).ok()
    } else {
        std::fs::read_to_string(root.join(task_path))
            .or_else(|_| std::fs::read_to_string(task_path))
            .ok()
    }
}

fn finish_failed(
    root: &Path,
    id: &str,
    model: Option<String>,
    cost_usd: Option<f64>,
    err: impl Into<String>,
) -> ModelReviewResult {
    let orig_err = err.into();
    let final_err = match save_review(
        root,
        id,
        model.as_deref(),
        cost_usd,
        Vec::new(),
        Vec::new(),
        Some(orig_err.clone()),
    ) {
        Ok(()) => orig_err,
        Err(save_err) => format!("{orig_err}; {save_err}"),
    };
    ModelReviewResult::failed(model, cost_usd, final_err)
}

fn save_review(
    root: &Path,
    id: &str,
    model: Option<&str>,
    cost_usd: Option<f64>,
    concerns: Vec<Concern>,
    fallbacks: Vec<FallbackVerdict>,
    error: Option<String>,
) -> Result<(), String> {
    let wt_dir = root.join(".wt");
    let review_path = wt_dir.join(format!("{id}.model-review.json"));
    std::fs::create_dir_all(&wt_dir)
        .map_err(|e| format!("cannot save {}: {e}", review_path.display()))?;
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let record = SavedModelReview {
        model: model.map(str::to_string),
        cost_usd,
        concerns,
        fallbacks,
        ts,
        error,
    };
    let json_str = serde_json::to_string_pretty(&record)
        .map_err(|e| format!("cannot serialize {}: {e}", review_path.display()))?;
    std::fs::write(&review_path, json_str + "\n")
        .map_err(|e| format!("cannot write {}: {e}", review_path.display()))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::fallback_check::Finding;

    #[test]
    fn test_parse_empty_object() {
        let res =
            parse(r#"{"concerns": [], "fallbacks": []}"#, false).expect("parse should succeed");
        assert!(res.concerns.is_empty());
        assert!(res.fallbacks.is_empty());
    }

    #[test]
    fn test_parse_bare_array_is_error() {
        assert!(parse("[]", false).is_err());
        assert!(parse(
            r#"[{"file":"src/a.rs","line":1,"severity":"high","text":"bad"}]"#,
            false
        )
        .is_err());
    }

    #[test]
    fn test_parse_missing_fallbacks_when_expected_is_error() {
        let err = parse(r#"{"concerns": []}"#, true).expect_err("expected error");
        assert!(err.contains("fallbacks"), "{err}");

        let ok = parse(r#"{"concerns": []}"#, false).expect("allowed when no candidates sent");
        assert!(ok.concerns.is_empty());
        assert!(ok.fallbacks.is_empty());
    }

    #[test]
    fn test_parse_unknown_verdict_is_error() {
        let input = r#"{
            "concerns": [],
            "fallbacks": [
                {"file": "src/a.rs", "line": 4, "verdict": "maybe", "reason": "unclear"}
            ]
        }"#;
        let err = parse(input, true).expect_err("expected error for unknown verdict");
        assert!(err.contains("maybe"), "{err}");
    }

    #[test]
    fn test_parse_both_arrays() {
        let input = r#"{
            "concerns": [
                {"file": "src/a.rs", "line": 10, "severity": "high", "text": "missing check"}
            ],
            "fallbacks": [
                {"file": "src/a.rs", "line": 4, "verdict": "fallback", "reason": "hides missing env var"},
                {"file": "src/b.rs", "line": 9, "verdict": "not_fallback", "reason": "documented default port"}
            ]
        }"#;
        let parsed = parse(input, true).expect("parse should succeed");
        assert_eq!(parsed.concerns.len(), 1);
        assert_eq!(parsed.fallbacks.len(), 2);
        assert_eq!(parsed.fallbacks[0].verdict, "fallback");
        assert_eq!(parsed.fallbacks[0].line, 4);
        assert_eq!(parsed.fallbacks[1].verdict, "not_fallback");
        assert_eq!(parsed.fallbacks[1].reason, "documented default port");
    }

    #[test]
    fn test_parse_empty_or_whitespace() {
        assert_eq!(parse("", false), Err("empty response".to_string()));
        assert_eq!(parse("  \n", false), Err("empty response".to_string()));
    }

    #[test]
    fn test_parse_error_message() {
        assert_eq!(
            parse_error_message("empty response", Some("MAX_TOKENS")),
            "empty response (finish reason: MAX_TOKENS)"
        );
        assert_eq!(
            parse_error_message("empty response", None),
            "empty response"
        );
    }

    #[test]
    fn test_parse_fenced_with_prose() {
        let input = r#"
Here is the review of the diff against the task:
```json
{
  "concerns": [
    {
      "file": "crates/blyte-cli/src/foo.rs",
      "line": 42,
      "severity": "high",
      "text": "Task requires error handling here"
    },
    {
      "file": "crates/blyte-cli/src/bar.rs",
      "line": 100,
      "severity": "medium",
      "text": "Missing edge case check"
    }
  ],
  "fallbacks": []
}
```
Overall looks okay otherwise.
"#;
        let parsed = parse(input, false).expect("parse should succeed");
        let concerns = parsed.concerns;
        assert_eq!(concerns.len(), 2);
        assert_eq!(concerns[0].file, "crates/blyte-cli/src/foo.rs");
        assert_eq!(concerns[0].line, Some(42));
        assert_eq!(concerns[0].severity, "high");
        assert_eq!(concerns[0].text, "Task requires error handling here");
        assert_eq!(concerns[1].file, "crates/blyte-cli/src/bar.rs");
        assert_eq!(concerns[1].line, Some(100));
        assert_eq!(concerns[1].severity, "medium");
        assert_eq!(concerns[1].text, "Missing edge case check");
    }

    #[test]
    fn test_parse_normalization_and_filtering() {
        let input = r#"{
            "concerns": [
                {
                    "file": "crates/a.rs",
                    "line": null,
                    "severity": "critical",
                    "text": "A severe issue"
                },
                {
                    "file": "crates/b.rs",
                    "line": 10,
                    "severity": "high"
                }
            ],
            "fallbacks": []
        }"#;
        let parsed = parse(input, false).expect("parse should succeed");
        let concerns = parsed.concerns;
        assert_eq!(concerns.len(), 1);
        assert_eq!(concerns[0].file, "crates/a.rs");
        assert_eq!(concerns[0].line, None);
        assert_eq!(concerns[0].severity, "low");
        assert_eq!(concerns[0].text, "A severe issue");
    }

    #[test]
    fn test_parse_not_json() {
        let err = parse("not json", false).expect_err("should return Err");
        assert!(err.contains("not json"));
    }

    #[test]
    fn test_parse_long_unparseable_truncated_to_200() {
        let input = "not json ".repeat(30);
        assert!(input.chars().count() > 200);
        let err = parse(&input, false).expect_err("should return Err");
        assert_eq!(err.chars().count(), 200);
        assert!(input.starts_with(&err));
    }

    #[test]
    fn test_build_request_diff_truncation() {
        let task = "Implement feature X with full test coverage.";
        let stat = " src/main.rs | 100 ++\n 1 file changed";
        let diff = "a".repeat(300_000);

        let req = build_request(task, stat, &diff, &[]);
        assert_eq!(req.max_output_tokens, Some(32_000));
        assert!(req.tools.is_empty(), "tools should be empty");
        assert_eq!(req.messages.len(), 1);

        let blyte_provider::Message::User(ref msg) = req.messages[0] else {
            panic!("expected user message");
        };

        assert!(
            msg.contains("[diff truncated]"),
            "must contain [diff truncated]"
        );
        assert!(msg.len() < 210_000, "user message length was {}", msg.len());

        let task_pos = msg.find(task).expect("task text missing");
        let diff_pos = msg.find("## Diff").expect("diff header missing");
        assert!(task_pos < diff_pos, "task text must appear before diff");
        assert!(!msg.contains("## Fallback candidates"), "{msg}");
    }

    #[test]
    fn test_build_request_lists_candidates_only_when_present() {
        let req_empty = build_request("task", "stat", "diff", &[]);
        let blyte_provider::Message::User(ref empty_msg) = req_empty.messages[0] else {
            panic!("expected user message");
        };
        assert!(!empty_msg.contains("## Fallback candidates"));

        let candidates = vec![
            Finding {
                file: "src/cfg.rs".to_string(),
                line: 14,
                pattern: "unwrap_or",
                text: "let port = env_port.unwrap_or(8080);".to_string(),
            },
            Finding {
                file: "src/io.rs".to_string(),
                line: 42,
                pattern: "unwrap_or_default",
                text: "let body = read().unwrap_or_default();".to_string(),
            },
        ];
        let req = build_request("task", "stat", "diff", &candidates);
        let blyte_provider::Message::User(ref msg) = req.messages[0] else {
            panic!("expected user message");
        };
        assert!(msg.contains("## Fallback candidates"), "{msg}");
        assert!(
            msg.contains("src/cfg.rs:14 [unwrap_or] let port = env_port.unwrap_or(8080);"),
            "{msg}"
        );
        assert!(
            msg.contains("src/io.rs:42 [unwrap_or_default] let body = read().unwrap_or_default();"),
            "{msg}"
        );
        assert!(
            msg.contains("does the program carry on with a substitute value?")
                && msg.contains("Whether the line existed before this change"),
            "{msg}"
        );
    }

    #[test]
    fn test_build_request_max_output_tokens() {
        let req = build_request("task", "stat", "diff", &[]);
        assert_eq!(req.max_output_tokens, Some(32_000));
    }

    #[test]
    fn test_concerns_sort_and_format() {
        let mut concerns = vec![
            Concern {
                file: "low.rs".to_string(),
                line: Some(1),
                severity: "low".to_string(),
                text: "low issue".to_string(),
            },
            Concern {
                file: "high.rs".to_string(),
                line: None,
                severity: "high".to_string(),
                text: "high issue".to_string(),
            },
            Concern {
                file: "med.rs".to_string(),
                line: Some(2),
                severity: "medium".to_string(),
                text: "medium issue".to_string(),
            },
        ];

        sort_concerns(&mut concerns);

        assert_eq!(concerns[0].severity, "high");
        assert_eq!(concerns[1].severity, "medium");
        assert_eq!(concerns[2].severity, "low");

        assert_eq!(format_concern(&concerns[0]), "[high] high.rs high issue");
        assert_eq!(
            format_concern(&concerns[1]),
            "[medium] med.rs:2 medium issue"
        );
        assert_eq!(format_concern(&concerns[2]), "[low] low.rs:1 low issue");
    }

    #[test]
    fn test_save_review_record_and_load_old_format() {
        let dir = tempfile::tempdir().unwrap();
        let concerns = vec![Concern {
            file: "foo.rs".to_string(),
            line: Some(5),
            severity: "high".to_string(),
            text: "problem".to_string(),
        }];
        let fallbacks = vec![FallbackVerdict {
            file: "foo.rs".to_string(),
            line: 7,
            verdict: "not_fallback".to_string(),
            reason: "documented default".to_string(),
        }];
        save_review(
            dir.path(),
            "T1",
            Some("gemini/gemini-3.8-flash"),
            Some(0.0012),
            concerns,
            fallbacks,
            None,
        )
        .unwrap();
        let path = dir.path().join(".wt/T1.model-review.json");
        assert!(path.is_file());
        let content = std::fs::read_to_string(&path).unwrap();
        let val: serde_json::Value = serde_json::from_str(&content).unwrap();
        assert_eq!(val["model"], "gemini/gemini-3.8-flash");
        assert_eq!(val["cost_usd"], 0.0012);
        assert_eq!(val["concerns"].as_array().unwrap().len(), 1);
        assert_eq!(val["fallbacks"].as_array().unwrap().len(), 1);
        assert_eq!(val["fallbacks"][0]["verdict"], "not_fallback");
        assert!(val["error"].is_null());
        assert!(val["ts"].as_u64().unwrap() > 0);

        let loaded = load_saved_review(&path).unwrap();
        assert_eq!(loaded.fallbacks.len(), 1);

        let old_path = dir.path().join(".wt/OLD.model-review.json");
        std::fs::write(
            &old_path,
            r#"{
  "model": "gemini/gemini-3.8-flash",
  "cost_usd": 0.001,
  "concerns": [],
  "ts": 1700000000,
  "error": null
}"#,
        )
        .unwrap();
        let old_loaded = load_saved_review(&old_path).unwrap();
        assert_eq!(old_loaded.model.as_deref(), Some("gemini/gemini-3.8-flash"));
        assert!(old_loaded.fallbacks.is_empty());
    }

    #[test]
    fn test_malformed_result_and_responses_carry_content_without_placeholders() {
        let missing_error = ModelReviewResult {
            status: "error".to_string(),
            model: Some("test-model".to_string()),
            cost_usd: None,
            concerns: Vec::new(),
            fallbacks: Vec::new(),
            error: None,
        };
        assert!(missing_error.is_failed());
        let flag = missing_error.flag().expect("expected flag");
        assert!(!flag.contains("unknown error"), "flag={flag}");
        assert!(!flag.contains('?'), "flag={flag}");
        assert!(flag.contains("test-model"), "flag={flag}");

        let rendered = format_result(&missing_error);
        assert!(!rendered.contains("unknown error"), "rendered={rendered}");
        assert!(!rendered.contains('?'), "rendered={rendered}");
        assert!(rendered.contains("test-model"), "rendered={rendered}");

        let missing_model = ModelReviewResult {
            status: "ok".to_string(),
            model: None,
            cost_usd: None,
            concerns: Vec::new(),
            fallbacks: Vec::new(),
            error: None,
        };
        assert!(missing_model.is_failed());
        let model_flag = missing_model.flag().expect("expected flag");
        assert!(!model_flag.contains("unknown error"), "flag={model_flag}");
        assert!(!model_flag.contains('?'), "flag={model_flag}");
        assert!(model_flag.contains("missing model"), "flag={model_flag}");

        let rendered_missing_model = format_result(&missing_model);
        assert!(
            !rendered_missing_model.contains('?'),
            "rendered={rendered_missing_model}"
        );
        assert!(
            !rendered_missing_model.contains("unknown error"),
            "rendered={rendered_missing_model}"
        );

        let no_price = ModelReviewResult::ok("custom/unpriced".to_string(), None, Vec::new());
        let rendered_no_price = format_result(&no_price);
        assert!(
            rendered_no_price.contains("price unknown"),
            "rendered={rendered_no_price}"
        );
        assert!(
            !rendered_no_price.contains('?'),
            "rendered={rendered_no_price}"
        );

        let bad_missing_fb = r#"{"concerns": [], "extra": "actual-payload-123"}"#;
        let err_fb = parse(bad_missing_fb, true).unwrap_err();
        assert!(err_fb.contains("actual-payload-123"), "err={err_fb}");
        assert!(!err_fb.contains("unknown error"), "err={err_fb}");

        let bad_verdict = r#"{"concerns": [], "fallbacks": [{"file": "a.rs", "line": 1, "verdict": "bogus", "reason": "r"}]}"#;
        let err_v = parse(bad_verdict, true).unwrap_err();
        assert!(err_v.contains("bogus"), "err={err_v}");
        assert!(err_v.contains("a.rs"), "err={err_v}");
    }

    #[test]
    fn test_save_review_errors_when_parent_is_a_file() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(".wt"), "blocking file").unwrap();
        let expected_path = dir.path().join(".wt/T1.model-review.json");
        let err = save_review(
            dir.path(),
            "T1",
            Some("test-model"),
            Some(0.01),
            Vec::new(),
            Vec::new(),
            None,
        )
        .expect_err("expected error when .wt is a file");
        assert!(
            err.contains(&expected_path.display().to_string()),
            "err={err}"
        );

        let res = run(dir.path(), "T1", "HEAD", dir.path());
        assert!(res.is_failed());
        let res_err = res.error.expect("expected error");
        assert!(
            res_err.contains(&expected_path.display().to_string()),
            "res_err={res_err}"
        );
    }
}