1use std::path::{Path, PathBuf};
2use std::process::Command;
3
4use crate::cli::ReviewVerdict;
5use crate::dispatch::{host_commands, outside_reads, refused_reads};
6
7#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
8pub struct Hold {
9 pub note: String,
10 pub ts: u64,
11}
12
13#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum Action {
16 Accept,
17 SendBack,
18 Redo,
19 Hold,
20 MarkRead,
21}
22
23#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize)]
24pub struct Decision {
25 pub run: String,
26 pub action: Action,
27 pub note: Option<String>,
28 pub conversation_message: Option<String>,
29}
30
31pub(crate) struct ReviewComputation {
32 pub(crate) wt: PathBuf,
33 pub(crate) wt_exists: bool,
34 pub(crate) is_research: bool,
35 pub(crate) base: String,
36 pub(crate) task_text: Option<String>,
37 pub(crate) changed_files: Vec<String>,
38 pub(crate) commits_out: String,
39 pub(crate) files_out: String,
40 pub(crate) tree_out: String,
41 pub(crate) diff_out: String,
42 pub(crate) hcmds: Vec<String>,
43 pub(crate) reads: Vec<String>,
44 pub(crate) report_val: Option<serde_json::Value>,
45 pub(crate) quote_problems: Option<Vec<String>>,
46 pub(crate) claim_check: Option<blyte_agent::claim_check::ClaimCheck>,
47 pub(crate) claim_check_skipped: Option<String>,
48 pub(crate) checks: crate::review_checks::Checks,
49 pub(crate) fallbacks: Vec<crate::fallback_check::Finding>,
50}
51
52pub fn record_verdict(
53 root: &Path,
54 id: &str,
55 verdict: ReviewVerdict,
56 notes: &str,
57 now: u64,
58) -> Result<(), String> {
59 let wt_dir = root.join(".wt");
60 std::fs::create_dir_all(&wt_dir)
61 .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
62 let verdict_path = wt_dir.join(format!("{id}.verdict.json"));
63 let verdict_obj = serde_json::json!({
64 "verdict": verdict.as_str(),
65 "notes": notes,
66 "ts": now,
67 });
68 let json_str = serde_json::to_string_pretty(&verdict_obj)
69 .map_err(|e| format!("error serializing verdict: {e}"))?;
70 std::fs::write(&verdict_path, json_str + "\n")
71 .map_err(|e| format!("error writing {}: {e}", verdict_path.display()))?;
72 crate::clean::clean_on_review(root, id);
73 Ok(())
74}
75
76pub fn read_verdict(root: &Path, id: &str) -> Result<Option<ReviewVerdict>, String> {
77 let verdict_path = root.join(".wt").join(format!("{id}.verdict.json"));
78 let raw = match std::fs::read_to_string(&verdict_path) {
79 Ok(s) => s,
80 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
81 Err(e) => {
82 return Err(format!("error reading {}: {e}", verdict_path.display()));
83 }
84 };
85 let val: serde_json::Value = serde_json::from_str(&raw)
86 .map_err(|e| format!("could not parse {}: {e}", verdict_path.display()))?;
87 let verdict_str = val
88 .get("verdict")
89 .and_then(|v| v.as_str())
90 .ok_or_else(|| format!("{} is missing string verdict", verdict_path.display()))?;
91 let parsed = match verdict_str {
92 "accepted" => ReviewVerdict::Accepted,
93 "fixed" => ReviewVerdict::Fixed,
94 "redone" => ReviewVerdict::Redone,
95 other => {
96 return Err(format!(
97 "{} has unknown verdict '{other}'",
98 verdict_path.display()
99 ));
100 }
101 };
102 Ok(Some(parsed))
103}
104
105enum ReviewError {
106 WorktreeGone(String),
107 Other(String),
108}
109
110impl ReviewError {
111 fn into_message(self) -> String {
112 match self {
113 Self::WorktreeGone(msg) | Self::Other(msg) => msg,
114 }
115 }
116}
117
118enum WtGit {
119 Output(std::process::Output),
120 WorktreeGone,
121 IoErr(std::io::Error),
122}
123
124fn wt_present(wt: &Path) -> bool {
125 wt.is_dir() && wt.join(".git").exists()
126}
127
128fn run_git_in_wt(wt: &Path, args: &[&str]) -> WtGit {
129 match Command::new("git").args(args).current_dir(wt).output() {
130 Ok(o) => {
131 if !o.status.success() && !wt_present(wt) {
132 WtGit::WorktreeGone
133 } else {
134 WtGit::Output(o)
135 }
136 }
137 Err(e) => {
138 if !wt_present(wt) {
139 WtGit::WorktreeGone
140 } else {
141 WtGit::IoErr(e)
142 }
143 }
144 }
145}
146
147struct WorktreeGitData {
148 base: String,
149 start_comments: Option<String>,
150 commits_out: String,
151 files_out: String,
152 tree_out: String,
153 diff_raw: Option<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_raw: None,
169 diff_out: String::new(),
170 task_text: None,
171 changed_files: Vec::new(),
172 subjects: Vec::new(),
173 }
174 }
175}
176
177fn git_stdout_in_wt_with(
178 run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
179 wt: &Path,
180 args: &[&str],
181) -> Result<Option<String>, String> {
182 match run_git(wt, args) {
183 WtGit::WorktreeGone => Ok(None),
184 WtGit::IoErr(e) => Err(format!(
185 "could not run git {} in {}: {e}",
186 args.join(" "),
187 wt.display()
188 )),
189 WtGit::Output(o) if o.status.success() => {
190 Ok(Some(String::from_utf8_lossy(&o.stdout).into_owned()))
191 }
192 WtGit::Output(o) => {
193 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
194 let detail = if stderr.is_empty() {
195 format!("exit {}", o.status)
196 } else {
197 stderr
198 };
199 Err(format!(
200 "git {} failed in {}: {detail}",
201 args.join(" "),
202 wt.display()
203 ))
204 }
205 }
206}
207
208fn read_worktree_git_data(
209 root: &Path,
210 id: &str,
211 wt: &Path,
212 is_research: bool,
213 include_diff_for_research: bool,
214 before_git: Option<&dyn Fn()>,
215 run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
216) -> Result<Option<WorktreeGitData>, String> {
217 let start_path = root.join(".wt").join(format!("{id}.start.json"));
218 let (start_base_sha, start_comments): (Option<String>, Option<String>) =
219 match std::fs::read_to_string(&start_path) {
220 Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
221 Ok(v) => (
222 v.get("base_sha")
223 .and_then(|s| s.as_str())
224 .map(str::trim)
225 .filter(|s| !s.is_empty())
226 .map(String::from),
227 v.get("comments")
228 .and_then(|s| s.as_str())
229 .map(str::trim)
230 .filter(|s| !s.is_empty())
231 .map(String::from),
232 ),
233 Err(e) => {
234 return Err(format!("cannot parse {}: {e}", start_path.display()));
235 }
236 },
237 Err(e) if e.kind() == std::io::ErrorKind::NotFound => (None, None),
238 Err(e) => {
239 return Err(format!("cannot read {}: {e}", start_path.display()));
240 }
241 };
242
243 if let Some(hook) = before_git {
244 hook();
245 }
246
247 let base = if let Some(sha) = start_base_sha {
248 let out = Command::new("git")
249 .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
250 .current_dir(root)
251 .output()
252 .map_err(|e| format!("cannot run git cat-file in {}: {e}", root.display()))?;
253 if !out.status.success() {
254 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
255 return Err(format!(
256 "run {id} started from {sha}, which is not in this repository (git cat-file in {}: {stderr})",
257 root.display()
258 ));
259 }
260 sha
261 } else if is_research {
262 match run_git(wt, &["rev-list", "--max-parents=0", "HEAD"]) {
263 WtGit::WorktreeGone => return Ok(None),
264 WtGit::IoErr(e) => {
265 return Err(format!(
266 "could not run git rev-list --max-parents=0 HEAD in {}: {e}",
267 wt.display()
268 ));
269 }
270 WtGit::Output(o) if o.status.success() => {
271 let stdout = String::from_utf8_lossy(&o.stdout);
272 let trimmed = stdout.trim();
273 let lines: Vec<&str> = trimmed.lines().collect();
274 match lines.as_slice() {
275 [only] => only.trim().to_string(),
276 [] => {
277 return Err(format!(
278 "cannot find the first commit of research run {id} in {}: git rev-list --max-parents=0 HEAD printed no commit",
279 wt.display()
280 ));
281 }
282 _ => {
283 return Err(format!(
284 "cannot find the first commit of research run {id} in {}: git rev-list --max-parents=0 HEAD printed more than one line: {trimmed}",
285 wt.display()
286 ));
287 }
288 }
289 }
290 WtGit::Output(o) => {
291 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
292 let detail = if stderr.is_empty() {
293 format!("exit {}", o.status)
294 } else {
295 stderr
296 };
297 return Err(format!(
298 "cannot find the first commit of research run {id} in {}: {detail}",
299 wt.display()
300 ));
301 }
302 }
303 } else {
304 let root_head = Command::new("git")
305 .args(["rev-parse", "HEAD"])
306 .current_dir(root)
307 .output();
308 let root_head_sha = match root_head {
309 Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
310 _ => {
311 return Err("could not resolve root HEAD".to_string());
312 }
313 };
314
315 match run_git(wt, &["merge-base", "HEAD", &root_head_sha]) {
316 WtGit::WorktreeGone => return Ok(None),
317 WtGit::IoErr(e) => {
318 return Err(format!(
319 "could not run git merge-base HEAD {root_head_sha} in {}: {e}",
320 wt.display()
321 ));
322 }
323 WtGit::Output(o) if o.status.success() => {
324 String::from_utf8_lossy(&o.stdout).trim().to_string()
325 }
326 WtGit::Output(_) => {
327 return Err(format!(
328 "cannot find where run {id} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}"
329 ));
330 }
331 }
332 };
333
334 let range = format!("{base}..HEAD");
335
336 let Some(commits_raw) = git_stdout_in_wt_with(run_git, wt, &["log", "--oneline", &range])?
337 else {
338 return Ok(None);
339 };
340 let commits_out = commits_raw.trim().to_string();
341
342 let Some(files_raw) = git_stdout_in_wt_with(run_git, wt, &["diff", "--stat", &range])? else {
343 return Ok(None);
344 };
345 let files_out = files_raw.trim().to_string();
346
347 let Some(tree_raw) = git_stdout_in_wt_with(run_git, wt, &["status", "--short"])? else {
348 return Ok(None);
349 };
350 let tree_out = tree_raw.trim().to_string();
351
352 let diff_raw = if !is_research || include_diff_for_research {
353 let Some(diff) = git_stdout_in_wt_with(run_git, wt, &["diff", &range])? else {
354 return Ok(None);
355 };
356 Some(diff)
357 } else {
358 None
359 };
360
361 let diff_out = match diff_raw.as_deref() {
362 Some(s) => s.trim().to_string(),
363 None => String::new(),
364 };
365
366 let task_text: Option<String> = (|| {
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 task_file = val.get("task_file")?.as_str()?;
371 let p = Path::new(task_file);
372 if let Ok(s) = std::fs::read_to_string(p) {
373 return Some(s);
374 }
375 std::fs::read_to_string(root.join(p)).ok()
376 })();
377
378 let Some(changed_raw) = git_stdout_in_wt_with(run_git, wt, &["diff", "--name-only", &range])?
379 else {
380 return Ok(None);
381 };
382 let changed_files: Vec<String> = changed_raw
383 .lines()
384 .map(|l| l.trim().to_string())
385 .filter(|l| !l.is_empty())
386 .collect();
387
388 let Some(subjects_raw) = git_stdout_in_wt_with(run_git, wt, &["log", "--format=%s", &range])?
389 else {
390 return Ok(None);
391 };
392 let subjects: Vec<String> = subjects_raw
393 .lines()
394 .map(|l| l.trim().to_string())
395 .filter(|l| !l.is_empty())
396 .collect();
397
398 Ok(Some(WorktreeGitData {
399 base,
400 start_comments,
401 commits_out,
402 files_out,
403 tree_out,
404 diff_raw,
405 diff_out,
406 task_text,
407 changed_files,
408 subjects,
409 }))
410}
411
412pub(crate) fn compute_review(
413 root: &Path,
414 id: &str,
415 include_diff_for_research: bool,
416) -> Result<ReviewComputation, String> {
417 compute_review_res(root, id, include_diff_for_research, None, None)
418 .map_err(ReviewError::into_message)
419}
420
421fn compute_review_res(
422 root: &Path,
423 id: &str,
424 include_diff_for_research: bool,
425 summary_worktree_fallback: Option<&Path>,
426 before_git: Option<&dyn Fn()>,
427) -> Result<ReviewComputation, ReviewError> {
428 compute_review_res_with_runner(
429 root,
430 id,
431 include_diff_for_research,
432 summary_worktree_fallback,
433 before_git,
434 &run_git_in_wt,
435 )
436}
437
438fn compute_review_res_with_runner(
439 root: &Path,
440 id: &str,
441 include_diff_for_research: bool,
442 summary_worktree_fallback: Option<&Path>,
443 before_git: Option<&dyn Fn()>,
444 run_git: &dyn Fn(&Path, &[&str]) -> WtGit,
445) -> Result<ReviewComputation, ReviewError> {
446 let wt = root.join(".wt").join(id);
447 let mut wt_exists = wt_present(&wt);
448 let is_research = crate::clean::is_research(root, id)
449 || root.join(".wt").join(format!("{id}.report.md")).exists();
450 let report_file = root.join(".wt").join(format!("{id}.report.json"));
451 let summary_file = root.join(".wt").join(format!("{id}.json"));
452 let missing_wt_err = |wt: &Path| -> Option<ReviewError> {
453 if !is_research {
454 if !report_file.exists() && summary_file.exists() {
455 return None;
456 }
457 return Some(ReviewError::WorktreeGone(format!(
458 "worktree {} does not exist",
459 wt.display()
460 )));
461 }
462 if !report_file.exists() && !summary_file.exists() {
463 return Some(ReviewError::WorktreeGone(format!(
464 "worktree {} does not exist and {} is missing: nothing to review",
465 wt.display(),
466 report_file.display()
467 )));
468 }
469 None
470 };
471 if !wt_exists {
472 if let Some(err) = missing_wt_err(&wt) {
473 return Err(err);
474 }
475 }
476
477 let git_data = if wt_exists {
478 match read_worktree_git_data(
479 root,
480 id,
481 &wt,
482 is_research,
483 include_diff_for_research,
484 before_git,
485 run_git,
486 ) {
487 Ok(Some(data)) => data,
488 Ok(None) => {
489 wt_exists = false;
490 if let Some(err) = missing_wt_err(&wt) {
491 return Err(err);
492 }
493 WorktreeGitData::empty()
494 }
495 Err(e) => return Err(ReviewError::Other(e)),
496 }
497 } else {
498 WorktreeGitData::empty()
499 };
500
501 let WorktreeGitData {
502 base,
503 start_comments,
504 commits_out,
505 files_out,
506 tree_out,
507 diff_raw,
508 diff_out,
509 task_text,
510 changed_files,
511 subjects,
512 } = git_data;
513
514 let log_file = root.join(".wt").join(format!("{id}.log"));
515 let log_content_opt = match std::fs::read_to_string(&log_file) {
516 Ok(content) => Some(content),
517 Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
518 Err(e) => {
519 return Err(ReviewError::Other(format!(
520 "cannot read {}: {e}",
521 log_file.display()
522 )));
523 }
524 };
525 let (hcmds, reads, (refused_count, refused_paths)) =
526 if let Some(ref log_content) = log_content_opt {
527 let hcmds = host_commands(log_content);
528 let home = std::env::var_os("HOME")
529 .map(PathBuf::from)
530 .unwrap_or_else(|| PathBuf::from("/"));
531 let allowed = [root.to_path_buf(), wt.clone()];
532 let reads = outside_reads(log_content, &allowed, &home);
533 let refused = refused_reads(log_content);
534 (hcmds, reads, refused)
535 } else {
536 (Vec::new(), Vec::new(), (0, Vec::new()))
537 };
538
539 let report_val = match read_optional_json(&report_file)? {
540 Some(v) => Some(v),
541 None => read_optional_json(&summary_file)?,
542 };
543 let outcome = report_val
544 .as_ref()
545 .and_then(|v| v.get("outcome"))
546 .and_then(|x| x.as_str());
547 let quote_problems: Option<Vec<String>> = report_val
548 .as_ref()
549 .and_then(|v| v.get("quote_problems"))
550 .and_then(|x| x.as_array())
551 .map(|arr| {
552 arr.iter()
553 .filter_map(|x| x.as_str().map(String::from))
554 .collect()
555 });
556 let read_loop = report_val
557 .as_ref()
558 .and_then(|v| v.get("read_loop"))
559 .and_then(|x| x.as_bool())
560 .unwrap_or(false);
561 let gate_left_out: Vec<String> = report_val
562 .as_ref()
563 .and_then(|v| v.get("gate_left_out"))
564 .and_then(|x| x.as_array())
565 .map(|arr| {
566 arr.iter()
567 .filter_map(|x| x.as_str().map(String::from))
568 .collect::<Vec<_>>()
569 })
570 .filter(|v| !v.is_empty())
571 .or_else(|| {
572 let start_file = root.join(".wt").join(format!("{id}.start.json"));
573 let content = std::fs::read_to_string(&start_file).ok()?;
574 let val: serde_json::Value = serde_json::from_str(&content).ok()?;
575 let arr = val.get("gate_left_out")?.as_array()?;
576 Some(
577 arr.iter()
578 .filter_map(|item| {
579 let cmd = item.get("command")?.as_str()?;
580 let reason = item.get("reason")?.as_str()?;
581 Some(format!("{cmd} ({reason})"))
582 })
583 .collect(),
584 )
585 })
586 .unwrap_or_default();
587 let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
588 .as_ref()
589 .and_then(|v| v.get("claim_check"))
590 .and_then(|x| serde_json::from_value(x.clone()).ok());
591 let claim_check_skipped: Option<String> = report_val
592 .as_ref()
593 .and_then(|v| v.get("claim_check_skipped"))
594 .and_then(|x| x.as_str())
595 .map(String::from);
596
597 let mut checks = if wt_exists {
598 crate::review_checks::build(
599 task_text.as_deref(),
600 &changed_files,
601 &subjects,
602 hcmds.len(),
603 reads.len(),
604 outcome,
605 )
606 } else {
607 crate::review_checks::build(
608 Some(""),
609 &[String::new()],
610 &[],
611 hcmds.len(),
612 reads.len(),
613 outcome,
614 )
615 };
616 let mut fallbacks: Vec<crate::fallback_check::Finding> = Vec::new();
617 if !is_research {
618 if let Some(ref diff) = diff_raw {
619 fallbacks = crate::fallback_check::added_fallbacks(diff);
620 if start_comments.as_deref() != Some("off") {
621 let wt_gone = std::cell::Cell::new(false);
622 match crate::comment_lint::added_comments(diff, &|path| match run_git_in_wt(
623 &wt,
624 &["show", &format!("HEAD:{path}")],
625 ) {
626 WtGit::WorktreeGone => {
627 wt_gone.set(true);
628 Err(format!("worktree {} does not exist", wt.display()))
629 }
630 WtGit::IoErr(e) => Err(e.to_string()),
631 WtGit::Output(o) => {
632 if o.status.success() {
633 Ok(String::from_utf8_lossy(&o.stdout).into_owned())
634 } else {
635 let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
636 if stderr.is_empty() {
637 Err(format!("exit {}", o.status))
638 } else {
639 Err(stderr)
640 }
641 }
642 }
643 }) {
644 Ok(comments) => {
645 if let Some(flag) = crate::comment_lint::flag(&comments) {
646 checks.flags.push(flag);
647 }
648 }
649 Err(reason) => {
650 if wt_gone.get() {
651 return Err(ReviewError::WorktreeGone(format!(
652 "worktree {} does not exist",
653 wt.display()
654 )));
655 }
656 let first_line = reason.lines().next().unwrap_or(reason.as_str());
657 let msg = format!("comment check not run: {first_line}");
658 let cut: String = msg.chars().take(200).collect();
659 checks.flags.push(cut);
660 }
661 }
662 }
663 }
664 if wt_exists {
665 match std::fs::read_to_string(&summary_file) {
666 Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
667 Ok(v) => match crate::outside_env::summary_worktree(&v) {
668 Ok(summary_wt) => {
669 if let Some(ref log_content) = log_content_opt {
670 let borrowed = crate::outside_env::borrowed_env_commands(
671 log_content,
672 &summary_wt,
673 );
674 if let Some(flag) = crate::outside_env::flag(&borrowed) {
675 checks.flags.push(flag);
676 }
677 }
678 }
679 Err(e) => {
680 checks.flags.push(format!("outside-env check not run: {e}"));
681 }
682 },
683 Err(e) => {
684 checks.flags.push(format!(
685 "outside-env check not run: cannot parse {}: {e}",
686 summary_file.display()
687 ));
688 }
689 },
690 Err(e) if e.kind() == std::io::ErrorKind::NotFound && log_content_opt.is_none() => {
691 }
692 Err(e)
693 if e.kind() == std::io::ErrorKind::NotFound
694 && summary_worktree_fallback.is_some() =>
695 {
696 if let (Some(summary_wt), Some(ref log_content)) =
697 (summary_worktree_fallback, &log_content_opt)
698 {
699 let borrowed =
700 crate::outside_env::borrowed_env_commands(log_content, summary_wt);
701 if let Some(flag) = crate::outside_env::flag(&borrowed) {
702 checks.flags.push(flag);
703 }
704 }
705 }
706 Err(e) => {
707 checks.flags.push(format!(
708 "outside-env check not run: cannot read {}: {e}",
709 summary_file.display()
710 ));
711 }
712 }
713 }
714 }
715 if let Some(ref problems) = quote_problems {
716 if !problems.is_empty() {
717 checks.flags.push(format!(
718 "quote check failed ({} problem(s)): see == report",
719 problems.len()
720 ));
721 }
722 }
723 if read_loop {
724 checks.flags.push(
725 "read loop: the run kept re-reading the same files without changing anything and was stopped"
726 .to_string(),
727 );
728 }
729 if !gate_left_out.is_empty() {
730 checks
731 .flags
732 .push(format!("gate left out: {}", gate_left_out.join("; ")));
733 }
734 if let Some(ref cc) = claim_check {
735 if !cc.contradicted.is_empty() {
736 checks.flags.push(format!(
737 "claim check: {} contradicted claims",
738 cc.contradicted.len()
739 ));
740 }
741 }
742 if let Some(ref skipped) = claim_check_skipped {
743 checks.flags.push(format!("claim check skipped: {skipped}"));
744 }
745 if refused_count > 0 {
746 let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
747 checks.flags.push(format!(
748 "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
749 first_3.join(", ")
750 ));
751 }
752 if is_research {
753 match &report_val {
754 Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
755 Ok((large, total)) => {
756 if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
757 checks.flags.push(flag);
758 }
759 }
760 Err(e) => {
761 checks.flags.push(format!("breadth check not run: {e}"));
762 }
763 },
764 None => {
765 checks.flags.push(format!(
766 "breadth check not run: cannot read {}",
767 report_file.display()
768 ));
769 }
770 }
771 if outcome == Some("budget_exhausted") {
772 match std::fs::read_to_string(&log_file) {
773 Ok(log) => {
774 let dirs = crate::research_breadth::read_dirs(&log, root);
775 if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
776 checks.flags.push(flag);
777 }
778 }
779 Err(e) => {
780 checks.flags.push(format!("split suggestion not run: {e}"));
781 }
782 }
783 }
784 }
785
786 Ok(ReviewComputation {
787 wt,
788 wt_exists,
789 is_research,
790 base,
791 task_text,
792 changed_files,
793 commits_out,
794 files_out,
795 tree_out,
796 diff_out,
797 hcmds,
798 reads,
799 report_val,
800 quote_problems,
801 claim_check,
802 claim_check_skipped,
803 checks,
804 fallbacks,
805 })
806}
807
808pub fn read_stored_model_review(
809 root: &Path,
810 id: &str,
811) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
812 let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
813 let raw = match std::fs::read_to_string(&checks_path) {
814 Ok(s) => s,
815 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
816 Err(e) => return Err(format!("cannot read {}: {e}", checks_path.display())),
817 };
818 let val: serde_json::Value = serde_json::from_str(&raw)
819 .map_err(|e| format!("cannot parse {}: {e}", checks_path.display()))?;
820 parse_stored_model_review(&checks_path, &val)
821}
822
823pub(crate) fn parse_stored_model_review(
824 checks_path: &Path,
825 val: &serde_json::Value,
826) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
827 let Some(obj) = val.as_object() else {
828 return Err(format!(
829 "cannot parse {}: expected a JSON object",
830 checks_path.display()
831 ));
832 };
833 let Some(mr) = obj.get("model_review") else {
834 return Ok(None);
835 };
836 if mr.is_null() {
837 return Ok(None);
838 }
839 let parsed: crate::model_review::ModelReviewResult = serde_json::from_value(mr.clone())
840 .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))?;
841 parsed
842 .validate()
843 .map_err(|e| format!("invalid model_review in {}: {e}", checks_path.display()))?;
844 Ok(Some(parsed))
845}
846
847fn read_optional_json(path: &Path) -> Result<Option<serde_json::Value>, ReviewError> {
848 let raw = match std::fs::read_to_string(path) {
849 Ok(content) => content,
850 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
851 Err(e) => {
852 return Err(ReviewError::Other(format!(
853 "cannot read {}: {e}",
854 path.display()
855 )));
856 }
857 };
858 serde_json::from_str::<serde_json::Value>(&raw)
859 .map(Some)
860 .map_err(|e| ReviewError::Other(format!("cannot parse {}: {e}", path.display())))
861}
862
863pub(crate) fn write_checks_file(
864 root: &Path,
865 id: &str,
866 flags: &[String],
867 fallbacks: &[crate::fallback_check::Finding],
868 model_review: Option<&crate::model_review::ModelReviewResult>,
869) -> Result<(), String> {
870 let checks_path = root.join(".wt").join(format!("{id}.checks.json"));
871 let ts = std::time::SystemTime::now()
872 .duration_since(std::time::UNIX_EPOCH)
873 .map_err(|e| format!("error: the system clock is before 1970: {e}"))?
874 .as_secs();
875 let annotated_fallbacks = crate::fallback_check::annotate_fallbacks(fallbacks, model_review);
876 let mut checks_obj = serde_json::json!({
877 "ts": ts,
878 "flags": flags,
879 "fallbacks": annotated_fallbacks,
880 });
881 if let Some(mr) = model_review {
882 checks_obj["model_review"] = serde_json::to_value(mr).map_err(|e| {
883 format!(
884 "error serializing model review for {}: {e}",
885 checks_path.display()
886 )
887 })?;
888 }
889 let checks_json = serde_json::to_string_pretty(&checks_obj)
890 .map_err(|e| format!("error writing {}: {e}", checks_path.display()))?;
891 std::fs::write(&checks_path, checks_json + "\n")
892 .map_err(|e| format!("error writing {}: {e}", checks_path.display()))
893}
894
895pub fn evaluate_verified_run(
896 root: &Path,
897 id: &str,
898) -> Result<Option<crate::model_review::ModelReviewResult>, String> {
899 evaluate_verified_run_with(root, id, false, crate::model_review::run)
900}
901
902pub fn evaluate_verified_run_with<F>(
903 root: &Path,
904 id: &str,
905 force_review: bool,
906 run_model_review: F,
907) -> Result<Option<crate::model_review::ModelReviewResult>, String>
908where
909 F: FnOnce(&Path, &str, &str, &Path) -> crate::model_review::ModelReviewResult,
910{
911 let wt_fallback = root.join(".wt").join(id);
912 let data = compute_review_res(root, id, false, Some(&wt_fallback), None)
913 .map_err(ReviewError::into_message)?;
914 let mut flags = data.checks.flags;
915 if data.is_research || !data.wt_exists {
916 flags.extend(crate::fallback_check::flags_for_review(
917 &data.fallbacks,
918 None,
919 ));
920 write_checks_file(root, id, &flags, &data.fallbacks, None)?;
921 return Ok(None);
922 }
923
924 let risky_matches = match crate::config::load_with_fallback(root) {
925 Ok(Some((cfg, _))) => {
926 match crate::config::match_risky_paths(&cfg.review.risky, &data.changed_files) {
927 Ok(matches) => matches,
928 Err(e) => {
929 flags.push(format!("risky path check not run: {e}"));
930 Vec::new()
931 }
932 }
933 }
934 Ok(None) => Vec::new(),
935 Err(e) => {
936 flags.push(format!("risky path check not run: {e}"));
937 Vec::new()
938 }
939 };
940
941 if force_review
942 || crate::review_checks::should_run_model_review(
943 &flags,
944 data.task_text.as_deref(),
945 &risky_matches,
946 data.fallbacks.len(),
947 )
948 {
949 let result = run_model_review(root, id, &data.base, &data.wt);
950 flags.extend(crate::fallback_check::flags_for_review(
951 &data.fallbacks,
952 Some(&result),
953 ));
954 if let Some(flag) = result.flag() {
955 flags.push(flag);
956 }
957 write_checks_file(root, id, &flags, &data.fallbacks, Some(&result))?;
958 Ok(Some(result))
959 } else {
960 let review_path = root.join(".wt").join(format!("{id}.model-review.json"));
961 if review_path.exists() {
962 std::fs::remove_file(&review_path)
963 .map_err(|e| format!("cannot remove {}: {e}", review_path.display()))?;
964 }
965 flags.extend(crate::fallback_check::flags_for_review(
966 &data.fallbacks,
967 None,
968 ));
969 write_checks_file(root, id, &flags, &data.fallbacks, None)?;
970 Ok(None)
971 }
972}
973
974pub fn ensure_checks(root: &Path, id: &str) -> Result<bool, String> {
975 ensure_checks_with_hook(root, id, None)
976}
977
978fn ensure_checks_with_hook(
979 root: &Path,
980 id: &str,
981 before_git: Option<&dyn Fn()>,
982) -> Result<bool, String> {
983 let wt_dir = root.join(".wt");
984 let summary_path = wt_dir.join(format!("{id}.json"));
985 if !summary_path.is_file() {
986 return Err(format!("no finished run {id} in {}", wt_dir.display()));
987 }
988 let checks_path = wt_dir.join(format!("{id}.checks.json"));
989 if checks_path.exists() {
990 return Ok(false);
991 }
992 let data = match compute_review_res(root, id, false, None, before_git) {
993 Ok(data) => data,
994 Err(ReviewError::WorktreeGone(_)) => return Ok(false),
995 Err(ReviewError::Other(e)) => return Err(e),
996 };
997 if !data.wt_exists {
998 return Ok(false);
999 }
1000 let mut flags = data.checks.flags;
1001 flags.extend(crate::fallback_check::flags_for_review(
1002 &data.fallbacks,
1003 None,
1004 ));
1005 write_checks_file(root, id, &flags, &data.fallbacks, None)?;
1006 Ok(true)
1007}
1008
1009pub fn set_hold(root: &Path, id: &str, note: &str, now: u64) -> Result<(), String> {
1010 let trimmed = note.trim();
1011 if trimmed.is_empty() {
1012 return Err(format!("a note is required to hold run {id}"));
1013 }
1014 let wt_dir = root.join(".wt");
1015 std::fs::create_dir_all(&wt_dir)
1016 .map_err(|e| format!("error creating directory {}: {e}", wt_dir.display()))?;
1017 let hold_path = wt_dir.join(format!("{id}.hold.json"));
1018 let hold = Hold {
1019 note: trimmed.to_string(),
1020 ts: now,
1021 };
1022 let json_str =
1023 serde_json::to_string_pretty(&hold).map_err(|e| format!("error serializing hold: {e}"))?;
1024 std::fs::write(&hold_path, json_str + "\n")
1025 .map_err(|e| format!("error writing {}: {e}", hold_path.display()))
1026}
1027
1028pub fn clear_hold(root: &Path, id: &str) -> Result<(), String> {
1029 let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
1030 match std::fs::remove_file(&hold_path) {
1031 Ok(()) => Ok(()),
1032 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
1033 Err(e) => Err(format!("error removing {}: {e}", hold_path.display())),
1034 }
1035}
1036
1037pub fn read_hold(root: &Path, id: &str) -> Result<Option<Hold>, String> {
1038 let hold_path = root.join(".wt").join(format!("{id}.hold.json"));
1039 let raw = match std::fs::read_to_string(&hold_path) {
1040 Ok(s) => s,
1041 Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(None),
1042 Err(e) => return Err(format!("error reading {}: {e}", hold_path.display())),
1043 };
1044 serde_json::from_str::<Hold>(&raw)
1045 .map(Some)
1046 .map_err(|e| format!("could not parse {}: {e}", hold_path.display()))
1047}
1048
1049pub fn decide(
1050 root: &Path,
1051 id: &str,
1052 action: Action,
1053 note: Option<&str>,
1054 now: u64,
1055) -> Result<Decision, String> {
1056 let wt_dir = root.join(".wt");
1057 let summary_path = wt_dir.join(format!("{id}.json"));
1058 let summary_raw = match std::fs::read_to_string(&summary_path) {
1059 Ok(s) => s,
1060 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
1061 return Err(format!("no finished run {id} in {}", wt_dir.display()));
1062 }
1063 Err(e) => {
1064 return Err(format!("error reading {}: {e}", summary_path.display()));
1065 }
1066 };
1067 let summary: serde_json::Value = serde_json::from_str(&summary_raw)
1068 .map_err(|e| format!("could not parse {}: {e}", summary_path.display()))?;
1069 let outcome = summary
1070 .get("outcome")
1071 .and_then(|v| v.as_str())
1072 .ok_or_else(|| format!("{} has no outcome", summary_path.display()))?;
1073 let is_research =
1074 crate::clean::is_research(root, id) || wt_dir.join(format!("{id}.report.md")).exists();
1075
1076 let trimmed_note: Option<String> = note
1077 .map(str::trim)
1078 .filter(|s| !s.is_empty())
1079 .map(String::from);
1080
1081 let conversation_message = match action {
1082 Action::Accept => {
1083 if is_research {
1084 return Err(format!("run {id} is a research run; mark it read"));
1085 }
1086 if outcome != "verified" {
1087 return Err(format!(
1088 "run {id} is {outcome}, not verified; it cannot be accepted"
1089 ));
1090 }
1091 record_verdict(
1092 root,
1093 id,
1094 ReviewVerdict::Accepted,
1095 trimmed_note.as_deref().unwrap_or(""),
1096 now,
1097 )?;
1098 clear_hold(root, id)?;
1099 None
1100 }
1101 Action::SendBack => {
1102 let Some(ref text) = trimmed_note else {
1103 return Err(format!("a note is required to send back run {id}"));
1104 };
1105 clear_hold(root, id)?;
1106 Some(format!(
1107 "Send back run {id}: {text} Draft a follow-up task for me to confirm."
1108 ))
1109 }
1110 Action::Redo => {
1111 record_verdict(
1112 root,
1113 id,
1114 ReviewVerdict::Redone,
1115 trimmed_note.as_deref().unwrap_or(""),
1116 now,
1117 )?;
1118 clear_hold(root, id)?;
1119 let msg = match trimmed_note.as_deref() {
1120 Some(text) => format!("Redo run {id}. Reason: {text}"),
1121 None => format!("Redo run {id}."),
1122 };
1123 Some(msg)
1124 }
1125 Action::Hold => {
1126 let Some(ref text) = trimmed_note else {
1127 return Err(format!("a note is required to hold run {id}"));
1128 };
1129 set_hold(root, id, text, now)?;
1130 None
1131 }
1132 Action::MarkRead => {
1133 if !is_research {
1134 return Err(format!("run {id} is not a research run"));
1135 }
1136 record_verdict(root, id, ReviewVerdict::Accepted, "read", now)?;
1137 clear_hold(root, id)?;
1138 None
1139 }
1140 };
1141
1142 Ok(Decision {
1143 run: id.to_string(),
1144 action,
1145 note: trimmed_note,
1146 conversation_message,
1147 })
1148}
1149
1150#[cfg(test)]
1151mod tests {
1152 use super::*;
1153
1154 fn git(dir: &Path, args: &[&str]) -> String {
1155 let out = Command::new("git")
1156 .args(["-c", "user.name=t", "-c", "user.email=t@t"])
1157 .args(args)
1158 .current_dir(dir)
1159 .output()
1160 .unwrap();
1161 assert!(
1162 out.status.success(),
1163 "git {args:?} failed: {}",
1164 String::from_utf8_lossy(&out.stderr)
1165 );
1166 String::from_utf8_lossy(&out.stdout).trim().to_string()
1167 }
1168
1169 fn init_repo() -> (tempfile::TempDir, String) {
1170 let d = tempfile::tempdir().unwrap();
1171 git(d.path(), &["init", "-q"]);
1172 std::fs::write(d.path().join("f.txt"), "hello\n").unwrap();
1173 git(d.path(), &["add", "."]);
1174 git(d.path(), &["commit", "-qm", "init", "--no-gpg-sign"]);
1175 std::fs::create_dir_all(d.path().join(".wt")).unwrap();
1176 let head = git(d.path(), &["rev-parse", "HEAD"]);
1177 (d, head)
1178 }
1179
1180 fn setup_finished_code_run(root: &Path, id: &str, base_sha: Option<&str>) {
1181 let wt_path = root.join(".wt").join(id);
1182 git(
1183 root,
1184 &[
1185 "worktree",
1186 "add",
1187 "-q",
1188 "-b",
1189 &format!("wip/{id}"),
1190 wt_path.to_str().unwrap(),
1191 "HEAD",
1192 ],
1193 );
1194 let mut start = serde_json::json!({
1195 "id": id,
1196 "pid": 999999,
1197 "started_at": 1000,
1198 "research": false,
1199 });
1200 if let Some(sha) = base_sha {
1201 start["base_sha"] = serde_json::json!(sha);
1202 }
1203 std::fs::write(
1204 root.join(".wt").join(format!("{id}.start.json")),
1205 start.to_string(),
1206 )
1207 .unwrap();
1208 std::fs::write(
1209 root.join(".wt").join(format!("{id}.report.json")),
1210 serde_json::json!({ "outcome": "error", "turns": 0 }).to_string(),
1211 )
1212 .unwrap();
1213 std::fs::write(
1214 root.join(".wt").join(format!("{id}.json")),
1215 serde_json::json!({
1216 "outcome": "error",
1217 "seconds": 1,
1218 "final_message": "",
1219 "commits": [],
1220 "changed_files": []
1221 })
1222 .to_string(),
1223 )
1224 .unwrap();
1225 }
1226
1227 #[test]
1228 fn ensure_checks_skips_when_worktree_vanishes_before_git_commands() {
1229 let (d, head) = init_repo();
1230 setup_finished_code_run(d.path(), "M2", Some(&head));
1231 let root = d.path().to_path_buf();
1232 let remove_wt = move || {
1233 let wt = root.join(".wt/M2");
1234 let status = Command::new("git")
1235 .args(["worktree", "remove", "--force"])
1236 .arg(&wt)
1237 .current_dir(&root)
1238 .status()
1239 .unwrap();
1240 assert!(status.success());
1241 };
1242
1243 let wrote = ensure_checks_with_hook(d.path(), "M2", Some(&remove_wt)).unwrap();
1244 assert!(!wrote);
1245 assert!(!d.path().join(".wt/M2").exists());
1246 assert!(!d.path().join(".wt/M2.checks.json").exists());
1247 }
1248
1249 #[test]
1250 fn ensure_checks_skips_when_worktree_vanishes_without_base_sha() {
1251 let (d, _head) = init_repo();
1252 setup_finished_code_run(d.path(), "M3", None);
1253 let root = d.path().to_path_buf();
1254 let remove_wt = move || {
1255 let wt = root.join(".wt/M3");
1256 let status = Command::new("git")
1257 .args(["worktree", "remove", "--force"])
1258 .arg(&wt)
1259 .current_dir(&root)
1260 .status()
1261 .unwrap();
1262 assert!(status.success());
1263 };
1264
1265 let wrote = ensure_checks_with_hook(d.path(), "M3", Some(&remove_wt)).unwrap();
1266 assert!(!wrote);
1267 assert!(!d.path().join(".wt/M3.checks.json").exists());
1268 }
1269
1270 #[test]
1271 fn ensure_checks_still_errors_when_base_sha_is_not_in_repository() {
1272 let (d, _head) = init_repo();
1273 let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1274 setup_finished_code_run(d.path(), "BAD1", Some(missing));
1275
1276 let err = ensure_checks(d.path(), "BAD1").unwrap_err();
1277 assert!(
1278 err.contains(&format!(
1279 "run BAD1 started from {missing}, which is not in this repository"
1280 )),
1281 "unexpected error: {err}"
1282 );
1283 }
1284
1285 #[test]
1286 fn research_review_uses_no_worktree_path_when_worktree_vanishes_mid_read() {
1287 let (d, _head) = init_repo();
1288 let wt = d.path().join(".wt/R1");
1289 std::fs::create_dir_all(&wt).unwrap();
1290 git(&wt, &["init", "-q"]);
1291 git(
1292 &wt,
1293 &[
1294 "commit",
1295 "-q",
1296 "--allow-empty",
1297 "-m",
1298 "research",
1299 "--no-gpg-sign",
1300 ],
1301 );
1302 std::fs::write(
1303 d.path().join(".wt/R1.start.json"),
1304 serde_json::json!({ "id": "R1", "research": true }).to_string(),
1305 )
1306 .unwrap();
1307 std::fs::write(
1308 d.path().join(".wt/R1.report.json"),
1309 serde_json::json!({ "outcome": "verified", "turns": 1 }).to_string(),
1310 )
1311 .unwrap();
1312
1313 let wt_to_remove = wt.clone();
1314 let remove_wt = move || {
1315 std::fs::remove_dir_all(&wt_to_remove).unwrap();
1316 };
1317 let data = compute_review_res(d.path(), "R1", false, None, Some(&remove_wt))
1318 .map_err(ReviewError::into_message)
1319 .unwrap();
1320 assert!(!data.wt_exists);
1321 assert!(data.is_research);
1322 }
1323
1324 #[test]
1325 fn review_summary_errors_when_worktree_git_io_fails_naming_args() {
1326 let (d, head) = init_repo();
1327 setup_finished_code_run(d.path(), "G1", Some(&head));
1328 let wt = d.path().join(".wt/G1");
1329 let range = format!("{head}..HEAD");
1330
1331 let failing_calls: &[(&[&str], &str)] = &[
1332 (&["log", "--oneline"], "log --oneline"),
1333 (&["diff", "--stat"], "diff --stat"),
1334 (&["status", "--short"], "status --short"),
1335 (&["diff", range.as_str()], "diff"),
1336 (&["diff", "--name-only"], "diff --name-only"),
1337 (&["log", "--format=%s"], "log --format=%s"),
1338 ];
1339
1340 for &(fail_prefix, expected_args) in failing_calls {
1341 let runner = |dir: &Path, args: &[&str]| -> WtGit {
1342 if args.starts_with(fail_prefix) {
1343 WtGit::IoErr(std::io::Error::new(
1344 std::io::ErrorKind::NotFound,
1345 "git binary missing",
1346 ))
1347 } else {
1348 run_git_in_wt(dir, args)
1349 }
1350 };
1351 let err = compute_review_res_with_runner(d.path(), "G1", false, None, None, &runner)
1352 .err()
1353 .expect("expected error")
1354 .into_message();
1355 assert!(
1356 err.contains("could not run git"),
1357 "for {expected_args}, got: {err}"
1358 );
1359 assert!(
1360 err.contains(expected_args),
1361 "for {expected_args}, got: {err}"
1362 );
1363 assert!(
1364 err.contains(&wt.display().to_string()),
1365 "for {expected_args}, got: {err}"
1366 );
1367 assert!(
1368 err.contains("git binary missing"),
1369 "for {expected_args}, got: {err}"
1370 );
1371 }
1372 }
1373
1374 #[test]
1375 fn review_summary_errors_when_worktree_git_exits_nonzero_with_stderr() {
1376 let (d, head) = init_repo();
1377 setup_finished_code_run(d.path(), "G2", Some(&head));
1378
1379 let runner = |dir: &Path, args: &[&str]| -> WtGit {
1380 if args.starts_with(&["diff", "--stat"]) {
1381 let mut out = Command::new("sh")
1382 .args(["-c", "echo 'fatal: bad revision' >&2; exit 128"])
1383 .output()
1384 .unwrap();
1385 out.stdout.clear();
1386 WtGit::Output(out)
1387 } else {
1388 run_git_in_wt(dir, args)
1389 }
1390 };
1391 let err = compute_review_res_with_runner(d.path(), "G2", false, None, None, &runner)
1392 .err()
1393 .expect("expected error")
1394 .into_message();
1395 assert!(err.contains("diff --stat"), "got: {err}");
1396 assert!(err.contains("fatal: bad revision"), "got: {err}");
1397 }
1398
1399 #[test]
1400 fn compute_review_errors_on_corrupt_report_json_naming_file() {
1401 let (d, head) = init_repo();
1402 setup_finished_code_run(d.path(), "C1", Some(&head));
1403 let report_path = d.path().join(".wt/C1.report.json");
1404 std::fs::write(&report_path, "{corrupt json").unwrap();
1405
1406 let err = compute_review(d.path(), "C1", false)
1407 .err()
1408 .expect("expected error for corrupt report.json");
1409 assert!(
1410 err.contains(&report_path.display().to_string()),
1411 "got: {err}"
1412 );
1413 }
1414
1415 #[test]
1416 fn compute_review_errors_on_unreadable_log_directory_naming_file() {
1417 let (d, head) = init_repo();
1418 setup_finished_code_run(d.path(), "C2", Some(&head));
1419 let log_path = d.path().join(".wt/C2.log");
1420 std::fs::create_dir_all(&log_path).unwrap();
1421
1422 let err = compute_review(d.path(), "C2", false)
1423 .err()
1424 .expect("expected error for unreadable log directory");
1425 assert!(err.contains(&log_path.display().to_string()), "got: {err}");
1426 }
1427
1428 #[test]
1429 fn compute_review_errors_on_corrupt_summary_json_when_report_absent() {
1430 let (d, head) = init_repo();
1431 setup_finished_code_run(d.path(), "C3", Some(&head));
1432 std::fs::remove_file(d.path().join(".wt/C3.report.json")).unwrap();
1433 let summary_path = d.path().join(".wt/C3.json");
1434 std::fs::write(&summary_path, "not json at all").unwrap();
1435
1436 let err = compute_review(d.path(), "C3", false)
1437 .err()
1438 .expect("expected error for corrupt summary json");
1439 assert!(
1440 err.contains(&summary_path.display().to_string()),
1441 "got: {err}"
1442 );
1443 }
1444
1445 #[test]
1446 fn research_review_errors_on_rev_list_io_err_empty_and_multiline() {
1447 let (d, _head) = init_repo();
1448 let wt = d.path().join(".wt/R2");
1449 std::fs::create_dir_all(&wt).unwrap();
1450 git(&wt, &["init", "-q"]);
1451 git(
1452 &wt,
1453 &[
1454 "commit",
1455 "-q",
1456 "--allow-empty",
1457 "-m",
1458 "research",
1459 "--no-gpg-sign",
1460 ],
1461 );
1462 std::fs::write(
1463 d.path().join(".wt/R2.start.json"),
1464 serde_json::json!({ "id": "R2", "research": true, "base_sha": serde_json::Value::Null })
1465 .to_string(),
1466 )
1467 .unwrap();
1468 std::fs::write(
1469 d.path().join(".wt/R2.report.json"),
1470 serde_json::json!({ "outcome": "budget_exhausted", "turns": 1 }).to_string(),
1471 )
1472 .unwrap();
1473
1474 let io_runner = |dir: &Path, args: &[&str]| -> WtGit {
1475 if args == ["rev-list", "--max-parents=0", "HEAD"] {
1476 WtGit::IoErr(std::io::Error::new(
1477 std::io::ErrorKind::NotFound,
1478 "git binary missing",
1479 ))
1480 } else {
1481 run_git_in_wt(dir, args)
1482 }
1483 };
1484 let io_err = compute_review_res_with_runner(d.path(), "R2", false, None, None, &io_runner)
1485 .err()
1486 .expect("expected IoErr")
1487 .into_message();
1488 assert!(
1489 io_err.contains("rev-list --max-parents=0 HEAD"),
1490 "got: {io_err}"
1491 );
1492 assert!(io_err.contains(&wt.display().to_string()), "got: {io_err}");
1493 assert!(io_err.contains("git binary missing"), "got: {io_err}");
1494
1495 let empty_runner = |dir: &Path, args: &[&str]| -> WtGit {
1496 if args == ["rev-list", "--max-parents=0", "HEAD"] {
1497 let mut out = Command::new("sh").args(["-c", "exit 0"]).output().unwrap();
1498 out.stdout.clear();
1499 out.stderr.clear();
1500 WtGit::Output(out)
1501 } else {
1502 run_git_in_wt(dir, args)
1503 }
1504 };
1505 let empty_err =
1506 compute_review_res_with_runner(d.path(), "R2", false, None, None, &empty_runner)
1507 .err()
1508 .expect("expected empty output error")
1509 .into_message();
1510 assert!(empty_err.contains("research run R2"), "got: {empty_err}");
1511 assert!(
1512 empty_err.contains(&wt.display().to_string()),
1513 "got: {empty_err}"
1514 );
1515
1516 let multi_runner = |dir: &Path, args: &[&str]| -> WtGit {
1517 if args == ["rev-list", "--max-parents=0", "HEAD"] {
1518 let out = Command::new("sh")
1519 .args(["-c", "printf 'aaaa1111\\nbbbb2222\\n'"])
1520 .output()
1521 .unwrap();
1522 WtGit::Output(out)
1523 } else {
1524 run_git_in_wt(dir, args)
1525 }
1526 };
1527 let multi_err =
1528 compute_review_res_with_runner(d.path(), "R2", false, None, None, &multi_runner)
1529 .err()
1530 .expect("expected multi-line output error")
1531 .into_message();
1532 assert!(multi_err.contains("research run R2"), "got: {multi_err}");
1533 assert!(
1534 multi_err.contains(&wt.display().to_string()),
1535 "got: {multi_err}"
1536 );
1537 assert!(multi_err.contains("aaaa1111"), "got: {multi_err}");
1538 assert!(multi_err.contains("bbbb2222"), "got: {multi_err}");
1539 }
1540
1541 #[test]
1542 fn research_review_with_base_sha_still_checks_recorded_base_sha() {
1543 let (d, _head) = init_repo();
1544 let wt = d.path().join(".wt/R3");
1545 std::fs::create_dir_all(&wt).unwrap();
1546 git(&wt, &["init", "-q"]);
1547 git(
1548 &wt,
1549 &[
1550 "commit",
1551 "-q",
1552 "--allow-empty",
1553 "-m",
1554 "research",
1555 "--no-gpg-sign",
1556 ],
1557 );
1558 let missing = "deadbeefdeadbeefdeadbeefdeadbeefdeadbeef";
1559 std::fs::write(
1560 d.path().join(".wt/R3.start.json"),
1561 serde_json::json!({ "id": "R3", "research": true, "base_sha": missing }).to_string(),
1562 )
1563 .unwrap();
1564 std::fs::write(
1565 d.path().join(".wt/R3.report.json"),
1566 serde_json::json!({ "outcome": "budget_exhausted", "turns": 1 }).to_string(),
1567 )
1568 .unwrap();
1569
1570 let err = compute_review(d.path(), "R3", false)
1571 .err()
1572 .expect("expected missing base_sha error");
1573 assert!(
1574 err.contains(&format!(
1575 "run R3 started from {missing}, which is not in this repository"
1576 )),
1577 "got: {err}"
1578 );
1579 }
1580}