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