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(crate) fn compute_review(
77    root: &Path,
78    id: &str,
79    include_diff_for_research: bool,
80) -> Result<ReviewComputation, String> {
81    compute_review_inner(root, id, include_diff_for_research, None)
82}
83
84fn compute_review_inner(
85    root: &Path,
86    id: &str,
87    include_diff_for_research: bool,
88    summary_worktree_fallback: Option<&Path>,
89) -> Result<ReviewComputation, String> {
90    let wt = root.join(".wt").join(id);
91    let wt_exists = wt.exists();
92    let is_research = crate::clean::is_research(root, id)
93        || root.join(".wt").join(format!("{id}.report.md")).exists();
94    let report_file = root.join(".wt").join(format!("{id}.report.json"));
95    if !wt_exists {
96        if !is_research {
97            return Err(format!("worktree {} does not exist", wt.display()));
98        }
99        if !report_file.exists() {
100            return Err(format!(
101                "worktree {} does not exist and {} is missing: nothing to review",
102                wt.display(),
103                report_file.display()
104            ));
105        }
106    }
107
108    let (
109        base,
110        start_comments,
111        commits_out,
112        files_out,
113        tree_out,
114        diff_res,
115        diff_out,
116        task_text,
117        changed_files,
118        subjects,
119    ) = if wt_exists {
120        let start_path = root.join(".wt").join(format!("{id}.start.json"));
121        let (start_base_sha, start_comments): (Option<String>, Option<String>) =
122            match std::fs::read_to_string(&start_path) {
123                Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
124                    Ok(v) => (
125                        v.get("base_sha")
126                            .and_then(|s| s.as_str())
127                            .map(str::trim)
128                            .filter(|s| !s.is_empty())
129                            .map(String::from),
130                        v.get("comments")
131                            .and_then(|s| s.as_str())
132                            .map(str::trim)
133                            .filter(|s| !s.is_empty())
134                            .map(String::from),
135                    ),
136                    Err(e) => {
137                        return Err(format!("cannot parse {}: {e}", start_path.display()));
138                    }
139                },
140                Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
141                Err(e) => {
142                    return Err(format!("cannot read {}: {e}", start_path.display()));
143                }
144            };
145
146        let base = if let Some(sha) = start_base_sha {
147            let out = Command::new("git")
148                .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
149                .current_dir(&wt)
150                .output()
151                .map_err(|e| format!("cannot run git cat-file in {}: {e}", wt.display()))?;
152            if !out.status.success() {
153                let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
154                return Err(format!(
155                    "run {id} started from {sha}, which is not in this repository (git cat-file in {}: {stderr})",
156                    wt.display()
157                ));
158            }
159            sha
160        } else {
161            let root_head = Command::new("git")
162                .args(["rev-parse", "HEAD"])
163                .current_dir(root)
164                .output();
165            let root_head_sha = match root_head {
166                Ok(o) if o.status.success() => {
167                    String::from_utf8_lossy(&o.stdout).trim().to_string()
168                }
169                _ => {
170                    return Err("could not resolve root HEAD".to_string());
171                }
172            };
173
174            let mb_out = Command::new("git")
175                .args(["merge-base", "HEAD", &root_head_sha])
176                .current_dir(&wt)
177                .output();
178            match mb_out {
179                Ok(o) if o.status.success() => {
180                    String::from_utf8_lossy(&o.stdout).trim().to_string()
181                }
182                _ => {
183                    return Err(format!(
184                        "cannot find where run {id} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}"
185                    ));
186                }
187            }
188        };
189
190        let commits_out = Command::new("git")
191            .args(["log", "--oneline", &format!("{base}..HEAD")])
192            .current_dir(&wt)
193            .output()
194            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
195            .unwrap_or_default();
196
197        let files_out = Command::new("git")
198            .args(["diff", "--stat", &format!("{base}..HEAD")])
199            .current_dir(&wt)
200            .output()
201            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
202            .unwrap_or_default();
203
204        let tree_out = Command::new("git")
205            .args(["status", "--short"])
206            .current_dir(&wt)
207            .output()
208            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
209            .unwrap_or_default();
210
211        let diff_res: Option<Result<String, String>> = if !is_research {
212            Some(
213                Command::new("git")
214                    .args(["diff", &format!("{base}..HEAD")])
215                    .current_dir(&wt)
216                    .output()
217                    .map_err(|e| e.to_string())
218                    .and_then(|o| {
219                        if o.status.success() {
220                            Ok(String::from_utf8_lossy(&o.stdout).into_owned())
221                        } else {
222                            let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
223                            if stderr.is_empty() {
224                                Err(format!("exit {}", o.status))
225                            } else {
226                                Err(stderr)
227                            }
228                        }
229                    }),
230            )
231        } else if include_diff_for_research {
232            Some(
233                Command::new("git")
234                    .args(["diff", &format!("{base}..HEAD")])
235                    .current_dir(&wt)
236                    .output()
237                    .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
238                    .map_err(|e| e.to_string()),
239            )
240        } else {
241            None
242        };
243
244        let diff_out = diff_res
245            .as_ref()
246            .and_then(|r| r.as_ref().ok())
247            .map(|s| s.trim().to_string())
248            .unwrap_or_default();
249
250        let task_text: Option<String> = (|| {
251            let start_file = root.join(".wt").join(format!("{id}.start.json"));
252            let content = std::fs::read_to_string(&start_file).ok()?;
253            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
254            let task_file = val.get("task_file")?.as_str()?;
255            let p = Path::new(task_file);
256            if let Ok(s) = std::fs::read_to_string(p) {
257                return Some(s);
258            }
259            std::fs::read_to_string(root.join(p)).ok()
260        })();
261
262        let changed_files: Vec<String> = Command::new("git")
263            .args(["diff", "--name-only", &format!("{base}..HEAD")])
264            .current_dir(&wt)
265            .output()
266            .ok()
267            .filter(|o| o.status.success())
268            .map(|o| {
269                String::from_utf8_lossy(&o.stdout)
270                    .lines()
271                    .map(|l| l.trim().to_string())
272                    .filter(|l| !l.is_empty())
273                    .collect()
274            })
275            .unwrap_or_default();
276
277        let subjects: Vec<String> = Command::new("git")
278            .args(["log", "--format=%s", &format!("{base}..HEAD")])
279            .current_dir(&wt)
280            .output()
281            .ok()
282            .filter(|o| o.status.success())
283            .map(|o| {
284                String::from_utf8_lossy(&o.stdout)
285                    .lines()
286                    .map(|l| l.trim().to_string())
287                    .filter(|l| !l.is_empty())
288                    .collect()
289            })
290            .unwrap_or_default();
291
292        (
293            base,
294            start_comments,
295            commits_out,
296            files_out,
297            tree_out,
298            diff_res,
299            diff_out,
300            task_text,
301            changed_files,
302            subjects,
303        )
304    } else {
305        (
306            String::new(),
307            None,
308            String::new(),
309            String::new(),
310            String::new(),
311            None,
312            String::new(),
313            None,
314            Vec::new(),
315            Vec::new(),
316        )
317    };
318
319    let log_file = root.join(".wt").join(format!("{id}.log"));
320    let log_content_opt = std::fs::read_to_string(&log_file).ok();
321    let (hcmds, reads, (refused_count, refused_paths)) =
322        if let Some(ref log_content) = log_content_opt {
323            let hcmds = host_commands(log_content);
324            let home = std::env::var_os("HOME")
325                .map(PathBuf::from)
326                .unwrap_or_else(|| PathBuf::from("/"));
327            let allowed = [root.to_path_buf(), wt.clone()];
328            let reads = outside_reads(log_content, &allowed, &home);
329            let refused = refused_reads(log_content);
330            (hcmds, reads, refused)
331        } else {
332            (Vec::new(), Vec::new(), (0, Vec::new()))
333        };
334
335    let report_val = std::fs::read_to_string(&report_file)
336        .ok()
337        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
338    let outcome = report_val
339        .as_ref()
340        .and_then(|v| v.get("outcome"))
341        .and_then(|x| x.as_str());
342    let quote_problems: Option<Vec<String>> = report_val
343        .as_ref()
344        .and_then(|v| v.get("quote_problems"))
345        .and_then(|x| x.as_array())
346        .map(|arr| {
347            arr.iter()
348                .filter_map(|x| x.as_str().map(String::from))
349                .collect()
350        });
351    let read_loop = report_val
352        .as_ref()
353        .and_then(|v| v.get("read_loop"))
354        .and_then(|x| x.as_bool())
355        .unwrap_or(false);
356    let gate_left_out: Vec<String> = report_val
357        .as_ref()
358        .and_then(|v| v.get("gate_left_out"))
359        .and_then(|x| x.as_array())
360        .map(|arr| {
361            arr.iter()
362                .filter_map(|x| x.as_str().map(String::from))
363                .collect::<Vec<_>>()
364        })
365        .filter(|v| !v.is_empty())
366        .or_else(|| {
367            let start_file = root.join(".wt").join(format!("{id}.start.json"));
368            let content = std::fs::read_to_string(&start_file).ok()?;
369            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
370            let arr = val.get("gate_left_out")?.as_array()?;
371            Some(
372                arr.iter()
373                    .filter_map(|item| {
374                        let cmd = item.get("command")?.as_str()?;
375                        let reason = item.get("reason")?.as_str()?;
376                        Some(format!("{cmd} ({reason})"))
377                    })
378                    .collect(),
379            )
380        })
381        .unwrap_or_default();
382    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
383        .as_ref()
384        .and_then(|v| v.get("claim_check"))
385        .and_then(|x| serde_json::from_value(x.clone()).ok());
386    let claim_check_skipped: Option<String> = report_val
387        .as_ref()
388        .and_then(|v| v.get("claim_check_skipped"))
389        .and_then(|x| x.as_str())
390        .map(String::from);
391
392    let mut checks = if wt_exists {
393        crate::review_checks::build(
394            task_text.as_deref(),
395            &changed_files,
396            &subjects,
397            hcmds.len(),
398            reads.len(),
399            outcome,
400        )
401    } else {
402        crate::review_checks::build(
403            Some(""),
404            &[String::new()],
405            &[],
406            hcmds.len(),
407            reads.len(),
408            outcome,
409        )
410    };
411    let mut fallbacks: Vec<crate::fallback_check::Finding> = Vec::new();
412    if !is_research {
413        if let Some(ref res) = diff_res {
414            match res {
415                Ok(diff) => {
416                    let findings = crate::fallback_check::added_fallbacks(diff);
417                    if let Some(flag) = crate::fallback_check::flag(&findings) {
418                        checks.flags.push(flag);
419                    }
420                    fallbacks = findings;
421                    if start_comments.as_deref() != Some("off") {
422                        match crate::comment_lint::added_comments(diff, &|path| {
423                            Command::new("git")
424                                .args(["show", &format!("HEAD:{path}")])
425                                .current_dir(&wt)
426                                .output()
427                                .map_err(|e| e.to_string())
428                                .and_then(|o| {
429                                    if o.status.success() {
430                                        Ok(String::from_utf8_lossy(&o.stdout).into_owned())
431                                    } else {
432                                        let stderr =
433                                            String::from_utf8_lossy(&o.stderr).trim().to_string();
434                                        if stderr.is_empty() {
435                                            Err(format!("exit {}", o.status))
436                                        } else {
437                                            Err(stderr)
438                                        }
439                                    }
440                                })
441                        }) {
442                            Ok(comments) => {
443                                if let Some(flag) = crate::comment_lint::flag(&comments) {
444                                    checks.flags.push(flag);
445                                }
446                            }
447                            Err(reason) => {
448                                let first_line = reason.lines().next().unwrap_or(reason.as_str());
449                                let msg = format!("comment check not run: {first_line}");
450                                let cut: String = msg.chars().take(200).collect();
451                                checks.flags.push(cut);
452                            }
453                        }
454                    }
455                }
456                Err(reason) => {
457                    let first_line = reason.lines().next().unwrap_or(reason.as_str());
458                    let msg = format!("fallback check not run: git diff failed: {first_line}");
459                    let cut: String = msg.chars().take(200).collect();
460                    checks.flags.push(cut);
461                }
462            }
463        }
464        let summary_path = root.join(".wt").join(format!("{id}.json"));
465        match std::fs::read_to_string(&summary_path) {
466            Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
467                Ok(v) => match crate::outside_env::summary_worktree(&v) {
468                    Ok(summary_wt) => {
469                        if let Some(ref log_content) = log_content_opt {
470                            let borrowed =
471                                crate::outside_env::borrowed_env_commands(log_content, &summary_wt);
472                            if let Some(flag) = crate::outside_env::flag(&borrowed) {
473                                checks.flags.push(flag);
474                            }
475                        }
476                    }
477                    Err(e) => {
478                        checks.flags.push(format!("outside-env check not run: {e}"));
479                    }
480                },
481                Err(e) => {
482                    checks.flags.push(format!(
483                        "outside-env check not run: cannot parse {}: {e}",
484                        summary_path.display()
485                    ));
486                }
487            },
488            Err(e) if e.kind() == std::io::ErrorKind::NotFound && log_content_opt.is_none() => {}
489            Err(e)
490                if e.kind() == std::io::ErrorKind::NotFound
491                    && summary_worktree_fallback.is_some() =>
492            {
493                if let (Some(summary_wt), Some(ref log_content)) =
494                    (summary_worktree_fallback, &log_content_opt)
495                {
496                    let borrowed =
497                        crate::outside_env::borrowed_env_commands(log_content, summary_wt);
498                    if let Some(flag) = crate::outside_env::flag(&borrowed) {
499                        checks.flags.push(flag);
500                    }
501                }
502            }
503            Err(e) => {
504                checks.flags.push(format!(
505                    "outside-env check not run: cannot read {}: {e}",
506                    summary_path.display()
507                ));
508            }
509        }
510    }
511    if let Some(ref problems) = quote_problems {
512        if !problems.is_empty() {
513            checks.flags.push(format!(
514                "quote check failed ({} problem(s)): see == report",
515                problems.len()
516            ));
517        }
518    }
519    if read_loop {
520        checks.flags.push(
521            "read loop: the run kept re-reading the same files without changing anything and was stopped"
522                .to_string(),
523        );
524    }
525    if !gate_left_out.is_empty() {
526        checks
527            .flags
528            .push(format!("gate left out: {}", gate_left_out.join("; ")));
529    }
530    if let Some(ref cc) = claim_check {
531        if !cc.contradicted.is_empty() {
532            checks.flags.push(format!(
533                "claim check: {} contradicted claims",
534                cc.contradicted.len()
535            ));
536        }
537    }
538    if let Some(ref skipped) = claim_check_skipped {
539        checks.flags.push(format!("claim check skipped: {skipped}"));
540    }
541    if refused_count > 0 {
542        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
543        checks.flags.push(format!(
544            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
545            first_3.join(", ")
546        ));
547    }
548    if is_research {
549        match &report_val {
550            Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
551                Ok((large, total)) => {
552                    if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
553                        checks.flags.push(flag);
554                    }
555                }
556                Err(e) => {
557                    checks.flags.push(format!("breadth check not run: {e}"));
558                }
559            },
560            None => {
561                checks.flags.push(format!(
562                    "breadth check not run: cannot read {}",
563                    report_file.display()
564                ));
565            }
566        }
567        if outcome == Some("budget_exhausted") {
568            match std::fs::read_to_string(&log_file) {
569                Ok(log) => {
570                    let dirs = crate::research_breadth::read_dirs(&log, root);
571                    if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
572                        checks.flags.push(flag);
573                    }
574                }
575                Err(e) => {
576                    checks.flags.push(format!("split suggestion not run: {e}"));
577                }
578            }
579        }
580    }
581
582    Ok(ReviewComputation {
583        wt,
584        wt_exists,
585        is_research,
586        base,
587        task_text,
588        changed_files,
589        commits_out,
590        files_out,
591        tree_out,
592        diff_out,
593        hcmds,
594        reads,
595        report_val,
596        quote_problems,
597        claim_check,
598        claim_check_skipped,
599        checks,
600        fallbacks,
601    })
602}
603
604pub fn read_stored_model_review(
605    root: &Path,
606    id: &str,
607) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
608    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
609    let raw = match std::fs::read_to_string(&checks_path) {
610        Ok(s) => s,
611        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
612        Err(e) => return Err(format!("cannot read {}: {e}", checks_path.display())),
613    };
614    let val: serde_json::Value = serde_json::from_str(&raw)
615        .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
616    parse_stored_model_review(&checks_path, &val)
617}
618
619pub(crate) fn parse_stored_model_review(
620    checks_path: &Path,
621    val: &serde_json::Value,
622) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
623    let Some(obj) = val.as_object() else {
624        return Err(format!(
625            "cannot parse {}: expected a JSON object",
626            checks_path.display()
627        ));
628    };
629    let Some(mr) = obj.get("model_review") else {
630        return Ok(None);
631    };
632    if mr.is_null() {
633        return Ok(None);
634    }
635    serde_json::from_value(mr.clone())
636        .map(Some)
637        .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))
638}
639
640pub(crate) fn write_checks_file(
641    root: &Path,
642    id: &str,
643    flags: &[String],
644    fallbacks: &[crate::fallback_check::Finding],
645    model_review: Option<&crate::model_review::ModelReviewResult>,
646) -> Result<(), String> {
647    let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
648    let ts = std::time::SystemTime::now()
649        .duration_since(std::time::UNIX_EPOCH)
650        .map_err(|e| format!("error: the system clock is before 1970: {e}"))?
651        .as_secs();
652    let mut checks_obj = serde_json::json!({
653        "ts": ts,
654        "flags": flags,
655        "fallbacks": fallbacks,
656    });
657    if let Some(mr) = model_review {
658        checks_obj["model_review"] = serde_json::to_value(mr).map_err(|e| {
659            format!(
660                "error serializing model review for {}: {e}",
661                checks_path.display()
662            )
663        })?;
664    }
665    let checks_json = serde_json::to_string_pretty(&checks_obj)
666        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))?;
667    std::fs::write(&checks_path, checks_json + "\n")
668        .map_err(|e| format!("error writing {}: {e}", checks_path.display()))
669}
670
671pub fn evaluate_verified_run(
672    root: &Path,
673    id: &str,
674) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
675    evaluate_verified_run_with(root, id, crate::model_review::run)
676}
677
678pub fn evaluate_verified_run_with<F>(
679    root: &Path,
680    id: &str,
681    run_model_review: F,
682) -> Result<Option<crate::model_review::ModelReviewResult>, String>
683where
684    F: FnOnce(&Path, &str, &str, &Path) -> crate::model_review::ModelReviewResult,
685{
686    let wt_fallback = root.join(".wt").join(id);
687    let data = compute_review_inner(root, id, false, Some(&wt_fallback))?;
688    let mut flags = data.checks.flags;
689    if data.is_research || !data.wt_exists {
690        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
691        return Ok(None);
692    }
693
694    let risky_matches = match crate::config::load_with_fallback(root) {
695        Ok(Some((cfg, _))) => {
696            match crate::config::match_risky_paths(&cfg.review.risky, &data.changed_files) {
697                Ok(matches) => matches,
698                Err(e) => {
699                    flags.push(format!("risky path check not run: {e}"));
700                    Vec::new()
701                }
702            }
703        }
704        Ok(None) => Vec::new(),
705        Err(e) => {
706            flags.push(format!("risky path check not run: {e}"));
707            Vec::new()
708        }
709    };
710
711    if crate::review_checks::should_run_model_review(
712        &flags,
713        data.task_text.as_deref(),
714        &risky_matches,
715    ) {
716        let result = run_model_review(root, id, &data.base, &data.wt);
717        if let Some(flag) = result.flag() {
718            flags.push(flag);
719        }
720        write_checks_file(root, id, &flags, &data.fallbacks, Some(&result))?;
721        Ok(Some(result))
722    } else {
723        write_checks_file(root, id, &flags, &data.fallbacks, None)?;
724        Ok(None)
725    }
726}
727
728pub fn ensure_checks(root: &Path, id: &str) -> Result<bool, String> {
729    let wt_dir = root.join(".wt");
730    let summary_path = wt_dir.join(format!("{id}.json"));
731    if !summary_path.is_file() {
732        return Err(format!("no finished run {id} in {}", wt_dir.display()));
733    }
734    let checks_path = wt_dir.join(format!("{id}.checks.json"));
735    if checks_path.exists() {
736        return Ok(false);
737    }
738    let data = compute_review(root, id, false)?;
739    write_checks_file(root, id, &data.checks.flags, &data.fallbacks, None)?;
740    Ok(true)
741}
742
743pub fn set_hold(root: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
744    let trimmed = note.trim();
745    if trimmed.is_empty() {
746        return Err(format!("a note is required to hold run {id}"));
747    }
748    let wt_dir = root.join(".wt");
749    std::fs::create_dir_all(&wt_dir)
750        .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
751    let hold_path = wt_dir.join(format!("{id}.hold.json"));
752    let hold = Hold {
753        note: trimmed.to_string(),
754        ts: now,
755    };
756    let json_str =
757        serde_json::to_string_pretty(&hold).map_err(|e| format!("error serializing hold: {e}"))?;
758    std::fs::write(&hold_path, json_str + "\n")
759        .map_err(|e| format!("error writing {}: {e}", hold_path.display()))
760}
761
762pub fn clear_hold(root: &Path, id: &str) -> Result<(), String> {
763    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
764    match std::fs::remove_file(&hold_path) {
765        Ok(()) => Ok(()),
766        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
767        Err(e) => Err(format!("error removing {}: {e}", hold_path.display())),
768    }
769}
770
771pub fn read_hold(root: &Path, id: &str) -> Result<Option<Hold>, String> {
772    let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
773    let raw = match std::fs::read_to_string(&hold_path) {
774        Ok(s) => s,
775        Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
776        Err(e) => return Err(format!("error reading {}: {e}", hold_path.display())),
777    };
778    serde_json::from_str::<Hold>(&raw)
779        .map(Some)
780        .map_err(|e| format!("could not parse {}: {e}", hold_path.display()))
781}
782
783pub fn decide(
784    root: &Path,
785    id: &str,
786    action: Action,
787    note: Option<&str>,
788    now: u64,
789) -> Result<Decision, String> {
790    let wt_dir = root.join(".wt");
791    let summary_path = wt_dir.join(format!("{id}.json"));
792    let summary_raw = match std::fs::read_to_string(&summary_path) {
793        Ok(s) => s,
794        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
795            return Err(format!("no finished run {id} in {}", wt_dir.display()));
796        }
797        Err(e) => {
798            return Err(format!("error reading {}: {e}", summary_path.display()));
799        }
800    };
801    let summary: serde_json::Value = serde_json::from_str(&summary_raw)
802        .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
803    let outcome = summary
804        .get("outcome")
805        .and_then(|v| v.as_str())
806        .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
807    let is_research =
808        crate::clean::is_research(root, id) || wt_dir.join(format!("{id}.report.md")).exists();
809
810    let trimmed_note: Option<String> = note
811        .map(str::trim)
812        .filter(|s| !s.is_empty())
813        .map(String::from);
814
815    let orchestrator_message = match action {
816        Action::Accept => {
817            if is_research {
818                return Err(format!("run {id} is a research run; mark it read"));
819            }
820            if outcome != "verified" {
821                return Err(format!(
822                    "run {id} is {outcome}, not verified; it cannot be accepted"
823                ));
824            }
825            record_verdict(
826                root,
827                id,
828                ReviewVerdict::Accepted,
829                trimmed_note.as_deref().unwrap_or(""),
830                now,
831            )?;
832            clear_hold(root, id)?;
833            Some(format!(
834                "Accepted run {id}. Combine it onto the working branch and run the gate."
835            ))
836        }
837        Action::SendBack => {
838            let Some(ref text) = trimmed_note else {
839                return Err(format!("a note is required to send back run {id}"));
840            };
841            clear_hold(root, id)?;
842            Some(format!(
843                "Send back run {id}: {text} Draft a follow-up task for me to confirm."
844            ))
845        }
846        Action::Redo => {
847            record_verdict(
848                root,
849                id,
850                ReviewVerdict::Redone,
851                trimmed_note.as_deref().unwrap_or(""),
852                now,
853            )?;
854            clear_hold(root, id)?;
855            let msg = match trimmed_note.as_deref() {
856                Some(text) => format!("Redo run {id}. Reason: {text}"),
857                None => format!("Redo run {id}."),
858            };
859            Some(msg)
860        }
861        Action::Hold => {
862            let Some(ref text) = trimmed_note else {
863                return Err(format!("a note is required to hold run {id}"));
864            };
865            set_hold(root, id, text, now)?;
866            None
867        }
868        Action::MarkRead => {
869            if !is_research {
870                return Err(format!("run {id} is not a research run"));
871            }
872            record_verdict(root, id, ReviewVerdict::Accepted, "read", now)?;
873            clear_hold(root, id)?;
874            None
875        }
876    };
877
878    Ok(Decision {
879        run: id.to_string(),
880        action,
881        note: trimmed_note,
882        orchestrator_message,
883    })
884}