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