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