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