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