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                    let findings = crate::fallback_check::added_fallbacks(diff);
528                    if let Some(flag) = crate::fallback_check::flag(&findings) {
529                        checks.flags.push(flag);
530                    }
531                    fallbacks = findings;
532                    if start_comments.as_deref() != Some("off") {
533                        let wt_gone = std::cell::Cell::new(false);
534                        match crate::comment_lint::added_comments(
535                            diff,
536                            &|path| match run_git_in_wt(&wt, &["show", &format!("HEAD:{path}")]) {
537                                WtGit::WorktreeGone => {
538                                    wt_gone.set(true);
539                                    Err(format!("worktree {} does not exist", wt.display()))
540                                }
541                                WtGit::IoErr(e) => Err(e.to_string()),
542                                WtGit::Output(o) => {
543                                    if o.status.success() {
544                                        Ok(String::from_utf8_lossy(&o.stdout).into_owned())
545                                    } else {
546                                        let stderr =
547                                            String::from_utf8_lossy(&o.stderr).trim().to_string();
548                                        if stderr.is_empty() {
549                                            Err(format!("exit {}", o.status))
550                                        } else {
551                                            Err(stderr)
552                                        }
553                                    }
554                                }
555                            },
556                        ) {
557                            Ok(comments) => {
558                                if let Some(flag) = crate::comment_lint::flag(&comments) {
559                                    checks.flags.push(flag);
560                                }
561                            }
562                            Err(reason) => {
563                                if wt_gone.get() {
564                                    return Err(ReviewError::WorktreeGone(format!(
565                                        "worktree {} does not exist",
566                                        wt.display()
567                                    )));
568                                }
569                                let first_line = reason.lines().next().unwrap_or(reason.as_str());
570                                let msg = format!("comment check not run: {first_line}");
571                                let cut: String = msg.chars().take(200).collect();
572                                checks.flags.push(cut);
573                            }
574                        }
575                    }
576                }
577                Err(reason) => {
578                    let first_line = reason.lines().next().unwrap_or(reason.as_str());
579                    let msg = format!("fallback check not run: git diff failed: {first_line}");
580                    let cut: String = msg.chars().take(200).collect();
581                    checks.flags.push(cut);
582                }
583            }
584        }
585        let summary_path = root.join(".wt").join(format!("{id}.json"));
586        match std::fs::read_to_string(&summary_path) {
587            Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
588                Ok(v) => match crate::outside_env::summary_worktree(&v) {
589                    Ok(summary_wt) => {
590                        if let Some(ref log_content) = log_content_opt {
591                            let borrowed =
592                                crate::outside_env::borrowed_env_commands(log_content, &summary_wt);
593                            if let Some(flag) = crate::outside_env::flag(&borrowed) {
594                                checks.flags.push(flag);
595                            }
596                        }
597                    }
598                    Err(e) => {
599                        checks.flags.push(format!("outside-env check not run: {e}"));
600                    }
601                },
602                Err(e) => {
603                    checks.flags.push(format!(
604                        "outside-env check not run: cannot parse {}: {e}",
605                        summary_path.display()
606                    ));
607                }
608            },
609            Err(e) if e.kind() == std::io::ErrorKind::NotFound && log_content_opt.is_none() => {}
610            Err(e)
611                if e.kind() == std::io::ErrorKind::NotFound
612                    && summary_worktree_fallback.is_some() =>
613            {
614                if let (Some(summary_wt), Some(ref log_content)) =
615                    (summary_worktree_fallback, &log_content_opt)
616                {
617                    let borrowed =
618                        crate::outside_env::borrowed_env_commands(log_content, summary_wt);
619                    if let Some(flag) = crate::outside_env::flag(&borrowed) {
620                        checks.flags.push(flag);
621                    }
622                }
623            }
624            Err(e) => {
625                checks.flags.push(format!(
626                    "outside-env check not run: cannot read {}: {e}",
627                    summary_path.display()
628                ));
629            }
630        }
631    }
632    if let Some(ref problems) = quote_problems {
633        if !problems.is_empty() {
634            checks.flags.push(format!(
635                "quote check failed ({} problem(s)): see == report",
636                problems.len()
637            ));
638        }
639    }
640    if read_loop {
641        checks.flags.push(
642            "read loop: the run kept re-reading the same files without changing anything and was stopped"
643                .to_string(),
644        );
645    }
646    if !gate_left_out.is_empty() {
647        checks
648            .flags
649            .push(format!("gate left out: {}", gate_left_out.join("; ")));
650    }
651    if let Some(ref cc) = claim_check {
652        if !cc.contradicted.is_empty() {
653            checks.flags.push(format!(
654                "claim check: {} contradicted claims",
655                cc.contradicted.len()
656            ));
657        }
658    }
659    if let Some(ref skipped) = claim_check_skipped {
660        checks.flags.push(format!("claim check skipped: {skipped}"));
661    }
662    if refused_count > 0 {
663        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
664        checks.flags.push(format!(
665            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
666            first_3.join(", ")
667        ));
668    }
669    if is_research {
670        match &report_val {
671            Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
672                Ok((large, total)) => {
673                    if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
674                        checks.flags.push(flag);
675                    }
676                }
677                Err(e) => {
678                    checks.flags.push(format!("breadth check not run: {e}"));
679                }
680            },
681            None => {
682                checks.flags.push(format!(
683                    "breadth check not run: cannot read {}",
684                    report_file.display()
685                ));
686            }
687        }
688        if outcome == Some("budget_exhausted") {
689            match std::fs::read_to_string(&log_file) {
690                Ok(log) => {
691                    let dirs = crate::research_breadth::read_dirs(&log, root);
692                    if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
693                        checks.flags.push(flag);
694                    }
695                }
696                Err(e) => {
697                    checks.flags.push(format!("split suggestion not run: {e}"));
698                }
699            }
700        }
701    }
702
703    Ok(ReviewComputation {
704        wt,
705        wt_exists,
706        is_research,
707        base,
708        task_text,
709        changed_files,
710        commits_out,
711        files_out,
712        tree_out,
713        diff_out,
714        hcmds,
715        reads,
716        report_val,
717        quote_problems,
718        claim_check,
719        claim_check_skipped,
720        checks,
721        fallbacks,
722    })
723}
724
725pub fn read_stored_model_review(
726    root: &Path,
727    id: &str,
728) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
729    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
730    let raw = match std::fs::read_to_string(&checks_path) {
731        Ok(s) => s,
732        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
733        Err(e) => return Err(format!("cannot read {}: {e}", checks_path.display())),
734    };
735    let val: serde_json::Value = serde_json::from_str(&raw)
736        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
737    parse_stored_model_review(&checks_path, &val)
738}
739
740pub(crate) fn parse_stored_model_review(
741    checks_path: &Path,
742    val: &serde_json::Value,
743) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
744    let Some(obj) = val.as_object() else {
745        return Err(format!(
746            "cannot parse {}: expected a JSON object",
747            checks_path.display()
748        ));
749    };
750    let Some(mr) = obj.get("model_review") else {
751        return Ok(None);
752    };
753    if mr.is_null() {
754        return Ok(None);
755    }
756    serde_json::from_value(mr.clone())
757        .map(Some)
758        .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))
759}
760
761pub(crate) fn write_checks_file(
762    root: &Path,
763    id: &str,
764    flags: &[String],
765    fallbacks: &[crate::fallback_check::Finding],
766    model_review: Option<&crate::model_review::ModelReviewResult>,
767) -> Result<(), String> {
768    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
769    let ts = std::time::SystemTime::now()
770        .duration_since(std::time::UNIX_EPOCH)
771        .map_err(|e| format!("error: the system clock is before 1970: {e}"))?
772        .as_secs();
773    let mut checks_obj = serde_json::json!({
774        "ts": ts,
775        "flags": flags,
776        "fallbacks": fallbacks,
777    });
778    if let Some(mr) = model_review {
779        checks_obj["model_review"] = serde_json::to_value(mr).map_err(|e| {
780            format!(
781                "error serializing model review for {}: {e}",
782                checks_path.display()
783            )
784        })?;
785    }
786    let checks_json = serde_json::to_string_pretty(&checks_obj)
787        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))?;
788    std::fs::write(&checks_path, checks_json + "\n")
789        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))
790}
791
792pub fn evaluate_verified_run(
793    root: &Path,
794    id: &str,
795) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
796    evaluate_verified_run_with(root, id, crate::model_review::run)
797}
798
799pub fn evaluate_verified_run_with<F>(
800    root: &Path,
801    id: &str,
802    run_model_review: F,
803) -> Result<Option<crate::model_review::ModelReviewResult>, String>
804where
805    F: FnOnce(&Path, &str, &str, &Path) -> crate::model_review::ModelReviewResult,
806{
807    let wt_fallback = root.join(".wt").join(id);
808    let data = compute_review_res(root, id, false, Some(&wt_fallback), None)
809        .map_err(ReviewError::into_message)?;
810    let mut flags = data.checks.flags;
811    if data.is_research || !data.wt_exists {
812        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
813        return Ok(None);
814    }
815
816    let risky_matches = match crate::config::load_with_fallback(root) {
817        Ok(Some((cfg, _))) => {
818            match crate::config::match_risky_paths(&cfg.review.risky, &data.changed_files) {
819                Ok(matches) => matches,
820                Err(e) => {
821                    flags.push(format!("risky path check not run: {e}"));
822                    Vec::new()
823                }
824            }
825        }
826        Ok(None) => Vec::new(),
827        Err(e) => {
828            flags.push(format!("risky path check not run: {e}"));
829            Vec::new()
830        }
831    };
832
833    if crate::review_checks::should_run_model_review(
834        &flags,
835        data.task_text.as_deref(),
836        &risky_matches,
837    ) {
838        let result = run_model_review(root, id, &data.base, &data.wt);
839        if let Some(flag) = result.flag() {
840            flags.push(flag);
841        }
842        write_checks_file(root, id, &flags, &data.fallbacks, Some(&result))?;
843        Ok(Some(result))
844    } else {
845        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
846        Ok(None)
847    }
848}
849
850pub fn ensure_checks(root: &Path, id: &str) -> Result<bool, String> {
851    ensure_checks_with_hook(root, id, None)
852}
853
854fn ensure_checks_with_hook(
855    root: &Path,
856    id: &str,
857    before_git: Option<&dyn Fn()>,
858) -> Result<bool, String> {
859    let wt_dir = root.join(".wt");
860    let summary_path = wt_dir.join(format!("{id}.json"));
861    if !summary_path.is_file() {
862        return Err(format!("no finished run {id} in {}", wt_dir.display()));
863    }
864    let checks_path = wt_dir.join(format!("{id}.checks.json"));
865    if checks_path.exists() {
866        return Ok(false);
867    }
868    let data = match compute_review_res(root, id, false, None, before_git) {
869        Ok(data) => data,
870        Err(ReviewError::WorktreeGone(_)) => return Ok(false),
871        Err(ReviewError::Other(e)) => return Err(e),
872    };
873    if !data.wt_exists {
874        return Ok(false);
875    }
876    write_checks_file(root, id, &data.checks.flags, &data.fallbacks, None)?;
877    Ok(true)
878}
879
880pub fn set_hold(root: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
881    let trimmed = note.trim();
882    if trimmed.is_empty() {
883        return Err(format!("a note is required to hold run {id}"));
884    }
885    let wt_dir = root.join(".wt");
886    std::fs::create_dir_all(&wt_dir)
887        .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
888    let hold_path = wt_dir.join(format!("{id}.hold.json"));
889    let hold = Hold {
890        note: trimmed.to_string(),
891        ts: now,
892    };
893    let json_str =
894        serde_json::to_string_pretty(&hold).map_err(|e| format!("error serializing hold: {e}"))?;
895    std::fs::write(&hold_path, json_str + "\n")
896        .map_err(|e| format!("error writing {}: {e}", hold_path.display()))
897}
898
899pub fn clear_hold(root: &Path, id: &str) -> Result<(), String> {
900    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
901    match std::fs::remove_file(&hold_path) {
902        Ok(()) => Ok(()),
903        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
904        Err(e) => Err(format!("error removing {}: {e}", hold_path.display())),
905    }
906}
907
908pub fn read_hold(root: &Path, id: &str) -> Result<Option<Hold>, String> {
909    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
910    let raw = match std::fs::read_to_string(&hold_path) {
911        Ok(s) => s,
912        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
913        Err(e) => return Err(format!("error reading {}: {e}", hold_path.display())),
914    };
915    serde_json::from_str::<Hold>(&raw)
916        .map(Some)
917        .map_err(|e| format!("could not parse {}: {e}", hold_path.display()))
918}
919
920pub fn decide(
921    root: &Path,
922    id: &str,
923    action: Action,
924    note: Option<&str>,
925    now: u64,
926) -> Result<Decision, String> {
927    let wt_dir = root.join(".wt");
928    let summary_path = wt_dir.join(format!("{id}.json"));
929    let summary_raw = match std::fs::read_to_string(&summary_path) {
930        Ok(s) => s,
931        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
932            return Err(format!("no finished run {id} in {}", wt_dir.display()));
933        }
934        Err(e) => {
935            return Err(format!("error reading {}: {e}", summary_path.display()));
936        }
937    };
938    let summary: serde_json::Value = serde_json::from_str(&summary_raw)
939        .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
940    let outcome = summary
941        .get("outcome")
942        .and_then(|v| v.as_str())
943        .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
944    let is_research =
945        crate::clean::is_research(root, id) || wt_dir.join(format!("{id}.report.md")).exists();
946
947    let trimmed_note: Option<String> = note
948        .map(str::trim)
949        .filter(|s| !s.is_empty())
950        .map(String::from);
951
952    let orchestrator_message = match action {
953        Action::Accept => {
954            if is_research {
955                return Err(format!("run {id} is a research run; mark it read"));
956            }
957            if outcome != "verified" {
958                return Err(format!(
959                    "run {id} is {outcome}, not verified; it cannot be accepted"
960                ));
961            }
962            record_verdict(
963                root,
964                id,
965                ReviewVerdict::Accepted,
966                trimmed_note.as_deref().unwrap_or(""),
967                now,
968            )?;
969            clear_hold(root, id)?;
970            None
971        }
972        Action::SendBack => {
973            let Some(ref text) = trimmed_note else {
974                return Err(format!("a note is required to send back run {id}"));
975            };
976            clear_hold(root, id)?;
977            Some(format!(
978                "Send back run {id}: {text} Draft a follow-up task for me to confirm."
979            ))
980        }
981        Action::Redo => {
982            record_verdict(
983                root,
984                id,
985                ReviewVerdict::Redone,
986                trimmed_note.as_deref().unwrap_or(""),
987                now,
988            )?;
989            clear_hold(root, id)?;
990            let msg = match trimmed_note.as_deref() {
991                Some(text) => format!("Redo run {id}. Reason: {text}"),
992                None => format!("Redo run {id}."),
993            };
994            Some(msg)
995        }
996        Action::Hold => {
997            let Some(ref text) = trimmed_note else {
998                return Err(format!("a note is required to hold run {id}"));
999            };
1000            set_hold(root, id, text, now)?;
1001            None
1002        }
1003        Action::MarkRead => {
1004            if !is_research {
1005                return Err(format!("run {id} is not a research run"));
1006            }
1007            record_verdict(root, id, ReviewVerdict::Accepted, "read", now)?;
1008            clear_hold(root, id)?;
1009            None
1010        }
1011    };
1012
1013    Ok(Decision {
1014        run: id.to_string(),
1015        action,
1016        note: trimmed_note,
1017        orchestrator_message,
1018    })
1019}
1020
1021#[cfg(test)]
1022mod tests {
1023    use super::*;
1024
1025    fn git(dir: &Path, args: &[&str]) -> String {
1026        let out = Command::new("git")
1027            .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1028            .args(args)
1029            .current_dir(dir)
1030            .output()
1031            .unwrap();
1032        assert!(
1033            out.status.success(),
1034            "git {args:?} failed: {}",
1035            String::from_utf8_lossy(&out.stderr)
1036        );
1037        String::from_utf8_lossy(&out.stdout).trim().to_string()
1038    }
1039
1040    fn init_repo() -> (tempfile::TempDir, String) {
1041        let d = tempfile::tempdir().unwrap();
1042        git(d.path(), &["init", "-q"]);
1043        std::fs::write(d.path().join("f.txt"), "hello\n").unwrap();
1044        git(d.path(), &["add", "."]);
1045        git(d.path(), &["commit", "-qm", "init", "--no-gpg-sign"]);
1046        std::fs::create_dir_all(d.path().join(".wt")).unwrap();
1047        let head = git(d.path(), &["rev-parse", "HEAD"]);
1048        (d, head)
1049    }
1050
1051    fn setup_finished_code_run(root: &Path, id: &str, base_sha: Option<&str>) {
1052        let wt_path = root.join(".wt").join(id);
1053        git(
1054            root,
1055            &[
1056                "worktree",
1057                "add",
1058                "-q",
1059                "-b",
1060                &format!("wip/{id}"),
1061                wt_path.to_str().unwrap(),
1062                "HEAD",
1063            ],
1064        );
1065        let mut start = serde_json::json!({
1066            "id": id,
1067            "pid": 999999,
1068            "started_at": 1000,
1069            "research": false,
1070        });
1071        if let Some(sha) = base_sha {
1072            start["base_sha"] = serde_json::json!(sha);
1073        }
1074        std::fs::write(
1075            root.join(".wt").join(format!("{id}.start.json")),
1076            start.to_string(),
1077        )
1078        .unwrap();
1079        std::fs::write(
1080            root.join(".wt").join(format!("{id}.report.json")),
1081            serde_json::json!({ "outcome": "error", "turns": 0 }).to_string(),
1082        )
1083        .unwrap();
1084        std::fs::write(
1085            root.join(".wt").join(format!("{id}.json")),
1086            serde_json::json!({
1087                "outcome": "error",
1088                "seconds": 1,
1089                "final_message": "",
1090                "commits": [],
1091                "changed_files": []
1092            })
1093            .to_string(),
1094        )
1095        .unwrap();
1096    }
1097
1098    #[test]
1099    fn ensure_checks_skips_when_worktree_vanishes_before_git_commands() {
1100        let (d, head) = init_repo();
1101        setup_finished_code_run(d.path(), "M2", Some(&head));
1102        let root = d.path().to_path_buf();
1103        let remove_wt = move || {
1104            let wt = root.join(".wt/M2");
1105            let status = Command::new("git")
1106                .args(["worktree", "remove", "--force"])
1107                .arg(&wt)
1108                .current_dir(&root)
1109                .status()
1110                .unwrap();
1111            assert!(status.success());
1112        };
1113
1114        let wrote = ensure_checks_with_hook(d.path(), "M2", Some(&remove_wt)).unwrap();
1115        assert!(!wrote);
1116        assert!(!d.path().join(".wt/M2").exists());
1117        assert!(!d.path().join(".wt/M2.checks.json").exists());
1118    }
1119
1120    #[test]
1121    fn ensure_checks_skips_when_worktree_vanishes_without_base_sha() {
1122        let (d, _head) = init_repo();
1123        setup_finished_code_run(d.path(), "M3", None);
1124        let root = d.path().to_path_buf();
1125        let remove_wt = move || {
1126            let wt = root.join(".wt/M3");
1127            let status = Command::new("git")
1128                .args(["worktree", "remove", "--force"])
1129                .arg(&wt)
1130                .current_dir(&root)
1131                .status()
1132                .unwrap();
1133            assert!(status.success());
1134        };
1135
1136        let wrote = ensure_checks_with_hook(d.path(), "M3", Some(&remove_wt)).unwrap();
1137        assert!(!wrote);
1138        assert!(!d.path().join(".wt/M3.checks.json").exists());
1139    }
1140
1141    #[test]
1142    fn ensure_checks_still_errors_when_base_sha_is_not_in_repository() {
1143        let (d, _head) = init_repo();
1144        let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1145        setup_finished_code_run(d.path(), "BAD1", Some(missing));
1146
1147        let err = ensure_checks(d.path(), "BAD1").unwrap_err();
1148        assert!(
1149            err.contains(&format!(
1150                "run BAD1 started from {missing}, which is not in this repository"
1151            )),
1152            "unexpected error: {err}"
1153        );
1154    }
1155
1156    #[test]
1157    fn research_review_uses_no_worktree_path_when_worktree_vanishes_mid_read() {
1158        let (d, _head) = init_repo();
1159        let wt = d.path().join(".wt/R1");
1160        std::fs::create_dir_all(&wt).unwrap();
1161        git(&wt, &["init", "-q"]);
1162        git(
1163            &wt,
1164            &[
1165                "commit",
1166                "-q",
1167                "--allow-empty",
1168                "-m",
1169                "research",
1170                "--no-gpg-sign",
1171            ],
1172        );
1173        std::fs::write(
1174            d.path().join(".wt/R1.start.json"),
1175            serde_json::json!({ "id": "R1", "research": true }).to_string(),
1176        )
1177        .unwrap();
1178        std::fs::write(
1179            d.path().join(".wt/R1.report.json"),
1180            serde_json::json!({ "outcome": "verified", "turns": 1 }).to_string(),
1181        )
1182        .unwrap();
1183
1184        let wt_to_remove = wt.clone();
1185        let remove_wt = move || {
1186            std::fs::remove_dir_all(&wt_to_remove).unwrap();
1187        };
1188        let data = compute_review_res(d.path(), "R1", false, None, Some(&remove_wt))
1189            .map_err(ReviewError::into_message)
1190            .unwrap();
1191        assert!(!data.wt_exists);
1192        assert!(data.is_research);
1193    }
1194}