Skip to main content

blyte_cli/
queue_actions.rs

1use std::path::{Path, PathBuf};
2use std::process::Command;
3
4use crate::cli::ReviewVerdict;
5use crate::dispatch::{host_commands, outside_reads, refused_reads};
6
7#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8pub struct Hold {
9    pub note: String,
10    pub ts: u64,
11}
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Action {
16    Accept,
17    SendBack,
18    Redo,
19    Hold,
20    MarkRead,
21}
22
23#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
24pub struct Decision {
25    pub run: String,
26    pub action: Action,
27    pub note: Option<String>,
28    pub conversation_message: Option<String>,
29}
30
31pub(crate) struct ReviewComputation {
32    pub(crate) wt: PathBuf,
33    pub(crate) wt_exists: bool,
34    pub(crate) is_research: bool,
35    pub(crate) base: String,
36    pub(crate) task_text: Option<String>,
37    pub(crate) changed_files: Vec<String>,
38    pub(crate) commits_out: String,
39    pub(crate) files_out: String,
40    pub(crate) tree_out: String,
41    pub(crate) diff_out: String,
42    pub(crate) hcmds: Vec<String>,
43    pub(crate) reads: Vec<String>,
44    pub(crate) report_val: Option<serde_json::Value>,
45    pub(crate) quote_problems: Option<Vec<String>>,
46    pub(crate) claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
47    pub(crate) claim_check_skipped: Option<String>,
48    pub(crate) checks: crate::review_checks::Checks,
49    pub(crate) fallbacks: Vec<crate::fallback_check::Finding>,
50}
51
52pub fn record_verdict(
53    root: &Path,
54    id: &str,
55    verdict: ReviewVerdict,
56    notes: &str,
57    now: u64,
58) -> Result<(), String> {
59    let wt_dir = root.join(".wt");
60    std::fs::create_dir_all(&wt_dir)
61        .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
62    let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
63    let verdict_obj = serde_json::json!({
64        "verdict": verdict.as_str(),
65        "notes": notes,
66        "ts": now,
67    });
68    let json_str = serde_json::to_string_pretty(&verdict_obj)
69        .map_err(|e| format!("error serializing verdict: {e}"))?;
70    std::fs::write(&verdict_path, json_str + "\n")
71        .map_err(|e| format!("error writing {}: {e}", verdict_path.display()))?;
72    crate::clean::clean_on_review(root, id);
73    Ok(())
74}
75
76pub fn read_verdict(root: &Path, id: &str) -> Result<Option<ReviewVerdict>, String> {
77    let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
78    let raw = match std::fs::read_to_string(&verdict_path) {
79        Ok(s) => s,
80        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
81        Err(e) => {
82            return Err(format!("error reading {}: {e}", verdict_path.display()));
83        }
84    };
85    let val: serde_json::Value = serde_json::from_str(&raw)
86        .map_err(|e| format!("could not parse {}: {e}", verdict_path.display()))?;
87    let verdict_str = val
88        .get("verdict")
89        .and_then(|v| v.as_str())
90        .ok_or_else(|| format!("{} is missing string verdict", verdict_path.display()))?;
91    let parsed = match verdict_str {
92        "accepted" => ReviewVerdict::Accepted,
93        "fixed" => ReviewVerdict::Fixed,
94        "redone" => ReviewVerdict::Redone,
95        other => {
96            return Err(format!(
97                "{} has unknown verdict '{other}'",
98                verdict_path.display()
99            ));
100        }
101    };
102    Ok(Some(parsed))
103}
104
105enum ReviewError {
106    WorktreeGone(String),
107    Other(String),
108}
109
110impl ReviewError {
111    fn into_message(self) -> String {
112        match self {
113            Self::WorktreeGone(msg) | Self::Other(msg) => msg,
114        }
115    }
116}
117
118enum WtGit {
119    Output(std::process::Output),
120    WorktreeGone,
121    IoErr(std::io::Error),
122}
123
124fn wt_present(wt: &Path) -> bool {
125    wt.is_dir() && wt.join(".git").exists()
126}
127
128fn run_git_in_wt(wt: &Path, args: &[&str]) -> WtGit {
129    match Command::new("git").args(args).current_dir(wt).output() {
130        Ok(o) => {
131            if !o.status.success() && !wt_present(wt) {
132                WtGit::WorktreeGone
133            } else {
134                WtGit::Output(o)
135            }
136        }
137        Err(e) => {
138            if !wt_present(wt) {
139                WtGit::WorktreeGone
140            } else {
141                WtGit::IoErr(e)
142            }
143        }
144    }
145}
146
147struct WorktreeGitData {
148    base: String,
149    start_comments: Option<String>,
150    commits_out: String,
151    files_out: String,
152    tree_out: String,
153    diff_raw: Option<String>,
154    diff_out: String,
155    task_text: Option<String>,
156    changed_files: Vec<String>,
157    subjects: Vec<String>,
158}
159
160impl WorktreeGitData {
161    fn empty() -> Self {
162        Self {
163            base: String::new(),
164            start_comments: None,
165            commits_out: String::new(),
166            files_out: String::new(),
167            tree_out: String::new(),
168            diff_raw: None,
169            diff_out: String::new(),
170            task_text: None,
171            changed_files: Vec::new(),
172            subjects: Vec::new(),
173        }
174    }
175}
176
177fn git_stdout_in_wt_with(
178    run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
179    wt: &Path,
180    args: &[&str],
181) -> Result<Option<String>, String> {
182    match run_git(wt, args) {
183        WtGit::WorktreeGone => Ok(None),
184        WtGit::IoErr(e) => Err(format!(
185            "could not run git {} in {}: {e}",
186            args.join(" "),
187            wt.display()
188        )),
189        WtGit::Output(o) if o.status.success() => {
190            Ok(Some(String::from_utf8_lossy(&o.stdout).into_owned()))
191        }
192        WtGit::Output(o) => {
193            let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
194            let detail = if stderr.is_empty() {
195                format!("exit {}", o.status)
196            } else {
197                stderr
198            };
199            Err(format!(
200                "git {} failed in {}: {detail}",
201                args.join(" "),
202                wt.display()
203            ))
204        }
205    }
206}
207
208fn read_worktree_git_data(
209    root: &Path,
210    id: &str,
211    wt: &Path,
212    is_research: bool,
213    include_diff_for_research: bool,
214    before_git: Option<&dyn Fn()>,
215    run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
216) -> Result<Option<WorktreeGitData>, String> {
217    let start_path = root.join(".wt").join(format!("{id}.start.json"));
218    let (start_base_sha, start_comments): (Option<String>, Option<String>) =
219        match std::fs::read_to_string(&start_path) {
220            Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
221                Ok(v) => (
222                    v.get("base_sha")
223                        .and_then(|s| s.as_str())
224                        .map(str::trim)
225                        .filter(|s| !s.is_empty())
226                        .map(String::from),
227                    v.get("comments")
228                        .and_then(|s| s.as_str())
229                        .map(str::trim)
230                        .filter(|s| !s.is_empty())
231                        .map(String::from),
232                ),
233                Err(e) => {
234                    return Err(format!("cannot parse {}: {e}", start_path.display()));
235                }
236            },
237            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
238            Err(e) => {
239                return Err(format!("cannot read {}: {e}", start_path.display()));
240            }
241        };
242
243    if let Some(hook) = before_git {
244        hook();
245    }
246
247    let base = if let Some(sha) = start_base_sha {
248        let out = Command::new("git")
249            .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
250            .current_dir(root)
251            .output()
252            .map_err(|e| format!("cannot run git cat-file in {}: {e}", root.display()))?;
253        if !out.status.success() {
254            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
255            return Err(format!(
256                "run {id} started from {sha}, which is not in this repository (git cat-file in {}: {stderr})",
257                root.display()
258            ));
259        }
260        sha
261    } else if is_research {
262        match run_git(wt, &["rev-list", "--max-parents=0", "HEAD"]) {
263            WtGit::WorktreeGone => return Ok(None),
264            WtGit::IoErr(e) => {
265                return Err(format!(
266                    "could not run git rev-list --max-parents=0 HEAD in {}: {e}",
267                    wt.display()
268                ));
269            }
270            WtGit::Output(o) if o.status.success() => {
271                let stdout = String::from_utf8_lossy(&o.stdout);
272                let trimmed = stdout.trim();
273                let lines: Vec<&str> = trimmed.lines().collect();
274                match lines.as_slice() {
275                    [only] => only.trim().to_string(),
276                    [] => {
277                        return Err(format!(
278                            "cannot find the first commit of research run {id} in {}: git rev-list --max-parents=0 HEAD printed no commit",
279                            wt.display()
280                        ));
281                    }
282                    _ => {
283                        return Err(format!(
284                            "cannot find the first commit of research run {id} in {}: git rev-list --max-parents=0 HEAD printed more than one line: {trimmed}",
285                            wt.display()
286                        ));
287                    }
288                }
289            }
290            WtGit::Output(o) => {
291                let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
292                let detail = if stderr.is_empty() {
293                    format!("exit {}", o.status)
294                } else {
295                    stderr
296                };
297                return Err(format!(
298                    "cannot find the first commit of research run {id} in {}: {detail}",
299                    wt.display()
300                ));
301            }
302        }
303    } else {
304        let root_head = Command::new("git")
305            .args(["rev-parse", "HEAD"])
306            .current_dir(root)
307            .output();
308        let root_head_sha = match root_head {
309            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
310            _ => {
311                return Err("could not resolve root HEAD".to_string());
312            }
313        };
314
315        match run_git(wt, &["merge-base", "HEAD", &root_head_sha]) {
316            WtGit::WorktreeGone => return Ok(None),
317            WtGit::IoErr(e) => {
318                return Err(format!(
319                    "could not run git merge-base HEAD {root_head_sha} in {}: {e}",
320                    wt.display()
321                ));
322            }
323            WtGit::Output(o) if o.status.success() => {
324                String::from_utf8_lossy(&o.stdout).trim().to_string()
325            }
326            WtGit::Output(_) => {
327                return Err(format!(
328                    "cannot find where run {id} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}"
329                ));
330            }
331        }
332    };
333
334    let range = format!("{base}..HEAD");
335
336    let Some(commits_raw) = git_stdout_in_wt_with(run_git, wt, &["log", "--oneline", &range])?
337    else {
338        return Ok(None);
339    };
340    let commits_out = commits_raw.trim().to_string();
341
342    let Some(files_raw) = git_stdout_in_wt_with(run_git, wt, &["diff", "--stat", &range])? else {
343        return Ok(None);
344    };
345    let files_out = files_raw.trim().to_string();
346
347    let Some(tree_raw) = git_stdout_in_wt_with(run_git, wt, &["status", "--short"])? else {
348        return Ok(None);
349    };
350    let tree_out = tree_raw.trim().to_string();
351
352    let diff_raw = if !is_research || include_diff_for_research {
353        let Some(diff) = git_stdout_in_wt_with(run_git, wt, &["diff", &range])? else {
354            return Ok(None);
355        };
356        Some(diff)
357    } else {
358        None
359    };
360
361    let diff_out = match diff_raw.as_deref() {
362        Some(s) => s.trim().to_string(),
363        None => String::new(),
364    };
365
366    let task_text: Option<String> = (|| {
367        let start_file = root.join(".wt").join(format!("{id}.start.json"));
368        let content = std::fs::read_to_string(&start_file).ok()?;
369        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
370        let task_file = val.get("task_file")?.as_str()?;
371        let p = Path::new(task_file);
372        if let Ok(s) = std::fs::read_to_string(p) {
373            return Some(s);
374        }
375        std::fs::read_to_string(root.join(p)).ok()
376    })();
377
378    let Some(changed_raw) = git_stdout_in_wt_with(run_git, wt, &["diff", "--name-only", &range])?
379    else {
380        return Ok(None);
381    };
382    let changed_files: Vec<String> = changed_raw
383        .lines()
384        .map(|l| l.trim().to_string())
385        .filter(|l| !l.is_empty())
386        .collect();
387
388    let Some(subjects_raw) = git_stdout_in_wt_with(run_git, wt, &["log", "--format=%s", &range])?
389    else {
390        return Ok(None);
391    };
392    let subjects: Vec<String> = subjects_raw
393        .lines()
394        .map(|l| l.trim().to_string())
395        .filter(|l| !l.is_empty())
396        .collect();
397
398    Ok(Some(WorktreeGitData {
399        base,
400        start_comments,
401        commits_out,
402        files_out,
403        tree_out,
404        diff_raw,
405        diff_out,
406        task_text,
407        changed_files,
408        subjects,
409    }))
410}
411
412pub(crate) fn compute_review(
413    root: &Path,
414    id: &str,
415    include_diff_for_research: bool,
416) -> Result<ReviewComputation, String> {
417    compute_review_res(root, id, include_diff_for_research, None, None)
418        .map_err(ReviewError::into_message)
419}
420
421fn compute_review_res(
422    root: &Path,
423    id: &str,
424    include_diff_for_research: bool,
425    summary_worktree_fallback: Option<&Path>,
426    before_git: Option<&dyn Fn()>,
427) -> Result<ReviewComputation, ReviewError> {
428    compute_review_res_with_runner(
429        root,
430        id,
431        include_diff_for_research,
432        summary_worktree_fallback,
433        before_git,
434        &run_git_in_wt,
435    )
436}
437
438fn compute_review_res_with_runner(
439    root: &Path,
440    id: &str,
441    include_diff_for_research: bool,
442    summary_worktree_fallback: Option<&Path>,
443    before_git: Option<&dyn Fn()>,
444    run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
445) -> Result<ReviewComputation, ReviewError> {
446    let wt = root.join(".wt").join(id);
447    let mut wt_exists = wt_present(&wt);
448    let is_research = crate::clean::is_research(root, id)
449        || root.join(".wt").join(format!("{id}.report.md")).exists();
450    let report_file = root.join(".wt").join(format!("{id}.report.json"));
451    let summary_file = root.join(".wt").join(format!("{id}.json"));
452    let missing_wt_err = |wt: &Path| -> Option<ReviewError> {
453        if !is_research {
454            if !report_file.exists() && summary_file.exists() {
455                return None;
456            }
457            return Some(ReviewError::WorktreeGone(format!(
458                "worktree {} does not exist",
459                wt.display()
460            )));
461        }
462        if !report_file.exists() && !summary_file.exists() {
463            return Some(ReviewError::WorktreeGone(format!(
464                "worktree {} does not exist and {} is missing: nothing to review",
465                wt.display(),
466                report_file.display()
467            )));
468        }
469        None
470    };
471    if !wt_exists {
472        if let Some(err) = missing_wt_err(&wt) {
473            return Err(err);
474        }
475    }
476
477    let git_data = if wt_exists {
478        match read_worktree_git_data(
479            root,
480            id,
481            &wt,
482            is_research,
483            include_diff_for_research,
484            before_git,
485            run_git,
486        ) {
487            Ok(Some(data)) => data,
488            Ok(None) => {
489                wt_exists = false;
490                if let Some(err) = missing_wt_err(&wt) {
491                    return Err(err);
492                }
493                WorktreeGitData::empty()
494            }
495            Err(e) => return Err(ReviewError::Other(e)),
496        }
497    } else {
498        WorktreeGitData::empty()
499    };
500
501    let WorktreeGitData {
502        base,
503        start_comments,
504        commits_out,
505        files_out,
506        tree_out,
507        diff_raw,
508        diff_out,
509        task_text,
510        changed_files,
511        subjects,
512    } = git_data;
513
514    let log_file = root.join(".wt").join(format!("{id}.log"));
515    let log_content_opt = match std::fs::read_to_string(&log_file) {
516        Ok(content) => Some(content),
517        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
518        Err(e) => {
519            return Err(ReviewError::Other(format!(
520                "cannot read {}: {e}",
521                log_file.display()
522            )));
523        }
524    };
525    let (hcmds, reads, (refused_count, refused_paths)) =
526        if let Some(ref log_content) = log_content_opt {
527            let hcmds = host_commands(log_content);
528            let home = std::env::var_os("HOME")
529                .map(PathBuf::from)
530                .unwrap_or_else(|| PathBuf::from("/"));
531            let allowed = [root.to_path_buf(), wt.clone()];
532            let reads = outside_reads(log_content, &allowed, &home);
533            let refused = refused_reads(log_content);
534            (hcmds, reads, refused)
535        } else {
536            (Vec::new(), Vec::new(), (0, Vec::new()))
537        };
538
539    let report_val = match read_optional_json(&report_file)? {
540        Some(v) => Some(v),
541        None => read_optional_json(&summary_file)?,
542    };
543    let outcome = report_val
544        .as_ref()
545        .and_then(|v| v.get("outcome"))
546        .and_then(|x| x.as_str());
547    let quote_problems: Option<Vec<String>> = report_val
548        .as_ref()
549        .and_then(|v| v.get("quote_problems"))
550        .and_then(|x| x.as_array())
551        .map(|arr| {
552            arr.iter()
553                .filter_map(|x| x.as_str().map(String::from))
554                .collect()
555        });
556    let read_loop = report_val
557        .as_ref()
558        .and_then(|v| v.get("read_loop"))
559        .and_then(|x| x.as_bool())
560        .unwrap_or(false);
561    let gate_left_out: Vec<String> = report_val
562        .as_ref()
563        .and_then(|v| v.get("gate_left_out"))
564        .and_then(|x| x.as_array())
565        .map(|arr| {
566            arr.iter()
567                .filter_map(|x| x.as_str().map(String::from))
568                .collect::<Vec<_>>()
569        })
570        .filter(|v| !v.is_empty())
571        .or_else(|| {
572            let start_file = root.join(".wt").join(format!("{id}.start.json"));
573            let content = std::fs::read_to_string(&start_file).ok()?;
574            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
575            let arr = val.get("gate_left_out")?.as_array()?;
576            Some(
577                arr.iter()
578                    .filter_map(|item| {
579                        let cmd = item.get("command")?.as_str()?;
580                        let reason = item.get("reason")?.as_str()?;
581                        Some(format!("{cmd} ({reason})"))
582                    })
583                    .collect(),
584            )
585        })
586        .unwrap_or_default();
587    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
588        .as_ref()
589        .and_then(|v| v.get("claim_check"))
590        .and_then(|x| serde_json::from_value(x.clone()).ok());
591    let claim_check_skipped: Option<String> = report_val
592        .as_ref()
593        .and_then(|v| v.get("claim_check_skipped"))
594        .and_then(|x| x.as_str())
595        .map(String::from);
596
597    let mut checks = if wt_exists {
598        crate::review_checks::build(
599            task_text.as_deref(),
600            &changed_files,
601            &subjects,
602            hcmds.len(),
603            reads.len(),
604            outcome,
605        )
606    } else {
607        crate::review_checks::build(
608            Some(""),
609            &[String::new()],
610            &[],
611            hcmds.len(),
612            reads.len(),
613            outcome,
614        )
615    };
616    let mut fallbacks: Vec<crate::fallback_check::Finding> = Vec::new();
617    if !is_research {
618        if let Some(ref diff) = diff_raw {
619            fallbacks = crate::fallback_check::added_fallbacks(diff);
620            if start_comments.as_deref() != Some("off") {
621                let wt_gone = std::cell::Cell::new(false);
622                match crate::comment_lint::added_comments(diff, &|path| match run_git_in_wt(
623                    &wt,
624                    &["show", &format!("HEAD:{path}")],
625                ) {
626                    WtGit::WorktreeGone => {
627                        wt_gone.set(true);
628                        Err(format!("worktree {} does not exist", wt.display()))
629                    }
630                    WtGit::IoErr(e) => Err(e.to_string()),
631                    WtGit::Output(o) => {
632                        if o.status.success() {
633                            Ok(String::from_utf8_lossy(&o.stdout).into_owned())
634                        } else {
635                            let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
636                            if stderr.is_empty() {
637                                Err(format!("exit {}", o.status))
638                            } else {
639                                Err(stderr)
640                            }
641                        }
642                    }
643                }) {
644                    Ok(comments) => {
645                        if let Some(flag) = crate::comment_lint::flag(&comments) {
646                            checks.flags.push(flag);
647                        }
648                    }
649                    Err(reason) => {
650                        if wt_gone.get() {
651                            return Err(ReviewError::WorktreeGone(format!(
652                                "worktree {} does not exist",
653                                wt.display()
654                            )));
655                        }
656                        let first_line = reason.lines().next().unwrap_or(reason.as_str());
657                        let msg = format!("comment check not run: {first_line}");
658                        let cut: String = msg.chars().take(200).collect();
659                        checks.flags.push(cut);
660                    }
661                }
662            }
663        }
664        if wt_exists {
665            match std::fs::read_to_string(&summary_file) {
666                Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
667                    Ok(v) => match crate::outside_env::summary_worktree(&v) {
668                        Ok(summary_wt) => {
669                            if let Some(ref log_content) = log_content_opt {
670                                let borrowed = crate::outside_env::borrowed_env_commands(
671                                    log_content,
672                                    &summary_wt,
673                                );
674                                if let Some(flag) = crate::outside_env::flag(&borrowed) {
675                                    checks.flags.push(flag);
676                                }
677                            }
678                        }
679                        Err(e) => {
680                            checks.flags.push(format!("outside-env check not run: {e}"));
681                        }
682                    },
683                    Err(e) => {
684                        checks.flags.push(format!(
685                            "outside-env check not run: cannot parse {}: {e}",
686                            summary_file.display()
687                        ));
688                    }
689                },
690                Err(e) if e.kind() == std::io::ErrorKind::NotFound && log_content_opt.is_none() => {
691                }
692                Err(e)
693                    if e.kind() == std::io::ErrorKind::NotFound
694                        && summary_worktree_fallback.is_some() =>
695                {
696                    if let (Some(summary_wt), Some(ref log_content)) =
697                        (summary_worktree_fallback, &log_content_opt)
698                    {
699                        let borrowed =
700                            crate::outside_env::borrowed_env_commands(log_content, summary_wt);
701                        if let Some(flag) = crate::outside_env::flag(&borrowed) {
702                            checks.flags.push(flag);
703                        }
704                    }
705                }
706                Err(e) => {
707                    checks.flags.push(format!(
708                        "outside-env check not run: cannot read {}: {e}",
709                        summary_file.display()
710                    ));
711                }
712            }
713        }
714    }
715    if let Some(ref problems) = quote_problems {
716        if !problems.is_empty() {
717            checks.flags.push(format!(
718                "quote check failed ({} problem(s)): see == report",
719                problems.len()
720            ));
721        }
722    }
723    if read_loop {
724        checks.flags.push(
725            "read loop: the run kept re-reading the same files without changing anything and was stopped"
726                .to_string(),
727        );
728    }
729    if !gate_left_out.is_empty() {
730        checks
731            .flags
732            .push(format!("gate left out: {}", gate_left_out.join("; ")));
733    }
734    if let Some(ref cc) = claim_check {
735        if !cc.contradicted.is_empty() {
736            checks.flags.push(format!(
737                "claim check: {} contradicted claims",
738                cc.contradicted.len()
739            ));
740        }
741    }
742    if let Some(ref skipped) = claim_check_skipped {
743        checks.flags.push(format!("claim check skipped: {skipped}"));
744    }
745    if refused_count > 0 {
746        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
747        checks.flags.push(format!(
748            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
749            first_3.join(", ")
750        ));
751    }
752    if is_research {
753        match &report_val {
754            Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
755                Ok((large, total)) => {
756                    if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
757                        checks.flags.push(flag);
758                    }
759                }
760                Err(e) => {
761                    checks.flags.push(format!("breadth check not run: {e}"));
762                }
763            },
764            None => {
765                checks.flags.push(format!(
766                    "breadth check not run: cannot read {}",
767                    report_file.display()
768                ));
769            }
770        }
771        if outcome == Some("budget_exhausted") {
772            match std::fs::read_to_string(&log_file) {
773                Ok(log) => {
774                    let dirs = crate::research_breadth::read_dirs(&log, root);
775                    if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
776                        checks.flags.push(flag);
777                    }
778                }
779                Err(e) => {
780                    checks.flags.push(format!("split suggestion not run: {e}"));
781                }
782            }
783        }
784    }
785
786    Ok(ReviewComputation {
787        wt,
788        wt_exists,
789        is_research,
790        base,
791        task_text,
792        changed_files,
793        commits_out,
794        files_out,
795        tree_out,
796        diff_out,
797        hcmds,
798        reads,
799        report_val,
800        quote_problems,
801        claim_check,
802        claim_check_skipped,
803        checks,
804        fallbacks,
805    })
806}
807
808pub fn read_stored_model_review(
809    root: &Path,
810    id: &str,
811) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
812    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
813    let raw = match std::fs::read_to_string(&checks_path) {
814        Ok(s) => s,
815        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
816        Err(e) => return Err(format!("cannot read {}: {e}", checks_path.display())),
817    };
818    let val: serde_json::Value = serde_json::from_str(&raw)
819        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
820    parse_stored_model_review(&checks_path, &val)
821}
822
823pub(crate) fn parse_stored_model_review(
824    checks_path: &Path,
825    val: &serde_json::Value,
826) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
827    let Some(obj) = val.as_object() else {
828        return Err(format!(
829            "cannot parse {}: expected a JSON object",
830            checks_path.display()
831        ));
832    };
833    let Some(mr) = obj.get("model_review") else {
834        return Ok(None);
835    };
836    if mr.is_null() {
837        return Ok(None);
838    }
839    let parsed: crate::model_review::ModelReviewResult = serde_json::from_value(mr.clone())
840        .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))?;
841    parsed
842        .validate()
843        .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))?;
844    Ok(Some(parsed))
845}
846
847fn read_optional_json(path: &Path) -> Result<Option<serde_json::Value>, ReviewError> {
848    let raw = match std::fs::read_to_string(path) {
849        Ok(content) => content,
850        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
851        Err(e) => {
852            return Err(ReviewError::Other(format!(
853                "cannot read {}: {e}",
854                path.display()
855            )));
856        }
857    };
858    serde_json::from_str::<serde_json::Value>(&raw)
859        .map(Some)
860        .map_err(|e| ReviewError::Other(format!("cannot parse {}: {e}", path.display())))
861}
862
863pub(crate) fn write_checks_file(
864    root: &Path,
865    id: &str,
866    flags: &[String],
867    fallbacks: &[crate::fallback_check::Finding],
868    model_review: Option<&crate::model_review::ModelReviewResult>,
869) -> Result<(), String> {
870    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
871    let ts = std::time::SystemTime::now()
872        .duration_since(std::time::UNIX_EPOCH)
873        .map_err(|e| format!("error: the system clock is before 1970: {e}"))?
874        .as_secs();
875    let annotated_fallbacks = crate::fallback_check::annotate_fallbacks(fallbacks, model_review);
876    let mut checks_obj = serde_json::json!({
877        "ts": ts,
878        "flags": flags,
879        "fallbacks": annotated_fallbacks,
880    });
881    if let Some(mr) = model_review {
882        checks_obj["model_review"] = serde_json::to_value(mr).map_err(|e| {
883            format!(
884                "error serializing model review for {}: {e}",
885                checks_path.display()
886            )
887        })?;
888    }
889    let checks_json = serde_json::to_string_pretty(&checks_obj)
890        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))?;
891    std::fs::write(&checks_path, checks_json + "\n")
892        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))
893}
894
895pub fn evaluate_verified_run(
896    root: &Path,
897    id: &str,
898) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
899    evaluate_verified_run_with(root, id, false, crate::model_review::run)
900}
901
902pub fn evaluate_verified_run_with<F>(
903    root: &Path,
904    id: &str,
905    force_review: bool,
906    run_model_review: F,
907) -> Result<Option<crate::model_review::ModelReviewResult>, String>
908where
909    F: FnOnce(&Path, &str, &str, &Path) -> crate::model_review::ModelReviewResult,
910{
911    let wt_fallback = root.join(".wt").join(id);
912    let data = compute_review_res(root, id, false, Some(&wt_fallback), None)
913        .map_err(ReviewError::into_message)?;
914    let mut flags = data.checks.flags;
915    if data.is_research || !data.wt_exists {
916        flags.extend(crate::fallback_check::flags_for_review(
917            &data.fallbacks,
918            None,
919        ));
920        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
921        return Ok(None);
922    }
923
924    let risky_matches = match crate::config::load_with_fallback(root) {
925        Ok(Some((cfg, _))) => {
926            match crate::config::match_risky_paths(&cfg.review.risky, &data.changed_files) {
927                Ok(matches) => matches,
928                Err(e) => {
929                    flags.push(format!("risky path check not run: {e}"));
930                    Vec::new()
931                }
932            }
933        }
934        Ok(None) => Vec::new(),
935        Err(e) => {
936            flags.push(format!("risky path check not run: {e}"));
937            Vec::new()
938        }
939    };
940
941    if force_review
942        || crate::review_checks::should_run_model_review(
943            &flags,
944            data.task_text.as_deref(),
945            &risky_matches,
946            data.fallbacks.len(),
947        )
948    {
949        let result = run_model_review(root, id, &data.base, &data.wt);
950        flags.extend(crate::fallback_check::flags_for_review(
951            &data.fallbacks,
952            Some(&result),
953        ));
954        if let Some(flag) = result.flag() {
955            flags.push(flag);
956        }
957        write_checks_file(root, id, &flags, &data.fallbacks, Some(&result))?;
958        Ok(Some(result))
959    } else {
960        let review_path = root.join(".wt").join(format!("{id}.model-review.json"));
961        if review_path.exists() {
962            std::fs::remove_file(&review_path)
963                .map_err(|e| format!("cannot remove {}: {e}", review_path.display()))?;
964        }
965        flags.extend(crate::fallback_check::flags_for_review(
966            &data.fallbacks,
967            None,
968        ));
969        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
970        Ok(None)
971    }
972}
973
974pub fn ensure_checks(root: &Path, id: &str) -> Result<bool, String> {
975    ensure_checks_with_hook(root, id, None)
976}
977
978fn ensure_checks_with_hook(
979    root: &Path,
980    id: &str,
981    before_git: Option<&dyn Fn()>,
982) -> Result<bool, String> {
983    let wt_dir = root.join(".wt");
984    let summary_path = wt_dir.join(format!("{id}.json"));
985    if !summary_path.is_file() {
986        return Err(format!("no finished run {id} in {}", wt_dir.display()));
987    }
988    let checks_path = wt_dir.join(format!("{id}.checks.json"));
989    if checks_path.exists() {
990        return Ok(false);
991    }
992    let data = match compute_review_res(root, id, false, None, before_git) {
993        Ok(data) => data,
994        Err(ReviewError::WorktreeGone(_)) => return Ok(false),
995        Err(ReviewError::Other(e)) => return Err(e),
996    };
997    if !data.wt_exists {
998        return Ok(false);
999    }
1000    let mut flags = data.checks.flags;
1001    flags.extend(crate::fallback_check::flags_for_review(
1002        &data.fallbacks,
1003        None,
1004    ));
1005    write_checks_file(root, id, &flags, &data.fallbacks, None)?;
1006    Ok(true)
1007}
1008
1009pub fn set_hold_in(records_dir: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
1010    let trimmed = note.trim();
1011    if trimmed.is_empty() {
1012        return Err(format!("a note is required to hold run {id}"));
1013    }
1014    std::fs::create_dir_all(records_dir)
1015        .map_err(|e| format!("error creating directory {}: {e}", records_dir.display()))?;
1016    let hold_path = records_dir.join(format!("{id}.hold.json"));
1017    let hold = Hold {
1018        note: trimmed.to_string(),
1019        ts: now,
1020    };
1021    let json_str =
1022        serde_json::to_string_pretty(&hold).map_err(|e| format!("error serializing hold: {e}"))?;
1023    std::fs::write(&hold_path, json_str + "\n")
1024        .map_err(|e| format!("error writing {}: {e}", hold_path.display()))
1025}
1026
1027pub fn set_hold(root: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
1028    set_hold_in(&root.join(".wt"), id, note, now)
1029}
1030
1031pub fn clear_hold_in(records_dir: &Path, id: &str) -> Result<(), String> {
1032    let hold_path = records_dir.join(format!("{id}.hold.json"));
1033    match std::fs::remove_file(&hold_path) {
1034        Ok(()) => Ok(()),
1035        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1036        Err(e) => Err(format!("error removing {}: {e}", hold_path.display())),
1037    }
1038}
1039
1040pub fn clear_hold(root: &Path, id: &str) -> Result<(), String> {
1041    clear_hold_in(&root.join(".wt"), id)
1042}
1043
1044pub fn read_hold_in(records_dir: &Path, id: &str) -> Result<Option<Hold>, String> {
1045    let hold_path = records_dir.join(format!("{id}.hold.json"));
1046    let raw = match std::fs::read_to_string(&hold_path) {
1047        Ok(s) => s,
1048        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1049        Err(e) => return Err(format!("error reading {}: {e}", hold_path.display())),
1050    };
1051    serde_json::from_str::<Hold>(&raw)
1052        .map(Some)
1053        .map_err(|e| format!("could not parse {}: {e}", hold_path.display()))
1054}
1055
1056pub fn read_hold(root: &Path, id: &str) -> Result<Option<Hold>, String> {
1057    read_hold_in(&root.join(".wt"), id)
1058}
1059
1060pub fn decide_in_place(
1061    records_dir: &Path,
1062    id: &str,
1063    action: Action,
1064    note: Option<&str>,
1065    now: u64,
1066) -> Result<Decision, String> {
1067    let summary_path = records_dir.join(format!("{id}.json"));
1068    let start_path = records_dir.join(format!("{id}.start.json"));
1069    let summary_raw = match std::fs::read_to_string(&summary_path) {
1070        Ok(s) => s,
1071        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1072            if start_path.exists() {
1073                return Err(format!("run {id} has not finished"));
1074            }
1075            return Err(format!("unknown run: {id}"));
1076        }
1077        Err(e) => {
1078            return Err(format!("error reading {}: {e}", summary_path.display()));
1079        }
1080    };
1081    let summary: serde_json::Value = serde_json::from_str(&summary_raw)
1082        .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
1083    let outcome = summary
1084        .get("outcome")
1085        .and_then(|v| v.as_str())
1086        .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
1087    let start_raw = std::fs::read_to_string(&start_path)
1088        .map_err(|e| format!("error reading {}: {e}", start_path.display()))?;
1089    let start_val: serde_json::Value = serde_json::from_str(&start_raw)
1090        .map_err(|e| format!("could not parse {}: {e}", start_path.display()))?;
1091    let start_research = crate::in_place_review::parse_research_flag(&start_val, &start_path)?;
1092    let is_research = start_research || records_dir.join(format!("{id}.report.md")).exists();
1093
1094    let trimmed_note: Option<String> = note
1095        .map(str::trim)
1096        .filter(|s| !s.is_empty())
1097        .map(String::from);
1098
1099    let conversation_message = match action {
1100        Action::Accept => {
1101            if is_research {
1102                return Err(format!("run {id} is a research run; mark it read"));
1103            }
1104            if !matches!(outcome, "verified" | "finished") {
1105                return Err(format!(
1106                    "run {id} is {outcome}, not finished or verified; it cannot be accepted"
1107                ));
1108            }
1109            crate::in_place_review::record_verdict_at(
1110                records_dir,
1111                id,
1112                ReviewVerdict::Accepted,
1113                trimmed_note.as_deref().unwrap_or(""),
1114                now,
1115            )?;
1116            clear_hold_in(records_dir, id)?;
1117            None
1118        }
1119        Action::SendBack => {
1120            let Some(ref text) = trimmed_note else {
1121                return Err(format!("a note is required to send back run {id}"));
1122            };
1123            clear_hold_in(records_dir, id)?;
1124            Some(format!(
1125                "Send back run {id}: {text} Draft a follow-up task for me to confirm."
1126            ))
1127        }
1128        Action::Redo => {
1129            crate::in_place_review::record_verdict_at(
1130                records_dir,
1131                id,
1132                ReviewVerdict::Redone,
1133                trimmed_note.as_deref().unwrap_or(""),
1134                now,
1135            )?;
1136            clear_hold_in(records_dir, id)?;
1137            let msg = match trimmed_note.as_deref() {
1138                Some(text) => format!("Redo run {id}. Reason: {text}"),
1139                None => format!("Redo run {id}."),
1140            };
1141            Some(msg)
1142        }
1143        Action::Hold => {
1144            let Some(ref text) = trimmed_note else {
1145                return Err(format!("a note is required to hold run {id}"));
1146            };
1147            set_hold_in(records_dir, id, text, now)?;
1148            None
1149        }
1150        Action::MarkRead => {
1151            if !is_research {
1152                return Err(format!("run {id} is not a research run"));
1153            }
1154            crate::in_place_review::record_verdict_at(
1155                records_dir,
1156                id,
1157                ReviewVerdict::Accepted,
1158                "read",
1159                now,
1160            )?;
1161            clear_hold_in(records_dir, id)?;
1162            None
1163        }
1164    };
1165
1166    Ok(Decision {
1167        run: id.to_string(),
1168        action,
1169        note: trimmed_note,
1170        conversation_message,
1171    })
1172}
1173
1174pub fn decide(
1175    root: &Path,
1176    id: &str,
1177    action: Action,
1178    note: Option<&str>,
1179    now: u64,
1180) -> Result<Decision, String> {
1181    let wt_dir = root.join(".wt");
1182    let summary_path = wt_dir.join(format!("{id}.json"));
1183    let summary_raw = match std::fs::read_to_string(&summary_path) {
1184        Ok(s) => s,
1185        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1186            return Err(format!("no finished run {id} in {}", wt_dir.display()));
1187        }
1188        Err(e) => {
1189            return Err(format!("error reading {}: {e}", summary_path.display()));
1190        }
1191    };
1192    let summary: serde_json::Value = serde_json::from_str(&summary_raw)
1193        .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
1194    let outcome = summary
1195        .get("outcome")
1196        .and_then(|v| v.as_str())
1197        .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
1198    let is_research =
1199        crate::clean::is_research(root, id) || wt_dir.join(format!("{id}.report.md")).exists();
1200
1201    let trimmed_note: Option<String> = note
1202        .map(str::trim)
1203        .filter(|s| !s.is_empty())
1204        .map(String::from);
1205
1206    let conversation_message = match action {
1207        Action::Accept => {
1208            if is_research {
1209                return Err(format!("run {id} is a research run; mark it read"));
1210            }
1211            if outcome != "verified" {
1212                return Err(format!(
1213                    "run {id} is {outcome}, not verified; it cannot be accepted"
1214                ));
1215            }
1216            record_verdict(
1217                root,
1218                id,
1219                ReviewVerdict::Accepted,
1220                trimmed_note.as_deref().unwrap_or(""),
1221                now,
1222            )?;
1223            clear_hold(root, id)?;
1224            None
1225        }
1226        Action::SendBack => {
1227            let Some(ref text) = trimmed_note else {
1228                return Err(format!("a note is required to send back run {id}"));
1229            };
1230            clear_hold(root, id)?;
1231            Some(format!(
1232                "Send back run {id}: {text} Draft a follow-up task for me to confirm."
1233            ))
1234        }
1235        Action::Redo => {
1236            record_verdict(
1237                root,
1238                id,
1239                ReviewVerdict::Redone,
1240                trimmed_note.as_deref().unwrap_or(""),
1241                now,
1242            )?;
1243            clear_hold(root, id)?;
1244            let msg = match trimmed_note.as_deref() {
1245                Some(text) => format!("Redo run {id}. Reason: {text}"),
1246                None => format!("Redo run {id}."),
1247            };
1248            Some(msg)
1249        }
1250        Action::Hold => {
1251            let Some(ref text) = trimmed_note else {
1252                return Err(format!("a note is required to hold run {id}"));
1253            };
1254            set_hold(root, id, text, now)?;
1255            None
1256        }
1257        Action::MarkRead => {
1258            if !is_research {
1259                return Err(format!("run {id} is not a research run"));
1260            }
1261            record_verdict(root, id, ReviewVerdict::Accepted, "read", now)?;
1262            clear_hold(root, id)?;
1263            None
1264        }
1265    };
1266
1267    Ok(Decision {
1268        run: id.to_string(),
1269        action,
1270        note: trimmed_note,
1271        conversation_message,
1272    })
1273}
1274
1275#[cfg(test)]
1276mod tests {
1277    use super::*;
1278
1279    fn git(dir: &Path, args: &[&str]) -> String {
1280        let out = Command::new("git")
1281            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1282            .args(args)
1283            .current_dir(dir)
1284            .output()
1285            .unwrap();
1286        assert!(
1287            out.status.success(),
1288            "git {args:?} failed: {}",
1289            String::from_utf8_lossy(&out.stderr)
1290        );
1291        String::from_utf8_lossy(&out.stdout).trim().to_string()
1292    }
1293
1294    fn init_repo() -> (tempfile::TempDir, String) {
1295        let d = tempfile::tempdir().unwrap();
1296        git(d.path(), &["init", "-q"]);
1297        std::fs::write(d.path().join("f.txt"), "hello\n").unwrap();
1298        git(d.path(), &["add", "."]);
1299        git(d.path(), &["commit", "-qm", "init", "--no-gpg-sign"]);
1300        std::fs::create_dir_all(d.path().join(".wt")).unwrap();
1301        let head = git(d.path(), &["rev-parse", "HEAD"]);
1302        (d, head)
1303    }
1304
1305    fn setup_finished_code_run(root: &Path, id: &str, base_sha: Option<&str>) {
1306        let wt_path = root.join(".wt").join(id);
1307        git(
1308            root,
1309            &[
1310                "worktree",
1311                "add",
1312                "-q",
1313                "-b",
1314                &format!("wip/{id}"),
1315                wt_path.to_str().unwrap(),
1316                "HEAD",
1317            ],
1318        );
1319        let mut start = serde_json::json!({
1320            "id": id,
1321            "pid": 999999,
1322            "started_at": 1000,
1323            "research": false,
1324        });
1325        if let Some(sha) = base_sha {
1326            start["base_sha"] = serde_json::json!(sha);
1327        }
1328        std::fs::write(
1329            root.join(".wt").join(format!("{id}.start.json")),
1330            start.to_string(),
1331        )
1332        .unwrap();
1333        std::fs::write(
1334            root.join(".wt").join(format!("{id}.report.json")),
1335            serde_json::json!({ "outcome": "error", "turns": 0 }).to_string(),
1336        )
1337        .unwrap();
1338        std::fs::write(
1339            root.join(".wt").join(format!("{id}.json")),
1340            serde_json::json!({
1341                "outcome": "error",
1342                "seconds": 1,
1343                "final_message": "",
1344                "commits": [],
1345                "changed_files": []
1346            })
1347            .to_string(),
1348        )
1349        .unwrap();
1350    }
1351
1352    #[test]
1353    fn ensure_checks_skips_when_worktree_vanishes_before_git_commands() {
1354        let (d, head) = init_repo();
1355        setup_finished_code_run(d.path(), "M2", Some(&head));
1356        let root = d.path().to_path_buf();
1357        let remove_wt = move || {
1358            let wt = root.join(".wt/M2");
1359            let status = Command::new("git")
1360                .args(["worktree", "remove", "--force"])
1361                .arg(&wt)
1362                .current_dir(&root)
1363                .status()
1364                .unwrap();
1365            assert!(status.success());
1366        };
1367
1368        let wrote = ensure_checks_with_hook(d.path(), "M2", Some(&remove_wt)).unwrap();
1369        assert!(!wrote);
1370        assert!(!d.path().join(".wt/M2").exists());
1371        assert!(!d.path().join(".wt/M2.checks.json").exists());
1372    }
1373
1374    #[test]
1375    fn ensure_checks_skips_when_worktree_vanishes_without_base_sha() {
1376        let (d, _head) = init_repo();
1377        setup_finished_code_run(d.path(), "M3", None);
1378        let root = d.path().to_path_buf();
1379        let remove_wt = move || {
1380            let wt = root.join(".wt/M3");
1381            let status = Command::new("git")
1382                .args(["worktree", "remove", "--force"])
1383                .arg(&wt)
1384                .current_dir(&root)
1385                .status()
1386                .unwrap();
1387            assert!(status.success());
1388        };
1389
1390        let wrote = ensure_checks_with_hook(d.path(), "M3", Some(&remove_wt)).unwrap();
1391        assert!(!wrote);
1392        assert!(!d.path().join(".wt/M3.checks.json").exists());
1393    }
1394
1395    #[test]
1396    fn ensure_checks_still_errors_when_base_sha_is_not_in_repository() {
1397        let (d, _head) = init_repo();
1398        let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1399        setup_finished_code_run(d.path(), "BAD1", Some(missing));
1400
1401        let err = ensure_checks(d.path(), "BAD1").unwrap_err();
1402        assert!(
1403            err.contains(&format!(
1404                "run BAD1 started from {missing}, which is not in this repository"
1405            )),
1406            "unexpected error: {err}"
1407        );
1408    }
1409
1410    #[test]
1411    fn research_review_uses_no_worktree_path_when_worktree_vanishes_mid_read() {
1412        let (d, _head) = init_repo();
1413        let wt = d.path().join(".wt/R1");
1414        std::fs::create_dir_all(&wt).unwrap();
1415        git(&wt, &["init", "-q"]);
1416        git(
1417            &wt,
1418            &[
1419                "commit",
1420                "-q",
1421                "--allow-empty",
1422                "-m",
1423                "research",
1424                "--no-gpg-sign",
1425            ],
1426        );
1427        std::fs::write(
1428            d.path().join(".wt/R1.start.json"),
1429            serde_json::json!({ "id": "R1", "research": true }).to_string(),
1430        )
1431        .unwrap();
1432        std::fs::write(
1433            d.path().join(".wt/R1.report.json"),
1434            serde_json::json!({ "outcome": "verified", "turns": 1 }).to_string(),
1435        )
1436        .unwrap();
1437
1438        let wt_to_remove = wt.clone();
1439        let remove_wt = move || {
1440            std::fs::remove_dir_all(&wt_to_remove).unwrap();
1441        };
1442        let data = compute_review_res(d.path(), "R1", false, None, Some(&remove_wt))
1443            .map_err(ReviewError::into_message)
1444            .unwrap();
1445        assert!(!data.wt_exists);
1446        assert!(data.is_research);
1447    }
1448
1449    #[test]
1450    fn review_summary_errors_when_worktree_git_io_fails_naming_args() {
1451        let (d, head) = init_repo();
1452        setup_finished_code_run(d.path(), "G1", Some(&head));
1453        let wt = d.path().join(".wt/G1");
1454        let range = format!("{head}..HEAD");
1455
1456        let failing_calls: &[(&[&str], &str)] = &[
1457            (&["log", "--oneline"], "log --oneline"),
1458            (&["diff", "--stat"], "diff --stat"),
1459            (&["status", "--short"], "status --short"),
1460            (&["diff", range.as_str()], "diff"),
1461            (&["diff", "--name-only"], "diff --name-only"),
1462            (&["log", "--format=%s"], "log --format=%s"),
1463        ];
1464
1465        for &(fail_prefix, expected_args) in failing_calls {
1466            let runner = |dir: &Path, args: &[&str]| -> WtGit {
1467                if args.starts_with(fail_prefix) {
1468                    WtGit::IoErr(std::io::Error::new(
1469                        std::io::ErrorKind::NotFound,
1470                        "git binary missing",
1471                    ))
1472                } else {
1473                    run_git_in_wt(dir, args)
1474                }
1475            };
1476            let err = compute_review_res_with_runner(d.path(), "G1", false, None, None, &runner)
1477                .err()
1478                .expect("expected error")
1479                .into_message();
1480            assert!(
1481                err.contains("could not run git"),
1482                "for {expected_args}, got: {err}"
1483            );
1484            assert!(
1485                err.contains(expected_args),
1486                "for {expected_args}, got: {err}"
1487            );
1488            assert!(
1489                err.contains(&wt.display().to_string()),
1490                "for {expected_args}, got: {err}"
1491            );
1492            assert!(
1493                err.contains("git binary missing"),
1494                "for {expected_args}, got: {err}"
1495            );
1496        }
1497    }
1498
1499    #[test]
1500    fn review_summary_errors_when_worktree_git_exits_nonzero_with_stderr() {
1501        let (d, head) = init_repo();
1502        setup_finished_code_run(d.path(), "G2", Some(&head));
1503
1504        let runner = |dir: &Path, args: &[&str]| -> WtGit {
1505            if args.starts_with(&["diff", "--stat"]) {
1506                let mut out = Command::new("sh")
1507                    .args(["-c", "echo 'fatal: bad revision' >&2; exit 128"])
1508                    .output()
1509                    .unwrap();
1510                out.stdout.clear();
1511                WtGit::Output(out)
1512            } else {
1513                run_git_in_wt(dir, args)
1514            }
1515        };
1516        let err = compute_review_res_with_runner(d.path(), "G2", false, None, None, &runner)
1517            .err()
1518            .expect("expected error")
1519            .into_message();
1520        assert!(err.contains("diff --stat"), "got: {err}");
1521        assert!(err.contains("fatal: bad revision"), "got: {err}");
1522    }
1523
1524    #[test]
1525    fn compute_review_errors_on_corrupt_report_json_naming_file() {
1526        let (d, head) = init_repo();
1527        setup_finished_code_run(d.path(), "C1", Some(&head));
1528        let report_path = d.path().join(".wt/C1.report.json");
1529        std::fs::write(&report_path, "{corrupt json").unwrap();
1530
1531        let err = compute_review(d.path(), "C1", false)
1532            .err()
1533            .expect("expected error for corrupt report.json");
1534        assert!(
1535            err.contains(&report_path.display().to_string()),
1536            "got: {err}"
1537        );
1538    }
1539
1540    #[test]
1541    fn compute_review_errors_on_unreadable_log_directory_naming_file() {
1542        let (d, head) = init_repo();
1543        setup_finished_code_run(d.path(), "C2", Some(&head));
1544        let log_path = d.path().join(".wt/C2.log");
1545        std::fs::create_dir_all(&log_path).unwrap();
1546
1547        let err = compute_review(d.path(), "C2", false)
1548            .err()
1549            .expect("expected error for unreadable log directory");
1550        assert!(err.contains(&log_path.display().to_string()), "got: {err}");
1551    }
1552
1553    #[test]
1554    fn compute_review_errors_on_corrupt_summary_json_when_report_absent() {
1555        let (d, head) = init_repo();
1556        setup_finished_code_run(d.path(), "C3", Some(&head));
1557        std::fs::remove_file(d.path().join(".wt/C3.report.json")).unwrap();
1558        let summary_path = d.path().join(".wt/C3.json");
1559        std::fs::write(&summary_path, "not json at all").unwrap();
1560
1561        let err = compute_review(d.path(), "C3", false)
1562            .err()
1563            .expect("expected error for corrupt summary json");
1564        assert!(
1565            err.contains(&summary_path.display().to_string()),
1566            "got: {err}"
1567        );
1568    }
1569
1570    #[test]
1571    fn research_review_errors_on_rev_list_io_err_empty_and_multiline() {
1572        let (d, _head) = init_repo();
1573        let wt = d.path().join(".wt/R2");
1574        std::fs::create_dir_all(&wt).unwrap();
1575        git(&wt, &["init", "-q"]);
1576        git(
1577            &wt,
1578            &[
1579                "commit",
1580                "-q",
1581                "--allow-empty",
1582                "-m",
1583                "research",
1584                "--no-gpg-sign",
1585            ],
1586        );
1587        std::fs::write(
1588            d.path().join(".wt/R2.start.json"),
1589            serde_json::json!({ "id": "R2", "research": true, "base_sha": serde_json::Value::Null })
1590                .to_string(),
1591        )
1592        .unwrap();
1593        std::fs::write(
1594            d.path().join(".wt/R2.report.json"),
1595            serde_json::json!({ "outcome": "budget_exhausted", "turns": 1 }).to_string(),
1596        )
1597        .unwrap();
1598
1599        let io_runner = |dir: &Path, args: &[&str]| -> WtGit {
1600            if args == ["rev-list", "--max-parents=0", "HEAD"] {
1601                WtGit::IoErr(std::io::Error::new(
1602                    std::io::ErrorKind::NotFound,
1603                    "git binary missing",
1604                ))
1605            } else {
1606                run_git_in_wt(dir, args)
1607            }
1608        };
1609        let io_err = compute_review_res_with_runner(d.path(), "R2", false, None, None, &io_runner)
1610            .err()
1611            .expect("expected IoErr")
1612            .into_message();
1613        assert!(
1614            io_err.contains("rev-list --max-parents=0 HEAD"),
1615            "got: {io_err}"
1616        );
1617        assert!(io_err.contains(&wt.display().to_string()), "got: {io_err}");
1618        assert!(io_err.contains("git binary missing"), "got: {io_err}");
1619
1620        let empty_runner = |dir: &Path, args: &[&str]| -> WtGit {
1621            if args == ["rev-list", "--max-parents=0", "HEAD"] {
1622                let mut out = Command::new("sh").args(["-c", "exit 0"]).output().unwrap();
1623                out.stdout.clear();
1624                out.stderr.clear();
1625                WtGit::Output(out)
1626            } else {
1627                run_git_in_wt(dir, args)
1628            }
1629        };
1630        let empty_err =
1631            compute_review_res_with_runner(d.path(), "R2", false, None, None, &empty_runner)
1632                .err()
1633                .expect("expected empty output error")
1634                .into_message();
1635        assert!(empty_err.contains("research run R2"), "got: {empty_err}");
1636        assert!(
1637            empty_err.contains(&wt.display().to_string()),
1638            "got: {empty_err}"
1639        );
1640
1641        let multi_runner = |dir: &Path, args: &[&str]| -> WtGit {
1642            if args == ["rev-list", "--max-parents=0", "HEAD"] {
1643                let out = Command::new("sh")
1644                    .args(["-c", "printf 'aaaa1111\\nbbbb2222\\n'"])
1645                    .output()
1646                    .unwrap();
1647                WtGit::Output(out)
1648            } else {
1649                run_git_in_wt(dir, args)
1650            }
1651        };
1652        let multi_err =
1653            compute_review_res_with_runner(d.path(), "R2", false, None, None, &multi_runner)
1654                .err()
1655                .expect("expected multi-line output error")
1656                .into_message();
1657        assert!(multi_err.contains("research run R2"), "got: {multi_err}");
1658        assert!(
1659            multi_err.contains(&wt.display().to_string()),
1660            "got: {multi_err}"
1661        );
1662        assert!(multi_err.contains("aaaa1111"), "got: {multi_err}");
1663        assert!(multi_err.contains("bbbb2222"), "got: {multi_err}");
1664    }
1665
1666    #[test]
1667    fn research_review_with_base_sha_still_checks_recorded_base_sha() {
1668        let (d, _head) = init_repo();
1669        let wt = d.path().join(".wt/R3");
1670        std::fs::create_dir_all(&wt).unwrap();
1671        git(&wt, &["init", "-q"]);
1672        git(
1673            &wt,
1674            &[
1675                "commit",
1676                "-q",
1677                "--allow-empty",
1678                "-m",
1679                "research",
1680                "--no-gpg-sign",
1681            ],
1682        );
1683        let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1684        std::fs::write(
1685            d.path().join(".wt/R3.start.json"),
1686            serde_json::json!({ "id": "R3", "research": true, "base_sha": missing }).to_string(),
1687        )
1688        .unwrap();
1689        std::fs::write(
1690            d.path().join(".wt/R3.report.json"),
1691            serde_json::json!({ "outcome": "budget_exhausted", "turns": 1 }).to_string(),
1692        )
1693        .unwrap();
1694
1695        let err = compute_review(d.path(), "R3", false)
1696            .err()
1697            .expect("expected missing base_sha error");
1698        assert!(
1699            err.contains(&format!(
1700                "run R3 started from {missing}, which is not in this repository"
1701            )),
1702            "got: {err}"
1703        );
1704    }
1705}