Skip to main content

blyte_cli/
dispatch.rs

1//! `blyte dispatch` and `blyte review` commands.
2
3use serde::{Deserialize, Serialize};
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use crate::cli::{DispatchArgs, ReviewArgs};
8
9pub const DISPATCH_RULES: &str = r#"Rules:
10- Stay within the task. If it cannot pass without a small change elsewhere, make the smallest one and say so.
11- Never delete, clean or modify anything outside the worktree, and never change the machine to make a check pass. If a check fails because of the environment (disk, network, a missing service), stop and say so.
12- Find files with the glob tool and search file contents with the grep tool. Do not run `find`, `grep -r` or `rg` in the shell over `/`, your home directory, or any directory outside the worktree: they walk huge trees and are killed at the time limit.
13- Do not push, open pull requests, or read secrets.
14- Commit locally before you stop, with the exact commit message the task gives (or a conventional one if it gives none).
15- When you believe the task is done and committed, stop calling tools: the harness then runs the check. Before that, run the check's quick steps (formatting, lint, the tests for your change) yourself; the full run happens at the gate.
16- Do not run the full test suite or the whole check yourself, not before you start and not while you work: the gate runs it when you stop, and each extra run costs minutes. Run the tests for the code you change.
17- Finish with a short report: what you changed, what you ran, and anything that deviated from the task."#;
18
19/// Writes a start record as pretty JSON plus a newline, through a temporary file renamed
20/// into place, so a concurrent reader never sees a partly written file.
21pub fn write_start_record(
22    path: &std::path::Path,
23    value: &serde_json::Value,
24) -> std::io::Result<()> {
25    let mut json = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
26    json.push('\n');
27    let mut tmp_name = path.as_os_str().to_os_string();
28    tmp_name.push(".tmp");
29    let tmp_path = std::path::PathBuf::from(tmp_name);
30    std::fs::write(&tmp_path, json)?;
31    std::fs::rename(&tmp_path, path)
32}
33
34pub fn wrap_task(task: &str) -> String {
35    format!(
36        "You are implementing exactly one task. Your working directory is a git worktree on its own branch; work only there.\n\n{}\n\n{}",
37        task.trim(),
38        DISPATCH_RULES
39    )
40}
41
42pub const RESEARCH_RULES: &str = r#"Rules:
43- Do not create, modify, move or delete any file anywhere except `report.md` in your working directory.
44- Do not run git commands that change state (no checkout, pull, commit, stash, worktree), and do not build, install, push, open pull requests, or write to any service.
45- Read the code with the read, grep and glob tools, using absolute paths under the repository (glob and grep with `path` set to the repository's absolute path); use the shell only when they cannot do what you need. Do not run `find`, `grep -r` or `rg` in the shell over `/`, your home directory, or any directory outside the repository: they walk huge trees and are killed at the time limit.
46- Answer the question with evidence: file paths with line numbers, and quote only what is needed.
47- To quote code, do not retype it: put a line `<<quote /absolute/path:N-M>>` on its own in report.md (at most 200 lines) and the harness replaces it with those lines of the file. You need the line numbers, not a fresh read of the file.
48- Write your findings to `report.md` in your working directory, then stop calling tools and reply with one line summarising them.
49- The harness checks report.md: every cited `path:line` must exist, and a code block must be copied from the file and lines cited on the line before it (`path:N-M`). A code block you type yourself is checked the same way, so prefer the quote line. A code block with no citation fails unless it is a command or output (```bash, ```text) or is tagged ```proposed (code you propose or sketch, not in the repository). If the check fails you get the list of problems to fix.
50- Start report.md early, after your first findings, and keep it updated as you go, so it always holds your best answer."#;
51
52pub fn wrap_research(question: &str, root: &Path) -> String {
53    format!(
54        "READ-ONLY RESEARCH TASK. The code to research is under {}: read it there by absolute path.\n\n{}\n\n{}",
55        root.display(),
56        question.trim(),
57        RESEARCH_RULES
58    )
59}
60
61pub fn quick_steps(gate: &str) -> Option<String> {
62    let lines: Vec<&str> = gate
63        .lines()
64        .map(str::trim)
65        .filter(|l| !l.is_empty())
66        .collect();
67    if lines.len() < 2 {
68        return None;
69    }
70    let steps = lines[..lines.len() - 1]
71        .iter()
72        .map(|s| format!("`{s}`"))
73        .collect::<Vec<_>>()
74        .join(", ");
75    Some(format!(
76        "The check's quick steps, to run yourself before you stop: {steps}. The last step, the full run, happens at the gate."
77    ))
78}
79
80pub fn dispatch_outcome(report_outcome: &str, commits: usize) -> &'static str {
81    match report_outcome {
82        "verified" => {
83            if commits == 0 {
84                "no_changes"
85            } else {
86                "verified"
87            }
88        }
89        "gate_failed" => "gate_failed",
90        "budget_exhausted" => "budget_exhausted",
91        "blocked" => "blocked",
92        "error" => "error",
93        _ => "error",
94    }
95}
96
97pub fn exit_code(outcome: &str) -> i32 {
98    match outcome {
99        "verified" => 0,
100        "no_changes" => 4,
101        "blocked" => 5,
102        _ => 1,
103    }
104}
105
106#[derive(Debug, Serialize)]
107pub struct CommitRecord {
108    pub sha: String,
109    pub subject: String,
110}
111
112#[derive(Debug, Serialize)]
113pub struct DispatchSummary {
114    pub id: String,
115    pub worktree: String,
116    pub branch: String,
117    pub outcome: &'static str,
118    pub exit: i32,
119    pub error: Option<String>,
120    pub commits: Vec<CommitRecord>,
121    pub changed_files: Vec<String>,
122    pub final_message: Option<String>,
123    pub turns: u32,
124    pub gate_attempts: u32,
125    pub gate_failures: Vec<String>,
126    pub cost_usd: Option<f64>,
127    pub model: Option<String>,
128    pub seconds: u64,
129    pub sandbox: String,
130    pub log: String,
131    pub report: String,
132    pub gate_source: &'static str,
133    pub research_report: Option<String>,
134}
135
136fn finish_summary(summary: &DispatchSummary, wt_parent: &Path) -> i32 {
137    let _ = std::fs::create_dir_all(wt_parent);
138    let json_str = serde_json::to_string_pretty(summary).unwrap();
139    let summary_path = wt_parent.join(format!("{}.json", summary.id));
140    let _ = std::fs::write(&summary_path, format!("{json_str}\n"));
141    println!("{json_str}");
142    summary.exit
143}
144
145pub fn branch_exists_message(root: &Path, branch: &str, id: &str) -> String {
146    if crate::clean::is_branch_merged(root, branch) {
147        format!(
148            "error: branch {branch} already exists from an earlier run, and its work is already merged. Run `blyte clean` to remove it, or dispatch with a new ID."
149        )
150    } else {
151        format!(
152            "error: branch {branch} already exists from an earlier run and is not merged. Review it with `blyte review {id}`, delete it (`git branch -D {branch}`) if it is not needed, or dispatch with a new ID."
153        )
154    }
155}
156
157/// Source-state block for the research root and each read root, skipping duplicates.
158fn research_source_block(
159    root: &Path,
160    config_allow_read: &[PathBuf],
161    allow_read: &[PathBuf],
162) -> String {
163    let mut roots: Vec<PathBuf> = vec![root.to_path_buf()];
164    for r in config_allow_read.iter().chain(allow_read) {
165        if !roots.contains(r) {
166            roots.push(r.clone());
167        }
168    }
169    let sources: Vec<(PathBuf, crate::provenance::SourceState)> = roots
170        .into_iter()
171        .map(|p| {
172            let state = crate::provenance::source_state(&p);
173            (p, state)
174        })
175        .collect();
176    crate::provenance::render(&sources)
177}
178
179/// Appends the source-state block to a copied report. Failure is reported, not fatal.
180fn append_source_state(path: &Path, block: &str) {
181    use std::io::Write;
182    let result = std::fs::OpenOptions::new()
183        .append(true)
184        .open(path)
185        .and_then(|mut f| f.write_all(format!("\n\n{block}").as_bytes()));
186    if let Err(e) = result {
187        eprintln!(
188            "error: could not add the source state to {}: {e}",
189            path.display()
190        );
191    }
192}
193
194pub fn run_dispatch(args: &DispatchArgs) -> i32 {
195    if let Ok(home) = crate::skill::home_dir() {
196        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
197            eprintln!(
198                "blyte: added context rules to {} (they apply from the next Claude session)",
199                path.display()
200            );
201        }
202    }
203
204    // 1. Root repository discovery and worktree preparation
205    let out = Command::new("git")
206        .args(["rev-parse", "--show-toplevel"])
207        .output();
208    let Ok(out) = out else {
209        eprintln!("error: git not found");
210        return 2;
211    };
212    if !out.status.success() {
213        eprintln!("error: not a git repository");
214        return 2;
215    }
216    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
217    let root = match crate::clean::find_repo_root() {
218        Ok(r) => r,
219        Err(e) => {
220            eprintln!("error: {e}");
221            return 2;
222        }
223    };
224    crate::registry::register(&root);
225
226    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
227        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
228        Ok(None) => (None, false),
229        Err(e) => {
230            eprintln!("{e}");
231            return 2;
232        }
233    };
234    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
235
236    let mut left_out: Vec<(String, String)> = Vec::new();
237    let (gate, gate_source) = if args.research {
238        ("test -s report.md".to_string(), "research")
239    } else if let Some(ref g) = args.gate {
240        (g.clone(), "flag")
241    } else if let Some(ref g) = dispatch_cfg.gate {
242        let toml_path = if from_main {
243            root.join("blyte.toml")
244        } else {
245            start_dir.join("blyte.toml")
246        };
247        let toml_content = std::fs::read_to_string(&toml_path).unwrap_or_default();
248        left_out = crate::gate_drift::left_out_steps(&toml_content);
249        if g.trim().is_empty() {
250            eprintln!(
251                "error: the gate in blyte.toml is empty; every step was left out. Fix the steps blyte init named, or pass --gate."
252            );
253            for (cmd, reason) in &left_out {
254                eprintln!("  {cmd}: {reason}");
255            }
256            return 2;
257        }
258        let missing = crate::gate_drift::missing_ci_steps(&root, g, &toml_content);
259        if let Some(warning) = crate::gate_drift::format_gate_drift_warning(&missing) {
260            eprintln!("{warning}");
261        }
262        if !left_out.is_empty() {
263            let formatted: Vec<String> = left_out
264                .iter()
265                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
266                .collect();
267            eprintln!(
268                "blyte: the gate is partial; left out: {}",
269                formatted.join("; ")
270            );
271        }
272        let source = if from_main {
273            "blyte.toml (main checkout)"
274        } else {
275            "blyte.toml"
276        };
277        (g.clone(), source)
278    } else {
279        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
280        return 2;
281    };
282
283    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
284    let (max_seconds, max_turns) = if args.research {
285        (
286            args.max_seconds.unwrap_or(1800),
287            args.max_turns.unwrap_or(300),
288        )
289    } else {
290        (
291            args.max_seconds
292                .or(dispatch_cfg.max_seconds)
293                .unwrap_or(3600),
294            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
295        )
296    };
297    let max_cost = args.max_cost_usd.or(dispatch_cfg.max_cost);
298    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
299    let network = args
300        .network
301        .as_deref()
302        .or(dispatch_cfg.network.as_deref())
303        .unwrap_or("on");
304
305    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
306        let content = match std::fs::read_to_string(tf) {
307            Ok(s) => s,
308            Err(e) => {
309                eprintln!("error reading task file {}: {e}", tf.display());
310                return 2;
311            }
312        };
313        (content, Some(tf.display().to_string()))
314    } else {
315        match (&args.plan, &args.plan_task) {
316            (Some(plan_path), Some(plan_task)) => {
317                let plan_str = match std::fs::read_to_string(plan_path) {
318                    Ok(s) => s,
319                    Err(e) => {
320                        eprintln!("error reading plan {plan_path}: {e}");
321                        return 2;
322                    }
323                };
324                let section = match crate::plan_section::extract(&plan_str, plan_task) {
325                    Some(sec) => sec,
326                    None => {
327                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
328                        if let Some(hint) =
329                            crate::plan_section::explain_missing(&plan_str, plan_task)
330                        {
331                            eprintln!("  {hint}");
332                        }
333                        return 2;
334                    }
335                };
336                let content = format!("From the plan {plan_path}:\n\n{section}");
337                (content, None)
338            }
339            _ => {
340                eprintln!("error: give a task file, or --plan with --plan-task");
341                return 2;
342            }
343        }
344    };
345
346    let home = std::env::var_os("HOME").map(PathBuf::from);
347    let main_checkout = root.clone();
348    let config_allow_read = match crate::config::expand_allow_read(
349        &dispatch_cfg.allow_read,
350        home.as_deref(),
351        &main_checkout,
352    ) {
353        Ok(paths) => paths,
354        Err(e) => {
355            eprintln!("{e}");
356            return 2;
357        }
358    };
359
360    if !args.no_path_check {
361        let mut readable = vec![start_dir.clone(), root.clone()];
362        readable.extend(config_allow_read.iter().cloned());
363        readable.extend(args.allow_read.iter().cloned());
364        let bad = unreadable_paths(&task_content, &readable);
365        if !bad.is_empty() {
366            let shown: Vec<String> = bad
367                .iter()
368                .take(5)
369                .map(|p| p.display().to_string())
370                .collect();
371            eprintln!(
372                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
373                shown.join(", ")
374            );
375            if args.research {
376                return 2;
377            }
378        }
379    }
380
381    let wt_parent = root.join(".wt");
382    let worktree_dir = wt_parent.join(&args.id);
383    let branch = format!("wip/{}", args.id);
384    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
385    let task_file_recorded =
386        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
387
388    if !args.research {
389        let start_path = wt_parent.join(format!("{}.start.json", args.id));
390        if start_path.exists() {
391            let start_str = match std::fs::read_to_string(&start_path) {
392                Ok(s) => s,
393                Err(e) => {
394                    eprintln!("error reading {}: {e}", start_path.display());
395                    return 2;
396                }
397            };
398            let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
399                Ok(v) => v,
400                Err(e) => {
401                    eprintln!("error parsing {}: {e}", start_path.display());
402                    return 2;
403                }
404            };
405            let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
406                eprintln!("error: missing pid in {}", start_path.display());
407                return 2;
408            };
409            let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
410                eprintln!("error: missing started_at in {}", start_path.display());
411                return 2;
412            };
413            if crate::clean::is_pid_alive(pid) {
414                let summary_path = wt_parent.join(format!("{}.json", args.id));
415                let finished_since_start = if summary_path.exists() {
416                    let meta = match std::fs::metadata(&summary_path) {
417                        Ok(m) => m,
418                        Err(e) => {
419                            eprintln!("error reading metadata of {}: {e}", summary_path.display());
420                            return 2;
421                        }
422                    };
423                    let mtime = match meta.modified() {
424                        Ok(t) => t,
425                        Err(e) => {
426                            eprintln!("error reading mtime of {}: {e}", summary_path.display());
427                            return 2;
428                        }
429                    };
430                    let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
431                        Ok(d) => d.as_secs(),
432                        Err(e) => {
433                            eprintln!("error reading timestamp of {}: {e}", summary_path.display());
434                            return 2;
435                        }
436                    };
437                    mtime_secs >= started_at
438                } else {
439                    false
440                };
441                if !finished_since_start {
442                    eprintln!(
443                        "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
444                        args.id
445                    );
446                    return 2;
447                }
448            }
449        }
450
451        let branch_ref = format!("refs/heads/{branch}");
452        let branch_out = Command::new("git")
453            .args(["show-ref", "--verify", "--quiet", &branch_ref])
454            .current_dir(&root)
455            .output();
456        let branch_exists = match branch_out {
457            Ok(o) if o.status.success() => true,
458            Ok(o) if o.status.code() == Some(1) => false,
459            Ok(o) => {
460                eprintln!(
461                    "error: git show-ref --verify --quiet {branch_ref}: {}",
462                    String::from_utf8_lossy(&o.stderr).trim()
463                );
464                return 2;
465            }
466            Err(e) => {
467                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
468                return 2;
469            }
470        };
471
472        if worktree_dir.exists() || branch_exists {
473            match crate::clean::remove_finished_run(&root, &args.id) {
474                Ok(Some(reason)) => {
475                    let secs =
476                        match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
477                            Ok(d) => d.as_secs(),
478                            Err(e) => {
479                                eprintln!("error: system clock before unix epoch: {e}");
480                                return 2;
481                            }
482                        };
483                    let archive_rel = format!(".wt/archive/{}-{secs}", args.id);
484                    let archive_dir = root.join(&archive_rel);
485                    if let Err(e) = std::fs::create_dir_all(&archive_dir) {
486                        eprintln!("error: {}: {e}", archive_dir.display());
487                        return 2;
488                    }
489                    for ext in ["json", "report.json", "start.json", "verdict.json", "log"] {
490                        let file_name = format!("{}.{ext}", args.id);
491                        let src = wt_parent.join(&file_name);
492                        if src.exists() {
493                            let dst = archive_dir.join(&file_name);
494                            if let Err(e) = std::fs::rename(&src, &dst) {
495                                eprintln!(
496                                    "error: rename {} -> {}: {e}",
497                                    src.display(),
498                                    dst.display()
499                                );
500                                return 2;
501                            }
502                        }
503                    }
504                    eprintln!(
505                        "dispatch: replaced the earlier run {} ({reason}); its records are in {archive_rel}/",
506                        args.id
507                    );
508                }
509                Ok(None) => {}
510                Err(e) => {
511                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
512                    return 2;
513                }
514            }
515        }
516
517        crate::clean::spawn_background_clean(&root, Some(&args.id));
518    }
519
520    let base_commit: Option<String> = if args.research {
521        if worktree_dir.exists() {
522            eprintln!("error: {} already exists", worktree_dir.display());
523            return 2;
524        }
525        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
526            eprintln!(
527                "error creating scratch directory {}: {e}",
528                worktree_dir.display()
529            );
530            return 2;
531        }
532        let init_out = Command::new("git")
533            .args(["init", "-q"])
534            .current_dir(&worktree_dir)
535            .output();
536        match init_out {
537            Ok(o) if o.status.success() => {}
538            Ok(o) => {
539                eprintln!(
540                    "error: git init failed: {}",
541                    String::from_utf8_lossy(&o.stderr)
542                );
543                return 2;
544            }
545            Err(e) => {
546                eprintln!("error: failed to execute git init: {e}");
547                return 2;
548            }
549        }
550        let commit_out = Command::new("git")
551            .args([
552                "-c",
553                "user.name=blyte",
554                "-c",
555                "user.email=blyte@local",
556                "commit",
557                "-q",
558                "--allow-empty",
559                "-m",
560                "research",
561            ])
562            .current_dir(&worktree_dir)
563            .output();
564        match commit_out {
565            Ok(o) if o.status.success() => {}
566            Ok(o) => {
567                eprintln!(
568                    "error: git commit failed: {}",
569                    String::from_utf8_lossy(&o.stderr)
570                );
571                return 2;
572            }
573            Err(e) => {
574                eprintln!("error: failed to execute git commit: {e}");
575                return 2;
576            }
577        }
578        None
579    } else if !worktree_dir.exists() {
580        let branch_exists = Command::new("git")
581            .args([
582                "rev-parse",
583                "--verify",
584                "--quiet",
585                &format!("refs/heads/{branch}"),
586            ])
587            .current_dir(&root)
588            .output()
589            .map(|o| o.status.success())
590            .unwrap_or(false);
591        if branch_exists {
592            eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
593            return 2;
594        }
595        let base_commit = Command::new("git")
596            .args([
597                "rev-parse",
598                "--verify",
599                &format!("{}^{{commit}}", args.base),
600            ])
601            .current_dir(&start_dir)
602            .output();
603        let base_commit = match base_commit {
604            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
605            _ => {
606                eprintln!("error: base {} is not a commit", args.base);
607                return 2;
608            }
609        };
610        let add_out = Command::new("git")
611            .args([
612                "worktree",
613                "add",
614                "-b",
615                &branch,
616                worktree_dir.to_str().unwrap(),
617                &base_commit,
618            ])
619            .current_dir(&root)
620            .output();
621        match add_out {
622            Ok(o) if o.status.success() => {}
623            Ok(o) => {
624                eprintln!(
625                    "error: git worktree add failed: {}",
626                    String::from_utf8_lossy(&o.stderr)
627                );
628                return 2;
629            }
630            Err(e) => {
631                eprintln!("error: failed to execute git worktree add: {e}");
632                return 2;
633            }
634        }
635        Some(base_commit)
636    } else {
637        let base_commit = match Command::new("git")
638            .args([
639                "rev-parse",
640                "--verify",
641                &format!("{}^{{commit}}", args.base),
642            ])
643            .current_dir(&start_dir)
644            .output()
645        {
646            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
647            Ok(o) => {
648                eprintln!(
649                    "error: git rev-parse {} failed: {}",
650                    args.base,
651                    String::from_utf8_lossy(&o.stderr).trim()
652                );
653                return 2;
654            }
655            Err(e) => {
656                eprintln!("error: failed to execute git rev-parse: {e}");
657                return 2;
658            }
659        };
660        let wt_head = match Command::new("git")
661            .args([
662                "-C",
663                worktree_dir.to_str().unwrap(),
664                "rev-parse",
665                "--verify",
666                "HEAD^{commit}",
667            ])
668            .output()
669        {
670            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
671            Ok(o) => {
672                eprintln!(
673                    "error: git -C {} rev-parse HEAD failed: {}",
674                    worktree_dir.display(),
675                    String::from_utf8_lossy(&o.stderr).trim()
676                );
677                return 2;
678            }
679            Err(e) => {
680                eprintln!("error: failed to execute git rev-parse: {e}");
681                return 2;
682            }
683        };
684        let ancestor_out = Command::new("git")
685            .args(["merge-base", "--is-ancestor", &base_commit, &wt_head])
686            .current_dir(&root)
687            .output();
688        match ancestor_out {
689            Ok(o) if o.status.success() => {}
690            Ok(o) if o.status.code() == Some(1) => {
691                let short_wt_head = &wt_head[..wt_head.len().min(7)];
692                let short_base = &base_commit[..base_commit.len().min(7)];
693                eprintln!(
694                    "error: .wt/{id} is from an earlier run based on {short_wt_head}, which does not contain {short_base} ({base_name}). Run `blyte clean`, remove it with `git worktree remove .wt/{id}` and `git branch -D wip/{id}` if it is not needed, or dispatch with a new ID.",
695                    id = args.id,
696                    base_name = args.base,
697                );
698                return 2;
699            }
700            Ok(o) => {
701                eprintln!(
702                    "error: git merge-base --is-ancestor failed: {}",
703                    String::from_utf8_lossy(&o.stderr).trim()
704                );
705                return 2;
706            }
707            Err(e) => {
708                eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
709                return 2;
710            }
711        }
712        Some(base_commit)
713    };
714
715    // 2. Ensure .wt/ is in info/exclude
716    let common_dir_raw = Command::new("git")
717        .args(["rev-parse", "--git-common-dir"])
718        .current_dir(&root)
719        .output();
720    let common_dir = if let Ok(out) = common_dir_raw {
721        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
722        if p.is_absolute() {
723            p
724        } else {
725            root.join(p)
726        }
727    } else {
728        root.join(".git")
729    };
730
731    let exclude_path = common_dir.join("info").join("exclude");
732    if let Some(parent) = exclude_path.parent() {
733        let _ = std::fs::create_dir_all(parent);
734    }
735    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
736    if !content.lines().any(|l| l.trim() == ".wt/") {
737        let mut new_content = content;
738        if !new_content.is_empty() && !new_content.ends_with('\n') {
739            new_content.push('\n');
740        }
741        new_content.push_str(".wt/\n");
742        let _ = std::fs::write(&exclude_path, new_content);
743    }
744
745    // 3. Record base_sha
746    let base_out = Command::new("git")
747        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
748        .output();
749    let base_sha = match base_out {
750        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
751        _ => {
752            eprintln!("error: could not resolve HEAD in worktree");
753            return 2;
754        }
755    };
756
757    if !args.research {
758        if let Some(ref setup_cmd) = dispatch_cfg.setup {
759            let first_line = setup_cmd.lines().next().unwrap_or("");
760            eprintln!("setup: {first_line}");
761            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
762            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
763            if let Err(msg) = crate::setup::run_setup(
764                setup_cmd,
765                &worktree_dir,
766                &main_checkout,
767                &dispatch_cfg.env,
768                &setup_log_path,
769                crate::setup::SETUP_TIMEOUT,
770            ) {
771                let outcome = "blocked";
772                let exit = exit_code(outcome);
773                let first_line_err = msg.lines().next().unwrap_or("").to_string();
774                let summary = DispatchSummary {
775                    id: args.id.clone(),
776                    worktree: worktree_dir.display().to_string(),
777                    branch: branch.clone(),
778                    outcome,
779                    exit,
780                    error: Some(first_line_err),
781                    commits: Vec::new(),
782                    changed_files: Vec::new(),
783                    final_message: Some(msg),
784                    turns: 0,
785                    gate_attempts: 0,
786                    gate_failures: Vec::new(),
787                    cost_usd: None,
788                    model: None,
789                    seconds: 0,
790                    sandbox: args.sandbox.clone(),
791                    log: setup_log_path.display().to_string(),
792                    report: "".to_string(),
793                    gate_source,
794                    research_report: None,
795                };
796                return finish_summary(&summary, &wt_parent);
797            }
798        }
799    }
800
801    // 4. Write task file and spawn child process
802    let _ = std::fs::create_dir_all(&wt_parent);
803    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
804        eprintln!("error writing task file {}: {e}", task_md_path.display());
805        return 2;
806    }
807
808    let log_path = wt_parent.join(format!("{}.log", args.id));
809    let summary_path = wt_parent.join(format!("{}.json", args.id));
810    if summary_path.exists() {
811        let _ = std::fs::remove_file(&summary_path);
812    }
813    let report_path = wt_parent.join(format!("{}.report.json", args.id));
814    if report_path.exists() {
815        let _ = std::fs::remove_file(&report_path);
816    }
817    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
818    if research_report_path.exists() {
819        let _ = std::fs::remove_file(&research_report_path);
820    }
821
822    let log_file = match std::fs::File::create(&log_path) {
823        Ok(f) => f,
824        Err(e) => {
825            eprintln!("error creating log file {}: {e}", log_path.display());
826            return 2;
827        }
828    };
829    let log_file_err = match log_file.try_clone() {
830        Ok(f) => f,
831        Err(e) => {
832            eprintln!("error cloning log file handle: {e}");
833            return 2;
834        }
835    };
836
837    let current_exe = match std::env::current_exe() {
838        Ok(p) => p,
839        Err(e) => {
840            eprintln!("error getting current executable: {e}");
841            return 2;
842        }
843    };
844
845    let mut cmd = Command::new(current_exe);
846    cmd.current_dir(&worktree_dir);
847    cmd.stdout(log_file);
848    cmd.stderr(log_file_err);
849
850    for (k, v) in &dispatch_cfg.env {
851        cmd.env(k, v);
852    }
853    cmd.env("BLYTE_DISPATCH_ID", &args.id);
854
855    cmd.arg("--gate").arg(&gate);
856    cmd.arg("--rollback=false");
857    cmd.arg("--max-seconds").arg(max_seconds.to_string());
858    cmd.arg("--max-turns").arg(max_turns.to_string());
859    cmd.arg("--report").arg(&report_path);
860
861    if let Some(m) = model {
862        cmd.arg("--model").arg(m);
863    }
864    if let Some(c) = max_cost {
865        cmd.arg("--max-cost").arg(c.to_string());
866    }
867    if let Some(fb) = fold_budget {
868        cmd.arg("--fold-budget").arg(fb.to_string());
869    }
870    cmd.arg("--sandbox").arg(&args.sandbox);
871    cmd.arg("--network").arg(network);
872    for r in &config_allow_read {
873        cmd.arg("--allow-read").arg(r);
874    }
875    for r in &args.allow_read {
876        cmd.arg("--allow-read").arg(r);
877    }
878    for p in &args.pass_env {
879        cmd.arg("--pass-env").arg(p);
880    }
881    // The read and grep tools may read what the sandbox may read.
882    for r in config_allow_read.iter().chain(&args.allow_read) {
883        cmd.arg("--read-root").arg(r);
884    }
885    if args.research {
886        cmd.arg("--read-root").arg(&root);
887        cmd.arg("--no-gate-slot");
888        cmd.arg("--research");
889        if !args.no_claim_check {
890            cmd.arg("--claim-check");
891        }
892    }
893
894    cmd.arg("--");
895    let research_sources = args
896        .research
897        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
898    let task_prompt = if let Some(block) = &research_sources {
899        wrap_research(&format!("{block}\n\n{task_content}"), &root)
900    } else {
901        let mut prompt = wrap_task(&task_content);
902        if let Some(qs) = quick_steps(&gate) {
903            prompt.push_str("\n\n");
904            prompt.push_str(&qs);
905        }
906        prompt
907    };
908    cmd.arg(task_prompt);
909
910    let mut child = match cmd.spawn() {
911        Ok(c) => c,
912        Err(e) => {
913            eprintln!("error spawning child process: {e}");
914            return 2;
915        }
916    };
917
918    let started_at = std::time::SystemTime::now()
919        .duration_since(std::time::UNIX_EPOCH)
920        .map(|d| d.as_secs())
921        .unwrap_or(0);
922
923    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
924    let mut tags = args.tags.clone();
925    if args.research {
926        tags.push("research".to_string());
927    }
928    let mut start_json = serde_json::json!({
929        "id": args.id,
930        "pid": child.id(),
931        "started_at": started_at,
932        "task_file": task_file_recorded,
933        "gate": gate,
934        "tags": tags,
935        "env": env_names,
936        "max_turns": max_turns,
937        "max_seconds": max_seconds,
938        "plan": args.plan,
939        "plan_task": args.plan_task,
940        "base": args.base,
941        "base_sha": base_commit,
942    });
943    if let Some(session) = crate::usage_log::session_from(
944        std::env::var("BLYTE_SESSION").ok(),
945        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
946    ) {
947        start_json["session"] = serde_json::json!(session);
948    }
949    if args.research {
950        start_json["research"] = serde_json::json!(true);
951    }
952    if !left_out.is_empty() {
953        start_json["gate_left_out"] = serde_json::json!(left_out
954            .iter()
955            .map(|(command, reason)| serde_json::json!({
956                "command": command,
957                "reason": reason,
958            }))
959            .collect::<Vec<_>>());
960    }
961    let start_path = wt_parent.join(format!("{}.start.json", args.id));
962    if let Err(err) = write_start_record(&start_path, &start_json) {
963        eprintln!(
964            "error: could not write the start record {}: {err}",
965            start_path.display()
966        );
967    }
968
969    let _ = child.wait();
970
971    if !left_out.is_empty() {
972        if let Ok(report_str) = std::fs::read_to_string(&report_path) {
973            if let Ok(mut report_val) = serde_json::from_str::<serde_json::Value>(&report_str) {
974                let formatted: Vec<String> = left_out
975                    .iter()
976                    .map(|(cmd, reason)| format!("{cmd} ({reason})"))
977                    .collect();
978                report_val["gate_left_out"] = serde_json::json!(formatted);
979                if let Ok(updated) = serde_json::to_string_pretty(&report_val) {
980                    let _ = std::fs::write(&report_path, updated + "\n");
981                }
982            }
983        }
984    }
985
986    let scratch_report = worktree_dir.join("report.md");
987    if args.research {
988        let is_non_empty = std::fs::metadata(&scratch_report)
989            .map(|m| m.len() > 0)
990            .unwrap_or(false);
991        if is_non_empty {
992            let _ = std::fs::copy(&scratch_report, &research_report_path);
993            if let Some(block) = &research_sources {
994                append_source_state(&research_report_path, block);
995            }
996            if let Some(ref report_to) = args.report_to {
997                if let Some(parent) = report_to.parent() {
998                    if !parent.as_os_str().is_empty() {
999                        let _ = std::fs::create_dir_all(parent);
1000                    }
1001                }
1002                let _ = std::fs::copy(&scratch_report, report_to);
1003                if let Some(block) = &research_sources {
1004                    append_source_state(report_to, block);
1005                }
1006            }
1007        }
1008    }
1009
1010    // 5. Read report, commits and changed files
1011    let log_out = Command::new("git")
1012        .args([
1013            "-C",
1014            worktree_dir.to_str().unwrap(),
1015            "log",
1016            "--reverse",
1017            "--format=%h%x09%s",
1018            &format!("{base_sha}..HEAD"),
1019        ])
1020        .output();
1021
1022    let mut commits = Vec::new();
1023    if let Ok(o) = log_out {
1024        let text = String::from_utf8_lossy(&o.stdout);
1025        for line in text.lines() {
1026            let line = line.trim();
1027            if line.is_empty() {
1028                continue;
1029            }
1030            if let Some((sha, subject)) = line.split_once('\t') {
1031                commits.push(CommitRecord {
1032                    sha: sha.to_string(),
1033                    subject: subject.to_string(),
1034                });
1035            }
1036        }
1037    }
1038
1039    let diff_out = Command::new("git")
1040        .args([
1041            "-C",
1042            worktree_dir.to_str().unwrap(),
1043            "diff",
1044            "--name-only",
1045            &format!("{base_sha}..HEAD"),
1046        ])
1047        .output();
1048
1049    let mut changed_files = Vec::new();
1050    if let Ok(o) = diff_out {
1051        let text = String::from_utf8_lossy(&o.stdout);
1052        for line in text.lines() {
1053            let line = line.trim();
1054            if !line.is_empty() {
1055                changed_files.push(line.to_string());
1056            }
1057        }
1058    }
1059
1060    let report_read = std::fs::read_to_string(&report_path);
1061    let record: Result<serde_json::Value, String> = match report_read {
1062        Ok(s) => serde_json::from_str(&s).map_err(|e| format!("unreadable report JSON: {e}")),
1063        Err(e) => Err(format!("missing report: {e}")),
1064    };
1065
1066    let (
1067        report_outcome,
1068        error,
1069        final_message,
1070        turns,
1071        gate_attempts,
1072        gate_failures,
1073        cost_usd,
1074        model,
1075        seconds,
1076        sandbox,
1077    ) = match record {
1078        Ok(rec) => {
1079            let gate_failures = rec
1080                .get("gate_failures")
1081                .and_then(|v| v.as_array())
1082                .map(|arr| {
1083                    arr.iter()
1084                        .filter_map(|v| v.as_str())
1085                        .map(|s| {
1086                            if s.chars().count() > 1000 {
1087                                s.chars().take(1000).collect()
1088                            } else {
1089                                s.to_string()
1090                            }
1091                        })
1092                        .collect()
1093                })
1094                .unwrap_or_default();
1095
1096            (
1097                rec.get("outcome")
1098                    .and_then(|v| v.as_str())
1099                    .unwrap_or("error")
1100                    .to_string(),
1101                rec.get("error").and_then(|v| v.as_str()).map(String::from),
1102                rec.get("final_message")
1103                    .and_then(|v| v.as_str())
1104                    .map(String::from),
1105                rec.get("turns").and_then(|v| v.as_u64()).unwrap_or(0) as u32,
1106                rec.get("gate_attempts")
1107                    .and_then(|v| v.as_u64())
1108                    .unwrap_or(0) as u32,
1109                gate_failures,
1110                rec.get("cost_usd").and_then(|v| v.as_f64()),
1111                rec.get("model_id")
1112                    .and_then(|v| v.as_str())
1113                    .map(String::from),
1114                rec.get("duration_seconds")
1115                    .and_then(|v| v.as_f64())
1116                    .unwrap_or(0.0)
1117                    .round() as u64,
1118                rec.get("sandbox")
1119                    .and_then(|v| v.as_str())
1120                    .unwrap_or(&args.sandbox)
1121                    .to_string(),
1122            )
1123        }
1124        Err(err_msg) => (
1125            "error".to_string(),
1126            Some(err_msg),
1127            None,
1128            0,
1129            0,
1130            Vec::new(),
1131            None,
1132            None,
1133            0,
1134            args.sandbox.clone(),
1135        ),
1136    };
1137
1138    let outcome = if args.research {
1139        match report_outcome.as_str() {
1140            "verified" => "verified",
1141            "gate_failed" => "gate_failed",
1142            "budget_exhausted" => "budget_exhausted",
1143            "blocked" => "blocked",
1144            _ => "error",
1145        }
1146    } else {
1147        dispatch_outcome(&report_outcome, commits.len())
1148    };
1149    let exit = exit_code(outcome);
1150
1151    let research_report = if args.research && research_report_path.exists() {
1152        Some(research_report_path.display().to_string())
1153    } else {
1154        None
1155    };
1156
1157    // 6. Print JSON summary
1158    let summary = DispatchSummary {
1159        id: args.id.clone(),
1160        worktree: worktree_dir.display().to_string(),
1161        branch,
1162        outcome,
1163        exit,
1164        error,
1165        commits,
1166        changed_files,
1167        final_message,
1168        turns,
1169        gate_attempts,
1170        gate_failures,
1171        cost_usd,
1172        model,
1173        seconds,
1174        sandbox,
1175        log: log_path.display().to_string(),
1176        report: report_path.display().to_string(),
1177        gate_source,
1178        research_report,
1179    };
1180
1181    finish_summary(&summary, &wt_parent)
1182}
1183
1184pub fn run_review(args: &ReviewArgs) -> i32 {
1185    let root = match crate::clean::find_repo_root() {
1186        Ok(r) => r,
1187        Err(e) => {
1188            eprintln!("error: {e}");
1189            return 2;
1190        }
1191    };
1192
1193    if args.notes.is_some() && args.verdict.is_none() {
1194        eprintln!("error: --notes requires --verdict");
1195        return 2;
1196    }
1197
1198    if let Some(ref v) = args.verdict {
1199        let wt_dir = root.join(".wt");
1200        if let Err(e) = std::fs::create_dir_all(&wt_dir) {
1201            eprintln!("error creating directory {}: {e}", wt_dir.display());
1202            return 2;
1203        }
1204        let verdict_path = wt_dir.join(format!("{}.verdict.json", args.id));
1205        let ts = std::time::SystemTime::now()
1206            .duration_since(std::time::UNIX_EPOCH)
1207            .map(|d| d.as_secs())
1208            .unwrap_or(0);
1209        let verdict_obj = serde_json::json!({
1210            "verdict": v.as_str(),
1211            "notes": args.notes.as_deref().unwrap_or(""),
1212            "ts": ts,
1213        });
1214        let json_str = match serde_json::to_string_pretty(&verdict_obj) {
1215            Ok(s) => s,
1216            Err(e) => {
1217                eprintln!("error serializing verdict: {e}");
1218                return 2;
1219            }
1220        };
1221        if let Err(e) = std::fs::write(&verdict_path, json_str + "\n") {
1222            eprintln!("error writing {}: {e}", verdict_path.display());
1223            return 2;
1224        }
1225        println!("recorded verdict {} for {}", v.as_str(), args.id);
1226        crate::clean::clean_on_review(&root, &args.id);
1227        return 0;
1228    }
1229
1230    let wt = root.join(".wt").join(&args.id);
1231    if !wt.exists() {
1232        eprintln!("error: worktree {} does not exist", wt.display());
1233        return 2;
1234    }
1235
1236    // Runs dispatched before base_sha was recorded have no start record field; a record that
1237    // exists but cannot be read is an error, not a reason to guess the base.
1238    let start_path = root.join(".wt").join(format!("{}.start.json", args.id));
1239    let start_base_sha: Option<String> = match std::fs::read_to_string(&start_path) {
1240        Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
1241            Ok(v) => v
1242                .get("base_sha")
1243                .and_then(|s| s.as_str())
1244                .map(str::trim)
1245                .filter(|s| !s.is_empty())
1246                .map(String::from),
1247            Err(e) => {
1248                eprintln!("error: cannot parse {}: {e}", start_path.display());
1249                return 2;
1250            }
1251        },
1252        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1253        Err(e) => {
1254            eprintln!("error: cannot read {}: {e}", start_path.display());
1255            return 2;
1256        }
1257    };
1258
1259    let base = if let Some(sha) = start_base_sha {
1260        let has_base = Command::new("git")
1261            .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
1262            .current_dir(&wt)
1263            .output()
1264            .map(|o| o.status.success())
1265            .unwrap_or(false);
1266        if !has_base {
1267            eprintln!(
1268                "error: run {} started from {sha}, which is not in this repository",
1269                args.id
1270            );
1271            return 2;
1272        }
1273        sha
1274    } else {
1275        let root_head = Command::new("git")
1276            .args(["rev-parse", "HEAD"])
1277            .current_dir(&root)
1278            .output();
1279        let root_head_sha = match root_head {
1280            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1281            _ => {
1282                eprintln!("error: could not resolve root HEAD");
1283                return 2;
1284            }
1285        };
1286
1287        let mb_out = Command::new("git")
1288            .args(["merge-base", "HEAD", &root_head_sha])
1289            .current_dir(&wt)
1290            .output();
1291        match mb_out {
1292            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1293            _ => {
1294                eprintln!(
1295                    "error: cannot find where run {} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}",
1296                    args.id
1297                );
1298                return 2;
1299            }
1300        }
1301    };
1302
1303    let commits_out = Command::new("git")
1304        .args(["log", "--oneline", &format!("{base}..HEAD")])
1305        .current_dir(&wt)
1306        .output()
1307        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1308        .unwrap_or_default();
1309
1310    let files_out = Command::new("git")
1311        .args(["diff", "--stat", &format!("{base}..HEAD")])
1312        .current_dir(&wt)
1313        .output()
1314        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1315        .unwrap_or_default();
1316
1317    let tree_out = Command::new("git")
1318        .args(["status", "--short"])
1319        .current_dir(&wt)
1320        .output()
1321        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1322        .unwrap_or_default();
1323
1324    let diff_out = if args.diff {
1325        Command::new("git")
1326            .args(["diff", &format!("{base}..HEAD")])
1327            .current_dir(&wt)
1328            .output()
1329            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1330            .unwrap_or_default()
1331    } else {
1332        String::new()
1333    };
1334
1335    let task_text: Option<String> = (|| {
1336        let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1337        let content = std::fs::read_to_string(&start_file).ok()?;
1338        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1339        let task_file = val.get("task_file")?.as_str()?;
1340        let p = Path::new(task_file);
1341        if let Ok(s) = std::fs::read_to_string(p) {
1342            return Some(s);
1343        }
1344        std::fs::read_to_string(root.join(p)).ok()
1345    })();
1346
1347    let changed_files: Vec<String> = Command::new("git")
1348        .args(["diff", "--name-only", &format!("{base}..HEAD")])
1349        .current_dir(&wt)
1350        .output()
1351        .ok()
1352        .filter(|o| o.status.success())
1353        .map(|o| {
1354            String::from_utf8_lossy(&o.stdout)
1355                .lines()
1356                .map(|l| l.trim().to_string())
1357                .filter(|l| !l.is_empty())
1358                .collect()
1359        })
1360        .unwrap_or_default();
1361
1362    let subjects: Vec<String> = Command::new("git")
1363        .args(["log", "--format=%s", &format!("{base}..HEAD")])
1364        .current_dir(&wt)
1365        .output()
1366        .ok()
1367        .filter(|o| o.status.success())
1368        .map(|o| {
1369            String::from_utf8_lossy(&o.stdout)
1370                .lines()
1371                .map(|l| l.trim().to_string())
1372                .filter(|l| !l.is_empty())
1373                .collect()
1374        })
1375        .unwrap_or_default();
1376
1377    let log_file = root.join(".wt").join(format!("{}.log", args.id));
1378    let (hcmds, reads, (refused_count, refused_paths)) =
1379        if let Ok(log_content) = std::fs::read_to_string(&log_file) {
1380            let hcmds = host_commands(&log_content);
1381            let home = std::env::var_os("HOME")
1382                .map(PathBuf::from)
1383                .unwrap_or_else(|| PathBuf::from("/"));
1384            let allowed = [root.clone(), wt.clone()];
1385            let reads = outside_reads(&log_content, &allowed, &home);
1386            let refused = refused_reads(&log_content);
1387            (hcmds, reads, refused)
1388        } else {
1389            (Vec::new(), Vec::new(), (0, Vec::new()))
1390        };
1391
1392    let report_file = root.join(".wt").join(format!("{}.report.json", args.id));
1393    let report_val = std::fs::read_to_string(&report_file)
1394        .ok()
1395        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
1396    let outcome = report_val
1397        .as_ref()
1398        .and_then(|v| v.get("outcome"))
1399        .and_then(|x| x.as_str());
1400    let quote_problems: Option<Vec<&str>> = report_val
1401        .as_ref()
1402        .and_then(|v| v.get("quote_problems"))
1403        .and_then(|x| x.as_array())
1404        .map(|arr| arr.iter().filter_map(|x| x.as_str()).collect());
1405    let read_loop = report_val
1406        .as_ref()
1407        .and_then(|v| v.get("read_loop"))
1408        .and_then(|x| x.as_bool())
1409        .unwrap_or(false);
1410    let gate_left_out: Vec<String> = report_val
1411        .as_ref()
1412        .and_then(|v| v.get("gate_left_out"))
1413        .and_then(|x| x.as_array())
1414        .map(|arr| {
1415            arr.iter()
1416                .filter_map(|x| x.as_str().map(String::from))
1417                .collect::<Vec<_>>()
1418        })
1419        .filter(|v| !v.is_empty())
1420        .or_else(|| {
1421            let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1422            let content = std::fs::read_to_string(&start_file).ok()?;
1423            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1424            let arr = val.get("gate_left_out")?.as_array()?;
1425            Some(
1426                arr.iter()
1427                    .filter_map(|item| {
1428                        let cmd = item.get("command")?.as_str()?;
1429                        let reason = item.get("reason")?.as_str()?;
1430                        Some(format!("{cmd} ({reason})"))
1431                    })
1432                    .collect(),
1433            )
1434        })
1435        .unwrap_or_default();
1436    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
1437        .as_ref()
1438        .and_then(|v| v.get("claim_check"))
1439        .and_then(|x| serde_json::from_value(x.clone()).ok());
1440    let claim_check_skipped: Option<String> = report_val
1441        .as_ref()
1442        .and_then(|v| v.get("claim_check_skipped"))
1443        .and_then(|x| x.as_str())
1444        .map(String::from);
1445
1446    let mut checks = crate::review_checks::build(
1447        task_text.as_deref(),
1448        &changed_files,
1449        &subjects,
1450        hcmds.len(),
1451        reads.len(),
1452        outcome,
1453    );
1454    if let Some(ref problems) = quote_problems {
1455        if !problems.is_empty() {
1456            checks.flags.push(format!(
1457                "quote check failed ({} problem(s)): see == report",
1458                problems.len()
1459            ));
1460        }
1461    }
1462    if read_loop {
1463        checks.flags.push(
1464            "read loop: the run kept re-reading the same files without changing anything and was stopped"
1465                .to_string(),
1466        );
1467    }
1468    if !gate_left_out.is_empty() {
1469        checks
1470            .flags
1471            .push(format!("gate left out: {}", gate_left_out.join("; ")));
1472    }
1473    if let Some(ref cc) = claim_check {
1474        if !cc.contradicted.is_empty() {
1475            checks.flags.push(format!(
1476                "claim check: {} contradicted claims",
1477                cc.contradicted.len()
1478            ));
1479        }
1480    }
1481    if let Some(ref skipped) = claim_check_skipped {
1482        checks.flags.push(format!("claim check skipped: {skipped}"));
1483    }
1484    if refused_count > 0 {
1485        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
1486        checks.flags.push(format!(
1487            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
1488            first_3.join(", ")
1489        ));
1490    }
1491
1492    println!("== checks");
1493    if checks.flags.is_empty() {
1494        println!("nothing flagged");
1495    } else {
1496        for flag in &checks.flags {
1497            println!("! {flag}");
1498        }
1499    }
1500
1501    println!("== commits");
1502    if !commits_out.is_empty() {
1503        println!("{commits_out}");
1504    }
1505    println!("== files");
1506    if !files_out.is_empty() {
1507        println!("{files_out}");
1508    }
1509    println!("== tree");
1510    if tree_out.is_empty() {
1511        println!("(clean)");
1512    } else {
1513        println!("{tree_out}");
1514    }
1515    println!("== report");
1516    if let Some(ref v) = report_val {
1517        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1518            println!("outcome: {outcome}");
1519        }
1520        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1521            println!("turns: {turns}");
1522        }
1523        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1524            println!("cost_usd: {cost}");
1525        }
1526        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1527            println!("final_message: {msg}");
1528        }
1529        if let Some(ref problems) = quote_problems {
1530            if problems.is_empty() {
1531                println!("quote check: passed");
1532            } else {
1533                println!(
1534                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
1535                    problems.len()
1536                );
1537                for p in problems.iter().take(5) {
1538                    let cut: String = p.chars().take(200).collect();
1539                    println!("  {cut}");
1540                }
1541            }
1542        }
1543        if let Some(ref cc) = claim_check {
1544            println!(
1545                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
1546                cc.checked,
1547                cc.contradicted.len(),
1548                cc.not_enough_evidence,
1549                cc.parse_errors,
1550                cc.unchecked
1551            );
1552            for f in cc.contradicted.iter().take(5) {
1553                let cut: String = f.text.chars().take(200).collect();
1554                println!("  report.md:{}: {cut}", f.line);
1555                println!("    {}", f.reason);
1556            }
1557        }
1558        if let Some(ref skipped) = claim_check_skipped {
1559            println!("claim check skipped: {skipped}");
1560        }
1561    }
1562
1563    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1564    if research_report_file.exists() {
1565        println!("== research report");
1566        println!("{}", research_report_file.display());
1567        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1568            for line in content.lines().take(40) {
1569                println!("{line}");
1570            }
1571        }
1572    }
1573
1574    if !hcmds.is_empty() {
1575        println!("== host commands (may have changed things outside the worktree)");
1576        for cmd in hcmds {
1577            println!("{cmd}");
1578        }
1579    }
1580    if !reads.is_empty() {
1581        println!("== reads outside the repository");
1582        for cmd in reads {
1583            println!("{cmd}");
1584        }
1585    }
1586
1587    if args.diff {
1588        println!("== diff");
1589        if !diff_out.is_empty() {
1590            println!("{diff_out}");
1591        }
1592    }
1593
1594    if args.model_review {
1595        crate::model_review::run(&root, &args.id, &base, &wt);
1596    }
1597
1598    0
1599}
1600
1601const OUTSIDE_PATHS: &[&str] = &[
1602    "~/",
1603    "$HOME",
1604    "/Users/",
1605    "/home/",
1606    "/private/",
1607    "/var/",
1608    "/etc/",
1609    "/opt/",
1610    "/usr/",
1611];
1612
1613const CHANGE_WORDS: &[&str] = &[
1614    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1615];
1616
1617fn contains_word(cmd: &str, word: &str) -> bool {
1618    let mut start = 0;
1619    while let Some(pos) = cmd[start..].find(word) {
1620        let abs_pos = start + pos;
1621        let before_ok = if abs_pos == 0 {
1622            true
1623        } else {
1624            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1625            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1626        };
1627        let after_pos = abs_pos + word.len();
1628        let after_ok = if after_pos >= cmd.len() {
1629            true
1630        } else {
1631            let next = cmd[after_pos..].chars().next().unwrap();
1632            !next.is_alphanumeric() && next != '_' && next != '-'
1633        };
1634        if before_ok && after_ok {
1635            return true;
1636        }
1637        start = abs_pos + word.len();
1638    }
1639    false
1640}
1641
1642fn has_non_dev_null_redirect(cmd: &str) -> bool {
1643    let chars: Vec<char> = cmd.chars().collect();
1644    let mut i = 0;
1645    while i < chars.len() {
1646        if chars[i] == '>' {
1647            while i < chars.len() && chars[i] == '>' {
1648                i += 1;
1649            }
1650            if i < chars.len() && chars[i] == '|' {
1651                i += 1;
1652            }
1653            while i < chars.len() && chars[i].is_whitespace() {
1654                i += 1;
1655            }
1656            if i >= chars.len() {
1657                break;
1658            }
1659            if chars[i] == '&'
1660                && i + 1 < chars.len()
1661                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1662            {
1663                i += 1;
1664                continue;
1665            }
1666            let target_start = i;
1667            while i < chars.len()
1668                && !chars[i].is_whitespace()
1669                && chars[i] != ';'
1670                && chars[i] != '|'
1671                && chars[i] != '&'
1672                && chars[i] != ')'
1673            {
1674                i += 1;
1675            }
1676            let target: String = chars[target_start..i].iter().collect();
1677            let target = target.trim_matches(|c| c == '\'' || c == '"');
1678            if !target.is_empty() && target != "/dev/null" {
1679                return true;
1680            }
1681        } else {
1682            i += 1;
1683        }
1684    }
1685    false
1686}
1687
1688fn changes_something(cmd: &str) -> bool {
1689    for &word in CHANGE_WORDS {
1690        if contains_word(cmd, word) {
1691            return true;
1692        }
1693    }
1694    has_non_dev_null_redirect(cmd)
1695}
1696
1697fn is_host_command(cmd: &str) -> bool {
1698    if cmd.contains("git push")
1699        || cmd.contains("sudo ")
1700        || cmd.contains("cache clean")
1701        || cmd.contains("cache prune")
1702        || cmd.contains("brew ")
1703    {
1704        return true;
1705    }
1706
1707    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1708    names_outside && changes_something(cmd)
1709}
1710
1711pub fn host_commands(log: &str) -> Vec<String> {
1712    let cleaned = strip_ansi(log);
1713    let mut result = Vec::new();
1714    for line in cleaned.lines() {
1715        let trimmed = line.trim();
1716        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1717            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1718                let cmd = cmd.trim();
1719                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1720                    result.push(cmd.to_string());
1721                    if result.len() == 20 {
1722                        break;
1723                    }
1724                }
1725            }
1726        }
1727    }
1728    result
1729}
1730
1731const TERMINAL_READS: &[&str] = &[
1732    "herdr pane read",
1733    "tmux capture-pane",
1734    "screen -X hardcopy",
1735    "zellij action dump-screen",
1736    "wezterm cli get-text",
1737];
1738
1739const TOOL_CACHES: &[&str] = &[
1740    ".cargo",
1741    ".rustup",
1742    ".cache",
1743    ".npm",
1744    ".local",
1745    "Library/Caches",
1746    ".gradle",
1747    ".m2",
1748    "go",
1749];
1750
1751fn normalize_path(path: &Path) -> PathBuf {
1752    use std::path::Component;
1753    let mut out = PathBuf::new();
1754    for comp in path.components() {
1755        match comp {
1756            Component::ParentDir => {
1757                out.pop();
1758            }
1759            Component::CurDir => {}
1760            _ => out.push(comp),
1761        }
1762    }
1763    out
1764}
1765
1766fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1767    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1768        return true;
1769    }
1770
1771    for raw_word in cmd.split_whitespace() {
1772        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1773        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1774            Some(home.join(suffix))
1775        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1776            Some(home.join(suffix))
1777        } else if word.starts_with('/') {
1778            Some(PathBuf::from(word))
1779        } else {
1780            None
1781        };
1782
1783        if let Some(path) = raw_path {
1784            let norm_path = normalize_path(&path);
1785            if !norm_path.starts_with(home) {
1786                continue;
1787            }
1788            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
1789            if under_allowed {
1790                continue;
1791            }
1792            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
1793            if under_cache {
1794                continue;
1795            }
1796            return true;
1797        }
1798    }
1799
1800    false
1801}
1802
1803pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
1804    let host_cmds = host_commands(log);
1805    let norm_home = normalize_path(home);
1806    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
1807    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
1808        .iter()
1809        .map(|c| normalize_path(&norm_home.join(c)))
1810        .collect();
1811
1812    let cleaned = strip_ansi(log);
1813    let mut result = Vec::new();
1814    for line in cleaned.lines() {
1815        let trimmed = line.trim();
1816        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1817            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1818                let cmd = cmd.trim();
1819                if host_cmds.iter().any(|c| c == cmd) {
1820                    continue;
1821                }
1822                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
1823                    && !result.iter().any(|c| c == cmd)
1824                {
1825                    result.push(cmd.to_string());
1826                    if result.len() == 20 {
1827                        break;
1828                    }
1829                }
1830            }
1831        }
1832    }
1833    result
1834}
1835
1836fn strip_ansi(s: &str) -> String {
1837    let mut out = String::with_capacity(s.len());
1838    let mut chars = s.chars().peekable();
1839    while let Some(c) = chars.next() {
1840        if c == '\x1b' && chars.peek() == Some(&'[') {
1841            chars.next();
1842            while let Some(&next_c) = chars.peek() {
1843                chars.next();
1844                if ('\x40'..='\x7e').contains(&next_c) {
1845                    break;
1846                }
1847                if next_c == '\n' || next_c == '\x1b' {
1848                    out.push(next_c);
1849                    break;
1850                }
1851            }
1852            continue;
1853        }
1854        out.push(c);
1855    }
1856    out
1857}
1858
1859#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1860pub struct LogProgress {
1861    pub turn: u32,
1862    pub last_tool: Option<String>,
1863    pub gate_attempts: u32,
1864    pub gate_passed: bool,
1865}
1866
1867pub fn parse_log(log: &str) -> LogProgress {
1868    let cleaned = strip_ansi(log);
1869    let mut turn: u32 = 0;
1870    let mut last_tool: Option<String> = None;
1871    let mut gate_attempts: u32 = 0;
1872    let mut gate_passed: bool = false;
1873
1874    for line in cleaned.lines() {
1875        if let Some(rest) = line.strip_prefix("[Turn ") {
1876            if let Some((n_str, _)) = rest.split_once(']') {
1877                if let Ok(n) = n_str.trim().parse::<u32>() {
1878                    turn = turn.max(n);
1879                }
1880            }
1881        }
1882
1883        if let Some(tool) = line.strip_prefix("● ") {
1884            let truncated = if tool.chars().count() > 200 {
1885                tool.chars().take(200).collect()
1886            } else {
1887                tool.to_string()
1888            };
1889            last_tool = Some(truncated);
1890        }
1891
1892        if line.starts_with("✓ Gate passed") {
1893            gate_attempts += 1;
1894            gate_passed = true;
1895        } else if line.starts_with("✗ Gate failed") {
1896            gate_attempts += 1;
1897            gate_passed = false;
1898        }
1899    }
1900
1901    LogProgress {
1902        turn,
1903        last_tool,
1904        gate_attempts,
1905        gate_passed,
1906    }
1907}
1908
1909#[derive(Debug, Serialize)]
1910pub struct StatusOutput {
1911    pub id: String,
1912    pub state: String,
1913    pub elapsed_s: u64,
1914    pub turn: u32,
1915    pub last_tool: Option<String>,
1916    pub gate_attempts: u32,
1917    pub gate_passed: bool,
1918    pub outcome: Option<String>,
1919    pub cost_usd: Option<f64>,
1920    pub final_message: Option<String>,
1921}
1922
1923pub fn run_status(id: &str, json: bool) -> i32 {
1924    let root = match crate::clean::find_repo_root() {
1925        Ok(r) => r,
1926        Err(e) => {
1927            eprintln!("error: {e}");
1928            return 2;
1929        }
1930    };
1931
1932    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1933    if !start_path.exists() {
1934        eprintln!("no dispatch {id} here");
1935        return 2;
1936    }
1937
1938    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
1939        Ok(s) => match serde_json::from_str(&s) {
1940            Ok(v) => v,
1941            Err(e) => {
1942                eprintln!("error parsing {}: {e}", start_path.display());
1943                return 2;
1944            }
1945        },
1946        Err(e) => {
1947            eprintln!("error reading {}: {e}", start_path.display());
1948            return 2;
1949        }
1950    };
1951
1952    let pid = start_record
1953        .get("pid")
1954        .and_then(|v| v.as_i64())
1955        .map(|v| v as libc::pid_t);
1956    let started_at = start_record
1957        .get("started_at")
1958        .and_then(|v| v.as_u64())
1959        .unwrap_or(0);
1960
1961    let is_alive = if let Some(pid) = pid {
1962        if pid > 0 {
1963            let ret = unsafe { libc::kill(pid, 0) };
1964            if ret == 0 {
1965                true
1966            } else {
1967                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1968            }
1969        } else {
1970            false
1971        }
1972    } else {
1973        false
1974    };
1975
1976    let report_path = root.join(".wt").join(format!("{id}.report.json"));
1977    let report_exists = report_path.exists();
1978
1979    let state = if report_exists {
1980        "finished"
1981    } else if is_alive {
1982        "running"
1983    } else {
1984        "dead"
1985    };
1986
1987    let now = std::time::SystemTime::now()
1988        .duration_since(std::time::UNIX_EPOCH)
1989        .map(|d| d.as_secs())
1990        .unwrap_or(0);
1991
1992    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
1993        if let Ok(content) = std::fs::read_to_string(&report_path) {
1994            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
1995                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
1996                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
1997                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
1998                    if s.chars().count() > 500 {
1999                        s.chars().take(500).collect()
2000                    } else {
2001                        s.to_string()
2002                    }
2003                });
2004                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
2005                (outcome, cost_usd, final_message, duration)
2006            } else {
2007                (None, None, None, None)
2008            }
2009        } else {
2010            (None, None, None, None)
2011        }
2012    } else {
2013        (None, None, None, None)
2014    };
2015
2016    let elapsed_s = if state == "finished" {
2017        report_duration
2018            .map(|d| d.round() as u64)
2019            .unwrap_or_else(|| now.saturating_sub(started_at))
2020    } else {
2021        now.saturating_sub(started_at)
2022    };
2023
2024    let log_path = root.join(".wt").join(format!("{id}.log"));
2025    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
2026    let progress = parse_log(&log_content);
2027
2028    if json {
2029        let status_obj = StatusOutput {
2030            id: id.to_string(),
2031            state: state.to_string(),
2032            elapsed_s,
2033            turn: progress.turn,
2034            last_tool: progress.last_tool,
2035            gate_attempts: progress.gate_attempts,
2036            gate_passed: progress.gate_passed,
2037            outcome,
2038            cost_usd,
2039            final_message,
2040        };
2041        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
2042        println!("{json_str}");
2043    } else {
2044        println!("id: {id}");
2045        println!("state: {state}");
2046        println!("elapsed_s: {elapsed_s}");
2047        println!("turn: {}", progress.turn);
2048        println!(
2049            "last_tool: {}",
2050            progress.last_tool.as_deref().unwrap_or("none")
2051        );
2052        println!("gate_attempts: {}", progress.gate_attempts);
2053        println!("gate_passed: {}", progress.gate_passed);
2054        if state == "finished" {
2055            if let Some(ref o) = outcome {
2056                println!("outcome: {o}");
2057            }
2058            if let Some(c) = cost_usd {
2059                println!("cost_usd: {c}");
2060            }
2061            if let Some(ref msg) = final_message {
2062                println!("final_message: {msg}");
2063            }
2064        }
2065    }
2066
2067    match state {
2068        "running" | "finished" => 0,
2069        _ => 1,
2070    }
2071}
2072
2073pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
2074    let readable_canon: Vec<PathBuf> = readable
2075        .iter()
2076        .filter_map(|r| std::fs::canonicalize(r).ok())
2077        .collect();
2078    let mut out = Vec::new();
2079    for raw in text.split(|c: char| {
2080        c.is_whitespace()
2081            || matches!(
2082                c,
2083                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
2084            )
2085    }) {
2086        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
2087        if !trimmed.starts_with('/')
2088            || trimmed.starts_with("//")
2089            || trimmed.len() <= 1
2090            || trimmed == "/dev/null"
2091        {
2092            continue;
2093        }
2094        let p = Path::new(trimmed);
2095        let Ok(canon) = std::fs::canonicalize(p) else {
2096            continue;
2097        };
2098        if readable_canon.iter().any(|r| canon.starts_with(r))
2099            || is_system_path(p)
2100            || is_system_path(&canon)
2101        {
2102            continue;
2103        }
2104        let pb = PathBuf::from(trimmed);
2105        if !out.contains(&pb) {
2106            out.push(pb);
2107        }
2108    }
2109    out
2110}
2111
2112/// A path no research task means as code to read: the filesystem root, a top-level directory,
2113/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
2114fn is_system_path(p: &Path) -> bool {
2115    const SYSTEM: &[&str] = &[
2116        "/usr",
2117        "/bin",
2118        "/sbin",
2119        "/etc",
2120        "/dev",
2121        "/opt",
2122        "/System",
2123        "/Library",
2124        "/Applications",
2125        "/nix",
2126        "/proc",
2127        "/sys",
2128    ];
2129    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
2130}
2131
2132pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
2133    let mut count = 0;
2134    let mut paths = Vec::new();
2135    for line in log_content.lines() {
2136        if !line.contains("path escapes the workspace") {
2137            continue;
2138        }
2139        count += 1;
2140        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
2141            let after = after.trim_start();
2142            let after = after.split("\x1b[").next().unwrap_or(after);
2143            let path = after
2144                .split(". This run can read")
2145                .next()
2146                .unwrap_or(after)
2147                .trim();
2148            if !path.is_empty() && !paths.iter().any(|p| p == path) {
2149                paths.push(path.to_string());
2150            }
2151        }
2152    }
2153    (count, paths)
2154}
2155
2156#[cfg(test)]
2157mod tests {
2158    use super::*;
2159
2160    #[test]
2161    fn outside_reads_excludes_commands_in_host_commands() {
2162        let home = Path::new("/Users/u");
2163        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2164        // rm -rf ~/repos/other is a host command (names outside and changes something)
2165        // cat ~/repos/other is not a host command (only reads)
2166        let log = "\
2167● bash rm -rf ~/repos/other/file.py -> exit 0
2168● bash cat ~/repos/other/file.py -> exit 0
2169";
2170        assert_eq!(
2171            host_commands(log),
2172            vec!["rm -rf ~/repos/other/file.py".to_string()]
2173        );
2174        assert_eq!(
2175            outside_reads(log, &allowed, home),
2176            vec!["cat ~/repos/other/file.py".to_string()]
2177        );
2178    }
2179
2180    #[test]
2181    fn outside_reads_all_terminal_patterns() {
2182        let home = Path::new("/Users/u");
2183        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2184        let log = "\
2185● bash herdr pane read p1 -> exit 0
2186● bash tmux capture-pane -t 1 -> exit 0
2187● bash screen -X hardcopy /tmp/screen.log -> exit 0
2188● bash zellij action dump-screen /tmp/dump -> exit 0
2189● bash wezterm cli get-text --pane-id 1 -> exit 0
2190";
2191        let reads = outside_reads(log, &allowed, home);
2192        assert_eq!(
2193            reads,
2194            vec![
2195                "herdr pane read p1",
2196                "tmux capture-pane -t 1",
2197                "screen -X hardcopy /tmp/screen.log",
2198                "zellij action dump-screen /tmp/dump",
2199                "wezterm cli get-text --pane-id 1",
2200            ]
2201        );
2202    }
2203
2204    #[test]
2205    fn outside_reads_all_tool_caches_ignored() {
2206        let home = Path::new("/Users/u");
2207        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2208        let log = "\
2209● bash ls ~/.cargo/bin -> exit 0
2210● bash ls ~/.rustup/toolchains -> exit 0
2211● bash ls ~/.cache/pip -> exit 0
2212● bash ls ~/.npm/_cacache -> exit 0
2213● bash ls ~/.local/share -> exit 0
2214● bash ls ~/Library/Caches/com.apple -> exit 0
2215● bash ls ~/.gradle/caches -> exit 0
2216● bash ls ~/.m2/repository -> exit 0
2217● bash ls ~/go/pkg -> exit 0
2218";
2219        assert!(outside_reads(log, &allowed, home).is_empty());
2220    }
2221
2222    #[test]
2223    fn outside_reads_trailing_punctuations_stripped() {
2224        let home = Path::new("/Users/u");
2225        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2226        let log = "\
2227● bash ls ~/secret: -> exit 0
2228● bash ls ~/secret, -> exit 0
2229● bash (ls ~/secret) -> exit 0
2230● bash bash -c 'ls ~/secret' -> exit 0
2231● bash bash -c \"ls ~/secret\" -> exit 0
2232";
2233        let reads = outside_reads(log, &allowed, home);
2234        // Deduplicated, so only one instance of the command or distinct commands:
2235        assert_eq!(reads.len(), 5);
2236    }
2237
2238    #[test]
2239    fn outside_reads_caps_at_20_and_deduplicates() {
2240        let home = Path::new("/Users/u");
2241        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2242        let mut log = String::new();
2243        for i in 0..30 {
2244            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
2245        }
2246        // Duplicate the first one
2247        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
2248        let reads = outside_reads(&log, &allowed, home);
2249        assert_eq!(reads.len(), 20);
2250        assert_eq!(reads[0], "cat ~/secret/0.txt");
2251        assert_eq!(reads[19], "cat ~/secret/19.txt");
2252    }
2253}