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- 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.
12- 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.
13- Do not push, open pull requests, or read secrets.
14- Commit locally before you stop, with the exact commit message the task gives (or a conventional one if it gives none).
15- 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.
16- 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.
17- Finish with a short report: what you changed, what you ran, and anything that deviated from the task."#;
18
19/// Writes a start record as pretty JSON plus a newline, through a temporary file renamed
20/// into place, so a concurrent reader never sees a partly written file.
21pub fn write_start_record(
22    path: &std::path::Path,
23    value: &serde_json::Value,
24) -> std::io::Result<()> {
25    let mut json = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
26    json.push('\n');
27    let mut tmp_name = path.as_os_str().to_os_string();
28    tmp_name.push(".tmp");
29    let tmp_path = std::path::PathBuf::from(tmp_name);
30    std::fs::write(&tmp_path, json)?;
31    std::fs::rename(&tmp_path, path)
32}
33
34struct StartRecordGuard {
35    path: PathBuf,
36    armed: bool,
37}
38
39impl Drop for StartRecordGuard {
40    fn drop(&mut self) {
41        if self.armed {
42            let _ = std::fs::remove_file(&self.path);
43        }
44    }
45}
46
47pub fn wrap_task(task: &str) -> String {
48    format!(
49        "You are implementing exactly one task. Your working directory is a git worktree on its own branch; work only there.\n\n{}\n\n{}",
50        task.trim(),
51        DISPATCH_RULES
52    )
53}
54
55pub const RESEARCH_RULES: &str = r#"Rules:
56- Do not create, modify, move or delete any file anywhere except `report.md` in your working directory.
57- 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.
58- 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.
59- Answer the question with evidence: file paths with line numbers, and quote only what is needed.
60- 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.
61- Write your findings to `report.md` in your working directory, then stop calling tools and reply with one line summarising them.
62- 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.
63- Start report.md early, after your first findings, and keep it updated as you go, so it always holds your best answer."#;
64
65pub fn wrap_research(question: &str, root: &Path) -> String {
66    format!(
67        "READ-ONLY RESEARCH TASK. The code to research is under {}: read it there by absolute path.\n\n{}\n\n{}",
68        root.display(),
69        question.trim(),
70        RESEARCH_RULES
71    )
72}
73
74pub fn quick_steps(gate: &str) -> Option<String> {
75    let lines: Vec<&str> = gate
76        .lines()
77        .map(str::trim)
78        .filter(|l| !l.is_empty())
79        .collect();
80    if lines.len() < 2 {
81        return None;
82    }
83    let steps = lines[..lines.len() - 1]
84        .iter()
85        .map(|s| format!("`{s}`"))
86        .collect::<Vec<_>>()
87        .join(", ");
88    Some(format!(
89        "The check's quick steps, to run yourself before you stop: {steps}. The last step, the full run, happens at the gate."
90    ))
91}
92
93pub fn dispatch_outcome(report_outcome: &str, commits: usize) -> &'static str {
94    match report_outcome {
95        "verified" => {
96            if commits == 0 {
97                "no_changes"
98            } else {
99                "verified"
100            }
101        }
102        "gate_failed" => "gate_failed",
103        "budget_exhausted" => "budget_exhausted",
104        "blocked" => "blocked",
105        "error" => "error",
106        _ => "error",
107    }
108}
109
110pub fn exit_code(outcome: &str) -> i32 {
111    match outcome {
112        "verified" => 0,
113        "no_changes" => 4,
114        "blocked" => 5,
115        _ => 1,
116    }
117}
118
119#[derive(Debug, Serialize)]
120pub struct CommitRecord {
121    pub sha: String,
122    pub subject: String,
123}
124
125#[derive(Debug, Serialize)]
126pub struct DispatchSummary {
127    pub id: String,
128    pub worktree: String,
129    pub branch: String,
130    pub outcome: &'static str,
131    pub exit: i32,
132    pub error: Option<String>,
133    pub commits: Vec<CommitRecord>,
134    pub changed_files: Vec<String>,
135    pub final_message: Option<String>,
136    pub turns: u32,
137    pub gate_attempts: u32,
138    pub gate_failures: Vec<String>,
139    pub cost_usd: Option<f64>,
140    pub model: Option<String>,
141    pub seconds: u64,
142    pub sandbox: String,
143    pub log: String,
144    pub report: String,
145    pub gate_source: &'static str,
146    pub research_report: Option<String>,
147}
148
149fn finish_summary(summary: &DispatchSummary, wt_parent: &Path) -> i32 {
150    let _ = std::fs::create_dir_all(wt_parent);
151    let json_str = serde_json::to_string_pretty(summary).unwrap();
152    let summary_path = wt_parent.join(format!("{}.json", summary.id));
153    let _ = std::fs::write(&summary_path, format!("{json_str}\n"));
154    println!("{json_str}");
155    summary.exit
156}
157
158pub fn branch_exists_message(root: &Path, branch: &str, id: &str) -> String {
159    if crate::clean::is_branch_merged(root, branch) {
160        format!(
161            "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."
162        )
163    } else {
164        format!(
165            "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."
166        )
167    }
168}
169
170/// Source-state block for the research root and each read root, skipping duplicates.
171fn research_source_block(
172    root: &Path,
173    config_allow_read: &[PathBuf],
174    allow_read: &[PathBuf],
175) -> String {
176    let mut roots: Vec<PathBuf> = vec![root.to_path_buf()];
177    for r in config_allow_read.iter().chain(allow_read) {
178        if !roots.contains(r) {
179            roots.push(r.clone());
180        }
181    }
182    let sources: Vec<(PathBuf, crate::provenance::SourceState)> = roots
183        .into_iter()
184        .map(|p| {
185            let state = crate::provenance::source_state(&p);
186            (p, state)
187        })
188        .collect();
189    crate::provenance::render(&sources)
190}
191
192/// Appends the source-state block to a copied report. Failure is reported, not fatal.
193fn append_source_state(path: &Path, block: &str) {
194    use std::io::Write;
195    let result = std::fs::OpenOptions::new()
196        .append(true)
197        .open(path)
198        .and_then(|mut f| f.write_all(format!("\n\n{block}").as_bytes()));
199    if let Err(e) = result {
200        eprintln!(
201            "error: could not add the source state to {}: {e}",
202            path.display()
203        );
204    }
205}
206
207pub fn run_dispatch(args: &DispatchArgs) -> i32 {
208    if let Ok(home) = crate::skill::home_dir() {
209        if let Ok(Some(path)) = crate::skill::ensure_context_block(&home) {
210            eprintln!(
211                "blyte: added context rules to {} (they apply from the next Claude session)",
212                path.display()
213            );
214        }
215    }
216
217    // 1. Root repository discovery and worktree preparation
218    let out = Command::new("git")
219        .args(["rev-parse", "--show-toplevel"])
220        .output();
221    let Ok(out) = out else {
222        eprintln!("error: git not found");
223        return 2;
224    };
225    if !out.status.success() {
226        eprintln!("error: not a git repository");
227        return 2;
228    }
229    let start_dir = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
230    let root = match crate::clean::find_repo_root() {
231        Ok(r) => r,
232        Err(e) => {
233            eprintln!("error: {e}");
234            return 2;
235        }
236    };
237    crate::registry::register(&root);
238
239    let (repo_config, from_main) = match crate::config::load_with_fallback(&start_dir) {
240        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
241        Ok(None) => (None, false),
242        Err(e) => {
243            eprintln!("{e}");
244            return 2;
245        }
246    };
247    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
248
249    let mut left_out: Vec<(String, String)> = Vec::new();
250    let (gate, gate_source) = if args.research {
251        ("test -s report.md".to_string(), "research")
252    } else if let Some(ref g) = args.gate {
253        (g.clone(), "flag")
254    } else if let Some(ref g) = dispatch_cfg.gate {
255        let toml_path = if from_main {
256            root.join("blyte.toml")
257        } else {
258            start_dir.join("blyte.toml")
259        };
260        let toml_content = std::fs::read_to_string(&toml_path).unwrap_or_default();
261        left_out = crate::gate_drift::left_out_steps(&toml_content);
262        if g.trim().is_empty() {
263            eprintln!(
264                "error: the gate in blyte.toml is empty; every step was left out. Fix the steps blyte init named, or pass --gate."
265            );
266            for (cmd, reason) in &left_out {
267                eprintln!("  {cmd}: {reason}");
268            }
269            return 2;
270        }
271        let missing = crate::gate_drift::missing_ci_steps(&root, g, &toml_content);
272        if let Some(warning) = crate::gate_drift::format_gate_drift_warning(&missing) {
273            eprintln!("{warning}");
274        }
275        if !left_out.is_empty() {
276            let formatted: Vec<String> = left_out
277                .iter()
278                .map(|(cmd, reason)| format!("{cmd} ({reason})"))
279                .collect();
280            eprintln!(
281                "blyte: the gate is partial; left out: {}",
282                formatted.join("; ")
283            );
284        }
285        let source = if from_main {
286            "blyte.toml (main checkout)"
287        } else {
288            "blyte.toml"
289        };
290        (g.clone(), source)
291    } else {
292        eprintln!("no gate: pass --gate, or run blyte init to write blyte.toml");
293        return 2;
294    };
295
296    let model = args.model.as_ref().or(dispatch_cfg.model.as_ref());
297    let (max_seconds, max_turns) = if args.research {
298        (
299            args.max_seconds.unwrap_or(1800),
300            args.max_turns.unwrap_or(300),
301        )
302    } else {
303        (
304            args.max_seconds
305                .or(dispatch_cfg.max_seconds)
306                .unwrap_or(3600),
307            args.max_turns.or(dispatch_cfg.max_turns).unwrap_or(300),
308        )
309    };
310    let max_cost = args.max_cost_usd.or(dispatch_cfg.max_cost);
311    let fold_budget = args.fold_budget.or(dispatch_cfg.fold_budget);
312    let network = args
313        .network
314        .as_deref()
315        .or(dispatch_cfg.network.as_deref())
316        .unwrap_or("on");
317
318    let (task_content, recorded_task_file) = if let Some(ref tf) = args.task_file {
319        let content = match std::fs::read_to_string(tf) {
320            Ok(s) => s,
321            Err(e) => {
322                eprintln!("error reading task file {}: {e}", tf.display());
323                return 2;
324            }
325        };
326        (content, Some(tf.display().to_string()))
327    } else {
328        match (&args.plan, &args.plan_task) {
329            (Some(plan_path), Some(plan_task)) => {
330                let plan_str = match std::fs::read_to_string(plan_path) {
331                    Ok(s) => s,
332                    Err(e) => {
333                        eprintln!("error reading plan {plan_path}: {e}");
334                        return 2;
335                    }
336                };
337                let section = match crate::plan_section::extract(&plan_str, plan_task) {
338                    Some(sec) => sec,
339                    None => {
340                        eprintln!("error: no heading \"{plan_task}\" in {plan_path}");
341                        if let Some(hint) =
342                            crate::plan_section::explain_missing(&plan_str, plan_task)
343                        {
344                            eprintln!("  {hint}");
345                        }
346                        return 2;
347                    }
348                };
349                let content = format!("From the plan {plan_path}:\n\n{section}");
350                (content, None)
351            }
352            _ => {
353                eprintln!("error: give a task file, or --plan with --plan-task");
354                if args.research {
355                    eprintln!(
356                        "A research question needs these sections:\n\n{}",
357                        crate::research_brief::TEMPLATE
358                    );
359                }
360                return 2;
361            }
362        }
363    };
364
365    if args.research && !args.no_brief_check {
366        let missing = crate::research_brief::missing_sections(&task_content);
367        if !missing.is_empty() {
368            eprintln!(
369                "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.",
370                missing.join(", "),
371                args.id
372            );
373        }
374        let unverified = crate::research_brief::unverified_inputs(&task_content, &root);
375        if !unverified.is_empty() {
376            let paths: Vec<String> = unverified.iter().map(|p| p.display().to_string()).collect();
377            eprintln!(
378                "blyte: the question names a report that did not pass blyte's checks: {}. Use a verified report, or --no-brief-check to start anyway.",
379                paths.join(", ")
380            );
381            return 2;
382        }
383    }
384
385    let home = std::env::var_os("HOME").map(PathBuf::from);
386    let main_checkout = root.clone();
387    let config_allow_read = match crate::config::expand_allow_read(
388        &dispatch_cfg.allow_read,
389        home.as_deref(),
390        &main_checkout,
391    ) {
392        Ok(paths) => paths,
393        Err(e) => {
394            eprintln!("{e}");
395            return 2;
396        }
397    };
398
399    if !args.no_path_check {
400        let mut readable = vec![start_dir.clone(), root.clone()];
401        readable.extend(config_allow_read.iter().cloned());
402        readable.extend(args.allow_read.iter().cloned());
403        let bad = unreadable_paths(&task_content, &readable);
404        if !bad.is_empty() {
405            let shown: Vec<String> = bad
406                .iter()
407                .take(5)
408                .map(|p| p.display().to_string())
409                .collect();
410            eprintln!(
411                "blyte: the task names paths this run cannot read: {}. Add --allow-read <dir> for each (or --no-path-check to start anyway).",
412                shown.join(", ")
413            );
414            if args.research {
415                return 2;
416            }
417        }
418    }
419
420    let wt_parent = root.join(".wt");
421    let worktree_dir = wt_parent.join(&args.id);
422    let branch = format!("wip/{}", args.id);
423    let task_md_path = wt_parent.join(format!("{}.task.md", args.id));
424    let task_file_recorded =
425        recorded_task_file.unwrap_or_else(|| task_md_path.display().to_string());
426
427    if !args.research {
428        let start_path = wt_parent.join(format!("{}.start.json", args.id));
429        if start_path.exists() {
430            let start_str = match std::fs::read_to_string(&start_path) {
431                Ok(s) => s,
432                Err(e) => {
433                    eprintln!("error reading {}: {e}", start_path.display());
434                    return 2;
435                }
436            };
437            let start_val: serde_json::Value = match serde_json::from_str(&start_str) {
438                Ok(v) => v,
439                Err(e) => {
440                    eprintln!("error parsing {}: {e}", start_path.display());
441                    return 2;
442                }
443            };
444            let Some(pid) = start_val.get("pid").and_then(|v| v.as_i64()) else {
445                eprintln!("error: missing pid in {}", start_path.display());
446                return 2;
447            };
448            let Some(started_at) = start_val.get("started_at").and_then(|v| v.as_u64()) else {
449                eprintln!("error: missing started_at in {}", start_path.display());
450                return 2;
451            };
452            if crate::clean::is_pid_alive(pid) {
453                let summary_path = wt_parent.join(format!("{}.json", args.id));
454                let finished_since_start = if summary_path.exists() {
455                    let meta = match std::fs::metadata(&summary_path) {
456                        Ok(m) => m,
457                        Err(e) => {
458                            eprintln!("error reading metadata of {}: {e}", summary_path.display());
459                            return 2;
460                        }
461                    };
462                    let mtime = match meta.modified() {
463                        Ok(t) => t,
464                        Err(e) => {
465                            eprintln!("error reading mtime of {}: {e}", summary_path.display());
466                            return 2;
467                        }
468                    };
469                    let mtime_secs = match mtime.duration_since(std::time::UNIX_EPOCH) {
470                        Ok(d) => d.as_secs(),
471                        Err(e) => {
472                            eprintln!("error reading timestamp of {}: {e}", summary_path.display());
473                            return 2;
474                        }
475                    };
476                    mtime_secs >= started_at
477                } else {
478                    false
479                };
480                if !finished_since_start {
481                    eprintln!(
482                        "error: run {} is still running (pid {pid}). Wait for it to finish, or dispatch with a new ID.",
483                        args.id
484                    );
485                    return 2;
486                }
487            }
488        }
489
490        let branch_ref = format!("refs/heads/{branch}");
491        let branch_out = Command::new("git")
492            .args(["show-ref", "--verify", "--quiet", &branch_ref])
493            .current_dir(&root)
494            .output();
495        let branch_exists = match branch_out {
496            Ok(o) if o.status.success() => true,
497            Ok(o) if o.status.code() == Some(1) => false,
498            Ok(o) => {
499                eprintln!(
500                    "error: git show-ref --verify --quiet {branch_ref}: {}",
501                    String::from_utf8_lossy(&o.stderr).trim()
502                );
503                return 2;
504            }
505            Err(e) => {
506                eprintln!("error: git show-ref --verify --quiet {branch_ref}: {e}");
507                return 2;
508            }
509        };
510
511        if worktree_dir.exists() || branch_exists {
512            match crate::clean::remove_finished_run(&root, &args.id) {
513                Ok(Some(reason)) => {
514                    let secs =
515                        match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
516                            Ok(d) => d.as_secs(),
517                            Err(e) => {
518                                eprintln!("error: system clock before unix epoch: {e}");
519                                return 2;
520                            }
521                        };
522                    let archive_rel = format!(".wt/archive/{}-{secs}", args.id);
523                    let archive_dir = root.join(&archive_rel);
524                    if let Err(e) = std::fs::create_dir_all(&archive_dir) {
525                        eprintln!("error: {}: {e}", archive_dir.display());
526                        return 2;
527                    }
528                    for ext in [
529                        "json",
530                        "report.json",
531                        "start.json",
532                        "verdict.json",
533                        "checks.json",
534                        "log",
535                    ] {
536                        let file_name = format!("{}.{ext}", args.id);
537                        let src = wt_parent.join(&file_name);
538                        if src.exists() {
539                            let dst = archive_dir.join(&file_name);
540                            if let Err(e) = std::fs::rename(&src, &dst) {
541                                eprintln!(
542                                    "error: rename {} -> {}: {e}",
543                                    src.display(),
544                                    dst.display()
545                                );
546                                return 2;
547                            }
548                        }
549                    }
550                    eprintln!(
551                        "dispatch: replaced the earlier run {} ({reason}); its records are in {archive_rel}/",
552                        args.id
553                    );
554                }
555                Ok(None) => {}
556                Err(e) => {
557                    eprintln!("error: could not remove the earlier run {}: {e}", args.id);
558                    return 2;
559                }
560            }
561        }
562    } else if worktree_dir.exists() {
563        eprintln!("error: {} already exists", worktree_dir.display());
564        return 2;
565    }
566
567    let started_at = std::time::SystemTime::now()
568        .duration_since(std::time::UNIX_EPOCH)
569        .map(|d| d.as_secs())
570        .unwrap_or(0);
571    let mut tags = args.tags.clone();
572    if args.research {
573        tags.push("research".to_string());
574    }
575    let session = crate::usage_log::session_from(
576        std::env::var("BLYTE_SESSION").ok(),
577        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
578    );
579    let start_path = wt_parent.join(format!("{}.start.json", args.id));
580    let mut initial_start = serde_json::json!({
581        "id": args.id,
582        "pid": std::process::id(),
583        "started_at": started_at,
584        "starting": true,
585        "tags": tags,
586        "plan": args.plan,
587        "plan_task": args.plan_task,
588        "base": args.base,
589    });
590    if let Some(ref s) = session {
591        initial_start["session"] = serde_json::json!(s);
592    }
593    if args.research {
594        initial_start["research"] = serde_json::json!(true);
595    }
596    if let Err(err) = std::fs::create_dir_all(&wt_parent)
597        .and_then(|()| write_start_record(&start_path, &initial_start))
598    {
599        eprintln!(
600            "error: could not write the start record {}: {err}",
601            start_path.display()
602        );
603        return 2;
604    }
605    let mut start_guard = StartRecordGuard {
606        path: start_path.clone(),
607        armed: true,
608    };
609
610    if !args.research {
611        crate::clean::spawn_background_clean(&root, Some(&args.id));
612    }
613
614    let base_commit: Option<String> = if args.research {
615        if let Err(e) = std::fs::create_dir_all(&worktree_dir) {
616            eprintln!(
617                "error creating scratch directory {}: {e}",
618                worktree_dir.display()
619            );
620            return 2;
621        }
622        let init_out = Command::new("git")
623            .args(["init", "-q"])
624            .current_dir(&worktree_dir)
625            .output();
626        match init_out {
627            Ok(o) if o.status.success() => {}
628            Ok(o) => {
629                eprintln!(
630                    "error: git init failed: {}",
631                    String::from_utf8_lossy(&o.stderr)
632                );
633                return 2;
634            }
635            Err(e) => {
636                eprintln!("error: failed to execute git init: {e}");
637                return 2;
638            }
639        }
640        let commit_out = Command::new("git")
641            .args([
642                "-c",
643                "user.name=blyte",
644                "-c",
645                "user.email=blyte@local",
646                "commit",
647                "-q",
648                "--allow-empty",
649                "-m",
650                "research",
651            ])
652            .current_dir(&worktree_dir)
653            .output();
654        match commit_out {
655            Ok(o) if o.status.success() => {}
656            Ok(o) => {
657                eprintln!(
658                    "error: git commit failed: {}",
659                    String::from_utf8_lossy(&o.stderr)
660                );
661                return 2;
662            }
663            Err(e) => {
664                eprintln!("error: failed to execute git commit: {e}");
665                return 2;
666            }
667        }
668        None
669    } else if !worktree_dir.exists() {
670        let branch_exists = Command::new("git")
671            .args([
672                "rev-parse",
673                "--verify",
674                "--quiet",
675                &format!("refs/heads/{branch}"),
676            ])
677            .current_dir(&root)
678            .output()
679            .map(|o| o.status.success())
680            .unwrap_or(false);
681        if branch_exists {
682            eprintln!("{}", branch_exists_message(&root, &branch, &args.id));
683            return 2;
684        }
685        let base_commit = Command::new("git")
686            .args([
687                "rev-parse",
688                "--verify",
689                &format!("{}^{{commit}}", args.base),
690            ])
691            .current_dir(&start_dir)
692            .output();
693        let base_commit = match base_commit {
694            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
695            _ => {
696                eprintln!("error: base {} is not a commit", args.base);
697                return 2;
698            }
699        };
700        let add_out = Command::new("git")
701            .args([
702                "worktree",
703                "add",
704                "-b",
705                &branch,
706                worktree_dir.to_str().unwrap(),
707                &base_commit,
708            ])
709            .current_dir(&root)
710            .output();
711        match add_out {
712            Ok(o) if o.status.success() => {}
713            Ok(o) => {
714                eprintln!(
715                    "error: git worktree add failed: {}",
716                    String::from_utf8_lossy(&o.stderr)
717                );
718                return 2;
719            }
720            Err(e) => {
721                eprintln!("error: failed to execute git worktree add: {e}");
722                return 2;
723            }
724        }
725        Some(base_commit)
726    } else {
727        let base_commit = match Command::new("git")
728            .args([
729                "rev-parse",
730                "--verify",
731                &format!("{}^{{commit}}", args.base),
732            ])
733            .current_dir(&start_dir)
734            .output()
735        {
736            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
737            Ok(o) => {
738                eprintln!(
739                    "error: git rev-parse {} failed: {}",
740                    args.base,
741                    String::from_utf8_lossy(&o.stderr).trim()
742                );
743                return 2;
744            }
745            Err(e) => {
746                eprintln!("error: failed to execute git rev-parse: {e}");
747                return 2;
748            }
749        };
750        let wt_head = match Command::new("git")
751            .args([
752                "-C",
753                worktree_dir.to_str().unwrap(),
754                "rev-parse",
755                "--verify",
756                "HEAD^{commit}",
757            ])
758            .output()
759        {
760            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
761            Ok(o) => {
762                eprintln!(
763                    "error: git -C {} rev-parse HEAD failed: {}",
764                    worktree_dir.display(),
765                    String::from_utf8_lossy(&o.stderr).trim()
766                );
767                return 2;
768            }
769            Err(e) => {
770                eprintln!("error: failed to execute git rev-parse: {e}");
771                return 2;
772            }
773        };
774        let ancestor_out = Command::new("git")
775            .args(["merge-base", "--is-ancestor", &base_commit, &wt_head])
776            .current_dir(&root)
777            .output();
778        match ancestor_out {
779            Ok(o) if o.status.success() => {}
780            Ok(o) if o.status.code() == Some(1) => {
781                let short_wt_head = &wt_head[..wt_head.len().min(7)];
782                let short_base = &base_commit[..base_commit.len().min(7)];
783                eprintln!(
784                    "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.",
785                    id = args.id,
786                    base_name = args.base,
787                );
788                return 2;
789            }
790            Ok(o) => {
791                eprintln!(
792                    "error: git merge-base --is-ancestor failed: {}",
793                    String::from_utf8_lossy(&o.stderr).trim()
794                );
795                return 2;
796            }
797            Err(e) => {
798                eprintln!("error: failed to execute git merge-base --is-ancestor: {e}");
799                return 2;
800            }
801        }
802        Some(base_commit)
803    };
804
805    // 2. Ensure .wt/ is in info/exclude
806    let common_dir_raw = Command::new("git")
807        .args(["rev-parse", "--git-common-dir"])
808        .current_dir(&root)
809        .output();
810    let common_dir = if let Ok(out) = common_dir_raw {
811        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
812        if p.is_absolute() {
813            p
814        } else {
815            root.join(p)
816        }
817    } else {
818        root.join(".git")
819    };
820
821    let exclude_path = common_dir.join("info").join("exclude");
822    if let Some(parent) = exclude_path.parent() {
823        let _ = std::fs::create_dir_all(parent);
824    }
825    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
826    if !content.lines().any(|l| l.trim() == ".wt/") {
827        let mut new_content = content;
828        if !new_content.is_empty() && !new_content.ends_with('\n') {
829            new_content.push('\n');
830        }
831        new_content.push_str(".wt/\n");
832        let _ = std::fs::write(&exclude_path, new_content);
833    }
834
835    // 3. Record base_sha
836    let base_out = Command::new("git")
837        .args(["-C", worktree_dir.to_str().unwrap(), "rev-parse", "HEAD"])
838        .output();
839    let base_sha = match base_out {
840        Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
841        _ => {
842            eprintln!("error: could not resolve HEAD in worktree");
843            return 2;
844        }
845    };
846
847    if !args.research {
848        if let Some(ref setup_cmd) = dispatch_cfg.setup {
849            let first_line = setup_cmd.lines().next().unwrap_or("");
850            eprintln!("setup: {first_line}");
851            let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
852            let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
853            if let Err(msg) = crate::setup::run_setup(
854                setup_cmd,
855                &worktree_dir,
856                &main_checkout,
857                &dispatch_cfg.env,
858                &setup_log_path,
859                crate::setup::SETUP_TIMEOUT,
860            ) {
861                let outcome = "blocked";
862                let exit = exit_code(outcome);
863                let first_line_err = msg.lines().next().unwrap_or("").to_string();
864                let summary = DispatchSummary {
865                    id: args.id.clone(),
866                    worktree: worktree_dir.display().to_string(),
867                    branch: branch.clone(),
868                    outcome,
869                    exit,
870                    error: Some(first_line_err),
871                    commits: Vec::new(),
872                    changed_files: Vec::new(),
873                    final_message: Some(msg),
874                    turns: 0,
875                    gate_attempts: 0,
876                    gate_failures: Vec::new(),
877                    cost_usd: None,
878                    model: None,
879                    seconds: 0,
880                    sandbox: args.sandbox.clone(),
881                    log: setup_log_path.display().to_string(),
882                    report: "".to_string(),
883                    gate_source,
884                    research_report: None,
885                };
886                return finish_summary(&summary, &wt_parent);
887            }
888        }
889    }
890
891    // 4. Write task file and spawn child process
892    let _ = std::fs::create_dir_all(&wt_parent);
893    if let Err(e) = std::fs::write(&task_md_path, &task_content) {
894        eprintln!("error writing task file {}: {e}", task_md_path.display());
895        return 2;
896    }
897
898    let log_path = wt_parent.join(format!("{}.log", args.id));
899    let summary_path = wt_parent.join(format!("{}.json", args.id));
900    if summary_path.exists() {
901        let _ = std::fs::remove_file(&summary_path);
902    }
903    let report_path = wt_parent.join(format!("{}.report.json", args.id));
904    if report_path.exists() {
905        let _ = std::fs::remove_file(&report_path);
906    }
907    let research_report_path = wt_parent.join(format!("{}.report.md", args.id));
908    if research_report_path.exists() {
909        let _ = std::fs::remove_file(&research_report_path);
910    }
911
912    let log_file = match std::fs::File::create(&log_path) {
913        Ok(f) => f,
914        Err(e) => {
915            eprintln!("error creating log file {}: {e}", log_path.display());
916            return 2;
917        }
918    };
919    let log_file_err = match log_file.try_clone() {
920        Ok(f) => f,
921        Err(e) => {
922            eprintln!("error cloning log file handle: {e}");
923            return 2;
924        }
925    };
926
927    let current_exe = match std::env::current_exe() {
928        Ok(p) => p,
929        Err(e) => {
930            eprintln!("error getting current executable: {e}");
931            return 2;
932        }
933    };
934
935    let mut cmd = Command::new(current_exe);
936    cmd.current_dir(&worktree_dir);
937    cmd.stdout(log_file);
938    cmd.stderr(log_file_err);
939
940    for (k, v) in &dispatch_cfg.env {
941        cmd.env(k, v);
942    }
943    cmd.env("BLYTE_DISPATCH_ID", &args.id);
944
945    cmd.arg("--gate").arg(&gate);
946    cmd.arg("--rollback=false");
947    cmd.arg("--max-seconds").arg(max_seconds.to_string());
948    cmd.arg("--max-turns").arg(max_turns.to_string());
949    cmd.arg("--report").arg(&report_path);
950
951    if let Some(m) = model {
952        cmd.arg("--model").arg(m);
953    }
954    if let Some(c) = max_cost {
955        cmd.arg("--max-cost").arg(c.to_string());
956    }
957    if let Some(fb) = fold_budget {
958        cmd.arg("--fold-budget").arg(fb.to_string());
959    }
960    cmd.arg("--sandbox").arg(&args.sandbox);
961    cmd.arg("--network").arg(network);
962    for r in &config_allow_read {
963        cmd.arg("--allow-read").arg(r);
964    }
965    for r in &args.allow_read {
966        cmd.arg("--allow-read").arg(r);
967    }
968    for p in &args.pass_env {
969        cmd.arg("--pass-env").arg(p);
970    }
971    // The read and grep tools may read what the sandbox may read.
972    for r in config_allow_read.iter().chain(&args.allow_read) {
973        cmd.arg("--read-root").arg(r);
974    }
975    if args.research {
976        cmd.arg("--read-root").arg(&root);
977        cmd.arg("--no-gate-slot");
978        cmd.arg("--research");
979        if !args.no_claim_check {
980            cmd.arg("--claim-check");
981        }
982    }
983
984    cmd.arg("--");
985    let research_sources = args
986        .research
987        .then(|| research_source_block(&root, &config_allow_read, &args.allow_read));
988    let task_prompt = if let Some(block) = &research_sources {
989        wrap_research(&format!("{block}\n\n{task_content}"), &root)
990    } else {
991        let mut prompt = wrap_task(&task_content);
992        if let Some(qs) = quick_steps(&gate) {
993            prompt.push_str("\n\n");
994            prompt.push_str(&qs);
995        }
996        prompt
997    };
998    cmd.arg(task_prompt);
999
1000    let mut child = match cmd.spawn() {
1001        Ok(c) => c,
1002        Err(e) => {
1003            eprintln!("error spawning child process: {e}");
1004            return 2;
1005        }
1006    };
1007    start_guard.armed = false;
1008
1009    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
1010    let mut start_json = serde_json::json!({
1011        "id": args.id,
1012        "pid": child.id(),
1013        "started_at": started_at,
1014        "task_file": task_file_recorded,
1015        "gate": gate,
1016        "tags": tags,
1017        "env": env_names,
1018        "max_turns": max_turns,
1019        "max_seconds": max_seconds,
1020        "plan": args.plan,
1021        "plan_task": args.plan_task,
1022        "base": args.base,
1023        "base_sha": base_commit,
1024    });
1025    if let Some(session) = session {
1026        start_json["session"] = serde_json::json!(session);
1027    }
1028    if args.research {
1029        start_json["research"] = serde_json::json!(true);
1030    }
1031    if !left_out.is_empty() {
1032        start_json["gate_left_out"] = serde_json::json!(left_out
1033            .iter()
1034            .map(|(command, reason)| serde_json::json!({
1035                "command": command,
1036                "reason": reason,
1037            }))
1038            .collect::<Vec<_>>());
1039    }
1040    if let Err(err) = write_start_record(&start_path, &start_json) {
1041        eprintln!(
1042            "error: could not write the start record {}: {err}",
1043            start_path.display()
1044        );
1045    }
1046
1047    let _ = child.wait();
1048
1049    if !left_out.is_empty() {
1050        if let Ok(report_str) = std::fs::read_to_string(&report_path) {
1051            if let Ok(mut report_val) = serde_json::from_str::<serde_json::Value>(&report_str) {
1052                let formatted: Vec<String> = left_out
1053                    .iter()
1054                    .map(|(cmd, reason)| format!("{cmd} ({reason})"))
1055                    .collect();
1056                report_val["gate_left_out"] = serde_json::json!(formatted);
1057                if let Ok(updated) = serde_json::to_string_pretty(&report_val) {
1058                    let _ = std::fs::write(&report_path, updated + "\n");
1059                }
1060            }
1061        }
1062    }
1063
1064    let scratch_report = worktree_dir.join("report.md");
1065    if args.research {
1066        let is_non_empty = std::fs::metadata(&scratch_report)
1067            .map(|m| m.len() > 0)
1068            .unwrap_or(false);
1069        if is_non_empty {
1070            let _ = std::fs::copy(&scratch_report, &research_report_path);
1071            if let Some(block) = &research_sources {
1072                append_source_state(&research_report_path, block);
1073            }
1074            if let Some(ref report_to) = args.report_to {
1075                if let Some(parent) = report_to.parent() {
1076                    if !parent.as_os_str().is_empty() {
1077                        let _ = std::fs::create_dir_all(parent);
1078                    }
1079                }
1080                let _ = std::fs::copy(&scratch_report, report_to);
1081                if let Some(block) = &research_sources {
1082                    append_source_state(report_to, block);
1083                }
1084            }
1085        }
1086    }
1087
1088    // 5. Read report, commits and changed files
1089    let log_out = Command::new("git")
1090        .args([
1091            "-C",
1092            worktree_dir.to_str().unwrap(),
1093            "log",
1094            "--reverse",
1095            "--format=%h%x09%s",
1096            &format!("{base_sha}..HEAD"),
1097        ])
1098        .output();
1099
1100    let mut commits = Vec::new();
1101    if let Ok(o) = log_out {
1102        let text = String::from_utf8_lossy(&o.stdout);
1103        for line in text.lines() {
1104            let line = line.trim();
1105            if line.is_empty() {
1106                continue;
1107            }
1108            if let Some((sha, subject)) = line.split_once('\t') {
1109                commits.push(CommitRecord {
1110                    sha: sha.to_string(),
1111                    subject: subject.to_string(),
1112                });
1113            }
1114        }
1115    }
1116
1117    let diff_out = Command::new("git")
1118        .args([
1119            "-C",
1120            worktree_dir.to_str().unwrap(),
1121            "diff",
1122            "--name-only",
1123            &format!("{base_sha}..HEAD"),
1124        ])
1125        .output();
1126
1127    let mut changed_files = Vec::new();
1128    if let Ok(o) = diff_out {
1129        let text = String::from_utf8_lossy(&o.stdout);
1130        for line in text.lines() {
1131            let line = line.trim();
1132            if !line.is_empty() {
1133                changed_files.push(line.to_string());
1134            }
1135        }
1136    }
1137
1138    let report_read = std::fs::read_to_string(&report_path);
1139    let record: Result<serde_json::Value, String> = match report_read {
1140        Ok(s) => serde_json::from_str(&s).map_err(|e| format!("unreadable report JSON: {e}")),
1141        Err(e) => Err(format!("missing report: {e}")),
1142    };
1143
1144    let (
1145        report_outcome,
1146        error,
1147        final_message,
1148        turns,
1149        report_turns,
1150        gate_attempts,
1151        gate_failures,
1152        cost_usd,
1153        model,
1154        seconds,
1155        sandbox,
1156    ) = match record {
1157        Ok(rec) => {
1158            let gate_failures = rec
1159                .get("gate_failures")
1160                .and_then(|v| v.as_array())
1161                .map(|arr| {
1162                    arr.iter()
1163                        .filter_map(|v| v.as_str())
1164                        .map(|s| {
1165                            if s.chars().count() > 1000 {
1166                                s.chars().take(1000).collect()
1167                            } else {
1168                                s.to_string()
1169                            }
1170                        })
1171                        .collect()
1172                })
1173                .unwrap_or_default();
1174            let raw_turns = rec.get("turns").and_then(|v| v.as_u64());
1175
1176            (
1177                rec.get("outcome")
1178                    .and_then(|v| v.as_str())
1179                    .unwrap_or("error")
1180                    .to_string(),
1181                rec.get("error").and_then(|v| v.as_str()).map(String::from),
1182                rec.get("final_message")
1183                    .and_then(|v| v.as_str())
1184                    .map(String::from),
1185                raw_turns.unwrap_or(0) as u32,
1186                raw_turns,
1187                rec.get("gate_attempts")
1188                    .and_then(|v| v.as_u64())
1189                    .unwrap_or(0) as u32,
1190                gate_failures,
1191                rec.get("cost_usd").and_then(|v| v.as_f64()),
1192                rec.get("model_id")
1193                    .and_then(|v| v.as_str())
1194                    .map(String::from),
1195                rec.get("duration_seconds")
1196                    .and_then(|v| v.as_f64())
1197                    .unwrap_or(0.0)
1198                    .round() as u64,
1199                rec.get("sandbox")
1200                    .and_then(|v| v.as_str())
1201                    .unwrap_or(&args.sandbox)
1202                    .to_string(),
1203            )
1204        }
1205        Err(err_msg) => (
1206            "error".to_string(),
1207            Some(err_msg),
1208            None,
1209            0,
1210            None,
1211            0,
1212            Vec::new(),
1213            None,
1214            None,
1215            0,
1216            args.sandbox.clone(),
1217        ),
1218    };
1219
1220    let outcome = if args.research {
1221        match report_outcome.as_str() {
1222            "verified" => "verified",
1223            "gate_failed" => "gate_failed",
1224            "budget_exhausted" => "budget_exhausted",
1225            "blocked" => "blocked",
1226            _ => "error",
1227        }
1228    } else {
1229        dispatch_outcome(&report_outcome, commits.len())
1230    };
1231    let exit = exit_code(outcome);
1232
1233    if args.research {
1234        if research_report_path.exists() {
1235            if let Err(err) =
1236                crate::provenance::mark_if_unverified(&research_report_path, outcome, report_turns)
1237            {
1238                eprintln!(
1239                    "error: could not mark {} as not verified: {err}",
1240                    research_report_path.display()
1241                );
1242            }
1243        }
1244        if let Some(ref report_to) = args.report_to {
1245            if report_to.exists() {
1246                if let Err(err) =
1247                    crate::provenance::mark_if_unverified(report_to, outcome, report_turns)
1248                {
1249                    eprintln!(
1250                        "error: could not mark {} as not verified: {err}",
1251                        report_to.display()
1252                    );
1253                }
1254            }
1255        }
1256    }
1257
1258    let research_report = if args.research && research_report_path.exists() {
1259        Some(research_report_path.display().to_string())
1260    } else {
1261        None
1262    };
1263
1264    // 6. Print JSON summary
1265    let summary = DispatchSummary {
1266        id: args.id.clone(),
1267        worktree: worktree_dir.display().to_string(),
1268        branch,
1269        outcome,
1270        exit,
1271        error,
1272        commits,
1273        changed_files,
1274        final_message,
1275        turns,
1276        gate_attempts,
1277        gate_failures,
1278        cost_usd,
1279        model,
1280        seconds,
1281        sandbox,
1282        log: log_path.display().to_string(),
1283        report: report_path.display().to_string(),
1284        gate_source,
1285        research_report,
1286    };
1287
1288    finish_summary(&summary, &wt_parent)
1289}
1290
1291pub fn run_review(args: &ReviewArgs) -> i32 {
1292    let root = match crate::clean::find_repo_root() {
1293        Ok(r) => r,
1294        Err(e) => {
1295            eprintln!("error: {e}");
1296            return 2;
1297        }
1298    };
1299
1300    if args.notes.is_some() && args.verdict.is_none() {
1301        eprintln!("error: --notes requires --verdict");
1302        return 2;
1303    }
1304
1305    if let Some(ref v) = args.verdict {
1306        let wt_dir = root.join(".wt");
1307        if let Err(e) = std::fs::create_dir_all(&wt_dir) {
1308            eprintln!("error creating directory {}: {e}", wt_dir.display());
1309            return 2;
1310        }
1311        let verdict_path = wt_dir.join(format!("{}.verdict.json", args.id));
1312        let ts = std::time::SystemTime::now()
1313            .duration_since(std::time::UNIX_EPOCH)
1314            .map(|d| d.as_secs())
1315            .unwrap_or(0);
1316        let verdict_obj = serde_json::json!({
1317            "verdict": v.as_str(),
1318            "notes": args.notes.as_deref().unwrap_or(""),
1319            "ts": ts,
1320        });
1321        let json_str = match serde_json::to_string_pretty(&verdict_obj) {
1322            Ok(s) => s,
1323            Err(e) => {
1324                eprintln!("error serializing verdict: {e}");
1325                return 2;
1326            }
1327        };
1328        if let Err(e) = std::fs::write(&verdict_path, json_str + "\n") {
1329            eprintln!("error writing {}: {e}", verdict_path.display());
1330            return 2;
1331        }
1332        println!("recorded verdict {} for {}", v.as_str(), args.id);
1333        crate::clean::clean_on_review(&root, &args.id);
1334        return 0;
1335    }
1336
1337    let wt = root.join(".wt").join(&args.id);
1338    if !wt.exists() {
1339        eprintln!("error: worktree {} does not exist", wt.display());
1340        return 2;
1341    }
1342
1343    // Runs dispatched before base_sha was recorded have no start record field; a record that
1344    // exists but cannot be read is an error, not a reason to guess the base.
1345    let start_path = root.join(".wt").join(format!("{}.start.json", args.id));
1346    let start_base_sha: Option<String> = match std::fs::read_to_string(&start_path) {
1347        Ok(c) => match serde_json::from_str::<serde_json::Value>(&c) {
1348            Ok(v) => v
1349                .get("base_sha")
1350                .and_then(|s| s.as_str())
1351                .map(str::trim)
1352                .filter(|s| !s.is_empty())
1353                .map(String::from),
1354            Err(e) => {
1355                eprintln!("error: cannot parse {}: {e}", start_path.display());
1356                return 2;
1357            }
1358        },
1359        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
1360        Err(e) => {
1361            eprintln!("error: cannot read {}: {e}", start_path.display());
1362            return 2;
1363        }
1364    };
1365
1366    let base = if let Some(sha) = start_base_sha {
1367        let has_base = Command::new("git")
1368            .args(["cat-file", "-e", &format!("{sha}^{{commit}}")])
1369            .current_dir(&wt)
1370            .output()
1371            .map(|o| o.status.success())
1372            .unwrap_or(false);
1373        if !has_base {
1374            eprintln!(
1375                "error: run {} started from {sha}, which is not in this repository",
1376                args.id
1377            );
1378            return 2;
1379        }
1380        sha
1381    } else {
1382        let root_head = Command::new("git")
1383            .args(["rev-parse", "HEAD"])
1384            .current_dir(&root)
1385            .output();
1386        let root_head_sha = match root_head {
1387            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1388            _ => {
1389                eprintln!("error: could not resolve root HEAD");
1390                return 2;
1391            }
1392        };
1393
1394        let mb_out = Command::new("git")
1395            .args(["merge-base", "HEAD", &root_head_sha])
1396            .current_dir(&wt)
1397            .output();
1398        match mb_out {
1399            Ok(o) if o.status.success() => String::from_utf8_lossy(&o.stdout).trim().to_string(),
1400            _ => {
1401                eprintln!(
1402                    "error: cannot find where run {} started; its start record has no base_sha and the worktree shares no history with {root_head_sha}",
1403                    args.id
1404                );
1405                return 2;
1406            }
1407        }
1408    };
1409
1410    let commits_out = Command::new("git")
1411        .args(["log", "--oneline", &format!("{base}..HEAD")])
1412        .current_dir(&wt)
1413        .output()
1414        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1415        .unwrap_or_default();
1416
1417    let files_out = Command::new("git")
1418        .args(["diff", "--stat", &format!("{base}..HEAD")])
1419        .current_dir(&wt)
1420        .output()
1421        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1422        .unwrap_or_default();
1423
1424    let tree_out = Command::new("git")
1425        .args(["status", "--short"])
1426        .current_dir(&wt)
1427        .output()
1428        .map(|o| String::from_utf8_lossy(&o.stdout).trim().to_string())
1429        .unwrap_or_default();
1430
1431    let is_research = crate::clean::is_research(&root, &args.id)
1432        || root
1433            .join(".wt")
1434            .join(format!("{}.report.md", args.id))
1435            .exists();
1436
1437    let diff_res: Option<Result<String, String>> = if !is_research {
1438        Some(
1439            Command::new("git")
1440                .args(["diff", &format!("{base}..HEAD")])
1441                .current_dir(&wt)
1442                .output()
1443                .map_err(|e| e.to_string())
1444                .and_then(|o| {
1445                    if o.status.success() {
1446                        Ok(String::from_utf8_lossy(&o.stdout).into_owned())
1447                    } else {
1448                        let stderr = String::from_utf8_lossy(&o.stderr).trim().to_string();
1449                        if stderr.is_empty() {
1450                            Err(format!("exit {}", o.status))
1451                        } else {
1452                            Err(stderr)
1453                        }
1454                    }
1455                }),
1456        )
1457    } else if args.diff {
1458        Some(
1459            Command::new("git")
1460                .args(["diff", &format!("{base}..HEAD")])
1461                .current_dir(&wt)
1462                .output()
1463                .map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
1464                .map_err(|e| e.to_string()),
1465        )
1466    } else {
1467        None
1468    };
1469
1470    let diff_out = diff_res
1471        .as_ref()
1472        .and_then(|r| r.as_ref().ok())
1473        .map(|s| s.trim().to_string())
1474        .unwrap_or_default();
1475
1476    let task_text: Option<String> = (|| {
1477        let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1478        let content = std::fs::read_to_string(&start_file).ok()?;
1479        let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1480        let task_file = val.get("task_file")?.as_str()?;
1481        let p = Path::new(task_file);
1482        if let Ok(s) = std::fs::read_to_string(p) {
1483            return Some(s);
1484        }
1485        std::fs::read_to_string(root.join(p)).ok()
1486    })();
1487
1488    let changed_files: Vec<String> = Command::new("git")
1489        .args(["diff", "--name-only", &format!("{base}..HEAD")])
1490        .current_dir(&wt)
1491        .output()
1492        .ok()
1493        .filter(|o| o.status.success())
1494        .map(|o| {
1495            String::from_utf8_lossy(&o.stdout)
1496                .lines()
1497                .map(|l| l.trim().to_string())
1498                .filter(|l| !l.is_empty())
1499                .collect()
1500        })
1501        .unwrap_or_default();
1502
1503    let subjects: Vec<String> = Command::new("git")
1504        .args(["log", "--format=%s", &format!("{base}..HEAD")])
1505        .current_dir(&wt)
1506        .output()
1507        .ok()
1508        .filter(|o| o.status.success())
1509        .map(|o| {
1510            String::from_utf8_lossy(&o.stdout)
1511                .lines()
1512                .map(|l| l.trim().to_string())
1513                .filter(|l| !l.is_empty())
1514                .collect()
1515        })
1516        .unwrap_or_default();
1517
1518    let log_file = root.join(".wt").join(format!("{}.log", args.id));
1519    let (hcmds, reads, (refused_count, refused_paths)) =
1520        if let Ok(log_content) = std::fs::read_to_string(&log_file) {
1521            let hcmds = host_commands(&log_content);
1522            let home = std::env::var_os("HOME")
1523                .map(PathBuf::from)
1524                .unwrap_or_else(|| PathBuf::from("/"));
1525            let allowed = [root.clone(), wt.clone()];
1526            let reads = outside_reads(&log_content, &allowed, &home);
1527            let refused = refused_reads(&log_content);
1528            (hcmds, reads, refused)
1529        } else {
1530            (Vec::new(), Vec::new(), (0, Vec::new()))
1531        };
1532
1533    let report_file = root.join(".wt").join(format!("{}.report.json", args.id));
1534    let report_val = std::fs::read_to_string(&report_file)
1535        .ok()
1536        .and_then(|c| serde_json::from_str::<serde_json::Value>(&c).ok());
1537    let outcome = report_val
1538        .as_ref()
1539        .and_then(|v| v.get("outcome"))
1540        .and_then(|x| x.as_str());
1541    let quote_problems: Option<Vec<&str>> = report_val
1542        .as_ref()
1543        .and_then(|v| v.get("quote_problems"))
1544        .and_then(|x| x.as_array())
1545        .map(|arr| arr.iter().filter_map(|x| x.as_str()).collect());
1546    let read_loop = report_val
1547        .as_ref()
1548        .and_then(|v| v.get("read_loop"))
1549        .and_then(|x| x.as_bool())
1550        .unwrap_or(false);
1551    let gate_left_out: Vec<String> = report_val
1552        .as_ref()
1553        .and_then(|v| v.get("gate_left_out"))
1554        .and_then(|x| x.as_array())
1555        .map(|arr| {
1556            arr.iter()
1557                .filter_map(|x| x.as_str().map(String::from))
1558                .collect::<Vec<_>>()
1559        })
1560        .filter(|v| !v.is_empty())
1561        .or_else(|| {
1562            let start_file = root.join(".wt").join(format!("{}.start.json", args.id));
1563            let content = std::fs::read_to_string(&start_file).ok()?;
1564            let val: serde_json::Value = serde_json::from_str(&content).ok()?;
1565            let arr = val.get("gate_left_out")?.as_array()?;
1566            Some(
1567                arr.iter()
1568                    .filter_map(|item| {
1569                        let cmd = item.get("command")?.as_str()?;
1570                        let reason = item.get("reason")?.as_str()?;
1571                        Some(format!("{cmd} ({reason})"))
1572                    })
1573                    .collect(),
1574            )
1575        })
1576        .unwrap_or_default();
1577    let claim_check: Option<blyte_agent::claim_check::ClaimCheck> = report_val
1578        .as_ref()
1579        .and_then(|v| v.get("claim_check"))
1580        .and_then(|x| serde_json::from_value(x.clone()).ok());
1581    let claim_check_skipped: Option<String> = report_val
1582        .as_ref()
1583        .and_then(|v| v.get("claim_check_skipped"))
1584        .and_then(|x| x.as_str())
1585        .map(String::from);
1586
1587    let mut checks = crate::review_checks::build(
1588        task_text.as_deref(),
1589        &changed_files,
1590        &subjects,
1591        hcmds.len(),
1592        reads.len(),
1593        outcome,
1594    );
1595    let mut fallbacks: Vec<crate::fallback_check::Finding> = Vec::new();
1596    if !is_research {
1597        if let Some(ref res) = diff_res {
1598            match res {
1599                Ok(diff) => {
1600                    let findings = crate::fallback_check::added_fallbacks(diff);
1601                    if let Some(flag) = crate::fallback_check::flag(&findings) {
1602                        checks.flags.push(flag);
1603                    }
1604                    fallbacks = findings;
1605                }
1606                Err(reason) => {
1607                    let first_line = reason.lines().next().unwrap_or(reason.as_str());
1608                    let msg = format!("fallback check not run: git diff failed: {first_line}");
1609                    let cut: String = msg.chars().take(200).collect();
1610                    checks.flags.push(cut);
1611                }
1612            }
1613        }
1614    }
1615    if let Some(ref problems) = quote_problems {
1616        if !problems.is_empty() {
1617            checks.flags.push(format!(
1618                "quote check failed ({} problem(s)): see == report",
1619                problems.len()
1620            ));
1621        }
1622    }
1623    if read_loop {
1624        checks.flags.push(
1625            "read loop: the run kept re-reading the same files without changing anything and was stopped"
1626                .to_string(),
1627        );
1628    }
1629    if !gate_left_out.is_empty() {
1630        checks
1631            .flags
1632            .push(format!("gate left out: {}", gate_left_out.join("; ")));
1633    }
1634    if let Some(ref cc) = claim_check {
1635        if !cc.contradicted.is_empty() {
1636            checks.flags.push(format!(
1637                "claim check: {} contradicted claims",
1638                cc.contradicted.len()
1639            ));
1640        }
1641    }
1642    if let Some(ref skipped) = claim_check_skipped {
1643        checks.flags.push(format!("claim check skipped: {skipped}"));
1644    }
1645    if refused_count > 0 {
1646        let first_3: Vec<&str> = refused_paths.iter().take(3).map(|s| s.as_str()).collect();
1647        checks.flags.push(format!(
1648            "refused reads: {refused_count} (outside the workspace and --allow-read): {}",
1649            first_3.join(", ")
1650        ));
1651    }
1652    if is_research {
1653        match &report_val {
1654            Some(rv) => match crate::research_breadth::large_prompt_turns(rv) {
1655                Ok((large, total)) => {
1656                    if let Some(flag) = crate::research_breadth::breadth_flag(large, total) {
1657                        checks.flags.push(flag);
1658                    }
1659                }
1660                Err(e) => {
1661                    checks.flags.push(format!("breadth check not run: {e}"));
1662                }
1663            },
1664            None => {
1665                checks.flags.push(format!(
1666                    "breadth check not run: cannot read {}",
1667                    report_file.display()
1668                ));
1669            }
1670        }
1671        if outcome == Some("budget_exhausted") {
1672            match std::fs::read_to_string(&log_file) {
1673                Ok(log) => {
1674                    let dirs = crate::research_breadth::read_dirs(&log, &root);
1675                    if let Some(flag) = crate::research_breadth::split_flag(&dirs) {
1676                        checks.flags.push(flag);
1677                    }
1678                }
1679                Err(e) => {
1680                    checks.flags.push(format!("split suggestion not run: {e}"));
1681                }
1682            }
1683        }
1684    }
1685
1686    let checks_path = root.join(".wt").join(format!("{}.checks.json", args.id));
1687    let ts = match std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH) {
1688        Ok(d) => d.as_secs(),
1689        Err(e) => {
1690            eprintln!("error: the system clock is before 1970: {e}");
1691            return 2;
1692        }
1693    };
1694    let checks_obj = serde_json::json!({
1695        "ts": ts,
1696        "flags": &checks.flags,
1697        "fallbacks": &fallbacks,
1698    });
1699    let checks_json = match serde_json::to_string_pretty(&checks_obj) {
1700        Ok(s) => s,
1701        Err(e) => {
1702            eprintln!("error writing {}: {e}", checks_path.display());
1703            return 2;
1704        }
1705    };
1706    if let Err(e) = std::fs::write(&checks_path, checks_json + "\n") {
1707        eprintln!("error writing {}: {e}", checks_path.display());
1708        return 2;
1709    }
1710
1711    println!("== checks");
1712    if checks.flags.is_empty() {
1713        println!("nothing flagged");
1714    } else {
1715        for flag in &checks.flags {
1716            println!("! {flag}");
1717        }
1718    }
1719
1720    println!("== commits");
1721    if !commits_out.is_empty() {
1722        println!("{commits_out}");
1723    }
1724    println!("== files");
1725    if !files_out.is_empty() {
1726        println!("{files_out}");
1727    }
1728    println!("== tree");
1729    if tree_out.is_empty() {
1730        println!("(clean)");
1731    } else {
1732        println!("{tree_out}");
1733    }
1734    println!("== report");
1735    if let Some(ref v) = report_val {
1736        if let Some(outcome) = v.get("outcome").and_then(|x| x.as_str()) {
1737            println!("outcome: {outcome}");
1738        }
1739        if let Some(turns) = v.get("turns").and_then(|x| x.as_u64()) {
1740            println!("turns: {turns}");
1741        }
1742        if let Some(cost) = v.get("cost_usd").and_then(|x| x.as_f64()) {
1743            println!("cost_usd: {cost}");
1744        }
1745        if let Some(msg) = v.get("final_message").and_then(|x| x.as_str()) {
1746            println!("final_message: {msg}");
1747        }
1748        if let Some(ref problems) = quote_problems {
1749            if problems.is_empty() {
1750                println!("quote check: passed");
1751            } else {
1752                println!(
1753                    "quote check: FAILED, {} problems (the report's quotes do not match the code)",
1754                    problems.len()
1755                );
1756                for p in problems.iter().take(5) {
1757                    let cut: String = p.chars().take(200).collect();
1758                    println!("  {cut}");
1759                }
1760            }
1761        }
1762        if let Some(ref cc) = claim_check {
1763            println!(
1764                "claim check: {} checked, {} contradicted, {} not enough evidence, {} parse errors, {} unchecked",
1765                cc.checked,
1766                cc.contradicted.len(),
1767                cc.not_enough_evidence,
1768                cc.parse_errors,
1769                cc.unchecked
1770            );
1771            for f in cc.contradicted.iter().take(5) {
1772                let cut: String = f.text.chars().take(200).collect();
1773                println!("  report.md:{}: {cut}", f.line);
1774                println!("    {}", f.reason);
1775            }
1776        }
1777        if let Some(ref skipped) = claim_check_skipped {
1778            println!("claim check skipped: {skipped}");
1779        }
1780    }
1781
1782    let research_report_file = root.join(".wt").join(format!("{}.report.md", args.id));
1783    if research_report_file.exists() {
1784        println!("== research report");
1785        println!("{}", research_report_file.display());
1786        if let Ok(content) = std::fs::read_to_string(&research_report_file) {
1787            for line in content.lines().take(40) {
1788                println!("{line}");
1789            }
1790        }
1791    }
1792
1793    if !hcmds.is_empty() {
1794        println!("== host commands (may have changed things outside the worktree)");
1795        for cmd in hcmds {
1796            println!("{cmd}");
1797        }
1798    }
1799    if !reads.is_empty() {
1800        println!("== reads outside the repository");
1801        for cmd in reads {
1802            println!("{cmd}");
1803        }
1804    }
1805
1806    if args.diff {
1807        println!("== diff");
1808        if !diff_out.is_empty() {
1809            println!("{diff_out}");
1810        }
1811    }
1812
1813    if args.model_review {
1814        crate::model_review::run(&root, &args.id, &base, &wt);
1815    }
1816
1817    0
1818}
1819
1820const OUTSIDE_PATHS: &[&str] = &[
1821    "~/",
1822    "$HOME",
1823    "/Users/",
1824    "/home/",
1825    "/private/",
1826    "/var/",
1827    "/etc/",
1828    "/opt/",
1829    "/usr/",
1830];
1831
1832const CHANGE_WORDS: &[&str] = &[
1833    "rm", "rmdir", "mv", "cp", "chmod", "chown", "truncate", "dd", "tee", "ln",
1834];
1835
1836fn contains_word(cmd: &str, word: &str) -> bool {
1837    let mut start = 0;
1838    while let Some(pos) = cmd[start..].find(word) {
1839        let abs_pos = start + pos;
1840        let before_ok = if abs_pos == 0 {
1841            true
1842        } else {
1843            let prev = cmd[..abs_pos].chars().next_back().unwrap();
1844            !prev.is_alphanumeric() && prev != '_' && prev != '-'
1845        };
1846        let after_pos = abs_pos + word.len();
1847        let after_ok = if after_pos >= cmd.len() {
1848            true
1849        } else {
1850            let next = cmd[after_pos..].chars().next().unwrap();
1851            !next.is_alphanumeric() && next != '_' && next != '-'
1852        };
1853        if before_ok && after_ok {
1854            return true;
1855        }
1856        start = abs_pos + word.len();
1857    }
1858    false
1859}
1860
1861fn has_non_dev_null_redirect(cmd: &str) -> bool {
1862    let chars: Vec<char> = cmd.chars().collect();
1863    let mut i = 0;
1864    while i < chars.len() {
1865        if chars[i] == '>' {
1866            while i < chars.len() && chars[i] == '>' {
1867                i += 1;
1868            }
1869            if i < chars.len() && chars[i] == '|' {
1870                i += 1;
1871            }
1872            while i < chars.len() && chars[i].is_whitespace() {
1873                i += 1;
1874            }
1875            if i >= chars.len() {
1876                break;
1877            }
1878            if chars[i] == '&'
1879                && i + 1 < chars.len()
1880                && (chars[i + 1].is_ascii_digit() || chars[i + 1] == '-')
1881            {
1882                i += 1;
1883                continue;
1884            }
1885            let target_start = i;
1886            while i < chars.len()
1887                && !chars[i].is_whitespace()
1888                && chars[i] != ';'
1889                && chars[i] != '|'
1890                && chars[i] != '&'
1891                && chars[i] != ')'
1892            {
1893                i += 1;
1894            }
1895            let target: String = chars[target_start..i].iter().collect();
1896            let target = target.trim_matches(|c| c == '\'' || c == '"');
1897            if !target.is_empty() && target != "/dev/null" {
1898                return true;
1899            }
1900        } else {
1901            i += 1;
1902        }
1903    }
1904    false
1905}
1906
1907fn changes_something(cmd: &str) -> bool {
1908    for &word in CHANGE_WORDS {
1909        if contains_word(cmd, word) {
1910            return true;
1911        }
1912    }
1913    has_non_dev_null_redirect(cmd)
1914}
1915
1916fn is_host_command(cmd: &str) -> bool {
1917    if cmd.contains("git push")
1918        || cmd.contains("sudo ")
1919        || cmd.contains("cache clean")
1920        || cmd.contains("cache prune")
1921        || cmd.contains("brew ")
1922    {
1923        return true;
1924    }
1925
1926    let names_outside = OUTSIDE_PATHS.iter().any(|path| cmd.contains(path));
1927    names_outside && changes_something(cmd)
1928}
1929
1930pub fn host_commands(log: &str) -> Vec<String> {
1931    let cleaned = strip_ansi(log);
1932    let mut result = Vec::new();
1933    for line in cleaned.lines() {
1934        let trimmed = line.trim();
1935        if let Some(rest) = trimmed.strip_prefix("● bash ") {
1936            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
1937                let cmd = cmd.trim();
1938                if is_host_command(cmd) && !result.iter().any(|c| c == cmd) {
1939                    result.push(cmd.to_string());
1940                    if result.len() == 20 {
1941                        break;
1942                    }
1943                }
1944            }
1945        }
1946    }
1947    result
1948}
1949
1950const TERMINAL_READS: &[&str] = &[
1951    "herdr pane read",
1952    "tmux capture-pane",
1953    "screen -X hardcopy",
1954    "zellij action dump-screen",
1955    "wezterm cli get-text",
1956];
1957
1958const TOOL_CACHES: &[&str] = &[
1959    ".cargo",
1960    ".rustup",
1961    ".cache",
1962    ".npm",
1963    ".local",
1964    "Library/Caches",
1965    ".gradle",
1966    ".m2",
1967    "go",
1968];
1969
1970fn normalize_path(path: &Path) -> PathBuf {
1971    use std::path::Component;
1972    let mut out = PathBuf::new();
1973    for comp in path.components() {
1974        match comp {
1975            Component::ParentDir => {
1976                out.pop();
1977            }
1978            Component::CurDir => {}
1979            _ => out.push(comp),
1980        }
1981    }
1982    out
1983}
1984
1985fn is_outside_read(cmd: &str, allowed: &[PathBuf], home: &Path, tool_caches: &[PathBuf]) -> bool {
1986    if TERMINAL_READS.iter().any(|pattern| cmd.contains(pattern)) {
1987        return true;
1988    }
1989
1990    for raw_word in cmd.split_whitespace() {
1991        let word = raw_word.trim_end_matches(&[':', ',', ')', '\'', '"'][..]);
1992        let raw_path = if let Some(suffix) = word.strip_prefix("~/") {
1993            Some(home.join(suffix))
1994        } else if let Some(suffix) = word.strip_prefix("$HOME/") {
1995            Some(home.join(suffix))
1996        } else if word.starts_with('/') {
1997            Some(PathBuf::from(word))
1998        } else {
1999            None
2000        };
2001
2002        if let Some(path) = raw_path {
2003            let norm_path = normalize_path(&path);
2004            if !norm_path.starts_with(home) {
2005                continue;
2006            }
2007            let under_allowed = allowed.iter().any(|a| norm_path.starts_with(a));
2008            if under_allowed {
2009                continue;
2010            }
2011            let under_cache = tool_caches.iter().any(|c| norm_path.starts_with(c));
2012            if under_cache {
2013                continue;
2014            }
2015            return true;
2016        }
2017    }
2018
2019    false
2020}
2021
2022pub fn outside_reads(log: &str, allowed: &[PathBuf], home: &Path) -> Vec<String> {
2023    let host_cmds = host_commands(log);
2024    let norm_home = normalize_path(home);
2025    let norm_allowed: Vec<PathBuf> = allowed.iter().map(|p| normalize_path(p)).collect();
2026    let cache_dirs: Vec<PathBuf> = TOOL_CACHES
2027        .iter()
2028        .map(|c| normalize_path(&norm_home.join(c)))
2029        .collect();
2030
2031    let cleaned = strip_ansi(log);
2032    let mut result = Vec::new();
2033    for line in cleaned.lines() {
2034        let trimmed = line.trim();
2035        if let Some(rest) = trimmed.strip_prefix("● bash ") {
2036            if let Some((cmd, _)) = rest.rsplit_once(" -> ") {
2037                let cmd = cmd.trim();
2038                if host_cmds.iter().any(|c| c == cmd) {
2039                    continue;
2040                }
2041                if is_outside_read(cmd, &norm_allowed, &norm_home, &cache_dirs)
2042                    && !result.iter().any(|c| c == cmd)
2043                {
2044                    result.push(cmd.to_string());
2045                    if result.len() == 20 {
2046                        break;
2047                    }
2048                }
2049            }
2050        }
2051    }
2052    result
2053}
2054
2055fn strip_ansi(s: &str) -> String {
2056    let mut out = String::with_capacity(s.len());
2057    let mut chars = s.chars().peekable();
2058    while let Some(c) = chars.next() {
2059        if c == '\x1b' && chars.peek() == Some(&'[') {
2060            chars.next();
2061            while let Some(&next_c) = chars.peek() {
2062                chars.next();
2063                if ('\x40'..='\x7e').contains(&next_c) {
2064                    break;
2065                }
2066                if next_c == '\n' || next_c == '\x1b' {
2067                    out.push(next_c);
2068                    break;
2069                }
2070            }
2071            continue;
2072        }
2073        out.push(c);
2074    }
2075    out
2076}
2077
2078#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
2079pub struct LogProgress {
2080    pub turn: u32,
2081    pub last_tool: Option<String>,
2082    pub gate_attempts: u32,
2083    pub gate_passed: bool,
2084}
2085
2086pub fn parse_log(log: &str) -> LogProgress {
2087    let cleaned = strip_ansi(log);
2088    let mut turn: u32 = 0;
2089    let mut last_tool: Option<String> = None;
2090    let mut gate_attempts: u32 = 0;
2091    let mut gate_passed: bool = false;
2092
2093    for line in cleaned.lines() {
2094        if let Some(rest) = line.strip_prefix("[Turn ") {
2095            if let Some((n_str, _)) = rest.split_once(']') {
2096                if let Ok(n) = n_str.trim().parse::<u32>() {
2097                    turn = turn.max(n);
2098                }
2099            }
2100        }
2101
2102        if let Some(tool) = line.strip_prefix("● ") {
2103            let truncated = if tool.chars().count() > 200 {
2104                tool.chars().take(200).collect()
2105            } else {
2106                tool.to_string()
2107            };
2108            last_tool = Some(truncated);
2109        }
2110
2111        if line.starts_with("✓ Gate passed") {
2112            gate_attempts += 1;
2113            gate_passed = true;
2114        } else if line.starts_with("✗ Gate failed") {
2115            gate_attempts += 1;
2116            gate_passed = false;
2117        }
2118    }
2119
2120    LogProgress {
2121        turn,
2122        last_tool,
2123        gate_attempts,
2124        gate_passed,
2125    }
2126}
2127
2128#[derive(Debug, Serialize)]
2129pub struct StatusOutput {
2130    pub id: String,
2131    pub state: String,
2132    pub elapsed_s: u64,
2133    pub turn: u32,
2134    pub last_tool: Option<String>,
2135    pub gate_attempts: u32,
2136    pub gate_passed: bool,
2137    pub outcome: Option<String>,
2138    pub cost_usd: Option<f64>,
2139    pub final_message: Option<String>,
2140}
2141
2142pub fn run_status(id: &str, json: bool) -> i32 {
2143    let root = match crate::clean::find_repo_root() {
2144        Ok(r) => r,
2145        Err(e) => {
2146            eprintln!("error: {e}");
2147            return 2;
2148        }
2149    };
2150
2151    let start_path = root.join(".wt").join(format!("{id}.start.json"));
2152    if !start_path.exists() {
2153        eprintln!("no dispatch {id} here");
2154        return 2;
2155    }
2156
2157    let start_record: serde_json::Value = match std::fs::read_to_string(&start_path) {
2158        Ok(s) => match serde_json::from_str(&s) {
2159            Ok(v) => v,
2160            Err(e) => {
2161                eprintln!("error parsing {}: {e}", start_path.display());
2162                return 2;
2163            }
2164        },
2165        Err(e) => {
2166            eprintln!("error reading {}: {e}", start_path.display());
2167            return 2;
2168        }
2169    };
2170
2171    let pid = start_record
2172        .get("pid")
2173        .and_then(|v| v.as_i64())
2174        .map(|v| v as libc::pid_t);
2175    let started_at = start_record
2176        .get("started_at")
2177        .and_then(|v| v.as_u64())
2178        .unwrap_or(0);
2179
2180    let is_alive = if let Some(pid) = pid {
2181        if pid > 0 {
2182            let ret = unsafe { libc::kill(pid, 0) };
2183            if ret == 0 {
2184                true
2185            } else {
2186                std::io::Error::last_os_error().raw_os_error() == Some(libc::EPERM)
2187            }
2188        } else {
2189            false
2190        }
2191    } else {
2192        false
2193    };
2194
2195    let report_path = root.join(".wt").join(format!("{id}.report.json"));
2196    let report_exists = report_path.exists();
2197
2198    let state = if report_exists {
2199        "finished"
2200    } else if is_alive {
2201        "running"
2202    } else {
2203        "dead"
2204    };
2205
2206    let now = std::time::SystemTime::now()
2207        .duration_since(std::time::UNIX_EPOCH)
2208        .map(|d| d.as_secs())
2209        .unwrap_or(0);
2210
2211    let (outcome, cost_usd, final_message, report_duration) = if state == "finished" {
2212        if let Ok(content) = std::fs::read_to_string(&report_path) {
2213            if let Ok(v) = serde_json::from_str::<serde_json::Value>(&content) {
2214                let outcome = v.get("outcome").and_then(|x| x.as_str()).map(String::from);
2215                let cost_usd = v.get("cost_usd").and_then(|x| x.as_f64());
2216                let final_message = v.get("final_message").and_then(|x| x.as_str()).map(|s| {
2217                    if s.chars().count() > 500 {
2218                        s.chars().take(500).collect()
2219                    } else {
2220                        s.to_string()
2221                    }
2222                });
2223                let duration = v.get("duration_seconds").and_then(|x| x.as_f64());
2224                (outcome, cost_usd, final_message, duration)
2225            } else {
2226                (None, None, None, None)
2227            }
2228        } else {
2229            (None, None, None, None)
2230        }
2231    } else {
2232        (None, None, None, None)
2233    };
2234
2235    let elapsed_s = if state == "finished" {
2236        report_duration
2237            .map(|d| d.round() as u64)
2238            .unwrap_or_else(|| now.saturating_sub(started_at))
2239    } else {
2240        now.saturating_sub(started_at)
2241    };
2242
2243    let log_path = root.join(".wt").join(format!("{id}.log"));
2244    let log_content = std::fs::read_to_string(&log_path).unwrap_or_default();
2245    let progress = parse_log(&log_content);
2246
2247    if json {
2248        let status_obj = StatusOutput {
2249            id: id.to_string(),
2250            state: state.to_string(),
2251            elapsed_s,
2252            turn: progress.turn,
2253            last_tool: progress.last_tool,
2254            gate_attempts: progress.gate_attempts,
2255            gate_passed: progress.gate_passed,
2256            outcome,
2257            cost_usd,
2258            final_message,
2259        };
2260        let json_str = serde_json::to_string_pretty(&status_obj).unwrap();
2261        println!("{json_str}");
2262    } else {
2263        println!("id: {id}");
2264        println!("state: {state}");
2265        println!("elapsed_s: {elapsed_s}");
2266        println!("turn: {}", progress.turn);
2267        println!(
2268            "last_tool: {}",
2269            progress.last_tool.as_deref().unwrap_or("none")
2270        );
2271        println!("gate_attempts: {}", progress.gate_attempts);
2272        println!("gate_passed: {}", progress.gate_passed);
2273        if state == "finished" {
2274            if let Some(ref o) = outcome {
2275                println!("outcome: {o}");
2276            }
2277            if let Some(c) = cost_usd {
2278                println!("cost_usd: {c}");
2279            }
2280            if let Some(ref msg) = final_message {
2281                println!("final_message: {msg}");
2282            }
2283        }
2284    }
2285
2286    match state {
2287        "running" | "finished" => 0,
2288        _ => 1,
2289    }
2290}
2291
2292pub fn unreadable_paths(text: &str, readable: &[PathBuf]) -> Vec<PathBuf> {
2293    let readable_canon: Vec<PathBuf> = readable
2294        .iter()
2295        .filter_map(|r| std::fs::canonicalize(r).ok())
2296        .collect();
2297    let mut out = Vec::new();
2298    for raw in text.split(|c: char| {
2299        c.is_whitespace()
2300            || matches!(
2301                c,
2302                '`' | '"' | '\'' | '(' | ')' | '[' | ']' | '{' | '}' | '<' | '>'
2303            )
2304    }) {
2305        let trimmed = raw.trim_end_matches(['.', ',', ';', ':', '!', '?']);
2306        if !trimmed.starts_with('/')
2307            || trimmed.starts_with("//")
2308            || trimmed.len() <= 1
2309            || trimmed == "/dev/null"
2310        {
2311            continue;
2312        }
2313        let p = Path::new(trimmed);
2314        let Ok(canon) = std::fs::canonicalize(p) else {
2315            continue;
2316        };
2317        if readable_canon.iter().any(|r| canon.starts_with(r))
2318            || is_system_path(p)
2319            || is_system_path(&canon)
2320        {
2321            continue;
2322        }
2323        let pb = PathBuf::from(trimmed);
2324        if !out.contains(&pb) {
2325            out.push(pb);
2326        }
2327    }
2328    out
2329}
2330
2331/// A path no research task means as code to read: the filesystem root, a top-level directory,
2332/// or anything under the system directories (`/usr/bin/env`, `/tmp`, `/dev/null`).
2333fn is_system_path(p: &Path) -> bool {
2334    const SYSTEM: &[&str] = &[
2335        "/usr",
2336        "/bin",
2337        "/sbin",
2338        "/etc",
2339        "/dev",
2340        "/opt",
2341        "/System",
2342        "/Library",
2343        "/Applications",
2344        "/nix",
2345        "/proc",
2346        "/sys",
2347    ];
2348    p.components().count() <= 2 || SYSTEM.iter().any(|s| p.starts_with(s))
2349}
2350
2351pub fn refused_reads(log_content: &str) -> (usize, Vec<String>) {
2352    let mut count = 0;
2353    let mut paths = Vec::new();
2354    for line in log_content.lines() {
2355        if !line.contains("path escapes the workspace") {
2356            continue;
2357        }
2358        count += 1;
2359        if let Some((_, after)) = line.split_once("path escapes the workspace:") {
2360            let after = after.trim_start();
2361            let after = after.split("\x1b[").next().unwrap_or(after);
2362            let path = after
2363                .split(". This run can read")
2364                .next()
2365                .unwrap_or(after)
2366                .trim();
2367            if !path.is_empty() && !paths.iter().any(|p| p == path) {
2368                paths.push(path.to_string());
2369            }
2370        }
2371    }
2372    (count, paths)
2373}
2374
2375#[cfg(test)]
2376mod tests {
2377    use super::*;
2378
2379    #[test]
2380    fn outside_reads_excludes_commands_in_host_commands() {
2381        let home = Path::new("/Users/u");
2382        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2383        // rm -rf ~/repos/other is a host command (names outside and changes something)
2384        // cat ~/repos/other is not a host command (only reads)
2385        let log = "\
2386● bash rm -rf ~/repos/other/file.py -> exit 0
2387● bash cat ~/repos/other/file.py -> exit 0
2388";
2389        assert_eq!(
2390            host_commands(log),
2391            vec!["rm -rf ~/repos/other/file.py".to_string()]
2392        );
2393        assert_eq!(
2394            outside_reads(log, &allowed, home),
2395            vec!["cat ~/repos/other/file.py".to_string()]
2396        );
2397    }
2398
2399    #[test]
2400    fn outside_reads_all_terminal_patterns() {
2401        let home = Path::new("/Users/u");
2402        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2403        let log = "\
2404● bash herdr pane read p1 -> exit 0
2405● bash tmux capture-pane -t 1 -> exit 0
2406● bash screen -X hardcopy /tmp/screen.log -> exit 0
2407● bash zellij action dump-screen /tmp/dump -> exit 0
2408● bash wezterm cli get-text --pane-id 1 -> exit 0
2409";
2410        let reads = outside_reads(log, &allowed, home);
2411        assert_eq!(
2412            reads,
2413            vec![
2414                "herdr pane read p1",
2415                "tmux capture-pane -t 1",
2416                "screen -X hardcopy /tmp/screen.log",
2417                "zellij action dump-screen /tmp/dump",
2418                "wezterm cli get-text --pane-id 1",
2419            ]
2420        );
2421    }
2422
2423    #[test]
2424    fn outside_reads_all_tool_caches_ignored() {
2425        let home = Path::new("/Users/u");
2426        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2427        let log = "\
2428● bash ls ~/.cargo/bin -> exit 0
2429● bash ls ~/.rustup/toolchains -> exit 0
2430● bash ls ~/.cache/pip -> exit 0
2431● bash ls ~/.npm/_cacache -> exit 0
2432● bash ls ~/.local/share -> exit 0
2433● bash ls ~/Library/Caches/com.apple -> exit 0
2434● bash ls ~/.gradle/caches -> exit 0
2435● bash ls ~/.m2/repository -> exit 0
2436● bash ls ~/go/pkg -> exit 0
2437";
2438        assert!(outside_reads(log, &allowed, home).is_empty());
2439    }
2440
2441    #[test]
2442    fn outside_reads_trailing_punctuations_stripped() {
2443        let home = Path::new("/Users/u");
2444        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2445        let log = "\
2446● bash ls ~/secret: -> exit 0
2447● bash ls ~/secret, -> exit 0
2448● bash (ls ~/secret) -> exit 0
2449● bash bash -c 'ls ~/secret' -> exit 0
2450● bash bash -c \"ls ~/secret\" -> exit 0
2451";
2452        let reads = outside_reads(log, &allowed, home);
2453        // Deduplicated, so only one instance of the command or distinct commands:
2454        assert_eq!(reads.len(), 5);
2455    }
2456
2457    #[test]
2458    fn outside_reads_caps_at_20_and_deduplicates() {
2459        let home = Path::new("/Users/u");
2460        let allowed = vec![PathBuf::from("/Users/u/repos/app")];
2461        let mut log = String::new();
2462        for i in 0..30 {
2463            log.push_str(&format!("● bash cat ~/secret/{i}.txt -> exit 0\n"));
2464        }
2465        // Duplicate the first one
2466        log.push_str("● bash cat ~/secret/0.txt -> exit 0\n");
2467        let reads = outside_reads(&log, &allowed, home);
2468        assert_eq!(reads.len(), 20);
2469        assert_eq!(reads[0], "cat ~/secret/0.txt");
2470        assert_eq!(reads[19], "cat ~/secret/19.txt");
2471    }
2472}