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