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