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