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