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