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