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