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 orchestrator_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_res: Option<Result<String, 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_res: None,
169            diff_out: String::new(),
170            task_text: None,
171            changed_files: Vec::new(),
172            subjects: Vec::new(),
173        }
174    }
175}
176
177fn read_worktree_git_data(
178    root: &Path,
179    id: &str,
180    wt: &Path,
181    is_research: bool,
182    include_diff_for_research: bool,
183    before_git: Option<&dyn Fn()>,
184) -> Result<Option<WorktreeGitData>, String> {
185    let start_path = root.join(".wt").join(format!("{id}.start.json"));
186    let (start_base_sha, start_comments): (Option<String>, Option<String>) =
187        match std::fs::read_to_string(&start_path) {
188            Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
189                Ok(v) => (
190                    v.get("base_sha")
191                        .and_then(|s| s.as_str())
192                        .map(str::trim)
193                        .filter(|s| !s.is_empty())
194                        .map(String::from),
195                    v.get("comments")
196                        .and_then(|s| s.as_str())
197                        .map(str::trim)
198                        .filter(|s| !s.is_empty())
199                        .map(String::from),
200                ),
201                Err(e) => {
202                    return Err(format!("cannot parse {}: {e}", start_path.display()));
203                }
204            },
205            Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
206            Err(e) => {
207                return Err(format!("cannot read {}: {e}", start_path.display()));
208            }
209        };
210
211    if let Some(hook) = before_git {
212        hook();
213    }
214
215    let base = if let Some(sha) = start_base_sha {
216        let out = Command::new("git")
217            .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
218            .current_dir(root)
219            .output()
220            .map_err(|e| format!("cannot run git cat-file in {}: {e}", root.display()))?;
221        if !out.status.success() {
222            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
223            return Err(format!(
224                "run {id} started from {sha}, which is not in this repository (git cat-file in {}: {stderr})",
225                root.display()
226            ));
227        }
228        sha
229    } else {
230        let root_head = Command::new("git")
231            .args(["rev-parse", "HEAD"])
232            .current_dir(root)
233            .output();
234        let root_head_sha = match root_head {
235            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
236            _ => {
237                return Err("could not resolve root HEAD".to_string());
238            }
239        };
240
241        match run_git_in_wt(wt, &["merge-base", "HEAD", &root_head_sha]) {
242            WtGit::WorktreeGone => return Ok(None),
243            WtGit::Output(o) if o.status.success() => {
244                String::from_utf8_lossy(&o.stdout).trim().to_string()
245            }
246            _ => {
247                return Err(format!(
248                    "cannot find where run {id} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}"
249                ));
250            }
251        }
252    };
253
254    let range = format!("{base}..HEAD");
255
256    let commits_out = match run_git_in_wt(wt, &["log", "--oneline", &range]) {
257        WtGit::WorktreeGone => return Ok(None),
258        WtGit::Output(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(),
259        WtGit::IoErr(_) => String::new(),
260    };
261
262    let files_out = match run_git_in_wt(wt, &["diff", "--stat", &range]) {
263        WtGit::WorktreeGone => return Ok(None),
264        WtGit::Output(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(),
265        WtGit::IoErr(_) => String::new(),
266    };
267
268    let tree_out = match run_git_in_wt(wt, &["status", "--short"]) {
269        WtGit::WorktreeGone => return Ok(None),
270        WtGit::Output(o) => String::from_utf8_lossy(&o.stdout).trim().to_string(),
271        WtGit::IoErr(_) => String::new(),
272    };
273
274    let diff_res: Option<Result<String, String>> = if !is_research {
275        match run_git_in_wt(wt, &["diff", &range]) {
276            WtGit::WorktreeGone => return Ok(None),
277            WtGit::IoErr(e) => Some(Err(e.to_string())),
278            WtGit::Output(o) => Some(if o.status.success() {
279                Ok(String::from_utf8_lossy(&o.stdout).into_owned())
280            } else {
281                let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
282                if stderr.is_empty() {
283                    Err(format!("exit {}", o.status))
284                } else {
285                    Err(stderr)
286                }
287            }),
288        }
289    } else if include_diff_for_research {
290        match run_git_in_wt(wt, &["diff", &range]) {
291            WtGit::WorktreeGone => return Ok(None),
292            WtGit::IoErr(e) => Some(Err(e.to_string())),
293            WtGit::Output(o) => Some(Ok(String::from_utf8_lossy(&o.stdout).into_owned())),
294        }
295    } else {
296        None
297    };
298
299    let diff_out = diff_res
300        .as_ref()
301        .and_then(|r| r.as_ref().ok())
302        .map(|s| s.trim().to_string())
303        .unwrap_or_default();
304
305    let task_text: Option<String> = (|| {
306        let start_file = root.join(".wt").join(format!("{id}.start.json"));
307        let content = std::fs::read_to_string(&start_file).ok()?;
308        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
309        let task_file = val.get("task_file")?.as_str()?;
310        let p = Path::new(task_file);
311        if let Ok(s) = std::fs::read_to_string(p) {
312            return Some(s);
313        }
314        std::fs::read_to_string(root.join(p)).ok()
315    })();
316
317    let changed_files: Vec<String> = match run_git_in_wt(wt, &["diff", "--name-only", &range]) {
318        WtGit::WorktreeGone => return Ok(None),
319        WtGit::Output(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
320            .lines()
321            .map(|l| l.trim().to_string())
322            .filter(|l| !l.is_empty())
323            .collect(),
324        _ => Vec::new(),
325    };
326
327    let subjects: Vec<String> = match run_git_in_wt(wt, &["log", "--format=%s", &range]) {
328        WtGit::WorktreeGone => return Ok(None),
329        WtGit::Output(o) if o.status.success() => String::from_utf8_lossy(&o.stdout)
330            .lines()
331            .map(|l| l.trim().to_string())
332            .filter(|l| !l.is_empty())
333            .collect(),
334        _ => Vec::new(),
335    };
336
337    Ok(Some(WorktreeGitData {
338        base,
339        start_comments,
340        commits_out,
341        files_out,
342        tree_out,
343        diff_res,
344        diff_out,
345        task_text,
346        changed_files,
347        subjects,
348    }))
349}
350
351pub(crate) fn compute_review(
352    root: &Path,
353    id: &str,
354    include_diff_for_research: bool,
355) -> Result<ReviewComputation, String> {
356    compute_review_res(root, id, include_diff_for_research, None, None)
357        .map_err(ReviewError::into_message)
358}
359
360fn compute_review_res(
361    root: &Path,
362    id: &str,
363    include_diff_for_research: bool,
364    summary_worktree_fallback: Option<&Path>,
365    before_git: Option<&dyn Fn()>,
366) -> Result<ReviewComputation, ReviewError> {
367    let wt = root.join(".wt").join(id);
368    let mut wt_exists = wt_present(&wt);
369    let is_research = crate::clean::is_research(root, id)
370        || root.join(".wt").join(format!("{id}.report.md")).exists();
371    let report_file = root.join(".wt").join(format!("{id}.report.json"));
372    let missing_wt_err = |wt: &Path| -> Option<ReviewError> {
373        if !is_research {
374            return Some(ReviewError::WorktreeGone(format!(
375                "worktree {} does not exist",
376                wt.display()
377            )));
378        }
379        if !report_file.exists() {
380            return Some(ReviewError::WorktreeGone(format!(
381                "worktree {} does not exist and {} is missing: nothing to review",
382                wt.display(),
383                report_file.display()
384            )));
385        }
386        None
387    };
388    if !wt_exists {
389        if let Some(err) = missing_wt_err(&wt) {
390            return Err(err);
391        }
392    }
393
394    let git_data = if wt_exists {
395        match read_worktree_git_data(
396            root,
397            id,
398            &wt,
399            is_research,
400            include_diff_for_research,
401            before_git,
402        ) {
403            Ok(Some(data)) => data,
404            Ok(None) => {
405                wt_exists = false;
406                if let Some(err) = missing_wt_err(&wt) {
407                    return Err(err);
408                }
409                WorktreeGitData::empty()
410            }
411            Err(e) => return Err(ReviewError::Other(e)),
412        }
413    } else {
414        WorktreeGitData::empty()
415    };
416
417    let WorktreeGitData {
418        base,
419        start_comments,
420        commits_out,
421        files_out,
422        tree_out,
423        diff_res,
424        diff_out,
425        task_text,
426        changed_files,
427        subjects,
428    } = git_data;
429
430    let log_file = root.join(".wt").join(format!("{id}.log"));
431    let log_content_opt = std::fs::read_to_string(&log_file).ok();
432    let (hcmds, reads, (refused_count, refused_paths)) =
433        if let Some(ref log_content) = log_content_opt {
434            let hcmds = host_commands(log_content);
435            let home = std::env::var_os("HOME")
436                .map(PathBuf::from)
437                .unwrap_or_else(|| PathBuf::from("/"));
438            let allowed = [root.to_path_buf(), wt.clone()];
439            let reads = outside_reads(log_content, &allowed, &home);
440            let refused = refused_reads(log_content);
441            (hcmds, reads, refused)
442        } else {
443            (Vec::new(), Vec::new(), (0, Vec::new()))
444        };
445
446    let report_val = std::fs::read_to_string(&report_file)
447        .ok()
448        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
449    let outcome = report_val
450        .as_ref()
451        .and_then(|v| v.get("outcome"))
452        .and_then(|x| x.as_str());
453    let quote_problems: Option<Vec<String>> = report_val
454        .as_ref()
455        .and_then(|v| v.get("quote_problems"))
456        .and_then(|x| x.as_array())
457        .map(|arr| {
458            arr.iter()
459                .filter_map(|x| x.as_str().map(String::from))
460                .collect()
461        });
462    let read_loop = report_val
463        .as_ref()
464        .and_then(|v| v.get("read_loop"))
465        .and_then(|x| x.as_bool())
466        .unwrap_or(false);
467    let gate_left_out: Vec<String> = report_val
468        .as_ref()
469        .and_then(|v| v.get("gate_left_out"))
470        .and_then(|x| x.as_array())
471        .map(|arr| {
472            arr.iter()
473                .filter_map(|x| x.as_str().map(String::from))
474                .collect::<Vec<_>>()
475        })
476        .filter(|v| !v.is_empty())
477        .or_else(|| {
478            let start_file = root.join(".wt").join(format!("{id}.start.json"));
479            let content = std::fs::read_to_string(&start_file).ok()?;
480            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
481            let arr = val.get("gate_left_out")?.as_array()?;
482            Some(
483                arr.iter()
484                    .filter_map(|item| {
485                        let cmd = item.get("command")?.as_str()?;
486                        let reason = item.get("reason")?.as_str()?;
487                        Some(format!("{cmd} ({reason})"))
488                    })
489                    .collect(),
490            )
491        })
492        .unwrap_or_default();
493    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
494        .as_ref()
495        .and_then(|v| v.get("claim_check"))
496        .and_then(|x| serde_json::from_value(x.clone()).ok());
497    let claim_check_skipped: Option<String> = report_val
498        .as_ref()
499        .and_then(|v| v.get("claim_check_skipped"))
500        .and_then(|x| x.as_str())
501        .map(String::from);
502
503    let mut checks = if wt_exists {
504        crate::review_checks::build(
505            task_text.as_deref(),
506            &changed_files,
507            &subjects,
508            hcmds.len(),
509            reads.len(),
510            outcome,
511        )
512    } else {
513        crate::review_checks::build(
514            Some(""),
515            &[String::new()],
516            &[],
517            hcmds.len(),
518            reads.len(),
519            outcome,
520        )
521    };
522    let mut fallbacks: Vec<crate::fallback_check::Finding> = Vec::new();
523    if !is_research {
524        if let Some(ref res) = diff_res {
525            match res {
526                Ok(diff) => {
527                    fallbacks = crate::fallback_check::added_fallbacks(diff);
528                    if start_comments.as_deref() != Some("off") {
529                        let wt_gone = std::cell::Cell::new(false);
530                        match crate::comment_lint::added_comments(
531                            diff,
532                            &|path| match run_git_in_wt(&wt, &["show", &format!("HEAD:{path}")]) {
533                                WtGit::WorktreeGone => {
534                                    wt_gone.set(true);
535                                    Err(format!("worktree {} does not exist", wt.display()))
536                                }
537                                WtGit::IoErr(e) => Err(e.to_string()),
538                                WtGit::Output(o) => {
539                                    if o.status.success() {
540                                        Ok(String::from_utf8_lossy(&o.stdout).into_owned())
541                                    } else {
542                                        let stderr =
543                                            String::from_utf8_lossy(&o.stderr).trim().to_string();
544                                        if stderr.is_empty() {
545                                            Err(format!("exit {}", o.status))
546                                        } else {
547                                            Err(stderr)
548                                        }
549                                    }
550                                }
551                            },
552                        ) {
553                            Ok(comments) => {
554                                if let Some(flag) = crate::comment_lint::flag(&comments) {
555                                    checks.flags.push(flag);
556                                }
557                            }
558                            Err(reason) => {
559                                if wt_gone.get() {
560                                    return Err(ReviewError::WorktreeGone(format!(
561                                        "worktree {} does not exist",
562                                        wt.display()
563                                    )));
564                                }
565                                let first_line = reason.lines().next().unwrap_or(reason.as_str());
566                                let msg = format!("comment check not run: {first_line}");
567                                let cut: String = msg.chars().take(200).collect();
568                                checks.flags.push(cut);
569                            }
570                        }
571                    }
572                }
573                Err(reason) => {
574                    let first_line = reason.lines().next().unwrap_or(reason.as_str());
575                    let msg = format!("fallback check not run: git diff failed: {first_line}");
576                    let cut: String = msg.chars().take(200).collect();
577                    checks.flags.push(cut);
578                }
579            }
580        }
581        let summary_path = root.join(".wt").join(format!("{id}.json"));
582        match std::fs::read_to_string(&summary_path) {
583            Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
584                Ok(v) => match crate::outside_env::summary_worktree(&v) {
585                    Ok(summary_wt) => {
586                        if let Some(ref log_content) = log_content_opt {
587                            let borrowed =
588                                crate::outside_env::borrowed_env_commands(log_content, &summary_wt);
589                            if let Some(flag) = crate::outside_env::flag(&borrowed) {
590                                checks.flags.push(flag);
591                            }
592                        }
593                    }
594                    Err(e) => {
595                        checks.flags.push(format!("outside-env check not run: {e}"));
596                    }
597                },
598                Err(e) => {
599                    checks.flags.push(format!(
600                        "outside-env check not run: cannot parse {}: {e}",
601                        summary_path.display()
602                    ));
603                }
604            },
605            Err(e) if e.kind() == std::io::ErrorKind::NotFound && log_content_opt.is_none() => {}
606            Err(e)
607                if e.kind() == std::io::ErrorKind::NotFound
608                    && summary_worktree_fallback.is_some() =>
609            {
610                if let (Some(summary_wt), Some(ref log_content)) =
611                    (summary_worktree_fallback, &log_content_opt)
612                {
613                    let borrowed =
614                        crate::outside_env::borrowed_env_commands(log_content, summary_wt);
615                    if let Some(flag) = crate::outside_env::flag(&borrowed) {
616                        checks.flags.push(flag);
617                    }
618                }
619            }
620            Err(e) => {
621                checks.flags.push(format!(
622                    "outside-env check not run: cannot read {}: {e}",
623                    summary_path.display()
624                ));
625            }
626        }
627    }
628    if let Some(ref problems) = quote_problems {
629        if !problems.is_empty() {
630            checks.flags.push(format!(
631                "quote check failed ({} problem(s)): see == report",
632                problems.len()
633            ));
634        }
635    }
636    if read_loop {
637        checks.flags.push(
638            "read loop: the run kept re-reading the same files without changing anything and was stopped"
639                .to_string(),
640        );
641    }
642    if !gate_left_out.is_empty() {
643        checks
644            .flags
645            .push(format!("gate left out: {}", gate_left_out.join("; ")));
646    }
647    if let Some(ref cc) = claim_check {
648        if !cc.contradicted.is_empty() {
649            checks.flags.push(format!(
650                "claim check: {} contradicted claims",
651                cc.contradicted.len()
652            ));
653        }
654    }
655    if let Some(ref skipped) = claim_check_skipped {
656        checks.flags.push(format!("claim check skipped: {skipped}"));
657    }
658    if refused_count > 0 {
659        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
660        checks.flags.push(format!(
661            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
662            first_3.join(", ")
663        ));
664    }
665    if is_research {
666        match &report_val {
667            Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
668                Ok((large, total)) => {
669                    if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
670                        checks.flags.push(flag);
671                    }
672                }
673                Err(e) => {
674                    checks.flags.push(format!("breadth check not run: {e}"));
675                }
676            },
677            None => {
678                checks.flags.push(format!(
679                    "breadth check not run: cannot read {}",
680                    report_file.display()
681                ));
682            }
683        }
684        if outcome == Some("budget_exhausted") {
685            match std::fs::read_to_string(&log_file) {
686                Ok(log) => {
687                    let dirs = crate::research_breadth::read_dirs(&log, root);
688                    if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
689                        checks.flags.push(flag);
690                    }
691                }
692                Err(e) => {
693                    checks.flags.push(format!("split suggestion not run: {e}"));
694                }
695            }
696        }
697    }
698
699    Ok(ReviewComputation {
700        wt,
701        wt_exists,
702        is_research,
703        base,
704        task_text,
705        changed_files,
706        commits_out,
707        files_out,
708        tree_out,
709        diff_out,
710        hcmds,
711        reads,
712        report_val,
713        quote_problems,
714        claim_check,
715        claim_check_skipped,
716        checks,
717        fallbacks,
718    })
719}
720
721pub fn read_stored_model_review(
722    root: &Path,
723    id: &str,
724) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
725    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
726    let raw = match std::fs::read_to_string(&checks_path) {
727        Ok(s) => s,
728        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
729        Err(e) => return Err(format!("cannot read {}: {e}", checks_path.display())),
730    };
731    let val: serde_json::Value = serde_json::from_str(&raw)
732        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
733    parse_stored_model_review(&checks_path, &val)
734}
735
736pub(crate) fn parse_stored_model_review(
737    checks_path: &Path,
738    val: &serde_json::Value,
739) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
740    let Some(obj) = val.as_object() else {
741        return Err(format!(
742            "cannot parse {}: expected a JSON object",
743            checks_path.display()
744        ));
745    };
746    let Some(mr) = obj.get("model_review") else {
747        return Ok(None);
748    };
749    if mr.is_null() {
750        return Ok(None);
751    }
752    serde_json::from_value(mr.clone())
753        .map(Some)
754        .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))
755}
756
757pub(crate) fn write_checks_file(
758    root: &Path,
759    id: &str,
760    flags: &[String],
761    fallbacks: &[crate::fallback_check::Finding],
762    model_review: Option<&crate::model_review::ModelReviewResult>,
763) -> Result<(), String> {
764    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
765    let ts = std::time::SystemTime::now()
766        .duration_since(std::time::UNIX_EPOCH)
767        .map_err(|e| format!("error: the system clock is before 1970: {e}"))?
768        .as_secs();
769    let annotated_fallbacks = crate::fallback_check::annotate_fallbacks(fallbacks, model_review);
770    let mut checks_obj = serde_json::json!({
771        "ts": ts,
772        "flags": flags,
773        "fallbacks": annotated_fallbacks,
774    });
775    if let Some(mr) = model_review {
776        checks_obj["model_review"] = serde_json::to_value(mr).map_err(|e| {
777            format!(
778                "error serializing model review for {}: {e}",
779                checks_path.display()
780            )
781        })?;
782    }
783    let checks_json = serde_json::to_string_pretty(&checks_obj)
784        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))?;
785    std::fs::write(&checks_path, checks_json + "\n")
786        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))
787}
788
789pub fn evaluate_verified_run(
790    root: &Path,
791    id: &str,
792) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
793    evaluate_verified_run_with(root, id, false, crate::model_review::run)
794}
795
796pub fn evaluate_verified_run_with<F>(
797    root: &Path,
798    id: &str,
799    force_review: bool,
800    run_model_review: F,
801) -> Result<Option<crate::model_review::ModelReviewResult>, String>
802where
803    F: FnOnce(&Path, &str, &str, &Path) -> crate::model_review::ModelReviewResult,
804{
805    let wt_fallback = root.join(".wt").join(id);
806    let data = compute_review_res(root, id, false, Some(&wt_fallback), None)
807        .map_err(ReviewError::into_message)?;
808    let mut flags = data.checks.flags;
809    if data.is_research || !data.wt_exists {
810        flags.extend(crate::fallback_check::flags_for_review(
811            &data.fallbacks,
812            None,
813        ));
814        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
815        return Ok(None);
816    }
817
818    let risky_matches = match crate::config::load_with_fallback(root) {
819        Ok(Some((cfg, _))) => {
820            match crate::config::match_risky_paths(&cfg.review.risky, &data.changed_files) {
821                Ok(matches) => matches,
822                Err(e) => {
823                    flags.push(format!("risky path check not run: {e}"));
824                    Vec::new()
825                }
826            }
827        }
828        Ok(None) => Vec::new(),
829        Err(e) => {
830            flags.push(format!("risky path check not run: {e}"));
831            Vec::new()
832        }
833    };
834
835    if force_review
836        || crate::review_checks::should_run_model_review(
837            &flags,
838            data.task_text.as_deref(),
839            &risky_matches,
840            data.fallbacks.len(),
841        )
842    {
843        let result = run_model_review(root, id, &data.base, &data.wt);
844        flags.extend(crate::fallback_check::flags_for_review(
845            &data.fallbacks,
846            Some(&result),
847        ));
848        if let Some(flag) = result.flag() {
849            flags.push(flag);
850        }
851        write_checks_file(root, id, &flags, &data.fallbacks, Some(&result))?;
852        Ok(Some(result))
853    } else {
854        let review_path = root.join(".wt").join(format!("{id}.model-review.json"));
855        if review_path.exists() {
856            std::fs::remove_file(&review_path)
857                .map_err(|e| format!("cannot remove {}: {e}", review_path.display()))?;
858        }
859        flags.extend(crate::fallback_check::flags_for_review(
860            &data.fallbacks,
861            None,
862        ));
863        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
864        Ok(None)
865    }
866}
867
868pub fn ensure_checks(root: &Path, id: &str) -> Result<bool, String> {
869    ensure_checks_with_hook(root, id, None)
870}
871
872fn ensure_checks_with_hook(
873    root: &Path,
874    id: &str,
875    before_git: Option<&dyn Fn()>,
876) -> Result<bool, String> {
877    let wt_dir = root.join(".wt");
878    let summary_path = wt_dir.join(format!("{id}.json"));
879    if !summary_path.is_file() {
880        return Err(format!("no finished run {id} in {}", wt_dir.display()));
881    }
882    let checks_path = wt_dir.join(format!("{id}.checks.json"));
883    if checks_path.exists() {
884        return Ok(false);
885    }
886    let data = match compute_review_res(root, id, false, None, before_git) {
887        Ok(data) => data,
888        Err(ReviewError::WorktreeGone(_)) => return Ok(false),
889        Err(ReviewError::Other(e)) => return Err(e),
890    };
891    if !data.wt_exists {
892        return Ok(false);
893    }
894    let mut flags = data.checks.flags;
895    flags.extend(crate::fallback_check::flags_for_review(
896        &data.fallbacks,
897        None,
898    ));
899    write_checks_file(root, id, &flags, &data.fallbacks, None)?;
900    Ok(true)
901}
902
903pub fn set_hold(root: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
904    let trimmed = note.trim();
905    if trimmed.is_empty() {
906        return Err(format!("a note is required to hold run {id}"));
907    }
908    let wt_dir = root.join(".wt");
909    std::fs::create_dir_all(&wt_dir)
910        .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
911    let hold_path = wt_dir.join(format!("{id}.hold.json"));
912    let hold = Hold {
913        note: trimmed.to_string(),
914        ts: now,
915    };
916    let json_str =
917        serde_json::to_string_pretty(&hold).map_err(|e| format!("error serializing hold: {e}"))?;
918    std::fs::write(&hold_path, json_str + "\n")
919        .map_err(|e| format!("error writing {}: {e}", hold_path.display()))
920}
921
922pub fn clear_hold(root: &Path, id: &str) -> Result<(), String> {
923    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
924    match std::fs::remove_file(&hold_path) {
925        Ok(()) => Ok(()),
926        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
927        Err(e) => Err(format!("error removing {}: {e}", hold_path.display())),
928    }
929}
930
931pub fn read_hold(root: &Path, id: &str) -> Result<Option<Hold>, String> {
932    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
933    let raw = match std::fs::read_to_string(&hold_path) {
934        Ok(s) => s,
935        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
936        Err(e) => return Err(format!("error reading {}: {e}", hold_path.display())),
937    };
938    serde_json::from_str::<Hold>(&raw)
939        .map(Some)
940        .map_err(|e| format!("could not parse {}: {e}", hold_path.display()))
941}
942
943pub fn decide(
944    root: &Path,
945    id: &str,
946    action: Action,
947    note: Option<&str>,
948    now: u64,
949) -> Result<Decision, String> {
950    let wt_dir = root.join(".wt");
951    let summary_path = wt_dir.join(format!("{id}.json"));
952    let summary_raw = match std::fs::read_to_string(&summary_path) {
953        Ok(s) => s,
954        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
955            return Err(format!("no finished run {id} in {}", wt_dir.display()));
956        }
957        Err(e) => {
958            return Err(format!("error reading {}: {e}", summary_path.display()));
959        }
960    };
961    let summary: serde_json::Value = serde_json::from_str(&summary_raw)
962        .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
963    let outcome = summary
964        .get("outcome")
965        .and_then(|v| v.as_str())
966        .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
967    let is_research =
968        crate::clean::is_research(root, id) || wt_dir.join(format!("{id}.report.md")).exists();
969
970    let trimmed_note: Option<String> = note
971        .map(str::trim)
972        .filter(|s| !s.is_empty())
973        .map(String::from);
974
975    let orchestrator_message = match action {
976        Action::Accept => {
977            if is_research {
978                return Err(format!("run {id} is a research run; mark it read"));
979            }
980            if outcome != "verified" {
981                return Err(format!(
982                    "run {id} is {outcome}, not verified; it cannot be accepted"
983                ));
984            }
985            record_verdict(
986                root,
987                id,
988                ReviewVerdict::Accepted,
989                trimmed_note.as_deref().unwrap_or(""),
990                now,
991            )?;
992            clear_hold(root, id)?;
993            None
994        }
995        Action::SendBack => {
996            let Some(ref text) = trimmed_note else {
997                return Err(format!("a note is required to send back run {id}"));
998            };
999            clear_hold(root, id)?;
1000            Some(format!(
1001                "Send back run {id}: {text} Draft a follow-up task for me to confirm."
1002            ))
1003        }
1004        Action::Redo => {
1005            record_verdict(
1006                root,
1007                id,
1008                ReviewVerdict::Redone,
1009                trimmed_note.as_deref().unwrap_or(""),
1010                now,
1011            )?;
1012            clear_hold(root, id)?;
1013            let msg = match trimmed_note.as_deref() {
1014                Some(text) => format!("Redo run {id}. Reason: {text}"),
1015                None => format!("Redo run {id}."),
1016            };
1017            Some(msg)
1018        }
1019        Action::Hold => {
1020            let Some(ref text) = trimmed_note else {
1021                return Err(format!("a note is required to hold run {id}"));
1022            };
1023            set_hold(root, id, text, now)?;
1024            None
1025        }
1026        Action::MarkRead => {
1027            if !is_research {
1028                return Err(format!("run {id} is not a research run"));
1029            }
1030            record_verdict(root, id, ReviewVerdict::Accepted, "read", now)?;
1031            clear_hold(root, id)?;
1032            None
1033        }
1034    };
1035
1036    Ok(Decision {
1037        run: id.to_string(),
1038        action,
1039        note: trimmed_note,
1040        orchestrator_message,
1041    })
1042}
1043
1044#[cfg(test)]
1045mod tests {
1046    use super::*;
1047
1048    fn git(dir: &Path, args: &[&str]) -> String {
1049        let out = Command::new("git")
1050            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1051            .args(args)
1052            .current_dir(dir)
1053            .output()
1054            .unwrap();
1055        assert!(
1056            out.status.success(),
1057            "git {args:?} failed: {}",
1058            String::from_utf8_lossy(&out.stderr)
1059        );
1060        String::from_utf8_lossy(&out.stdout).trim().to_string()
1061    }
1062
1063    fn init_repo() -> (tempfile::TempDir, String) {
1064        let d = tempfile::tempdir().unwrap();
1065        git(d.path(), &["init", "-q"]);
1066        std::fs::write(d.path().join("f.txt"), "hello\n").unwrap();
1067        git(d.path(), &["add", "."]);
1068        git(d.path(), &["commit", "-qm", "init", "--no-gpg-sign"]);
1069        std::fs::create_dir_all(d.path().join(".wt")).unwrap();
1070        let head = git(d.path(), &["rev-parse", "HEAD"]);
1071        (d, head)
1072    }
1073
1074    fn setup_finished_code_run(root: &Path, id: &str, base_sha: Option<&str>) {
1075        let wt_path = root.join(".wt").join(id);
1076        git(
1077            root,
1078            &[
1079                "worktree",
1080                "add",
1081                "-q",
1082                "-b",
1083                &format!("wip/{id}"),
1084                wt_path.to_str().unwrap(),
1085                "HEAD",
1086            ],
1087        );
1088        let mut start = serde_json::json!({
1089            "id": id,
1090            "pid": 999999,
1091            "started_at": 1000,
1092            "research": false,
1093        });
1094        if let Some(sha) = base_sha {
1095            start["base_sha"] = serde_json::json!(sha);
1096        }
1097        std::fs::write(
1098            root.join(".wt").join(format!("{id}.start.json")),
1099            start.to_string(),
1100        )
1101        .unwrap();
1102        std::fs::write(
1103            root.join(".wt").join(format!("{id}.report.json")),
1104            serde_json::json!({ "outcome": "error", "turns": 0 }).to_string(),
1105        )
1106        .unwrap();
1107        std::fs::write(
1108            root.join(".wt").join(format!("{id}.json")),
1109            serde_json::json!({
1110                "outcome": "error",
1111                "seconds": 1,
1112                "final_message": "",
1113                "commits": [],
1114                "changed_files": []
1115            })
1116            .to_string(),
1117        )
1118        .unwrap();
1119    }
1120
1121    #[test]
1122    fn ensure_checks_skips_when_worktree_vanishes_before_git_commands() {
1123        let (d, head) = init_repo();
1124        setup_finished_code_run(d.path(), "M2", Some(&head));
1125        let root = d.path().to_path_buf();
1126        let remove_wt = move || {
1127            let wt = root.join(".wt/M2");
1128            let status = Command::new("git")
1129                .args(["worktree", "remove", "--force"])
1130                .arg(&wt)
1131                .current_dir(&root)
1132                .status()
1133                .unwrap();
1134            assert!(status.success());
1135        };
1136
1137        let wrote = ensure_checks_with_hook(d.path(), "M2", Some(&remove_wt)).unwrap();
1138        assert!(!wrote);
1139        assert!(!d.path().join(".wt/M2").exists());
1140        assert!(!d.path().join(".wt/M2.checks.json").exists());
1141    }
1142
1143    #[test]
1144    fn ensure_checks_skips_when_worktree_vanishes_without_base_sha() {
1145        let (d, _head) = init_repo();
1146        setup_finished_code_run(d.path(), "M3", None);
1147        let root = d.path().to_path_buf();
1148        let remove_wt = move || {
1149            let wt = root.join(".wt/M3");
1150            let status = Command::new("git")
1151                .args(["worktree", "remove", "--force"])
1152                .arg(&wt)
1153                .current_dir(&root)
1154                .status()
1155                .unwrap();
1156            assert!(status.success());
1157        };
1158
1159        let wrote = ensure_checks_with_hook(d.path(), "M3", Some(&remove_wt)).unwrap();
1160        assert!(!wrote);
1161        assert!(!d.path().join(".wt/M3.checks.json").exists());
1162    }
1163
1164    #[test]
1165    fn ensure_checks_still_errors_when_base_sha_is_not_in_repository() {
1166        let (d, _head) = init_repo();
1167        let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1168        setup_finished_code_run(d.path(), "BAD1", Some(missing));
1169
1170        let err = ensure_checks(d.path(), "BAD1").unwrap_err();
1171        assert!(
1172            err.contains(&format!(
1173                "run BAD1 started from {missing}, which is not in this repository"
1174            )),
1175            "unexpected error: {err}"
1176        );
1177    }
1178
1179    #[test]
1180    fn research_review_uses_no_worktree_path_when_worktree_vanishes_mid_read() {
1181        let (d, _head) = init_repo();
1182        let wt = d.path().join(".wt/R1");
1183        std::fs::create_dir_all(&wt).unwrap();
1184        git(&wt, &["init", "-q"]);
1185        git(
1186            &wt,
1187            &[
1188                "commit",
1189                "-q",
1190                "--allow-empty",
1191                "-m",
1192                "research",
1193                "--no-gpg-sign",
1194            ],
1195        );
1196        std::fs::write(
1197            d.path().join(".wt/R1.start.json"),
1198            serde_json::json!({ "id": "R1", "research": true }).to_string(),
1199        )
1200        .unwrap();
1201        std::fs::write(
1202            d.path().join(".wt/R1.report.json"),
1203            serde_json::json!({ "outcome": "verified", "turns": 1 }).to_string(),
1204        )
1205        .unwrap();
1206
1207        let wt_to_remove = wt.clone();
1208        let remove_wt = move || {
1209            std::fs::remove_dir_all(&wt_to_remove).unwrap();
1210        };
1211        let data = compute_review_res(d.path(), "R1", false, None, Some(&remove_wt))
1212            .map_err(ReviewError::into_message)
1213            .unwrap();
1214        assert!(!data.wt_exists);
1215        assert!(data.is_research);
1216    }
1217}