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    let claim_check_skipped: Option<String> = report_val
1310        .as_ref()
1311        .and_then(|v| v.get("claim_check_skipped"))
1312        .and_then(|x| x.as_str())
1313        .map(String::from);
1314
1315    let mut checks = crate::review_checks::build(
1316        task_text.as_deref(),
1317        &changed_files,
1318        &subjects,
1319        hcmds.len(),
1320        reads.len(),
1321        outcome,
1322    );
1323    if let Some(ref problems) = quote_problems {
1324        if !problems.is_empty() {
1325            checks.flags.push(format!(
1326                "quote check failed ({} problem(s)): see == report",
1327                problems.len()
1328            ));
1329        }
1330    }
1331    if read_loop {
1332        checks.flags.push(
1333            "read loop: the run kept re-reading the same files without changing anything and was stopped"
1334                .to_string(),
1335        );
1336    }
1337    if !gate_left_out.is_empty() {
1338        checks
1339            .flags
1340            .push(format!("gate left out: {}", gate_left_out.join("; ")));
1341    }
1342    if let Some(ref cc) = claim_check {
1343        if !cc.contradicted.is_empty() {
1344            checks.flags.push(format!(
1345                "claim check: {} contradicted claims",
1346                cc.contradicted.len()
1347            ));
1348        }
1349    }
1350    if let Some(ref skipped) = claim_check_skipped {
1351        checks.flags.push(format!("claim check skipped: {skipped}"));
1352    }
1353    if refused_count > 0 {
1354        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
1355        checks.flags.push(format!(
1356            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
1357            first_3.join(", ")
1358        ));
1359    }
1360
1361    println!("== checks");
1362    if checks.flags.is_empty() {
1363        println!("nothing flagged");
1364    } else {
1365        for flag in &checks.flags {
1366            println!("! {flag}");
1367        }
1368    }
1369
1370    println!("== commits");
1371    if !commits_out.is_empty() {
1372        println!("{commits_out}");
1373    }
1374    println!("== files");
1375    if !files_out.is_empty() {
1376        println!("{files_out}");
1377    }
1378    println!("== tree");
1379    if tree_out.is_empty() {
1380        println!("(clean)");
1381    } else {
1382        println!("{tree_out}");
1383    }
1384    println!("== report");
1385    if let Some(ref v) = report_val {
1386        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1387            println!("outcome: {outcome}");
1388        }
1389        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1390            println!("turns: {turns}");
1391        }
1392        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1393            println!("cost_usd: {cost}");
1394        }
1395        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1396            println!("final_message: {msg}");
1397        }
1398        if let Some(ref problems) = quote_problems {
1399            if problems.is_empty() {
1400                println!("quote check: passed");
1401            } else {
1402                println!(
1403                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
1404                    problems.len()
1405                );
1406                for p in problems.iter().take(5) {
1407                    let cut: String = p.chars().take(200).collect();
1408                    println!("  {cut}");
1409                }
1410            }
1411        }
1412        if let Some(ref cc) = claim_check {
1413            println!(
1414                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
1415                cc.checked,
1416                cc.contradicted.len(),
1417                cc.not_enough_evidence,
1418                cc.parse_errors,
1419                cc.unchecked
1420            );
1421            for f in cc.contradicted.iter().take(5) {
1422                let cut: String = f.text.chars().take(200).collect();
1423                println!("  report.md:{}: {cut}", f.line);
1424                println!("    {}", f.reason);
1425            }
1426        }
1427        if let Some(ref skipped) = claim_check_skipped {
1428            println!("claim check skipped: {skipped}");
1429        }
1430    }
1431
1432    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1433    if research_report_file.exists() {
1434        println!("== research report");
1435        println!("{}", research_report_file.display());
1436        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1437            for line in content.lines().take(40) {
1438                println!("{line}");
1439            }
1440        }
1441    }
1442
1443    if !hcmds.is_empty() {
1444        println!("== host commands (may have changed things outside the worktree)");
1445        for cmd in hcmds {
1446            println!("{cmd}");
1447        }
1448    }
1449    if !reads.is_empty() {
1450        println!("== reads outside the repository");
1451        for cmd in reads {
1452            println!("{cmd}");
1453        }
1454    }
1455
1456    if args.diff {
1457        println!("== diff");
1458        if !diff_out.is_empty() {
1459            println!("{diff_out}");
1460        }
1461    }
1462
1463    if args.model_review {
1464        crate::model_review::run(&root, &args.id, &base, &wt);
1465    }
1466
1467    0
1468}
1469
1470const OUTSIDE_PATHS: &[&str] = &[
1471    "~/",
1472    "$HOME",
1473    "/Users/",
1474    "/home/",
1475    "/private/",
1476    "/var/",
1477    "/etc/",
1478    "/opt/",
1479    "/usr/",
1480];
1481
1482const CHANGE_WORDS: &[&str] = &[
1483    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1484];
1485
1486fn contains_word(cmd: &str, word: &str) -> bool {
1487    let mut start = 0;
1488    while let Some(pos) = cmd[start..].find(word) {
1489        let abs_pos = start + pos;
1490        let before_ok = if abs_pos == 0 {
1491            true
1492        } else {
1493            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1494            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1495        };
1496        let after_pos = abs_pos + word.len();
1497        let after_ok = if after_pos >= cmd.len() {
1498            true
1499        } else {
1500            let next = cmd[after_pos..].chars().next().unwrap();
1501            !next.is_alphanumeric() && next != '_' && next != '-'
1502        };
1503        if before_ok && after_ok {
1504            return true;
1505        }
1506        start = abs_pos + word.len();
1507    }
1508    false
1509}
1510
1511fn has_non_dev_null_redirect(cmd: &str) -> bool {
1512    let chars: Vec<char> = cmd.chars().collect();
1513    let mut i = 0;
1514    while i < chars.len() {
1515        if chars[i] == '>' {
1516            while i < chars.len() && chars[i] == '>' {
1517                i += 1;
1518            }
1519            if i < chars.len() && chars[i] == '|' {
1520                i += 1;
1521            }
1522            while i < chars.len() && chars[i].is_whitespace() {
1523                i += 1;
1524            }
1525            if i >= chars.len() {
1526                break;
1527            }
1528            if chars[i] == '&'
1529                && i + 1 < chars.len()
1530                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1531            {
1532                i += 1;
1533                continue;
1534            }
1535            let target_start = i;
1536            while i < chars.len()
1537                && !chars[i].is_whitespace()
1538                && chars[i] != ';'
1539                && chars[i] != '|'
1540                && chars[i] != '&'
1541                && chars[i] != ')'
1542            {
1543                i += 1;
1544            }
1545            let target: String = chars[target_start..i].iter().collect();
1546            let target = target.trim_matches(|c| c == '\'' || c == '"');
1547            if !target.is_empty() && target != "/dev/null" {
1548                return true;
1549            }
1550        } else {
1551            i += 1;
1552        }
1553    }
1554    false
1555}
1556
1557fn changes_something(cmd: &str) -> bool {
1558    for &word in CHANGE_WORDS {
1559        if contains_word(cmd, word) {
1560            return true;
1561        }
1562    }
1563    has_non_dev_null_redirect(cmd)
1564}
1565
1566fn is_host_command(cmd: &str) -> bool {
1567    if cmd.contains("git push")
1568        || cmd.contains("sudo ")
1569        || cmd.contains("cache clean")
1570        || cmd.contains("cache prune")
1571        || cmd.contains("brew ")
1572    {
1573        return true;
1574    }
1575
1576    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1577    if names_outside && changes_something(cmd) {
1578        return true;
1579    }
1580
1581    false
1582}
1583
1584pub fn host_commands(log: &str) -> Vec<String> {
1585    let cleaned = strip_ansi(log);
1586    let mut result = Vec::new();
1587    for line in cleaned.lines() {
1588        let trimmed = line.trim();
1589        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1590            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1591                let cmd = cmd.trim();
1592                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1593                    result.push(cmd.to_string());
1594                    if result.len() == 20 {
1595                        break;
1596                    }
1597                }
1598            }
1599        }
1600    }
1601    result
1602}
1603
1604const TERMINAL_READS: &[&str] = &[
1605    "herdr pane read",
1606    "tmux capture-pane",
1607    "screen -X hardcopy",
1608    "zellij action dump-screen",
1609    "wezterm cli get-text",
1610];
1611
1612const TOOL_CACHES: &[&str] = &[
1613    ".cargo",
1614    ".rustup",
1615    ".cache",
1616    ".npm",
1617    ".local",
1618    "Library/Caches",
1619    ".gradle",
1620    ".m2",
1621    "go",
1622];
1623
1624fn normalize_path(path: &Path) -> PathBuf {
1625    use std::path::Component;
1626    let mut out = PathBuf::new();
1627    for comp in path.components() {
1628        match comp {
1629            Component::ParentDir => {
1630                out.pop();
1631            }
1632            Component::CurDir => {}
1633            _ => out.push(comp),
1634        }
1635    }
1636    out
1637}
1638
1639fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1640    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1641        return true;
1642    }
1643
1644    for raw_word in cmd.split_whitespace() {
1645        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1646        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1647            Some(home.join(suffix))
1648        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1649            Some(home.join(suffix))
1650        } else if word.starts_with('/') {
1651            Some(PathBuf::from(word))
1652        } else {
1653            None
1654        };
1655
1656        if let Some(path) = raw_path {
1657            let norm_path = normalize_path(&path);
1658            if !norm_path.starts_with(home) {
1659                continue;
1660            }
1661            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
1662            if under_allowed {
1663                continue;
1664            }
1665            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
1666            if under_cache {
1667                continue;
1668            }
1669            return true;
1670        }
1671    }
1672
1673    false
1674}
1675
1676pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
1677    let host_cmds = host_commands(log);
1678    let norm_home = normalize_path(home);
1679    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
1680    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
1681        .iter()
1682        .map(|c| normalize_path(&norm_home.join(c)))
1683        .collect();
1684
1685    let cleaned = strip_ansi(log);
1686    let mut result = Vec::new();
1687    for line in cleaned.lines() {
1688        let trimmed = line.trim();
1689        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1690            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1691                let cmd = cmd.trim();
1692                if host_cmds.iter().any(|c| c == cmd) {
1693                    continue;
1694                }
1695                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
1696                    && !result.iter().any(|c| c == cmd)
1697                {
1698                    result.push(cmd.to_string());
1699                    if result.len() == 20 {
1700                        break;
1701                    }
1702                }
1703            }
1704        }
1705    }
1706    result
1707}
1708
1709fn strip_ansi(s: &str) -> String {
1710    let mut out = String::with_capacity(s.len());
1711    let mut chars = s.chars().peekable();
1712    while let Some(c) = chars.next() {
1713        if c == '\x1b' && chars.peek() == Some(&'[') {
1714            chars.next();
1715            while let Some(&next_c) = chars.peek() {
1716                chars.next();
1717                if ('\x40'..='\x7e').contains(&next_c) {
1718                    break;
1719                }
1720                if next_c == '\n' || next_c == '\x1b' {
1721                    out.push(next_c);
1722                    break;
1723                }
1724            }
1725            continue;
1726        }
1727        out.push(c);
1728    }
1729    out
1730}
1731
1732#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1733pub struct LogProgress {
1734    pub turn: u32,
1735    pub last_tool: Option<String>,
1736    pub gate_attempts: u32,
1737    pub gate_passed: bool,
1738}
1739
1740pub fn parse_log(log: &str) -> LogProgress {
1741    let cleaned = strip_ansi(log);
1742    let mut turn: u32 = 0;
1743    let mut last_tool: Option<String> = None;
1744    let mut gate_attempts: u32 = 0;
1745    let mut gate_passed: bool = false;
1746
1747    for line in cleaned.lines() {
1748        if let Some(rest) = line.strip_prefix("[Turn ") {
1749            if let Some((n_str, _)) = rest.split_once(']') {
1750                if let Ok(n) = n_str.trim().parse::<u32>() {
1751                    turn = turn.max(n);
1752                }
1753            }
1754        }
1755
1756        if let Some(tool) = line.strip_prefix("● ") {
1757            let truncated = if tool.chars().count() > 200 {
1758                tool.chars().take(200).collect()
1759            } else {
1760                tool.to_string()
1761            };
1762            last_tool = Some(truncated);
1763        }
1764
1765        if line.starts_with("✓ Gate passed") {
1766            gate_attempts += 1;
1767            gate_passed = true;
1768        } else if line.starts_with("✗ Gate failed") {
1769            gate_attempts += 1;
1770            gate_passed = false;
1771        }
1772    }
1773
1774    LogProgress {
1775        turn,
1776        last_tool,
1777        gate_attempts,
1778        gate_passed,
1779    }
1780}
1781
1782#[derive(Debug, Serialize)]
1783pub struct StatusOutput {
1784    pub id: String,
1785    pub state: String,
1786    pub elapsed_s: u64,
1787    pub turn: u32,
1788    pub last_tool: Option<String>,
1789    pub gate_attempts: u32,
1790    pub gate_passed: bool,
1791    pub outcome: Option<String>,
1792    pub cost_usd: Option<f64>,
1793    pub final_message: Option<String>,
1794}
1795
1796pub fn run_status(id: &str, json: bool) -> i32 {
1797    let out = Command::new("git")
1798        .args(["rev-parse", "--show-toplevel"])
1799        .output();
1800    let Ok(out) = out else {
1801        eprintln!("error: git not found");
1802        return 2;
1803    };
1804    if !out.status.success() {
1805        eprintln!("error: not a git repository");
1806        return 2;
1807    }
1808    let root = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1809
1810    let start_path = root.join(".wt").join(format!("{id}.start.json"));
1811    if !start_path.exists() {
1812        eprintln!("no dispatch {id} here");
1813        return 2;
1814    }
1815
1816    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
1817        Ok(s) => match serde_json::from_str(&s) {
1818            Ok(v) => v,
1819            Err(e) => {
1820                eprintln!("error parsing {}: {e}", start_path.display());
1821                return 2;
1822            }
1823        },
1824        Err(e) => {
1825            eprintln!("error reading {}: {e}", start_path.display());
1826            return 2;
1827        }
1828    };
1829
1830    let pid = start_record
1831        .get("pid")
1832        .and_then(|v| v.as_i64())
1833        .map(|v| v as libc::pid_t);
1834    let started_at = start_record
1835        .get("started_at")
1836        .and_then(|v| v.as_u64())
1837        .unwrap_or(0);
1838
1839    let is_alive = if let Some(pid) = pid {
1840        if pid > 0 {
1841            let ret = unsafe { libc::kill(pid, 0) };
1842            if ret == 0 {
1843                true
1844            } else {
1845                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
1846            }
1847        } else {
1848            false
1849        }
1850    } else {
1851        false
1852    };
1853
1854    let report_path = root.join(".wt").join(format!("{id}.report.json"));
1855    let report_exists = report_path.exists();
1856
1857    let state = if report_exists {
1858        "finished"
1859    } else if is_alive {
1860        "running"
1861    } else {
1862        "dead"
1863    };
1864
1865    let now = std::time::SystemTime::now()
1866        .duration_since(std::time::UNIX_EPOCH)
1867        .map(|d| d.as_secs())
1868        .unwrap_or(0);
1869
1870    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
1871        if let Ok(content) = std::fs::read_to_string(&report_path) {
1872            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
1873                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
1874                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
1875                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
1876                    if s.chars().count() > 500 {
1877                        s.chars().take(500).collect()
1878                    } else {
1879                        s.to_string()
1880                    }
1881                });
1882                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
1883                (outcome, cost_usd, final_message, duration)
1884            } else {
1885                (None, None, None, None)
1886            }
1887        } else {
1888            (None, None, None, None)
1889        }
1890    } else {
1891        (None, None, None, None)
1892    };
1893
1894    let elapsed_s = if state == "finished" {
1895        report_duration
1896            .map(|d| d.round() as u64)
1897            .unwrap_or_else(|| now.saturating_sub(started_at))
1898    } else {
1899        now.saturating_sub(started_at)
1900    };
1901
1902    let log_path = root.join(".wt").join(format!("{id}.log"));
1903    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
1904    let progress = parse_log(&log_content);
1905
1906    if json {
1907        let status_obj = StatusOutput {
1908            id: id.to_string(),
1909            state: state.to_string(),
1910            elapsed_s,
1911            turn: progress.turn,
1912            last_tool: progress.last_tool,
1913            gate_attempts: progress.gate_attempts,
1914            gate_passed: progress.gate_passed,
1915            outcome,
1916            cost_usd,
1917            final_message,
1918        };
1919        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
1920        println!("{json_str}");
1921    } else {
1922        println!("id: {id}");
1923        println!("state: {state}");
1924        println!("elapsed_s: {elapsed_s}");
1925        println!("turn: {}", progress.turn);
1926        println!(
1927            "last_tool: {}",
1928            progress.last_tool.as_deref().unwrap_or("none")
1929        );
1930        println!("gate_attempts: {}", progress.gate_attempts);
1931        println!("gate_passed: {}", progress.gate_passed);
1932        if state == "finished" {
1933            if let Some(ref o) = outcome {
1934                println!("outcome: {o}");
1935            }
1936            if let Some(c) = cost_usd {
1937                println!("cost_usd: {c}");
1938            }
1939            if let Some(ref msg) = final_message {
1940                println!("final_message: {msg}");
1941            }
1942        }
1943    }
1944
1945    match state {
1946        "running" | "finished" => 0,
1947        _ => 1,
1948    }
1949}
1950
1951pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
1952    let readable_canon: Vec<PathBuf> = readable
1953        .iter()
1954        .filter_map(|r| std::fs::canonicalize(r).ok())
1955        .collect();
1956    let mut out = Vec::new();
1957    for raw in text.split(|c: char| {
1958        c.is_whitespace()
1959            || matches!(
1960                c,
1961                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
1962            )
1963    }) {
1964        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
1965        if !trimmed.starts_with('/')
1966            || trimmed.starts_with("//")
1967            || trimmed.len() <= 1
1968            || trimmed == "/dev/null"
1969        {
1970            continue;
1971        }
1972        let p = Path::new(trimmed);
1973        let Ok(canon) = std::fs::canonicalize(p) else {
1974            continue;
1975        };
1976        if readable_canon.iter().any(|r| canon.starts_with(r))
1977            || is_system_path(p)
1978            || is_system_path(&canon)
1979        {
1980            continue;
1981        }
1982        let pb = PathBuf::from(trimmed);
1983        if !out.contains(&pb) {
1984            out.push(pb);
1985        }
1986    }
1987    out
1988}
1989
1990/// A path no research task means as code to read: the filesystem root, a top-level directory,
1991/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
1992fn is_system_path(p: &Path) -> bool {
1993    const SYSTEM: &[&str] = &[
1994        "/usr",
1995        "/bin",
1996        "/sbin",
1997        "/etc",
1998        "/dev",
1999        "/opt",
2000        "/System",
2001        "/Library",
2002        "/Applications",
2003        "/nix",
2004        "/proc",
2005        "/sys",
2006    ];
2007    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
2008}
2009
2010pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
2011    let mut count = 0;
2012    let mut paths = Vec::new();
2013    for line in log_content.lines() {
2014        if !line.contains("path escapes the workspace") {
2015            continue;
2016        }
2017        count += 1;
2018        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
2019            let after = after.trim_start();
2020            let after = after.split("\x1b[").next().unwrap_or(after);
2021            let path = after
2022                .split(". This run can read")
2023                .next()
2024                .unwrap_or(after)
2025                .trim();
2026            if !path.is_empty() && !paths.iter().any(|p| p == path) {
2027                paths.push(path.to_string());
2028            }
2029        }
2030    }
2031    (count, paths)
2032}
2033
2034#[cfg(test)]
2035mod tests {
2036    use super::*;
2037
2038    #[test]
2039    fn outside_reads_excludes_commands_in_host_commands() {
2040        let home = Path::new("/Users/u");
2041        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2042        // rm -rf ~/repos/other is a host command (names outside and changes something)
2043        // cat ~/repos/other is not a host command (only reads)
2044        let log = "\
2045● bash rm -rf ~/repos/other/file.py -> exit 0
2046● bash cat ~/repos/other/file.py -> exit 0
2047";
2048        assert_eq!(
2049            host_commands(log),
2050            vec!["rm -rf ~/repos/other/file.py".to_string()]
2051        );
2052        assert_eq!(
2053            outside_reads(log, &allowed, home),
2054            vec!["cat ~/repos/other/file.py".to_string()]
2055        );
2056    }
2057
2058    #[test]
2059    fn outside_reads_all_terminal_patterns() {
2060        let home = Path::new("/Users/u");
2061        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2062        let log = "\
2063● bash herdr pane read p1 -> exit 0
2064● bash tmux capture-pane -t 1 -> exit 0
2065● bash screen -X hardcopy /tmp/screen.log -> exit 0
2066● bash zellij action dump-screen /tmp/dump -> exit 0
2067● bash wezterm cli get-text --pane-id 1 -> exit 0
2068";
2069        let reads = outside_reads(log, &allowed, home);
2070        assert_eq!(
2071            reads,
2072            vec![
2073                "herdr pane read p1",
2074                "tmux capture-pane -t 1",
2075                "screen -X hardcopy /tmp/screen.log",
2076                "zellij action dump-screen /tmp/dump",
2077                "wezterm cli get-text --pane-id 1",
2078            ]
2079        );
2080    }
2081
2082    #[test]
2083    fn outside_reads_all_tool_caches_ignored() {
2084        let home = Path::new("/Users/u");
2085        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2086        let log = "\
2087● bash ls ~/.cargo/bin -> exit 0
2088● bash ls ~/.rustup/toolchains -> exit 0
2089● bash ls ~/.cache/pip -> exit 0
2090● bash ls ~/.npm/_cacache -> exit 0
2091● bash ls ~/.local/share -> exit 0
2092● bash ls ~/Library/Caches/com.apple -> exit 0
2093● bash ls ~/.gradle/caches -> exit 0
2094● bash ls ~/.m2/repository -> exit 0
2095● bash ls ~/go/pkg -> exit 0
2096";
2097        assert!(outside_reads(log, &allowed, home).is_empty());
2098    }
2099
2100    #[test]
2101    fn outside_reads_trailing_punctuations_stripped() {
2102        let home = Path::new("/Users/u");
2103        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2104        let log = "\
2105● bash ls ~/secret: -> exit 0
2106● bash ls ~/secret, -> exit 0
2107● bash (ls ~/secret) -> exit 0
2108● bash bash -c 'ls ~/secret' -> exit 0
2109● bash bash -c \"ls ~/secret\" -> exit 0
2110";
2111        let reads = outside_reads(log, &allowed, home);
2112        // Deduplicated, so only one instance of the command or distinct commands:
2113        assert_eq!(reads.len(), 5);
2114    }
2115
2116    #[test]
2117    fn outside_reads_caps_at_20_and_deduplicates() {
2118        let home = Path::new("/Users/u");
2119        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2120        let mut log = String::new();
2121        for i in 0..30 {
2122            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
2123        }
2124        // Duplicate the first one
2125        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
2126        let reads = outside_reads(&log, &allowed, home);
2127        assert_eq!(reads.len(), 20);
2128        assert_eq!(reads[0], "cat ~/secret/0.txt");
2129        assert_eq!(reads[19], "cat ~/secret/19.txt");
2130    }
2131}