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