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