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