Skip to main content

blyte_cli/
direct_edit.rs

1//! `blyte edit-start` and `blyte edit-finish` commands.
2
3use blyte_agent::run::run_gate_steps;
4use blyte_agent::shell::{LocalShell, Output, Shell};
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9use std::sync::Mutex;
10use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
11
12use crate::cli::{EditFinishArgs, EditStartArgs};
13use crate::dispatch::{CommitRecord, DispatchSummary};
14use crate::report::{RunRecord, UsageRecord, SCHEMA_VERSION};
15
16const TAIL_MAX_LINES: usize = 80;
17const TAIL_MAX_BYTES: usize = 8192;
18const ALREADY_PASSED_LOG: &str = "check skipped: tree already passed\n";
19
20#[derive(Debug, Clone, Serialize, Deserialize)]
21pub struct EditRecord {
22    pub id: String,
23    pub base: String,
24    pub base_sha: String,
25    pub started_at: u64,
26}
27
28#[derive(Debug, Serialize)]
29pub struct EditStartOutput {
30    pub id: String,
31    pub path: String,
32    pub base_sha: String,
33}
34
35#[derive(Debug, Serialize)]
36pub struct EditGateFailedOutput {
37    pub id: String,
38    pub outcome: &'static str,
39    pub failing_step: String,
40    pub output_tail: String,
41}
42
43#[derive(Debug, Serialize)]
44pub struct EditOutOfScopeOutput {
45    pub id: String,
46    pub outcome: &'static str,
47    pub changed_files: Vec<String>,
48    pub error: String,
49}
50
51#[derive(Debug, Serialize)]
52pub struct EditReviewFinding {
53    pub file: String,
54    pub line: Option<u64>,
55    pub text: String,
56}
57
58#[derive(Debug, Serialize)]
59pub struct EditReviewFindingsOutput {
60    pub id: String,
61    pub outcome: &'static str,
62    pub findings: Vec<EditReviewFinding>,
63}
64
65pub fn direct_edit_scope(changed: &[String]) -> Result<(), String> {
66    if changed.len() <= 1 || changed.iter().all(|p| is_documentation_path(p)) {
67        return Ok(());
68    }
69    Err(format!(
70        "direct edits are for documentation or a change confined to one file; this edit changes {} files ({}): hand it to a run with blyte dispatch",
71        changed.len(),
72        changed.join(", ")
73    ))
74}
75
76fn is_documentation_path(path: &str) -> bool {
77    if path.starts_with("docs/") {
78        return true;
79    }
80    let p = Path::new(path);
81    if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
82        if matches!(
83            ext.to_ascii_lowercase().as_str(),
84            "md" | "mdx" | "rst" | "txt" | "adoc"
85        ) {
86            return true;
87        }
88    }
89    p.file_name().and_then(|n| n.to_str()).is_some_and(|name| {
90        name.starts_with("README") || name.starts_with("CHANGELOG") || name.starts_with("LICENSE")
91    })
92}
93
94struct StepOutput {
95    command: String,
96    output: String,
97}
98
99struct GateOutcome {
100    elapsed: Duration,
101    gate_attempts: u32,
102    gate_wait_ms: u64,
103    log_text: String,
104}
105
106struct EnvShell<S> {
107    inner: S,
108    env: BTreeMap<String, String>,
109    steps: Mutex<Vec<StepOutput>>,
110}
111
112impl<S: Shell> Shell for EnvShell<S> {
113    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
114        let res = if self.env.is_empty() {
115            self.inner.exec(command, cwd, timeout)
116        } else {
117            let mut script = String::new();
118            for (k, v) in &self.env {
119                let quoted = format!("'{}'", v.replace('\'', "'\\''"));
120                script.push_str(&format!("export {k}={quoted}\n"));
121            }
122            script.push_str(command);
123            self.inner.exec(&script, cwd, timeout)
124        };
125        let recorded = match &res {
126            Ok(out) => format_step_output(out),
127            Err(e) => format!("error: {e}\n"),
128        };
129        self.steps.lock().unwrap().push(StepOutput {
130            command: command.to_string(),
131            output: recorded,
132        });
133        res
134    }
135
136    fn describe(&self) -> String {
137        self.inner.describe()
138    }
139}
140
141fn format_step_output(out: &Output) -> String {
142    let mut text = String::new();
143    if !out.stdout.is_empty() {
144        text.push_str(&out.stdout);
145        if !text.ends_with('\n') {
146            text.push('\n');
147        }
148    }
149    if !out.stderr.is_empty() {
150        text.push_str(&out.stderr);
151        if !text.ends_with('\n') {
152            text.push('\n');
153        }
154    }
155    if text.is_empty() || out.exit_code != 0 {
156        text.push_str(&format!("exit {}\n", out.exit_code));
157    }
158    text
159}
160
161fn format_gate_log(steps: &[StepOutput]) -> String {
162    let mut log = String::new();
163    for (idx, step) in steps.iter().enumerate() {
164        if idx > 0 {
165            log.push('\n');
166        }
167        log.push_str(&format!("$ {}\n", step.command));
168        log.push_str(&step.output);
169    }
170    log
171}
172
173fn write_log(path: &Path, content: &str) -> Result<(), String> {
174    std::fs::write(path, content).map_err(|e| format!("cannot write log {}: {e}", path.display()))
175}
176
177fn tail_output(text: &str, max_lines: usize, max_bytes: usize) -> String {
178    let lines: Vec<&str> = text.lines().collect();
179    let start = lines.len().saturating_sub(max_lines);
180    let mut joined = lines[start..].join("\n");
181    if joined.len() > max_bytes {
182        let mut cut = joined.len() - max_bytes;
183        while cut < joined.len() && !joined.is_char_boundary(cut) {
184            cut += 1;
185        }
186        joined = joined[cut..].to_string();
187    }
188    joined
189}
190
191fn now_secs() -> Result<u64, String> {
192    SystemTime::now()
193        .duration_since(UNIX_EPOCH)
194        .map(|d| d.as_secs())
195        .map_err(|e| format!("system clock before unix epoch: {e}"))
196}
197
198fn git_toplevel() -> Result<PathBuf, String> {
199    let out = Command::new("git")
200        .args(["rev-parse", "--show-toplevel"])
201        .output()
202        .map_err(|e| format!("failed to execute git: {e}"))?;
203    if !out.status.success() {
204        return Err("not a git repository".to_string());
205    }
206    Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
207}
208
209fn ensure_wt_excluded(root: &Path) {
210    let common_dir_raw = Command::new("git")
211        .args(["rev-parse", "--git-common-dir"])
212        .current_dir(root)
213        .output();
214    let common_dir = if let Ok(out) = common_dir_raw {
215        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
216        if p.is_absolute() {
217            p
218        } else {
219            root.join(p)
220        }
221    } else {
222        root.join(".git")
223    };
224
225    let exclude_path = common_dir.join("info").join("exclude");
226    if let Some(parent) = exclude_path.parent() {
227        let _ = std::fs::create_dir_all(parent);
228    }
229    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
230    if !content.lines().any(|l| l.trim() == ".wt/") {
231        let mut new_content = content;
232        if !new_content.is_empty() && !new_content.ends_with('\n') {
233            new_content.push('\n');
234        }
235        new_content.push_str(".wt/\n");
236        let _ = std::fs::write(&exclude_path, new_content);
237    }
238}
239
240fn branch_exists(root: &Path, branch: &str) -> Result<bool, String> {
241    let branch_ref = format!("refs/heads/{branch}");
242    let out = Command::new("git")
243        .args(["show-ref", "--verify", "--quiet", &branch_ref])
244        .current_dir(root)
245        .output()
246        .map_err(|e| format!("git show-ref --verify --quiet {branch_ref}: {e}"))?;
247    if out.status.success() {
248        Ok(true)
249    } else if out.status.code() == Some(1) {
250        Ok(false)
251    } else {
252        Err(format!(
253            "git show-ref --verify --quiet {branch_ref}: {}",
254            String::from_utf8_lossy(&out.stderr).trim()
255        ))
256    }
257}
258
259fn cleanup_worktree_and_branch(root: &Path, worktree_dir: &Path, branch: &str) {
260    let _ = Command::new("git")
261        .args(["worktree", "remove", "--force"])
262        .arg(worktree_dir)
263        .current_dir(root)
264        .output();
265    if worktree_dir.exists() {
266        let _ = std::fs::remove_dir_all(worktree_dir);
267    }
268    let _ = Command::new("git")
269        .args(["worktree", "prune"])
270        .current_dir(root)
271        .output();
272    let _ = Command::new("git")
273        .args(["branch", "-D", branch])
274        .current_dir(root)
275        .output();
276}
277
278fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
279    let mut json = serde_json::to_string_pretty(value)
280        .map_err(|e| format!("failed to serialize {}: {e}", path.display()))?;
281    json.push('\n');
282    let mut tmp_name = path.as_os_str().to_os_string();
283    tmp_name.push(".tmp");
284    let tmp_path = PathBuf::from(tmp_name);
285    std::fs::write(&tmp_path, json)
286        .map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
287    std::fs::rename(&tmp_path, path).map_err(|e| {
288        format!(
289            "failed to rename {} to {}: {e}",
290            tmp_path.display(),
291            path.display()
292        )
293    })
294}
295
296pub fn run_edit_start(args: &EditStartArgs) -> i32 {
297    match run_edit_start_inner(args) {
298        Ok(output) => {
299            let json = serde_json::to_string_pretty(&output).unwrap();
300            println!("{json}");
301            0
302        }
303        Err(err) => {
304            eprintln!("error: {err}");
305            2
306        }
307    }
308}
309
310fn run_edit_start_inner(args: &EditStartArgs) -> Result<EditStartOutput, String> {
311    crate::dispatch::validate_run_id(&args.id)?;
312    if args.task.trim().is_empty() {
313        return Err("--task must not be empty".to_string());
314    }
315
316    let start_dir = git_toplevel()?;
317    let root = crate::clean::find_repo_root().map_err(|e| e.to_string())?;
318    crate::registry::register(&root);
319
320    let (repo_config, _) = crate::config::load_with_fallback(&start_dir)?
321        .map(|(cfg, from_main)| (Some(cfg), from_main))
322        .unwrap_or((None, false));
323    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
324
325    let wt_parent = root.join(".wt");
326    let worktree_dir = wt_parent.join(&args.id);
327    let start_path = wt_parent.join(format!("{}.start.json", args.id));
328    let edit_path = wt_parent.join(format!("{}.edit.json", args.id));
329    let task_path = wt_parent.join(format!("{}.task.md", args.id));
330    let branch = format!("wip/{}", args.id);
331
332    if worktree_dir.exists() {
333        return Err(format!(
334            "worktree {} already exists",
335            worktree_dir.display()
336        ));
337    }
338    if start_path.exists() {
339        return Err(format!(
340            "start record {} already exists",
341            start_path.display()
342        ));
343    }
344    if edit_path.exists() {
345        return Err(format!(
346            "edit record {} already exists",
347            edit_path.display()
348        ));
349    }
350    if branch_exists(&root, &branch)? {
351        return Err(format!("branch {branch} already exists"));
352    }
353
354    let base_sha = crate::dispatch::resolve_base_commit(&start_dir, &args.base)?;
355
356    std::fs::create_dir_all(&wt_parent)
357        .map_err(|e| format!("failed to create {}: {e}", wt_parent.display()))?;
358    ensure_wt_excluded(&root);
359
360    let add_out = Command::new("git")
361        .args(["worktree", "add", "-b", &branch])
362        .arg(&worktree_dir)
363        .arg(&base_sha)
364        .current_dir(&root)
365        .output()
366        .map_err(|e| format!("failed to execute git worktree add: {e}"))?;
367    if !add_out.status.success() {
368        return Err(format!(
369            "git worktree add failed: {}",
370            String::from_utf8_lossy(&add_out.stderr).trim()
371        ));
372    }
373
374    if let Some(ref setup_cmd) = dispatch_cfg.setup {
375        let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
376        let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
377        if let Err(msg) = crate::setup::run_setup(
378            setup_cmd,
379            &worktree_dir,
380            &main_checkout,
381            &dispatch_cfg.env,
382            &setup_log_path,
383            crate::setup::SETUP_TIMEOUT,
384        ) {
385            cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
386            return Err(format!("setup failed: {msg}"));
387        }
388    }
389
390    if let Err(e) = std::fs::write(&task_path, &args.task) {
391        cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
392        return Err(format!("failed to write {}: {e}", task_path.display()));
393    }
394
395    let started_at = now_secs()?;
396    let edit_record = EditRecord {
397        id: args.id.clone(),
398        base: args.base.clone(),
399        base_sha: base_sha.clone(),
400        started_at,
401    };
402    if let Err(e) = write_json_atomic(&edit_path, &edit_record) {
403        let _ = std::fs::remove_file(&task_path);
404        cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
405        return Err(e);
406    }
407
408    let abs_path = std::fs::canonicalize(&worktree_dir).unwrap_or(worktree_dir);
409    Ok(EditStartOutput {
410        id: args.id.clone(),
411        path: abs_path.display().to_string(),
412        base_sha,
413    })
414}
415
416pub fn run_edit_finish(args: &EditFinishArgs) -> i32 {
417    let start_dir = match git_toplevel() {
418        Ok(d) => d,
419        Err(e) => {
420            eprintln!("error: {e}");
421            return 2;
422        }
423    };
424    let root = match crate::clean::find_repo_root() {
425        Ok(r) => r,
426        Err(e) => {
427            eprintln!("error: {e}");
428            return 2;
429        }
430    };
431    let current_exe = match std::env::current_exe() {
432        Ok(p) => p,
433        Err(e) => {
434            eprintln!("error: getting current executable: {e}");
435            return 2;
436        }
437    };
438    run_edit_finish_in(&root, &start_dir, &current_exe, args, None)
439}
440
441pub fn run_edit_finish_in(
442    root: &Path,
443    start_dir: &Path,
444    blyte_exe: &Path,
445    args: &EditFinishArgs,
446    after_start_record: Option<&dyn Fn() -> Result<(), String>>,
447) -> i32 {
448    if let Err(e) = crate::dispatch::validate_run_id(&args.id) {
449        eprintln!("error: {e}");
450        return 2;
451    }
452    if let Some(ref req) = args.request {
453        if let Err(e) = crate::dispatch::validate_request_id(req) {
454            eprintln!("error: {e}");
455            return 2;
456        }
457    }
458
459    let wt_parent = root.join(".wt");
460    let edit_path = wt_parent.join(format!("{}.edit.json", args.id));
461    let summary_path = wt_parent.join(format!("{}.json", args.id));
462    let start_path = wt_parent.join(format!("{}.start.json", args.id));
463    let task_path = wt_parent.join(format!("{}.task.md", args.id));
464    let log_path = wt_parent.join(format!("{}.log", args.id));
465    let report_path = wt_parent.join(format!("{}.report.json", args.id));
466    let worktree_dir = wt_parent.join(&args.id);
467    let branch = format!("wip/{}", args.id);
468
469    if !edit_path.exists() {
470        eprintln!("error: missing edit record {}", edit_path.display());
471        return 2;
472    }
473    if summary_path.exists() {
474        eprintln!(
475            "error: edit {} has already finished ({})",
476            args.id,
477            summary_path.display()
478        );
479        return 2;
480    }
481
482    let edit_raw = match std::fs::read_to_string(&edit_path) {
483        Ok(s) => s,
484        Err(e) => {
485            eprintln!("error: failed to read {}: {e}", edit_path.display());
486            return 2;
487        }
488    };
489    let edit: EditRecord = match serde_json::from_str(&edit_raw) {
490        Ok(r) => r,
491        Err(e) => {
492            eprintln!("error: failed to parse {}: {e}", edit_path.display());
493            return 2;
494        }
495    };
496
497    if !worktree_dir.exists() {
498        eprintln!("error: missing worktree {}", worktree_dir.display());
499        return 2;
500    }
501
502    if let Err(e) = verify_worktree_git_pointer(root, &worktree_dir, &args.id) {
503        eprintln!("error: {e}");
504        return 2;
505    }
506
507    let task_text = match std::fs::read_to_string(&task_path) {
508        Ok(s) => s,
509        Err(e) => {
510            eprintln!(
511                "error: failed to read task file {}: {e}",
512                task_path.display()
513            );
514            return 2;
515        }
516    };
517
518    if let Some(ref msg) = args.message {
519        if msg.trim().is_empty() {
520            eprintln!("error: --message must not be empty");
521            return 2;
522        }
523    }
524
525    match crate::passed_trees::worktree_is_clean(&worktree_dir) {
526        Ok(true) => {}
527        Ok(false) => match args.message.as_deref() {
528            Some(msg) => {
529                if let Err(e) = commit_worktree_changes(&worktree_dir, msg) {
530                    eprintln!("error: {e}");
531                    return 2;
532                }
533            }
534            None => {
535                eprintln!(
536                    "error: worktree {} has uncommitted or untracked changes; pass --message to commit them",
537                    worktree_dir.display()
538                );
539                return 2;
540            }
541        },
542        Err(e) => {
543            eprintln!("error: failed to check worktree status: {e}");
544            return 2;
545        }
546    }
547
548    let commits = match collect_commits(&worktree_dir, &edit.base_sha) {
549        Ok(c) => c,
550        Err(e) => {
551            eprintln!("error: {e}");
552            return 2;
553        }
554    };
555    if commits.is_empty() {
556        eprintln!(
557            "error: branch {branch} has no commits beyond base {}",
558            edit.base_sha
559        );
560        return 2;
561    }
562
563    let changed_files = match collect_changed_files(&worktree_dir, &edit.base_sha) {
564        Ok(f) => f,
565        Err(e) => {
566            eprintln!("error: {e}");
567            return 2;
568        }
569    };
570
571    if let Err(error) = direct_edit_scope(&changed_files) {
572        let out = EditOutOfScopeOutput {
573            id: args.id.clone(),
574            outcome: "out_of_scope",
575            changed_files,
576            error,
577        };
578        let json = serde_json::to_string_pretty(&out).unwrap();
579        println!("{json}");
580        return 2;
581    }
582
583    let (repo_config, from_main) = match crate::config::load_with_fallback(start_dir) {
584        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
585        Ok(None) => (None, false),
586        Err(e) => {
587            eprintln!("error: {e}");
588            return 2;
589        }
590    };
591    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
592    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
593        Ok(m) => m,
594        Err(e) => {
595            eprintln!("error: {e}");
596            return 2;
597        }
598    };
599    let configured_gate = match dispatch_cfg.gate {
600        Some(ref g) if !g.trim().is_empty() => g.clone(),
601        Some(_) => {
602            eprintln!("error: the gate in blyte.toml is empty");
603            return 2;
604        }
605        None => {
606            eprintln!("error: no gate configured in blyte.toml");
607            return 2;
608        }
609    };
610    let gate_source = if from_main {
611        "blyte.toml (main checkout)"
612    } else {
613        "blyte.toml"
614    };
615
616    let full_gate = if comments == crate::config::CommentMode::Gate {
617        crate::dispatch::gate_with_comment_step(
618            &configured_gate,
619            &crate::dispatch::comment_step(blyte_exe, &edit.base_sha),
620        )
621    } else {
622        configured_gate.clone()
623    };
624
625    let passed_key = crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env);
626    let head_tree = match crate::passed_trees::tree_of(&worktree_dir, "HEAD") {
627        Ok(t) => t,
628        Err(e) => {
629            eprintln!("error: {e}");
630            return 2;
631        }
632    };
633    let now = crate::passed_trees::now_secs();
634    let already_passed = match crate::passed_trees::has_passed(root, &head_tree, &passed_key, now) {
635        Ok(v) => v,
636        Err(e) => {
637            eprintln!("error: {e}");
638            return 2;
639        }
640    };
641
642    let gate_outcome = if already_passed {
643        GateOutcome {
644            elapsed: Duration::ZERO,
645            gate_attempts: 0,
646            gate_wait_ms: 0,
647            log_text: ALREADY_PASSED_LOG.to_string(),
648        }
649    } else {
650        let shell = EnvShell {
651            inner: LocalShell::new(),
652            env: dispatch_cfg.env.clone(),
653            steps: Mutex::new(Vec::new()),
654        };
655        let mut deadline = None;
656        let started = Instant::now();
657        let gate_result = run_gate_steps(
658            &shell,
659            &full_gate,
660            &worktree_dir,
661            &[],
662            &mut deadline,
663            |_| {},
664            &Instant::now,
665        );
666        let elapsed = started.elapsed();
667        let log_text = format_gate_log(&shell.steps.lock().unwrap());
668        if !gate_result.passed {
669            if let Err(e) = write_log(&log_path, &log_text) {
670                eprintln!("error: {e}");
671                return 2;
672            }
673            let (failing_step, raw_output) = match gate_result.failures.first() {
674                Some(f) => (f.step.clone(), f.output.as_str()),
675                None => (full_gate.clone(), gate_result.output.as_str()),
676            };
677            let failed_out = EditGateFailedOutput {
678                id: args.id.clone(),
679                outcome: "gate_failed",
680                failing_step,
681                output_tail: tail_output(raw_output, TAIL_MAX_LINES, TAIL_MAX_BYTES),
682            };
683            let json = serde_json::to_string_pretty(&failed_out).unwrap();
684            println!("{json}");
685            return 1;
686        }
687        match crate::passed_trees::worktree_is_clean(&worktree_dir) {
688            Ok(true) => {
689                if let Err(e) = crate::passed_trees::record_passed(root, &head_tree, &passed_key) {
690                    eprintln!("error: could not record passed tree: {e}");
691                    return 2;
692                }
693            }
694            Ok(false) => {}
695            Err(e) => {
696                eprintln!("error: failed to check worktree status after gate: {e}");
697                return 2;
698            }
699        }
700        GateOutcome {
701            elapsed,
702            gate_attempts: 1,
703            gate_wait_ms: gate_result.wait_ms,
704            log_text,
705        }
706    };
707
708    if let Err(e) = write_log(&log_path, &gate_outcome.log_text) {
709        eprintln!("error: {e}");
710        return 2;
711    }
712
713    let gate_elapsed_ms = gate_outcome.elapsed.as_millis() as u64;
714    let (gate_ms, gate_turns, gate_wait_ms, gate_seconds) = if gate_outcome.gate_attempts > 0 {
715        (
716            vec![gate_elapsed_ms],
717            vec![0],
718            vec![gate_outcome.gate_wait_ms],
719            gate_elapsed_ms as f64 / 1000.0,
720        )
721    } else {
722        (Vec::new(), Vec::new(), Vec::new(), 0.0)
723    };
724    let report_record = RunRecord {
725        schema_version: SCHEMA_VERSION,
726        harness_build: env!("BLYTE_BUILD").into(),
727        outcome: "verified".into(),
728        error: None,
729        final_message: Some(task_text.clone()),
730        model_requested: None,
731        model_id: None,
732        effort: None,
733        context: String::new(),
734        gated: true,
735        gate_source: gate_source.to_string(),
736        gate_left_out: Vec::new(),
737        container: None,
738        container_workdir: String::new(),
739        sandboxed: false,
740        sandbox: "off".into(),
741        network: "on".into(),
742        allow_read: Vec::new(),
743        pass_env: Vec::new(),
744        withheld_env: Vec::new(),
745        duration_seconds: gate_outcome.elapsed.as_secs_f64(),
746        turns: 0,
747        empty_turns: 0,
748        truncated_turns: 0,
749        read_loop: false,
750        peak_read_repeats: 0,
751        fold_thrash: false,
752        stalled: false,
753        big_read_turns: 0,
754        tool_calls: 0,
755        gate_attempts: gate_outcome.gate_attempts,
756        rollbacks: 0,
757        provider_retries: 0,
758        cost_usd: Some(0.0),
759        max_cost_usd: None,
760        cost_capped: false,
761        fold_budget: None,
762        turn_usage: Vec::new(),
763        usage: UsageRecord::default(),
764        gate_ms,
765        gate_turns,
766        gate_wait_ms,
767        gate_failures: Vec::new(),
768        tool_counts: BTreeMap::new(),
769        model_seconds: 0.0,
770        tools_seconds: 0.0,
771        gate_seconds,
772        quote_problems: None,
773        claim_check: None,
774        claim_check_skipped: None,
775        base_check_passed: None,
776        base_check_seconds: None,
777    };
778    if let Err(e) = crate::report::write(&report_path, &report_record) {
779        eprintln!("error: {e}");
780        return 2;
781    }
782
783    let seconds = gate_outcome.elapsed.as_secs();
784    let gate_attempts = gate_outcome.gate_attempts;
785
786    let comments_str = match comments {
787        crate::config::CommentMode::Gate => "gate",
788        crate::config::CommentMode::Review => "review",
789        crate::config::CommentMode::Off => "off",
790    };
791    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
792    let session = crate::usage_log::session_from(
793        std::env::var("BLYTE_SESSION").ok(),
794        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
795    );
796    let mut start_json = serde_json::json!({
797        "id": args.id,
798        "pid": std::process::id(),
799        "started_at": edit.started_at,
800        "task_file": task_path.display().to_string(),
801        "gate": full_gate,
802        "tags": Vec::<String>::new(),
803        "env": env_names,
804        "max_turns": 0,
805        "max_seconds": 0,
806        "plan": serde_json::Value::Null,
807        "plan_task": serde_json::Value::Null,
808        "request": args.request,
809        "base": edit.base,
810        "base_sha": edit.base_sha,
811        "base_check": "off",
812        "comments": comments_str,
813        "kind": "edit",
814    });
815    if let Some(s) = session {
816        start_json["session"] = serde_json::json!(s);
817    }
818
819    if let Err(e) = crate::dispatch::write_start_record(&start_path, &start_json) {
820        eprintln!(
821            "error: could not write start record {}: {e}",
822            start_path.display()
823        );
824        return 2;
825    }
826
827    if let Some(hook) = after_start_record {
828        if let Err(e) = hook() {
829            eprintln!("error: {e}");
830            return 2;
831        }
832    }
833
834    let review = match crate::queue_actions::evaluate_verified_run_with(
835        root,
836        &args.id,
837        true,
838        crate::model_review::run,
839    ) {
840        Ok(mr) => mr,
841        Err(e) => {
842            eprintln!(
843                "warning: post-edit review check failed for {}: {e}",
844                args.id
845            );
846            None
847        }
848    };
849
850    let fixround_path = crate::fix_round::record_path(&wt_parent, &args.id);
851    let existing_fixround = match crate::fix_round::load_record(&fixround_path) {
852        Ok(rec) => rec,
853        Err(e) => {
854            eprintln!("error: {e}");
855            return 2;
856        }
857    };
858    let needs_fix_round = crate::fix_round::should_run(false, "verified", true, review.as_ref())
859        || review
860            .as_ref()
861            .is_some_and(crate::model_review::ModelReviewResult::has_findings);
862    if existing_fixround.is_none() && needs_fix_round {
863        let mr = review.as_ref().unwrap();
864        let pre_round_sha = match git_head_sha(&worktree_dir) {
865            Ok(sha) => sha,
866            Err(e) => {
867                eprintln!("error: {e}");
868                return 2;
869            }
870        };
871        let fallbacks_sent = if crate::fix_round::confirmed_count(mr) > 0 {
872            match crate::fix_round::collect_confirmed_fallbacks(root, &args.id, &worktree_dir, mr) {
873                Ok(fbs) => fbs,
874                Err(e) => {
875                    eprintln!("error: {e}");
876                    return 2;
877                }
878            }
879        } else {
880            Vec::new()
881        };
882        let started_at = match now_secs() {
883            Ok(ts) => ts,
884            Err(e) => {
885                eprintln!("error: {e}");
886                return 2;
887            }
888        };
889        let started_record = crate::fix_round::FixRoundRecord::Started {
890            pre_round_sha,
891            fallbacks_sent,
892            started_at,
893        };
894        if let Err(e) = crate::fix_round::write_record(&fixround_path, &started_record) {
895            eprintln!("error: {e}");
896            return 2;
897        }
898        let findings = collect_review_findings(mr);
899        let findings_out = EditReviewFindingsOutput {
900            id: args.id.clone(),
901            outcome: "review_findings",
902            findings,
903        };
904        let json = serde_json::to_string_pretty(&findings_out).unwrap();
905        println!("{json}");
906        return 1;
907    }
908
909    let summary = DispatchSummary {
910        id: args.id.clone(),
911        worktree: worktree_dir.display().to_string(),
912        branch,
913        outcome: "verified",
914        exit: 0,
915        error: None,
916        commits,
917        changed_files,
918        final_message: Some(task_text),
919        turns: 0,
920        gate_attempts,
921        gate_failures: Vec::new(),
922        cost_usd: Some(0.0),
923        model: None,
924        seconds,
925        sandbox: "none".to_string(),
926        fix_round: None,
927        log: log_path.display().to_string(),
928        report: report_path.display().to_string(),
929        gate_source,
930        research_report: None,
931        base_check_seconds: None,
932        warnings: Vec::new(),
933    };
934
935    if let Err(e) = write_json_atomic(&summary_path, &summary) {
936        eprintln!("error: {e}");
937        return 2;
938    }
939
940    let notify_outcome = crate::surface_notify::notify_runs_changed(root, &args.id);
941    crate::surface_notify::report(&notify_outcome, &mut std::io::stderr());
942
943    let json = serde_json::to_string_pretty(&summary).unwrap();
944    println!("{json}");
945    0
946}
947
948fn git_common_dir(dir: &Path) -> Result<PathBuf, String> {
949    let out = Command::new("git")
950        .args(["rev-parse", "--git-common-dir"])
951        .current_dir(dir)
952        .output()
953        .map_err(|e| format!("failed to execute git rev-parse --git-common-dir: {e}"))?;
954    if !out.status.success() {
955        return Err(format!(
956            "git rev-parse --git-common-dir failed: {}",
957            String::from_utf8_lossy(&out.stderr).trim()
958        ));
959    }
960    let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
961    if raw.is_empty() {
962        return Err("git rev-parse --git-common-dir returned empty output".to_string());
963    }
964    let path = PathBuf::from(raw);
965    Ok(if path.is_absolute() {
966        path
967    } else {
968        dir.join(path)
969    })
970}
971
972fn verify_worktree_git_pointer(
973    main_checkout: &Path,
974    worktree_dir: &Path,
975    id: &str,
976) -> Result<(), String> {
977    let git_file = worktree_dir.join(".git");
978    let meta = std::fs::symlink_metadata(&git_file).map_err(|e| {
979        format!(
980            "worktree git pointer {} cannot be inspected: {e}",
981            git_file.display()
982        )
983    })?;
984    let ft = meta.file_type();
985    if ft.is_symlink() {
986        return Err(format!(
987            "worktree git pointer {} is a symlink, expected a regular file",
988            git_file.display()
989        ));
990    }
991    if ft.is_dir() {
992        return Err(format!(
993            "worktree git pointer {} is a directory, expected a regular file",
994            git_file.display()
995        ));
996    }
997    if !ft.is_file() {
998        return Err(format!(
999            "worktree git pointer {} is not a regular file",
1000            git_file.display()
1001        ));
1002    }
1003
1004    let content = std::fs::read_to_string(&git_file).map_err(|e| {
1005        format!(
1006            "worktree git pointer {} cannot be read: {e}",
1007            git_file.display()
1008        )
1009    })?;
1010    let trimmed = content
1011        .strip_suffix("\r\n")
1012        .or_else(|| content.strip_suffix('\n'))
1013        .unwrap_or(&content);
1014    let Some(pointed_str) = trimmed.strip_prefix("gitdir: ") else {
1015        return Err(format!(
1016            "worktree git pointer {} must be a single `gitdir: <path>` line",
1017            git_file.display()
1018        ));
1019    };
1020    if pointed_str.is_empty() || pointed_str.contains(['\n', '\r']) {
1021        return Err(format!(
1022            "worktree git pointer {} must be a single `gitdir: <path>` line",
1023            git_file.display()
1024        ));
1025    }
1026
1027    let common_dir = git_common_dir(main_checkout).map_err(|e| {
1028        format!(
1029            "cannot resolve git common dir while verifying {}: {e}",
1030            git_file.display()
1031        )
1032    })?;
1033    let expected_worktree_gitdir = common_dir.join("worktrees").join(id);
1034    if !expected_worktree_gitdir.is_dir() {
1035        return Err(format!(
1036            "worktree git pointer {} expects worktree metadata directory {}, which does not exist",
1037            git_file.display(),
1038            expected_worktree_gitdir.display()
1039        ));
1040    }
1041    let expected_canon = std::fs::canonicalize(&expected_worktree_gitdir).map_err(|e| {
1042        format!(
1043            "cannot canonicalize {} while verifying {}: {e}",
1044            expected_worktree_gitdir.display(),
1045            git_file.display()
1046        )
1047    })?;
1048
1049    let pointed_path = Path::new(pointed_str);
1050    let resolved_pointed = if pointed_path.is_absolute() {
1051        pointed_path.to_path_buf()
1052    } else {
1053        worktree_dir.join(pointed_path)
1054    };
1055    let pointed_canon = std::fs::canonicalize(&resolved_pointed).map_err(|e| {
1056        format!(
1057            "worktree git pointer {} points to {}, which cannot be resolved: {e}",
1058            git_file.display(),
1059            pointed_str
1060        )
1061    })?;
1062    if pointed_canon != expected_canon {
1063        return Err(format!(
1064            "worktree git pointer {} points to {}, expected {}",
1065            git_file.display(),
1066            pointed_canon.display(),
1067            expected_canon.display()
1068        ));
1069    }
1070
1071    let backlink_file = expected_canon.join("gitdir");
1072    let backlink_content = std::fs::read_to_string(&backlink_file).map_err(|e| {
1073        format!(
1074            "worktree git pointer {} cannot be verified because {} cannot be read: {e}",
1075            git_file.display(),
1076            backlink_file.display()
1077        )
1078    })?;
1079    let backlink_trimmed = backlink_content
1080        .strip_suffix("\r\n")
1081        .or_else(|| backlink_content.strip_suffix('\n'))
1082        .unwrap_or(&backlink_content);
1083    if backlink_trimmed.is_empty() || backlink_trimmed.contains(['\n', '\r']) {
1084        return Err(format!(
1085            "worktree git pointer {} cannot be verified because {} is malformed",
1086            git_file.display(),
1087            backlink_file.display()
1088        ));
1089    }
1090    let backlink_path = Path::new(backlink_trimmed);
1091    let resolved_backlink = if backlink_path.is_absolute() {
1092        backlink_path.to_path_buf()
1093    } else {
1094        expected_canon.join(backlink_path)
1095    };
1096    let backlink_canon = std::fs::canonicalize(&resolved_backlink).map_err(|e| {
1097        format!(
1098            "worktree git pointer {} cannot be verified because {} points to {}, which cannot be resolved: {e}",
1099            git_file.display(),
1100            backlink_file.display(),
1101            backlink_trimmed
1102        )
1103    })?;
1104    let git_file_canon = std::fs::canonicalize(&git_file).map_err(|e| {
1105        format!(
1106            "cannot canonicalize worktree git pointer {}: {e}",
1107            git_file.display()
1108        )
1109    })?;
1110    if backlink_canon != git_file_canon {
1111        return Err(format!(
1112            "worktree git pointer {} is not the target of {} (points to {})",
1113            git_file.display(),
1114            backlink_file.display(),
1115            backlink_canon.display()
1116        ));
1117    }
1118
1119    Ok(())
1120}
1121
1122fn commit_worktree_changes(worktree_dir: &Path, message: &str) -> Result<(), String> {
1123    let add_out = Command::new("git")
1124        .current_dir(worktree_dir)
1125        .args(["add", "-A"])
1126        .output()
1127        .map_err(|e| format!("failed to run git add -A: {e}"))?;
1128    if !add_out.status.success() {
1129        return Err(format!(
1130            "git add -A failed: {}",
1131            String::from_utf8_lossy(&add_out.stderr).trim()
1132        ));
1133    }
1134    let commit_out = Command::new("git")
1135        .current_dir(worktree_dir)
1136        .args(["commit", "--no-gpg-sign", "-m", message])
1137        .output()
1138        .map_err(|e| format!("failed to run git commit: {e}"))?;
1139    if !commit_out.status.success() {
1140        return Err(format!(
1141            "git commit failed: {}",
1142            String::from_utf8_lossy(&commit_out.stderr).trim()
1143        ));
1144    }
1145    Ok(())
1146}
1147
1148fn collect_commits(worktree_dir: &Path, base_sha: &str) -> Result<Vec<CommitRecord>, String> {
1149    let out = Command::new("git")
1150        .current_dir(worktree_dir)
1151        .args([
1152            "log",
1153            "--reverse",
1154            "--format=%h%x09%s",
1155            &format!("{base_sha}..HEAD"),
1156        ])
1157        .output()
1158        .map_err(|e| format!("failed to run git log: {e}"))?;
1159    if !out.status.success() {
1160        return Err(format!(
1161            "git log failed: {}",
1162            String::from_utf8_lossy(&out.stderr).trim()
1163        ));
1164    }
1165    let text = String::from_utf8_lossy(&out.stdout);
1166    let mut commits = Vec::new();
1167    for line in text.lines() {
1168        let line = line.trim();
1169        if line.is_empty() {
1170            continue;
1171        }
1172        if let Some((sha, subject)) = line.split_once('\t') {
1173            commits.push(CommitRecord {
1174                sha: sha.to_string(),
1175                subject: subject.to_string(),
1176            });
1177        }
1178    }
1179    Ok(commits)
1180}
1181
1182fn git_head_sha(worktree_dir: &Path) -> Result<String, String> {
1183    let out = Command::new("git")
1184        .current_dir(worktree_dir)
1185        .args(["rev-parse", "HEAD"])
1186        .output()
1187        .map_err(|e| format!("failed to run git rev-parse HEAD: {e}"))?;
1188    if !out.status.success() {
1189        return Err(format!(
1190            "git rev-parse HEAD failed: {}",
1191            String::from_utf8_lossy(&out.stderr).trim()
1192        ));
1193    }
1194    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
1195    if sha.is_empty() {
1196        return Err("git rev-parse HEAD returned empty output".to_string());
1197    }
1198    Ok(sha)
1199}
1200
1201fn collect_review_findings(
1202    review: &crate::model_review::ModelReviewResult,
1203) -> Vec<EditReviewFinding> {
1204    let mut out = Vec::new();
1205    for c in &review.concerns {
1206        out.push(EditReviewFinding {
1207            file: c.file.clone(),
1208            line: c.line,
1209            text: c.text.clone(),
1210        });
1211    }
1212    for f in review.fallbacks.iter().filter(|f| f.verdict == "fallback") {
1213        out.push(EditReviewFinding {
1214            file: f.file.clone(),
1215            line: Some(f.line as u64),
1216            text: f.reason.clone(),
1217        });
1218    }
1219    out
1220}
1221
1222fn collect_changed_files(worktree_dir: &Path, base_sha: &str) -> Result<Vec<String>, String> {
1223    let out = Command::new("git")
1224        .current_dir(worktree_dir)
1225        .args(["diff", "--name-only", &format!("{base_sha}..HEAD")])
1226        .output()
1227        .map_err(|e| format!("failed to run git diff: {e}"))?;
1228    if !out.status.success() {
1229        return Err(format!(
1230            "git diff failed: {}",
1231            String::from_utf8_lossy(&out.stderr).trim()
1232        ));
1233    }
1234    let text = String::from_utf8_lossy(&out.stdout);
1235    let mut files = Vec::new();
1236    for line in text.lines() {
1237        let line = line.trim();
1238        if !line.is_empty() {
1239            files.push(line.to_string());
1240        }
1241    }
1242    Ok(files)
1243}