Skip to main content

blyte_cli/
dispatch.rs

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