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