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