Skip to main content

blyte_cli/
dispatch.rs

1//! `blyte dispatch` and `blyte review` commands.
2
3use serde::{Deserialize, Serialize};
4use std::path::{Path, PathBuf};
5use std::process::Command;
6
7use crate::cli::{DispatchArgs, ReviewArgs};
8
9pub const DISPATCH_RULES: &str = r#"Rules:
10- Stay within the task. If it cannot pass without a small change elsewhere, make the smallest one and say so.
11- Never delete, clean or modify anything outside the worktree, and never change the machine to make a check pass. If a check fails because of the environment (disk, network, a missing service), stop and say so.
12- Do not push, open pull requests, or read secrets.
13- Commit locally before you stop, with the exact commit message the task gives (or a conventional one if it gives none).
14- 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.
15- 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.
16- Finish with a short report: what you changed, what you ran, and anything that deviated from the task."#;
17
18pub fn wrap_task(task: &str) -> String {
19    format!(
20        "You are implementing exactly one task. Your working directory is a git worktree on its own branch; work only there.\n\n{}\n\n{}",
21        task.trim(),
22        DISPATCH_RULES
23    )
24}
25
26pub const RESEARCH_RULES: &str = r#"Rules:
27- Do not create, modify, move or delete any file anywhere except `report.md` in your working directory.
28- 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.
29- Read the code with the read and grep tools, using absolute paths under the repository; use the shell only when they cannot do what you need.
30- Answer the question with evidence: file paths with line numbers, and quote only what is needed.
31- Write your findings to `report.md` in your working directory, then stop calling tools and reply with one line summarising them. The harness checks that `report.md` exists.
32- Start report.md early, after your first findings, and keep it updated as you go, so it always holds your best answer."#;
33
34pub fn wrap_research(question: &str, root: &Path) -> String {
35    format!(
36        "READ-ONLY RESEARCH TASK. The code to research is under {}: read it there by absolute path.\n\n{}\n\n{}",
37        root.display(),
38        question.trim(),
39        RESEARCH_RULES
40    )
41}
42
43pub fn quick_steps(gate: &str) -> Option<String> {
44    let lines: Vec<&str> = gate
45        .lines()
46        .map(str::trim)
47        .filter(|l| !l.is_empty())
48        .collect();
49    if lines.len() < 2 {
50        return None;
51    }
52    let steps = lines[..lines.len() - 1]
53        .iter()
54        .map(|s| format!("`{s}`"))
55        .collect::<Vec<_>>()
56        .join(", ");
57    Some(format!(
58        "The check's quick steps, to run yourself before you stop: {steps}. The last step, the full run, happens at the gate."
59    ))
60}
61
62pub fn dispatch_outcome(report_outcome: &str, commits: usize) -> &'static str {
63    match report_outcome {
64        "verified" => {
65            if commits == 0 {
66                "no_changes"
67            } else {
68                "verified"
69            }
70        }
71        "gate_failed" => "gate_failed",
72        "budget_exhausted" => "budget_exhausted",
73        "blocked" => "blocked",
74        "error" => "error",
75        _ => "error",
76    }
77}
78
79pub fn exit_code(outcome: &str) -> i32 {
80    match outcome {
81        "verified" => 0,
82        "no_changes" => 4,
83        "blocked" => 5,
84        _ => 1,
85    }
86}
87
88#[derive(Debug, Serialize)]
89pub struct CommitRecord {
90    pub sha: String,
91    pub subject: String,
92}
93
94#[derive(Debug, Serialize)]
95pub struct DispatchSummary {
96    pub id: String,
97    pub worktree: String,
98    pub branch: String,
99    pub outcome: &'static str,
100    pub exit: i32,
101    pub error: Option<String>,
102    pub commits: Vec<CommitRecord>,
103    pub changed_files: Vec<String>,
104    pub final_message: Option<String>,
105    pub turns: u32,
106    pub gate_attempts: u32,
107    pub gate_failures: Vec<String>,
108    pub cost_usd: Option<f64>,
109    pub seconds: u64,
110    pub sandbox: String,
111    pub log: String,
112    pub report: String,
113    pub gate_source: &'static str,
114    pub research_report: Option<String>,
115}
116
117fn finish_summary(summary: &DispatchSummary, wt_parent: &Path) -> i32 {
118    let _ = std::fs::create_dir_all(wt_parent);
119    let json_str = serde_json::to_string_pretty(summary).unwrap();
120    let summary_path = wt_parent.join(format!("{}.json", summary.id));
121    let _ = std::fs::write(&summary_path, format!("{json_str}\n"));
122    println!("{json_str}");
123    summary.exit
124}
125
126pub fn run_dispatch(args: &DispatchArgs) -> i32 {
127    if let Ok(home) = crate::skill::home_dir() {
128        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
129            eprintln!(
130                "blyte: added context rules to {} (they apply from the next Claude session)",
131                path.display()
132            );
133        }
134    }
135
136    // 1. Root repository discovery and worktree preparation
137    let out = Command::new("git")
138        .args(["rev-parse", "--show-toplevel"])
139        .output();
140    let Ok(out) = out else {
141        eprintln!("error: git not found");
142        return 2;
143    };
144    if !out.status.success() {
145        eprintln!("error: not a git repository");
146        return 2;
147    }
148    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
149    crate::registry::register(&root);
150
151    let (repo_config, from_main) = match crate::config::load_with_fallback(&root) {
152        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
153        Ok(None) => (None, false),
154        Err(e) => {
155            eprintln!("{e}");
156            return 2;
157        }
158    };
159    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
160
161    let (gate, gate_source) = if args.research {
162        ("test -s report.md".to_string(), "research")
163    } else if let Some(ref g) = args.gate {
164        (g.clone(), "flag")
165    } else if let Some(ref g) = dispatch_cfg.gate {
166        let toml_path = if from_main {
167            crate::config::main_checkout(&root)
168                .map(|m| m.join("blyte.toml"))
169                .unwrap_or_else(|| root.join("blyte.toml"))
170        } else {
171            root.join("blyte.toml")
172        };
173        let toml_content = std::fs::read_to_string(&toml_path).unwrap_or_default();
174        let missing = crate::gate_drift::missing_ci_steps(&root, g, &toml_content);
175        if let Some(warning) = crate::gate_drift::format_gate_drift_warning(&missing) {
176            eprintln!("{warning}");
177        }
178        let source = if from_main {
179            "blyte.toml (main checkout)"
180        } else {
181            "blyte.toml"
182        };
183        (g.clone(), source)
184    } else {
185        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
186        return 2;
187    };
188
189    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
190    let (max_seconds, max_turns) = if args.research {
191        (
192            args.max_seconds.unwrap_or(1800),
193            args.max_turns.unwrap_or(300),
194        )
195    } else {
196        (
197            args.max_seconds
198                .or(dispatch_cfg.max_seconds)
199                .unwrap_or(3600),
200            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
201        )
202    };
203    let max_cost = args.max_cost_usd.or(dispatch_cfg.max_cost);
204    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
205    let network = args
206        .network
207        .as_deref()
208        .or(dispatch_cfg.network.as_deref())
209        .unwrap_or("on");
210
211    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
212        let content = match std::fs::read_to_string(tf) {
213            Ok(s) => s,
214            Err(e) => {
215                eprintln!("error reading task file {}: {e}", tf.display());
216                return 2;
217            }
218        };
219        (content, Some(tf.display().to_string()))
220    } else {
221        match (&args.plan, &args.plan_task) {
222            (Some(plan_path), Some(plan_task)) => {
223                let plan_str = match std::fs::read_to_string(plan_path) {
224                    Ok(s) => s,
225                    Err(e) => {
226                        eprintln!("error reading plan {plan_path}: {e}");
227                        return 2;
228                    }
229                };
230                let section = match crate::plan_section::extract(&plan_str, plan_task) {
231                    Some(sec) => sec,
232                    None => {
233                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
234                        if let Some(hint) =
235                            crate::plan_section::explain_missing(&plan_str, plan_task)
236                        {
237                            eprintln!("  {hint}");
238                        }
239                        return 2;
240                    }
241                };
242                let content = format!("From the plan {plan_path}:\n\n{section}");
243                (content, None)
244            }
245            _ => {
246                eprintln!("error: give a task file, or --plan with --plan-task");
247                return 2;
248            }
249        }
250    };
251
252    let wt_parent = root.join(".wt");
253    let worktree_dir = wt_parent.join(&args.id);
254    let branch = format!("wip/{}", args.id);
255    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
256    let task_file_recorded =
257        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
258
259    if !args.research {
260        crate::clean::clean_quiet(&root, Some(&args.id));
261    }
262
263    if args.research {
264        if worktree_dir.exists() {
265            eprintln!("error: {} already exists", worktree_dir.display());
266            return 2;
267        }
268        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
269            eprintln!(
270                "error creating scratch directory {}: {e}",
271                worktree_dir.display()
272            );
273            return 2;
274        }
275        let init_out = Command::new("git")
276            .args(["init", "-q"])
277            .current_dir(&worktree_dir)
278            .output();
279        match init_out {
280            Ok(o) if o.status.success() => {}
281            Ok(o) => {
282                eprintln!(
283                    "error: git init failed: {}",
284                    String::from_utf8_lossy(&o.stderr)
285                );
286                return 2;
287            }
288            Err(e) => {
289                eprintln!("error: failed to execute git init: {e}");
290                return 2;
291            }
292        }
293        let commit_out = Command::new("git")
294            .args([
295                "-c",
296                "user.name=blyte",
297                "-c",
298                "user.email=blyte@local",
299                "commit",
300                "-q",
301                "--allow-empty",
302                "-m",
303                "research",
304            ])
305            .current_dir(&worktree_dir)
306            .output();
307        match commit_out {
308            Ok(o) if o.status.success() => {}
309            Ok(o) => {
310                eprintln!(
311                    "error: git commit failed: {}",
312                    String::from_utf8_lossy(&o.stderr)
313                );
314                return 2;
315            }
316            Err(e) => {
317                eprintln!("error: failed to execute git commit: {e}");
318                return 2;
319            }
320        }
321    } else if !worktree_dir.exists() {
322        let add_out = Command::new("git")
323            .args([
324                "worktree",
325                "add",
326                "-b",
327                &branch,
328                worktree_dir.to_str().unwrap(),
329                &args.base,
330            ])
331            .current_dir(&root)
332            .output();
333        match add_out {
334            Ok(o) if o.status.success() => {}
335            Ok(o) => {
336                eprintln!(
337                    "error: git worktree add failed: {}",
338                    String::from_utf8_lossy(&o.stderr)
339                );
340                return 2;
341            }
342            Err(e) => {
343                eprintln!("error: failed to execute git worktree add: {e}");
344                return 2;
345            }
346        }
347    }
348
349    // 2. Ensure .wt/ is in info/exclude
350    let common_dir_raw = Command::new("git")
351        .args(["rev-parse", "--git-common-dir"])
352        .current_dir(&root)
353        .output();
354    let common_dir = if let Ok(out) = common_dir_raw {
355        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
356        if p.is_absolute() {
357            p
358        } else {
359            root.join(p)
360        }
361    } else {
362        root.join(".git")
363    };
364
365    let exclude_path = common_dir.join("info").join("exclude");
366    if let Some(parent) = exclude_path.parent() {
367        let _ = std::fs::create_dir_all(parent);
368    }
369    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
370    if !content.lines().any(|l| l.trim() == ".wt/") {
371        let mut new_content = content;
372        if !new_content.is_empty() && !new_content.ends_with('\n') {
373            new_content.push('\n');
374        }
375        new_content.push_str(".wt/\n");
376        let _ = std::fs::write(&exclude_path, new_content);
377    }
378
379    // 3. Record base_sha
380    let base_out = Command::new("git")
381        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
382        .output();
383    let base_sha = match base_out {
384        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
385        _ => {
386            eprintln!("error: could not resolve HEAD in worktree");
387            return 2;
388        }
389    };
390
391    if !args.research {
392        if let Some(ref setup_cmd) = dispatch_cfg.setup {
393            let first_line = setup_cmd.lines().next().unwrap_or("");
394            eprintln!("setup: {first_line}");
395            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
396            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
397            if let Err(msg) = crate::setup::run_setup(
398                setup_cmd,
399                &worktree_dir,
400                &main_checkout,
401                &dispatch_cfg.env,
402                &setup_log_path,
403                crate::setup::SETUP_TIMEOUT,
404            ) {
405                let outcome = "blocked";
406                let exit = exit_code(outcome);
407                let first_line_err = msg.lines().next().unwrap_or("").to_string();
408                let summary = DispatchSummary {
409                    id: args.id.clone(),
410                    worktree: worktree_dir.display().to_string(),
411                    branch: branch.clone(),
412                    outcome,
413                    exit,
414                    error: Some(first_line_err),
415                    commits: Vec::new(),
416                    changed_files: Vec::new(),
417                    final_message: Some(msg),
418                    turns: 0,
419                    gate_attempts: 0,
420                    gate_failures: Vec::new(),
421                    cost_usd: None,
422                    seconds: 0,
423                    sandbox: args.sandbox.clone(),
424                    log: setup_log_path.display().to_string(),
425                    report: "".to_string(),
426                    gate_source,
427                    research_report: None,
428                };
429                return finish_summary(&summary, &wt_parent);
430            }
431        }
432    }
433
434    // 4. Write task file and spawn child process
435    let _ = std::fs::create_dir_all(&wt_parent);
436    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
437        eprintln!("error writing task file {}: {e}", task_md_path.display());
438        return 2;
439    }
440
441    let log_path = wt_parent.join(format!("{}.log", args.id));
442    let report_path = wt_parent.join(format!("{}.report.json", args.id));
443    if report_path.exists() {
444        let _ = std::fs::remove_file(&report_path);
445    }
446    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
447    if research_report_path.exists() {
448        let _ = std::fs::remove_file(&research_report_path);
449    }
450
451    let log_file = match std::fs::File::create(&log_path) {
452        Ok(f) => f,
453        Err(e) => {
454            eprintln!("error creating log file {}: {e}", log_path.display());
455            return 2;
456        }
457    };
458    let log_file_err = match log_file.try_clone() {
459        Ok(f) => f,
460        Err(e) => {
461            eprintln!("error cloning log file handle: {e}");
462            return 2;
463        }
464    };
465
466    let current_exe = match std::env::current_exe() {
467        Ok(p) => p,
468        Err(e) => {
469            eprintln!("error getting current executable: {e}");
470            return 2;
471        }
472    };
473
474    let mut cmd = Command::new(current_exe);
475    cmd.current_dir(&worktree_dir);
476    cmd.stdout(log_file);
477    cmd.stderr(log_file_err);
478
479    for (k, v) in &dispatch_cfg.env {
480        cmd.env(k, v);
481    }
482    cmd.env("BLYTE_DISPATCH_ID", &args.id);
483
484    cmd.arg("--gate").arg(&gate);
485    cmd.arg("--rollback=false");
486    cmd.arg("--max-seconds").arg(max_seconds.to_string());
487    cmd.arg("--max-turns").arg(max_turns.to_string());
488    cmd.arg("--report").arg(&report_path);
489
490    if let Some(m) = model {
491        cmd.arg("--model").arg(m);
492    }
493    if let Some(c) = max_cost {
494        cmd.arg("--max-cost").arg(c.to_string());
495    }
496    if let Some(fb) = fold_budget {
497        cmd.arg("--fold-budget").arg(fb.to_string());
498    }
499    cmd.arg("--sandbox").arg(&args.sandbox);
500    cmd.arg("--network").arg(network);
501    let home = std::env::var_os("HOME").map(PathBuf::from);
502    let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
503    let config_allow_read = match crate::config::expand_allow_read(
504        &dispatch_cfg.allow_read,
505        home.as_deref(),
506        &main_checkout,
507    ) {
508        Ok(paths) => paths,
509        Err(e) => {
510            eprintln!("{e}");
511            return 2;
512        }
513    };
514    for r in &config_allow_read {
515        cmd.arg("--allow-read").arg(r);
516    }
517    for r in &args.allow_read {
518        cmd.arg("--allow-read").arg(r);
519    }
520    for p in &args.pass_env {
521        cmd.arg("--pass-env").arg(p);
522    }
523    if args.research {
524        cmd.arg("--read-root").arg(&root);
525        cmd.arg("--no-gate-slot");
526        cmd.arg("--research");
527    }
528
529    cmd.arg("--");
530    let task_prompt = if args.research {
531        wrap_research(&task_content, &root)
532    } else {
533        let mut prompt = wrap_task(&task_content);
534        if let Some(qs) = quick_steps(&gate) {
535            prompt.push_str("\n\n");
536            prompt.push_str(&qs);
537        }
538        prompt
539    };
540    cmd.arg(task_prompt);
541
542    let mut child = match cmd.spawn() {
543        Ok(c) => c,
544        Err(e) => {
545            eprintln!("error spawning child process: {e}");
546            return 2;
547        }
548    };
549
550    let started_at = std::time::SystemTime::now()
551        .duration_since(std::time::UNIX_EPOCH)
552        .map(|d| d.as_secs())
553        .unwrap_or(0);
554
555    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
556    let mut tags = args.tags.clone();
557    if args.research {
558        tags.push("research".to_string());
559    }
560    let mut start_json = serde_json::json!({
561        "id": args.id,
562        "pid": child.id(),
563        "started_at": started_at,
564        "task_file": task_file_recorded,
565        "gate": gate,
566        "tags": tags,
567        "env": env_names,
568        "max_turns": max_turns,
569        "max_seconds": max_seconds,
570        "plan": args.plan,
571        "plan_task": args.plan_task,
572        "base": args.base,
573    });
574    if let Some(session) = crate::usage_log::session_from(
575        std::env::var("BLYTE_SESSION").ok(),
576        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
577    ) {
578        start_json["session"] = serde_json::json!(session);
579    }
580    if args.research {
581        start_json["research"] = serde_json::json!(true);
582    }
583    let start_path = wt_parent.join(format!("{}.start.json", args.id));
584    if let Ok(json_str) = serde_json::to_string_pretty(&start_json) {
585        let _ = std::fs::write(&start_path, json_str + "\n");
586    }
587
588    let _ = child.wait();
589
590    let scratch_report = worktree_dir.join("report.md");
591    if args.research {
592        let is_non_empty = std::fs::metadata(&scratch_report)
593            .map(|m| m.len() > 0)
594            .unwrap_or(false);
595        if is_non_empty {
596            let _ = std::fs::copy(&scratch_report, &research_report_path);
597            if let Some(ref report_to) = args.report_to {
598                if let Some(parent) = report_to.parent() {
599                    if !parent.as_os_str().is_empty() {
600                        let _ = std::fs::create_dir_all(parent);
601                    }
602                }
603                let _ = std::fs::copy(&scratch_report, report_to);
604            }
605        }
606    }
607
608    // 5. Read report, commits and changed files
609    let log_out = Command::new("git")
610        .args([
611            "-C",
612            worktree_dir.to_str().unwrap(),
613            "log",
614            "--reverse",
615            "--format=%h%x09%s",
616            &format!("{base_sha}..HEAD"),
617        ])
618        .output();
619
620    let mut commits = Vec::new();
621    if let Ok(o) = log_out {
622        let text = String::from_utf8_lossy(&o.stdout);
623        for line in text.lines() {
624            let line = line.trim();
625            if line.is_empty() {
626                continue;
627            }
628            if let Some((sha, subject)) = line.split_once('\t') {
629                commits.push(CommitRecord {
630                    sha: sha.to_string(),
631                    subject: subject.to_string(),
632                });
633            }
634        }
635    }
636
637    let diff_out = Command::new("git")
638        .args([
639            "-C",
640            worktree_dir.to_str().unwrap(),
641            "diff",
642            "--name-only",
643            &format!("{base_sha}..HEAD"),
644        ])
645        .output();
646
647    let mut changed_files = Vec::new();
648    if let Ok(o) = diff_out {
649        let text = String::from_utf8_lossy(&o.stdout);
650        for line in text.lines() {
651            let line = line.trim();
652            if !line.is_empty() {
653                changed_files.push(line.to_string());
654            }
655        }
656    }
657
658    let report_read = std::fs::read_to_string(&report_path);
659    let record: Result<serde_json::Value, String> = match report_read {
660        Ok(s) => serde_json::from_str(&s).map_err(|e| format!("unreadable report JSON: {e}")),
661        Err(e) => Err(format!("missing report: {e}")),
662    };
663
664    let (
665        report_outcome,
666        error,
667        final_message,
668        turns,
669        gate_attempts,
670        gate_failures,
671        cost_usd,
672        seconds,
673        sandbox,
674    ) = match record {
675        Ok(rec) => {
676            let gate_failures = rec
677                .get("gate_failures")
678                .and_then(|v| v.as_array())
679                .map(|arr| {
680                    arr.iter()
681                        .filter_map(|v| v.as_str())
682                        .map(|s| {
683                            if s.chars().count() > 1000 {
684                                s.chars().take(1000).collect()
685                            } else {
686                                s.to_string()
687                            }
688                        })
689                        .collect()
690                })
691                .unwrap_or_default();
692
693            (
694                rec.get("outcome")
695                    .and_then(|v| v.as_str())
696                    .unwrap_or("error")
697                    .to_string(),
698                rec.get("error").and_then(|v| v.as_str()).map(String::from),
699                rec.get("final_message")
700                    .and_then(|v| v.as_str())
701                    .map(String::from),
702                rec.get("turns").and_then(|v| v.as_u64()).unwrap_or(0) as u32,
703                rec.get("gate_attempts")
704                    .and_then(|v| v.as_u64())
705                    .unwrap_or(0) as u32,
706                gate_failures,
707                rec.get("cost_usd").and_then(|v| v.as_f64()),
708                rec.get("duration_seconds")
709                    .and_then(|v| v.as_f64())
710                    .unwrap_or(0.0)
711                    .round() as u64,
712                rec.get("sandbox")
713                    .and_then(|v| v.as_str())
714                    .unwrap_or(&args.sandbox)
715                    .to_string(),
716            )
717        }
718        Err(err_msg) => (
719            "error".to_string(),
720            Some(err_msg),
721            None,
722            0,
723            0,
724            Vec::new(),
725            None,
726            0,
727            args.sandbox.clone(),
728        ),
729    };
730
731    let outcome = if args.research {
732        match report_outcome.as_str() {
733            "verified" => "verified",
734            "gate_failed" => "gate_failed",
735            "budget_exhausted" => "budget_exhausted",
736            "blocked" => "blocked",
737            _ => "error",
738        }
739    } else {
740        dispatch_outcome(&report_outcome, commits.len())
741    };
742    let exit = exit_code(outcome);
743
744    let research_report = if args.research && research_report_path.exists() {
745        Some(research_report_path.display().to_string())
746    } else {
747        None
748    };
749
750    // 6. Print JSON summary
751    let summary = DispatchSummary {
752        id: args.id.clone(),
753        worktree: worktree_dir.display().to_string(),
754        branch,
755        outcome,
756        exit,
757        error,
758        commits,
759        changed_files,
760        final_message,
761        turns,
762        gate_attempts,
763        gate_failures,
764        cost_usd,
765        seconds,
766        sandbox,
767        log: log_path.display().to_string(),
768        report: report_path.display().to_string(),
769        gate_source,
770        research_report,
771    };
772
773    finish_summary(&summary, &wt_parent)
774}
775
776pub fn run_review(args: &ReviewArgs) -> i32 {
777    let out = Command::new("git")
778        .args(["rev-parse", "--show-toplevel"])
779        .output();
780    let Ok(out) = out else {
781        eprintln!("error: git not found");
782        return 2;
783    };
784    if !out.status.success() {
785        eprintln!("error: not a git repository");
786        return 2;
787    }
788    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
789
790    if args.notes.is_some() && args.verdict.is_none() {
791        eprintln!("error: --notes requires --verdict");
792        return 2;
793    }
794
795    if let Some(ref v) = args.verdict {
796        let wt_dir = root.join(".wt");
797        if let Err(e) = std::fs::create_dir_all(&wt_dir) {
798            eprintln!("error creating directory {}: {e}", wt_dir.display());
799            return 2;
800        }
801        let verdict_path = wt_dir.join(format!("{}.verdict.json", args.id));
802        let ts = std::time::SystemTime::now()
803            .duration_since(std::time::UNIX_EPOCH)
804            .map(|d| d.as_secs())
805            .unwrap_or(0);
806        let verdict_obj = serde_json::json!({
807            "verdict": v.as_str(),
808            "notes": args.notes.as_deref().unwrap_or(""),
809            "ts": ts,
810        });
811        let json_str = match serde_json::to_string_pretty(&verdict_obj) {
812            Ok(s) => s,
813            Err(e) => {
814                eprintln!("error serializing verdict: {e}");
815                return 2;
816            }
817        };
818        if let Err(e) = std::fs::write(&verdict_path, json_str + "\n") {
819            eprintln!("error writing {}: {e}", verdict_path.display());
820            return 2;
821        }
822        println!("recorded verdict {} for {}", v.as_str(), args.id);
823        crate::clean::clean_on_review(&root, &args.id);
824        return 0;
825    }
826
827    let wt = root.join(".wt").join(&args.id);
828    if !wt.exists() {
829        eprintln!("error: worktree {} does not exist", wt.display());
830        return 2;
831    }
832
833    let root_head = Command::new("git")
834        .args(["rev-parse", "HEAD"])
835        .current_dir(&root)
836        .output();
837    let root_head_sha = match root_head {
838        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
839        _ => {
840            eprintln!("error: could not resolve root HEAD");
841            return 2;
842        }
843    };
844
845    let mb_out = Command::new("git")
846        .args(["merge-base", "HEAD", &root_head_sha])
847        .current_dir(&wt)
848        .output();
849    let base = match mb_out {
850        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
851        _ => {
852            let has_root_head = Command::new("git")
853                .args(["cat-file", "-e", &format!("{root_head_sha}^{{commit}}")])
854                .current_dir(&wt)
855                .output()
856                .map(|o| o.status.success())
857                .unwrap_or(false);
858            if has_root_head {
859                root_head_sha
860            } else {
861                Command::new("git")
862                    .args(["rev-list", "--max-parents=0", "HEAD"])
863                    .current_dir(&wt)
864                    .output()
865                    .ok()
866                    .filter(|o| o.status.success())
867                    .map(|o| {
868                        String::from_utf8_lossy(&o.stdout)
869                            .lines()
870                            .next()
871                            .unwrap_or("")
872                            .trim()
873                            .to_string()
874                    })
875                    .filter(|s| !s.is_empty())
876                    .unwrap_or(root_head_sha)
877            }
878        }
879    };
880
881    let commits_out = Command::new("git")
882        .args(["log", "--oneline", &format!("{base}..HEAD")])
883        .current_dir(&wt)
884        .output()
885        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
886        .unwrap_or_default();
887
888    let files_out = Command::new("git")
889        .args(["diff", "--stat", &format!("{base}..HEAD")])
890        .current_dir(&wt)
891        .output()
892        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
893        .unwrap_or_default();
894
895    let tree_out = Command::new("git")
896        .args(["status", "--short"])
897        .current_dir(&wt)
898        .output()
899        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
900        .unwrap_or_default();
901
902    let diff_out = if args.diff {
903        Command::new("git")
904            .args(["diff", &format!("{base}..HEAD")])
905            .current_dir(&wt)
906            .output()
907            .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
908            .unwrap_or_default()
909    } else {
910        String::new()
911    };
912
913    let task_text: Option<String> = (|| {
914        let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
915        let content = std::fs::read_to_string(&start_file).ok()?;
916        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
917        let task_file = val.get("task_file")?.as_str()?;
918        let p = Path::new(task_file);
919        if let Ok(s) = std::fs::read_to_string(p) {
920            return Some(s);
921        }
922        std::fs::read_to_string(root.join(p)).ok()
923    })();
924
925    let changed_files: Vec<String> = Command::new("git")
926        .args(["diff", "--name-only", &format!("{base}..HEAD")])
927        .current_dir(&wt)
928        .output()
929        .ok()
930        .filter(|o| o.status.success())
931        .map(|o| {
932            String::from_utf8_lossy(&o.stdout)
933                .lines()
934                .map(|l| l.trim().to_string())
935                .filter(|l| !l.is_empty())
936                .collect()
937        })
938        .unwrap_or_default();
939
940    let subjects: Vec<String> = Command::new("git")
941        .args(["log", "--format=%s", &format!("{base}..HEAD")])
942        .current_dir(&wt)
943        .output()
944        .ok()
945        .filter(|o| o.status.success())
946        .map(|o| {
947            String::from_utf8_lossy(&o.stdout)
948                .lines()
949                .map(|l| l.trim().to_string())
950                .filter(|l| !l.is_empty())
951                .collect()
952        })
953        .unwrap_or_default();
954
955    let log_file = root.join(".wt").join(format!("{}.log", args.id));
956    let (hcmds, reads) = if let Ok(log_content) = std::fs::read_to_string(&log_file) {
957        let hcmds = host_commands(&log_content);
958        let home = std::env::var_os("HOME")
959            .map(PathBuf::from)
960            .unwrap_or_else(|| PathBuf::from("/"));
961        let allowed = [root.clone(), wt.clone()];
962        let reads = outside_reads(&log_content, &allowed, &home);
963        (hcmds, reads)
964    } else {
965        (Vec::new(), Vec::new())
966    };
967
968    let report_file = root.join(".wt").join(format!("{}.report.json", args.id));
969    let report_val = std::fs::read_to_string(&report_file)
970        .ok()
971        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
972    let outcome = report_val
973        .as_ref()
974        .and_then(|v| v.get("outcome"))
975        .and_then(|x| x.as_str());
976
977    let checks = crate::review_checks::build(
978        task_text.as_deref(),
979        &changed_files,
980        &subjects,
981        hcmds.len(),
982        reads.len(),
983        outcome,
984    );
985
986    println!("== checks");
987    if checks.flags.is_empty() {
988        println!("nothing flagged");
989    } else {
990        for flag in &checks.flags {
991            println!("! {flag}");
992        }
993    }
994
995    println!("== commits");
996    if !commits_out.is_empty() {
997        println!("{commits_out}");
998    }
999    println!("== files");
1000    if !files_out.is_empty() {
1001        println!("{files_out}");
1002    }
1003    println!("== tree");
1004    if tree_out.is_empty() {
1005        println!("(clean)");
1006    } else {
1007        println!("{tree_out}");
1008    }
1009    println!("== report");
1010    if let Some(ref v) = report_val {
1011        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1012            println!("outcome: {outcome}");
1013        }
1014        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1015            println!("turns: {turns}");
1016        }
1017        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1018            println!("cost_usd: {cost}");
1019        }
1020        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1021            println!("final_message: {msg}");
1022        }
1023    }
1024
1025    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1026    if research_report_file.exists() {
1027        println!("== research report");
1028        println!("{}", research_report_file.display());
1029        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1030            for line in content.lines().take(40) {
1031                println!("{line}");
1032            }
1033        }
1034    }
1035
1036    if !hcmds.is_empty() {
1037        println!("== host commands (may have changed things outside the worktree)");
1038        for cmd in hcmds {
1039            println!("{cmd}");
1040        }
1041    }
1042    if !reads.is_empty() {
1043        println!("== reads outside the repository");
1044        for cmd in reads {
1045            println!("{cmd}");
1046        }
1047    }
1048
1049    if args.diff {
1050        println!("== diff");
1051        if !diff_out.is_empty() {
1052            println!("{diff_out}");
1053        }
1054    }
1055
1056    if args.model_review {
1057        crate::model_review::run(&root, &args.id, &base, &wt);
1058    }
1059
1060    0
1061}
1062
1063const OUTSIDE_PATHS: &[&str] = &[
1064    "~/",
1065    "$HOME",
1066    "/Users/",
1067    "/home/",
1068    "/private/",
1069    "/var/",
1070    "/etc/",
1071    "/opt/",
1072    "/usr/",
1073];
1074
1075const CHANGE_WORDS: &[&str] = &[
1076    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1077];
1078
1079fn contains_word(cmd: &str, word: &str) -> bool {
1080    let mut start = 0;
1081    while let Some(pos) = cmd[start..].find(word) {
1082        let abs_pos = start + pos;
1083        let before_ok = if abs_pos == 0 {
1084            true
1085        } else {
1086            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1087            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1088        };
1089        let after_pos = abs_pos + word.len();
1090        let after_ok = if after_pos >= cmd.len() {
1091            true
1092        } else {
1093            let next = cmd[after_pos..].chars().next().unwrap();
1094            !next.is_alphanumeric() && next != '_' && next != '-'
1095        };
1096        if before_ok && after_ok {
1097            return true;
1098        }
1099        start = abs_pos + word.len();
1100    }
1101    false
1102}
1103
1104fn has_non_dev_null_redirect(cmd: &str) -> bool {
1105    let chars: Vec<char> = cmd.chars().collect();
1106    let mut i = 0;
1107    while i < chars.len() {
1108        if chars[i] == '>' {
1109            while i < chars.len() && chars[i] == '>' {
1110                i += 1;
1111            }
1112            if i < chars.len() && chars[i] == '|' {
1113                i += 1;
1114            }
1115            while i < chars.len() && chars[i].is_whitespace() {
1116                i += 1;
1117            }
1118            if i >= chars.len() {
1119                break;
1120            }
1121            if chars[i] == '&'
1122                && i + 1 < chars.len()
1123                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1124            {
1125                i += 1;
1126                continue;
1127            }
1128            let target_start = i;
1129            while i < chars.len()
1130                && !chars[i].is_whitespace()
1131                && chars[i] != ';'
1132                && chars[i] != '|'
1133                && chars[i] != '&'
1134                && chars[i] != ')'
1135            {
1136                i += 1;
1137            }
1138            let target: String = chars[target_start..i].iter().collect();
1139            let target = target.trim_matches(|c| c == '\'' || c == '"');
1140            if !target.is_empty() && target != "/dev/null" {
1141                return true;
1142            }
1143        } else {
1144            i += 1;
1145        }
1146    }
1147    false
1148}
1149
1150fn changes_something(cmd: &str) -> bool {
1151    for &word in CHANGE_WORDS {
1152        if contains_word(cmd, word) {
1153            return true;
1154        }
1155    }
1156    has_non_dev_null_redirect(cmd)
1157}
1158
1159fn is_host_command(cmd: &str) -> bool {
1160    if cmd.contains("git push")
1161        || cmd.contains("sudo ")
1162        || cmd.contains("cache clean")
1163        || cmd.contains("cache prune")
1164        || cmd.contains("brew ")
1165    {
1166        return true;
1167    }
1168
1169    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1170    if names_outside && changes_something(cmd) {
1171        return true;
1172    }
1173
1174    false
1175}
1176
1177pub fn host_commands(log: &str) -> Vec<String> {
1178    let cleaned = strip_ansi(log);
1179    let mut result = Vec::new();
1180    for line in cleaned.lines() {
1181        let trimmed = line.trim();
1182        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1183            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1184                let cmd = cmd.trim();
1185                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1186                    result.push(cmd.to_string());
1187                    if result.len() == 20 {
1188                        break;
1189                    }
1190                }
1191            }
1192        }
1193    }
1194    result
1195}
1196
1197const TERMINAL_READS: &[&str] = &[
1198    "herdr pane read",
1199    "tmux capture-pane",
1200    "screen -X hardcopy",
1201    "zellij action dump-screen",
1202    "wezterm cli get-text",
1203];
1204
1205const TOOL_CACHES: &[&str] = &[
1206    ".cargo",
1207    ".rustup",
1208    ".cache",
1209    ".npm",
1210    ".local",
1211    "Library/Caches",
1212    ".gradle",
1213    ".m2",
1214    "go",
1215];
1216
1217fn normalize_path(path: &Path) -> PathBuf {
1218    use std::path::Component;
1219    let mut out = PathBuf::new();
1220    for comp in path.components() {
1221        match comp {
1222            Component::ParentDir => {
1223                out.pop();
1224            }
1225            Component::CurDir => {}
1226            _ => out.push(comp),
1227        }
1228    }
1229    out
1230}
1231
1232fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1233    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1234        return true;
1235    }
1236
1237    for raw_word in cmd.split_whitespace() {
1238        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1239        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1240            Some(home.join(suffix))
1241        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1242            Some(home.join(suffix))
1243        } else if word.starts_with('/') {
1244            Some(PathBuf::from(word))
1245        } else {
1246            None
1247        };
1248
1249        if let Some(path) = raw_path {
1250            let norm_path = normalize_path(&path);
1251            if !norm_path.starts_with(home) {
1252                continue;
1253            }
1254            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
1255            if under_allowed {
1256                continue;
1257            }
1258            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
1259            if under_cache {
1260                continue;
1261            }
1262            return true;
1263        }
1264    }
1265
1266    false
1267}
1268
1269pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
1270    let host_cmds = host_commands(log);
1271    let norm_home = normalize_path(home);
1272    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
1273    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
1274        .iter()
1275        .map(|c| normalize_path(&norm_home.join(c)))
1276        .collect();
1277
1278    let cleaned = strip_ansi(log);
1279    let mut result = Vec::new();
1280    for line in cleaned.lines() {
1281        let trimmed = line.trim();
1282        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1283            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1284                let cmd = cmd.trim();
1285                if host_cmds.iter().any(|c| c == cmd) {
1286                    continue;
1287                }
1288                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
1289                    && !result.iter().any(|c| c == cmd)
1290                {
1291                    result.push(cmd.to_string());
1292                    if result.len() == 20 {
1293                        break;
1294                    }
1295                }
1296            }
1297        }
1298    }
1299    result
1300}
1301
1302fn strip_ansi(s: &str) -> String {
1303    let mut out = String::with_capacity(s.len());
1304    let mut chars = s.chars().peekable();
1305    while let Some(c) = chars.next() {
1306        if c == '\x1b' && chars.peek() == Some(&'[') {
1307            chars.next();
1308            while let Some(&next_c) = chars.peek() {
1309                chars.next();
1310                if ('\x40'..='\x7e').contains(&next_c) {
1311                    break;
1312                }
1313                if next_c == '\n' || next_c == '\x1b' {
1314                    out.push(next_c);
1315                    break;
1316                }
1317            }
1318            continue;
1319        }
1320        out.push(c);
1321    }
1322    out
1323}
1324
1325#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1326pub struct LogProgress {
1327    pub turn: u32,
1328    pub last_tool: Option<String>,
1329    pub gate_attempts: u32,
1330    pub gate_passed: bool,
1331}
1332
1333pub fn parse_log(log: &str) -> LogProgress {
1334    let cleaned = strip_ansi(log);
1335    let mut turn: u32 = 0;
1336    let mut last_tool: Option<String> = None;
1337    let mut gate_attempts: u32 = 0;
1338    let mut gate_passed: bool = false;
1339
1340    for line in cleaned.lines() {
1341        if let Some(rest) = line.strip_prefix("[Turn ") {
1342            if let Some((n_str, _)) = rest.split_once(']') {
1343                if let Ok(n) = n_str.trim().parse::<u32>() {
1344                    turn = turn.max(n);
1345                }
1346            }
1347        }
1348
1349        if let Some(tool) = line.strip_prefix("● ") {
1350            let truncated = if tool.chars().count() > 200 {
1351                tool.chars().take(200).collect()
1352            } else {
1353                tool.to_string()
1354            };
1355            last_tool = Some(truncated);
1356        }
1357
1358        if line.starts_with("✓ Gate passed") {
1359            gate_attempts += 1;
1360            gate_passed = true;
1361        } else if line.starts_with("✗ Gate failed") {
1362            gate_attempts += 1;
1363            gate_passed = false;
1364        }
1365    }
1366
1367    LogProgress {
1368        turn,
1369        last_tool,
1370        gate_attempts,
1371        gate_passed,
1372    }
1373}
1374
1375#[derive(Debug, Serialize)]
1376pub struct StatusOutput {
1377    pub id: String,
1378    pub state: String,
1379    pub elapsed_s: u64,
1380    pub turn: u32,
1381    pub last_tool: Option<String>,
1382    pub gate_attempts: u32,
1383    pub gate_passed: bool,
1384    pub outcome: Option<String>,
1385    pub cost_usd: Option<f64>,
1386    pub final_message: Option<String>,
1387}
1388
1389pub fn run_status(id: &str, json: bool) -> i32 {
1390    let out = Command::new("git")
1391        .args(["rev-parse", "--show-toplevel"])
1392        .output();
1393    let Ok(out) = out else {
1394        eprintln!("error: git not found");
1395        return 2;
1396    };
1397    if !out.status.success() {
1398        eprintln!("error: not a git repository");
1399        return 2;
1400    }
1401    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1402
1403    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1404    if !start_path.exists() {
1405        eprintln!("no dispatch {id} here");
1406        return 2;
1407    }
1408
1409    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
1410        Ok(s) => match serde_json::from_str(&s) {
1411            Ok(v) => v,
1412            Err(e) => {
1413                eprintln!("error parsing {}: {e}", start_path.display());
1414                return 2;
1415            }
1416        },
1417        Err(e) => {
1418            eprintln!("error reading {}: {e}", start_path.display());
1419            return 2;
1420        }
1421    };
1422
1423    let pid = start_record
1424        .get("pid")
1425        .and_then(|v| v.as_i64())
1426        .map(|v| v as libc::pid_t);
1427    let started_at = start_record
1428        .get("started_at")
1429        .and_then(|v| v.as_u64())
1430        .unwrap_or(0);
1431
1432    let is_alive = if let Some(pid) = pid {
1433        if pid > 0 {
1434            let ret = unsafe { libc::kill(pid, 0) };
1435            if ret == 0 {
1436                true
1437            } else {
1438                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1439            }
1440        } else {
1441            false
1442        }
1443    } else {
1444        false
1445    };
1446
1447    let report_path = root.join(".wt").join(format!("{id}.report.json"));
1448    let report_exists = report_path.exists();
1449
1450    let state = if report_exists {
1451        "finished"
1452    } else if is_alive {
1453        "running"
1454    } else {
1455        "dead"
1456    };
1457
1458    let now = std::time::SystemTime::now()
1459        .duration_since(std::time::UNIX_EPOCH)
1460        .map(|d| d.as_secs())
1461        .unwrap_or(0);
1462
1463    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
1464        if let Ok(content) = std::fs::read_to_string(&report_path) {
1465            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
1466                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
1467                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
1468                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
1469                    if s.chars().count() > 500 {
1470                        s.chars().take(500).collect()
1471                    } else {
1472                        s.to_string()
1473                    }
1474                });
1475                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
1476                (outcome, cost_usd, final_message, duration)
1477            } else {
1478                (None, None, None, None)
1479            }
1480        } else {
1481            (None, None, None, None)
1482        }
1483    } else {
1484        (None, None, None, None)
1485    };
1486
1487    let elapsed_s = if state == "finished" {
1488        report_duration
1489            .map(|d| d.round() as u64)
1490            .unwrap_or_else(|| now.saturating_sub(started_at))
1491    } else {
1492        now.saturating_sub(started_at)
1493    };
1494
1495    let log_path = root.join(".wt").join(format!("{id}.log"));
1496    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
1497    let progress = parse_log(&log_content);
1498
1499    if json {
1500        let status_obj = StatusOutput {
1501            id: id.to_string(),
1502            state: state.to_string(),
1503            elapsed_s,
1504            turn: progress.turn,
1505            last_tool: progress.last_tool,
1506            gate_attempts: progress.gate_attempts,
1507            gate_passed: progress.gate_passed,
1508            outcome,
1509            cost_usd,
1510            final_message,
1511        };
1512        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
1513        println!("{json_str}");
1514    } else {
1515        println!("id: {id}");
1516        println!("state: {state}");
1517        println!("elapsed_s: {elapsed_s}");
1518        println!("turn: {}", progress.turn);
1519        println!(
1520            "last_tool: {}",
1521            progress.last_tool.as_deref().unwrap_or("none")
1522        );
1523        println!("gate_attempts: {}", progress.gate_attempts);
1524        println!("gate_passed: {}", progress.gate_passed);
1525        if state == "finished" {
1526            if let Some(ref o) = outcome {
1527                println!("outcome: {o}");
1528            }
1529            if let Some(c) = cost_usd {
1530                println!("cost_usd: {c}");
1531            }
1532            if let Some(ref msg) = final_message {
1533                println!("final_message: {msg}");
1534            }
1535        }
1536    }
1537
1538    match state {
1539        "running" | "finished" => 0,
1540        _ => 1,
1541    }
1542}
1543
1544#[cfg(test)]
1545mod tests {
1546    use super::*;
1547
1548    #[test]
1549    fn outside_reads_excludes_commands_in_host_commands() {
1550        let home = Path::new("/Users/u");
1551        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1552        // rm -rf ~/repos/other is a host command (names outside and changes something)
1553        // cat ~/repos/other is not a host command (only reads)
1554        let log = "\
1555● bash rm -rf ~/repos/other/file.py -> exit 0
1556● bash cat ~/repos/other/file.py -> exit 0
1557";
1558        assert_eq!(
1559            host_commands(log),
1560            vec!["rm -rf ~/repos/other/file.py".to_string()]
1561        );
1562        assert_eq!(
1563            outside_reads(log, &allowed, home),
1564            vec!["cat ~/repos/other/file.py".to_string()]
1565        );
1566    }
1567
1568    #[test]
1569    fn outside_reads_all_terminal_patterns() {
1570        let home = Path::new("/Users/u");
1571        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1572        let log = "\
1573● bash herdr pane read p1 -> exit 0
1574● bash tmux capture-pane -t 1 -> exit 0
1575● bash screen -X hardcopy /tmp/screen.log -> exit 0
1576● bash zellij action dump-screen /tmp/dump -> exit 0
1577● bash wezterm cli get-text --pane-id 1 -> exit 0
1578";
1579        let reads = outside_reads(log, &allowed, home);
1580        assert_eq!(
1581            reads,
1582            vec![
1583                "herdr pane read p1",
1584                "tmux capture-pane -t 1",
1585                "screen -X hardcopy /tmp/screen.log",
1586                "zellij action dump-screen /tmp/dump",
1587                "wezterm cli get-text --pane-id 1",
1588            ]
1589        );
1590    }
1591
1592    #[test]
1593    fn outside_reads_all_tool_caches_ignored() {
1594        let home = Path::new("/Users/u");
1595        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1596        let log = "\
1597● bash ls ~/.cargo/bin -> exit 0
1598● bash ls ~/.rustup/toolchains -> exit 0
1599● bash ls ~/.cache/pip -> exit 0
1600● bash ls ~/.npm/_cacache -> exit 0
1601● bash ls ~/.local/share -> exit 0
1602● bash ls ~/Library/Caches/com.apple -> exit 0
1603● bash ls ~/.gradle/caches -> exit 0
1604● bash ls ~/.m2/repository -> exit 0
1605● bash ls ~/go/pkg -> exit 0
1606";
1607        assert!(outside_reads(log, &allowed, home).is_empty());
1608    }
1609
1610    #[test]
1611    fn outside_reads_trailing_punctuations_stripped() {
1612        let home = Path::new("/Users/u");
1613        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1614        let log = "\
1615● bash ls ~/secret: -> exit 0
1616● bash ls ~/secret, -> exit 0
1617● bash (ls ~/secret) -> exit 0
1618● bash bash -c 'ls ~/secret' -> exit 0
1619● bash bash -c \"ls ~/secret\" -> exit 0
1620";
1621        let reads = outside_reads(log, &allowed, home);
1622        // Deduplicated, so only one instance of the command or distinct commands:
1623        assert_eq!(reads.len(), 5);
1624    }
1625
1626    #[test]
1627    fn outside_reads_caps_at_20_and_deduplicates() {
1628        let home = Path::new("/Users/u");
1629        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1630        let mut log = String::new();
1631        for i in 0..30 {
1632            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
1633        }
1634        // Duplicate the first one
1635        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
1636        let reads = outside_reads(&log, &allowed, home);
1637        assert_eq!(reads.len(), 20);
1638        assert_eq!(reads[0], "cat ~/secret/0.txt");
1639        assert_eq!(reads[19], "cat ~/secret/19.txt");
1640    }
1641}