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 Ok(home) = crate::skill::home_dir() {
1188        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
1189            eprintln!(
1190                "blyte: added context rules to {} (they apply from the next Claude session)",
1191                path.display()
1192            );
1193        }
1194    }
1195
1196    // 1. Root repository discovery and worktree preparation
1197    let out = Command::new("git")
1198        .args(["rev-parse", "--show-toplevel"])
1199        .output();
1200    let Ok(out) = out else {
1201        eprintln!("error: git not found");
1202        return 2;
1203    };
1204    if !out.status.success() {
1205        eprintln!("error: not a git repository");
1206        return 2;
1207    }
1208    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1209    let root = match crate::clean::find_repo_root() {
1210        Ok(r) => r,
1211        Err(e) => {
1212            eprintln!("error: {e}");
1213            return 2;
1214        }
1215    };
1216    crate::registry::register(&root);
1217
1218    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
1219        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
1220        Ok(None) => (None, false),
1221        Err(e) => {
1222            eprintln!("{e}");
1223            return 2;
1224        }
1225    };
1226    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
1227    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
1228        Ok(m) => m,
1229        Err(e) => {
1230            eprintln!("error: {e}");
1231            return 2;
1232        }
1233    };
1234
1235    let mut left_out: Vec<(String, String)> = Vec::new();
1236    let (gate, gate_source) = if args.research {
1237        ("test -s report.md".to_string(), "research")
1238    } else if let Some(ref g) = args.gate {
1239        (g.clone(), "flag")
1240    } else if let Some(ref g) = dispatch_cfg.gate {
1241        let toml_path = if from_main {
1242            root.join("blyte.toml")
1243        } else {
1244            start_dir.join("blyte.toml")
1245        };
1246        let drift = match load_gate_drift(&root, &toml_path, g) {
1247            Ok(v) => v,
1248            Err(e) => {
1249                eprintln!("error: {e}");
1250                return 2;
1251            }
1252        };
1253        left_out = drift.left_out;
1254        if let Some(warning) = drift.warning {
1255            eprintln!("{warning}");
1256        }
1257        if !left_out.is_empty() {
1258            let formatted: Vec<String> = left_out
1259                .iter()
1260                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
1261                .collect();
1262            eprintln!(
1263                "blyte: the gate is partial; left out: {}",
1264                formatted.join("; ")
1265            );
1266        }
1267        let source = if from_main {
1268            "blyte.toml (main checkout)"
1269        } else {
1270            "blyte.toml"
1271        };
1272        (g.clone(), source)
1273    } else {
1274        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
1275        return 2;
1276    };
1277
1278    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
1279    let (max_seconds, max_turns) = if args.research {
1280        (
1281            args.max_seconds.unwrap_or(1800),
1282            args.max_turns.unwrap_or(300),
1283        )
1284    } else {
1285        (
1286            args.max_seconds
1287                .or(dispatch_cfg.max_seconds)
1288                .unwrap_or(3600),
1289            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
1290        )
1291    };
1292    let max_cost = resolve_max_cost(args.max_cost_usd, dispatch_cfg.max_cost);
1293    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
1294    let network = args
1295        .network
1296        .as_deref()
1297        .or(dispatch_cfg.network.as_deref())
1298        .unwrap_or("on");
1299
1300    let wt_parent = root.join(".wt");
1301    let worktree_dir = wt_parent.join(&args.id);
1302    let branch = format!("wip/{}", args.id);
1303    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
1304    let summary_path = wt_parent.join(format!("{}.json", args.id));
1305    let fixround_path = crate::fix_round::record_path(&wt_parent, &args.id);
1306
1307    let existing_fixround = if args.research {
1308        None
1309    } else {
1310        match crate::fix_round::load_record(&fixround_path) {
1311            Ok(rec) => rec,
1312            Err(e) => {
1313                eprintln!("error: {e}");
1314                return 2;
1315            }
1316        }
1317    };
1318
1319    let resuming_fix_round = !args.research
1320        && !summary_path.exists()
1321        && matches!(
1322            existing_fixround,
1323            Some(crate::fix_round::FixRoundRecord::Started { .. })
1324        );
1325
1326    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
1327        let content = match std::fs::read_to_string(tf) {
1328            Ok(s) => s,
1329            Err(e) => {
1330                eprintln!("error reading task file {}: {e}", tf.display());
1331                return 2;
1332            }
1333        };
1334        (content, Some(tf.display().to_string()))
1335    } else {
1336        match (&args.plan, &args.plan_task) {
1337            (Some(plan_path), Some(plan_task)) => {
1338                let plan_str = match std::fs::read_to_string(plan_path) {
1339                    Ok(s) => s,
1340                    Err(e) => {
1341                        eprintln!("error reading plan {plan_path}: {e}");
1342                        return 2;
1343                    }
1344                };
1345                let section = match crate::plan_section::extract(&plan_str, plan_task) {
1346                    Some(sec) => sec,
1347                    None => {
1348                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
1349                        if let Some(hint) =
1350                            crate::plan_section::explain_missing(&plan_str, plan_task)
1351                        {
1352                            eprintln!("  {hint}");
1353                        }
1354                        return 2;
1355                    }
1356                };
1357                let content = format!("From the plan {plan_path}:\n\n{section}");
1358                (content, None)
1359            }
1360            _ if resuming_fix_round => {
1361                let start_path = wt_parent.join(format!("{}.start.json", args.id));
1362                match read_start_task_content(&root, &start_path) {
1363                    Ok(content) => (content, None),
1364                    Err(e) => {
1365                        eprintln!("error: {e}");
1366                        return 2;
1367                    }
1368                }
1369            }
1370            _ => {
1371                eprintln!("error: give a task file, or --plan with --plan-task");
1372                if args.research {
1373                    eprintln!(
1374                        "A research question needs these sections:\n\n{}",
1375                        crate::research_brief::TEMPLATE
1376                    );
1377                }
1378                return 2;
1379            }
1380        }
1381    };
1382
1383    let brief_missing = args
1384        .research
1385        .then(|| crate::research_brief::missing_sections(&task_content));
1386    if let Some(ref missing) = brief_missing {
1387        if !args.no_brief_check {
1388            if !missing.is_empty() {
1389                eprintln!(
1390                    "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.",
1391                    missing.join(", "),
1392                    args.id
1393                );
1394            }
1395            let unverified = crate::research_brief::unverified_inputs(&task_content, &root);
1396            if !unverified.is_empty() {
1397                let paths: Vec<String> =
1398                    unverified.iter().map(|p| p.display().to_string()).collect();
1399                eprintln!(
1400                    "blyte: the question names a report that did not pass blyte's checks: {}. Use a verified report, or --no-brief-check to start anyway.",
1401                    paths.join(", ")
1402                );
1403                return 2;
1404            }
1405        }
1406    }
1407
1408    let home = std::env::var_os("HOME").map(PathBuf::from);
1409    let main_checkout = root.clone();
1410    let config_allow_read = match crate::config::expand_allow_read(
1411        &dispatch_cfg.allow_read,
1412        home.as_deref(),
1413        &main_checkout,
1414    ) {
1415        Ok(paths) => paths,
1416        Err(e) => {
1417            eprintln!("{e}");
1418            return 2;
1419        }
1420    };
1421
1422    if !args.no_path_check {
1423        let mut readable = vec![start_dir.clone(), root.clone()];
1424        readable.extend(config_allow_read.iter().cloned());
1425        readable.extend(args.allow_read.iter().cloned());
1426        let bad = unreadable_paths(&task_content, &readable);
1427        if !bad.is_empty() {
1428            let shown: Vec<String> = bad
1429                .iter()
1430                .take(5)
1431                .map(|p| p.display().to_string())
1432                .collect();
1433            eprintln!(
1434                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
1435                shown.join(", ")
1436            );
1437            if args.research {
1438                return 2;
1439            }
1440        }
1441    }
1442
1443    let task_file_recorded =
1444        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
1445
1446    let mut replaced_earlier_run = false;
1447    if !args.research {
1448        let start_path = wt_parent.join(format!("{}.start.json", args.id));
1449        if start_path.exists() {
1450            let start_str = match std::fs::read_to_string(&start_path) {
1451                Ok(s) => s,
1452                Err(e) => {
1453                    eprintln!("error reading {}: {e}", start_path.display());
1454                    return 2;
1455                }
1456            };
1457            let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
1458                Ok(v) => v,
1459                Err(e) => {
1460                    eprintln!("error parsing {}: {e}", start_path.display());
1461                    return 2;
1462                }
1463            };
1464            let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
1465                eprintln!("error: missing pid in {}", start_path.display());
1466                return 2;
1467            };
1468            let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
1469                eprintln!("error: missing started_at in {}", start_path.display());
1470                return 2;
1471            };
1472            if crate::clean::is_pid_alive(pid) {
1473                let finished_since_start = if summary_path.exists() {
1474                    let meta = match std::fs::metadata(&summary_path) {
1475                        Ok(m) => m,
1476                        Err(e) => {
1477                            eprintln!("error reading metadata of {}: {e}", summary_path.display());
1478                            return 2;
1479                        }
1480                    };
1481                    let mtime = match meta.modified() {
1482                        Ok(t) => t,
1483                        Err(e) => {
1484                            eprintln!("error reading mtime of {}: {e}", summary_path.display());
1485                            return 2;
1486                        }
1487                    };
1488                    let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
1489                        Ok(d) => d.as_secs(),
1490                        Err(e) => {
1491                            eprintln!("error reading timestamp of {}: {e}", summary_path.display());
1492                            return 2;
1493                        }
1494                    };
1495                    mtime_secs >= started_at
1496                } else {
1497                    false
1498                };
1499                if !finished_since_start {
1500                    eprintln!(
1501                        "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
1502                        args.id
1503                    );
1504                    return 2;
1505                }
1506            }
1507        }
1508
1509        if let Some(crate::fix_round::FixRoundRecord::Started {
1510            pre_round_sha,
1511            fallbacks_sent,
1512            concerns_sent,
1513            started_at: round_started_at,
1514        }) = existing_fixround.clone()
1515        {
1516            if !summary_path.exists() {
1517                if !worktree_dir.exists() {
1518                    eprintln!("error: missing worktree {}", worktree_dir.display());
1519                    return 2;
1520                }
1521                let base_sha = match read_start_base_sha(&start_path) {
1522                    Ok(sha) => sha,
1523                    Err(e) => {
1524                        eprintln!("error: {e}");
1525                        return 2;
1526                    }
1527                };
1528                let report_path = wt_parent.join(format!("{}.report.json", args.id));
1529                let log_path = wt_parent.join(format!("{}.log", args.id));
1530                let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
1531                let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
1532                    Ok(r) => r,
1533                    Err(e) => {
1534                        eprintln!("error: {e}");
1535                        return 2;
1536                    }
1537                };
1538                let current_exe = match std::env::current_exe() {
1539                    Ok(p) => p,
1540                    Err(e) => {
1541                        eprintln!("error getting current executable: {e}");
1542                        return 2;
1543                    }
1544                };
1545                let configured_gate = gate;
1546                let passed_key = Some(crate::passed_trees::check_key(
1547                    &configured_gate,
1548                    &dispatch_cfg.env,
1549                ));
1550                let effective_gate = if comments == crate::config::CommentMode::Gate {
1551                    gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
1552                } else {
1553                    configured_gate
1554                };
1555                let mut warnings = Vec::new();
1556                if let Err(err_msg) = git_reset_hard(&worktree_dir, &pre_round_sha) {
1557                    let summary = build_error_summary(
1558                        &args.id,
1559                        &worktree_dir,
1560                        branch,
1561                        err_msg,
1562                        pass1.sandbox,
1563                        &log_path,
1564                        &report_path,
1565                        gate_source,
1566                        warnings,
1567                    );
1568                    return finish_summary(&summary, &root);
1569                }
1570                let impl_cfg = ImplementerConfig {
1571                    current_exe: &current_exe,
1572                    worktree_dir: &worktree_dir,
1573                    root: &root,
1574                    id: &args.id,
1575                    gate: &effective_gate,
1576                    env: &dispatch_cfg.env,
1577                    model: model.map(String::as_str),
1578                    max_seconds,
1579                    max_turns,
1580                    max_cost,
1581                    fold_budget,
1582                    sandbox: &args.sandbox,
1583                    network,
1584                    config_allow_read: &config_allow_read,
1585                    cli_allow_read: &args.allow_read,
1586                    pass_env: &args.pass_env,
1587                    research: false,
1588                    no_claim_check: args.no_claim_check,
1589                    left_out: &left_out,
1590                };
1591                let (fix_summary, round_report) = match execute_fix_round(
1592                    &root,
1593                    &start_path,
1594                    &impl_cfg,
1595                    &log_path,
1596                    &fix_report_path,
1597                    &fixround_path,
1598                    passed_key.as_deref(),
1599                    &task_content,
1600                    pre_round_sha,
1601                    fallbacks_sent,
1602                    concerns_sent,
1603                    round_started_at,
1604                    &mut warnings,
1605                ) {
1606                    Ok(res) => res,
1607                    Err(err_msg) => {
1608                        let summary = build_error_summary(
1609                            &args.id,
1610                            &worktree_dir,
1611                            branch,
1612                            err_msg,
1613                            pass1.sandbox,
1614                            &log_path,
1615                            &report_path,
1616                            gate_source,
1617                            warnings,
1618                        );
1619                        return finish_summary(&summary, &root);
1620                    }
1621                };
1622                let commits = git_commits_since(&worktree_dir, &base_sha);
1623                let changed_files = git_changed_files_since(&worktree_dir, &base_sha);
1624                let kept = fix_summary.kept;
1625                let summary = DispatchSummary {
1626                    id: args.id.clone(),
1627                    worktree: worktree_dir.display().to_string(),
1628                    branch,
1629                    outcome: "verified",
1630                    exit: exit_code("verified"),
1631                    error: pass1.error,
1632                    commits,
1633                    changed_files,
1634                    final_message: crate::fix_round::combined_final_message(
1635                        pass1.final_message,
1636                        round_report.final_message,
1637                        kept,
1638                    ),
1639                    turns: pass1.turns.saturating_add(round_report.turns),
1640                    gate_attempts: pass1.gate_attempts,
1641                    gate_failures: pass1.gate_failures,
1642                    cost_usd: crate::fix_round::sum_costs(pass1.cost_usd, round_report.cost_usd),
1643                    model: pass1.model.or(round_report.model),
1644                    seconds: pass1.seconds.saturating_add(round_report.seconds),
1645                    sandbox: pass1.sandbox,
1646                    log: log_path.display().to_string(),
1647                    report: report_path.display().to_string(),
1648                    gate_source,
1649                    research_report: None,
1650                    base_check_seconds: pass1.base_check_seconds,
1651                    warnings,
1652                    fix_round: Some(fix_summary),
1653                };
1654                return finish_summary(&summary, &root);
1655            }
1656        }
1657
1658        let branch_ref = format!("refs/heads/{branch}");
1659        let branch_out = Command::new("git")
1660            .args(["show-ref", "--verify", "--quiet", &branch_ref])
1661            .current_dir(&root)
1662            .output();
1663        let branch_exists = match branch_out {
1664            Ok(o) if o.status.success() => true,
1665            Ok(o) if o.status.code() == Some(1) => false,
1666            Ok(o) => {
1667                eprintln!(
1668                    "error: git show-ref --verify --quiet {branch_ref}: {}",
1669                    String::from_utf8_lossy(&o.stderr).trim()
1670                );
1671                return 2;
1672            }
1673            Err(e) => {
1674                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
1675                return 2;
1676            }
1677        };
1678
1679        if worktree_dir.exists() || branch_exists {
1680            match crate::clean::remove_finished_run(&root, &args.id) {
1681                Ok(Some(reason)) => {
1682                    replaced_earlier_run = true;
1683                    let secs =
1684                        match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
1685                            Ok(d) => d.as_secs(),
1686                            Err(e) => {
1687                                eprintln!("error: system clock before unix epoch: {e}");
1688                                return 2;
1689                            }
1690                        };
1691                    let archive_rel = format!(".wt/archive/{}-{secs}", args.id);
1692                    let archive_dir = root.join(&archive_rel);
1693                    if let Err(e) = std::fs::create_dir_all(&archive_dir) {
1694                        eprintln!("error: {}: {e}", archive_dir.display());
1695                        return 2;
1696                    }
1697                    for ext in [
1698                        "json",
1699                        "report.json",
1700                        "reported.json",
1701                        "start.json",
1702                        "verdict.json",
1703                        "checks.json",
1704                        "model-review.json",
1705                        "fixround.json",
1706                        "fix.report.json",
1707                        "log",
1708                    ] {
1709                        let file_name = format!("{}.{ext}", args.id);
1710                        let src = wt_parent.join(&file_name);
1711                        if src.exists() {
1712                            let dst = archive_dir.join(&file_name);
1713                            if let Err(e) = std::fs::rename(&src, &dst) {
1714                                eprintln!(
1715                                    "error: rename {} -> {}: {e}",
1716                                    src.display(),
1717                                    dst.display()
1718                                );
1719                                return 2;
1720                            }
1721                        }
1722                    }
1723                    eprintln!(
1724                        "dispatch: replaced the earlier run {} ({reason}); its records are in {archive_rel}/",
1725                        args.id
1726                    );
1727                }
1728                Ok(None) => {}
1729                Err(e) => {
1730                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
1731                    return 2;
1732                }
1733            }
1734        }
1735    } else if worktree_dir.exists() {
1736        eprintln!("error: {} already exists", worktree_dir.display());
1737        return 2;
1738    }
1739
1740    let fix_round_already_done = !replaced_earlier_run
1741        && matches!(
1742            existing_fixround,
1743            Some(crate::fix_round::FixRoundRecord::Done { .. })
1744        );
1745
1746    let started_at = std::time::SystemTime::now()
1747        .duration_since(std::time::UNIX_EPOCH)
1748        .map(|d| d.as_secs())
1749        .unwrap_or(0);
1750    let mut tags = args.tags.clone();
1751    if args.research {
1752        tags.push("research".to_string());
1753    }
1754    let session = crate::usage_log::session_from(
1755        std::env::var("BLYTE_SESSION").ok(),
1756        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
1757    );
1758    let start_path = wt_parent.join(format!("{}.start.json", args.id));
1759    let mut initial_start = serde_json::json!({
1760        "id": args.id,
1761        "pid": std::process::id(),
1762        "started_at": started_at,
1763        "starting": true,
1764        "tags": tags,
1765        "plan": args.plan,
1766        "plan_task": args.plan_task,
1767        "request": args.request,
1768        "surface": args.surface,
1769        "base": args.base,
1770    });
1771    if let Some(ref s) = session {
1772        initial_start["session"] = serde_json::json!(s);
1773    }
1774    if let Some(ref missing) = brief_missing {
1775        initial_start["research"] = serde_json::json!(true);
1776        initial_start["brief_missing"] = serde_json::json!(missing);
1777    }
1778    if let Err(err) = std::fs::create_dir_all(&wt_parent)
1779        .and_then(|()| write_start_record(&start_path, &initial_start))
1780    {
1781        eprintln!(
1782            "error: could not write the start record {}: {err}",
1783            start_path.display()
1784        );
1785        return 2;
1786    }
1787    let mut start_guard = StartRecordGuard {
1788        path: start_path.clone(),
1789        armed: true,
1790    };
1791
1792    if !args.research {
1793        crate::clean::spawn_background_clean(&root, Some(&args.id));
1794    }
1795
1796    let base_commit: Option<String> = if args.research {
1797        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
1798            eprintln!(
1799                "error creating scratch directory {}: {e}",
1800                worktree_dir.display()
1801            );
1802            return 2;
1803        }
1804        let init_out = Command::new("git")
1805            .args(["init", "-q"])
1806            .current_dir(&worktree_dir)
1807            .output();
1808        match init_out {
1809            Ok(o) if o.status.success() => {}
1810            Ok(o) => {
1811                eprintln!(
1812                    "error: git init failed: {}",
1813                    String::from_utf8_lossy(&o.stderr)
1814                );
1815                return 2;
1816            }
1817            Err(e) => {
1818                eprintln!("error: failed to execute git init: {e}");
1819                return 2;
1820            }
1821        }
1822        let commit_out = Command::new("git")
1823            .args([
1824                "-c",
1825                "user.name=blyte",
1826                "-c",
1827                "user.email=blyte@local",
1828                "commit",
1829                "-q",
1830                "--allow-empty",
1831                "-m",
1832                "research",
1833            ])
1834            .current_dir(&worktree_dir)
1835            .output();
1836        match commit_out {
1837            Ok(o) if o.status.success() => {}
1838            Ok(o) => {
1839                eprintln!(
1840                    "error: git commit failed: {}",
1841                    String::from_utf8_lossy(&o.stderr)
1842                );
1843                return 2;
1844            }
1845            Err(e) => {
1846                eprintln!("error: failed to execute git commit: {e}");
1847                return 2;
1848            }
1849        }
1850        None
1851    } else if !worktree_dir.exists() {
1852        let branch_exists = Command::new("git")
1853            .args([
1854                "rev-parse",
1855                "--verify",
1856                "--quiet",
1857                &format!("refs/heads/{branch}"),
1858            ])
1859            .current_dir(&root)
1860            .output()
1861            .map(|o| o.status.success())
1862            .unwrap_or(false);
1863        if branch_exists {
1864            eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
1865            return 2;
1866        }
1867        let base_commit = match resolve_base_commit(&start_dir, &args.base) {
1868            Ok(sha) => sha,
1869            Err(e) => {
1870                eprintln!("error: {e}");
1871                return 2;
1872            }
1873        };
1874        let add_out = Command::new("git")
1875            .args([
1876                "worktree",
1877                "add",
1878                "-b",
1879                &branch,
1880                worktree_dir.to_str().unwrap(),
1881                &base_commit,
1882            ])
1883            .current_dir(&root)
1884            .output();
1885        match add_out {
1886            Ok(o) if o.status.success() => {}
1887            Ok(o) => {
1888                eprintln!(
1889                    "error: git worktree add failed: {}",
1890                    String::from_utf8_lossy(&o.stderr)
1891                );
1892                return 2;
1893            }
1894            Err(e) => {
1895                eprintln!("error: failed to execute git worktree add: {e}");
1896                return 2;
1897            }
1898        }
1899        Some(base_commit)
1900    } else {
1901        let base_commit = match Command::new("git")
1902            .args([
1903                "rev-parse",
1904                "--verify",
1905                &format!("{}^{{commit}}", args.base),
1906            ])
1907            .current_dir(&start_dir)
1908            .output()
1909        {
1910            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1911            Ok(o) => {
1912                eprintln!(
1913                    "error: git rev-parse {} failed: {}",
1914                    args.base,
1915                    String::from_utf8_lossy(&o.stderr).trim()
1916                );
1917                return 2;
1918            }
1919            Err(e) => {
1920                eprintln!("error: failed to execute git rev-parse: {e}");
1921                return 2;
1922            }
1923        };
1924        let wt_head = match Command::new("git")
1925            .args([
1926                "-C",
1927                worktree_dir.to_str().unwrap(),
1928                "rev-parse",
1929                "--verify",
1930                "HEAD^{commit}",
1931            ])
1932            .output()
1933        {
1934            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1935            Ok(o) => {
1936                eprintln!(
1937                    "error: git -C {} rev-parse HEAD failed: {}",
1938                    worktree_dir.display(),
1939                    String::from_utf8_lossy(&o.stderr).trim()
1940                );
1941                return 2;
1942            }
1943            Err(e) => {
1944                eprintln!("error: failed to execute git rev-parse: {e}");
1945                return 2;
1946            }
1947        };
1948        let ancestor_out = Command::new("git")
1949            .args(["merge-base", "--is-ancestor", &base_commit, &wt_head])
1950            .current_dir(&root)
1951            .output();
1952        match ancestor_out {
1953            Ok(o) if o.status.success() => {}
1954            Ok(o) if o.status.code() == Some(1) => {
1955                let short_wt_head = &wt_head[..wt_head.len().min(7)];
1956                let short_base = &base_commit[..base_commit.len().min(7)];
1957                eprintln!(
1958                    "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.",
1959                    id = args.id,
1960                    base_name = args.base,
1961                );
1962                return 2;
1963            }
1964            Ok(o) => {
1965                eprintln!(
1966                    "error: git merge-base --is-ancestor failed: {}",
1967                    String::from_utf8_lossy(&o.stderr).trim()
1968                );
1969                return 2;
1970            }
1971            Err(e) => {
1972                eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
1973                return 2;
1974            }
1975        }
1976        Some(base_commit)
1977    };
1978
1979    // 2. Ensure .wt/ is in info/exclude
1980    let common_dir_raw = Command::new("git")
1981        .args(["rev-parse", "--git-common-dir"])
1982        .current_dir(&root)
1983        .output();
1984    let common_dir = if let Ok(out) = common_dir_raw {
1985        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
1986        if p.is_absolute() {
1987            p
1988        } else {
1989            root.join(p)
1990        }
1991    } else {
1992        root.join(".git")
1993    };
1994
1995    let exclude_path = common_dir.join("info").join("exclude");
1996    if let Some(parent) = exclude_path.parent() {
1997        let _ = std::fs::create_dir_all(parent);
1998    }
1999    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
2000    if !content.lines().any(|l| l.trim() == ".wt/") {
2001        let mut new_content = content;
2002        if !new_content.is_empty() && !new_content.ends_with('\n') {
2003            new_content.push('\n');
2004        }
2005        new_content.push_str(".wt/\n");
2006        let _ = std::fs::write(&exclude_path, new_content);
2007    }
2008
2009    // 3. Record base_sha
2010    let base_out = Command::new("git")
2011        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
2012        .output();
2013    let base_sha = match base_out {
2014        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
2015        _ => {
2016            eprintln!("error: could not resolve HEAD in worktree");
2017            return 2;
2018        }
2019    };
2020
2021    if !args.research {
2022        if let Some(ref setup_cmd) = dispatch_cfg.setup {
2023            let first_line = setup_cmd.lines().next().unwrap_or("");
2024            eprintln!("setup: {first_line}");
2025            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
2026            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
2027            if let Err(msg) = crate::setup::run_setup(
2028                setup_cmd,
2029                &worktree_dir,
2030                &main_checkout,
2031                &dispatch_cfg.env,
2032                &setup_log_path,
2033                crate::setup::SETUP_TIMEOUT,
2034            ) {
2035                let outcome = "blocked";
2036                let exit = exit_code(outcome);
2037                let first_line_err = msg.lines().next().unwrap_or("").to_string();
2038                let summary = DispatchSummary {
2039                    id: args.id.clone(),
2040                    worktree: worktree_dir.display().to_string(),
2041                    branch: branch.clone(),
2042                    outcome,
2043                    exit,
2044                    error: Some(first_line_err),
2045                    commits: Vec::new(),
2046                    changed_files: Vec::new(),
2047                    final_message: Some(msg),
2048                    turns: 0,
2049                    gate_attempts: 0,
2050                    gate_failures: Vec::new(),
2051                    cost_usd: None,
2052                    model: None,
2053                    seconds: 0,
2054                    sandbox: args.sandbox.clone(),
2055                    log: if setup_log_path.is_file() {
2056                        setup_log_path.display().to_string()
2057                    } else {
2058                        String::new()
2059                    },
2060                    report: "".to_string(),
2061                    gate_source,
2062                    research_report: None,
2063                    base_check_seconds: None,
2064                    warnings: Vec::new(),
2065                    fix_round: None,
2066                };
2067                return finish_summary(&summary, &root);
2068            }
2069        }
2070    }
2071
2072    // 4. Write task file and spawn child process
2073    let _ = std::fs::create_dir_all(&wt_parent);
2074    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
2075        eprintln!("error writing task file {}: {e}", task_md_path.display());
2076        return 2;
2077    }
2078
2079    let log_path = wt_parent.join(format!("{}.log", args.id));
2080    let summary_path = wt_parent.join(format!("{}.json", args.id));
2081    if summary_path.exists() {
2082        let _ = std::fs::remove_file(&summary_path);
2083    }
2084    let report_path = wt_parent.join(format!("{}.report.json", args.id));
2085    if report_path.exists() {
2086        let _ = std::fs::remove_file(&report_path);
2087    }
2088    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
2089    if research_report_path.exists() {
2090        let _ = std::fs::remove_file(&research_report_path);
2091    }
2092    let reported_marker_path = wt_parent.join(format!("{}.reported.json", args.id));
2093    if reported_marker_path.exists() {
2094        let _ = std::fs::remove_file(&reported_marker_path);
2095    }
2096
2097    let configured_gate = gate;
2098    let passed_key = (!args.research)
2099        .then(|| crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env));
2100    let (base_check_decision, base_tree) = match decide_base_check(
2101        &root,
2102        &worktree_dir,
2103        &base_sha,
2104        &configured_gate,
2105        &dispatch_cfg.env,
2106        args.research,
2107        args.no_base_check,
2108        dispatch_cfg.base_check,
2109        crate::passed_trees::now_secs(),
2110    ) {
2111        Ok(res) => res,
2112        Err(e) => {
2113            eprintln!("error: {e}");
2114            return 2;
2115        }
2116    };
2117    if base_check_decision == BaseCheckDecision::AlreadyPassed {
2118        eprintln!("base check: this commit's content already passed");
2119    }
2120
2121    let current_exe = match std::env::current_exe() {
2122        Ok(p) => p,
2123        Err(e) => {
2124            eprintln!("error getting current executable: {e}");
2125            return 2;
2126        }
2127    };
2128
2129    let gate = if !args.research && comments == crate::config::CommentMode::Gate {
2130        gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
2131    } else {
2132        configured_gate
2133    };
2134
2135    let mut base_wt_guard: Option<BaseWorktreeGuard> = None;
2136    let base_check_dir = if !args.research && base_check_decision == BaseCheckDecision::Run {
2137        let base_wt_dir = wt_parent.join(format!("{}.base", args.id));
2138        match BaseWorktreeGuard::create(&root, base_wt_dir.clone(), &base_sha) {
2139            Ok(guard) => {
2140                base_wt_guard = Some(guard);
2141                Some(base_wt_dir)
2142            }
2143            Err(e) => {
2144                eprintln!("error creating base check worktree: {e}");
2145                return 2;
2146            }
2147        }
2148    } else {
2149        None
2150    };
2151
2152    let research_sources = args
2153        .research
2154        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
2155    let task_prompt = if let Some(block) = &research_sources {
2156        wrap_research(&format!("{block}\n\n{task_content}"), &root)
2157    } else {
2158        let mut prompt = wrap_task(&task_content);
2159        if let Some(qs) = quick_steps(&gate) {
2160            prompt.push_str("\n\n");
2161            prompt.push_str(&qs);
2162        }
2163        prompt
2164    };
2165
2166    let impl_cfg = ImplementerConfig {
2167        current_exe: &current_exe,
2168        worktree_dir: &worktree_dir,
2169        root: &root,
2170        id: &args.id,
2171        gate: &gate,
2172        env: &dispatch_cfg.env,
2173        model: model.map(String::as_str),
2174        max_seconds,
2175        max_turns,
2176        max_cost,
2177        fold_budget,
2178        sandbox: &args.sandbox,
2179        network,
2180        config_allow_read: &config_allow_read,
2181        cli_allow_read: &args.allow_read,
2182        pass_env: &args.pass_env,
2183        research: args.research,
2184        no_claim_check: args.no_claim_check,
2185        left_out: &left_out,
2186    };
2187
2188    let comments_str = if args.research {
2189        "off"
2190    } else {
2191        match comments {
2192            crate::config::CommentMode::Gate => "gate",
2193            crate::config::CommentMode::Review => "review",
2194            crate::config::CommentMode::Off => "off",
2195        }
2196    };
2197    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
2198    if let Err(e) = run_implementer_pass(
2199        &impl_cfg,
2200        &log_path,
2201        None,
2202        &report_path,
2203        &task_prompt,
2204        base_check_dir.as_deref(),
2205        |pid| {
2206            start_guard.armed = false;
2207            let mut start_json = serde_json::json!({
2208                "id": args.id,
2209                "pid": pid,
2210                "started_at": started_at,
2211                "task_file": task_file_recorded,
2212                "gate": gate,
2213                "tags": tags,
2214                "env": env_names,
2215                "max_turns": max_turns,
2216                "max_seconds": max_seconds,
2217                "plan": args.plan,
2218                "plan_task": args.plan_task,
2219                "request": args.request,
2220                "surface": args.surface,
2221                "base": args.base,
2222                "base_sha": base_commit,
2223                "base_check": base_check_decision.as_json(),
2224                "comments": comments_str,
2225            });
2226            if let Some(ref session) = session {
2227                start_json["session"] = serde_json::json!(session);
2228            }
2229            if let Some(ref missing) = brief_missing {
2230                start_json["research"] = serde_json::json!(true);
2231                start_json["brief_missing"] = serde_json::json!(missing);
2232            }
2233            if !left_out.is_empty() {
2234                start_json["gate_left_out"] = serde_json::json!(left_out
2235                    .iter()
2236                    .map(|(command, reason)| serde_json::json!({
2237                        "command": command,
2238                        "reason": reason,
2239                    }))
2240                    .collect::<Vec<_>>());
2241            }
2242            if let Err(err) = write_start_record(&start_path, &start_json) {
2243                eprintln!(
2244                    "error: could not write the start record {}: {err}",
2245                    start_path.display()
2246                );
2247            }
2248        },
2249    ) {
2250        eprintln!("{e}");
2251        return 2;
2252    }
2253    drop(base_wt_guard);
2254
2255    let scratch_report = worktree_dir.join("report.md");
2256    if args.research {
2257        let is_non_empty = std::fs::metadata(&scratch_report)
2258            .map(|m| m.len() > 0)
2259            .unwrap_or(false);
2260        if is_non_empty {
2261            if let Err(err_msg) = copy_research_reports(
2262                &scratch_report,
2263                &research_report_path,
2264                args.report_to.as_deref(),
2265                research_sources.as_deref(),
2266            ) {
2267                if research_report_path.exists() {
2268                    if let Err(err) =
2269                        crate::provenance::mark_if_unverified(&research_report_path, "error", None)
2270                    {
2271                        eprintln!(
2272                            "error: could not mark {} as not verified: {err}",
2273                            research_report_path.display()
2274                        );
2275                    }
2276                }
2277                let summary = build_error_summary(
2278                    &args.id,
2279                    &worktree_dir,
2280                    branch,
2281                    err_msg,
2282                    args.sandbox.clone(),
2283                    &log_path,
2284                    &report_path,
2285                    gate_source,
2286                    Vec::new(),
2287                );
2288                return finish_summary(&summary, &root);
2289            }
2290        }
2291    }
2292
2293    // 5. Read report, commits and changed files
2294    let mut commits = git_commits_since(&worktree_dir, &base_sha);
2295    let mut changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2296
2297    let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
2298        Ok(r) => r,
2299        Err(err_msg) => pass_report_from_error(err_msg, &args.sandbox),
2300    };
2301
2302    let outcome = if args.research {
2303        match pass1.report_outcome.as_str() {
2304            "verified" => "verified",
2305            "gate_failed" => "gate_failed",
2306            "budget_exhausted" => "budget_exhausted",
2307            "blocked" => "blocked",
2308            _ => "error",
2309        }
2310    } else {
2311        dispatch_outcome(&pass1.report_outcome, commits.len())
2312    };
2313    let exit = exit_code(outcome);
2314
2315    if args.research {
2316        if research_report_path.exists() {
2317            if let Err(err) = crate::provenance::mark_if_unverified(
2318                &research_report_path,
2319                outcome,
2320                pass1.report_turns,
2321            ) {
2322                eprintln!(
2323                    "error: could not mark {} as not verified: {err}",
2324                    research_report_path.display()
2325                );
2326            }
2327        }
2328        if let Some(ref report_to) = args.report_to {
2329            if report_to.exists() {
2330                if let Err(err) =
2331                    crate::provenance::mark_if_unverified(report_to, outcome, pass1.report_turns)
2332                {
2333                    eprintln!(
2334                        "error: could not mark {} as not verified: {err}",
2335                        report_to.display()
2336                    );
2337                }
2338            }
2339        }
2340    }
2341
2342    let research_report = if args.research && research_report_path.exists() {
2343        Some(research_report_path.display().to_string())
2344    } else {
2345        None
2346    };
2347
2348    let mut warnings = record_passed_after_run(
2349        &root,
2350        &worktree_dir,
2351        args.research,
2352        base_check_decision,
2353        base_tree.as_deref(),
2354        passed_key.as_deref(),
2355        outcome,
2356        pass1.base_check_passed,
2357    );
2358    for warning in &warnings {
2359        eprintln!("warning: {warning}");
2360    }
2361
2362    let mut final_message = pass1.final_message;
2363    let mut turns = pass1.turns;
2364    let mut cost_usd = pass1.cost_usd;
2365    let mut seconds = pass1.seconds;
2366    let mut summary_model = pass1.model;
2367    let mut fix_round_summary: Option<crate::fix_round::FixRoundSummary> = None;
2368
2369    if outcome == "verified" && !args.research {
2370        let first_review = match crate::queue_actions::evaluate_verified_run(&root, &args.id) {
2371            Ok(mr) => mr,
2372            Err(err) => {
2373                eprintln!(
2374                    "warning: post-dispatch review check failed for {}: {err}",
2375                    args.id
2376                );
2377                None
2378            }
2379        };
2380
2381        if !fix_round_already_done
2382            && crate::fix_round::should_run(
2383                args.research,
2384                outcome,
2385                dispatch_cfg.fix_round,
2386                first_review.as_ref(),
2387            )
2388        {
2389            let review_ref = first_review.as_ref().unwrap();
2390            let pre_round_sha = match git_head_sha(&worktree_dir) {
2391                Ok(sha) => sha,
2392                Err(err_msg) => {
2393                    let summary = build_error_summary(
2394                        &args.id,
2395                        &worktree_dir,
2396                        branch,
2397                        err_msg,
2398                        pass1.sandbox,
2399                        &log_path,
2400                        &report_path,
2401                        gate_source,
2402                        warnings,
2403                    );
2404                    return finish_summary(&summary, &root);
2405                }
2406            };
2407            let fallbacks_sent = if crate::fix_round::confirmed_count(review_ref) > 0 {
2408                match crate::fix_round::collect_confirmed_fallbacks(
2409                    &root,
2410                    &args.id,
2411                    &worktree_dir,
2412                    review_ref,
2413                ) {
2414                    Ok(fbs) => fbs,
2415                    Err(err_msg) => {
2416                        let summary = build_error_summary(
2417                            &args.id,
2418                            &worktree_dir,
2419                            branch,
2420                            err_msg,
2421                            pass1.sandbox,
2422                            &log_path,
2423                            &report_path,
2424                            gate_source,
2425                            warnings,
2426                        );
2427                        return finish_summary(&summary, &root);
2428                    }
2429                }
2430            } else {
2431                Vec::new()
2432            };
2433            let concerns_sent = review_ref.concerns.clone();
2434            let round_started_at =
2435                match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
2436                    Ok(d) => d.as_secs(),
2437                    Err(e) => {
2438                        let summary = build_error_summary(
2439                            &args.id,
2440                            &worktree_dir,
2441                            branch,
2442                            format!("system clock before UNIX_EPOCH: {e}"),
2443                            pass1.sandbox,
2444                            &log_path,
2445                            &report_path,
2446                            gate_source,
2447                            warnings,
2448                        );
2449                        return finish_summary(&summary, &root);
2450                    }
2451                };
2452            let started_record = crate::fix_round::FixRoundRecord::Started {
2453                pre_round_sha: pre_round_sha.clone(),
2454                fallbacks_sent: fallbacks_sent.clone(),
2455                concerns_sent: concerns_sent.clone(),
2456                started_at: round_started_at,
2457            };
2458            if let Err(err_msg) = crate::fix_round::write_record(&fixround_path, &started_record) {
2459                let summary = build_error_summary(
2460                    &args.id,
2461                    &worktree_dir,
2462                    branch,
2463                    err_msg,
2464                    pass1.sandbox,
2465                    &log_path,
2466                    &report_path,
2467                    gate_source,
2468                    warnings,
2469                );
2470                return finish_summary(&summary, &root);
2471            }
2472
2473            let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
2474            match execute_fix_round(
2475                &root,
2476                &start_path,
2477                &impl_cfg,
2478                &log_path,
2479                &fix_report_path,
2480                &fixround_path,
2481                passed_key.as_deref(),
2482                &task_content,
2483                pre_round_sha,
2484                fallbacks_sent,
2485                concerns_sent,
2486                round_started_at,
2487                &mut warnings,
2488            ) {
2489                Ok((fix_sum, round_report)) => {
2490                    commits = git_commits_since(&worktree_dir, &base_sha);
2491                    changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2492                    turns = turns.saturating_add(round_report.turns);
2493                    cost_usd = crate::fix_round::sum_costs(cost_usd, round_report.cost_usd);
2494                    seconds = seconds.saturating_add(round_report.seconds);
2495                    summary_model = summary_model.or(round_report.model);
2496                    final_message = crate::fix_round::combined_final_message(
2497                        final_message,
2498                        round_report.final_message,
2499                        fix_sum.kept,
2500                    );
2501                    fix_round_summary = Some(fix_sum);
2502                }
2503                Err(err_msg) => {
2504                    let summary = build_error_summary(
2505                        &args.id,
2506                        &worktree_dir,
2507                        branch,
2508                        err_msg,
2509                        pass1.sandbox,
2510                        &log_path,
2511                        &report_path,
2512                        gate_source,
2513                        warnings,
2514                    );
2515                    return finish_summary(&summary, &root);
2516                }
2517            }
2518        }
2519    }
2520
2521    // 6. Print JSON summary
2522    let summary = DispatchSummary {
2523        id: args.id.clone(),
2524        worktree: worktree_dir.display().to_string(),
2525        branch,
2526        outcome,
2527        exit,
2528        error: pass1.error,
2529        commits,
2530        changed_files,
2531        final_message,
2532        turns,
2533        gate_attempts: pass1.gate_attempts,
2534        gate_failures: pass1.gate_failures,
2535        cost_usd,
2536        model: summary_model,
2537        seconds,
2538        sandbox: pass1.sandbox,
2539        log: log_path.display().to_string(),
2540        report: report_path.display().to_string(),
2541        gate_source,
2542        research_report,
2543        base_check_seconds: pass1.base_check_seconds,
2544        warnings,
2545        fix_round: fix_round_summary,
2546    };
2547
2548    finish_summary(&summary, &root)
2549}
2550
2551pub fn run_review(args: &ReviewArgs) -> i32 {
2552    let root = match crate::clean::find_repo_root() {
2553        Ok(r) => r,
2554        Err(e) => {
2555            eprintln!("error: {e}");
2556            return 2;
2557        }
2558    };
2559
2560    if args.notes.is_some() && args.verdict.is_none() {
2561        eprintln!("error: --notes requires --verdict");
2562        return 2;
2563    }
2564
2565    if let Some(v) = args.verdict {
2566        let ts = std::time::SystemTime::now()
2567            .duration_since(std::time::UNIX_EPOCH)
2568            .map(|d| d.as_secs())
2569            .unwrap_or(0);
2570        if let Err(e) = crate::queue_actions::record_verdict(
2571            &root,
2572            &args.id,
2573            v,
2574            args.notes.as_deref().unwrap_or(""),
2575            ts,
2576        ) {
2577            eprintln!("{e}");
2578            return 2;
2579        }
2580        let notify_outcome = crate::surface_notify::notify_runs_changed(&root, &args.id);
2581        crate::surface_notify::report(&notify_outcome, &mut std::io::stderr());
2582        println!("recorded verdict {} for {}", v.as_str(), args.id);
2583        return 0;
2584    }
2585
2586    let mut data = match crate::queue_actions::compute_review(&root, &args.id, args.diff) {
2587        Ok(d) => d,
2588        Err(e) => {
2589            eprintln!("error: {e}");
2590            return 2;
2591        }
2592    };
2593
2594    let stored_model_review = if args.model_review {
2595        None
2596    } else {
2597        match crate::queue_actions::read_stored_model_review(&root, &args.id) {
2598            Ok(mr) => mr,
2599            Err(e) => {
2600                eprintln!("error: {e}");
2601                return 2;
2602            }
2603        }
2604    };
2605    if !args.model_review {
2606        data.checks
2607            .flags
2608            .extend(crate::fallback_check::flags_for_review(
2609                &data.fallbacks,
2610                stored_model_review.as_ref(),
2611            ));
2612        if let Some(ref mr) = stored_model_review {
2613            if let Some(flag) = mr.flag() {
2614                if !data
2615                    .checks
2616                    .flags
2617                    .iter()
2618                    .any(|f| f.starts_with("model review"))
2619                {
2620                    data.checks.flags.push(flag);
2621                }
2622            }
2623        }
2624    }
2625
2626    if !args.model_review {
2627        if let Err(e) = crate::queue_actions::write_checks_file(
2628            &root,
2629            &args.id,
2630            &data.checks.flags,
2631            &data.fallbacks,
2632            stored_model_review.as_ref(),
2633        ) {
2634            eprintln!("{e}");
2635            return 2;
2636        }
2637    }
2638
2639    let crate::queue_actions::ReviewComputation {
2640        wt,
2641        wt_exists,
2642        is_research: _,
2643        base,
2644        task_text: _,
2645        changed_files: _,
2646        commits_out,
2647        files_out,
2648        tree_out,
2649        diff_out,
2650        hcmds,
2651        reads,
2652        report_val,
2653        quote_problems,
2654        claim_check,
2655        claim_check_skipped,
2656        mut checks,
2657        fallbacks,
2658    } = data;
2659
2660    println!("== checks");
2661    if checks.flags.is_empty() {
2662        println!("nothing flagged");
2663    } else {
2664        for flag in &checks.flags {
2665            println!("! {flag}");
2666        }
2667    }
2668
2669    println!("== commits");
2670    if !wt_exists {
2671        println!("(worktree removed)");
2672    } else if !commits_out.is_empty() {
2673        println!("{commits_out}");
2674    }
2675    println!("== files");
2676    if !wt_exists {
2677        println!("(worktree removed)");
2678    } else if !files_out.is_empty() {
2679        println!("{files_out}");
2680    }
2681    println!("== tree");
2682    if !wt_exists {
2683        println!("(worktree removed)");
2684    } else if tree_out.is_empty() {
2685        println!("(clean)");
2686    } else {
2687        println!("{tree_out}");
2688    }
2689    println!("== report");
2690    if let Some(ref v) = report_val {
2691        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
2692            println!("outcome: {outcome}");
2693        }
2694        let final_message = v.get("final_message").and_then(|x| x.as_str());
2695        if let Some(err) = v
2696            .get("error")
2697            .and_then(|x| x.as_str())
2698            .filter(|s| !s.trim().is_empty())
2699        {
2700            if !final_message.is_some_and(|m| m.contains(err)) {
2701                println!("error: {err}");
2702            }
2703        }
2704        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
2705            println!("turns: {turns}");
2706        }
2707        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
2708            println!("cost_usd: {cost}");
2709        }
2710        if let Some(msg) = final_message {
2711            println!("final_message: {msg}");
2712        }
2713        if let Some(ref problems) = quote_problems {
2714            if problems.is_empty() {
2715                println!("quote check: passed");
2716            } else {
2717                println!(
2718                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
2719                    problems.len()
2720                );
2721                for p in problems.iter().take(5) {
2722                    let cut: String = p.chars().take(200).collect();
2723                    println!("  {cut}");
2724                }
2725            }
2726        }
2727        if let Some(ref cc) = claim_check {
2728            println!(
2729                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
2730                cc.checked,
2731                cc.contradicted.len(),
2732                cc.not_enough_evidence,
2733                cc.parse_errors,
2734                cc.unchecked
2735            );
2736            for f in cc.contradicted.iter().take(5) {
2737                let cut: String = f.text.chars().take(200).collect();
2738                println!("  report.md:{}: {cut}", f.line);
2739                println!("    {}", f.reason);
2740            }
2741        }
2742        if let Some(ref skipped) = claim_check_skipped {
2743            println!("claim check skipped: {skipped}");
2744        }
2745    }
2746
2747    if let Some(ref v) = report_val {
2748        if let Some(failures) = v.get("gate_failures").and_then(|x| x.as_array()) {
2749            let entries: Vec<&str> = failures.iter().filter_map(|x| x.as_str()).collect();
2750            if let Some(last) = entries.last() {
2751                println!("== check failures");
2752                if entries.len() > 1 {
2753                    println!("({} failed attempts; the last one)", entries.len());
2754                }
2755                println!("{last}");
2756            }
2757        }
2758    }
2759
2760    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
2761    if research_report_file.exists() {
2762        println!("== research report");
2763        println!("{}", research_report_file.display());
2764        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
2765            for line in content.lines().take(40) {
2766                println!("{line}");
2767            }
2768        }
2769    }
2770
2771    if !hcmds.is_empty() {
2772        println!("== host commands (may have changed things outside the worktree)");
2773        for cmd in hcmds {
2774            println!("{cmd}");
2775        }
2776    }
2777    if !reads.is_empty() {
2778        println!("== reads outside the repository");
2779        for cmd in reads {
2780            println!("{cmd}");
2781        }
2782    }
2783
2784    if args.diff {
2785        println!("== diff");
2786        if !wt_exists {
2787            println!("(worktree removed)");
2788        } else if !diff_out.is_empty() {
2789            println!("{diff_out}");
2790        }
2791    }
2792
2793    if args.model_review && wt_exists {
2794        let mr = crate::model_review::run(&root, &args.id, &base, &wt);
2795        crate::model_review::print_result(&mr);
2796        checks.flags.extend(crate::fallback_check::flags_for_review(
2797            &fallbacks,
2798            Some(&mr),
2799        ));
2800        if let Some(flag) = mr.flag() {
2801            checks.flags.push(flag);
2802        }
2803        if let Err(e) = crate::queue_actions::write_checks_file(
2804            &root,
2805            &args.id,
2806            &checks.flags,
2807            &fallbacks,
2808            Some(&mr),
2809        ) {
2810            eprintln!("{e}");
2811            return 2;
2812        }
2813    } else if args.model_review {
2814        checks
2815            .flags
2816            .extend(crate::fallback_check::flags_for_review(&fallbacks, None));
2817        if let Err(e) = crate::queue_actions::write_checks_file(
2818            &root,
2819            &args.id,
2820            &checks.flags,
2821            &fallbacks,
2822            None,
2823        ) {
2824            eprintln!("{e}");
2825            return 2;
2826        }
2827    } else if let Some(ref mr) = stored_model_review {
2828        crate::model_review::print_result(mr);
2829    }
2830
2831    0
2832}
2833
2834const OUTSIDE_PATHS: &[&str] = &[
2835    "~/",
2836    "$HOME",
2837    "/Users/",
2838    "/home/",
2839    "/private/",
2840    "/var/",
2841    "/etc/",
2842    "/opt/",
2843    "/usr/",
2844];
2845
2846const CHANGE_WORDS: &[&str] = &[
2847    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
2848];
2849
2850fn contains_word(cmd: &str, word: &str) -> bool {
2851    let mut start = 0;
2852    while let Some(pos) = cmd[start..].find(word) {
2853        let abs_pos = start + pos;
2854        let before_ok = if abs_pos == 0 {
2855            true
2856        } else {
2857            let prev = cmd[..abs_pos].chars().next_back().unwrap();
2858            !prev.is_alphanumeric() && prev != '_' && prev != '-'
2859        };
2860        let after_pos = abs_pos + word.len();
2861        let after_ok = if after_pos >= cmd.len() {
2862            true
2863        } else {
2864            let next = cmd[after_pos..].chars().next().unwrap();
2865            !next.is_alphanumeric() && next != '_' && next != '-'
2866        };
2867        if before_ok && after_ok {
2868            return true;
2869        }
2870        start = abs_pos + word.len();
2871    }
2872    false
2873}
2874
2875fn has_non_dev_null_redirect(cmd: &str) -> bool {
2876    let chars: Vec<char> = cmd.chars().collect();
2877    let mut i = 0;
2878    while i < chars.len() {
2879        if chars[i] == '>' {
2880            while i < chars.len() && chars[i] == '>' {
2881                i += 1;
2882            }
2883            if i < chars.len() && chars[i] == '|' {
2884                i += 1;
2885            }
2886            while i < chars.len() && chars[i].is_whitespace() {
2887                i += 1;
2888            }
2889            if i >= chars.len() {
2890                break;
2891            }
2892            if chars[i] == '&'
2893                && i + 1 < chars.len()
2894                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
2895            {
2896                i += 1;
2897                continue;
2898            }
2899            let target_start = i;
2900            while i < chars.len()
2901                && !chars[i].is_whitespace()
2902                && chars[i] != ';'
2903                && chars[i] != '|'
2904                && chars[i] != '&'
2905                && chars[i] != ')'
2906            {
2907                i += 1;
2908            }
2909            let target: String = chars[target_start..i].iter().collect();
2910            let target = target.trim_matches(|c| c == '\'' || c == '"');
2911            if !target.is_empty() && target != "/dev/null" {
2912                return true;
2913            }
2914        } else {
2915            i += 1;
2916        }
2917    }
2918    false
2919}
2920
2921fn changes_something(cmd: &str) -> bool {
2922    for &word in CHANGE_WORDS {
2923        if contains_word(cmd, word) {
2924            return true;
2925        }
2926    }
2927    has_non_dev_null_redirect(cmd)
2928}
2929
2930fn is_host_command(cmd: &str) -> bool {
2931    if cmd.contains("git push")
2932        || cmd.contains("sudo ")
2933        || cmd.contains("cache clean")
2934        || cmd.contains("cache prune")
2935        || cmd.contains("brew ")
2936    {
2937        return true;
2938    }
2939
2940    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
2941    names_outside && changes_something(cmd)
2942}
2943
2944pub(crate) fn bash_commands(log: &str) -> Vec<String> {
2945    let cleaned = strip_ansi(log);
2946    let mut result = Vec::new();
2947    for line in cleaned.lines() {
2948        let trimmed = line.trim();
2949        if let Some(rest) = trimmed.strip_prefix("● bash ") {
2950            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
2951                let cmd = cmd.trim();
2952                if !cmd.is_empty() {
2953                    result.push(cmd.to_string());
2954                }
2955            }
2956        }
2957    }
2958    result
2959}
2960
2961pub fn host_commands(log: &str) -> Vec<String> {
2962    let mut result = Vec::new();
2963    for cmd in bash_commands(log) {
2964        if is_host_command(&cmd) && !result.iter().any(|c| c == &cmd) {
2965            result.push(cmd);
2966            if result.len() == 20 {
2967                break;
2968            }
2969        }
2970    }
2971    result
2972}
2973
2974const TERMINAL_READS: &[&str] = &[
2975    "herdr pane read",
2976    "tmux capture-pane",
2977    "screen -X hardcopy",
2978    "zellij action dump-screen",
2979    "wezterm cli get-text",
2980];
2981
2982const TOOL_CACHES: &[&str] = &[
2983    ".cargo",
2984    ".rustup",
2985    ".cache",
2986    ".npm",
2987    ".local",
2988    "Library/Caches",
2989    ".gradle",
2990    ".m2",
2991    "go",
2992];
2993
2994fn normalize_path(path: &Path) -> PathBuf {
2995    use std::path::Component;
2996    let mut out = PathBuf::new();
2997    for comp in path.components() {
2998        match comp {
2999            Component::ParentDir => {
3000                out.pop();
3001            }
3002            Component::CurDir => {}
3003            _ => out.push(comp),
3004        }
3005    }
3006    out
3007}
3008
3009fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
3010    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
3011        return true;
3012    }
3013
3014    for raw_word in cmd.split_whitespace() {
3015        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
3016        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
3017            Some(home.join(suffix))
3018        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
3019            Some(home.join(suffix))
3020        } else if word.starts_with('/') {
3021            Some(PathBuf::from(word))
3022        } else {
3023            None
3024        };
3025
3026        if let Some(path) = raw_path {
3027            let norm_path = normalize_path(&path);
3028            if !norm_path.starts_with(home) {
3029                continue;
3030            }
3031            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
3032            if under_allowed {
3033                continue;
3034            }
3035            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
3036            if under_cache {
3037                continue;
3038            }
3039            return true;
3040        }
3041    }
3042
3043    false
3044}
3045
3046pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
3047    let host_cmds = host_commands(log);
3048    let norm_home = normalize_path(home);
3049    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
3050    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
3051        .iter()
3052        .map(|c| normalize_path(&norm_home.join(c)))
3053        .collect();
3054
3055    let cleaned = strip_ansi(log);
3056    let mut result = Vec::new();
3057    for line in cleaned.lines() {
3058        let trimmed = line.trim();
3059        if let Some(rest) = trimmed.strip_prefix("● bash ") {
3060            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
3061                let cmd = cmd.trim();
3062                if host_cmds.iter().any(|c| c == cmd) {
3063                    continue;
3064                }
3065                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
3066                    && !result.iter().any(|c| c == cmd)
3067                {
3068                    result.push(cmd.to_string());
3069                    if result.len() == 20 {
3070                        break;
3071                    }
3072                }
3073            }
3074        }
3075    }
3076    result
3077}
3078
3079fn strip_ansi(s: &str) -> String {
3080    let mut out = String::with_capacity(s.len());
3081    let mut chars = s.chars().peekable();
3082    while let Some(c) = chars.next() {
3083        if c == '\x1b' && chars.peek() == Some(&'[') {
3084            chars.next();
3085            while let Some(&next_c) = chars.peek() {
3086                chars.next();
3087                if ('\x40'..='\x7e').contains(&next_c) {
3088                    break;
3089                }
3090                if next_c == '\n' || next_c == '\x1b' {
3091                    out.push(next_c);
3092                    break;
3093                }
3094            }
3095            continue;
3096        }
3097        out.push(c);
3098    }
3099    out
3100}
3101
3102#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3103pub struct LogProgress {
3104    pub turn: u32,
3105    pub last_tool: Option<String>,
3106    pub gate_attempts: u32,
3107    pub gate_passed: bool,
3108}
3109
3110pub fn parse_log(log: &str) -> LogProgress {
3111    let cleaned = strip_ansi(log);
3112    let mut turn: u32 = 0;
3113    let mut last_tool: Option<String> = None;
3114    let mut gate_attempts: u32 = 0;
3115    let mut gate_passed: bool = false;
3116
3117    for line in cleaned.lines() {
3118        if let Some(rest) = line.strip_prefix("[Turn ") {
3119            if let Some((n_str, _)) = rest.split_once(']') {
3120                if let Ok(n) = n_str.trim().parse::<u32>() {
3121                    turn = turn.max(n);
3122                }
3123            }
3124        }
3125
3126        if let Some(tool) = line.strip_prefix("● ") {
3127            let truncated = if tool.chars().count() > 200 {
3128                tool.chars().take(200).collect()
3129            } else {
3130                tool.to_string()
3131            };
3132            last_tool = Some(truncated);
3133        }
3134
3135        if line.starts_with("✓ Gate passed") {
3136            gate_attempts += 1;
3137            gate_passed = true;
3138        } else if line.starts_with("✗ Gate failed") {
3139            gate_attempts += 1;
3140            gate_passed = false;
3141        }
3142    }
3143
3144    LogProgress {
3145        turn,
3146        last_tool,
3147        gate_attempts,
3148        gate_passed,
3149    }
3150}
3151
3152#[derive(Debug, Serialize)]
3153pub struct StatusOutput {
3154    pub id: String,
3155    pub state: String,
3156    pub elapsed_s: u64,
3157    pub turn: u32,
3158    pub last_tool: Option<String>,
3159    pub gate_attempts: u32,
3160    pub gate_passed: bool,
3161    pub outcome: Option<String>,
3162    pub cost_usd: Option<f64>,
3163    pub final_message: Option<String>,
3164}
3165
3166pub fn run_status(id: &str, json: bool) -> i32 {
3167    let root = match crate::clean::find_repo_root() {
3168        Ok(r) => r,
3169        Err(e) => {
3170            eprintln!("error: {e}");
3171            return 2;
3172        }
3173    };
3174
3175    let start_path = root.join(".wt").join(format!("{id}.start.json"));
3176    let start_raw = match std::fs::read_to_string(&start_path) {
3177        Ok(s) => s,
3178        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
3179            eprintln!("no dispatch {id} here");
3180            return 2;
3181        }
3182        Err(e) => {
3183            eprintln!("error reading {}: {e}", start_path.display());
3184            return 2;
3185        }
3186    };
3187    let start_record: serde_json::Value = match serde_json::from_str(&start_raw) {
3188        Ok(v) => v,
3189        Err(e) => {
3190            eprintln!("error parsing {}: {e}", start_path.display());
3191            return 2;
3192        }
3193    };
3194
3195    let pid = start_record
3196        .get("pid")
3197        .and_then(|v| v.as_i64())
3198        .map(|v| v as libc::pid_t);
3199    let Some(started_at) = start_record.get("started_at").and_then(|v| v.as_u64()) else {
3200        eprintln!(
3201            "error: missing or invalid \"started_at\" in {}",
3202            start_path.display()
3203        );
3204        return 2;
3205    };
3206
3207    let is_alive = if let Some(pid) = pid {
3208        if pid > 0 {
3209            let ret = unsafe { libc::kill(pid, 0) };
3210            if ret == 0 {
3211                true
3212            } else {
3213                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
3214            }
3215        } else {
3216            false
3217        }
3218    } else {
3219        false
3220    };
3221
3222    let report_path = root.join(".wt").join(format!("{id}.report.json"));
3223    let report_json: Option<serde_json::Value> = match std::fs::read_to_string(&report_path) {
3224        Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
3225            Ok(v) if v.is_object() => Some(v),
3226            Ok(_) => {
3227                eprintln!(
3228                    "error parsing {}: expected a JSON object",
3229                    report_path.display()
3230                );
3231                return 2;
3232            }
3233            Err(e) => {
3234                eprintln!("error parsing {}: {e}", report_path.display());
3235                return 2;
3236            }
3237        },
3238        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
3239        Err(e) => {
3240            eprintln!("error reading {}: {e}", report_path.display());
3241            return 2;
3242        }
3243    };
3244
3245    let state = if report_json.is_some() {
3246        "finished"
3247    } else if is_alive {
3248        "running"
3249    } else {
3250        "dead"
3251    };
3252
3253    let now = std::time::SystemTime::now()
3254        .duration_since(std::time::UNIX_EPOCH)
3255        .map(|d| d.as_secs())
3256        .unwrap_or(0);
3257
3258    let (outcome, cost_usd, final_message, report_duration) = if let Some(ref v) = report_json {
3259        let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
3260        let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
3261        let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
3262            if s.chars().count() > 500 {
3263                s.chars().take(500).collect()
3264            } else {
3265                s.to_string()
3266            }
3267        });
3268        let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
3269        (outcome, cost_usd, final_message, duration)
3270    } else {
3271        (None, None, None, None)
3272    };
3273
3274    let elapsed_s = if state == "finished" {
3275        report_duration
3276            .map(|d| d.round() as u64)
3277            .unwrap_or_else(|| now.saturating_sub(started_at))
3278    } else {
3279        now.saturating_sub(started_at)
3280    };
3281
3282    let log_path = root.join(".wt").join(format!("{id}.log"));
3283    let log_content = match std::fs::read_to_string(&log_path) {
3284        Ok(s) => s,
3285        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3286        Err(e) => {
3287            eprintln!("error reading {}: {e}", log_path.display());
3288            return 2;
3289        }
3290    };
3291    let progress = parse_log(&log_content);
3292
3293    if json {
3294        let status_obj = StatusOutput {
3295            id: id.to_string(),
3296            state: state.to_string(),
3297            elapsed_s,
3298            turn: progress.turn,
3299            last_tool: progress.last_tool,
3300            gate_attempts: progress.gate_attempts,
3301            gate_passed: progress.gate_passed,
3302            outcome,
3303            cost_usd,
3304            final_message,
3305        };
3306        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
3307        println!("{json_str}");
3308    } else {
3309        println!("id: {id}");
3310        println!("state: {state}");
3311        println!("elapsed_s: {elapsed_s}");
3312        println!("turn: {}", progress.turn);
3313        println!(
3314            "last_tool: {}",
3315            progress.last_tool.as_deref().unwrap_or("none")
3316        );
3317        println!("gate_attempts: {}", progress.gate_attempts);
3318        println!("gate_passed: {}", progress.gate_passed);
3319        if state == "finished" {
3320            if let Some(ref o) = outcome {
3321                println!("outcome: {o}");
3322            }
3323            if let Some(c) = cost_usd {
3324                println!("cost_usd: {c}");
3325            }
3326            if let Some(ref msg) = final_message {
3327                println!("final_message: {msg}");
3328            }
3329        }
3330    }
3331
3332    match state {
3333        "running" | "finished" => 0,
3334        _ => 1,
3335    }
3336}
3337
3338pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
3339    let readable_canon: Vec<PathBuf> = readable
3340        .iter()
3341        .filter_map(|r| std::fs::canonicalize(r).ok())
3342        .collect();
3343    let mut out = Vec::new();
3344    for raw in text.split(|c: char| {
3345        c.is_whitespace()
3346            || matches!(
3347                c,
3348                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
3349            )
3350    }) {
3351        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
3352        if !trimmed.starts_with('/')
3353            || trimmed.starts_with("//")
3354            || trimmed.len() <= 1
3355            || trimmed == "/dev/null"
3356        {
3357            continue;
3358        }
3359        let p = Path::new(trimmed);
3360        let Ok(canon) = std::fs::canonicalize(p) else {
3361            continue;
3362        };
3363        if readable_canon.iter().any(|r| canon.starts_with(r))
3364            || is_system_path(p)
3365            || is_system_path(&canon)
3366        {
3367            continue;
3368        }
3369        let pb = PathBuf::from(trimmed);
3370        if !out.contains(&pb) {
3371            out.push(pb);
3372        }
3373    }
3374    out
3375}
3376
3377/// A path no research task means as code to read: the filesystem root, a top-level directory,
3378/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
3379fn is_system_path(p: &Path) -> bool {
3380    const SYSTEM: &[&str] = &[
3381        "/usr",
3382        "/bin",
3383        "/sbin",
3384        "/etc",
3385        "/dev",
3386        "/opt",
3387        "/System",
3388        "/Library",
3389        "/Applications",
3390        "/nix",
3391        "/proc",
3392        "/sys",
3393    ];
3394    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
3395}
3396
3397pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
3398    let mut count = 0;
3399    let mut paths = Vec::new();
3400    for line in log_content.lines() {
3401        if !line.contains("path escapes the workspace") {
3402            continue;
3403        }
3404        count += 1;
3405        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
3406            let after = after.trim_start();
3407            let after = after.split("\x1b[").next().unwrap_or(after);
3408            let path = after
3409                .split(". This run can read")
3410                .next()
3411                .unwrap_or(after)
3412                .trim();
3413            if !path.is_empty() && !paths.iter().any(|p| p == path) {
3414                paths.push(path.to_string());
3415            }
3416        }
3417    }
3418    (count, paths)
3419}
3420
3421#[cfg(test)]
3422mod tests {
3423    use super::*;
3424
3425    #[test]
3426    fn outside_reads_excludes_commands_in_host_commands() {
3427        let home = Path::new("/Users/u");
3428        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3429        // rm -rf ~/repos/other is a host command (names outside and changes something)
3430        // cat ~/repos/other is not a host command (only reads)
3431        let log = "\
3432● bash rm -rf ~/repos/other/file.py -> exit 0
3433● bash cat ~/repos/other/file.py -> exit 0
3434";
3435        assert_eq!(
3436            host_commands(log),
3437            vec!["rm -rf ~/repos/other/file.py".to_string()]
3438        );
3439        assert_eq!(
3440            outside_reads(log, &allowed, home),
3441            vec!["cat ~/repos/other/file.py".to_string()]
3442        );
3443    }
3444
3445    #[test]
3446    fn outside_reads_all_terminal_patterns() {
3447        let home = Path::new("/Users/u");
3448        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3449        let log = "\
3450● bash herdr pane read p1 -> exit 0
3451● bash tmux capture-pane -t 1 -> exit 0
3452● bash screen -X hardcopy /tmp/screen.log -> exit 0
3453● bash zellij action dump-screen /tmp/dump -> exit 0
3454● bash wezterm cli get-text --pane-id 1 -> exit 0
3455";
3456        let reads = outside_reads(log, &allowed, home);
3457        assert_eq!(
3458            reads,
3459            vec![
3460                "herdr pane read p1",
3461                "tmux capture-pane -t 1",
3462                "screen -X hardcopy /tmp/screen.log",
3463                "zellij action dump-screen /tmp/dump",
3464                "wezterm cli get-text --pane-id 1",
3465            ]
3466        );
3467    }
3468
3469    #[test]
3470    fn outside_reads_all_tool_caches_ignored() {
3471        let home = Path::new("/Users/u");
3472        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3473        let log = "\
3474● bash ls ~/.cargo/bin -> exit 0
3475● bash ls ~/.rustup/toolchains -> exit 0
3476● bash ls ~/.cache/pip -> exit 0
3477● bash ls ~/.npm/_cacache -> exit 0
3478● bash ls ~/.local/share -> exit 0
3479● bash ls ~/Library/Caches/com.apple -> exit 0
3480● bash ls ~/.gradle/caches -> exit 0
3481● bash ls ~/.m2/repository -> exit 0
3482● bash ls ~/go/pkg -> exit 0
3483";
3484        assert!(outside_reads(log, &allowed, home).is_empty());
3485    }
3486
3487    #[test]
3488    fn outside_reads_trailing_punctuations_stripped() {
3489        let home = Path::new("/Users/u");
3490        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3491        let log = "\
3492● bash ls ~/secret: -> exit 0
3493● bash ls ~/secret, -> exit 0
3494● bash (ls ~/secret) -> exit 0
3495● bash bash -c 'ls ~/secret' -> exit 0
3496● bash bash -c \"ls ~/secret\" -> exit 0
3497";
3498        let reads = outside_reads(log, &allowed, home);
3499        // Deduplicated, so only one instance of the command or distinct commands:
3500        assert_eq!(reads.len(), 5);
3501    }
3502
3503    #[test]
3504    fn outside_reads_caps_at_20_and_deduplicates() {
3505        let home = Path::new("/Users/u");
3506        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3507        let mut log = String::new();
3508        for i in 0..30 {
3509            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
3510        }
3511        // Duplicate the first one
3512        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
3513        let reads = outside_reads(&log, &allowed, home);
3514        assert_eq!(reads.len(), 20);
3515        assert_eq!(reads[0], "cat ~/secret/0.txt");
3516        assert_eq!(reads[19], "cat ~/secret/19.txt");
3517    }
3518
3519    fn sample_summary(id: &str, exit: i32) -> DispatchSummary {
3520        DispatchSummary {
3521            id: id.to_string(),
3522            worktree: "/tmp/wt".to_string(),
3523            branch: format!("wip/{id}"),
3524            outcome: if exit == 0 { "verified" } else { "gate_failed" },
3525            exit,
3526            error: None,
3527            commits: Vec::new(),
3528            changed_files: Vec::new(),
3529            final_message: Some("ok".to_string()),
3530            turns: 1,
3531            gate_attempts: 1,
3532            gate_failures: Vec::new(),
3533            cost_usd: Some(0.01),
3534            model: None,
3535            seconds: 1,
3536            sandbox: "off".to_string(),
3537            log: "/tmp/wt.log".to_string(),
3538            report: "/tmp/wt.report.json".to_string(),
3539            gate_source: "flag",
3540            research_report: None,
3541            base_check_seconds: None,
3542            warnings: Vec::new(),
3543            fix_round: None,
3544        }
3545    }
3546
3547    #[test]
3548    fn finish_summary_reports_error_when_wt_is_a_regular_file() {
3549        let d = tempfile::tempdir().unwrap();
3550        let wt_file = d.path().join(".wt");
3551        std::fs::write(&wt_file, "not a dir").unwrap();
3552
3553        let summary_ok = sample_summary("FC1", 0);
3554        let mut out_ok = Vec::new();
3555        let mut err_ok = Vec::new();
3556        let code_ok = finish_summary_with_writers(&summary_ok, d.path(), &mut out_ok, &mut err_ok);
3557        assert_eq!(code_ok, 1);
3558        let stderr_ok = String::from_utf8(err_ok).unwrap();
3559        let expected_path = wt_file.join("FC1.json");
3560        assert!(
3561            stderr_ok.contains("blyte: could not write"),
3562            "stderr: {stderr_ok}"
3563        );
3564        assert!(
3565            stderr_ok.contains(&expected_path.display().to_string()),
3566            "stderr: {stderr_ok}"
3567        );
3568        let parsed_ok: serde_json::Value = serde_json::from_slice(&out_ok).unwrap();
3569        assert_eq!(parsed_ok["id"], "FC1");
3570        assert_eq!(parsed_ok["exit"], 0);
3571
3572        let summary_fail = sample_summary("FC3", 3);
3573        let mut out_fail = Vec::new();
3574        let mut err_fail = Vec::new();
3575        let code_fail =
3576            finish_summary_with_writers(&summary_fail, d.path(), &mut out_fail, &mut err_fail);
3577        assert_eq!(code_fail, 3);
3578        let stderr_fail = String::from_utf8(err_fail).unwrap();
3579        assert!(
3580            stderr_fail.contains(&wt_file.join("FC3.json").display().to_string()),
3581            "stderr: {stderr_fail}"
3582        );
3583        let parsed_fail: serde_json::Value = serde_json::from_slice(&out_fail).unwrap();
3584        assert_eq!(parsed_fail["id"], "FC3");
3585        assert_eq!(parsed_fail["exit"], 3);
3586    }
3587
3588    #[test]
3589    fn resolve_max_cost_precedence() {
3590        assert_eq!(resolve_max_cost(None, None), 25.0);
3591        assert_eq!(resolve_max_cost(None, None), DEFAULT_MAX_COST_USD);
3592        assert_eq!(resolve_max_cost(None, Some(8.0)), 8.0);
3593        assert_eq!(resolve_max_cost(Some(3.0), Some(8.0)), 3.0);
3594        assert_eq!(resolve_max_cost(Some(3.0), None), 3.0);
3595    }
3596}