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