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
19/// Writes a start record as pretty JSON plus a newline, through a temporary file renamed
20/// into place, so a concurrent reader never sees a partly written file.
21pub fn write_start_record(
22    path: &std::path::Path,
23    value: &serde_json::Value,
24) -> std::io::Result<()> {
25    let mut json = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
26    json.push('\n');
27    let mut tmp_name = path.as_os_str().to_os_string();
28    tmp_name.push(".tmp");
29    let tmp_path = std::path::PathBuf::from(tmp_name);
30    std::fs::write(&tmp_path, json)?;
31    std::fs::rename(&tmp_path, path)
32}
33
34struct StartRecordGuard {
35    path: PathBuf,
36    armed: bool,
37}
38
39impl Drop for StartRecordGuard {
40    fn drop(&mut self) {
41        if self.armed {
42            let _ = std::fs::remove_file(&self.path);
43        }
44    }
45}
46
47pub fn wrap_task(task: &str) -> String {
48    format!(
49        "You are implementing exactly one task. Your working directory is a git worktree on its own branch; work only there.\n\n{}\n\n{}",
50        task.trim(),
51        DISPATCH_RULES
52    )
53}
54
55pub const RESEARCH_RULES: &str = r#"Rules:
56- Do not create, modify, move or delete any file anywhere except `report.md` in your working directory.
57- 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.
58- 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.
59- Answer the question with evidence: file paths with line numbers, and quote only what is needed.
60- To quote code, do not retype it: put a line `<<quote /absolute/path:N-M>>` on its own in report.md (at most 200 lines) and the harness replaces it with those lines of the file. You need the line numbers, not a fresh read of the file.
61- Write your findings to `report.md` in your working directory, then stop calling tools and reply with one line summarising them.
62- 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 you type yourself is checked the same way, so prefer the quote line. 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.
63- Start report.md early, after your first findings, and keep it updated as you go, so it always holds your best answer."#;
64
65pub fn wrap_research(question: &str, root: &Path) -> String {
66    format!(
67        "READ-ONLY RESEARCH TASK. The code to research is under {}: read it there by absolute path.\n\n{}\n\n{}",
68        root.display(),
69        question.trim(),
70        RESEARCH_RULES
71    )
72}
73
74pub fn quick_steps(gate: &str) -> Option<String> {
75    let lines: Vec<&str> = gate
76        .lines()
77        .map(str::trim)
78        .filter(|l| !l.is_empty())
79        .collect();
80    if lines.len() < 2 {
81        return None;
82    }
83    let steps = lines[..lines.len() - 1]
84        .iter()
85        .map(|s| format!("`{s}`"))
86        .collect::<Vec<_>>()
87        .join(", ");
88    Some(format!(
89        "The check's quick steps, to run yourself before you stop: {steps}. The last step, the full run, happens at the gate."
90    ))
91}
92
93pub fn dispatch_outcome(report_outcome: &str, commits: usize) -> &'static str {
94    match report_outcome {
95        "verified" => {
96            if commits == 0 {
97                "no_changes"
98            } else {
99                "verified"
100            }
101        }
102        "gate_failed" => "gate_failed",
103        "budget_exhausted" => "budget_exhausted",
104        "blocked" => "blocked",
105        "error" => "error",
106        _ => "error",
107    }
108}
109
110pub fn exit_code(outcome: &str) -> i32 {
111    match outcome {
112        "verified" => 0,
113        "no_changes" => 4,
114        "blocked" => 5,
115        _ => 1,
116    }
117}
118
119#[derive(Debug, Serialize)]
120pub struct CommitRecord {
121    pub sha: String,
122    pub subject: String,
123}
124
125#[derive(Debug, Serialize)]
126pub struct DispatchSummary {
127    pub id: String,
128    pub worktree: String,
129    pub branch: String,
130    pub outcome: &'static str,
131    pub exit: i32,
132    pub error: Option<String>,
133    pub commits: Vec<CommitRecord>,
134    pub changed_files: Vec<String>,
135    pub final_message: Option<String>,
136    pub turns: u32,
137    pub gate_attempts: u32,
138    pub gate_failures: Vec<String>,
139    pub cost_usd: Option<f64>,
140    pub model: Option<String>,
141    pub seconds: u64,
142    pub sandbox: String,
143    pub log: String,
144    pub report: String,
145    pub gate_source: &'static str,
146    pub research_report: Option<String>,
147}
148
149fn finish_summary(summary: &DispatchSummary, wt_parent: &Path) -> i32 {
150    let _ = std::fs::create_dir_all(wt_parent);
151    let json_str = serde_json::to_string_pretty(summary).unwrap();
152    let summary_path = wt_parent.join(format!("{}.json", summary.id));
153    let _ = std::fs::write(&summary_path, format!("{json_str}\n"));
154    println!("{json_str}");
155    summary.exit
156}
157
158pub fn branch_exists_message(root: &Path, branch: &str, id: &str) -> String {
159    if crate::clean::is_branch_merged(root, branch) {
160        format!(
161            "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."
162        )
163    } else {
164        format!(
165            "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."
166        )
167    }
168}
169
170/// Source-state block for the research root and each read root, skipping duplicates.
171fn research_source_block(
172    root: &Path,
173    config_allow_read: &[PathBuf],
174    allow_read: &[PathBuf],
175) -> String {
176    let mut roots: Vec<PathBuf> = vec![root.to_path_buf()];
177    for r in config_allow_read.iter().chain(allow_read) {
178        if !roots.contains(r) {
179            roots.push(r.clone());
180        }
181    }
182    let sources: Vec<(PathBuf, crate::provenance::SourceState)> = roots
183        .into_iter()
184        .map(|p| {
185            let state = crate::provenance::source_state(&p);
186            (p, state)
187        })
188        .collect();
189    crate::provenance::render(&sources)
190}
191
192/// Appends the source-state block to a copied report. Failure is reported, not fatal.
193fn append_source_state(path: &Path, block: &str) {
194    use std::io::Write;
195    let result = std::fs::OpenOptions::new()
196        .append(true)
197        .open(path)
198        .and_then(|mut f| f.write_all(format!("\n\n{block}").as_bytes()));
199    if let Err(e) = result {
200        eprintln!(
201            "error: could not add the source state to {}: {e}",
202            path.display()
203        );
204    }
205}
206
207pub fn run_dispatch(args: &DispatchArgs) -> i32 {
208    if let Ok(home) = crate::skill::home_dir() {
209        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
210            eprintln!(
211                "blyte: added context rules to {} (they apply from the next Claude session)",
212                path.display()
213            );
214        }
215    }
216
217    // 1. Root repository discovery and worktree preparation
218    let out = Command::new("git")
219        .args(["rev-parse", "--show-toplevel"])
220        .output();
221    let Ok(out) = out else {
222        eprintln!("error: git not found");
223        return 2;
224    };
225    if !out.status.success() {
226        eprintln!("error: not a git repository");
227        return 2;
228    }
229    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
230    let root = match crate::clean::find_repo_root() {
231        Ok(r) => r,
232        Err(e) => {
233            eprintln!("error: {e}");
234            return 2;
235        }
236    };
237    crate::registry::register(&root);
238
239    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
240        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
241        Ok(None) => (None, false),
242        Err(e) => {
243            eprintln!("{e}");
244            return 2;
245        }
246    };
247    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
248
249    let mut left_out: Vec<(String, String)> = Vec::new();
250    let (gate, gate_source) = if args.research {
251        ("test -s report.md".to_string(), "research")
252    } else if let Some(ref g) = args.gate {
253        (g.clone(), "flag")
254    } else if let Some(ref g) = dispatch_cfg.gate {
255        let toml_path = if from_main {
256            root.join("blyte.toml")
257        } else {
258            start_dir.join("blyte.toml")
259        };
260        let toml_content = std::fs::read_to_string(&toml_path).unwrap_or_default();
261        left_out = crate::gate_drift::left_out_steps(&toml_content);
262        if g.trim().is_empty() {
263            eprintln!(
264                "error: the gate in blyte.toml is empty; every step was left out. Fix the steps blyte init named, or pass --gate."
265            );
266            for (cmd, reason) in &left_out {
267                eprintln!("  {cmd}: {reason}");
268            }
269            return 2;
270        }
271        let missing = crate::gate_drift::missing_ci_steps(&root, g, &toml_content);
272        if let Some(warning) = crate::gate_drift::format_gate_drift_warning(&missing) {
273            eprintln!("{warning}");
274        }
275        if !left_out.is_empty() {
276            let formatted: Vec<String> = left_out
277                .iter()
278                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
279                .collect();
280            eprintln!(
281                "blyte: the gate is partial; left out: {}",
282                formatted.join("; ")
283            );
284        }
285        let source = if from_main {
286            "blyte.toml (main checkout)"
287        } else {
288            "blyte.toml"
289        };
290        (g.clone(), source)
291    } else {
292        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
293        return 2;
294    };
295
296    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
297    let (max_seconds, max_turns) = if args.research {
298        (
299            args.max_seconds.unwrap_or(1800),
300            args.max_turns.unwrap_or(300),
301        )
302    } else {
303        (
304            args.max_seconds
305                .or(dispatch_cfg.max_seconds)
306                .unwrap_or(3600),
307            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
308        )
309    };
310    let max_cost = args.max_cost_usd.or(dispatch_cfg.max_cost);
311    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
312    let network = args
313        .network
314        .as_deref()
315        .or(dispatch_cfg.network.as_deref())
316        .unwrap_or("on");
317
318    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
319        let content = match std::fs::read_to_string(tf) {
320            Ok(s) => s,
321            Err(e) => {
322                eprintln!("error reading task file {}: {e}", tf.display());
323                return 2;
324            }
325        };
326        (content, Some(tf.display().to_string()))
327    } else {
328        match (&args.plan, &args.plan_task) {
329            (Some(plan_path), Some(plan_task)) => {
330                let plan_str = match std::fs::read_to_string(plan_path) {
331                    Ok(s) => s,
332                    Err(e) => {
333                        eprintln!("error reading plan {plan_path}: {e}");
334                        return 2;
335                    }
336                };
337                let section = match crate::plan_section::extract(&plan_str, plan_task) {
338                    Some(sec) => sec,
339                    None => {
340                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
341                        if let Some(hint) =
342                            crate::plan_section::explain_missing(&plan_str, plan_task)
343                        {
344                            eprintln!("  {hint}");
345                        }
346                        return 2;
347                    }
348                };
349                let content = format!("From the plan {plan_path}:\n\n{section}");
350                (content, None)
351            }
352            _ => {
353                eprintln!("error: give a task file, or --plan with --plan-task");
354                return 2;
355            }
356        }
357    };
358
359    let home = std::env::var_os("HOME").map(PathBuf::from);
360    let main_checkout = root.clone();
361    let config_allow_read = match crate::config::expand_allow_read(
362        &dispatch_cfg.allow_read,
363        home.as_deref(),
364        &main_checkout,
365    ) {
366        Ok(paths) => paths,
367        Err(e) => {
368            eprintln!("{e}");
369            return 2;
370        }
371    };
372
373    if !args.no_path_check {
374        let mut readable = vec![start_dir.clone(), root.clone()];
375        readable.extend(config_allow_read.iter().cloned());
376        readable.extend(args.allow_read.iter().cloned());
377        let bad = unreadable_paths(&task_content, &readable);
378        if !bad.is_empty() {
379            let shown: Vec<String> = bad
380                .iter()
381                .take(5)
382                .map(|p| p.display().to_string())
383                .collect();
384            eprintln!(
385                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
386                shown.join(", ")
387            );
388            if args.research {
389                return 2;
390            }
391        }
392    }
393
394    let wt_parent = root.join(".wt");
395    let worktree_dir = wt_parent.join(&args.id);
396    let branch = format!("wip/{}", args.id);
397    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
398    let task_file_recorded =
399        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
400
401    if !args.research {
402        let start_path = wt_parent.join(format!("{}.start.json", args.id));
403        if start_path.exists() {
404            let start_str = match std::fs::read_to_string(&start_path) {
405                Ok(s) => s,
406                Err(e) => {
407                    eprintln!("error reading {}: {e}", start_path.display());
408                    return 2;
409                }
410            };
411            let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
412                Ok(v) => v,
413                Err(e) => {
414                    eprintln!("error parsing {}: {e}", start_path.display());
415                    return 2;
416                }
417            };
418            let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
419                eprintln!("error: missing pid in {}", start_path.display());
420                return 2;
421            };
422            let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
423                eprintln!("error: missing started_at in {}", start_path.display());
424                return 2;
425            };
426            if crate::clean::is_pid_alive(pid) {
427                let summary_path = wt_parent.join(format!("{}.json", args.id));
428                let finished_since_start = if summary_path.exists() {
429                    let meta = match std::fs::metadata(&summary_path) {
430                        Ok(m) => m,
431                        Err(e) => {
432                            eprintln!("error reading metadata of {}: {e}", summary_path.display());
433                            return 2;
434                        }
435                    };
436                    let mtime = match meta.modified() {
437                        Ok(t) => t,
438                        Err(e) => {
439                            eprintln!("error reading mtime of {}: {e}", summary_path.display());
440                            return 2;
441                        }
442                    };
443                    let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
444                        Ok(d) => d.as_secs(),
445                        Err(e) => {
446                            eprintln!("error reading timestamp of {}: {e}", summary_path.display());
447                            return 2;
448                        }
449                    };
450                    mtime_secs >= started_at
451                } else {
452                    false
453                };
454                if !finished_since_start {
455                    eprintln!(
456                        "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
457                        args.id
458                    );
459                    return 2;
460                }
461            }
462        }
463
464        let branch_ref = format!("refs/heads/{branch}");
465        let branch_out = Command::new("git")
466            .args(["show-ref", "--verify", "--quiet", &branch_ref])
467            .current_dir(&root)
468            .output();
469        let branch_exists = match branch_out {
470            Ok(o) if o.status.success() => true,
471            Ok(o) if o.status.code() == Some(1) => false,
472            Ok(o) => {
473                eprintln!(
474                    "error: git show-ref --verify --quiet {branch_ref}: {}",
475                    String::from_utf8_lossy(&o.stderr).trim()
476                );
477                return 2;
478            }
479            Err(e) => {
480                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
481                return 2;
482            }
483        };
484
485        if worktree_dir.exists() || branch_exists {
486            match crate::clean::remove_finished_run(&root, &args.id) {
487                Ok(Some(reason)) => {
488                    let secs =
489                        match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
490                            Ok(d) => d.as_secs(),
491                            Err(e) => {
492                                eprintln!("error: system clock before unix epoch: {e}");
493                                return 2;
494                            }
495                        };
496                    let archive_rel = format!(".wt/archive/{}-{secs}", args.id);
497                    let archive_dir = root.join(&archive_rel);
498                    if let Err(e) = std::fs::create_dir_all(&archive_dir) {
499                        eprintln!("error: {}: {e}", archive_dir.display());
500                        return 2;
501                    }
502                    for ext in ["json", "report.json", "start.json", "verdict.json", "log"] {
503                        let file_name = format!("{}.{ext}", args.id);
504                        let src = wt_parent.join(&file_name);
505                        if src.exists() {
506                            let dst = archive_dir.join(&file_name);
507                            if let Err(e) = std::fs::rename(&src, &dst) {
508                                eprintln!(
509                                    "error: rename {} -> {}: {e}",
510                                    src.display(),
511                                    dst.display()
512                                );
513                                return 2;
514                            }
515                        }
516                    }
517                    eprintln!(
518                        "dispatch: replaced the earlier run {} ({reason}); its records are in {archive_rel}/",
519                        args.id
520                    );
521                }
522                Ok(None) => {}
523                Err(e) => {
524                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
525                    return 2;
526                }
527            }
528        }
529    } else if worktree_dir.exists() {
530        eprintln!("error: {} already exists", worktree_dir.display());
531        return 2;
532    }
533
534    let started_at = std::time::SystemTime::now()
535        .duration_since(std::time::UNIX_EPOCH)
536        .map(|d| d.as_secs())
537        .unwrap_or(0);
538    let mut tags = args.tags.clone();
539    if args.research {
540        tags.push("research".to_string());
541    }
542    let session = crate::usage_log::session_from(
543        std::env::var("BLYTE_SESSION").ok(),
544        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
545    );
546    let start_path = wt_parent.join(format!("{}.start.json", args.id));
547    let mut initial_start = serde_json::json!({
548        "id": args.id,
549        "pid": std::process::id(),
550        "started_at": started_at,
551        "starting": true,
552        "tags": tags,
553        "plan": args.plan,
554        "plan_task": args.plan_task,
555        "base": args.base,
556    });
557    if let Some(ref s) = session {
558        initial_start["session"] = serde_json::json!(s);
559    }
560    if args.research {
561        initial_start["research"] = serde_json::json!(true);
562    }
563    if let Err(err) = std::fs::create_dir_all(&wt_parent)
564        .and_then(|()| write_start_record(&start_path, &initial_start))
565    {
566        eprintln!(
567            "error: could not write the start record {}: {err}",
568            start_path.display()
569        );
570        return 2;
571    }
572    let mut start_guard = StartRecordGuard {
573        path: start_path.clone(),
574        armed: true,
575    };
576
577    if !args.research {
578        crate::clean::spawn_background_clean(&root, Some(&args.id));
579    }
580
581    let base_commit: Option<String> = if args.research {
582        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
583            eprintln!(
584                "error creating scratch directory {}: {e}",
585                worktree_dir.display()
586            );
587            return 2;
588        }
589        let init_out = Command::new("git")
590            .args(["init", "-q"])
591            .current_dir(&worktree_dir)
592            .output();
593        match init_out {
594            Ok(o) if o.status.success() => {}
595            Ok(o) => {
596                eprintln!(
597                    "error: git init failed: {}",
598                    String::from_utf8_lossy(&o.stderr)
599                );
600                return 2;
601            }
602            Err(e) => {
603                eprintln!("error: failed to execute git init: {e}");
604                return 2;
605            }
606        }
607        let commit_out = Command::new("git")
608            .args([
609                "-c",
610                "user.name=blyte",
611                "-c",
612                "user.email=blyte@local",
613                "commit",
614                "-q",
615                "--allow-empty",
616                "-m",
617                "research",
618            ])
619            .current_dir(&worktree_dir)
620            .output();
621        match commit_out {
622            Ok(o) if o.status.success() => {}
623            Ok(o) => {
624                eprintln!(
625                    "error: git commit failed: {}",
626                    String::from_utf8_lossy(&o.stderr)
627                );
628                return 2;
629            }
630            Err(e) => {
631                eprintln!("error: failed to execute git commit: {e}");
632                return 2;
633            }
634        }
635        None
636    } else if !worktree_dir.exists() {
637        let branch_exists = Command::new("git")
638            .args([
639                "rev-parse",
640                "--verify",
641                "--quiet",
642                &format!("refs/heads/{branch}"),
643            ])
644            .current_dir(&root)
645            .output()
646            .map(|o| o.status.success())
647            .unwrap_or(false);
648        if branch_exists {
649            eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
650            return 2;
651        }
652        let base_commit = Command::new("git")
653            .args([
654                "rev-parse",
655                "--verify",
656                &format!("{}^{{commit}}", args.base),
657            ])
658            .current_dir(&start_dir)
659            .output();
660        let base_commit = match base_commit {
661            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
662            _ => {
663                eprintln!("error: base {} is not a commit", args.base);
664                return 2;
665            }
666        };
667        let add_out = Command::new("git")
668            .args([
669                "worktree",
670                "add",
671                "-b",
672                &branch,
673                worktree_dir.to_str().unwrap(),
674                &base_commit,
675            ])
676            .current_dir(&root)
677            .output();
678        match add_out {
679            Ok(o) if o.status.success() => {}
680            Ok(o) => {
681                eprintln!(
682                    "error: git worktree add failed: {}",
683                    String::from_utf8_lossy(&o.stderr)
684                );
685                return 2;
686            }
687            Err(e) => {
688                eprintln!("error: failed to execute git worktree add: {e}");
689                return 2;
690            }
691        }
692        Some(base_commit)
693    } else {
694        let base_commit = match Command::new("git")
695            .args([
696                "rev-parse",
697                "--verify",
698                &format!("{}^{{commit}}", args.base),
699            ])
700            .current_dir(&start_dir)
701            .output()
702        {
703            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
704            Ok(o) => {
705                eprintln!(
706                    "error: git rev-parse {} failed: {}",
707                    args.base,
708                    String::from_utf8_lossy(&o.stderr).trim()
709                );
710                return 2;
711            }
712            Err(e) => {
713                eprintln!("error: failed to execute git rev-parse: {e}");
714                return 2;
715            }
716        };
717        let wt_head = match Command::new("git")
718            .args([
719                "-C",
720                worktree_dir.to_str().unwrap(),
721                "rev-parse",
722                "--verify",
723                "HEAD^{commit}",
724            ])
725            .output()
726        {
727            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
728            Ok(o) => {
729                eprintln!(
730                    "error: git -C {} rev-parse HEAD failed: {}",
731                    worktree_dir.display(),
732                    String::from_utf8_lossy(&o.stderr).trim()
733                );
734                return 2;
735            }
736            Err(e) => {
737                eprintln!("error: failed to execute git rev-parse: {e}");
738                return 2;
739            }
740        };
741        let ancestor_out = Command::new("git")
742            .args(["merge-base", "--is-ancestor", &base_commit, &wt_head])
743            .current_dir(&root)
744            .output();
745        match ancestor_out {
746            Ok(o) if o.status.success() => {}
747            Ok(o) if o.status.code() == Some(1) => {
748                let short_wt_head = &wt_head[..wt_head.len().min(7)];
749                let short_base = &base_commit[..base_commit.len().min(7)];
750                eprintln!(
751                    "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.",
752                    id = args.id,
753                    base_name = args.base,
754                );
755                return 2;
756            }
757            Ok(o) => {
758                eprintln!(
759                    "error: git merge-base --is-ancestor failed: {}",
760                    String::from_utf8_lossy(&o.stderr).trim()
761                );
762                return 2;
763            }
764            Err(e) => {
765                eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
766                return 2;
767            }
768        }
769        Some(base_commit)
770    };
771
772    // 2. Ensure .wt/ is in info/exclude
773    let common_dir_raw = Command::new("git")
774        .args(["rev-parse", "--git-common-dir"])
775        .current_dir(&root)
776        .output();
777    let common_dir = if let Ok(out) = common_dir_raw {
778        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
779        if p.is_absolute() {
780            p
781        } else {
782            root.join(p)
783        }
784    } else {
785        root.join(".git")
786    };
787
788    let exclude_path = common_dir.join("info").join("exclude");
789    if let Some(parent) = exclude_path.parent() {
790        let _ = std::fs::create_dir_all(parent);
791    }
792    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
793    if !content.lines().any(|l| l.trim() == ".wt/") {
794        let mut new_content = content;
795        if !new_content.is_empty() && !new_content.ends_with('\n') {
796            new_content.push('\n');
797        }
798        new_content.push_str(".wt/\n");
799        let _ = std::fs::write(&exclude_path, new_content);
800    }
801
802    // 3. Record base_sha
803    let base_out = Command::new("git")
804        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
805        .output();
806    let base_sha = match base_out {
807        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
808        _ => {
809            eprintln!("error: could not resolve HEAD in worktree");
810            return 2;
811        }
812    };
813
814    if !args.research {
815        if let Some(ref setup_cmd) = dispatch_cfg.setup {
816            let first_line = setup_cmd.lines().next().unwrap_or("");
817            eprintln!("setup: {first_line}");
818            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
819            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
820            if let Err(msg) = crate::setup::run_setup(
821                setup_cmd,
822                &worktree_dir,
823                &main_checkout,
824                &dispatch_cfg.env,
825                &setup_log_path,
826                crate::setup::SETUP_TIMEOUT,
827            ) {
828                let outcome = "blocked";
829                let exit = exit_code(outcome);
830                let first_line_err = msg.lines().next().unwrap_or("").to_string();
831                let summary = DispatchSummary {
832                    id: args.id.clone(),
833                    worktree: worktree_dir.display().to_string(),
834                    branch: branch.clone(),
835                    outcome,
836                    exit,
837                    error: Some(first_line_err),
838                    commits: Vec::new(),
839                    changed_files: Vec::new(),
840                    final_message: Some(msg),
841                    turns: 0,
842                    gate_attempts: 0,
843                    gate_failures: Vec::new(),
844                    cost_usd: None,
845                    model: None,
846                    seconds: 0,
847                    sandbox: args.sandbox.clone(),
848                    log: setup_log_path.display().to_string(),
849                    report: "".to_string(),
850                    gate_source,
851                    research_report: None,
852                };
853                return finish_summary(&summary, &wt_parent);
854            }
855        }
856    }
857
858    // 4. Write task file and spawn child process
859    let _ = std::fs::create_dir_all(&wt_parent);
860    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
861        eprintln!("error writing task file {}: {e}", task_md_path.display());
862        return 2;
863    }
864
865    let log_path = wt_parent.join(format!("{}.log", args.id));
866    let summary_path = wt_parent.join(format!("{}.json", args.id));
867    if summary_path.exists() {
868        let _ = std::fs::remove_file(&summary_path);
869    }
870    let report_path = wt_parent.join(format!("{}.report.json", args.id));
871    if report_path.exists() {
872        let _ = std::fs::remove_file(&report_path);
873    }
874    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
875    if research_report_path.exists() {
876        let _ = std::fs::remove_file(&research_report_path);
877    }
878
879    let log_file = match std::fs::File::create(&log_path) {
880        Ok(f) => f,
881        Err(e) => {
882            eprintln!("error creating log file {}: {e}", log_path.display());
883            return 2;
884        }
885    };
886    let log_file_err = match log_file.try_clone() {
887        Ok(f) => f,
888        Err(e) => {
889            eprintln!("error cloning log file handle: {e}");
890            return 2;
891        }
892    };
893
894    let current_exe = match std::env::current_exe() {
895        Ok(p) => p,
896        Err(e) => {
897            eprintln!("error getting current executable: {e}");
898            return 2;
899        }
900    };
901
902    let mut cmd = Command::new(current_exe);
903    cmd.current_dir(&worktree_dir);
904    cmd.stdout(log_file);
905    cmd.stderr(log_file_err);
906
907    for (k, v) in &dispatch_cfg.env {
908        cmd.env(k, v);
909    }
910    cmd.env("BLYTE_DISPATCH_ID", &args.id);
911
912    cmd.arg("--gate").arg(&gate);
913    cmd.arg("--rollback=false");
914    cmd.arg("--max-seconds").arg(max_seconds.to_string());
915    cmd.arg("--max-turns").arg(max_turns.to_string());
916    cmd.arg("--report").arg(&report_path);
917
918    if let Some(m) = model {
919        cmd.arg("--model").arg(m);
920    }
921    if let Some(c) = max_cost {
922        cmd.arg("--max-cost").arg(c.to_string());
923    }
924    if let Some(fb) = fold_budget {
925        cmd.arg("--fold-budget").arg(fb.to_string());
926    }
927    cmd.arg("--sandbox").arg(&args.sandbox);
928    cmd.arg("--network").arg(network);
929    for r in &config_allow_read {
930        cmd.arg("--allow-read").arg(r);
931    }
932    for r in &args.allow_read {
933        cmd.arg("--allow-read").arg(r);
934    }
935    for p in &args.pass_env {
936        cmd.arg("--pass-env").arg(p);
937    }
938    // The read and grep tools may read what the sandbox may read.
939    for r in config_allow_read.iter().chain(&args.allow_read) {
940        cmd.arg("--read-root").arg(r);
941    }
942    if args.research {
943        cmd.arg("--read-root").arg(&root);
944        cmd.arg("--no-gate-slot");
945        cmd.arg("--research");
946        if !args.no_claim_check {
947            cmd.arg("--claim-check");
948        }
949    }
950
951    cmd.arg("--");
952    let research_sources = args
953        .research
954        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
955    let task_prompt = if let Some(block) = &research_sources {
956        wrap_research(&format!("{block}\n\n{task_content}"), &root)
957    } else {
958        let mut prompt = wrap_task(&task_content);
959        if let Some(qs) = quick_steps(&gate) {
960            prompt.push_str("\n\n");
961            prompt.push_str(&qs);
962        }
963        prompt
964    };
965    cmd.arg(task_prompt);
966
967    let mut child = match cmd.spawn() {
968        Ok(c) => c,
969        Err(e) => {
970            eprintln!("error spawning child process: {e}");
971            return 2;
972        }
973    };
974    start_guard.armed = false;
975
976    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
977    let mut start_json = serde_json::json!({
978        "id": args.id,
979        "pid": child.id(),
980        "started_at": started_at,
981        "task_file": task_file_recorded,
982        "gate": gate,
983        "tags": tags,
984        "env": env_names,
985        "max_turns": max_turns,
986        "max_seconds": max_seconds,
987        "plan": args.plan,
988        "plan_task": args.plan_task,
989        "base": args.base,
990        "base_sha": base_commit,
991    });
992    if let Some(session) = session {
993        start_json["session"] = serde_json::json!(session);
994    }
995    if args.research {
996        start_json["research"] = serde_json::json!(true);
997    }
998    if !left_out.is_empty() {
999        start_json["gate_left_out"] = serde_json::json!(left_out
1000            .iter()
1001            .map(|(command, reason)| serde_json::json!({
1002                "command": command,
1003                "reason": reason,
1004            }))
1005            .collect::<Vec<_>>());
1006    }
1007    if let Err(err) = write_start_record(&start_path, &start_json) {
1008        eprintln!(
1009            "error: could not write the start record {}: {err}",
1010            start_path.display()
1011        );
1012    }
1013
1014    let _ = child.wait();
1015
1016    if !left_out.is_empty() {
1017        if let Ok(report_str) = std::fs::read_to_string(&report_path) {
1018            if let Ok(mut report_val) = serde_json::from_str::<serde_json::Value>(&report_str) {
1019                let formatted: Vec<String> = left_out
1020                    .iter()
1021                    .map(|(cmd, reason)| format!("{cmd} ({reason})"))
1022                    .collect();
1023                report_val["gate_left_out"] = serde_json::json!(formatted);
1024                if let Ok(updated) = serde_json::to_string_pretty(&report_val) {
1025                    let _ = std::fs::write(&report_path, updated + "\n");
1026                }
1027            }
1028        }
1029    }
1030
1031    let scratch_report = worktree_dir.join("report.md");
1032    if args.research {
1033        let is_non_empty = std::fs::metadata(&scratch_report)
1034            .map(|m| m.len() > 0)
1035            .unwrap_or(false);
1036        if is_non_empty {
1037            let _ = std::fs::copy(&scratch_report, &research_report_path);
1038            if let Some(block) = &research_sources {
1039                append_source_state(&research_report_path, block);
1040            }
1041            if let Some(ref report_to) = args.report_to {
1042                if let Some(parent) = report_to.parent() {
1043                    if !parent.as_os_str().is_empty() {
1044                        let _ = std::fs::create_dir_all(parent);
1045                    }
1046                }
1047                let _ = std::fs::copy(&scratch_report, report_to);
1048                if let Some(block) = &research_sources {
1049                    append_source_state(report_to, block);
1050                }
1051            }
1052        }
1053    }
1054
1055    // 5. Read report, commits and changed files
1056    let log_out = Command::new("git")
1057        .args([
1058            "-C",
1059            worktree_dir.to_str().unwrap(),
1060            "log",
1061            "--reverse",
1062            "--format=%h%x09%s",
1063            &format!("{base_sha}..HEAD"),
1064        ])
1065        .output();
1066
1067    let mut commits = Vec::new();
1068    if let Ok(o) = log_out {
1069        let text = String::from_utf8_lossy(&o.stdout);
1070        for line in text.lines() {
1071            let line = line.trim();
1072            if line.is_empty() {
1073                continue;
1074            }
1075            if let Some((sha, subject)) = line.split_once('\t') {
1076                commits.push(CommitRecord {
1077                    sha: sha.to_string(),
1078                    subject: subject.to_string(),
1079                });
1080            }
1081        }
1082    }
1083
1084    let diff_out = Command::new("git")
1085        .args([
1086            "-C",
1087            worktree_dir.to_str().unwrap(),
1088            "diff",
1089            "--name-only",
1090            &format!("{base_sha}..HEAD"),
1091        ])
1092        .output();
1093
1094    let mut changed_files = Vec::new();
1095    if let Ok(o) = diff_out {
1096        let text = String::from_utf8_lossy(&o.stdout);
1097        for line in text.lines() {
1098            let line = line.trim();
1099            if !line.is_empty() {
1100                changed_files.push(line.to_string());
1101            }
1102        }
1103    }
1104
1105    let report_read = std::fs::read_to_string(&report_path);
1106    let record: Result<serde_json::Value, String> = match report_read {
1107        Ok(s) => serde_json::from_str(&s).map_err(|e| format!("unreadable report JSON: {e}")),
1108        Err(e) => Err(format!("missing report: {e}")),
1109    };
1110
1111    let (
1112        report_outcome,
1113        error,
1114        final_message,
1115        turns,
1116        report_turns,
1117        gate_attempts,
1118        gate_failures,
1119        cost_usd,
1120        model,
1121        seconds,
1122        sandbox,
1123    ) = match record {
1124        Ok(rec) => {
1125            let gate_failures = rec
1126                .get("gate_failures")
1127                .and_then(|v| v.as_array())
1128                .map(|arr| {
1129                    arr.iter()
1130                        .filter_map(|v| v.as_str())
1131                        .map(|s| {
1132                            if s.chars().count() > 1000 {
1133                                s.chars().take(1000).collect()
1134                            } else {
1135                                s.to_string()
1136                            }
1137                        })
1138                        .collect()
1139                })
1140                .unwrap_or_default();
1141            let raw_turns = rec.get("turns").and_then(|v| v.as_u64());
1142
1143            (
1144                rec.get("outcome")
1145                    .and_then(|v| v.as_str())
1146                    .unwrap_or("error")
1147                    .to_string(),
1148                rec.get("error").and_then(|v| v.as_str()).map(String::from),
1149                rec.get("final_message")
1150                    .and_then(|v| v.as_str())
1151                    .map(String::from),
1152                raw_turns.unwrap_or(0) as u32,
1153                raw_turns,
1154                rec.get("gate_attempts")
1155                    .and_then(|v| v.as_u64())
1156                    .unwrap_or(0) as u32,
1157                gate_failures,
1158                rec.get("cost_usd").and_then(|v| v.as_f64()),
1159                rec.get("model_id")
1160                    .and_then(|v| v.as_str())
1161                    .map(String::from),
1162                rec.get("duration_seconds")
1163                    .and_then(|v| v.as_f64())
1164                    .unwrap_or(0.0)
1165                    .round() as u64,
1166                rec.get("sandbox")
1167                    .and_then(|v| v.as_str())
1168                    .unwrap_or(&args.sandbox)
1169                    .to_string(),
1170            )
1171        }
1172        Err(err_msg) => (
1173            "error".to_string(),
1174            Some(err_msg),
1175            None,
1176            0,
1177            None,
1178            0,
1179            Vec::new(),
1180            None,
1181            None,
1182            0,
1183            args.sandbox.clone(),
1184        ),
1185    };
1186
1187    let outcome = if args.research {
1188        match report_outcome.as_str() {
1189            "verified" => "verified",
1190            "gate_failed" => "gate_failed",
1191            "budget_exhausted" => "budget_exhausted",
1192            "blocked" => "blocked",
1193            _ => "error",
1194        }
1195    } else {
1196        dispatch_outcome(&report_outcome, commits.len())
1197    };
1198    let exit = exit_code(outcome);
1199
1200    if args.research {
1201        if research_report_path.exists() {
1202            if let Err(err) =
1203                crate::provenance::mark_if_unverified(&research_report_path, outcome, report_turns)
1204            {
1205                eprintln!(
1206                    "error: could not mark {} as not verified: {err}",
1207                    research_report_path.display()
1208                );
1209            }
1210        }
1211        if let Some(ref report_to) = args.report_to {
1212            if report_to.exists() {
1213                if let Err(err) =
1214                    crate::provenance::mark_if_unverified(report_to, outcome, report_turns)
1215                {
1216                    eprintln!(
1217                        "error: could not mark {} as not verified: {err}",
1218                        report_to.display()
1219                    );
1220                }
1221            }
1222        }
1223    }
1224
1225    let research_report = if args.research && research_report_path.exists() {
1226        Some(research_report_path.display().to_string())
1227    } else {
1228        None
1229    };
1230
1231    // 6. Print JSON summary
1232    let summary = DispatchSummary {
1233        id: args.id.clone(),
1234        worktree: worktree_dir.display().to_string(),
1235        branch,
1236        outcome,
1237        exit,
1238        error,
1239        commits,
1240        changed_files,
1241        final_message,
1242        turns,
1243        gate_attempts,
1244        gate_failures,
1245        cost_usd,
1246        model,
1247        seconds,
1248        sandbox,
1249        log: log_path.display().to_string(),
1250        report: report_path.display().to_string(),
1251        gate_source,
1252        research_report,
1253    };
1254
1255    finish_summary(&summary, &wt_parent)
1256}
1257
1258pub fn run_review(args: &ReviewArgs) -> i32 {
1259    let root = match crate::clean::find_repo_root() {
1260        Ok(r) => r,
1261        Err(e) => {
1262            eprintln!("error: {e}");
1263            return 2;
1264        }
1265    };
1266
1267    if args.notes.is_some() && args.verdict.is_none() {
1268        eprintln!("error: --notes requires --verdict");
1269        return 2;
1270    }
1271
1272    if let Some(ref v) = args.verdict {
1273        let wt_dir = root.join(".wt");
1274        if let Err(e) = std::fs::create_dir_all(&wt_dir) {
1275            eprintln!("error creating directory {}: {e}", wt_dir.display());
1276            return 2;
1277        }
1278        let verdict_path = wt_dir.join(format!("{}.verdict.json", args.id));
1279        let ts = std::time::SystemTime::now()
1280            .duration_since(std::time::UNIX_EPOCH)
1281            .map(|d| d.as_secs())
1282            .unwrap_or(0);
1283        let verdict_obj = serde_json::json!({
1284            "verdict": v.as_str(),
1285            "notes": args.notes.as_deref().unwrap_or(""),
1286            "ts": ts,
1287        });
1288        let json_str = match serde_json::to_string_pretty(&verdict_obj) {
1289            Ok(s) => s,
1290            Err(e) => {
1291                eprintln!("error serializing verdict: {e}");
1292                return 2;
1293            }
1294        };
1295        if let Err(e) = std::fs::write(&verdict_path, json_str + "\n") {
1296            eprintln!("error writing {}: {e}", verdict_path.display());
1297            return 2;
1298        }
1299        println!("recorded verdict {} for {}", v.as_str(), args.id);
1300        crate::clean::clean_on_review(&root, &args.id);
1301        return 0;
1302    }
1303
1304    let wt = root.join(".wt").join(&args.id);
1305    if !wt.exists() {
1306        eprintln!("error: worktree {} does not exist", wt.display());
1307        return 2;
1308    }
1309
1310    // Runs dispatched before base_sha was recorded have no start record field; a record that
1311    // exists but cannot be read is an error, not a reason to guess the base.
1312    let start_path = root.join(".wt").join(format!("{}.start.json", args.id));
1313    let start_base_sha: Option<String> = match std::fs::read_to_string(&start_path) {
1314        Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
1315            Ok(v) => v
1316                .get("base_sha")
1317                .and_then(|s| s.as_str())
1318                .map(str::trim)
1319                .filter(|s| !s.is_empty())
1320                .map(String::from),
1321            Err(e) => {
1322                eprintln!("error: cannot parse {}: {e}", start_path.display());
1323                return 2;
1324            }
1325        },
1326        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1327        Err(e) => {
1328            eprintln!("error: cannot read {}: {e}", start_path.display());
1329            return 2;
1330        }
1331    };
1332
1333    let base = if let Some(sha) = start_base_sha {
1334        let has_base = Command::new("git")
1335            .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
1336            .current_dir(&wt)
1337            .output()
1338            .map(|o| o.status.success())
1339            .unwrap_or(false);
1340        if !has_base {
1341            eprintln!(
1342                "error: run {} started from {sha}, which is not in this repository",
1343                args.id
1344            );
1345            return 2;
1346        }
1347        sha
1348    } else {
1349        let root_head = Command::new("git")
1350            .args(["rev-parse", "HEAD"])
1351            .current_dir(&root)
1352            .output();
1353        let root_head_sha = match root_head {
1354            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1355            _ => {
1356                eprintln!("error: could not resolve root HEAD");
1357                return 2;
1358            }
1359        };
1360
1361        let mb_out = Command::new("git")
1362            .args(["merge-base", "HEAD", &root_head_sha])
1363            .current_dir(&wt)
1364            .output();
1365        match mb_out {
1366            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1367            _ => {
1368                eprintln!(
1369                    "error: cannot find where run {} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}",
1370                    args.id
1371                );
1372                return 2;
1373            }
1374        }
1375    };
1376
1377    let commits_out = Command::new("git")
1378        .args(["log", "--oneline", &format!("{base}..HEAD")])
1379        .current_dir(&wt)
1380        .output()
1381        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1382        .unwrap_or_default();
1383
1384    let files_out = Command::new("git")
1385        .args(["diff", "--stat", &format!("{base}..HEAD")])
1386        .current_dir(&wt)
1387        .output()
1388        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1389        .unwrap_or_default();
1390
1391    let tree_out = Command::new("git")
1392        .args(["status", "--short"])
1393        .current_dir(&wt)
1394        .output()
1395        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1396        .unwrap_or_default();
1397
1398    let is_research = crate::clean::is_research(&root, &args.id)
1399        || root
1400            .join(".wt")
1401            .join(format!("{}.report.md", args.id))
1402            .exists();
1403
1404    let diff_res: Option<Result<String, String>> = if !is_research {
1405        Some(
1406            Command::new("git")
1407                .args(["diff", &format!("{base}..HEAD")])
1408                .current_dir(&wt)
1409                .output()
1410                .map_err(|e| e.to_string())
1411                .and_then(|o| {
1412                    if o.status.success() {
1413                        Ok(String::from_utf8_lossy(&o.stdout).into_owned())
1414                    } else {
1415                        let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
1416                        if stderr.is_empty() {
1417                            Err(format!("exit {}", o.status))
1418                        } else {
1419                            Err(stderr)
1420                        }
1421                    }
1422                }),
1423        )
1424    } else if args.diff {
1425        Some(
1426            Command::new("git")
1427                .args(["diff", &format!("{base}..HEAD")])
1428                .current_dir(&wt)
1429                .output()
1430                .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
1431                .map_err(|e| e.to_string()),
1432        )
1433    } else {
1434        None
1435    };
1436
1437    let diff_out = diff_res
1438        .as_ref()
1439        .and_then(|r| r.as_ref().ok())
1440        .map(|s| s.trim().to_string())
1441        .unwrap_or_default();
1442
1443    let task_text: Option<String> = (|| {
1444        let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1445        let content = std::fs::read_to_string(&start_file).ok()?;
1446        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1447        let task_file = val.get("task_file")?.as_str()?;
1448        let p = Path::new(task_file);
1449        if let Ok(s) = std::fs::read_to_string(p) {
1450            return Some(s);
1451        }
1452        std::fs::read_to_string(root.join(p)).ok()
1453    })();
1454
1455    let changed_files: Vec<String> = Command::new("git")
1456        .args(["diff", "--name-only", &format!("{base}..HEAD")])
1457        .current_dir(&wt)
1458        .output()
1459        .ok()
1460        .filter(|o| o.status.success())
1461        .map(|o| {
1462            String::from_utf8_lossy(&o.stdout)
1463                .lines()
1464                .map(|l| l.trim().to_string())
1465                .filter(|l| !l.is_empty())
1466                .collect()
1467        })
1468        .unwrap_or_default();
1469
1470    let subjects: Vec<String> = Command::new("git")
1471        .args(["log", "--format=%s", &format!("{base}..HEAD")])
1472        .current_dir(&wt)
1473        .output()
1474        .ok()
1475        .filter(|o| o.status.success())
1476        .map(|o| {
1477            String::from_utf8_lossy(&o.stdout)
1478                .lines()
1479                .map(|l| l.trim().to_string())
1480                .filter(|l| !l.is_empty())
1481                .collect()
1482        })
1483        .unwrap_or_default();
1484
1485    let log_file = root.join(".wt").join(format!("{}.log", args.id));
1486    let (hcmds, reads, (refused_count, refused_paths)) =
1487        if let Ok(log_content) = std::fs::read_to_string(&log_file) {
1488            let hcmds = host_commands(&log_content);
1489            let home = std::env::var_os("HOME")
1490                .map(PathBuf::from)
1491                .unwrap_or_else(|| PathBuf::from("/"));
1492            let allowed = [root.clone(), wt.clone()];
1493            let reads = outside_reads(&log_content, &allowed, &home);
1494            let refused = refused_reads(&log_content);
1495            (hcmds, reads, refused)
1496        } else {
1497            (Vec::new(), Vec::new(), (0, Vec::new()))
1498        };
1499
1500    let report_file = root.join(".wt").join(format!("{}.report.json", args.id));
1501    let report_val = std::fs::read_to_string(&report_file)
1502        .ok()
1503        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
1504    let outcome = report_val
1505        .as_ref()
1506        .and_then(|v| v.get("outcome"))
1507        .and_then(|x| x.as_str());
1508    let quote_problems: Option<Vec<&str>> = report_val
1509        .as_ref()
1510        .and_then(|v| v.get("quote_problems"))
1511        .and_then(|x| x.as_array())
1512        .map(|arr| arr.iter().filter_map(|x| x.as_str()).collect());
1513    let read_loop = report_val
1514        .as_ref()
1515        .and_then(|v| v.get("read_loop"))
1516        .and_then(|x| x.as_bool())
1517        .unwrap_or(false);
1518    let gate_left_out: Vec<String> = report_val
1519        .as_ref()
1520        .and_then(|v| v.get("gate_left_out"))
1521        .and_then(|x| x.as_array())
1522        .map(|arr| {
1523            arr.iter()
1524                .filter_map(|x| x.as_str().map(String::from))
1525                .collect::<Vec<_>>()
1526        })
1527        .filter(|v| !v.is_empty())
1528        .or_else(|| {
1529            let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1530            let content = std::fs::read_to_string(&start_file).ok()?;
1531            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1532            let arr = val.get("gate_left_out")?.as_array()?;
1533            Some(
1534                arr.iter()
1535                    .filter_map(|item| {
1536                        let cmd = item.get("command")?.as_str()?;
1537                        let reason = item.get("reason")?.as_str()?;
1538                        Some(format!("{cmd} ({reason})"))
1539                    })
1540                    .collect(),
1541            )
1542        })
1543        .unwrap_or_default();
1544    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
1545        .as_ref()
1546        .and_then(|v| v.get("claim_check"))
1547        .and_then(|x| serde_json::from_value(x.clone()).ok());
1548    let claim_check_skipped: Option<String> = report_val
1549        .as_ref()
1550        .and_then(|v| v.get("claim_check_skipped"))
1551        .and_then(|x| x.as_str())
1552        .map(String::from);
1553
1554    let mut checks = crate::review_checks::build(
1555        task_text.as_deref(),
1556        &changed_files,
1557        &subjects,
1558        hcmds.len(),
1559        reads.len(),
1560        outcome,
1561    );
1562    if !is_research {
1563        if let Some(ref res) = diff_res {
1564            match res {
1565                Ok(diff) => {
1566                    let findings = crate::fallback_check::added_fallbacks(diff);
1567                    if let Some(flag) = crate::fallback_check::flag(&findings) {
1568                        checks.flags.push(flag);
1569                    }
1570                }
1571                Err(reason) => {
1572                    let first_line = reason.lines().next().unwrap_or(reason.as_str());
1573                    let msg = format!("fallback check not run: git diff failed: {first_line}");
1574                    let cut: String = msg.chars().take(200).collect();
1575                    checks.flags.push(cut);
1576                }
1577            }
1578        }
1579    }
1580    if let Some(ref problems) = quote_problems {
1581        if !problems.is_empty() {
1582            checks.flags.push(format!(
1583                "quote check failed ({} problem(s)): see == report",
1584                problems.len()
1585            ));
1586        }
1587    }
1588    if read_loop {
1589        checks.flags.push(
1590            "read loop: the run kept re-reading the same files without changing anything and was stopped"
1591                .to_string(),
1592        );
1593    }
1594    if !gate_left_out.is_empty() {
1595        checks
1596            .flags
1597            .push(format!("gate left out: {}", gate_left_out.join("; ")));
1598    }
1599    if let Some(ref cc) = claim_check {
1600        if !cc.contradicted.is_empty() {
1601            checks.flags.push(format!(
1602                "claim check: {} contradicted claims",
1603                cc.contradicted.len()
1604            ));
1605        }
1606    }
1607    if let Some(ref skipped) = claim_check_skipped {
1608        checks.flags.push(format!("claim check skipped: {skipped}"));
1609    }
1610    if refused_count > 0 {
1611        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
1612        checks.flags.push(format!(
1613            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
1614            first_3.join(", ")
1615        ));
1616    }
1617
1618    println!("== checks");
1619    if checks.flags.is_empty() {
1620        println!("nothing flagged");
1621    } else {
1622        for flag in &checks.flags {
1623            println!("! {flag}");
1624        }
1625    }
1626
1627    println!("== commits");
1628    if !commits_out.is_empty() {
1629        println!("{commits_out}");
1630    }
1631    println!("== files");
1632    if !files_out.is_empty() {
1633        println!("{files_out}");
1634    }
1635    println!("== tree");
1636    if tree_out.is_empty() {
1637        println!("(clean)");
1638    } else {
1639        println!("{tree_out}");
1640    }
1641    println!("== report");
1642    if let Some(ref v) = report_val {
1643        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1644            println!("outcome: {outcome}");
1645        }
1646        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1647            println!("turns: {turns}");
1648        }
1649        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1650            println!("cost_usd: {cost}");
1651        }
1652        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1653            println!("final_message: {msg}");
1654        }
1655        if let Some(ref problems) = quote_problems {
1656            if problems.is_empty() {
1657                println!("quote check: passed");
1658            } else {
1659                println!(
1660                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
1661                    problems.len()
1662                );
1663                for p in problems.iter().take(5) {
1664                    let cut: String = p.chars().take(200).collect();
1665                    println!("  {cut}");
1666                }
1667            }
1668        }
1669        if let Some(ref cc) = claim_check {
1670            println!(
1671                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
1672                cc.checked,
1673                cc.contradicted.len(),
1674                cc.not_enough_evidence,
1675                cc.parse_errors,
1676                cc.unchecked
1677            );
1678            for f in cc.contradicted.iter().take(5) {
1679                let cut: String = f.text.chars().take(200).collect();
1680                println!("  report.md:{}: {cut}", f.line);
1681                println!("    {}", f.reason);
1682            }
1683        }
1684        if let Some(ref skipped) = claim_check_skipped {
1685            println!("claim check skipped: {skipped}");
1686        }
1687    }
1688
1689    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1690    if research_report_file.exists() {
1691        println!("== research report");
1692        println!("{}", research_report_file.display());
1693        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1694            for line in content.lines().take(40) {
1695                println!("{line}");
1696            }
1697        }
1698    }
1699
1700    if !hcmds.is_empty() {
1701        println!("== host commands (may have changed things outside the worktree)");
1702        for cmd in hcmds {
1703            println!("{cmd}");
1704        }
1705    }
1706    if !reads.is_empty() {
1707        println!("== reads outside the repository");
1708        for cmd in reads {
1709            println!("{cmd}");
1710        }
1711    }
1712
1713    if args.diff {
1714        println!("== diff");
1715        if !diff_out.is_empty() {
1716            println!("{diff_out}");
1717        }
1718    }
1719
1720    if args.model_review {
1721        crate::model_review::run(&root, &args.id, &base, &wt);
1722    }
1723
1724    0
1725}
1726
1727const OUTSIDE_PATHS: &[&str] = &[
1728    "~/",
1729    "$HOME",
1730    "/Users/",
1731    "/home/",
1732    "/private/",
1733    "/var/",
1734    "/etc/",
1735    "/opt/",
1736    "/usr/",
1737];
1738
1739const CHANGE_WORDS: &[&str] = &[
1740    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1741];
1742
1743fn contains_word(cmd: &str, word: &str) -> bool {
1744    let mut start = 0;
1745    while let Some(pos) = cmd[start..].find(word) {
1746        let abs_pos = start + pos;
1747        let before_ok = if abs_pos == 0 {
1748            true
1749        } else {
1750            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1751            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1752        };
1753        let after_pos = abs_pos + word.len();
1754        let after_ok = if after_pos >= cmd.len() {
1755            true
1756        } else {
1757            let next = cmd[after_pos..].chars().next().unwrap();
1758            !next.is_alphanumeric() && next != '_' && next != '-'
1759        };
1760        if before_ok && after_ok {
1761            return true;
1762        }
1763        start = abs_pos + word.len();
1764    }
1765    false
1766}
1767
1768fn has_non_dev_null_redirect(cmd: &str) -> bool {
1769    let chars: Vec<char> = cmd.chars().collect();
1770    let mut i = 0;
1771    while i < chars.len() {
1772        if chars[i] == '>' {
1773            while i < chars.len() && chars[i] == '>' {
1774                i += 1;
1775            }
1776            if i < chars.len() && chars[i] == '|' {
1777                i += 1;
1778            }
1779            while i < chars.len() && chars[i].is_whitespace() {
1780                i += 1;
1781            }
1782            if i >= chars.len() {
1783                break;
1784            }
1785            if chars[i] == '&'
1786                && i + 1 < chars.len()
1787                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1788            {
1789                i += 1;
1790                continue;
1791            }
1792            let target_start = i;
1793            while i < chars.len()
1794                && !chars[i].is_whitespace()
1795                && chars[i] != ';'
1796                && chars[i] != '|'
1797                && chars[i] != '&'
1798                && chars[i] != ')'
1799            {
1800                i += 1;
1801            }
1802            let target: String = chars[target_start..i].iter().collect();
1803            let target = target.trim_matches(|c| c == '\'' || c == '"');
1804            if !target.is_empty() && target != "/dev/null" {
1805                return true;
1806            }
1807        } else {
1808            i += 1;
1809        }
1810    }
1811    false
1812}
1813
1814fn changes_something(cmd: &str) -> bool {
1815    for &word in CHANGE_WORDS {
1816        if contains_word(cmd, word) {
1817            return true;
1818        }
1819    }
1820    has_non_dev_null_redirect(cmd)
1821}
1822
1823fn is_host_command(cmd: &str) -> bool {
1824    if cmd.contains("git push")
1825        || cmd.contains("sudo ")
1826        || cmd.contains("cache clean")
1827        || cmd.contains("cache prune")
1828        || cmd.contains("brew ")
1829    {
1830        return true;
1831    }
1832
1833    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1834    names_outside && changes_something(cmd)
1835}
1836
1837pub fn host_commands(log: &str) -> Vec<String> {
1838    let cleaned = strip_ansi(log);
1839    let mut result = Vec::new();
1840    for line in cleaned.lines() {
1841        let trimmed = line.trim();
1842        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1843            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1844                let cmd = cmd.trim();
1845                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1846                    result.push(cmd.to_string());
1847                    if result.len() == 20 {
1848                        break;
1849                    }
1850                }
1851            }
1852        }
1853    }
1854    result
1855}
1856
1857const TERMINAL_READS: &[&str] = &[
1858    "herdr pane read",
1859    "tmux capture-pane",
1860    "screen -X hardcopy",
1861    "zellij action dump-screen",
1862    "wezterm cli get-text",
1863];
1864
1865const TOOL_CACHES: &[&str] = &[
1866    ".cargo",
1867    ".rustup",
1868    ".cache",
1869    ".npm",
1870    ".local",
1871    "Library/Caches",
1872    ".gradle",
1873    ".m2",
1874    "go",
1875];
1876
1877fn normalize_path(path: &Path) -> PathBuf {
1878    use std::path::Component;
1879    let mut out = PathBuf::new();
1880    for comp in path.components() {
1881        match comp {
1882            Component::ParentDir => {
1883                out.pop();
1884            }
1885            Component::CurDir => {}
1886            _ => out.push(comp),
1887        }
1888    }
1889    out
1890}
1891
1892fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1893    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1894        return true;
1895    }
1896
1897    for raw_word in cmd.split_whitespace() {
1898        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1899        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1900            Some(home.join(suffix))
1901        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1902            Some(home.join(suffix))
1903        } else if word.starts_with('/') {
1904            Some(PathBuf::from(word))
1905        } else {
1906            None
1907        };
1908
1909        if let Some(path) = raw_path {
1910            let norm_path = normalize_path(&path);
1911            if !norm_path.starts_with(home) {
1912                continue;
1913            }
1914            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
1915            if under_allowed {
1916                continue;
1917            }
1918            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
1919            if under_cache {
1920                continue;
1921            }
1922            return true;
1923        }
1924    }
1925
1926    false
1927}
1928
1929pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
1930    let host_cmds = host_commands(log);
1931    let norm_home = normalize_path(home);
1932    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
1933    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
1934        .iter()
1935        .map(|c| normalize_path(&norm_home.join(c)))
1936        .collect();
1937
1938    let cleaned = strip_ansi(log);
1939    let mut result = Vec::new();
1940    for line in cleaned.lines() {
1941        let trimmed = line.trim();
1942        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1943            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1944                let cmd = cmd.trim();
1945                if host_cmds.iter().any(|c| c == cmd) {
1946                    continue;
1947                }
1948                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
1949                    && !result.iter().any(|c| c == cmd)
1950                {
1951                    result.push(cmd.to_string());
1952                    if result.len() == 20 {
1953                        break;
1954                    }
1955                }
1956            }
1957        }
1958    }
1959    result
1960}
1961
1962fn strip_ansi(s: &str) -> String {
1963    let mut out = String::with_capacity(s.len());
1964    let mut chars = s.chars().peekable();
1965    while let Some(c) = chars.next() {
1966        if c == '\x1b' && chars.peek() == Some(&'[') {
1967            chars.next();
1968            while let Some(&next_c) = chars.peek() {
1969                chars.next();
1970                if ('\x40'..='\x7e').contains(&next_c) {
1971                    break;
1972                }
1973                if next_c == '\n' || next_c == '\x1b' {
1974                    out.push(next_c);
1975                    break;
1976                }
1977            }
1978            continue;
1979        }
1980        out.push(c);
1981    }
1982    out
1983}
1984
1985#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
1986pub struct LogProgress {
1987    pub turn: u32,
1988    pub last_tool: Option<String>,
1989    pub gate_attempts: u32,
1990    pub gate_passed: bool,
1991}
1992
1993pub fn parse_log(log: &str) -> LogProgress {
1994    let cleaned = strip_ansi(log);
1995    let mut turn: u32 = 0;
1996    let mut last_tool: Option<String> = None;
1997    let mut gate_attempts: u32 = 0;
1998    let mut gate_passed: bool = false;
1999
2000    for line in cleaned.lines() {
2001        if let Some(rest) = line.strip_prefix("[Turn ") {
2002            if let Some((n_str, _)) = rest.split_once(']') {
2003                if let Ok(n) = n_str.trim().parse::<u32>() {
2004                    turn = turn.max(n);
2005                }
2006            }
2007        }
2008
2009        if let Some(tool) = line.strip_prefix("● ") {
2010            let truncated = if tool.chars().count() > 200 {
2011                tool.chars().take(200).collect()
2012            } else {
2013                tool.to_string()
2014            };
2015            last_tool = Some(truncated);
2016        }
2017
2018        if line.starts_with("✓ Gate passed") {
2019            gate_attempts += 1;
2020            gate_passed = true;
2021        } else if line.starts_with("✗ Gate failed") {
2022            gate_attempts += 1;
2023            gate_passed = false;
2024        }
2025    }
2026
2027    LogProgress {
2028        turn,
2029        last_tool,
2030        gate_attempts,
2031        gate_passed,
2032    }
2033}
2034
2035#[derive(Debug, Serialize)]
2036pub struct StatusOutput {
2037    pub id: String,
2038    pub state: String,
2039    pub elapsed_s: u64,
2040    pub turn: u32,
2041    pub last_tool: Option<String>,
2042    pub gate_attempts: u32,
2043    pub gate_passed: bool,
2044    pub outcome: Option<String>,
2045    pub cost_usd: Option<f64>,
2046    pub final_message: Option<String>,
2047}
2048
2049pub fn run_status(id: &str, json: bool) -> i32 {
2050    let root = match crate::clean::find_repo_root() {
2051        Ok(r) => r,
2052        Err(e) => {
2053            eprintln!("error: {e}");
2054            return 2;
2055        }
2056    };
2057
2058    let start_path = root.join(".wt").join(format!("{id}.start.json"));
2059    if !start_path.exists() {
2060        eprintln!("no dispatch {id} here");
2061        return 2;
2062    }
2063
2064    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
2065        Ok(s) => match serde_json::from_str(&s) {
2066            Ok(v) => v,
2067            Err(e) => {
2068                eprintln!("error parsing {}: {e}", start_path.display());
2069                return 2;
2070            }
2071        },
2072        Err(e) => {
2073            eprintln!("error reading {}: {e}", start_path.display());
2074            return 2;
2075        }
2076    };
2077
2078    let pid = start_record
2079        .get("pid")
2080        .and_then(|v| v.as_i64())
2081        .map(|v| v as libc::pid_t);
2082    let started_at = start_record
2083        .get("started_at")
2084        .and_then(|v| v.as_u64())
2085        .unwrap_or(0);
2086
2087    let is_alive = if let Some(pid) = pid {
2088        if pid > 0 {
2089            let ret = unsafe { libc::kill(pid, 0) };
2090            if ret == 0 {
2091                true
2092            } else {
2093                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
2094            }
2095        } else {
2096            false
2097        }
2098    } else {
2099        false
2100    };
2101
2102    let report_path = root.join(".wt").join(format!("{id}.report.json"));
2103    let report_exists = report_path.exists();
2104
2105    let state = if report_exists {
2106        "finished"
2107    } else if is_alive {
2108        "running"
2109    } else {
2110        "dead"
2111    };
2112
2113    let now = std::time::SystemTime::now()
2114        .duration_since(std::time::UNIX_EPOCH)
2115        .map(|d| d.as_secs())
2116        .unwrap_or(0);
2117
2118    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
2119        if let Ok(content) = std::fs::read_to_string(&report_path) {
2120            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
2121                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
2122                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
2123                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
2124                    if s.chars().count() > 500 {
2125                        s.chars().take(500).collect()
2126                    } else {
2127                        s.to_string()
2128                    }
2129                });
2130                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
2131                (outcome, cost_usd, final_message, duration)
2132            } else {
2133                (None, None, None, None)
2134            }
2135        } else {
2136            (None, None, None, None)
2137        }
2138    } else {
2139        (None, None, None, None)
2140    };
2141
2142    let elapsed_s = if state == "finished" {
2143        report_duration
2144            .map(|d| d.round() as u64)
2145            .unwrap_or_else(|| now.saturating_sub(started_at))
2146    } else {
2147        now.saturating_sub(started_at)
2148    };
2149
2150    let log_path = root.join(".wt").join(format!("{id}.log"));
2151    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
2152    let progress = parse_log(&log_content);
2153
2154    if json {
2155        let status_obj = StatusOutput {
2156            id: id.to_string(),
2157            state: state.to_string(),
2158            elapsed_s,
2159            turn: progress.turn,
2160            last_tool: progress.last_tool,
2161            gate_attempts: progress.gate_attempts,
2162            gate_passed: progress.gate_passed,
2163            outcome,
2164            cost_usd,
2165            final_message,
2166        };
2167        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
2168        println!("{json_str}");
2169    } else {
2170        println!("id: {id}");
2171        println!("state: {state}");
2172        println!("elapsed_s: {elapsed_s}");
2173        println!("turn: {}", progress.turn);
2174        println!(
2175            "last_tool: {}",
2176            progress.last_tool.as_deref().unwrap_or("none")
2177        );
2178        println!("gate_attempts: {}", progress.gate_attempts);
2179        println!("gate_passed: {}", progress.gate_passed);
2180        if state == "finished" {
2181            if let Some(ref o) = outcome {
2182                println!("outcome: {o}");
2183            }
2184            if let Some(c) = cost_usd {
2185                println!("cost_usd: {c}");
2186            }
2187            if let Some(ref msg) = final_message {
2188                println!("final_message: {msg}");
2189            }
2190        }
2191    }
2192
2193    match state {
2194        "running" | "finished" => 0,
2195        _ => 1,
2196    }
2197}
2198
2199pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
2200    let readable_canon: Vec<PathBuf> = readable
2201        .iter()
2202        .filter_map(|r| std::fs::canonicalize(r).ok())
2203        .collect();
2204    let mut out = Vec::new();
2205    for raw in text.split(|c: char| {
2206        c.is_whitespace()
2207            || matches!(
2208                c,
2209                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
2210            )
2211    }) {
2212        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
2213        if !trimmed.starts_with('/')
2214            || trimmed.starts_with("//")
2215            || trimmed.len() <= 1
2216            || trimmed == "/dev/null"
2217        {
2218            continue;
2219        }
2220        let p = Path::new(trimmed);
2221        let Ok(canon) = std::fs::canonicalize(p) else {
2222            continue;
2223        };
2224        if readable_canon.iter().any(|r| canon.starts_with(r))
2225            || is_system_path(p)
2226            || is_system_path(&canon)
2227        {
2228            continue;
2229        }
2230        let pb = PathBuf::from(trimmed);
2231        if !out.contains(&pb) {
2232            out.push(pb);
2233        }
2234    }
2235    out
2236}
2237
2238/// A path no research task means as code to read: the filesystem root, a top-level directory,
2239/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
2240fn is_system_path(p: &Path) -> bool {
2241    const SYSTEM: &[&str] = &[
2242        "/usr",
2243        "/bin",
2244        "/sbin",
2245        "/etc",
2246        "/dev",
2247        "/opt",
2248        "/System",
2249        "/Library",
2250        "/Applications",
2251        "/nix",
2252        "/proc",
2253        "/sys",
2254    ];
2255    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
2256}
2257
2258pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
2259    let mut count = 0;
2260    let mut paths = Vec::new();
2261    for line in log_content.lines() {
2262        if !line.contains("path escapes the workspace") {
2263            continue;
2264        }
2265        count += 1;
2266        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
2267            let after = after.trim_start();
2268            let after = after.split("\x1b[").next().unwrap_or(after);
2269            let path = after
2270                .split(". This run can read")
2271                .next()
2272                .unwrap_or(after)
2273                .trim();
2274            if !path.is_empty() && !paths.iter().any(|p| p == path) {
2275                paths.push(path.to_string());
2276            }
2277        }
2278    }
2279    (count, paths)
2280}
2281
2282#[cfg(test)]
2283mod tests {
2284    use super::*;
2285
2286    #[test]
2287    fn outside_reads_excludes_commands_in_host_commands() {
2288        let home = Path::new("/Users/u");
2289        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2290        // rm -rf ~/repos/other is a host command (names outside and changes something)
2291        // cat ~/repos/other is not a host command (only reads)
2292        let log = "\
2293● bash rm -rf ~/repos/other/file.py -> exit 0
2294● bash cat ~/repos/other/file.py -> exit 0
2295";
2296        assert_eq!(
2297            host_commands(log),
2298            vec!["rm -rf ~/repos/other/file.py".to_string()]
2299        );
2300        assert_eq!(
2301            outside_reads(log, &allowed, home),
2302            vec!["cat ~/repos/other/file.py".to_string()]
2303        );
2304    }
2305
2306    #[test]
2307    fn outside_reads_all_terminal_patterns() {
2308        let home = Path::new("/Users/u");
2309        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2310        let log = "\
2311● bash herdr pane read p1 -> exit 0
2312● bash tmux capture-pane -t 1 -> exit 0
2313● bash screen -X hardcopy /tmp/screen.log -> exit 0
2314● bash zellij action dump-screen /tmp/dump -> exit 0
2315● bash wezterm cli get-text --pane-id 1 -> exit 0
2316";
2317        let reads = outside_reads(log, &allowed, home);
2318        assert_eq!(
2319            reads,
2320            vec![
2321                "herdr pane read p1",
2322                "tmux capture-pane -t 1",
2323                "screen -X hardcopy /tmp/screen.log",
2324                "zellij action dump-screen /tmp/dump",
2325                "wezterm cli get-text --pane-id 1",
2326            ]
2327        );
2328    }
2329
2330    #[test]
2331    fn outside_reads_all_tool_caches_ignored() {
2332        let home = Path::new("/Users/u");
2333        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2334        let log = "\
2335● bash ls ~/.cargo/bin -> exit 0
2336● bash ls ~/.rustup/toolchains -> exit 0
2337● bash ls ~/.cache/pip -> exit 0
2338● bash ls ~/.npm/_cacache -> exit 0
2339● bash ls ~/.local/share -> exit 0
2340● bash ls ~/Library/Caches/com.apple -> exit 0
2341● bash ls ~/.gradle/caches -> exit 0
2342● bash ls ~/.m2/repository -> exit 0
2343● bash ls ~/go/pkg -> exit 0
2344";
2345        assert!(outside_reads(log, &allowed, home).is_empty());
2346    }
2347
2348    #[test]
2349    fn outside_reads_trailing_punctuations_stripped() {
2350        let home = Path::new("/Users/u");
2351        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2352        let log = "\
2353● bash ls ~/secret: -> exit 0
2354● bash ls ~/secret, -> exit 0
2355● bash (ls ~/secret) -> exit 0
2356● bash bash -c 'ls ~/secret' -> exit 0
2357● bash bash -c \"ls ~/secret\" -> exit 0
2358";
2359        let reads = outside_reads(log, &allowed, home);
2360        // Deduplicated, so only one instance of the command or distinct commands:
2361        assert_eq!(reads.len(), 5);
2362    }
2363
2364    #[test]
2365    fn outside_reads_caps_at_20_and_deduplicates() {
2366        let home = Path::new("/Users/u");
2367        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2368        let mut log = String::new();
2369        for i in 0..30 {
2370            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
2371        }
2372        // Duplicate the first one
2373        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
2374        let reads = outside_reads(&log, &allowed, home);
2375        assert_eq!(reads.len(), 20);
2376        assert_eq!(reads[0], "cat ~/secret/0.txt");
2377        assert_eq!(reads[19], "cat ~/secret/19.txt");
2378    }
2379}