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