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