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