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    let quote_problems: Option<Vec<&str>> = report_val
992        .as_ref()
993        .and_then(|v| v.get("quote_problems"))
994        .and_then(|x| x.as_array())
995        .map(|arr| arr.iter().filter_map(|x| x.as_str()).collect());
996
997    let mut checks = crate::review_checks::build(
998        task_text.as_deref(),
999        &changed_files,
1000        &subjects,
1001        hcmds.len(),
1002        reads.len(),
1003        outcome,
1004    );
1005    if let Some(ref problems) = quote_problems {
1006        if !problems.is_empty() {
1007            checks.flags.push(format!(
1008                "quote check failed ({} problem(s)): see == report",
1009                problems.len()
1010            ));
1011        }
1012    }
1013
1014    println!("== checks");
1015    if checks.flags.is_empty() {
1016        println!("nothing flagged");
1017    } else {
1018        for flag in &checks.flags {
1019            println!("! {flag}");
1020        }
1021    }
1022
1023    println!("== commits");
1024    if !commits_out.is_empty() {
1025        println!("{commits_out}");
1026    }
1027    println!("== files");
1028    if !files_out.is_empty() {
1029        println!("{files_out}");
1030    }
1031    println!("== tree");
1032    if tree_out.is_empty() {
1033        println!("(clean)");
1034    } else {
1035        println!("{tree_out}");
1036    }
1037    println!("== report");
1038    if let Some(ref v) = report_val {
1039        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1040            println!("outcome: {outcome}");
1041        }
1042        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1043            println!("turns: {turns}");
1044        }
1045        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1046            println!("cost_usd: {cost}");
1047        }
1048        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1049            println!("final_message: {msg}");
1050        }
1051        if let Some(ref problems) = quote_problems {
1052            if problems.is_empty() {
1053                println!("quote check: passed");
1054            } else {
1055                println!(
1056                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
1057                    problems.len()
1058                );
1059                for p in problems.iter().take(5) {
1060                    let cut: String = p.chars().take(200).collect();
1061                    println!("  {cut}");
1062                }
1063            }
1064        }
1065    }
1066
1067    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1068    if research_report_file.exists() {
1069        println!("== research report");
1070        println!("{}", research_report_file.display());
1071        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1072            for line in content.lines().take(40) {
1073                println!("{line}");
1074            }
1075        }
1076    }
1077
1078    if !hcmds.is_empty() {
1079        println!("== host commands (may have changed things outside the worktree)");
1080        for cmd in hcmds {
1081            println!("{cmd}");
1082        }
1083    }
1084    if !reads.is_empty() {
1085        println!("== reads outside the repository");
1086        for cmd in reads {
1087            println!("{cmd}");
1088        }
1089    }
1090
1091    if args.diff {
1092        println!("== diff");
1093        if !diff_out.is_empty() {
1094            println!("{diff_out}");
1095        }
1096    }
1097
1098    if args.model_review {
1099        crate::model_review::run(&root, &args.id, &base, &wt);
1100    }
1101
1102    0
1103}
1104
1105const OUTSIDE_PATHS: &[&str] = &[
1106    "~/",
1107    "$HOME",
1108    "/Users/",
1109    "/home/",
1110    "/private/",
1111    "/var/",
1112    "/etc/",
1113    "/opt/",
1114    "/usr/",
1115];
1116
1117const CHANGE_WORDS: &[&str] = &[
1118    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1119];
1120
1121fn contains_word(cmd: &str, word: &str) -> bool {
1122    let mut start = 0;
1123    while let Some(pos) = cmd[start..].find(word) {
1124        let abs_pos = start + pos;
1125        let before_ok = if abs_pos == 0 {
1126            true
1127        } else {
1128            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1129            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1130        };
1131        let after_pos = abs_pos + word.len();
1132        let after_ok = if after_pos >= cmd.len() {
1133            true
1134        } else {
1135            let next = cmd[after_pos..].chars().next().unwrap();
1136            !next.is_alphanumeric() && next != '_' && next != '-'
1137        };
1138        if before_ok && after_ok {
1139            return true;
1140        }
1141        start = abs_pos + word.len();
1142    }
1143    false
1144}
1145
1146fn has_non_dev_null_redirect(cmd: &str) -> bool {
1147    let chars: Vec<char> = cmd.chars().collect();
1148    let mut i = 0;
1149    while i < chars.len() {
1150        if chars[i] == '>' {
1151            while i < chars.len() && chars[i] == '>' {
1152                i += 1;
1153            }
1154            if i < chars.len() && chars[i] == '|' {
1155                i += 1;
1156            }
1157            while i < chars.len() && chars[i].is_whitespace() {
1158                i += 1;
1159            }
1160            if i >= chars.len() {
1161                break;
1162            }
1163            if chars[i] == '&'
1164                && i + 1 < chars.len()
1165                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1166            {
1167                i += 1;
1168                continue;
1169            }
1170            let target_start = i;
1171            while i < chars.len()
1172                && !chars[i].is_whitespace()
1173                && chars[i] != ';'
1174                && chars[i] != '|'
1175                && chars[i] != '&'
1176                && chars[i] != ')'
1177            {
1178                i += 1;
1179            }
1180            let target: String = chars[target_start..i].iter().collect();
1181            let target = target.trim_matches(|c| c == '\'' || c == '"');
1182            if !target.is_empty() && target != "/dev/null" {
1183                return true;
1184            }
1185        } else {
1186            i += 1;
1187        }
1188    }
1189    false
1190}
1191
1192fn changes_something(cmd: &str) -> bool {
1193    for &word in CHANGE_WORDS {
1194        if contains_word(cmd, word) {
1195            return true;
1196        }
1197    }
1198    has_non_dev_null_redirect(cmd)
1199}
1200
1201fn is_host_command(cmd: &str) -> bool {
1202    if cmd.contains("git push")
1203        || cmd.contains("sudo ")
1204        || cmd.contains("cache clean")
1205        || cmd.contains("cache prune")
1206        || cmd.contains("brew ")
1207    {
1208        return true;
1209    }
1210
1211    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1212    if names_outside && changes_something(cmd) {
1213        return true;
1214    }
1215
1216    false
1217}
1218
1219pub fn host_commands(log: &str) -> Vec<String> {
1220    let cleaned = strip_ansi(log);
1221    let mut result = Vec::new();
1222    for line in cleaned.lines() {
1223        let trimmed = line.trim();
1224        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1225            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1226                let cmd = cmd.trim();
1227                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1228                    result.push(cmd.to_string());
1229                    if result.len() == 20 {
1230                        break;
1231                    }
1232                }
1233            }
1234        }
1235    }
1236    result
1237}
1238
1239const TERMINAL_READS: &[&str] = &[
1240    "herdr pane read",
1241    "tmux capture-pane",
1242    "screen -X hardcopy",
1243    "zellij action dump-screen",
1244    "wezterm cli get-text",
1245];
1246
1247const TOOL_CACHES: &[&str] = &[
1248    ".cargo",
1249    ".rustup",
1250    ".cache",
1251    ".npm",
1252    ".local",
1253    "Library/Caches",
1254    ".gradle",
1255    ".m2",
1256    "go",
1257];
1258
1259fn normalize_path(path: &Path) -> PathBuf {
1260    use std::path::Component;
1261    let mut out = PathBuf::new();
1262    for comp in path.components() {
1263        match comp {
1264            Component::ParentDir => {
1265                out.pop();
1266            }
1267            Component::CurDir => {}
1268            _ => out.push(comp),
1269        }
1270    }
1271    out
1272}
1273
1274fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1275    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1276        return true;
1277    }
1278
1279    for raw_word in cmd.split_whitespace() {
1280        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1281        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1282            Some(home.join(suffix))
1283        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1284            Some(home.join(suffix))
1285        } else if word.starts_with('/') {
1286            Some(PathBuf::from(word))
1287        } else {
1288            None
1289        };
1290
1291        if let Some(path) = raw_path {
1292            let norm_path = normalize_path(&path);
1293            if !norm_path.starts_with(home) {
1294                continue;
1295            }
1296            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
1297            if under_allowed {
1298                continue;
1299            }
1300            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
1301            if under_cache {
1302                continue;
1303            }
1304            return true;
1305        }
1306    }
1307
1308    false
1309}
1310
1311pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
1312    let host_cmds = host_commands(log);
1313    let norm_home = normalize_path(home);
1314    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
1315    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
1316        .iter()
1317        .map(|c| normalize_path(&norm_home.join(c)))
1318        .collect();
1319
1320    let cleaned = strip_ansi(log);
1321    let mut result = Vec::new();
1322    for line in cleaned.lines() {
1323        let trimmed = line.trim();
1324        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1325            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1326                let cmd = cmd.trim();
1327                if host_cmds.iter().any(|c| c == cmd) {
1328                    continue;
1329                }
1330                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
1331                    && !result.iter().any(|c| c == cmd)
1332                {
1333                    result.push(cmd.to_string());
1334                    if result.len() == 20 {
1335                        break;
1336                    }
1337                }
1338            }
1339        }
1340    }
1341    result
1342}
1343
1344fn strip_ansi(s: &str) -> String {
1345    let mut out = String::with_capacity(s.len());
1346    let mut chars = s.chars().peekable();
1347    while let Some(c) = chars.next() {
1348        if c == '\x1b' && chars.peek() == Some(&'[') {
1349            chars.next();
1350            while let Some(&next_c) = chars.peek() {
1351                chars.next();
1352                if ('\x40'..='\x7e').contains(&next_c) {
1353                    break;
1354                }
1355                if next_c == '\n' || next_c == '\x1b' {
1356                    out.push(next_c);
1357                    break;
1358                }
1359            }
1360            continue;
1361        }
1362        out.push(c);
1363    }
1364    out
1365}
1366
1367#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1368pub struct LogProgress {
1369    pub turn: u32,
1370    pub last_tool: Option<String>,
1371    pub gate_attempts: u32,
1372    pub gate_passed: bool,
1373}
1374
1375pub fn parse_log(log: &str) -> LogProgress {
1376    let cleaned = strip_ansi(log);
1377    let mut turn: u32 = 0;
1378    let mut last_tool: Option<String> = None;
1379    let mut gate_attempts: u32 = 0;
1380    let mut gate_passed: bool = false;
1381
1382    for line in cleaned.lines() {
1383        if let Some(rest) = line.strip_prefix("[Turn ") {
1384            if let Some((n_str, _)) = rest.split_once(']') {
1385                if let Ok(n) = n_str.trim().parse::<u32>() {
1386                    turn = turn.max(n);
1387                }
1388            }
1389        }
1390
1391        if let Some(tool) = line.strip_prefix("● ") {
1392            let truncated = if tool.chars().count() > 200 {
1393                tool.chars().take(200).collect()
1394            } else {
1395                tool.to_string()
1396            };
1397            last_tool = Some(truncated);
1398        }
1399
1400        if line.starts_with("✓ Gate passed") {
1401            gate_attempts += 1;
1402            gate_passed = true;
1403        } else if line.starts_with("✗ Gate failed") {
1404            gate_attempts += 1;
1405            gate_passed = false;
1406        }
1407    }
1408
1409    LogProgress {
1410        turn,
1411        last_tool,
1412        gate_attempts,
1413        gate_passed,
1414    }
1415}
1416
1417#[derive(Debug, Serialize)]
1418pub struct StatusOutput {
1419    pub id: String,
1420    pub state: String,
1421    pub elapsed_s: u64,
1422    pub turn: u32,
1423    pub last_tool: Option<String>,
1424    pub gate_attempts: u32,
1425    pub gate_passed: bool,
1426    pub outcome: Option<String>,
1427    pub cost_usd: Option<f64>,
1428    pub final_message: Option<String>,
1429}
1430
1431pub fn run_status(id: &str, json: bool) -> i32 {
1432    let out = Command::new("git")
1433        .args(["rev-parse", "--show-toplevel"])
1434        .output();
1435    let Ok(out) = out else {
1436        eprintln!("error: git not found");
1437        return 2;
1438    };
1439    if !out.status.success() {
1440        eprintln!("error: not a git repository");
1441        return 2;
1442    }
1443    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1444
1445    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1446    if !start_path.exists() {
1447        eprintln!("no dispatch {id} here");
1448        return 2;
1449    }
1450
1451    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
1452        Ok(s) => match serde_json::from_str(&s) {
1453            Ok(v) => v,
1454            Err(e) => {
1455                eprintln!("error parsing {}: {e}", start_path.display());
1456                return 2;
1457            }
1458        },
1459        Err(e) => {
1460            eprintln!("error reading {}: {e}", start_path.display());
1461            return 2;
1462        }
1463    };
1464
1465    let pid = start_record
1466        .get("pid")
1467        .and_then(|v| v.as_i64())
1468        .map(|v| v as libc::pid_t);
1469    let started_at = start_record
1470        .get("started_at")
1471        .and_then(|v| v.as_u64())
1472        .unwrap_or(0);
1473
1474    let is_alive = if let Some(pid) = pid {
1475        if pid > 0 {
1476            let ret = unsafe { libc::kill(pid, 0) };
1477            if ret == 0 {
1478                true
1479            } else {
1480                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1481            }
1482        } else {
1483            false
1484        }
1485    } else {
1486        false
1487    };
1488
1489    let report_path = root.join(".wt").join(format!("{id}.report.json"));
1490    let report_exists = report_path.exists();
1491
1492    let state = if report_exists {
1493        "finished"
1494    } else if is_alive {
1495        "running"
1496    } else {
1497        "dead"
1498    };
1499
1500    let now = std::time::SystemTime::now()
1501        .duration_since(std::time::UNIX_EPOCH)
1502        .map(|d| d.as_secs())
1503        .unwrap_or(0);
1504
1505    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
1506        if let Ok(content) = std::fs::read_to_string(&report_path) {
1507            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
1508                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
1509                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
1510                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
1511                    if s.chars().count() > 500 {
1512                        s.chars().take(500).collect()
1513                    } else {
1514                        s.to_string()
1515                    }
1516                });
1517                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
1518                (outcome, cost_usd, final_message, duration)
1519            } else {
1520                (None, None, None, None)
1521            }
1522        } else {
1523            (None, None, None, None)
1524        }
1525    } else {
1526        (None, None, None, None)
1527    };
1528
1529    let elapsed_s = if state == "finished" {
1530        report_duration
1531            .map(|d| d.round() as u64)
1532            .unwrap_or_else(|| now.saturating_sub(started_at))
1533    } else {
1534        now.saturating_sub(started_at)
1535    };
1536
1537    let log_path = root.join(".wt").join(format!("{id}.log"));
1538    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
1539    let progress = parse_log(&log_content);
1540
1541    if json {
1542        let status_obj = StatusOutput {
1543            id: id.to_string(),
1544            state: state.to_string(),
1545            elapsed_s,
1546            turn: progress.turn,
1547            last_tool: progress.last_tool,
1548            gate_attempts: progress.gate_attempts,
1549            gate_passed: progress.gate_passed,
1550            outcome,
1551            cost_usd,
1552            final_message,
1553        };
1554        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
1555        println!("{json_str}");
1556    } else {
1557        println!("id: {id}");
1558        println!("state: {state}");
1559        println!("elapsed_s: {elapsed_s}");
1560        println!("turn: {}", progress.turn);
1561        println!(
1562            "last_tool: {}",
1563            progress.last_tool.as_deref().unwrap_or("none")
1564        );
1565        println!("gate_attempts: {}", progress.gate_attempts);
1566        println!("gate_passed: {}", progress.gate_passed);
1567        if state == "finished" {
1568            if let Some(ref o) = outcome {
1569                println!("outcome: {o}");
1570            }
1571            if let Some(c) = cost_usd {
1572                println!("cost_usd: {c}");
1573            }
1574            if let Some(ref msg) = final_message {
1575                println!("final_message: {msg}");
1576            }
1577        }
1578    }
1579
1580    match state {
1581        "running" | "finished" => 0,
1582        _ => 1,
1583    }
1584}
1585
1586#[cfg(test)]
1587mod tests {
1588    use super::*;
1589
1590    #[test]
1591    fn outside_reads_excludes_commands_in_host_commands() {
1592        let home = Path::new("/Users/u");
1593        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1594        // rm -rf ~/repos/other is a host command (names outside and changes something)
1595        // cat ~/repos/other is not a host command (only reads)
1596        let log = "\
1597● bash rm -rf ~/repos/other/file.py -> exit 0
1598● bash cat ~/repos/other/file.py -> exit 0
1599";
1600        assert_eq!(
1601            host_commands(log),
1602            vec!["rm -rf ~/repos/other/file.py".to_string()]
1603        );
1604        assert_eq!(
1605            outside_reads(log, &allowed, home),
1606            vec!["cat ~/repos/other/file.py".to_string()]
1607        );
1608    }
1609
1610    #[test]
1611    fn outside_reads_all_terminal_patterns() {
1612        let home = Path::new("/Users/u");
1613        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1614        let log = "\
1615● bash herdr pane read p1 -> exit 0
1616● bash tmux capture-pane -t 1 -> exit 0
1617● bash screen -X hardcopy /tmp/screen.log -> exit 0
1618● bash zellij action dump-screen /tmp/dump -> exit 0
1619● bash wezterm cli get-text --pane-id 1 -> exit 0
1620";
1621        let reads = outside_reads(log, &allowed, home);
1622        assert_eq!(
1623            reads,
1624            vec![
1625                "herdr pane read p1",
1626                "tmux capture-pane -t 1",
1627                "screen -X hardcopy /tmp/screen.log",
1628                "zellij action dump-screen /tmp/dump",
1629                "wezterm cli get-text --pane-id 1",
1630            ]
1631        );
1632    }
1633
1634    #[test]
1635    fn outside_reads_all_tool_caches_ignored() {
1636        let home = Path::new("/Users/u");
1637        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1638        let log = "\
1639● bash ls ~/.cargo/bin -> exit 0
1640● bash ls ~/.rustup/toolchains -> exit 0
1641● bash ls ~/.cache/pip -> exit 0
1642● bash ls ~/.npm/_cacache -> exit 0
1643● bash ls ~/.local/share -> exit 0
1644● bash ls ~/Library/Caches/com.apple -> exit 0
1645● bash ls ~/.gradle/caches -> exit 0
1646● bash ls ~/.m2/repository -> exit 0
1647● bash ls ~/go/pkg -> exit 0
1648";
1649        assert!(outside_reads(log, &allowed, home).is_empty());
1650    }
1651
1652    #[test]
1653    fn outside_reads_trailing_punctuations_stripped() {
1654        let home = Path::new("/Users/u");
1655        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1656        let log = "\
1657● bash ls ~/secret: -> exit 0
1658● bash ls ~/secret, -> exit 0
1659● bash (ls ~/secret) -> exit 0
1660● bash bash -c 'ls ~/secret' -> exit 0
1661● bash bash -c \"ls ~/secret\" -> exit 0
1662";
1663        let reads = outside_reads(log, &allowed, home);
1664        // Deduplicated, so only one instance of the command or distinct commands:
1665        assert_eq!(reads.len(), 5);
1666    }
1667
1668    #[test]
1669    fn outside_reads_caps_at_20_and_deduplicates() {
1670        let home = Path::new("/Users/u");
1671        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
1672        let mut log = String::new();
1673        for i in 0..30 {
1674            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
1675        }
1676        // Duplicate the first one
1677        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
1678        let reads = outside_reads(&log, &allowed, home);
1679        assert_eq!(reads.len(), 20);
1680        assert_eq!(reads[0], "cat ~/secret/0.txt");
1681        assert_eq!(reads[19], "cat ~/secret/19.txt");
1682    }
1683}