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