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