Skip to main content

blyte_cli/
dispatch.rs

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