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