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