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