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