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