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