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