Skip to main content

blyte_cli/
dispatch.rs

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