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    #[serde(skip_serializing_if = "Option::is_none")]
264    pub fix_round: Option<crate::fix_round::FixRoundSummary>,
265}
266
267struct ImplementerConfig<'a> {
268    current_exe: &'a Path,
269    worktree_dir: &'a Path,
270    root: &'a Path,
271    id: &'a str,
272    gate: &'a str,
273    env: &'a std::collections::BTreeMap<String, String>,
274    model: Option<&'a str>,
275    max_seconds: u64,
276    max_turns: u32,
277    max_cost: Option<f64>,
278    fold_budget: Option<usize>,
279    sandbox: &'a str,
280    network: &'a str,
281    config_allow_read: &'a [PathBuf],
282    cli_allow_read: &'a [PathBuf],
283    pass_env: &'a [String],
284    research: bool,
285    no_claim_check: bool,
286    left_out: &'a [(String, String)],
287}
288
289struct PassReport {
290    report_outcome: String,
291    error: Option<String>,
292    final_message: Option<String>,
293    turns: u32,
294    report_turns: Option<u64>,
295    gate_attempts: u32,
296    gate_failures: Vec<String>,
297    cost_usd: Option<f64>,
298    model: Option<String>,
299    seconds: u64,
300    sandbox: String,
301    base_check_passed: Option<bool>,
302    base_check_seconds: Option<f64>,
303}
304
305fn open_pass_log(log_path: &Path, append_header: Option<&str>) -> Result<std::fs::File, String> {
306    match append_header {
307        None => std::fs::File::create(log_path)
308            .map_err(|e| format!("error creating log file {}: {e}", log_path.display())),
309        Some(header) => {
310            use std::io::Write;
311            let needs_leading_nl = match std::fs::read(log_path) {
312                Ok(bytes) => !bytes.is_empty() && !bytes.ends_with(b"\n"),
313                Err(e) if e.kind() == std::io::ErrorKind::NotFound => false,
314                Err(e) => {
315                    return Err(format!(
316                        "error reading log file {}: {e}",
317                        log_path.display()
318                    ));
319                }
320            };
321            let mut f = std::fs::OpenOptions::new()
322                .create(true)
323                .append(true)
324                .open(log_path)
325                .map_err(|e| format!("error opening log file {}: {e}", log_path.display()))?;
326            if needs_leading_nl {
327                writeln!(f)
328                    .map_err(|e| format!("error writing log file {}: {e}", log_path.display()))?;
329            }
330            writeln!(f, "{header}")
331                .map_err(|e| format!("error writing log file {}: {e}", log_path.display()))?;
332            Ok(f)
333        }
334    }
335}
336
337fn run_implementer_pass<F>(
338    cfg: &ImplementerConfig<'_>,
339    log_path: &Path,
340    append_log_header: Option<&str>,
341    report_path: &Path,
342    task_prompt: &str,
343    base_check_dir: Option<&Path>,
344    on_spawn: F,
345) -> Result<(), String>
346where
347    F: FnOnce(u32),
348{
349    if report_path.exists() {
350        std::fs::remove_file(report_path)
351            .map_err(|e| format!("error removing {}: {e}", report_path.display()))?;
352    }
353    let log_file = open_pass_log(log_path, append_log_header)?;
354    let log_file_err = log_file
355        .try_clone()
356        .map_err(|e| format!("error cloning log file handle: {e}"))?;
357
358    let mut cmd = Command::new(cfg.current_exe);
359    cmd.current_dir(cfg.worktree_dir);
360    cmd.stdout(log_file);
361    cmd.stderr(log_file_err);
362
363    for (k, v) in cfg.env {
364        cmd.env(k, v);
365    }
366    cmd.env("BLYTE_DISPATCH_ID", cfg.id);
367    cmd.env_remove(blyte_agent::shell::MODEL_SHELL_ENV);
368
369    cmd.arg("--gate").arg(cfg.gate);
370    cmd.arg("--rollback=false");
371    cmd.arg("--max-seconds").arg(cfg.max_seconds.to_string());
372    cmd.arg("--max-turns").arg(cfg.max_turns.to_string());
373    cmd.arg("--report").arg(report_path);
374
375    if let Some(m) = cfg.model {
376        cmd.arg("--model").arg(m);
377    }
378    if let Some(c) = cfg.max_cost {
379        cmd.arg("--max-cost").arg(c.to_string());
380    }
381    if let Some(fb) = cfg.fold_budget {
382        cmd.arg("--fold-budget").arg(fb.to_string());
383    }
384    cmd.arg("--sandbox").arg(cfg.sandbox);
385    cmd.arg("--network").arg(cfg.network);
386    for r in cfg.config_allow_read {
387        cmd.arg("--allow-read").arg(r);
388    }
389    for r in cfg.cli_allow_read {
390        cmd.arg("--allow-read").arg(r);
391    }
392    for p in cfg.pass_env {
393        cmd.arg("--pass-env").arg(p);
394    }
395    for r in cfg.config_allow_read.iter().chain(cfg.cli_allow_read) {
396        cmd.arg("--read-root").arg(r);
397    }
398    if cfg.research {
399        cmd.arg("--read-root").arg(cfg.root);
400        cmd.arg("--no-gate-slot");
401        cmd.arg("--research");
402        if !cfg.no_claim_check {
403            cmd.arg("--claim-check");
404        }
405    } else if let Some(base_wt_dir) = base_check_dir {
406        cmd.arg("--base-check");
407        cmd.arg("--base-check-dir").arg(base_wt_dir);
408    }
409
410    cmd.arg("--");
411    cmd.arg(task_prompt);
412
413    let mut child = cmd
414        .spawn()
415        .map_err(|e| format!("error spawning child process: {e}"))?;
416    let pid = child.id();
417    on_spawn(pid);
418    if let Err(msg) = crate::keep_awake::hold(pid) {
419        eprintln!("blyte: warning: {msg}; the machine may sleep during this run");
420    }
421
422    let _ = child.wait();
423
424    if !cfg.left_out.is_empty() {
425        if let Ok(report_str) = std::fs::read_to_string(report_path) {
426            if let Ok(mut report_val) = serde_json::from_str::<serde_json::Value>(&report_str) {
427                let formatted: Vec<String> = cfg
428                    .left_out
429                    .iter()
430                    .map(|(cmd_name, reason)| format!("{cmd_name} ({reason})"))
431                    .collect();
432                report_val["gate_left_out"] = serde_json::json!(formatted);
433                if let Ok(updated) = serde_json::to_string_pretty(&report_val) {
434                    let _ = std::fs::write(report_path, updated + "\n");
435                }
436            }
437        }
438    }
439
440    Ok(())
441}
442
443fn parse_pass_report(report_path: &Path, default_sandbox: &str) -> Result<PassReport, String> {
444    let raw = std::fs::read_to_string(report_path)
445        .map_err(|e| format!("missing report {}: {e}", report_path.display()))?;
446    let rec: serde_json::Value = serde_json::from_str(&raw)
447        .map_err(|e| format!("unreadable report JSON {}: {e}", report_path.display()))?;
448
449    let gate_failures = match rec.get("gate_failures").and_then(|v| v.as_array()) {
450        Some(arr) => arr
451            .iter()
452            .filter_map(|v| v.as_str())
453            .map(|s| {
454                if s.chars().count() > 1000 {
455                    s.chars().take(1000).collect()
456                } else {
457                    s.to_string()
458                }
459            })
460            .collect(),
461        None => Vec::new(),
462    };
463    let raw_turns = rec.get("turns").and_then(|v| v.as_u64());
464    let rec_outcome = rec
465        .get("outcome")
466        .and_then(|v| v.as_str())
467        .ok_or_else(|| format!("missing \"outcome\" in {}", report_path.display()))?;
468    let turns = match raw_turns {
469        Some(t) => t as u32,
470        None => 0,
471    };
472    let gate_attempts = match rec.get("gate_attempts").and_then(|v| v.as_u64()) {
473        Some(n) => n as u32,
474        None => 0,
475    };
476    let seconds = match rec.get("duration_seconds").and_then(|v| v.as_f64()) {
477        Some(d) => d.round() as u64,
478        None => 0,
479    };
480    let sandbox = match rec.get("sandbox").and_then(|v| v.as_str()) {
481        Some(s) => s.to_string(),
482        None => default_sandbox.to_string(),
483    };
484
485    Ok(PassReport {
486        report_outcome: rec_outcome.to_string(),
487        error: summary_error(rec_outcome, rec.get("error").and_then(|v| v.as_str())),
488        final_message: rec
489            .get("final_message")
490            .and_then(|v| v.as_str())
491            .map(String::from),
492        turns,
493        report_turns: raw_turns,
494        gate_attempts,
495        gate_failures,
496        cost_usd: rec.get("cost_usd").and_then(|v| v.as_f64()),
497        model: rec
498            .get("model_id")
499            .and_then(|v| v.as_str())
500            .map(String::from),
501        seconds,
502        sandbox,
503        base_check_passed: rec.get("base_check_passed").and_then(|v| v.as_bool()),
504        base_check_seconds: rec.get("base_check_seconds").and_then(|v| v.as_f64()),
505    })
506}
507
508fn pass_report_from_error(err_msg: String, default_sandbox: &str) -> PassReport {
509    PassReport {
510        report_outcome: "error".to_string(),
511        error: Some(err_msg),
512        final_message: None,
513        turns: 0,
514        report_turns: None,
515        gate_attempts: 0,
516        gate_failures: Vec::new(),
517        cost_usd: None,
518        model: None,
519        seconds: 0,
520        sandbox: default_sandbox.to_string(),
521        base_check_passed: None,
522        base_check_seconds: None,
523    }
524}
525
526fn git_head_sha(worktree_dir: &Path) -> Result<String, String> {
527    let wt = worktree_dir
528        .to_str()
529        .ok_or_else(|| format!("non-UTF-8 worktree path {}", worktree_dir.display()))?;
530    let out = Command::new("git")
531        .args(["-C", wt, "rev-parse", "HEAD"])
532        .output()
533        .map_err(|e| format!("failed to execute git rev-parse HEAD in {wt}: {e}"))?;
534    if !out.status.success() {
535        return Err(format!(
536            "git rev-parse HEAD failed in {wt}: {}",
537            String::from_utf8_lossy(&out.stderr).trim()
538        ));
539    }
540    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
541}
542
543fn git_reset_hard(worktree_dir: &Path, sha: &str) -> Result<(), String> {
544    let wt = worktree_dir
545        .to_str()
546        .ok_or_else(|| format!("non-UTF-8 worktree path {}", worktree_dir.display()))?;
547    let out = Command::new("git")
548        .args(["-C", wt, "reset", "--hard", sha])
549        .output()
550        .map_err(|e| format!("failed to run git reset --hard {sha} in {wt}: {e}"))?;
551    if !out.status.success() {
552        return Err(format!(
553            "git reset --hard {sha} failed in {wt}: {}",
554            String::from_utf8_lossy(&out.stderr).trim()
555        ));
556    }
557    Ok(())
558}
559
560fn git_commits_since(worktree_dir: &Path, base_sha: &str) -> Vec<CommitRecord> {
561    let log_out = Command::new("git")
562        .args([
563            "-C",
564            worktree_dir.to_str().unwrap(),
565            "log",
566            "--reverse",
567            "--format=%h%x09%s",
568            &format!("{base_sha}..HEAD"),
569        ])
570        .output();
571
572    let mut commits = Vec::new();
573    if let Ok(o) = log_out {
574        let text = String::from_utf8_lossy(&o.stdout);
575        for line in text.lines() {
576            let line = line.trim();
577            if line.is_empty() {
578                continue;
579            }
580            if let Some((sha, subject)) = line.split_once('\t') {
581                commits.push(CommitRecord {
582                    sha: sha.to_string(),
583                    subject: subject.to_string(),
584                });
585            }
586        }
587    }
588    commits
589}
590
591fn git_changed_files_since(worktree_dir: &Path, base_sha: &str) -> Vec<String> {
592    let diff_out = Command::new("git")
593        .args([
594            "-C",
595            worktree_dir.to_str().unwrap(),
596            "diff",
597            "--name-only",
598            &format!("{base_sha}..HEAD"),
599        ])
600        .output();
601
602    let mut changed_files = Vec::new();
603    if let Ok(o) = diff_out {
604        let text = String::from_utf8_lossy(&o.stdout);
605        for line in text.lines() {
606            let line = line.trim();
607            if !line.is_empty() {
608                changed_files.push(line.to_string());
609            }
610        }
611    }
612    changed_files
613}
614
615fn update_start_record_pid(start_path: &Path, pid: u32) {
616    let raw = match std::fs::read_to_string(start_path) {
617        Ok(s) => s,
618        Err(e) => {
619            eprintln!("warning: cannot read {}: {e}", start_path.display());
620            return;
621        }
622    };
623    let mut val = match serde_json::from_str::<serde_json::Value>(&raw) {
624        Ok(v) => v,
625        Err(e) => {
626            eprintln!("warning: cannot parse {}: {e}", start_path.display());
627            return;
628        }
629    };
630    val["pid"] = serde_json::json!(pid);
631    if let Err(e) = write_start_record(start_path, &val) {
632        eprintln!("warning: cannot update {}: {e}", start_path.display());
633    }
634}
635
636fn read_start_base_sha(start_path: &Path) -> Result<String, String> {
637    let raw = std::fs::read_to_string(start_path)
638        .map_err(|e| format!("cannot read {}: {e}", start_path.display()))?;
639    let val: serde_json::Value = serde_json::from_str(&raw)
640        .map_err(|e| format!("cannot parse {}: {e}", start_path.display()))?;
641    val.get("base_sha")
642        .and_then(|v| v.as_str())
643        .map(str::to_string)
644        .ok_or_else(|| format!("missing \"base_sha\" in {}", start_path.display()))
645}
646
647fn read_start_task_content(root: &Path, start_path: &Path) -> Result<String, String> {
648    let raw = std::fs::read_to_string(start_path)
649        .map_err(|e| format!("cannot read {}: {e}", start_path.display()))?;
650    let val: serde_json::Value = serde_json::from_str(&raw)
651        .map_err(|e| format!("cannot parse {}: {e}", start_path.display()))?;
652    let task_file_str = val
653        .get("task_file")
654        .and_then(|v| v.as_str())
655        .ok_or_else(|| format!("missing \"task_file\" in {}", start_path.display()))?;
656    let task_path = Path::new(task_file_str);
657    let resolved = if task_path.is_absolute() {
658        task_path.to_path_buf()
659    } else {
660        root.join(task_path)
661    };
662    std::fs::read_to_string(&resolved)
663        .map_err(|e| format!("cannot read task file {}: {e}", resolved.display()))
664}
665
666#[allow(clippy::too_many_arguments)]
667fn build_error_summary(
668    id: &str,
669    worktree_dir: &Path,
670    branch: String,
671    err_msg: String,
672    sandbox: String,
673    log_path: &Path,
674    report_path: &Path,
675    gate_source: &'static str,
676    warnings: Vec<String>,
677) -> DispatchSummary {
678    let outcome = "error";
679    DispatchSummary {
680        id: id.to_string(),
681        worktree: worktree_dir.display().to_string(),
682        branch,
683        outcome,
684        exit: exit_code(outcome),
685        error: Some(err_msg),
686        commits: Vec::new(),
687        changed_files: Vec::new(),
688        final_message: None,
689        turns: 0,
690        gate_attempts: 0,
691        gate_failures: Vec::new(),
692        cost_usd: None,
693        model: None,
694        seconds: 0,
695        sandbox,
696        log: log_path.display().to_string(),
697        report: report_path.display().to_string(),
698        gate_source,
699        research_report: None,
700        base_check_seconds: None,
701        warnings,
702        fix_round: None,
703    }
704}
705
706#[allow(clippy::too_many_arguments)]
707fn execute_fix_round(
708    root: &Path,
709    start_path: &Path,
710    impl_cfg: &ImplementerConfig<'_>,
711    log_path: &Path,
712    fix_report_path: &Path,
713    fixround_path: &Path,
714    passed_key: Option<&str>,
715    original_task: &str,
716    pre_round_sha: String,
717    fallbacks_sent: Vec<crate::fix_round::ConfirmedFallback>,
718    round_started_at: u64,
719    warnings: &mut Vec<String>,
720) -> Result<(crate::fix_round::FixRoundSummary, PassReport), String> {
721    let round_task = crate::fix_round::task_text(original_task, &fallbacks_sent);
722    let mut round_prompt = wrap_task(&round_task);
723    if let Some(qs) = quick_steps(impl_cfg.gate) {
724        round_prompt.push_str("\n\n");
725        round_prompt.push_str(&qs);
726    }
727
728    if fix_report_path.exists() {
729        std::fs::remove_file(fix_report_path).map_err(|e| {
730            format!(
731                "cannot remove stale fix round report {}: {e}",
732                fix_report_path.display()
733            )
734        })?;
735    }
736
737    run_implementer_pass(
738        impl_cfg,
739        log_path,
740        Some("== fix round"),
741        fix_report_path,
742        &round_prompt,
743        None,
744        |pid| update_start_record_pid(start_path, pid),
745    )?;
746
747    let round_report = match parse_pass_report(fix_report_path, impl_cfg.sandbox) {
748        Ok(r) => r,
749        Err(err_msg) => pass_report_from_error(err_msg, impl_cfg.sandbox),
750    };
751    let round_commits = git_commits_since(impl_cfg.worktree_dir, &pre_round_sha);
752
753    let (kept, round_outcome, done_commits, fallbacks_left) =
754        if round_report.report_outcome == "verified" && !round_commits.is_empty() {
755            let second_review = match crate::queue_actions::evaluate_verified_run(root, impl_cfg.id)
756            {
757                Ok(mr) => mr,
758                Err(err) => {
759                    eprintln!(
760                        "warning: post-dispatch review check failed for {}: {err}",
761                        impl_cfg.id
762                    );
763                    None
764                }
765            };
766            let round_warnings = record_passed_after_run(
767                root,
768                impl_cfg.worktree_dir,
769                false,
770                BaseCheckDecision::Disabled,
771                None,
772                passed_key,
773                "verified",
774                None,
775            );
776            for w in &round_warnings {
777                eprintln!("warning: {w}");
778            }
779            warnings.extend(round_warnings);
780            let left = crate::fix_round::fallbacks_left(second_review.as_ref());
781            let commit_shas = round_commits.into_iter().map(|c| c.sha).collect();
782            (true, "verified".to_string(), commit_shas, left)
783        } else {
784            let round_outcome = if round_report.report_outcome == "verified" {
785                "no_change".to_string()
786            } else {
787                match round_report.report_outcome.as_str() {
788                    "gate_failed" => "gate_failed".to_string(),
789                    "budget_exhausted" => "budget_exhausted".to_string(),
790                    "blocked" => "blocked".to_string(),
791                    _ => "error".to_string(),
792                }
793            };
794            git_reset_hard(impl_cfg.worktree_dir, &pre_round_sha)?;
795            let flag = crate::fix_round::failure_flag(&round_outcome);
796            crate::fix_round::append_check_flag(root, impl_cfg.id, &flag)?;
797            (false, round_outcome, Vec::new(), Some(fallbacks_sent.len()))
798        };
799
800    let fix_summary = crate::fix_round::FixRoundSummary {
801        outcome: round_outcome,
802        turns: round_report.turns,
803        cost_usd: round_report.cost_usd,
804        seconds: round_report.seconds,
805        commits: done_commits,
806        fallbacks_left,
807        kept,
808    };
809    let done_record = crate::fix_round::FixRoundRecord::Done {
810        pre_round_sha: Some(pre_round_sha),
811        fallbacks_sent,
812        started_at: Some(round_started_at),
813        summary: fix_summary.clone(),
814    };
815    crate::fix_round::write_record(fixround_path, &done_record)?;
816    Ok((fix_summary, round_report))
817}
818
819struct BaseWorktreeGuard {
820    root: PathBuf,
821    dir: PathBuf,
822}
823
824impl BaseWorktreeGuard {
825    fn create(root: &Path, dir: PathBuf, base_sha: &str) -> Result<Self, String> {
826        if dir.exists() {
827            let _ = Command::new("git")
828                .args([
829                    "-C",
830                    root.to_str().unwrap_or("."),
831                    "worktree",
832                    "remove",
833                    "--force",
834                ])
835                .arg(&dir)
836                .output();
837            if dir.exists() {
838                let _ = std::fs::remove_dir_all(&dir);
839            }
840            let _ = Command::new("git")
841                .args(["-C", root.to_str().unwrap_or("."), "worktree", "prune"])
842                .output();
843        }
844        let out = Command::new("git")
845            .args([
846                "-C",
847                root.to_str().unwrap_or("."),
848                "worktree",
849                "add",
850                "--detach",
851            ])
852            .arg(&dir)
853            .arg(base_sha)
854            .output()
855            .map_err(|e| format!("failed to run git worktree add --detach: {e}"))?;
856        if !out.status.success() {
857            return Err(format!(
858                "git worktree add --detach failed: {}",
859                String::from_utf8_lossy(&out.stderr).trim()
860            ));
861        }
862        Ok(Self {
863            root: root.to_path_buf(),
864            dir,
865        })
866    }
867}
868
869impl Drop for BaseWorktreeGuard {
870    fn drop(&mut self) {
871        let _ = Command::new("git")
872            .args([
873                "-C",
874                self.root.to_str().unwrap_or("."),
875                "worktree",
876                "remove",
877                "--force",
878            ])
879            .arg(&self.dir)
880            .output();
881    }
882}
883
884fn finish_summary(summary: &DispatchSummary, wt_parent: &Path) -> i32 {
885    let _ = std::fs::create_dir_all(wt_parent);
886    let json_str = serde_json::to_string_pretty(summary).unwrap();
887    let summary_path = wt_parent.join(format!("{}.json", summary.id));
888    let _ = std::fs::write(&summary_path, format!("{json_str}\n"));
889    println!("{json_str}");
890    summary.exit
891}
892
893pub fn branch_exists_message(root: &Path, branch: &str, id: &str) -> String {
894    if crate::clean::is_branch_merged(root, branch) {
895        format!(
896            "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."
897        )
898    } else {
899        format!(
900            "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."
901        )
902    }
903}
904
905/// Source-state block for the research root and each read root, skipping duplicates.
906fn research_source_block(
907    root: &Path,
908    config_allow_read: &[PathBuf],
909    allow_read: &[PathBuf],
910) -> String {
911    let mut roots: Vec<PathBuf> = vec![root.to_path_buf()];
912    for r in config_allow_read.iter().chain(allow_read) {
913        if !roots.contains(r) {
914            roots.push(r.clone());
915        }
916    }
917    let sources: Vec<(PathBuf, crate::provenance::SourceState)> = roots
918        .into_iter()
919        .map(|p| {
920            let state = crate::provenance::source_state(&p);
921            (p, state)
922        })
923        .collect();
924    crate::provenance::render(&sources)
925}
926
927/// Appends the source-state block to a copied report. Failure is reported, not fatal.
928fn append_source_state(path: &Path, block: &str) {
929    use std::io::Write;
930    let result = std::fs::OpenOptions::new()
931        .append(true)
932        .open(path)
933        .and_then(|mut f| f.write_all(format!("\n\n{block}").as_bytes()));
934    if let Err(e) = result {
935        eprintln!(
936            "error: could not add the source state to {}: {e}",
937            path.display()
938        );
939    }
940}
941
942pub fn validate_run_id(id: &str) -> Result<(), String> {
943    if id.is_empty() {
944        return Err("invalid run id: must not be empty".to_string());
945    }
946    if id.len() > 128 {
947        return Err(format!(
948            "invalid run id {:?}: must be at most 128 characters",
949            id
950        ));
951    }
952    if id.starts_with('.')
953        || id.starts_with('-')
954        || id.ends_with('.')
955        || id.contains("..")
956        || id.ends_with(".lock")
957        || !id
958            .bytes()
959            .all(|b| b.is_ascii_alphanumeric() || matches!(b, b'.' | b'_' | b'-'))
960    {
961        return Err(format!(
962            "invalid run id {:?}: only ASCII letters, digits, '.', '-' and '_' are allowed (no leading '.' or '-', no '..')",
963            id
964        ));
965    }
966    Ok(())
967}
968
969pub fn resolve_base_commit(start_dir: &Path, base: &str) -> Result<String, String> {
970    let out = Command::new("git")
971        .args(["rev-parse", "--verify", &format!("{base}^{{commit}}")])
972        .current_dir(start_dir)
973        .output();
974    match out {
975        Ok(o) if o.status.success() => Ok(String::from_utf8_lossy(&o.stdout).trim().to_string()),
976        _ => Err(format!("base {base} is not a commit")),
977    }
978}
979
980pub fn validate_request_id(id: &str) -> Result<(), String> {
981    if id.is_empty() {
982        return Err("invalid --request value: must not be empty".to_string());
983    }
984    if id.len() > 64 {
985        return Err(format!(
986            "invalid --request value {:?}: must be at most 64 characters",
987            id
988        ));
989    }
990    if !id
991        .chars()
992        .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
993    {
994        return Err(format!(
995            "invalid --request value {:?}: only ASCII letters, digits, '-' and '_' are allowed",
996            id
997        ));
998    }
999    Ok(())
1000}
1001
1002pub fn run_dispatch(args: &DispatchArgs) -> i32 {
1003    if let Err(e) = validate_run_id(&args.id) {
1004        eprintln!("error: {e}");
1005        return 2;
1006    }
1007    if let Some(ref req) = args.request {
1008        if let Err(e) = validate_request_id(req) {
1009            eprintln!("error: {e}");
1010            return 2;
1011        }
1012    }
1013    if let Ok(home) = crate::skill::home_dir() {
1014        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
1015            eprintln!(
1016                "blyte: added context rules to {} (they apply from the next Claude session)",
1017                path.display()
1018            );
1019        }
1020    }
1021
1022    // 1. Root repository discovery and worktree preparation
1023    let out = Command::new("git")
1024        .args(["rev-parse", "--show-toplevel"])
1025        .output();
1026    let Ok(out) = out else {
1027        eprintln!("error: git not found");
1028        return 2;
1029    };
1030    if !out.status.success() {
1031        eprintln!("error: not a git repository");
1032        return 2;
1033    }
1034    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1035    let root = match crate::clean::find_repo_root() {
1036        Ok(r) => r,
1037        Err(e) => {
1038            eprintln!("error: {e}");
1039            return 2;
1040        }
1041    };
1042    crate::registry::register(&root);
1043
1044    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
1045        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
1046        Ok(None) => (None, false),
1047        Err(e) => {
1048            eprintln!("{e}");
1049            return 2;
1050        }
1051    };
1052    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
1053    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
1054        Ok(m) => m,
1055        Err(e) => {
1056            eprintln!("error: {e}");
1057            return 2;
1058        }
1059    };
1060
1061    let mut left_out: Vec<(String, String)> = Vec::new();
1062    let (gate, gate_source) = if args.research {
1063        ("test -s report.md".to_string(), "research")
1064    } else if let Some(ref g) = args.gate {
1065        (g.clone(), "flag")
1066    } else if let Some(ref g) = dispatch_cfg.gate {
1067        let toml_path = if from_main {
1068            root.join("blyte.toml")
1069        } else {
1070            start_dir.join("blyte.toml")
1071        };
1072        let toml_content = std::fs::read_to_string(&toml_path).unwrap_or_default();
1073        left_out = crate::gate_drift::left_out_steps(&toml_content);
1074        if g.trim().is_empty() {
1075            eprintln!(
1076                "error: the gate in blyte.toml is empty; every step was left out. Fix the steps blyte init named, or pass --gate."
1077            );
1078            for (cmd, reason) in &left_out {
1079                eprintln!("  {cmd}: {reason}");
1080            }
1081            return 2;
1082        }
1083        let missing = crate::gate_drift::missing_ci_steps(&root, g, &toml_content);
1084        if let Some(warning) = crate::gate_drift::format_gate_drift_warning(&missing) {
1085            eprintln!("{warning}");
1086        }
1087        if !left_out.is_empty() {
1088            let formatted: Vec<String> = left_out
1089                .iter()
1090                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
1091                .collect();
1092            eprintln!(
1093                "blyte: the gate is partial; left out: {}",
1094                formatted.join("; ")
1095            );
1096        }
1097        let source = if from_main {
1098            "blyte.toml (main checkout)"
1099        } else {
1100            "blyte.toml"
1101        };
1102        (g.clone(), source)
1103    } else {
1104        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
1105        return 2;
1106    };
1107
1108    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
1109    let (max_seconds, max_turns) = if args.research {
1110        (
1111            args.max_seconds.unwrap_or(1800),
1112            args.max_turns.unwrap_or(300),
1113        )
1114    } else {
1115        (
1116            args.max_seconds
1117                .or(dispatch_cfg.max_seconds)
1118                .unwrap_or(3600),
1119            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
1120        )
1121    };
1122    let max_cost = args.max_cost_usd.or(dispatch_cfg.max_cost);
1123    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
1124    let network = args
1125        .network
1126        .as_deref()
1127        .or(dispatch_cfg.network.as_deref())
1128        .unwrap_or("on");
1129
1130    let wt_parent = root.join(".wt");
1131    let worktree_dir = wt_parent.join(&args.id);
1132    let branch = format!("wip/{}", args.id);
1133    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
1134    let summary_path = wt_parent.join(format!("{}.json", args.id));
1135    let fixround_path = crate::fix_round::record_path(&wt_parent, &args.id);
1136
1137    let existing_fixround = if args.research {
1138        None
1139    } else {
1140        match crate::fix_round::load_record(&fixround_path) {
1141            Ok(rec) => rec,
1142            Err(e) => {
1143                eprintln!("error: {e}");
1144                return 2;
1145            }
1146        }
1147    };
1148
1149    let resuming_fix_round = !args.research
1150        && !summary_path.exists()
1151        && matches!(
1152            existing_fixround,
1153            Some(crate::fix_round::FixRoundRecord::Started { .. })
1154        );
1155
1156    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
1157        let content = match std::fs::read_to_string(tf) {
1158            Ok(s) => s,
1159            Err(e) => {
1160                eprintln!("error reading task file {}: {e}", tf.display());
1161                return 2;
1162            }
1163        };
1164        (content, Some(tf.display().to_string()))
1165    } else {
1166        match (&args.plan, &args.plan_task) {
1167            (Some(plan_path), Some(plan_task)) => {
1168                let plan_str = match std::fs::read_to_string(plan_path) {
1169                    Ok(s) => s,
1170                    Err(e) => {
1171                        eprintln!("error reading plan {plan_path}: {e}");
1172                        return 2;
1173                    }
1174                };
1175                let section = match crate::plan_section::extract(&plan_str, plan_task) {
1176                    Some(sec) => sec,
1177                    None => {
1178                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
1179                        if let Some(hint) =
1180                            crate::plan_section::explain_missing(&plan_str, plan_task)
1181                        {
1182                            eprintln!("  {hint}");
1183                        }
1184                        return 2;
1185                    }
1186                };
1187                let content = format!("From the plan {plan_path}:\n\n{section}");
1188                (content, None)
1189            }
1190            _ if resuming_fix_round => {
1191                let start_path = wt_parent.join(format!("{}.start.json", args.id));
1192                match read_start_task_content(&root, &start_path) {
1193                    Ok(content) => (content, None),
1194                    Err(e) => {
1195                        eprintln!("error: {e}");
1196                        return 2;
1197                    }
1198                }
1199            }
1200            _ => {
1201                eprintln!("error: give a task file, or --plan with --plan-task");
1202                if args.research {
1203                    eprintln!(
1204                        "A research question needs these sections:\n\n{}",
1205                        crate::research_brief::TEMPLATE
1206                    );
1207                }
1208                return 2;
1209            }
1210        }
1211    };
1212
1213    let brief_missing = args
1214        .research
1215        .then(|| crate::research_brief::missing_sections(&task_content));
1216    if let Some(ref missing) = brief_missing {
1217        if !args.no_brief_check {
1218            if !missing.is_empty() {
1219                eprintln!(
1220                    "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.",
1221                    missing.join(", "),
1222                    args.id
1223                );
1224            }
1225            let unverified = crate::research_brief::unverified_inputs(&task_content, &root);
1226            if !unverified.is_empty() {
1227                let paths: Vec<String> =
1228                    unverified.iter().map(|p| p.display().to_string()).collect();
1229                eprintln!(
1230                    "blyte: the question names a report that did not pass blyte's checks: {}. Use a verified report, or --no-brief-check to start anyway.",
1231                    paths.join(", ")
1232                );
1233                return 2;
1234            }
1235        }
1236    }
1237
1238    let home = std::env::var_os("HOME").map(PathBuf::from);
1239    let main_checkout = root.clone();
1240    let config_allow_read = match crate::config::expand_allow_read(
1241        &dispatch_cfg.allow_read,
1242        home.as_deref(),
1243        &main_checkout,
1244    ) {
1245        Ok(paths) => paths,
1246        Err(e) => {
1247            eprintln!("{e}");
1248            return 2;
1249        }
1250    };
1251
1252    if !args.no_path_check {
1253        let mut readable = vec![start_dir.clone(), root.clone()];
1254        readable.extend(config_allow_read.iter().cloned());
1255        readable.extend(args.allow_read.iter().cloned());
1256        let bad = unreadable_paths(&task_content, &readable);
1257        if !bad.is_empty() {
1258            let shown: Vec<String> = bad
1259                .iter()
1260                .take(5)
1261                .map(|p| p.display().to_string())
1262                .collect();
1263            eprintln!(
1264                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
1265                shown.join(", ")
1266            );
1267            if args.research {
1268                return 2;
1269            }
1270        }
1271    }
1272
1273    let task_file_recorded =
1274        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
1275
1276    let mut replaced_earlier_run = false;
1277    if !args.research {
1278        let start_path = wt_parent.join(format!("{}.start.json", args.id));
1279        if start_path.exists() {
1280            let start_str = match std::fs::read_to_string(&start_path) {
1281                Ok(s) => s,
1282                Err(e) => {
1283                    eprintln!("error reading {}: {e}", start_path.display());
1284                    return 2;
1285                }
1286            };
1287            let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
1288                Ok(v) => v,
1289                Err(e) => {
1290                    eprintln!("error parsing {}: {e}", start_path.display());
1291                    return 2;
1292                }
1293            };
1294            let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
1295                eprintln!("error: missing pid in {}", start_path.display());
1296                return 2;
1297            };
1298            let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
1299                eprintln!("error: missing started_at in {}", start_path.display());
1300                return 2;
1301            };
1302            if crate::clean::is_pid_alive(pid) {
1303                let finished_since_start = if summary_path.exists() {
1304                    let meta = match std::fs::metadata(&summary_path) {
1305                        Ok(m) => m,
1306                        Err(e) => {
1307                            eprintln!("error reading metadata of {}: {e}", summary_path.display());
1308                            return 2;
1309                        }
1310                    };
1311                    let mtime = match meta.modified() {
1312                        Ok(t) => t,
1313                        Err(e) => {
1314                            eprintln!("error reading mtime of {}: {e}", summary_path.display());
1315                            return 2;
1316                        }
1317                    };
1318                    let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
1319                        Ok(d) => d.as_secs(),
1320                        Err(e) => {
1321                            eprintln!("error reading timestamp of {}: {e}", summary_path.display());
1322                            return 2;
1323                        }
1324                    };
1325                    mtime_secs >= started_at
1326                } else {
1327                    false
1328                };
1329                if !finished_since_start {
1330                    eprintln!(
1331                        "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
1332                        args.id
1333                    );
1334                    return 2;
1335                }
1336            }
1337        }
1338
1339        if let Some(crate::fix_round::FixRoundRecord::Started {
1340            pre_round_sha,
1341            fallbacks_sent,
1342            started_at: round_started_at,
1343        }) = existing_fixround.clone()
1344        {
1345            if !summary_path.exists() {
1346                if !worktree_dir.exists() {
1347                    eprintln!("error: missing worktree {}", worktree_dir.display());
1348                    return 2;
1349                }
1350                let base_sha = match read_start_base_sha(&start_path) {
1351                    Ok(sha) => sha,
1352                    Err(e) => {
1353                        eprintln!("error: {e}");
1354                        return 2;
1355                    }
1356                };
1357                let report_path = wt_parent.join(format!("{}.report.json", args.id));
1358                let log_path = wt_parent.join(format!("{}.log", args.id));
1359                let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
1360                let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
1361                    Ok(r) => r,
1362                    Err(e) => {
1363                        eprintln!("error: {e}");
1364                        return 2;
1365                    }
1366                };
1367                let current_exe = match std::env::current_exe() {
1368                    Ok(p) => p,
1369                    Err(e) => {
1370                        eprintln!("error getting current executable: {e}");
1371                        return 2;
1372                    }
1373                };
1374                let configured_gate = gate;
1375                let passed_key = Some(crate::passed_trees::check_key(
1376                    &configured_gate,
1377                    &dispatch_cfg.env,
1378                ));
1379                let effective_gate = if comments == crate::config::CommentMode::Gate {
1380                    gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
1381                } else {
1382                    configured_gate
1383                };
1384                let mut warnings = Vec::new();
1385                if let Err(err_msg) = git_reset_hard(&worktree_dir, &pre_round_sha) {
1386                    let summary = build_error_summary(
1387                        &args.id,
1388                        &worktree_dir,
1389                        branch,
1390                        err_msg,
1391                        pass1.sandbox,
1392                        &log_path,
1393                        &report_path,
1394                        gate_source,
1395                        warnings,
1396                    );
1397                    return finish_summary(&summary, &wt_parent);
1398                }
1399                let impl_cfg = ImplementerConfig {
1400                    current_exe: &current_exe,
1401                    worktree_dir: &worktree_dir,
1402                    root: &root,
1403                    id: &args.id,
1404                    gate: &effective_gate,
1405                    env: &dispatch_cfg.env,
1406                    model: model.map(String::as_str),
1407                    max_seconds,
1408                    max_turns,
1409                    max_cost,
1410                    fold_budget,
1411                    sandbox: &args.sandbox,
1412                    network,
1413                    config_allow_read: &config_allow_read,
1414                    cli_allow_read: &args.allow_read,
1415                    pass_env: &args.pass_env,
1416                    research: false,
1417                    no_claim_check: args.no_claim_check,
1418                    left_out: &left_out,
1419                };
1420                let (fix_summary, round_report) = match execute_fix_round(
1421                    &root,
1422                    &start_path,
1423                    &impl_cfg,
1424                    &log_path,
1425                    &fix_report_path,
1426                    &fixround_path,
1427                    passed_key.as_deref(),
1428                    &task_content,
1429                    pre_round_sha,
1430                    fallbacks_sent,
1431                    round_started_at,
1432                    &mut warnings,
1433                ) {
1434                    Ok(res) => res,
1435                    Err(err_msg) => {
1436                        let summary = build_error_summary(
1437                            &args.id,
1438                            &worktree_dir,
1439                            branch,
1440                            err_msg,
1441                            pass1.sandbox,
1442                            &log_path,
1443                            &report_path,
1444                            gate_source,
1445                            warnings,
1446                        );
1447                        return finish_summary(&summary, &wt_parent);
1448                    }
1449                };
1450                let commits = git_commits_since(&worktree_dir, &base_sha);
1451                let changed_files = git_changed_files_since(&worktree_dir, &base_sha);
1452                let kept = fix_summary.kept;
1453                let summary = DispatchSummary {
1454                    id: args.id.clone(),
1455                    worktree: worktree_dir.display().to_string(),
1456                    branch,
1457                    outcome: "verified",
1458                    exit: exit_code("verified"),
1459                    error: pass1.error,
1460                    commits,
1461                    changed_files,
1462                    final_message: crate::fix_round::combined_final_message(
1463                        pass1.final_message,
1464                        round_report.final_message,
1465                        kept,
1466                    ),
1467                    turns: pass1.turns.saturating_add(round_report.turns),
1468                    gate_attempts: pass1.gate_attempts,
1469                    gate_failures: pass1.gate_failures,
1470                    cost_usd: crate::fix_round::sum_costs(pass1.cost_usd, round_report.cost_usd),
1471                    model: pass1.model.or(round_report.model),
1472                    seconds: pass1.seconds.saturating_add(round_report.seconds),
1473                    sandbox: pass1.sandbox,
1474                    log: log_path.display().to_string(),
1475                    report: report_path.display().to_string(),
1476                    gate_source,
1477                    research_report: None,
1478                    base_check_seconds: pass1.base_check_seconds,
1479                    warnings,
1480                    fix_round: Some(fix_summary),
1481                };
1482                return finish_summary(&summary, &wt_parent);
1483            }
1484        }
1485
1486        let branch_ref = format!("refs/heads/{branch}");
1487        let branch_out = Command::new("git")
1488            .args(["show-ref", "--verify", "--quiet", &branch_ref])
1489            .current_dir(&root)
1490            .output();
1491        let branch_exists = match branch_out {
1492            Ok(o) if o.status.success() => true,
1493            Ok(o) if o.status.code() == Some(1) => false,
1494            Ok(o) => {
1495                eprintln!(
1496                    "error: git show-ref --verify --quiet {branch_ref}: {}",
1497                    String::from_utf8_lossy(&o.stderr).trim()
1498                );
1499                return 2;
1500            }
1501            Err(e) => {
1502                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
1503                return 2;
1504            }
1505        };
1506
1507        if worktree_dir.exists() || branch_exists {
1508            match crate::clean::remove_finished_run(&root, &args.id) {
1509                Ok(Some(reason)) => {
1510                    replaced_earlier_run = true;
1511                    let secs =
1512                        match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
1513                            Ok(d) => d.as_secs(),
1514                            Err(e) => {
1515                                eprintln!("error: system clock before unix epoch: {e}");
1516                                return 2;
1517                            }
1518                        };
1519                    let archive_rel = format!(".wt/archive/{}-{secs}", args.id);
1520                    let archive_dir = root.join(&archive_rel);
1521                    if let Err(e) = std::fs::create_dir_all(&archive_dir) {
1522                        eprintln!("error: {}: {e}", archive_dir.display());
1523                        return 2;
1524                    }
1525                    for ext in [
1526                        "json",
1527                        "report.json",
1528                        "reported.json",
1529                        "start.json",
1530                        "verdict.json",
1531                        "checks.json",
1532                        "model-review.json",
1533                        "fixround.json",
1534                        "fix.report.json",
1535                        "log",
1536                    ] {
1537                        let file_name = format!("{}.{ext}", args.id);
1538                        let src = wt_parent.join(&file_name);
1539                        if src.exists() {
1540                            let dst = archive_dir.join(&file_name);
1541                            if let Err(e) = std::fs::rename(&src, &dst) {
1542                                eprintln!(
1543                                    "error: rename {} -> {}: {e}",
1544                                    src.display(),
1545                                    dst.display()
1546                                );
1547                                return 2;
1548                            }
1549                        }
1550                    }
1551                    eprintln!(
1552                        "dispatch: replaced the earlier run {} ({reason}); its records are in {archive_rel}/",
1553                        args.id
1554                    );
1555                }
1556                Ok(None) => {}
1557                Err(e) => {
1558                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
1559                    return 2;
1560                }
1561            }
1562        }
1563    } else if worktree_dir.exists() {
1564        eprintln!("error: {} already exists", worktree_dir.display());
1565        return 2;
1566    }
1567
1568    let fix_round_already_done = !replaced_earlier_run
1569        && matches!(
1570            existing_fixround,
1571            Some(crate::fix_round::FixRoundRecord::Done { .. })
1572        );
1573
1574    let started_at = std::time::SystemTime::now()
1575        .duration_since(std::time::UNIX_EPOCH)
1576        .map(|d| d.as_secs())
1577        .unwrap_or(0);
1578    let mut tags = args.tags.clone();
1579    if args.research {
1580        tags.push("research".to_string());
1581    }
1582    let session = crate::usage_log::session_from(
1583        std::env::var("BLYTE_SESSION").ok(),
1584        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
1585    );
1586    let start_path = wt_parent.join(format!("{}.start.json", args.id));
1587    let mut initial_start = serde_json::json!({
1588        "id": args.id,
1589        "pid": std::process::id(),
1590        "started_at": started_at,
1591        "starting": true,
1592        "tags": tags,
1593        "plan": args.plan,
1594        "plan_task": args.plan_task,
1595        "request": args.request,
1596        "base": args.base,
1597    });
1598    if let Some(ref s) = session {
1599        initial_start["session"] = serde_json::json!(s);
1600    }
1601    if let Some(ref missing) = brief_missing {
1602        initial_start["research"] = serde_json::json!(true);
1603        initial_start["brief_missing"] = serde_json::json!(missing);
1604    }
1605    if let Err(err) = std::fs::create_dir_all(&wt_parent)
1606        .and_then(|()| write_start_record(&start_path, &initial_start))
1607    {
1608        eprintln!(
1609            "error: could not write the start record {}: {err}",
1610            start_path.display()
1611        );
1612        return 2;
1613    }
1614    let mut start_guard = StartRecordGuard {
1615        path: start_path.clone(),
1616        armed: true,
1617    };
1618
1619    if !args.research {
1620        crate::clean::spawn_background_clean(&root, Some(&args.id));
1621    }
1622
1623    let base_commit: Option<String> = if args.research {
1624        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
1625            eprintln!(
1626                "error creating scratch directory {}: {e}",
1627                worktree_dir.display()
1628            );
1629            return 2;
1630        }
1631        let init_out = Command::new("git")
1632            .args(["init", "-q"])
1633            .current_dir(&worktree_dir)
1634            .output();
1635        match init_out {
1636            Ok(o) if o.status.success() => {}
1637            Ok(o) => {
1638                eprintln!(
1639                    "error: git init failed: {}",
1640                    String::from_utf8_lossy(&o.stderr)
1641                );
1642                return 2;
1643            }
1644            Err(e) => {
1645                eprintln!("error: failed to execute git init: {e}");
1646                return 2;
1647            }
1648        }
1649        let commit_out = Command::new("git")
1650            .args([
1651                "-c",
1652                "user.name=blyte",
1653                "-c",
1654                "user.email=blyte@local",
1655                "commit",
1656                "-q",
1657                "--allow-empty",
1658                "-m",
1659                "research",
1660            ])
1661            .current_dir(&worktree_dir)
1662            .output();
1663        match commit_out {
1664            Ok(o) if o.status.success() => {}
1665            Ok(o) => {
1666                eprintln!(
1667                    "error: git commit failed: {}",
1668                    String::from_utf8_lossy(&o.stderr)
1669                );
1670                return 2;
1671            }
1672            Err(e) => {
1673                eprintln!("error: failed to execute git commit: {e}");
1674                return 2;
1675            }
1676        }
1677        None
1678    } else if !worktree_dir.exists() {
1679        let branch_exists = Command::new("git")
1680            .args([
1681                "rev-parse",
1682                "--verify",
1683                "--quiet",
1684                &format!("refs/heads/{branch}"),
1685            ])
1686            .current_dir(&root)
1687            .output()
1688            .map(|o| o.status.success())
1689            .unwrap_or(false);
1690        if branch_exists {
1691            eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
1692            return 2;
1693        }
1694        let base_commit = match resolve_base_commit(&start_dir, &args.base) {
1695            Ok(sha) => sha,
1696            Err(e) => {
1697                eprintln!("error: {e}");
1698                return 2;
1699            }
1700        };
1701        let add_out = Command::new("git")
1702            .args([
1703                "worktree",
1704                "add",
1705                "-b",
1706                &branch,
1707                worktree_dir.to_str().unwrap(),
1708                &base_commit,
1709            ])
1710            .current_dir(&root)
1711            .output();
1712        match add_out {
1713            Ok(o) if o.status.success() => {}
1714            Ok(o) => {
1715                eprintln!(
1716                    "error: git worktree add failed: {}",
1717                    String::from_utf8_lossy(&o.stderr)
1718                );
1719                return 2;
1720            }
1721            Err(e) => {
1722                eprintln!("error: failed to execute git worktree add: {e}");
1723                return 2;
1724            }
1725        }
1726        Some(base_commit)
1727    } else {
1728        let base_commit = match Command::new("git")
1729            .args([
1730                "rev-parse",
1731                "--verify",
1732                &format!("{}^{{commit}}", args.base),
1733            ])
1734            .current_dir(&start_dir)
1735            .output()
1736        {
1737            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1738            Ok(o) => {
1739                eprintln!(
1740                    "error: git rev-parse {} failed: {}",
1741                    args.base,
1742                    String::from_utf8_lossy(&o.stderr).trim()
1743                );
1744                return 2;
1745            }
1746            Err(e) => {
1747                eprintln!("error: failed to execute git rev-parse: {e}");
1748                return 2;
1749            }
1750        };
1751        let wt_head = match Command::new("git")
1752            .args([
1753                "-C",
1754                worktree_dir.to_str().unwrap(),
1755                "rev-parse",
1756                "--verify",
1757                "HEAD^{commit}",
1758            ])
1759            .output()
1760        {
1761            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1762            Ok(o) => {
1763                eprintln!(
1764                    "error: git -C {} rev-parse HEAD failed: {}",
1765                    worktree_dir.display(),
1766                    String::from_utf8_lossy(&o.stderr).trim()
1767                );
1768                return 2;
1769            }
1770            Err(e) => {
1771                eprintln!("error: failed to execute git rev-parse: {e}");
1772                return 2;
1773            }
1774        };
1775        let ancestor_out = Command::new("git")
1776            .args(["merge-base", "--is-ancestor", &base_commit, &wt_head])
1777            .current_dir(&root)
1778            .output();
1779        match ancestor_out {
1780            Ok(o) if o.status.success() => {}
1781            Ok(o) if o.status.code() == Some(1) => {
1782                let short_wt_head = &wt_head[..wt_head.len().min(7)];
1783                let short_base = &base_commit[..base_commit.len().min(7)];
1784                eprintln!(
1785                    "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.",
1786                    id = args.id,
1787                    base_name = args.base,
1788                );
1789                return 2;
1790            }
1791            Ok(o) => {
1792                eprintln!(
1793                    "error: git merge-base --is-ancestor failed: {}",
1794                    String::from_utf8_lossy(&o.stderr).trim()
1795                );
1796                return 2;
1797            }
1798            Err(e) => {
1799                eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
1800                return 2;
1801            }
1802        }
1803        Some(base_commit)
1804    };
1805
1806    // 2. Ensure .wt/ is in info/exclude
1807    let common_dir_raw = Command::new("git")
1808        .args(["rev-parse", "--git-common-dir"])
1809        .current_dir(&root)
1810        .output();
1811    let common_dir = if let Ok(out) = common_dir_raw {
1812        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1813        if p.is_absolute() {
1814            p
1815        } else {
1816            root.join(p)
1817        }
1818    } else {
1819        root.join(".git")
1820    };
1821
1822    let exclude_path = common_dir.join("info").join("exclude");
1823    if let Some(parent) = exclude_path.parent() {
1824        let _ = std::fs::create_dir_all(parent);
1825    }
1826    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
1827    if !content.lines().any(|l| l.trim() == ".wt/") {
1828        let mut new_content = content;
1829        if !new_content.is_empty() && !new_content.ends_with('\n') {
1830            new_content.push('\n');
1831        }
1832        new_content.push_str(".wt/\n");
1833        let _ = std::fs::write(&exclude_path, new_content);
1834    }
1835
1836    // 3. Record base_sha
1837    let base_out = Command::new("git")
1838        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
1839        .output();
1840    let base_sha = match base_out {
1841        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1842        _ => {
1843            eprintln!("error: could not resolve HEAD in worktree");
1844            return 2;
1845        }
1846    };
1847
1848    if !args.research {
1849        if let Some(ref setup_cmd) = dispatch_cfg.setup {
1850            let first_line = setup_cmd.lines().next().unwrap_or("");
1851            eprintln!("setup: {first_line}");
1852            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
1853            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
1854            if let Err(msg) = crate::setup::run_setup(
1855                setup_cmd,
1856                &worktree_dir,
1857                &main_checkout,
1858                &dispatch_cfg.env,
1859                &setup_log_path,
1860                crate::setup::SETUP_TIMEOUT,
1861            ) {
1862                let outcome = "blocked";
1863                let exit = exit_code(outcome);
1864                let first_line_err = msg.lines().next().unwrap_or("").to_string();
1865                let summary = DispatchSummary {
1866                    id: args.id.clone(),
1867                    worktree: worktree_dir.display().to_string(),
1868                    branch: branch.clone(),
1869                    outcome,
1870                    exit,
1871                    error: Some(first_line_err),
1872                    commits: Vec::new(),
1873                    changed_files: Vec::new(),
1874                    final_message: Some(msg),
1875                    turns: 0,
1876                    gate_attempts: 0,
1877                    gate_failures: Vec::new(),
1878                    cost_usd: None,
1879                    model: None,
1880                    seconds: 0,
1881                    sandbox: args.sandbox.clone(),
1882                    log: setup_log_path.display().to_string(),
1883                    report: "".to_string(),
1884                    gate_source,
1885                    research_report: None,
1886                    base_check_seconds: None,
1887                    warnings: Vec::new(),
1888                    fix_round: None,
1889                };
1890                return finish_summary(&summary, &wt_parent);
1891            }
1892        }
1893    }
1894
1895    // 4. Write task file and spawn child process
1896    let _ = std::fs::create_dir_all(&wt_parent);
1897    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
1898        eprintln!("error writing task file {}: {e}", task_md_path.display());
1899        return 2;
1900    }
1901
1902    let log_path = wt_parent.join(format!("{}.log", args.id));
1903    let summary_path = wt_parent.join(format!("{}.json", args.id));
1904    if summary_path.exists() {
1905        let _ = std::fs::remove_file(&summary_path);
1906    }
1907    let report_path = wt_parent.join(format!("{}.report.json", args.id));
1908    if report_path.exists() {
1909        let _ = std::fs::remove_file(&report_path);
1910    }
1911    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
1912    if research_report_path.exists() {
1913        let _ = std::fs::remove_file(&research_report_path);
1914    }
1915    let reported_marker_path = wt_parent.join(format!("{}.reported.json", args.id));
1916    if reported_marker_path.exists() {
1917        let _ = std::fs::remove_file(&reported_marker_path);
1918    }
1919
1920    let configured_gate = gate;
1921    let passed_key = (!args.research)
1922        .then(|| crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env));
1923    let (base_check_decision, base_tree) = match decide_base_check(
1924        &root,
1925        &worktree_dir,
1926        &base_sha,
1927        &configured_gate,
1928        &dispatch_cfg.env,
1929        args.research,
1930        args.no_base_check,
1931        dispatch_cfg.base_check,
1932        crate::passed_trees::now_secs(),
1933    ) {
1934        Ok(res) => res,
1935        Err(e) => {
1936            eprintln!("error: {e}");
1937            return 2;
1938        }
1939    };
1940    if base_check_decision == BaseCheckDecision::AlreadyPassed {
1941        eprintln!("base check: this commit's content already passed");
1942    }
1943
1944    let current_exe = match std::env::current_exe() {
1945        Ok(p) => p,
1946        Err(e) => {
1947            eprintln!("error getting current executable: {e}");
1948            return 2;
1949        }
1950    };
1951
1952    let gate = if !args.research && comments == crate::config::CommentMode::Gate {
1953        gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
1954    } else {
1955        configured_gate
1956    };
1957
1958    let mut base_wt_guard: Option<BaseWorktreeGuard> = None;
1959    let base_check_dir = if !args.research && base_check_decision == BaseCheckDecision::Run {
1960        let base_wt_dir = wt_parent.join(format!("{}.base", args.id));
1961        match BaseWorktreeGuard::create(&root, base_wt_dir.clone(), &base_sha) {
1962            Ok(guard) => {
1963                base_wt_guard = Some(guard);
1964                Some(base_wt_dir)
1965            }
1966            Err(e) => {
1967                eprintln!("error creating base check worktree: {e}");
1968                return 2;
1969            }
1970        }
1971    } else {
1972        None
1973    };
1974
1975    let research_sources = args
1976        .research
1977        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
1978    let task_prompt = if let Some(block) = &research_sources {
1979        wrap_research(&format!("{block}\n\n{task_content}"), &root)
1980    } else {
1981        let mut prompt = wrap_task(&task_content);
1982        if let Some(qs) = quick_steps(&gate) {
1983            prompt.push_str("\n\n");
1984            prompt.push_str(&qs);
1985        }
1986        prompt
1987    };
1988
1989    let impl_cfg = ImplementerConfig {
1990        current_exe: &current_exe,
1991        worktree_dir: &worktree_dir,
1992        root: &root,
1993        id: &args.id,
1994        gate: &gate,
1995        env: &dispatch_cfg.env,
1996        model: model.map(String::as_str),
1997        max_seconds,
1998        max_turns,
1999        max_cost,
2000        fold_budget,
2001        sandbox: &args.sandbox,
2002        network,
2003        config_allow_read: &config_allow_read,
2004        cli_allow_read: &args.allow_read,
2005        pass_env: &args.pass_env,
2006        research: args.research,
2007        no_claim_check: args.no_claim_check,
2008        left_out: &left_out,
2009    };
2010
2011    let comments_str = if args.research {
2012        "off"
2013    } else {
2014        match comments {
2015            crate::config::CommentMode::Gate => "gate",
2016            crate::config::CommentMode::Review => "review",
2017            crate::config::CommentMode::Off => "off",
2018        }
2019    };
2020    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
2021    if let Err(e) = run_implementer_pass(
2022        &impl_cfg,
2023        &log_path,
2024        None,
2025        &report_path,
2026        &task_prompt,
2027        base_check_dir.as_deref(),
2028        |pid| {
2029            start_guard.armed = false;
2030            let mut start_json = serde_json::json!({
2031                "id": args.id,
2032                "pid": pid,
2033                "started_at": started_at,
2034                "task_file": task_file_recorded,
2035                "gate": gate,
2036                "tags": tags,
2037                "env": env_names,
2038                "max_turns": max_turns,
2039                "max_seconds": max_seconds,
2040                "plan": args.plan,
2041                "plan_task": args.plan_task,
2042                "request": args.request,
2043                "base": args.base,
2044                "base_sha": base_commit,
2045                "base_check": base_check_decision.as_json(),
2046                "comments": comments_str,
2047            });
2048            if let Some(ref session) = session {
2049                start_json["session"] = serde_json::json!(session);
2050            }
2051            if let Some(ref missing) = brief_missing {
2052                start_json["research"] = serde_json::json!(true);
2053                start_json["brief_missing"] = serde_json::json!(missing);
2054            }
2055            if !left_out.is_empty() {
2056                start_json["gate_left_out"] = serde_json::json!(left_out
2057                    .iter()
2058                    .map(|(command, reason)| serde_json::json!({
2059                        "command": command,
2060                        "reason": reason,
2061                    }))
2062                    .collect::<Vec<_>>());
2063            }
2064            if let Err(err) = write_start_record(&start_path, &start_json) {
2065                eprintln!(
2066                    "error: could not write the start record {}: {err}",
2067                    start_path.display()
2068                );
2069            }
2070        },
2071    ) {
2072        eprintln!("{e}");
2073        return 2;
2074    }
2075    drop(base_wt_guard);
2076
2077    let scratch_report = worktree_dir.join("report.md");
2078    if args.research {
2079        let is_non_empty = std::fs::metadata(&scratch_report)
2080            .map(|m| m.len() > 0)
2081            .unwrap_or(false);
2082        if is_non_empty {
2083            let _ = std::fs::copy(&scratch_report, &research_report_path);
2084            if let Some(block) = &research_sources {
2085                append_source_state(&research_report_path, block);
2086            }
2087            if let Some(ref report_to) = args.report_to {
2088                if let Some(parent) = report_to.parent() {
2089                    if !parent.as_os_str().is_empty() {
2090                        let _ = std::fs::create_dir_all(parent);
2091                    }
2092                }
2093                let _ = std::fs::copy(&scratch_report, report_to);
2094                if let Some(block) = &research_sources {
2095                    append_source_state(report_to, block);
2096                }
2097            }
2098        }
2099    }
2100
2101    // 5. Read report, commits and changed files
2102    let mut commits = git_commits_since(&worktree_dir, &base_sha);
2103    let mut changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2104
2105    let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
2106        Ok(r) => r,
2107        Err(err_msg) => pass_report_from_error(err_msg, &args.sandbox),
2108    };
2109
2110    let outcome = if args.research {
2111        match pass1.report_outcome.as_str() {
2112            "verified" => "verified",
2113            "gate_failed" => "gate_failed",
2114            "budget_exhausted" => "budget_exhausted",
2115            "blocked" => "blocked",
2116            _ => "error",
2117        }
2118    } else {
2119        dispatch_outcome(&pass1.report_outcome, commits.len())
2120    };
2121    let exit = exit_code(outcome);
2122
2123    if args.research {
2124        if research_report_path.exists() {
2125            if let Err(err) = crate::provenance::mark_if_unverified(
2126                &research_report_path,
2127                outcome,
2128                pass1.report_turns,
2129            ) {
2130                eprintln!(
2131                    "error: could not mark {} as not verified: {err}",
2132                    research_report_path.display()
2133                );
2134            }
2135        }
2136        if let Some(ref report_to) = args.report_to {
2137            if report_to.exists() {
2138                if let Err(err) =
2139                    crate::provenance::mark_if_unverified(report_to, outcome, pass1.report_turns)
2140                {
2141                    eprintln!(
2142                        "error: could not mark {} as not verified: {err}",
2143                        report_to.display()
2144                    );
2145                }
2146            }
2147        }
2148    }
2149
2150    let research_report = if args.research && research_report_path.exists() {
2151        Some(research_report_path.display().to_string())
2152    } else {
2153        None
2154    };
2155
2156    let mut warnings = record_passed_after_run(
2157        &root,
2158        &worktree_dir,
2159        args.research,
2160        base_check_decision,
2161        base_tree.as_deref(),
2162        passed_key.as_deref(),
2163        outcome,
2164        pass1.base_check_passed,
2165    );
2166    for warning in &warnings {
2167        eprintln!("warning: {warning}");
2168    }
2169
2170    let mut final_message = pass1.final_message;
2171    let mut turns = pass1.turns;
2172    let mut cost_usd = pass1.cost_usd;
2173    let mut seconds = pass1.seconds;
2174    let mut summary_model = pass1.model;
2175    let mut fix_round_summary: Option<crate::fix_round::FixRoundSummary> = None;
2176
2177    if outcome == "verified" && !args.research {
2178        let first_review = match crate::queue_actions::evaluate_verified_run(&root, &args.id) {
2179            Ok(mr) => mr,
2180            Err(err) => {
2181                eprintln!(
2182                    "warning: post-dispatch review check failed for {}: {err}",
2183                    args.id
2184                );
2185                None
2186            }
2187        };
2188
2189        if !fix_round_already_done
2190            && crate::fix_round::should_run(
2191                args.research,
2192                outcome,
2193                dispatch_cfg.fix_round,
2194                first_review.as_ref(),
2195            )
2196        {
2197            let review_ref = first_review.as_ref().unwrap();
2198            let pre_round_sha = match git_head_sha(&worktree_dir) {
2199                Ok(sha) => sha,
2200                Err(err_msg) => {
2201                    let summary = build_error_summary(
2202                        &args.id,
2203                        &worktree_dir,
2204                        branch,
2205                        err_msg,
2206                        pass1.sandbox,
2207                        &log_path,
2208                        &report_path,
2209                        gate_source,
2210                        warnings,
2211                    );
2212                    return finish_summary(&summary, &wt_parent);
2213                }
2214            };
2215            let fallbacks_sent = match crate::fix_round::collect_confirmed_fallbacks(
2216                &root,
2217                &args.id,
2218                &worktree_dir,
2219                review_ref,
2220            ) {
2221                Ok(fbs) => fbs,
2222                Err(err_msg) => {
2223                    let summary = build_error_summary(
2224                        &args.id,
2225                        &worktree_dir,
2226                        branch,
2227                        err_msg,
2228                        pass1.sandbox,
2229                        &log_path,
2230                        &report_path,
2231                        gate_source,
2232                        warnings,
2233                    );
2234                    return finish_summary(&summary, &wt_parent);
2235                }
2236            };
2237            let round_started_at =
2238                match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
2239                    Ok(d) => d.as_secs(),
2240                    Err(e) => {
2241                        let summary = build_error_summary(
2242                            &args.id,
2243                            &worktree_dir,
2244                            branch,
2245                            format!("system clock before UNIX_EPOCH: {e}"),
2246                            pass1.sandbox,
2247                            &log_path,
2248                            &report_path,
2249                            gate_source,
2250                            warnings,
2251                        );
2252                        return finish_summary(&summary, &wt_parent);
2253                    }
2254                };
2255            let started_record = crate::fix_round::FixRoundRecord::Started {
2256                pre_round_sha: pre_round_sha.clone(),
2257                fallbacks_sent: fallbacks_sent.clone(),
2258                started_at: round_started_at,
2259            };
2260            if let Err(err_msg) = crate::fix_round::write_record(&fixround_path, &started_record) {
2261                let summary = build_error_summary(
2262                    &args.id,
2263                    &worktree_dir,
2264                    branch,
2265                    err_msg,
2266                    pass1.sandbox,
2267                    &log_path,
2268                    &report_path,
2269                    gate_source,
2270                    warnings,
2271                );
2272                return finish_summary(&summary, &wt_parent);
2273            }
2274
2275            let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
2276            match execute_fix_round(
2277                &root,
2278                &start_path,
2279                &impl_cfg,
2280                &log_path,
2281                &fix_report_path,
2282                &fixround_path,
2283                passed_key.as_deref(),
2284                &task_content,
2285                pre_round_sha,
2286                fallbacks_sent,
2287                round_started_at,
2288                &mut warnings,
2289            ) {
2290                Ok((fix_sum, round_report)) => {
2291                    commits = git_commits_since(&worktree_dir, &base_sha);
2292                    changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2293                    turns = turns.saturating_add(round_report.turns);
2294                    cost_usd = crate::fix_round::sum_costs(cost_usd, round_report.cost_usd);
2295                    seconds = seconds.saturating_add(round_report.seconds);
2296                    summary_model = summary_model.or(round_report.model);
2297                    final_message = crate::fix_round::combined_final_message(
2298                        final_message,
2299                        round_report.final_message,
2300                        fix_sum.kept,
2301                    );
2302                    fix_round_summary = Some(fix_sum);
2303                }
2304                Err(err_msg) => {
2305                    let summary = build_error_summary(
2306                        &args.id,
2307                        &worktree_dir,
2308                        branch,
2309                        err_msg,
2310                        pass1.sandbox,
2311                        &log_path,
2312                        &report_path,
2313                        gate_source,
2314                        warnings,
2315                    );
2316                    return finish_summary(&summary, &wt_parent);
2317                }
2318            }
2319        }
2320    }
2321
2322    // 6. Print JSON summary
2323    let summary = DispatchSummary {
2324        id: args.id.clone(),
2325        worktree: worktree_dir.display().to_string(),
2326        branch,
2327        outcome,
2328        exit,
2329        error: pass1.error,
2330        commits,
2331        changed_files,
2332        final_message,
2333        turns,
2334        gate_attempts: pass1.gate_attempts,
2335        gate_failures: pass1.gate_failures,
2336        cost_usd,
2337        model: summary_model,
2338        seconds,
2339        sandbox: pass1.sandbox,
2340        log: log_path.display().to_string(),
2341        report: report_path.display().to_string(),
2342        gate_source,
2343        research_report,
2344        base_check_seconds: pass1.base_check_seconds,
2345        warnings,
2346        fix_round: fix_round_summary,
2347    };
2348
2349    finish_summary(&summary, &wt_parent)
2350}
2351
2352pub fn run_review(args: &ReviewArgs) -> i32 {
2353    let root = match crate::clean::find_repo_root() {
2354        Ok(r) => r,
2355        Err(e) => {
2356            eprintln!("error: {e}");
2357            return 2;
2358        }
2359    };
2360
2361    if args.notes.is_some() && args.verdict.is_none() {
2362        eprintln!("error: --notes requires --verdict");
2363        return 2;
2364    }
2365
2366    if let Some(v) = args.verdict {
2367        let ts = std::time::SystemTime::now()
2368            .duration_since(std::time::UNIX_EPOCH)
2369            .map(|d| d.as_secs())
2370            .unwrap_or(0);
2371        if let Err(e) = crate::queue_actions::record_verdict(
2372            &root,
2373            &args.id,
2374            v,
2375            args.notes.as_deref().unwrap_or(""),
2376            ts,
2377        ) {
2378            eprintln!("{e}");
2379            return 2;
2380        }
2381        println!("recorded verdict {} for {}", v.as_str(), args.id);
2382        return 0;
2383    }
2384
2385    let mut data = match crate::queue_actions::compute_review(&root, &args.id, args.diff) {
2386        Ok(d) => d,
2387        Err(e) => {
2388            eprintln!("error: {e}");
2389            return 2;
2390        }
2391    };
2392
2393    let stored_model_review = if args.model_review {
2394        None
2395    } else {
2396        match crate::queue_actions::read_stored_model_review(&root, &args.id) {
2397            Ok(mr) => mr,
2398            Err(e) => {
2399                eprintln!("error: {e}");
2400                return 2;
2401            }
2402        }
2403    };
2404    if !args.model_review {
2405        data.checks
2406            .flags
2407            .extend(crate::fallback_check::flags_for_review(
2408                &data.fallbacks,
2409                stored_model_review.as_ref(),
2410            ));
2411        if let Some(ref mr) = stored_model_review {
2412            if let Some(flag) = mr.flag() {
2413                if !data
2414                    .checks
2415                    .flags
2416                    .iter()
2417                    .any(|f| f.starts_with("model review"))
2418                {
2419                    data.checks.flags.push(flag);
2420                }
2421            }
2422        }
2423    }
2424
2425    if !args.model_review {
2426        if let Err(e) = crate::queue_actions::write_checks_file(
2427            &root,
2428            &args.id,
2429            &data.checks.flags,
2430            &data.fallbacks,
2431            stored_model_review.as_ref(),
2432        ) {
2433            eprintln!("{e}");
2434            return 2;
2435        }
2436    }
2437
2438    let crate::queue_actions::ReviewComputation {
2439        wt,
2440        wt_exists,
2441        is_research: _,
2442        base,
2443        task_text: _,
2444        changed_files: _,
2445        commits_out,
2446        files_out,
2447        tree_out,
2448        diff_out,
2449        hcmds,
2450        reads,
2451        report_val,
2452        quote_problems,
2453        claim_check,
2454        claim_check_skipped,
2455        mut checks,
2456        fallbacks,
2457    } = data;
2458
2459    println!("== checks");
2460    if checks.flags.is_empty() {
2461        println!("nothing flagged");
2462    } else {
2463        for flag in &checks.flags {
2464            println!("! {flag}");
2465        }
2466    }
2467
2468    println!("== commits");
2469    if !wt_exists {
2470        println!("(worktree removed)");
2471    } else if !commits_out.is_empty() {
2472        println!("{commits_out}");
2473    }
2474    println!("== files");
2475    if !wt_exists {
2476        println!("(worktree removed)");
2477    } else if !files_out.is_empty() {
2478        println!("{files_out}");
2479    }
2480    println!("== tree");
2481    if !wt_exists {
2482        println!("(worktree removed)");
2483    } else if tree_out.is_empty() {
2484        println!("(clean)");
2485    } else {
2486        println!("{tree_out}");
2487    }
2488    println!("== report");
2489    if let Some(ref v) = report_val {
2490        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
2491            println!("outcome: {outcome}");
2492        }
2493        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
2494            println!("turns: {turns}");
2495        }
2496        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
2497            println!("cost_usd: {cost}");
2498        }
2499        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
2500            println!("final_message: {msg}");
2501        }
2502        if let Some(ref problems) = quote_problems {
2503            if problems.is_empty() {
2504                println!("quote check: passed");
2505            } else {
2506                println!(
2507                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
2508                    problems.len()
2509                );
2510                for p in problems.iter().take(5) {
2511                    let cut: String = p.chars().take(200).collect();
2512                    println!("  {cut}");
2513                }
2514            }
2515        }
2516        if let Some(ref cc) = claim_check {
2517            println!(
2518                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
2519                cc.checked,
2520                cc.contradicted.len(),
2521                cc.not_enough_evidence,
2522                cc.parse_errors,
2523                cc.unchecked
2524            );
2525            for f in cc.contradicted.iter().take(5) {
2526                let cut: String = f.text.chars().take(200).collect();
2527                println!("  report.md:{}: {cut}", f.line);
2528                println!("    {}", f.reason);
2529            }
2530        }
2531        if let Some(ref skipped) = claim_check_skipped {
2532            println!("claim check skipped: {skipped}");
2533        }
2534    }
2535
2536    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
2537    if research_report_file.exists() {
2538        println!("== research report");
2539        println!("{}", research_report_file.display());
2540        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
2541            for line in content.lines().take(40) {
2542                println!("{line}");
2543            }
2544        }
2545    }
2546
2547    if !hcmds.is_empty() {
2548        println!("== host commands (may have changed things outside the worktree)");
2549        for cmd in hcmds {
2550            println!("{cmd}");
2551        }
2552    }
2553    if !reads.is_empty() {
2554        println!("== reads outside the repository");
2555        for cmd in reads {
2556            println!("{cmd}");
2557        }
2558    }
2559
2560    if args.diff {
2561        println!("== diff");
2562        if !wt_exists {
2563            println!("(worktree removed)");
2564        } else if !diff_out.is_empty() {
2565            println!("{diff_out}");
2566        }
2567    }
2568
2569    if args.model_review && wt_exists {
2570        let mr = crate::model_review::run(&root, &args.id, &base, &wt);
2571        crate::model_review::print_result(&mr);
2572        checks.flags.extend(crate::fallback_check::flags_for_review(
2573            &fallbacks,
2574            Some(&mr),
2575        ));
2576        if let Some(flag) = mr.flag() {
2577            checks.flags.push(flag);
2578        }
2579        if let Err(e) = crate::queue_actions::write_checks_file(
2580            &root,
2581            &args.id,
2582            &checks.flags,
2583            &fallbacks,
2584            Some(&mr),
2585        ) {
2586            eprintln!("{e}");
2587            return 2;
2588        }
2589    } else if args.model_review {
2590        checks
2591            .flags
2592            .extend(crate::fallback_check::flags_for_review(&fallbacks, None));
2593        if let Err(e) = crate::queue_actions::write_checks_file(
2594            &root,
2595            &args.id,
2596            &checks.flags,
2597            &fallbacks,
2598            None,
2599        ) {
2600            eprintln!("{e}");
2601            return 2;
2602        }
2603    } else if let Some(ref mr) = stored_model_review {
2604        crate::model_review::print_result(mr);
2605    }
2606
2607    0
2608}
2609
2610const OUTSIDE_PATHS: &[&str] = &[
2611    "~/",
2612    "$HOME",
2613    "/Users/",
2614    "/home/",
2615    "/private/",
2616    "/var/",
2617    "/etc/",
2618    "/opt/",
2619    "/usr/",
2620];
2621
2622const CHANGE_WORDS: &[&str] = &[
2623    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
2624];
2625
2626fn contains_word(cmd: &str, word: &str) -> bool {
2627    let mut start = 0;
2628    while let Some(pos) = cmd[start..].find(word) {
2629        let abs_pos = start + pos;
2630        let before_ok = if abs_pos == 0 {
2631            true
2632        } else {
2633            let prev = cmd[..abs_pos].chars().next_back().unwrap();
2634            !prev.is_alphanumeric() && prev != '_' && prev != '-'
2635        };
2636        let after_pos = abs_pos + word.len();
2637        let after_ok = if after_pos >= cmd.len() {
2638            true
2639        } else {
2640            let next = cmd[after_pos..].chars().next().unwrap();
2641            !next.is_alphanumeric() && next != '_' && next != '-'
2642        };
2643        if before_ok && after_ok {
2644            return true;
2645        }
2646        start = abs_pos + word.len();
2647    }
2648    false
2649}
2650
2651fn has_non_dev_null_redirect(cmd: &str) -> bool {
2652    let chars: Vec<char> = cmd.chars().collect();
2653    let mut i = 0;
2654    while i < chars.len() {
2655        if chars[i] == '>' {
2656            while i < chars.len() && chars[i] == '>' {
2657                i += 1;
2658            }
2659            if i < chars.len() && chars[i] == '|' {
2660                i += 1;
2661            }
2662            while i < chars.len() && chars[i].is_whitespace() {
2663                i += 1;
2664            }
2665            if i >= chars.len() {
2666                break;
2667            }
2668            if chars[i] == '&'
2669                && i + 1 < chars.len()
2670                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
2671            {
2672                i += 1;
2673                continue;
2674            }
2675            let target_start = i;
2676            while i < chars.len()
2677                && !chars[i].is_whitespace()
2678                && chars[i] != ';'
2679                && chars[i] != '|'
2680                && chars[i] != '&'
2681                && chars[i] != ')'
2682            {
2683                i += 1;
2684            }
2685            let target: String = chars[target_start..i].iter().collect();
2686            let target = target.trim_matches(|c| c == '\'' || c == '"');
2687            if !target.is_empty() && target != "/dev/null" {
2688                return true;
2689            }
2690        } else {
2691            i += 1;
2692        }
2693    }
2694    false
2695}
2696
2697fn changes_something(cmd: &str) -> bool {
2698    for &word in CHANGE_WORDS {
2699        if contains_word(cmd, word) {
2700            return true;
2701        }
2702    }
2703    has_non_dev_null_redirect(cmd)
2704}
2705
2706fn is_host_command(cmd: &str) -> bool {
2707    if cmd.contains("git push")
2708        || cmd.contains("sudo ")
2709        || cmd.contains("cache clean")
2710        || cmd.contains("cache prune")
2711        || cmd.contains("brew ")
2712    {
2713        return true;
2714    }
2715
2716    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
2717    names_outside && changes_something(cmd)
2718}
2719
2720pub(crate) fn bash_commands(log: &str) -> Vec<String> {
2721    let cleaned = strip_ansi(log);
2722    let mut result = Vec::new();
2723    for line in cleaned.lines() {
2724        let trimmed = line.trim();
2725        if let Some(rest) = trimmed.strip_prefix("● bash ") {
2726            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
2727                let cmd = cmd.trim();
2728                if !cmd.is_empty() {
2729                    result.push(cmd.to_string());
2730                }
2731            }
2732        }
2733    }
2734    result
2735}
2736
2737pub fn host_commands(log: &str) -> Vec<String> {
2738    let mut result = Vec::new();
2739    for cmd in bash_commands(log) {
2740        if is_host_command(&cmd) && !result.iter().any(|c| c == &cmd) {
2741            result.push(cmd);
2742            if result.len() == 20 {
2743                break;
2744            }
2745        }
2746    }
2747    result
2748}
2749
2750const TERMINAL_READS: &[&str] = &[
2751    "herdr pane read",
2752    "tmux capture-pane",
2753    "screen -X hardcopy",
2754    "zellij action dump-screen",
2755    "wezterm cli get-text",
2756];
2757
2758const TOOL_CACHES: &[&str] = &[
2759    ".cargo",
2760    ".rustup",
2761    ".cache",
2762    ".npm",
2763    ".local",
2764    "Library/Caches",
2765    ".gradle",
2766    ".m2",
2767    "go",
2768];
2769
2770fn normalize_path(path: &Path) -> PathBuf {
2771    use std::path::Component;
2772    let mut out = PathBuf::new();
2773    for comp in path.components() {
2774        match comp {
2775            Component::ParentDir => {
2776                out.pop();
2777            }
2778            Component::CurDir => {}
2779            _ => out.push(comp),
2780        }
2781    }
2782    out
2783}
2784
2785fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
2786    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
2787        return true;
2788    }
2789
2790    for raw_word in cmd.split_whitespace() {
2791        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
2792        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
2793            Some(home.join(suffix))
2794        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
2795            Some(home.join(suffix))
2796        } else if word.starts_with('/') {
2797            Some(PathBuf::from(word))
2798        } else {
2799            None
2800        };
2801
2802        if let Some(path) = raw_path {
2803            let norm_path = normalize_path(&path);
2804            if !norm_path.starts_with(home) {
2805                continue;
2806            }
2807            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
2808            if under_allowed {
2809                continue;
2810            }
2811            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
2812            if under_cache {
2813                continue;
2814            }
2815            return true;
2816        }
2817    }
2818
2819    false
2820}
2821
2822pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
2823    let host_cmds = host_commands(log);
2824    let norm_home = normalize_path(home);
2825    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
2826    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
2827        .iter()
2828        .map(|c| normalize_path(&norm_home.join(c)))
2829        .collect();
2830
2831    let cleaned = strip_ansi(log);
2832    let mut result = Vec::new();
2833    for line in cleaned.lines() {
2834        let trimmed = line.trim();
2835        if let Some(rest) = trimmed.strip_prefix("● bash ") {
2836            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
2837                let cmd = cmd.trim();
2838                if host_cmds.iter().any(|c| c == cmd) {
2839                    continue;
2840                }
2841                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
2842                    && !result.iter().any(|c| c == cmd)
2843                {
2844                    result.push(cmd.to_string());
2845                    if result.len() == 20 {
2846                        break;
2847                    }
2848                }
2849            }
2850        }
2851    }
2852    result
2853}
2854
2855fn strip_ansi(s: &str) -> String {
2856    let mut out = String::with_capacity(s.len());
2857    let mut chars = s.chars().peekable();
2858    while let Some(c) = chars.next() {
2859        if c == '\x1b' && chars.peek() == Some(&'[') {
2860            chars.next();
2861            while let Some(&next_c) = chars.peek() {
2862                chars.next();
2863                if ('\x40'..='\x7e').contains(&next_c) {
2864                    break;
2865                }
2866                if next_c == '\n' || next_c == '\x1b' {
2867                    out.push(next_c);
2868                    break;
2869                }
2870            }
2871            continue;
2872        }
2873        out.push(c);
2874    }
2875    out
2876}
2877
2878#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2879pub struct LogProgress {
2880    pub turn: u32,
2881    pub last_tool: Option<String>,
2882    pub gate_attempts: u32,
2883    pub gate_passed: bool,
2884}
2885
2886pub fn parse_log(log: &str) -> LogProgress {
2887    let cleaned = strip_ansi(log);
2888    let mut turn: u32 = 0;
2889    let mut last_tool: Option<String> = None;
2890    let mut gate_attempts: u32 = 0;
2891    let mut gate_passed: bool = false;
2892
2893    for line in cleaned.lines() {
2894        if let Some(rest) = line.strip_prefix("[Turn ") {
2895            if let Some((n_str, _)) = rest.split_once(']') {
2896                if let Ok(n) = n_str.trim().parse::<u32>() {
2897                    turn = turn.max(n);
2898                }
2899            }
2900        }
2901
2902        if let Some(tool) = line.strip_prefix("● ") {
2903            let truncated = if tool.chars().count() > 200 {
2904                tool.chars().take(200).collect()
2905            } else {
2906                tool.to_string()
2907            };
2908            last_tool = Some(truncated);
2909        }
2910
2911        if line.starts_with("✓ Gate passed") {
2912            gate_attempts += 1;
2913            gate_passed = true;
2914        } else if line.starts_with("✗ Gate failed") {
2915            gate_attempts += 1;
2916            gate_passed = false;
2917        }
2918    }
2919
2920    LogProgress {
2921        turn,
2922        last_tool,
2923        gate_attempts,
2924        gate_passed,
2925    }
2926}
2927
2928#[derive(Debug, Serialize)]
2929pub struct StatusOutput {
2930    pub id: String,
2931    pub state: String,
2932    pub elapsed_s: u64,
2933    pub turn: u32,
2934    pub last_tool: Option<String>,
2935    pub gate_attempts: u32,
2936    pub gate_passed: bool,
2937    pub outcome: Option<String>,
2938    pub cost_usd: Option<f64>,
2939    pub final_message: Option<String>,
2940}
2941
2942pub fn run_status(id: &str, json: bool) -> i32 {
2943    let root = match crate::clean::find_repo_root() {
2944        Ok(r) => r,
2945        Err(e) => {
2946            eprintln!("error: {e}");
2947            return 2;
2948        }
2949    };
2950
2951    let start_path = root.join(".wt").join(format!("{id}.start.json"));
2952    if !start_path.exists() {
2953        eprintln!("no dispatch {id} here");
2954        return 2;
2955    }
2956
2957    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
2958        Ok(s) => match serde_json::from_str(&s) {
2959            Ok(v) => v,
2960            Err(e) => {
2961                eprintln!("error parsing {}: {e}", start_path.display());
2962                return 2;
2963            }
2964        },
2965        Err(e) => {
2966            eprintln!("error reading {}: {e}", start_path.display());
2967            return 2;
2968        }
2969    };
2970
2971    let pid = start_record
2972        .get("pid")
2973        .and_then(|v| v.as_i64())
2974        .map(|v| v as libc::pid_t);
2975    let started_at = start_record
2976        .get("started_at")
2977        .and_then(|v| v.as_u64())
2978        .unwrap_or(0);
2979
2980    let is_alive = if let Some(pid) = pid {
2981        if pid > 0 {
2982            let ret = unsafe { libc::kill(pid, 0) };
2983            if ret == 0 {
2984                true
2985            } else {
2986                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
2987            }
2988        } else {
2989            false
2990        }
2991    } else {
2992        false
2993    };
2994
2995    let report_path = root.join(".wt").join(format!("{id}.report.json"));
2996    let report_exists = report_path.exists();
2997
2998    let state = if report_exists {
2999        "finished"
3000    } else if is_alive {
3001        "running"
3002    } else {
3003        "dead"
3004    };
3005
3006    let now = std::time::SystemTime::now()
3007        .duration_since(std::time::UNIX_EPOCH)
3008        .map(|d| d.as_secs())
3009        .unwrap_or(0);
3010
3011    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
3012        if let Ok(content) = std::fs::read_to_string(&report_path) {
3013            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
3014                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
3015                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
3016                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
3017                    if s.chars().count() > 500 {
3018                        s.chars().take(500).collect()
3019                    } else {
3020                        s.to_string()
3021                    }
3022                });
3023                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
3024                (outcome, cost_usd, final_message, duration)
3025            } else {
3026                (None, None, None, None)
3027            }
3028        } else {
3029            (None, None, None, None)
3030        }
3031    } else {
3032        (None, None, None, None)
3033    };
3034
3035    let elapsed_s = if state == "finished" {
3036        report_duration
3037            .map(|d| d.round() as u64)
3038            .unwrap_or_else(|| now.saturating_sub(started_at))
3039    } else {
3040        now.saturating_sub(started_at)
3041    };
3042
3043    let log_path = root.join(".wt").join(format!("{id}.log"));
3044    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
3045    let progress = parse_log(&log_content);
3046
3047    if json {
3048        let status_obj = StatusOutput {
3049            id: id.to_string(),
3050            state: state.to_string(),
3051            elapsed_s,
3052            turn: progress.turn,
3053            last_tool: progress.last_tool,
3054            gate_attempts: progress.gate_attempts,
3055            gate_passed: progress.gate_passed,
3056            outcome,
3057            cost_usd,
3058            final_message,
3059        };
3060        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
3061        println!("{json_str}");
3062    } else {
3063        println!("id: {id}");
3064        println!("state: {state}");
3065        println!("elapsed_s: {elapsed_s}");
3066        println!("turn: {}", progress.turn);
3067        println!(
3068            "last_tool: {}",
3069            progress.last_tool.as_deref().unwrap_or("none")
3070        );
3071        println!("gate_attempts: {}", progress.gate_attempts);
3072        println!("gate_passed: {}", progress.gate_passed);
3073        if state == "finished" {
3074            if let Some(ref o) = outcome {
3075                println!("outcome: {o}");
3076            }
3077            if let Some(c) = cost_usd {
3078                println!("cost_usd: {c}");
3079            }
3080            if let Some(ref msg) = final_message {
3081                println!("final_message: {msg}");
3082            }
3083        }
3084    }
3085
3086    match state {
3087        "running" | "finished" => 0,
3088        _ => 1,
3089    }
3090}
3091
3092pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
3093    let readable_canon: Vec<PathBuf> = readable
3094        .iter()
3095        .filter_map(|r| std::fs::canonicalize(r).ok())
3096        .collect();
3097    let mut out = Vec::new();
3098    for raw in text.split(|c: char| {
3099        c.is_whitespace()
3100            || matches!(
3101                c,
3102                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
3103            )
3104    }) {
3105        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
3106        if !trimmed.starts_with('/')
3107            || trimmed.starts_with("//")
3108            || trimmed.len() <= 1
3109            || trimmed == "/dev/null"
3110        {
3111            continue;
3112        }
3113        let p = Path::new(trimmed);
3114        let Ok(canon) = std::fs::canonicalize(p) else {
3115            continue;
3116        };
3117        if readable_canon.iter().any(|r| canon.starts_with(r))
3118            || is_system_path(p)
3119            || is_system_path(&canon)
3120        {
3121            continue;
3122        }
3123        let pb = PathBuf::from(trimmed);
3124        if !out.contains(&pb) {
3125            out.push(pb);
3126        }
3127    }
3128    out
3129}
3130
3131/// A path no research task means as code to read: the filesystem root, a top-level directory,
3132/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
3133fn is_system_path(p: &Path) -> bool {
3134    const SYSTEM: &[&str] = &[
3135        "/usr",
3136        "/bin",
3137        "/sbin",
3138        "/etc",
3139        "/dev",
3140        "/opt",
3141        "/System",
3142        "/Library",
3143        "/Applications",
3144        "/nix",
3145        "/proc",
3146        "/sys",
3147    ];
3148    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
3149}
3150
3151pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
3152    let mut count = 0;
3153    let mut paths = Vec::new();
3154    for line in log_content.lines() {
3155        if !line.contains("path escapes the workspace") {
3156            continue;
3157        }
3158        count += 1;
3159        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
3160            let after = after.trim_start();
3161            let after = after.split("\x1b[").next().unwrap_or(after);
3162            let path = after
3163                .split(". This run can read")
3164                .next()
3165                .unwrap_or(after)
3166                .trim();
3167            if !path.is_empty() && !paths.iter().any(|p| p == path) {
3168                paths.push(path.to_string());
3169            }
3170        }
3171    }
3172    (count, paths)
3173}
3174
3175#[cfg(test)]
3176mod tests {
3177    use super::*;
3178
3179    #[test]
3180    fn outside_reads_excludes_commands_in_host_commands() {
3181        let home = Path::new("/Users/u");
3182        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3183        // rm -rf ~/repos/other is a host command (names outside and changes something)
3184        // cat ~/repos/other is not a host command (only reads)
3185        let log = "\
3186● bash rm -rf ~/repos/other/file.py -> exit 0
3187● bash cat ~/repos/other/file.py -> exit 0
3188";
3189        assert_eq!(
3190            host_commands(log),
3191            vec!["rm -rf ~/repos/other/file.py".to_string()]
3192        );
3193        assert_eq!(
3194            outside_reads(log, &allowed, home),
3195            vec!["cat ~/repos/other/file.py".to_string()]
3196        );
3197    }
3198
3199    #[test]
3200    fn outside_reads_all_terminal_patterns() {
3201        let home = Path::new("/Users/u");
3202        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3203        let log = "\
3204● bash herdr pane read p1 -> exit 0
3205● bash tmux capture-pane -t 1 -> exit 0
3206● bash screen -X hardcopy /tmp/screen.log -> exit 0
3207● bash zellij action dump-screen /tmp/dump -> exit 0
3208● bash wezterm cli get-text --pane-id 1 -> exit 0
3209";
3210        let reads = outside_reads(log, &allowed, home);
3211        assert_eq!(
3212            reads,
3213            vec![
3214                "herdr pane read p1",
3215                "tmux capture-pane -t 1",
3216                "screen -X hardcopy /tmp/screen.log",
3217                "zellij action dump-screen /tmp/dump",
3218                "wezterm cli get-text --pane-id 1",
3219            ]
3220        );
3221    }
3222
3223    #[test]
3224    fn outside_reads_all_tool_caches_ignored() {
3225        let home = Path::new("/Users/u");
3226        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3227        let log = "\
3228● bash ls ~/.cargo/bin -> exit 0
3229● bash ls ~/.rustup/toolchains -> exit 0
3230● bash ls ~/.cache/pip -> exit 0
3231● bash ls ~/.npm/_cacache -> exit 0
3232● bash ls ~/.local/share -> exit 0
3233● bash ls ~/Library/Caches/com.apple -> exit 0
3234● bash ls ~/.gradle/caches -> exit 0
3235● bash ls ~/.m2/repository -> exit 0
3236● bash ls ~/go/pkg -> exit 0
3237";
3238        assert!(outside_reads(log, &allowed, home).is_empty());
3239    }
3240
3241    #[test]
3242    fn outside_reads_trailing_punctuations_stripped() {
3243        let home = Path::new("/Users/u");
3244        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3245        let log = "\
3246● bash ls ~/secret: -> exit 0
3247● bash ls ~/secret, -> exit 0
3248● bash (ls ~/secret) -> exit 0
3249● bash bash -c 'ls ~/secret' -> exit 0
3250● bash bash -c \"ls ~/secret\" -> exit 0
3251";
3252        let reads = outside_reads(log, &allowed, home);
3253        // Deduplicated, so only one instance of the command or distinct commands:
3254        assert_eq!(reads.len(), 5);
3255    }
3256
3257    #[test]
3258    fn outside_reads_caps_at_20_and_deduplicates() {
3259        let home = Path::new("/Users/u");
3260        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3261        let mut log = String::new();
3262        for i in 0..30 {
3263            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
3264        }
3265        // Duplicate the first one
3266        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
3267        let reads = outside_reads(&log, &allowed, home);
3268        assert_eq!(reads.len(), 20);
3269        assert_eq!(reads[0], "cat ~/secret/0.txt");
3270        assert_eq!(reads[19], "cat ~/secret/19.txt");
3271    }
3272}