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 alive = match crate::clean::run_process_alive(&start_val) {
1701            Ok(a) => a,
1702            Err(e) => {
1703                eprintln!("error in {}: {e}", start_path.display());
1704                return 2;
1705            }
1706        };
1707        let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
1708            eprintln!("error: missing started_at in {}", start_path.display());
1709            return 2;
1710        };
1711        if alive {
1712            let finished_since_start = if summary_path.exists() {
1713                let meta = match std::fs::metadata(&summary_path) {
1714                    Ok(m) => m,
1715                    Err(e) => {
1716                        eprintln!("error reading metadata of {}: {e}", summary_path.display());
1717                        return 2;
1718                    }
1719                };
1720                let mtime = match meta.modified() {
1721                    Ok(t) => t,
1722                    Err(e) => {
1723                        eprintln!("error reading mtime of {}: {e}", summary_path.display());
1724                        return 2;
1725                    }
1726                };
1727                let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
1728                    Ok(d) => d.as_secs(),
1729                    Err(e) => {
1730                        eprintln!("error reading timestamp of {}: {e}", summary_path.display());
1731                        return 2;
1732                    }
1733                };
1734                mtime_secs >= started_at
1735            } else {
1736                false
1737            };
1738            if !finished_since_start {
1739                let pid_opt = start_val.get("pid").and_then(|v| v.as_i64());
1740                let dispatch_pid_opt = start_val.get("dispatch_pid").and_then(|v| v.as_i64());
1741                let live_pid = match (pid_opt, dispatch_pid_opt) {
1742                    (Some(p), _) if crate::clean::is_pid_alive(p) => p,
1743                    (_, Some(dp)) if crate::clean::is_pid_alive(dp) => dp,
1744                    (_, Some(dp)) => dp,
1745                    (Some(p), None) => p,
1746                    (None, None) => unreachable!(),
1747                };
1748                eprintln!(
1749                    "error: run {} is still running (pid {live_pid}). Wait for it to finish, or dispatch with a new ID.",
1750                    args.id
1751                );
1752                return 2;
1753            }
1754        }
1755    }
1756
1757    let mut replaced_reason: Option<String> = None;
1758    let mut need_worktree_add = false;
1759    let base_commit: Option<String> = if !args.research {
1760        if let Some(crate::fix_round::FixRoundRecord::Started {
1761            pre_round_sha,
1762            fallbacks_sent,
1763            concerns_sent,
1764            started_at: round_started_at,
1765        }) = existing_fixround.clone()
1766        {
1767            if !summary_path.exists() {
1768                if !worktree_dir.exists() {
1769                    eprintln!("error: missing worktree {}", worktree_dir.display());
1770                    return 2;
1771                }
1772                let base_sha = match read_start_base_sha(&start_path) {
1773                    Ok(sha) => sha,
1774                    Err(e) => {
1775                        eprintln!("error: {e}");
1776                        return 2;
1777                    }
1778                };
1779                let report_path = wt_parent.join(format!("{}.report.json", args.id));
1780                let log_path = wt_parent.join(format!("{}.log", args.id));
1781                let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
1782                let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
1783                    Ok(r) => r,
1784                    Err(e) => {
1785                        eprintln!("error: {e}");
1786                        return 2;
1787                    }
1788                };
1789                let current_exe = match std::env::current_exe() {
1790                    Ok(p) => p,
1791                    Err(e) => {
1792                        eprintln!("error getting current executable: {e}");
1793                        return 2;
1794                    }
1795                };
1796                let configured_gate = gate;
1797                let passed_key = Some(crate::passed_trees::check_key(
1798                    &configured_gate,
1799                    &dispatch_cfg.env,
1800                ));
1801                let effective_gate = if comments == crate::config::CommentMode::Gate {
1802                    gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
1803                } else {
1804                    configured_gate
1805                };
1806                let mut warnings = Vec::new();
1807                if let Err(err_msg) = git_reset_hard(&worktree_dir, &pre_round_sha) {
1808                    let summary = build_error_summary(
1809                        &args.id,
1810                        &worktree_dir,
1811                        branch,
1812                        err_msg,
1813                        pass1.sandbox,
1814                        &log_path,
1815                        &report_path,
1816                        gate_source,
1817                        warnings,
1818                    );
1819                    return finish_summary(&summary, &root);
1820                }
1821                let impl_cfg = ImplementerConfig {
1822                    current_exe: &current_exe,
1823                    worktree_dir: &worktree_dir,
1824                    root: &root,
1825                    id: &args.id,
1826                    gate: &effective_gate,
1827                    env: &dispatch_cfg.env,
1828                    model: model.map(String::as_str),
1829                    max_seconds,
1830                    max_turns,
1831                    max_cost,
1832                    fold_budget,
1833                    sandbox: &args.sandbox,
1834                    network,
1835                    config_allow_read: &config_allow_read,
1836                    cli_allow_read: &args.allow_read,
1837                    pass_env: &args.pass_env,
1838                    research: false,
1839                    no_claim_check: args.no_claim_check,
1840                    left_out: &left_out,
1841                    snapshot_dir: None,
1842                    snapshot_manifest: None,
1843                };
1844                let (fix_summary, round_report) = match execute_fix_round(
1845                    &root,
1846                    &start_path,
1847                    &impl_cfg,
1848                    &log_path,
1849                    &fix_report_path,
1850                    &fixround_path,
1851                    passed_key.as_deref(),
1852                    &task_content,
1853                    pre_round_sha,
1854                    fallbacks_sent,
1855                    concerns_sent,
1856                    round_started_at,
1857                    &mut warnings,
1858                ) {
1859                    Ok(res) => res,
1860                    Err(err_msg) => {
1861                        let summary = build_error_summary(
1862                            &args.id,
1863                            &worktree_dir,
1864                            branch,
1865                            err_msg,
1866                            pass1.sandbox,
1867                            &log_path,
1868                            &report_path,
1869                            gate_source,
1870                            warnings,
1871                        );
1872                        return finish_summary(&summary, &root);
1873                    }
1874                };
1875                let commits = git_commits_since(&worktree_dir, &base_sha);
1876                let changed_files = git_changed_files_since(&worktree_dir, &base_sha);
1877                let kept = fix_summary.kept;
1878                let summary = DispatchSummary {
1879                    id: args.id.clone(),
1880                    worktree: worktree_dir.display().to_string(),
1881                    branch,
1882                    outcome: "verified",
1883                    exit: exit_code("verified"),
1884                    error: pass1.error,
1885                    commits,
1886                    changed_files,
1887                    final_message: crate::fix_round::combined_final_message(
1888                        pass1.final_message,
1889                        round_report.final_message,
1890                        kept,
1891                    ),
1892                    turns: pass1.turns.saturating_add(round_report.turns),
1893                    gate_attempts: pass1.gate_attempts,
1894                    gate_failures: pass1.gate_failures,
1895                    cost_usd: crate::fix_round::sum_costs(pass1.cost_usd, round_report.cost_usd),
1896                    model: pass1.model.or(round_report.model),
1897                    seconds: pass1.seconds.saturating_add(round_report.seconds),
1898                    sandbox: pass1.sandbox,
1899                    log: log_path.display().to_string(),
1900                    report: report_path.display().to_string(),
1901                    gate_source,
1902                    research_report: None,
1903                    base_check_seconds: pass1.base_check_seconds,
1904                    warnings,
1905                    fix_round: Some(fix_summary),
1906                };
1907                return finish_summary(&summary, &root);
1908            }
1909        }
1910
1911        let resolved_base = match resolve_base_commit(&start_dir, &args.base) {
1912            Ok(sha) => sha,
1913            Err(e) => {
1914                eprintln!("error: {e}");
1915                return 2;
1916            }
1917        };
1918
1919        let branch_ref = format!("refs/heads/{branch}");
1920        let branch_out = Command::new("git")
1921            .args(["show-ref", "--verify", "--quiet", &branch_ref])
1922            .current_dir(&root)
1923            .output();
1924        let mut branch_exists = match branch_out {
1925            Ok(o) if o.status.success() => true,
1926            Ok(o) if o.status.code() == Some(1) => false,
1927            Ok(o) => {
1928                eprintln!(
1929                    "error: git show-ref --verify --quiet {branch_ref}: {}",
1930                    String::from_utf8_lossy(&o.stderr).trim()
1931                );
1932                return 2;
1933            }
1934            Err(e) => {
1935                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
1936                return 2;
1937            }
1938        };
1939
1940        if worktree_dir.exists() || branch_exists {
1941            match crate::clean::remove_finished_run(&root, &args.id) {
1942                Ok(Some(reason)) => {
1943                    replaced_reason = Some(reason);
1944                    branch_exists = false;
1945                }
1946                Ok(None) => {}
1947                Err(e) => {
1948                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
1949                    return 2;
1950                }
1951            }
1952        }
1953
1954        if !worktree_dir.exists() {
1955            if branch_exists {
1956                eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
1957                return 2;
1958            }
1959            need_worktree_add = true;
1960        } else {
1961            let wt_head = match Command::new("git")
1962                .args([
1963                    "-C",
1964                    worktree_dir.to_str().unwrap(),
1965                    "rev-parse",
1966                    "--verify",
1967                    "HEAD^{commit}",
1968                ])
1969                .output()
1970            {
1971                Ok(o) if o.status.success() => {
1972                    String::from_utf8_lossy(&o.stdout).trim().to_string()
1973                }
1974                Ok(o) => {
1975                    eprintln!(
1976                        "error: git -C {} rev-parse HEAD failed: {}",
1977                        worktree_dir.display(),
1978                        String::from_utf8_lossy(&o.stderr).trim()
1979                    );
1980                    return 2;
1981                }
1982                Err(e) => {
1983                    eprintln!("error: failed to execute git rev-parse: {e}");
1984                    return 2;
1985                }
1986            };
1987            let ancestor_out = Command::new("git")
1988                .args(["merge-base", "--is-ancestor", &resolved_base, &wt_head])
1989                .current_dir(&root)
1990                .output();
1991            match ancestor_out {
1992                Ok(o) if o.status.success() => {}
1993                Ok(o) if o.status.code() == Some(1) => {
1994                    let short_wt_head = &wt_head[..wt_head.len().min(7)];
1995                    let short_base = &resolved_base[..resolved_base.len().min(7)];
1996                    eprintln!(
1997                        "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.",
1998                        id = args.id,
1999                        base_name = args.base,
2000                    );
2001                    return 2;
2002                }
2003                Ok(o) => {
2004                    eprintln!(
2005                        "error: git merge-base --is-ancestor failed: {}",
2006                        String::from_utf8_lossy(&o.stderr).trim()
2007                    );
2008                    return 2;
2009                }
2010                Err(e) => {
2011                    eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
2012                    return 2;
2013                }
2014            }
2015        }
2016        Some(resolved_base)
2017    } else if worktree_dir.exists() {
2018        eprintln!("error: {} already exists", worktree_dir.display());
2019        return 2;
2020    } else {
2021        None
2022    };
2023
2024    let replaced_earlier_run = replaced_reason.is_some();
2025    let fix_round_already_done = !replaced_earlier_run
2026        && matches!(
2027            existing_fixround,
2028            Some(crate::fix_round::FixRoundRecord::Done { .. })
2029        );
2030
2031    let archive_rel = match archive_run_records(&root, &args.id) {
2032        Ok(rel) => rel,
2033        Err(e) => {
2034            eprintln!("error: {e}");
2035            return 2;
2036        }
2037    };
2038    if let Some(reason) = replaced_reason {
2039        if let Some(ref rel) = archive_rel {
2040            eprintln!(
2041                "dispatch: replaced the earlier run {} ({reason}); its records are in {rel}/",
2042                args.id
2043            );
2044        } else {
2045            eprintln!("dispatch: replaced the earlier run {} ({reason})", args.id);
2046        }
2047    }
2048
2049    let started_at = std::time::SystemTime::now()
2050        .duration_since(std::time::UNIX_EPOCH)
2051        .map(|d| d.as_secs())
2052        .unwrap_or(0);
2053    let mut tags = args.tags.clone();
2054    if args.research {
2055        tags.push("research".to_string());
2056    }
2057    let session = crate::usage_log::session_from(
2058        std::env::var("BLYTE_SESSION").ok(),
2059        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
2060    );
2061    let mut initial_start = serde_json::json!({
2062        "id": args.id,
2063        "pid": std::process::id(),
2064        "dispatch_pid": std::process::id(),
2065        "started_at": started_at,
2066        "starting": true,
2067        "tags": tags,
2068        "plan": args.plan,
2069        "plan_task": args.plan_task,
2070        "request": args.request,
2071        "surface": args.surface,
2072        "base": args.base,
2073    });
2074    if let Some(ref started_by) = args.started_by {
2075        initial_start["started_by"] = serde_json::json!(started_by);
2076    }
2077    if let Some(ref s) = session {
2078        initial_start["session"] = serde_json::json!(s);
2079    }
2080    if let Some(ref missing) = brief_missing {
2081        initial_start["research"] = serde_json::json!(true);
2082        initial_start["brief_missing"] = serde_json::json!(missing);
2083    }
2084    if let Err(err) = std::fs::create_dir_all(&wt_parent)
2085        .and_then(|()| write_start_record(&start_path, &initial_start))
2086    {
2087        eprintln!(
2088            "error: could not write the start record {}: {err}",
2089            start_path.display()
2090        );
2091        return 2;
2092    }
2093    let mut start_guard = StartRecordGuard {
2094        path: start_path.clone(),
2095        armed: true,
2096    };
2097
2098    if !args.research {
2099        crate::clean::spawn_background_clean(&root, Some(&args.id));
2100    }
2101
2102    if args.research {
2103        if let Err(e) = create_research_scratch_dir(&worktree_dir) {
2104            eprintln!("{e}");
2105            return 2;
2106        }
2107    } else if need_worktree_add {
2108        let base_ref = base_commit.as_deref().unwrap();
2109        let add_out = Command::new("git")
2110            .args([
2111                "worktree",
2112                "add",
2113                "-b",
2114                &branch,
2115                worktree_dir.to_str().unwrap(),
2116                base_ref,
2117            ])
2118            .current_dir(&root)
2119            .output();
2120        match add_out {
2121            Ok(o) if o.status.success() => {}
2122            Ok(o) => {
2123                eprintln!(
2124                    "error: git worktree add failed: {}",
2125                    String::from_utf8_lossy(&o.stderr)
2126                );
2127                return 2;
2128            }
2129            Err(e) => {
2130                eprintln!("error: failed to execute git worktree add: {e}");
2131                return 2;
2132            }
2133        }
2134    }
2135
2136    // 2. Ensure .wt/ is in info/exclude
2137    let common_dir_raw = Command::new("git")
2138        .args(["rev-parse", "--git-common-dir"])
2139        .current_dir(&root)
2140        .output();
2141    let common_dir = if let Ok(out) = common_dir_raw {
2142        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
2143        if p.is_absolute() {
2144            p
2145        } else {
2146            root.join(p)
2147        }
2148    } else {
2149        root.join(".git")
2150    };
2151
2152    let exclude_path = common_dir.join("info").join("exclude");
2153    if let Some(parent) = exclude_path.parent() {
2154        let _ = std::fs::create_dir_all(parent);
2155    }
2156    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
2157    if !content.lines().any(|l| l.trim() == ".wt/") {
2158        let mut new_content = content;
2159        if !new_content.is_empty() && !new_content.ends_with('\n') {
2160            new_content.push('\n');
2161        }
2162        new_content.push_str(".wt/\n");
2163        let _ = std::fs::write(&exclude_path, new_content);
2164    }
2165
2166    // 3. Record base_sha
2167    let base_out = Command::new("git")
2168        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
2169        .output();
2170    let base_sha = match base_out {
2171        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
2172        _ => {
2173            eprintln!("error: could not resolve HEAD in worktree");
2174            return 2;
2175        }
2176    };
2177
2178    if !args.research {
2179        if let Some(ref setup_cmd) = dispatch_cfg.setup {
2180            let first_line = setup_cmd.lines().next().unwrap_or("");
2181            eprintln!("setup: {first_line}");
2182            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
2183            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
2184            if let Err(msg) = crate::setup::run_setup(
2185                setup_cmd,
2186                &worktree_dir,
2187                &main_checkout,
2188                &dispatch_cfg.env,
2189                &setup_log_path,
2190                crate::setup::SETUP_TIMEOUT,
2191            ) {
2192                let outcome = "blocked";
2193                let exit = exit_code(outcome);
2194                let first_line_err = msg.lines().next().unwrap_or("").to_string();
2195                let summary = DispatchSummary {
2196                    id: args.id.clone(),
2197                    worktree: worktree_dir.display().to_string(),
2198                    branch: branch.clone(),
2199                    outcome,
2200                    exit,
2201                    error: Some(first_line_err),
2202                    commits: Vec::new(),
2203                    changed_files: Vec::new(),
2204                    final_message: Some(msg),
2205                    turns: 0,
2206                    gate_attempts: 0,
2207                    gate_failures: Vec::new(),
2208                    cost_usd: None,
2209                    model: None,
2210                    seconds: 0,
2211                    sandbox: args.sandbox.clone(),
2212                    log: if setup_log_path.is_file() {
2213                        setup_log_path.display().to_string()
2214                    } else {
2215                        String::new()
2216                    },
2217                    report: "".to_string(),
2218                    gate_source,
2219                    research_report: None,
2220                    base_check_seconds: None,
2221                    warnings: Vec::new(),
2222                    fix_round: None,
2223                };
2224                return finish_summary(&summary, &root);
2225            }
2226        }
2227    }
2228
2229    // 4. Write task file and spawn child process
2230    let _ = std::fs::create_dir_all(&wt_parent);
2231    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
2232        eprintln!("error writing task file {}: {e}", task_md_path.display());
2233        return 2;
2234    }
2235
2236    let log_path = wt_parent.join(format!("{}.log", args.id));
2237    let report_path = wt_parent.join(format!("{}.report.json", args.id));
2238    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
2239
2240    let configured_gate = gate;
2241    let passed_key = (!args.research)
2242        .then(|| crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env));
2243    let (base_check_decision, base_tree) = match decide_base_check(
2244        &root,
2245        &worktree_dir,
2246        &base_sha,
2247        &configured_gate,
2248        &dispatch_cfg.env,
2249        args.research,
2250        args.no_base_check,
2251        dispatch_cfg.base_check,
2252        crate::passed_trees::now_secs(),
2253    ) {
2254        Ok(res) => res,
2255        Err(e) => {
2256            eprintln!("error: {e}");
2257            return 2;
2258        }
2259    };
2260    if base_check_decision == BaseCheckDecision::AlreadyPassed {
2261        eprintln!("base check: this commit's content already passed");
2262    }
2263
2264    let current_exe = match std::env::current_exe() {
2265        Ok(p) => p,
2266        Err(e) => {
2267            eprintln!("error getting current executable: {e}");
2268            return 2;
2269        }
2270    };
2271
2272    let gate = if !args.research && comments == crate::config::CommentMode::Gate {
2273        gate_with_comment_step(&configured_gate, &comment_step(&current_exe, &base_sha))
2274    } else {
2275        configured_gate
2276    };
2277
2278    let mut base_wt_guard: Option<BaseWorktreeGuard> = None;
2279    let base_check_dir = if !args.research && base_check_decision == BaseCheckDecision::Run {
2280        let base_wt_dir = wt_parent.join(format!("{}.base", args.id));
2281        match BaseWorktreeGuard::create(&root, base_wt_dir.clone(), &base_sha) {
2282            Ok(guard) => {
2283                base_wt_guard = Some(guard);
2284                Some(base_wt_dir)
2285            }
2286            Err(e) => {
2287                eprintln!("error creating base check worktree: {e}");
2288                return 2;
2289            }
2290        }
2291    } else {
2292        None
2293    };
2294
2295    let research_sources = args
2296        .research
2297        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
2298    let task_prompt = if let Some(block) = &research_sources {
2299        wrap_research(&format!("{block}\n\n{task_content}"), &root)
2300    } else {
2301        let mut prompt = wrap_task(&task_content);
2302        if let Some(qs) = quick_steps(&gate) {
2303            prompt.push_str("\n\n");
2304            prompt.push_str(&qs);
2305        }
2306        prompt
2307    };
2308
2309    let impl_cfg = ImplementerConfig {
2310        current_exe: &current_exe,
2311        worktree_dir: &worktree_dir,
2312        root: &root,
2313        id: &args.id,
2314        gate: &gate,
2315        env: &dispatch_cfg.env,
2316        model: model.map(String::as_str),
2317        max_seconds,
2318        max_turns,
2319        max_cost,
2320        fold_budget,
2321        sandbox: &args.sandbox,
2322        network,
2323        config_allow_read: &config_allow_read,
2324        cli_allow_read: &args.allow_read,
2325        pass_env: &args.pass_env,
2326        research: args.research,
2327        no_claim_check: args.no_claim_check,
2328        left_out: &left_out,
2329        snapshot_dir: None,
2330        snapshot_manifest: None,
2331    };
2332
2333    let comments_str = if args.research {
2334        "off"
2335    } else {
2336        match comments {
2337            crate::config::CommentMode::Gate => "gate",
2338            crate::config::CommentMode::Review => "review",
2339            crate::config::CommentMode::Off => "off",
2340        }
2341    };
2342    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
2343    if let Err(e) = run_implementer_pass(
2344        &impl_cfg,
2345        &log_path,
2346        None,
2347        &report_path,
2348        &task_prompt,
2349        base_check_dir.as_deref(),
2350        |pid| {
2351            start_guard.armed = false;
2352            let mut start_json = serde_json::json!({
2353                "id": args.id,
2354                "pid": pid,
2355                "dispatch_pid": std::process::id(),
2356                "started_at": started_at,
2357                "task_file": task_file_recorded,
2358                "gate": gate,
2359                "tags": tags,
2360                "env": env_names,
2361                "max_turns": max_turns,
2362                "max_seconds": max_seconds,
2363                "plan": args.plan,
2364                "plan_task": args.plan_task,
2365                "request": args.request,
2366                "surface": args.surface,
2367                "base": args.base,
2368                "base_sha": base_commit,
2369                "base_check": base_check_decision.as_json(),
2370                "comments": comments_str,
2371            });
2372            if let Some(ref started_by) = args.started_by {
2373                start_json["started_by"] = serde_json::json!(started_by);
2374            }
2375            if let Some(ref session) = session {
2376                start_json["session"] = serde_json::json!(session);
2377            }
2378            if let Some(ref missing) = brief_missing {
2379                start_json["research"] = serde_json::json!(true);
2380                start_json["brief_missing"] = serde_json::json!(missing);
2381            }
2382            if !left_out.is_empty() {
2383                start_json["gate_left_out"] = serde_json::json!(left_out
2384                    .iter()
2385                    .map(|(command, reason)| serde_json::json!({
2386                        "command": command,
2387                        "reason": reason,
2388                    }))
2389                    .collect::<Vec<_>>());
2390            }
2391            if let Err(err) = write_start_record(&start_path, &start_json) {
2392                eprintln!(
2393                    "error: could not write the start record {}: {err}",
2394                    start_path.display()
2395                );
2396            }
2397        },
2398    ) {
2399        eprintln!("{e}");
2400        return 2;
2401    }
2402    drop(base_wt_guard);
2403
2404    let scratch_report = worktree_dir.join("report.md");
2405    if args.research {
2406        let is_non_empty = std::fs::metadata(&scratch_report)
2407            .map(|m| m.len() > 0)
2408            .unwrap_or(false);
2409        if is_non_empty {
2410            if let Err(err_msg) = copy_research_reports(
2411                &scratch_report,
2412                &research_report_path,
2413                args.report_to.as_deref(),
2414                research_sources.as_deref(),
2415            ) {
2416                if research_report_path.exists() {
2417                    if let Err(err) =
2418                        crate::provenance::mark_if_unverified(&research_report_path, "error", None)
2419                    {
2420                        eprintln!(
2421                            "error: could not mark {} as not verified: {err}",
2422                            research_report_path.display()
2423                        );
2424                    }
2425                }
2426                let summary = build_error_summary(
2427                    &args.id,
2428                    &worktree_dir,
2429                    branch,
2430                    err_msg,
2431                    args.sandbox.clone(),
2432                    &log_path,
2433                    &report_path,
2434                    gate_source,
2435                    Vec::new(),
2436                );
2437                return finish_summary(&summary, &root);
2438            }
2439        }
2440    }
2441
2442    // 5. Read report, commits and changed files
2443    let mut commits = git_commits_since(&worktree_dir, &base_sha);
2444    let mut changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2445
2446    let pass1 = match parse_pass_report(&report_path, &args.sandbox) {
2447        Ok(r) => r,
2448        Err(err_msg) => pass_report_from_error(err_msg, &args.sandbox),
2449    };
2450
2451    let outcome = if args.research {
2452        research_outcome(&pass1.report_outcome)
2453    } else {
2454        dispatch_outcome(&pass1.report_outcome, commits.len())
2455    };
2456    let exit = exit_code(outcome);
2457
2458    if args.research {
2459        if research_report_path.exists() {
2460            if let Err(err) = crate::provenance::mark_if_unverified(
2461                &research_report_path,
2462                outcome,
2463                pass1.report_turns,
2464            ) {
2465                eprintln!(
2466                    "error: could not mark {} as not verified: {err}",
2467                    research_report_path.display()
2468                );
2469            }
2470        }
2471        if let Some(ref report_to) = args.report_to {
2472            if report_to.exists() {
2473                if let Err(err) =
2474                    crate::provenance::mark_if_unverified(report_to, outcome, pass1.report_turns)
2475                {
2476                    eprintln!(
2477                        "error: could not mark {} as not verified: {err}",
2478                        report_to.display()
2479                    );
2480                }
2481            }
2482        }
2483    }
2484
2485    let research_report = if args.research && research_report_path.exists() {
2486        Some(research_report_path.display().to_string())
2487    } else {
2488        None
2489    };
2490
2491    let mut warnings = record_passed_after_run(
2492        &root,
2493        &worktree_dir,
2494        args.research,
2495        base_check_decision,
2496        base_tree.as_deref(),
2497        passed_key.as_deref(),
2498        outcome,
2499        pass1.base_check_passed,
2500    );
2501    for warning in &warnings {
2502        eprintln!("warning: {warning}");
2503    }
2504
2505    let mut final_message = pass1.final_message;
2506    let mut turns = pass1.turns;
2507    let mut cost_usd = pass1.cost_usd;
2508    let mut seconds = pass1.seconds;
2509    let mut summary_model = pass1.model;
2510    let mut fix_round_summary: Option<crate::fix_round::FixRoundSummary> = None;
2511
2512    if outcome == "verified" && !args.research {
2513        let first_review = match crate::queue_actions::evaluate_verified_run(&root, &args.id) {
2514            Ok(mr) => mr,
2515            Err(err) => {
2516                eprintln!(
2517                    "warning: post-dispatch review check failed for {}: {err}",
2518                    args.id
2519                );
2520                None
2521            }
2522        };
2523
2524        if !fix_round_already_done
2525            && crate::fix_round::should_run(
2526                args.research,
2527                outcome,
2528                dispatch_cfg.fix_round,
2529                first_review.as_ref(),
2530            )
2531        {
2532            let review_ref = first_review.as_ref().unwrap();
2533            let pre_round_sha = match git_head_sha(&worktree_dir) {
2534                Ok(sha) => sha,
2535                Err(err_msg) => {
2536                    let summary = build_error_summary(
2537                        &args.id,
2538                        &worktree_dir,
2539                        branch,
2540                        err_msg,
2541                        pass1.sandbox,
2542                        &log_path,
2543                        &report_path,
2544                        gate_source,
2545                        warnings,
2546                    );
2547                    return finish_summary(&summary, &root);
2548                }
2549            };
2550            let fallbacks_sent = if crate::fix_round::confirmed_count(review_ref) > 0 {
2551                match crate::fix_round::collect_confirmed_fallbacks(
2552                    &root,
2553                    &args.id,
2554                    &worktree_dir,
2555                    review_ref,
2556                ) {
2557                    Ok(fbs) => fbs,
2558                    Err(err_msg) => {
2559                        let summary = build_error_summary(
2560                            &args.id,
2561                            &worktree_dir,
2562                            branch,
2563                            err_msg,
2564                            pass1.sandbox,
2565                            &log_path,
2566                            &report_path,
2567                            gate_source,
2568                            warnings,
2569                        );
2570                        return finish_summary(&summary, &root);
2571                    }
2572                }
2573            } else {
2574                Vec::new()
2575            };
2576            let concerns_sent = review_ref.concerns.clone();
2577            let round_started_at =
2578                match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
2579                    Ok(d) => d.as_secs(),
2580                    Err(e) => {
2581                        let summary = build_error_summary(
2582                            &args.id,
2583                            &worktree_dir,
2584                            branch,
2585                            format!("system clock before UNIX_EPOCH: {e}"),
2586                            pass1.sandbox,
2587                            &log_path,
2588                            &report_path,
2589                            gate_source,
2590                            warnings,
2591                        );
2592                        return finish_summary(&summary, &root);
2593                    }
2594                };
2595            let started_record = crate::fix_round::FixRoundRecord::Started {
2596                pre_round_sha: pre_round_sha.clone(),
2597                fallbacks_sent: fallbacks_sent.clone(),
2598                concerns_sent: concerns_sent.clone(),
2599                started_at: round_started_at,
2600            };
2601            if let Err(err_msg) = crate::fix_round::write_record(&fixround_path, &started_record) {
2602                let summary = build_error_summary(
2603                    &args.id,
2604                    &worktree_dir,
2605                    branch,
2606                    err_msg,
2607                    pass1.sandbox,
2608                    &log_path,
2609                    &report_path,
2610                    gate_source,
2611                    warnings,
2612                );
2613                return finish_summary(&summary, &root);
2614            }
2615
2616            let fix_report_path = wt_parent.join(format!("{}.fix.report.json", args.id));
2617            match execute_fix_round(
2618                &root,
2619                &start_path,
2620                &impl_cfg,
2621                &log_path,
2622                &fix_report_path,
2623                &fixround_path,
2624                passed_key.as_deref(),
2625                &task_content,
2626                pre_round_sha,
2627                fallbacks_sent,
2628                concerns_sent,
2629                round_started_at,
2630                &mut warnings,
2631            ) {
2632                Ok((fix_sum, round_report)) => {
2633                    commits = git_commits_since(&worktree_dir, &base_sha);
2634                    changed_files = git_changed_files_since(&worktree_dir, &base_sha);
2635                    turns = turns.saturating_add(round_report.turns);
2636                    cost_usd = crate::fix_round::sum_costs(cost_usd, round_report.cost_usd);
2637                    seconds = seconds.saturating_add(round_report.seconds);
2638                    summary_model = summary_model.or(round_report.model);
2639                    final_message = crate::fix_round::combined_final_message(
2640                        final_message,
2641                        round_report.final_message,
2642                        fix_sum.kept,
2643                    );
2644                    fix_round_summary = Some(fix_sum);
2645                }
2646                Err(err_msg) => {
2647                    let summary = build_error_summary(
2648                        &args.id,
2649                        &worktree_dir,
2650                        branch,
2651                        err_msg,
2652                        pass1.sandbox,
2653                        &log_path,
2654                        &report_path,
2655                        gate_source,
2656                        warnings,
2657                    );
2658                    return finish_summary(&summary, &root);
2659                }
2660            }
2661        }
2662    }
2663
2664    // 6. Print JSON summary
2665    let summary = DispatchSummary {
2666        id: args.id.clone(),
2667        worktree: worktree_dir.display().to_string(),
2668        branch,
2669        outcome,
2670        exit,
2671        error: pass1.error,
2672        commits,
2673        changed_files,
2674        final_message,
2675        turns,
2676        gate_attempts: pass1.gate_attempts,
2677        gate_failures: pass1.gate_failures,
2678        cost_usd,
2679        model: summary_model,
2680        seconds,
2681        sandbox: pass1.sandbox,
2682        log: log_path.display().to_string(),
2683        report: report_path.display().to_string(),
2684        gate_source,
2685        research_report,
2686        base_check_seconds: pass1.base_check_seconds,
2687        warnings,
2688        fix_round: fix_round_summary,
2689    };
2690
2691    finish_summary(&summary, &root)
2692}
2693
2694pub fn run_review(args: &ReviewArgs) -> i32 {
2695    if let Ok(cwd) = std::env::current_dir() {
2696        if let Ok(out) = Command::new("git")
2697            .current_dir(&cwd)
2698            .args(["rev-parse", "--show-toplevel"])
2699            .output()
2700        {
2701            if !out.status.success() {
2702                return crate::in_place_review::review(args);
2703            }
2704        }
2705    }
2706
2707    let root = match crate::clean::find_repo_root() {
2708        Ok(r) => r,
2709        Err(e) => {
2710            eprintln!("error: {e}");
2711            return 2;
2712        }
2713    };
2714
2715    if args.notes.is_some() && args.verdict.is_none() {
2716        eprintln!("error: --notes requires --verdict");
2717        return 2;
2718    }
2719
2720    if let Some(v) = args.verdict {
2721        let ts = std::time::SystemTime::now()
2722            .duration_since(std::time::UNIX_EPOCH)
2723            .map(|d| d.as_secs())
2724            .unwrap_or(0);
2725        if let Err(e) = crate::queue_actions::record_verdict(
2726            &root,
2727            &args.id,
2728            v,
2729            args.notes.as_deref().unwrap_or(""),
2730            ts,
2731        ) {
2732            eprintln!("{e}");
2733            return 2;
2734        }
2735        let notify_outcome = crate::surface_notify::notify_runs_changed(&root, &args.id);
2736        crate::surface_notify::report(&notify_outcome, &mut std::io::stderr());
2737        println!("recorded verdict {} for {}", v.as_str(), args.id);
2738        return 0;
2739    }
2740
2741    let mut data = match crate::queue_actions::compute_review(&root, &args.id, args.diff) {
2742        Ok(d) => d,
2743        Err(e) => {
2744            eprintln!("error: {e}");
2745            return 2;
2746        }
2747    };
2748
2749    let stored_model_review = if args.model_review {
2750        None
2751    } else {
2752        match crate::queue_actions::read_stored_model_review(&root, &args.id) {
2753            Ok(mr) => mr,
2754            Err(e) => {
2755                eprintln!("error: {e}");
2756                return 2;
2757            }
2758        }
2759    };
2760    if !args.model_review {
2761        data.checks
2762            .flags
2763            .extend(crate::fallback_check::flags_for_review(
2764                &data.fallbacks,
2765                stored_model_review.as_ref(),
2766            ));
2767        if let Some(ref mr) = stored_model_review {
2768            if let Some(flag) = mr.flag() {
2769                if !data
2770                    .checks
2771                    .flags
2772                    .iter()
2773                    .any(|f| f.starts_with("model review"))
2774                {
2775                    data.checks.flags.push(flag);
2776                }
2777            }
2778        }
2779    }
2780
2781    if !args.model_review {
2782        if let Err(e) = crate::queue_actions::write_checks_file(
2783            &root,
2784            &args.id,
2785            &data.checks.flags,
2786            &data.fallbacks,
2787            stored_model_review.as_ref(),
2788        ) {
2789            eprintln!("{e}");
2790            return 2;
2791        }
2792    }
2793
2794    let crate::queue_actions::ReviewComputation {
2795        wt,
2796        wt_exists,
2797        is_research: _,
2798        base,
2799        task_text: _,
2800        changed_files: _,
2801        commits_out,
2802        files_out,
2803        tree_out,
2804        diff_out,
2805        hcmds,
2806        reads,
2807        report_val,
2808        quote_problems,
2809        claim_check,
2810        claim_check_skipped,
2811        mut checks,
2812        fallbacks,
2813    } = data;
2814
2815    println!("== checks");
2816    if checks.flags.is_empty() {
2817        println!("nothing flagged");
2818    } else {
2819        for flag in &checks.flags {
2820            println!("! {flag}");
2821        }
2822    }
2823
2824    println!("== commits");
2825    if !wt_exists {
2826        println!("(worktree removed)");
2827    } else if !commits_out.is_empty() {
2828        println!("{commits_out}");
2829    }
2830    println!("== files");
2831    if !wt_exists {
2832        println!("(worktree removed)");
2833    } else if !files_out.is_empty() {
2834        println!("{files_out}");
2835    }
2836    println!("== tree");
2837    if !wt_exists {
2838        println!("(worktree removed)");
2839    } else if tree_out.is_empty() {
2840        println!("(clean)");
2841    } else {
2842        println!("{tree_out}");
2843    }
2844    println!("== report");
2845    if let Some(ref v) = report_val {
2846        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
2847            println!("outcome: {outcome}");
2848        }
2849        let final_message = v.get("final_message").and_then(|x| x.as_str());
2850        if let Some(err) = v
2851            .get("error")
2852            .and_then(|x| x.as_str())
2853            .filter(|s| !s.trim().is_empty())
2854        {
2855            if !final_message.is_some_and(|m| m.contains(err)) {
2856                println!("error: {err}");
2857            }
2858        }
2859        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
2860            println!("turns: {turns}");
2861        }
2862        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
2863            println!("cost_usd: {cost}");
2864        }
2865        if let Some(msg) = final_message {
2866            println!("final_message: {msg}");
2867        }
2868        if let Some(ref problems) = quote_problems {
2869            if problems.is_empty() {
2870                println!("quote check: passed");
2871            } else {
2872                println!(
2873                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
2874                    problems.len()
2875                );
2876                for p in problems.iter().take(5) {
2877                    let cut: String = p.chars().take(200).collect();
2878                    println!("  {cut}");
2879                }
2880            }
2881        }
2882        if let Some(ref cc) = claim_check {
2883            println!(
2884                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
2885                cc.checked,
2886                cc.contradicted.len(),
2887                cc.not_enough_evidence,
2888                cc.parse_errors,
2889                cc.unchecked
2890            );
2891            for f in cc.contradicted.iter().take(5) {
2892                let cut: String = f.text.chars().take(200).collect();
2893                println!("  report.md:{}: {cut}", f.line);
2894                println!("    {}", f.reason);
2895            }
2896        }
2897        if let Some(ref skipped) = claim_check_skipped {
2898            println!("claim check skipped: {skipped}");
2899        }
2900    }
2901
2902    if let Some(ref v) = report_val {
2903        if let Some(failures) = v.get("gate_failures").and_then(|x| x.as_array()) {
2904            let entries: Vec<&str> = failures.iter().filter_map(|x| x.as_str()).collect();
2905            if let Some(last) = entries.last() {
2906                println!("== check failures");
2907                if entries.len() > 1 {
2908                    println!("({} failed attempts; the last one)", entries.len());
2909                }
2910                println!("{last}");
2911            }
2912        }
2913    }
2914
2915    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
2916    if research_report_file.exists() {
2917        println!("== research report");
2918        println!("{}", research_report_file.display());
2919        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
2920            for line in content.lines().take(40) {
2921                println!("{line}");
2922            }
2923        }
2924    }
2925
2926    if !hcmds.is_empty() {
2927        println!("== host commands (may have changed things outside the worktree)");
2928        for cmd in hcmds {
2929            println!("{cmd}");
2930        }
2931    }
2932    if !reads.is_empty() {
2933        println!("== reads outside the repository");
2934        for cmd in reads {
2935            println!("{cmd}");
2936        }
2937    }
2938
2939    if args.diff {
2940        println!("== diff");
2941        if !wt_exists {
2942            println!("(worktree removed)");
2943        } else if !diff_out.is_empty() {
2944            println!("{diff_out}");
2945        }
2946    }
2947
2948    if args.model_review && wt_exists {
2949        let mr = crate::model_review::run(&root, &args.id, &base, &wt);
2950        crate::model_review::print_result(&mr);
2951        checks.flags.extend(crate::fallback_check::flags_for_review(
2952            &fallbacks,
2953            Some(&mr),
2954        ));
2955        if let Some(flag) = mr.flag() {
2956            checks.flags.push(flag);
2957        }
2958        if let Err(e) = crate::queue_actions::write_checks_file(
2959            &root,
2960            &args.id,
2961            &checks.flags,
2962            &fallbacks,
2963            Some(&mr),
2964        ) {
2965            eprintln!("{e}");
2966            return 2;
2967        }
2968    } else if args.model_review {
2969        checks
2970            .flags
2971            .extend(crate::fallback_check::flags_for_review(&fallbacks, None));
2972        if let Err(e) = crate::queue_actions::write_checks_file(
2973            &root,
2974            &args.id,
2975            &checks.flags,
2976            &fallbacks,
2977            None,
2978        ) {
2979            eprintln!("{e}");
2980            return 2;
2981        }
2982    } else if let Some(ref mr) = stored_model_review {
2983        crate::model_review::print_result(mr);
2984    }
2985
2986    0
2987}
2988
2989const OUTSIDE_PATHS: &[&str] = &[
2990    "~/",
2991    "$HOME",
2992    "/Users/",
2993    "/home/",
2994    "/private/",
2995    "/var/",
2996    "/etc/",
2997    "/opt/",
2998    "/usr/",
2999];
3000
3001const CHANGE_WORDS: &[&str] = &[
3002    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
3003];
3004
3005fn contains_word(cmd: &str, word: &str) -> bool {
3006    let mut start = 0;
3007    while let Some(pos) = cmd[start..].find(word) {
3008        let abs_pos = start + pos;
3009        let before_ok = if abs_pos == 0 {
3010            true
3011        } else {
3012            let prev = cmd[..abs_pos].chars().next_back().unwrap();
3013            !prev.is_alphanumeric() && prev != '_' && prev != '-'
3014        };
3015        let after_pos = abs_pos + word.len();
3016        let after_ok = if after_pos >= cmd.len() {
3017            true
3018        } else {
3019            let next = cmd[after_pos..].chars().next().unwrap();
3020            !next.is_alphanumeric() && next != '_' && next != '-'
3021        };
3022        if before_ok && after_ok {
3023            return true;
3024        }
3025        start = abs_pos + word.len();
3026    }
3027    false
3028}
3029
3030fn has_non_dev_null_redirect(cmd: &str) -> bool {
3031    let chars: Vec<char> = cmd.chars().collect();
3032    let mut i = 0;
3033    while i < chars.len() {
3034        if chars[i] == '>' {
3035            while i < chars.len() && chars[i] == '>' {
3036                i += 1;
3037            }
3038            if i < chars.len() && chars[i] == '|' {
3039                i += 1;
3040            }
3041            while i < chars.len() && chars[i].is_whitespace() {
3042                i += 1;
3043            }
3044            if i >= chars.len() {
3045                break;
3046            }
3047            if chars[i] == '&'
3048                && i + 1 < chars.len()
3049                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
3050            {
3051                i += 1;
3052                continue;
3053            }
3054            let target_start = i;
3055            while i < chars.len()
3056                && !chars[i].is_whitespace()
3057                && chars[i] != ';'
3058                && chars[i] != '|'
3059                && chars[i] != '&'
3060                && chars[i] != ')'
3061            {
3062                i += 1;
3063            }
3064            let target: String = chars[target_start..i].iter().collect();
3065            let target = target.trim_matches(|c| c == '\'' || c == '"');
3066            if !target.is_empty() && target != "/dev/null" {
3067                return true;
3068            }
3069        } else {
3070            i += 1;
3071        }
3072    }
3073    false
3074}
3075
3076fn changes_something(cmd: &str) -> bool {
3077    for &word in CHANGE_WORDS {
3078        if contains_word(cmd, word) {
3079            return true;
3080        }
3081    }
3082    has_non_dev_null_redirect(cmd)
3083}
3084
3085fn is_host_command(cmd: &str) -> bool {
3086    if cmd.contains("git push")
3087        || cmd.contains("sudo ")
3088        || cmd.contains("cache clean")
3089        || cmd.contains("cache prune")
3090        || cmd.contains("brew ")
3091    {
3092        return true;
3093    }
3094
3095    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
3096    names_outside && changes_something(cmd)
3097}
3098
3099pub(crate) fn bash_commands(log: &str) -> Vec<String> {
3100    let cleaned = strip_ansi(log);
3101    let mut result = Vec::new();
3102    for line in cleaned.lines() {
3103        let trimmed = line.trim();
3104        if let Some(rest) = trimmed.strip_prefix("● bash ") {
3105            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
3106                let cmd = cmd.trim();
3107                if !cmd.is_empty() {
3108                    result.push(cmd.to_string());
3109                }
3110            }
3111        }
3112    }
3113    result
3114}
3115
3116pub fn host_commands(log: &str) -> Vec<String> {
3117    let mut result = Vec::new();
3118    for cmd in bash_commands(log) {
3119        if is_host_command(&cmd) && !result.iter().any(|c| c == &cmd) {
3120            result.push(cmd);
3121            if result.len() == 20 {
3122                break;
3123            }
3124        }
3125    }
3126    result
3127}
3128
3129const TERMINAL_READS: &[&str] = &[
3130    "herdr pane read",
3131    "tmux capture-pane",
3132    "screen -X hardcopy",
3133    "zellij action dump-screen",
3134    "wezterm cli get-text",
3135];
3136
3137const TOOL_CACHES: &[&str] = &[
3138    ".cargo",
3139    ".rustup",
3140    ".cache",
3141    ".npm",
3142    ".local",
3143    "Library/Caches",
3144    ".gradle",
3145    ".m2",
3146    "go",
3147];
3148
3149fn normalize_path(path: &Path) -> PathBuf {
3150    use std::path::Component;
3151    let mut out = PathBuf::new();
3152    for comp in path.components() {
3153        match comp {
3154            Component::ParentDir => {
3155                out.pop();
3156            }
3157            Component::CurDir => {}
3158            _ => out.push(comp),
3159        }
3160    }
3161    out
3162}
3163
3164fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
3165    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
3166        return true;
3167    }
3168
3169    for raw_word in cmd.split_whitespace() {
3170        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
3171        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
3172            Some(home.join(suffix))
3173        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
3174            Some(home.join(suffix))
3175        } else if word.starts_with('/') {
3176            Some(PathBuf::from(word))
3177        } else {
3178            None
3179        };
3180
3181        if let Some(path) = raw_path {
3182            let norm_path = normalize_path(&path);
3183            if !norm_path.starts_with(home) {
3184                continue;
3185            }
3186            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
3187            if under_allowed {
3188                continue;
3189            }
3190            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
3191            if under_cache {
3192                continue;
3193            }
3194            return true;
3195        }
3196    }
3197
3198    false
3199}
3200
3201pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
3202    let host_cmds = host_commands(log);
3203    let norm_home = normalize_path(home);
3204    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
3205    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
3206        .iter()
3207        .map(|c| normalize_path(&norm_home.join(c)))
3208        .collect();
3209
3210    let cleaned = strip_ansi(log);
3211    let mut result = Vec::new();
3212    for line in cleaned.lines() {
3213        let trimmed = line.trim();
3214        if let Some(rest) = trimmed.strip_prefix("● bash ") {
3215            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
3216                let cmd = cmd.trim();
3217                if host_cmds.iter().any(|c| c == cmd) {
3218                    continue;
3219                }
3220                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
3221                    && !result.iter().any(|c| c == cmd)
3222                {
3223                    result.push(cmd.to_string());
3224                    if result.len() == 20 {
3225                        break;
3226                    }
3227                }
3228            }
3229        }
3230    }
3231    result
3232}
3233
3234fn strip_ansi(s: &str) -> String {
3235    let mut out = String::with_capacity(s.len());
3236    let mut chars = s.chars().peekable();
3237    while let Some(c) = chars.next() {
3238        if c == '\x1b' && chars.peek() == Some(&'[') {
3239            chars.next();
3240            while let Some(&next_c) = chars.peek() {
3241                chars.next();
3242                if ('\x40'..='\x7e').contains(&next_c) {
3243                    break;
3244                }
3245                if next_c == '\n' || next_c == '\x1b' {
3246                    out.push(next_c);
3247                    break;
3248                }
3249            }
3250            continue;
3251        }
3252        out.push(c);
3253    }
3254    out
3255}
3256
3257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
3258pub struct LogProgress {
3259    pub turn: u32,
3260    pub last_tool: Option<String>,
3261    pub gate_attempts: u32,
3262    pub gate_passed: bool,
3263}
3264
3265pub fn parse_log(log: &str) -> LogProgress {
3266    let cleaned = strip_ansi(log);
3267    let mut turn: u32 = 0;
3268    let mut last_tool: Option<String> = None;
3269    let mut gate_attempts: u32 = 0;
3270    let mut gate_passed: bool = false;
3271
3272    for line in cleaned.lines() {
3273        if let Some(rest) = line.strip_prefix("[Turn ") {
3274            if let Some((n_str, _)) = rest.split_once(']') {
3275                if let Ok(n) = n_str.trim().parse::<u32>() {
3276                    turn = turn.max(n);
3277                }
3278            }
3279        }
3280
3281        if let Some(tool) = line.strip_prefix("● ") {
3282            let truncated = if tool.chars().count() > 200 {
3283                tool.chars().take(200).collect()
3284            } else {
3285                tool.to_string()
3286            };
3287            last_tool = Some(truncated);
3288        }
3289
3290        if line.starts_with("✓ Gate passed") {
3291            gate_attempts += 1;
3292            gate_passed = true;
3293        } else if line.starts_with("✗ Gate failed") {
3294            gate_attempts += 1;
3295            gate_passed = false;
3296        }
3297    }
3298
3299    LogProgress {
3300        turn,
3301        last_tool,
3302        gate_attempts,
3303        gate_passed,
3304    }
3305}
3306
3307#[derive(Debug, Serialize)]
3308pub struct StatusOutput {
3309    pub id: String,
3310    pub state: String,
3311    #[serde(skip_serializing_if = "Option::is_none")]
3312    pub phase: Option<String>,
3313    pub elapsed_s: u64,
3314    pub turn: u32,
3315    pub last_tool: Option<String>,
3316    pub gate_attempts: u32,
3317    pub gate_passed: bool,
3318    pub outcome: Option<String>,
3319    pub cost_usd: Option<f64>,
3320    pub final_message: Option<String>,
3321}
3322
3323pub fn run_status(id: &str, json: bool) -> i32 {
3324    let cwd = match std::env::current_dir() {
3325        Ok(d) => d,
3326        Err(e) => {
3327            eprintln!("error: {e}");
3328            return 2;
3329        }
3330    };
3331    let records_dir = match crate::dispatch_in_place::records_dir_for(&cwd) {
3332        Ok(d) => d,
3333        Err(e) => {
3334            eprintln!("error: {e}");
3335            return 2;
3336        }
3337    };
3338
3339    let start_path = records_dir.join(format!("{id}.start.json"));
3340    let start_raw = match std::fs::read_to_string(&start_path) {
3341        Ok(s) => s,
3342        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
3343            eprintln!("no dispatch {id} here");
3344            return 2;
3345        }
3346        Err(e) => {
3347            eprintln!("error reading {}: {e}", start_path.display());
3348            return 2;
3349        }
3350    };
3351    let start_record: serde_json::Value = match serde_json::from_str(&start_raw) {
3352        Ok(v) => v,
3353        Err(e) => {
3354            eprintln!("error parsing {}: {e}", start_path.display());
3355            return 2;
3356        }
3357    };
3358
3359    let is_alive = match crate::clean::run_process_alive(&start_record) {
3360        Ok(alive) => alive,
3361        Err(e) => {
3362            eprintln!("error in {}: {e}", start_path.display());
3363            return 2;
3364        }
3365    };
3366    let Some(started_at) = start_record.get("started_at").and_then(|v| v.as_u64()) else {
3367        eprintln!(
3368            "error: missing or invalid \"started_at\" in {}",
3369            start_path.display()
3370        );
3371        return 2;
3372    };
3373
3374    let summary_exists = records_dir.join(format!("{id}.json")).exists();
3375    let report_path = records_dir.join(format!("{id}.report.json"));
3376    let report_json: Option<serde_json::Value> = match std::fs::read_to_string(&report_path) {
3377        Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
3378            Ok(v) if v.is_object() => Some(v),
3379            Ok(_) => {
3380                eprintln!(
3381                    "error parsing {}: expected a JSON object",
3382                    report_path.display()
3383                );
3384                return 2;
3385            }
3386            Err(e) => {
3387                eprintln!("error parsing {}: {e}", report_path.display());
3388                return 2;
3389            }
3390        },
3391        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
3392        Err(e) => {
3393            eprintln!("error reading {}: {e}", report_path.display());
3394            return 2;
3395        }
3396    };
3397
3398    let state = if !summary_exists && is_alive {
3399        "running"
3400    } else if report_json.is_some() {
3401        "finished"
3402    } else {
3403        "dead"
3404    };
3405    let phase = if state == "running" && report_json.is_some() {
3406        Some("reviewing".to_string())
3407    } else {
3408        None
3409    };
3410
3411    let now = std::time::SystemTime::now()
3412        .duration_since(std::time::UNIX_EPOCH)
3413        .map(|d| d.as_secs())
3414        .unwrap_or(0);
3415
3416    let (outcome, cost_usd, final_message, report_duration) = if let Some(ref v) = report_json {
3417        let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
3418        let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
3419        let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
3420            if s.chars().count() > 500 {
3421                s.chars().take(500).collect()
3422            } else {
3423                s.to_string()
3424            }
3425        });
3426        let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
3427        (outcome, cost_usd, final_message, duration)
3428    } else {
3429        (None, None, None, None)
3430    };
3431
3432    let elapsed_s = if state == "finished" {
3433        report_duration
3434            .map(|d| d.round() as u64)
3435            .unwrap_or_else(|| now.saturating_sub(started_at))
3436    } else {
3437        now.saturating_sub(started_at)
3438    };
3439
3440    let log_path = records_dir.join(format!("{id}.log"));
3441    let log_content = match std::fs::read_to_string(&log_path) {
3442        Ok(s) => s,
3443        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
3444        Err(e) => {
3445            eprintln!("error reading {}: {e}", log_path.display());
3446            return 2;
3447        }
3448    };
3449    let progress = parse_log(&log_content);
3450
3451    if json {
3452        let status_obj = StatusOutput {
3453            id: id.to_string(),
3454            state: state.to_string(),
3455            phase,
3456            elapsed_s,
3457            turn: progress.turn,
3458            last_tool: progress.last_tool,
3459            gate_attempts: progress.gate_attempts,
3460            gate_passed: progress.gate_passed,
3461            outcome,
3462            cost_usd,
3463            final_message,
3464        };
3465        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
3466        println!("{json_str}");
3467    } else {
3468        println!("id: {id}");
3469        if let Some(ref p) = phase {
3470            println!("state: {state} {p}");
3471        } else {
3472            println!("state: {state}");
3473        }
3474        println!("elapsed_s: {elapsed_s}");
3475        println!("turn: {}", progress.turn);
3476        println!(
3477            "last_tool: {}",
3478            progress.last_tool.as_deref().unwrap_or("none")
3479        );
3480        println!("gate_attempts: {}", progress.gate_attempts);
3481        println!("gate_passed: {}", progress.gate_passed);
3482        if state == "finished" {
3483            if let Some(ref o) = outcome {
3484                println!("outcome: {o}");
3485            }
3486            if let Some(c) = cost_usd {
3487                println!("cost_usd: {c}");
3488            }
3489            if let Some(ref msg) = final_message {
3490                println!("final_message: {msg}");
3491            }
3492        }
3493    }
3494
3495    match state {
3496        "running" | "finished" => 0,
3497        _ => 1,
3498    }
3499}
3500
3501pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
3502    let readable_canon: Vec<PathBuf> = readable
3503        .iter()
3504        .filter_map(|r| std::fs::canonicalize(r).ok())
3505        .collect();
3506    let mut out = Vec::new();
3507    for raw in text.split(|c: char| {
3508        c.is_whitespace()
3509            || matches!(
3510                c,
3511                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
3512            )
3513    }) {
3514        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
3515        if !trimmed.starts_with('/')
3516            || trimmed.starts_with("//")
3517            || trimmed.len() <= 1
3518            || trimmed == "/dev/null"
3519        {
3520            continue;
3521        }
3522        let p = Path::new(trimmed);
3523        let Ok(canon) = std::fs::canonicalize(p) else {
3524            continue;
3525        };
3526        if readable_canon.iter().any(|r| canon.starts_with(r))
3527            || is_system_path(p)
3528            || is_system_path(&canon)
3529        {
3530            continue;
3531        }
3532        let pb = PathBuf::from(trimmed);
3533        if !out.contains(&pb) {
3534            out.push(pb);
3535        }
3536    }
3537    out
3538}
3539
3540/// A path no research task means as code to read: the filesystem root, a top-level directory,
3541/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
3542fn is_system_path(p: &Path) -> bool {
3543    const SYSTEM: &[&str] = &[
3544        "/usr",
3545        "/bin",
3546        "/sbin",
3547        "/etc",
3548        "/dev",
3549        "/opt",
3550        "/System",
3551        "/Library",
3552        "/Applications",
3553        "/nix",
3554        "/proc",
3555        "/sys",
3556    ];
3557    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
3558}
3559
3560pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
3561    let mut count = 0;
3562    let mut paths = Vec::new();
3563    for line in log_content.lines() {
3564        if !line.contains("path escapes the workspace") {
3565            continue;
3566        }
3567        count += 1;
3568        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
3569            let after = after.trim_start();
3570            let after = after.split("\x1b[").next().unwrap_or(after);
3571            let path = after
3572                .split(". This run can read")
3573                .next()
3574                .unwrap_or(after)
3575                .trim();
3576            if !path.is_empty() && !paths.iter().any(|p| p == path) {
3577                paths.push(path.to_string());
3578            }
3579        }
3580    }
3581    (count, paths)
3582}
3583
3584#[cfg(test)]
3585mod tests {
3586    use super::*;
3587
3588    #[test]
3589    fn outside_reads_excludes_commands_in_host_commands() {
3590        let home = Path::new("/Users/u");
3591        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3592        // rm -rf ~/repos/other is a host command (names outside and changes something)
3593        // cat ~/repos/other is not a host command (only reads)
3594        let log = "\
3595● bash rm -rf ~/repos/other/file.py -> exit 0
3596● bash cat ~/repos/other/file.py -> exit 0
3597";
3598        assert_eq!(
3599            host_commands(log),
3600            vec!["rm -rf ~/repos/other/file.py".to_string()]
3601        );
3602        assert_eq!(
3603            outside_reads(log, &allowed, home),
3604            vec!["cat ~/repos/other/file.py".to_string()]
3605        );
3606    }
3607
3608    #[test]
3609    fn outside_reads_all_terminal_patterns() {
3610        let home = Path::new("/Users/u");
3611        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3612        let log = "\
3613● bash herdr pane read p1 -> exit 0
3614● bash tmux capture-pane -t 1 -> exit 0
3615● bash screen -X hardcopy /tmp/screen.log -> exit 0
3616● bash zellij action dump-screen /tmp/dump -> exit 0
3617● bash wezterm cli get-text --pane-id 1 -> exit 0
3618";
3619        let reads = outside_reads(log, &allowed, home);
3620        assert_eq!(
3621            reads,
3622            vec![
3623                "herdr pane read p1",
3624                "tmux capture-pane -t 1",
3625                "screen -X hardcopy /tmp/screen.log",
3626                "zellij action dump-screen /tmp/dump",
3627                "wezterm cli get-text --pane-id 1",
3628            ]
3629        );
3630    }
3631
3632    #[test]
3633    fn outside_reads_all_tool_caches_ignored() {
3634        let home = Path::new("/Users/u");
3635        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3636        let log = "\
3637● bash ls ~/.cargo/bin -> exit 0
3638● bash ls ~/.rustup/toolchains -> exit 0
3639● bash ls ~/.cache/pip -> exit 0
3640● bash ls ~/.npm/_cacache -> exit 0
3641● bash ls ~/.local/share -> exit 0
3642● bash ls ~/Library/Caches/com.apple -> exit 0
3643● bash ls ~/.gradle/caches -> exit 0
3644● bash ls ~/.m2/repository -> exit 0
3645● bash ls ~/go/pkg -> exit 0
3646";
3647        assert!(outside_reads(log, &allowed, home).is_empty());
3648    }
3649
3650    #[test]
3651    fn outside_reads_trailing_punctuations_stripped() {
3652        let home = Path::new("/Users/u");
3653        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3654        let log = "\
3655● bash ls ~/secret: -> exit 0
3656● bash ls ~/secret, -> exit 0
3657● bash (ls ~/secret) -> exit 0
3658● bash bash -c 'ls ~/secret' -> exit 0
3659● bash bash -c \"ls ~/secret\" -> exit 0
3660";
3661        let reads = outside_reads(log, &allowed, home);
3662        // Deduplicated, so only one instance of the command or distinct commands:
3663        assert_eq!(reads.len(), 5);
3664    }
3665
3666    #[test]
3667    fn outside_reads_caps_at_20_and_deduplicates() {
3668        let home = Path::new("/Users/u");
3669        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
3670        let mut log = String::new();
3671        for i in 0..30 {
3672            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
3673        }
3674        // Duplicate the first one
3675        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
3676        let reads = outside_reads(&log, &allowed, home);
3677        assert_eq!(reads.len(), 20);
3678        assert_eq!(reads[0], "cat ~/secret/0.txt");
3679        assert_eq!(reads[19], "cat ~/secret/19.txt");
3680    }
3681
3682    fn sample_summary(id: &str, exit: i32) -> DispatchSummary {
3683        DispatchSummary {
3684            id: id.to_string(),
3685            worktree: "/tmp/wt".to_string(),
3686            branch: format!("wip/{id}"),
3687            outcome: if exit == 0 { "verified" } else { "gate_failed" },
3688            exit,
3689            error: None,
3690            commits: Vec::new(),
3691            changed_files: Vec::new(),
3692            final_message: Some("ok".to_string()),
3693            turns: 1,
3694            gate_attempts: 1,
3695            gate_failures: Vec::new(),
3696            cost_usd: Some(0.01),
3697            model: None,
3698            seconds: 1,
3699            sandbox: "off".to_string(),
3700            log: "/tmp/wt.log".to_string(),
3701            report: "/tmp/wt.report.json".to_string(),
3702            gate_source: "flag",
3703            research_report: None,
3704            base_check_seconds: None,
3705            warnings: Vec::new(),
3706            fix_round: None,
3707        }
3708    }
3709
3710    #[test]
3711    fn finish_summary_reports_error_when_wt_is_a_regular_file() {
3712        let d = tempfile::tempdir().unwrap();
3713        let wt_file = d.path().join(".wt");
3714        std::fs::write(&wt_file, "not a dir").unwrap();
3715
3716        let summary_ok = sample_summary("FC1", 0);
3717        let mut out_ok = Vec::new();
3718        let mut err_ok = Vec::new();
3719        let code_ok = finish_summary_with_writers(&summary_ok, d.path(), &mut out_ok, &mut err_ok);
3720        assert_eq!(code_ok, 1);
3721        let stderr_ok = String::from_utf8(err_ok).unwrap();
3722        let expected_path = wt_file.join("FC1.json");
3723        assert!(
3724            stderr_ok.contains("blyte: could not write"),
3725            "stderr: {stderr_ok}"
3726        );
3727        assert!(
3728            stderr_ok.contains(&expected_path.display().to_string()),
3729            "stderr: {stderr_ok}"
3730        );
3731        let parsed_ok: serde_json::Value = serde_json::from_slice(&out_ok).unwrap();
3732        assert_eq!(parsed_ok["id"], "FC1");
3733        assert_eq!(parsed_ok["exit"], 0);
3734
3735        let summary_fail = sample_summary("FC3", 3);
3736        let mut out_fail = Vec::new();
3737        let mut err_fail = Vec::new();
3738        let code_fail =
3739            finish_summary_with_writers(&summary_fail, d.path(), &mut out_fail, &mut err_fail);
3740        assert_eq!(code_fail, 3);
3741        let stderr_fail = String::from_utf8(err_fail).unwrap();
3742        assert!(
3743            stderr_fail.contains(&wt_file.join("FC3.json").display().to_string()),
3744            "stderr: {stderr_fail}"
3745        );
3746        let parsed_fail: serde_json::Value = serde_json::from_slice(&out_fail).unwrap();
3747        assert_eq!(parsed_fail["id"], "FC3");
3748        assert_eq!(parsed_fail["exit"], 3);
3749    }
3750
3751    #[test]
3752    fn resolve_max_cost_precedence() {
3753        assert_eq!(resolve_max_cost(None, None), 25.0);
3754        assert_eq!(resolve_max_cost(None, None), DEFAULT_MAX_COST_USD);
3755        assert_eq!(resolve_max_cost(None, Some(8.0)), 8.0);
3756        assert_eq!(resolve_max_cost(Some(3.0), Some(8.0)), 3.0);
3757        assert_eq!(resolve_max_cost(Some(3.0), None), 3.0);
3758    }
3759
3760    #[test]
3761    fn archive_run_records_skips_archive_dir_when_empty() {
3762        let d = tempfile::tempdir().unwrap();
3763        let wt = d.path().join(".wt");
3764        std::fs::create_dir_all(&wt).unwrap();
3765        std::fs::write(wt.join("A1.task.md"), "task").unwrap();
3766        std::fs::write(wt.join("A1.out"), "out").unwrap();
3767
3768        let res = archive_run_records_at(d.path(), "A1", 1700000000).unwrap();
3769        assert_eq!(res, None);
3770        assert!(!wt.join("archive").exists());
3771        assert!(wt.join("A1.task.md").is_file());
3772        assert!(wt.join("A1.out").is_file());
3773    }
3774
3775    #[test]
3776    fn archive_run_records_moves_all_extensions_and_uses_non_colliding_suffix() {
3777        let d = tempfile::tempdir().unwrap();
3778        let wt = d.path().join(".wt");
3779        std::fs::create_dir_all(&wt).unwrap();
3780        for ext in RUN_RECORD_EXTENSIONS {
3781            std::fs::write(wt.join(format!("A1.{ext}")), format!("first-{ext}")).unwrap();
3782        }
3783        std::fs::write(wt.join("A1.task.md"), "keep task").unwrap();
3784        std::fs::write(wt.join("A1.out"), "keep out").unwrap();
3785
3786        let rel1 = archive_run_records_at(d.path(), "A1", 1700000000)
3787            .unwrap()
3788            .unwrap();
3789        assert_eq!(rel1, ".wt/archive/A1-1700000000");
3790        for ext in RUN_RECORD_EXTENSIONS {
3791            assert!(!wt.join(format!("A1.{ext}")).exists());
3792            assert_eq!(
3793                std::fs::read_to_string(d.path().join(&rel1).join(format!("A1.{ext}"))).unwrap(),
3794                format!("first-{ext}")
3795            );
3796        }
3797        assert_eq!(
3798            std::fs::read_to_string(wt.join("A1.task.md")).unwrap(),
3799            "keep task"
3800        );
3801        assert_eq!(
3802            std::fs::read_to_string(wt.join("A1.out")).unwrap(),
3803            "keep out"
3804        );
3805
3806        std::fs::write(wt.join("A1.verdict.json"), "second").unwrap();
3807        let rel2 = archive_run_records_at(d.path(), "A1", 1700000000)
3808            .unwrap()
3809            .unwrap();
3810        assert_eq!(rel2, ".wt/archive/A1-1700000000-2");
3811        assert_eq!(
3812            std::fs::read_to_string(d.path().join(&rel2).join("A1.verdict.json")).unwrap(),
3813            "second"
3814        );
3815        assert_eq!(
3816            std::fs::read_to_string(d.path().join(&rel1).join("A1.verdict.json")).unwrap(),
3817            "first-verdict.json"
3818        );
3819
3820        std::fs::write(wt.join("A1.verdict.json"), "third").unwrap();
3821        let rel3 = archive_run_records_at(d.path(), "A1", 1700000000)
3822            .unwrap()
3823            .unwrap();
3824        assert_eq!(rel3, ".wt/archive/A1-1700000000-3");
3825        assert_eq!(
3826            std::fs::read_to_string(d.path().join(&rel3).join("A1.verdict.json")).unwrap(),
3827            "third"
3828        );
3829    }
3830
3831    #[test]
3832    fn archive_run_records_errors_naming_path_when_archive_root_is_file() {
3833        let d = tempfile::tempdir().unwrap();
3834        let wt = d.path().join(".wt");
3835        std::fs::create_dir_all(&wt).unwrap();
3836        let blocker = wt.join("archive");
3837        std::fs::write(&blocker, "not a dir").unwrap();
3838        std::fs::write(wt.join("A1.verdict.json"), r#"{"verdict":"accepted"}"#).unwrap();
3839
3840        let err = archive_run_records_at(d.path(), "A1", 1700000000).unwrap_err();
3841        assert!(
3842            err.contains(&blocker.display().to_string()),
3843            "error should name archive root path: {err}"
3844        );
3845    }
3846
3847    #[test]
3848    fn update_start_record_pid_keeps_dispatch_pid() {
3849        let d = tempfile::tempdir().unwrap();
3850        let path = d.path().join("T1.start.json");
3851        let initial = serde_json::json!({
3852            "id": "T1",
3853            "pid": 100,
3854            "dispatch_pid": 200,
3855            "started_at": 1700000000,
3856        });
3857        write_start_record(&path, &initial).unwrap();
3858
3859        update_start_record_pid(&path, 300);
3860
3861        let updated: serde_json::Value =
3862            serde_json::from_str(&std::fs::read_to_string(&path).unwrap()).unwrap();
3863        assert_eq!(updated["pid"], 300);
3864        assert_eq!(updated["dispatch_pid"], 200);
3865    }
3866}