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