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    if let Some(ref surface) = args.surface {
459        if let Err(e) = blyte_agent::sandbox::validate_surface_id(surface) {
460            eprintln!("blyte: {e}");
461            return 2;
462        }
463    }
464
465    let wt_parent = root.join(".wt");
466    let edit_path = wt_parent.join(format!("{}.edit.json", args.id));
467    let summary_path = wt_parent.join(format!("{}.json", args.id));
468    let start_path = wt_parent.join(format!("{}.start.json", args.id));
469    let task_path = wt_parent.join(format!("{}.task.md", args.id));
470    let log_path = wt_parent.join(format!("{}.log", args.id));
471    let report_path = wt_parent.join(format!("{}.report.json", args.id));
472    let worktree_dir = wt_parent.join(&args.id);
473    let branch = format!("wip/{}", args.id);
474
475    if !edit_path.exists() {
476        eprintln!("error: missing edit record {}", edit_path.display());
477        return 2;
478    }
479    if summary_path.exists() {
480        eprintln!(
481            "error: edit {} has already finished ({})",
482            args.id,
483            summary_path.display()
484        );
485        return 2;
486    }
487
488    let edit_raw = match std::fs::read_to_string(&edit_path) {
489        Ok(s) => s,
490        Err(e) => {
491            eprintln!("error: failed to read {}: {e}", edit_path.display());
492            return 2;
493        }
494    };
495    let edit: EditRecord = match serde_json::from_str(&edit_raw) {
496        Ok(r) => r,
497        Err(e) => {
498            eprintln!("error: failed to parse {}: {e}", edit_path.display());
499            return 2;
500        }
501    };
502
503    if !worktree_dir.exists() {
504        eprintln!("error: missing worktree {}", worktree_dir.display());
505        return 2;
506    }
507
508    if let Err(e) = verify_worktree_git_pointer(root, &worktree_dir, &args.id) {
509        eprintln!("error: {e}");
510        return 2;
511    }
512
513    let task_text = match std::fs::read_to_string(&task_path) {
514        Ok(s) => s,
515        Err(e) => {
516            eprintln!(
517                "error: failed to read task file {}: {e}",
518                task_path.display()
519            );
520            return 2;
521        }
522    };
523
524    if let Some(ref msg) = args.message {
525        if msg.trim().is_empty() {
526            eprintln!("error: --message must not be empty");
527            return 2;
528        }
529    }
530
531    match crate::passed_trees::worktree_is_clean(&worktree_dir) {
532        Ok(true) => {}
533        Ok(false) => match args.message.as_deref() {
534            Some(msg) => {
535                if let Err(e) = commit_worktree_changes(&worktree_dir, msg) {
536                    eprintln!("error: {e}");
537                    return 2;
538                }
539            }
540            None => {
541                eprintln!(
542                    "error: worktree {} has uncommitted or untracked changes; pass --message to commit them",
543                    worktree_dir.display()
544                );
545                return 2;
546            }
547        },
548        Err(e) => {
549            eprintln!("error: failed to check worktree status: {e}");
550            return 2;
551        }
552    }
553
554    let commits = match collect_commits(&worktree_dir, &edit.base_sha) {
555        Ok(c) => c,
556        Err(e) => {
557            eprintln!("error: {e}");
558            return 2;
559        }
560    };
561    if commits.is_empty() {
562        eprintln!(
563            "error: branch {branch} has no commits beyond base {}",
564            edit.base_sha
565        );
566        return 2;
567    }
568
569    let changed_files = match collect_changed_files(&worktree_dir, &edit.base_sha) {
570        Ok(f) => f,
571        Err(e) => {
572            eprintln!("error: {e}");
573            return 2;
574        }
575    };
576
577    if let Err(error) = direct_edit_scope(&changed_files) {
578        let out = EditOutOfScopeOutput {
579            id: args.id.clone(),
580            outcome: "out_of_scope",
581            changed_files,
582            error,
583        };
584        let json = serde_json::to_string_pretty(&out).unwrap();
585        println!("{json}");
586        return 2;
587    }
588
589    let (repo_config, from_main) = match crate::config::load_with_fallback(start_dir) {
590        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
591        Ok(None) => (None, false),
592        Err(e) => {
593            eprintln!("error: {e}");
594            return 2;
595        }
596    };
597    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
598    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
599        Ok(m) => m,
600        Err(e) => {
601            eprintln!("error: {e}");
602            return 2;
603        }
604    };
605    let configured_gate = match dispatch_cfg.gate {
606        Some(ref g) if !g.trim().is_empty() => g.clone(),
607        Some(_) => {
608            eprintln!("error: the gate in blyte.toml is empty");
609            return 2;
610        }
611        None => {
612            eprintln!("error: no gate configured in blyte.toml");
613            return 2;
614        }
615    };
616    let gate_source = if from_main {
617        "blyte.toml (main checkout)"
618    } else {
619        "blyte.toml"
620    };
621
622    let full_gate = if comments == crate::config::CommentMode::Gate {
623        crate::dispatch::gate_with_comment_step(
624            &configured_gate,
625            &crate::dispatch::comment_step(blyte_exe, &edit.base_sha),
626        )
627    } else {
628        configured_gate.clone()
629    };
630
631    let passed_key = crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env);
632    let head_tree = match crate::passed_trees::tree_of(&worktree_dir, "HEAD") {
633        Ok(t) => t,
634        Err(e) => {
635            eprintln!("error: {e}");
636            return 2;
637        }
638    };
639    let now = crate::passed_trees::now_secs();
640    let already_passed = match crate::passed_trees::has_passed(root, &head_tree, &passed_key, now) {
641        Ok(v) => v,
642        Err(e) => {
643            eprintln!("error: {e}");
644            return 2;
645        }
646    };
647
648    let gate_outcome = if already_passed {
649        GateOutcome {
650            elapsed: Duration::ZERO,
651            gate_attempts: 0,
652            gate_wait_ms: 0,
653            log_text: ALREADY_PASSED_LOG.to_string(),
654        }
655    } else {
656        let shell = EnvShell {
657            inner: LocalShell::new(),
658            env: dispatch_cfg.env.clone(),
659            steps: Mutex::new(Vec::new()),
660        };
661        let mut deadline = None;
662        let started = Instant::now();
663        let gate_result = run_gate_steps(
664            &shell,
665            &full_gate,
666            &worktree_dir,
667            &[],
668            &mut deadline,
669            |_| {},
670            &Instant::now,
671        );
672        let elapsed = started.elapsed();
673        let log_text = format_gate_log(&shell.steps.lock().unwrap());
674        if !gate_result.passed {
675            if let Err(e) = write_log(&log_path, &log_text) {
676                eprintln!("error: {e}");
677                return 2;
678            }
679            let (failing_step, raw_output) = match gate_result.failures.first() {
680                Some(f) => (f.step.clone(), f.output.as_str()),
681                None => (full_gate.clone(), gate_result.output.as_str()),
682            };
683            let failed_out = EditGateFailedOutput {
684                id: args.id.clone(),
685                outcome: "gate_failed",
686                failing_step,
687                output_tail: tail_output(raw_output, TAIL_MAX_LINES, TAIL_MAX_BYTES),
688            };
689            let json = serde_json::to_string_pretty(&failed_out).unwrap();
690            println!("{json}");
691            return 1;
692        }
693        match crate::passed_trees::worktree_is_clean(&worktree_dir) {
694            Ok(true) => {
695                if let Err(e) = crate::passed_trees::record_passed(root, &head_tree, &passed_key) {
696                    eprintln!("error: could not record passed tree: {e}");
697                    return 2;
698                }
699            }
700            Ok(false) => {}
701            Err(e) => {
702                eprintln!("error: failed to check worktree status after gate: {e}");
703                return 2;
704            }
705        }
706        GateOutcome {
707            elapsed,
708            gate_attempts: 1,
709            gate_wait_ms: gate_result.wait_ms,
710            log_text,
711        }
712    };
713
714    if let Err(e) = write_log(&log_path, &gate_outcome.log_text) {
715        eprintln!("error: {e}");
716        return 2;
717    }
718
719    let gate_elapsed_ms = gate_outcome.elapsed.as_millis() as u64;
720    let (gate_ms, gate_turns, gate_wait_ms, gate_seconds) = if gate_outcome.gate_attempts > 0 {
721        (
722            vec![gate_elapsed_ms],
723            vec![0],
724            vec![gate_outcome.gate_wait_ms],
725            gate_elapsed_ms as f64 / 1000.0,
726        )
727    } else {
728        (Vec::new(), Vec::new(), Vec::new(), 0.0)
729    };
730    let report_record = RunRecord {
731        schema_version: SCHEMA_VERSION,
732        harness_build: env!("BLYTE_BUILD").into(),
733        outcome: "verified".into(),
734        error: None,
735        final_message: Some(task_text.clone()),
736        model_requested: None,
737        model_id: None,
738        effort: None,
739        context: String::new(),
740        gated: true,
741        gate_source: gate_source.to_string(),
742        gate_left_out: Vec::new(),
743        container: None,
744        container_workdir: String::new(),
745        sandboxed: false,
746        sandbox: "off".into(),
747        network: "on".into(),
748        allow_read: Vec::new(),
749        pass_env: Vec::new(),
750        withheld_env: Vec::new(),
751        duration_seconds: gate_outcome.elapsed.as_secs_f64(),
752        turns: 0,
753        empty_turns: 0,
754        truncated_turns: 0,
755        read_loop: false,
756        peak_read_repeats: 0,
757        fold_thrash: false,
758        stalled: false,
759        big_read_turns: 0,
760        tool_calls: 0,
761        gate_attempts: gate_outcome.gate_attempts,
762        rollbacks: 0,
763        provider_retries: 0,
764        cost_usd: Some(0.0),
765        max_cost_usd: None,
766        cost_capped: false,
767        fold_budget: None,
768        turn_usage: Vec::new(),
769        usage: UsageRecord::default(),
770        gate_ms,
771        gate_turns,
772        gate_wait_ms,
773        gate_failures: Vec::new(),
774        tool_counts: BTreeMap::new(),
775        model_seconds: 0.0,
776        tools_seconds: 0.0,
777        gate_seconds,
778        quote_problems: None,
779        claim_check: None,
780        claim_check_skipped: None,
781        base_check_passed: None,
782        base_check_seconds: None,
783    };
784    if let Err(e) = crate::report::write(&report_path, &report_record) {
785        eprintln!("error: {e}");
786        return 2;
787    }
788
789    let seconds = gate_outcome.elapsed.as_secs();
790    let gate_attempts = gate_outcome.gate_attempts;
791
792    let comments_str = match comments {
793        crate::config::CommentMode::Gate => "gate",
794        crate::config::CommentMode::Review => "review",
795        crate::config::CommentMode::Off => "off",
796    };
797    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
798    let session = crate::usage_log::session_from(
799        std::env::var("BLYTE_SESSION").ok(),
800        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
801    );
802    let mut start_json = serde_json::json!({
803        "id": args.id,
804        "pid": std::process::id(),
805        "started_at": edit.started_at,
806        "task_file": task_path.display().to_string(),
807        "gate": full_gate,
808        "tags": Vec::<String>::new(),
809        "env": env_names,
810        "max_turns": 0,
811        "max_seconds": 0,
812        "plan": serde_json::Value::Null,
813        "plan_task": serde_json::Value::Null,
814        "request": args.request,
815        "surface": args.surface,
816        "base": edit.base,
817        "base_sha": edit.base_sha,
818        "base_check": "off",
819        "comments": comments_str,
820        "kind": "edit",
821    });
822    if let Some(s) = session {
823        start_json["session"] = serde_json::json!(s);
824    }
825
826    if let Err(e) = crate::dispatch::write_start_record(&start_path, &start_json) {
827        eprintln!(
828            "error: could not write start record {}: {e}",
829            start_path.display()
830        );
831        return 2;
832    }
833
834    if let Some(hook) = after_start_record {
835        if let Err(e) = hook() {
836            eprintln!("error: {e}");
837            return 2;
838        }
839    }
840
841    let review = match crate::queue_actions::evaluate_verified_run_with(
842        root,
843        &args.id,
844        true,
845        crate::model_review::run,
846    ) {
847        Ok(mr) => mr,
848        Err(e) => {
849            eprintln!(
850                "warning: post-edit review check failed for {}: {e}",
851                args.id
852            );
853            None
854        }
855    };
856
857    let fixround_path = crate::fix_round::record_path(&wt_parent, &args.id);
858    let existing_fixround = match crate::fix_round::load_record(&fixround_path) {
859        Ok(rec) => rec,
860        Err(e) => {
861            eprintln!("error: {e}");
862            return 2;
863        }
864    };
865    let needs_fix_round = crate::fix_round::should_run(false, "verified", true, review.as_ref());
866    if existing_fixround.is_none() && needs_fix_round {
867        let mr = review.as_ref().unwrap();
868        let pre_round_sha = match git_head_sha(&worktree_dir) {
869            Ok(sha) => sha,
870            Err(e) => {
871                eprintln!("error: {e}");
872                return 2;
873            }
874        };
875        let fallbacks_sent = if crate::fix_round::confirmed_count(mr) > 0 {
876            match crate::fix_round::collect_confirmed_fallbacks(root, &args.id, &worktree_dir, mr) {
877                Ok(fbs) => fbs,
878                Err(e) => {
879                    eprintln!("error: {e}");
880                    return 2;
881                }
882            }
883        } else {
884            Vec::new()
885        };
886        let concerns_sent = mr.concerns.clone();
887        let started_at = match now_secs() {
888            Ok(ts) => ts,
889            Err(e) => {
890                eprintln!("error: {e}");
891                return 2;
892            }
893        };
894        let started_record = crate::fix_round::FixRoundRecord::Started {
895            pre_round_sha,
896            fallbacks_sent,
897            concerns_sent,
898            started_at,
899        };
900        if let Err(e) = crate::fix_round::write_record(&fixround_path, &started_record) {
901            eprintln!("error: {e}");
902            return 2;
903        }
904        let findings = collect_review_findings(mr);
905        let findings_out = EditReviewFindingsOutput {
906            id: args.id.clone(),
907            outcome: "review_findings",
908            findings,
909        };
910        let json = serde_json::to_string_pretty(&findings_out).unwrap();
911        println!("{json}");
912        return 1;
913    }
914
915    let summary = DispatchSummary {
916        id: args.id.clone(),
917        worktree: worktree_dir.display().to_string(),
918        branch,
919        outcome: "verified",
920        exit: 0,
921        error: None,
922        commits,
923        changed_files,
924        final_message: Some(task_text),
925        turns: 0,
926        gate_attempts,
927        gate_failures: Vec::new(),
928        cost_usd: Some(0.0),
929        model: None,
930        seconds,
931        sandbox: "none".to_string(),
932        fix_round: None,
933        log: log_path.display().to_string(),
934        report: report_path.display().to_string(),
935        gate_source,
936        research_report: None,
937        base_check_seconds: None,
938        warnings: Vec::new(),
939    };
940
941    if let Err(e) = write_json_atomic(&summary_path, &summary) {
942        eprintln!("error: {e}");
943        return 2;
944    }
945
946    let notify_outcome = crate::surface_notify::notify_runs_changed(root, &args.id);
947    crate::surface_notify::report(&notify_outcome, &mut std::io::stderr());
948
949    let json = serde_json::to_string_pretty(&summary).unwrap();
950    println!("{json}");
951    0
952}
953
954fn git_common_dir(dir: &Path) -> Result<PathBuf, String> {
955    let out = Command::new("git")
956        .args(["rev-parse", "--git-common-dir"])
957        .current_dir(dir)
958        .output()
959        .map_err(|e| format!("failed to execute git rev-parse --git-common-dir: {e}"))?;
960    if !out.status.success() {
961        return Err(format!(
962            "git rev-parse --git-common-dir failed: {}",
963            String::from_utf8_lossy(&out.stderr).trim()
964        ));
965    }
966    let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
967    if raw.is_empty() {
968        return Err("git rev-parse --git-common-dir returned empty output".to_string());
969    }
970    let path = PathBuf::from(raw);
971    Ok(if path.is_absolute() {
972        path
973    } else {
974        dir.join(path)
975    })
976}
977
978fn verify_worktree_git_pointer(
979    main_checkout: &Path,
980    worktree_dir: &Path,
981    id: &str,
982) -> Result<(), String> {
983    let git_file = worktree_dir.join(".git");
984    let meta = std::fs::symlink_metadata(&git_file).map_err(|e| {
985        format!(
986            "worktree git pointer {} cannot be inspected: {e}",
987            git_file.display()
988        )
989    })?;
990    let ft = meta.file_type();
991    if ft.is_symlink() {
992        return Err(format!(
993            "worktree git pointer {} is a symlink, expected a regular file",
994            git_file.display()
995        ));
996    }
997    if ft.is_dir() {
998        return Err(format!(
999            "worktree git pointer {} is a directory, expected a regular file",
1000            git_file.display()
1001        ));
1002    }
1003    if !ft.is_file() {
1004        return Err(format!(
1005            "worktree git pointer {} is not a regular file",
1006            git_file.display()
1007        ));
1008    }
1009
1010    let content = std::fs::read_to_string(&git_file).map_err(|e| {
1011        format!(
1012            "worktree git pointer {} cannot be read: {e}",
1013            git_file.display()
1014        )
1015    })?;
1016    let trimmed = content
1017        .strip_suffix("\r\n")
1018        .or_else(|| content.strip_suffix('\n'))
1019        .unwrap_or(&content);
1020    let Some(pointed_str) = trimmed.strip_prefix("gitdir: ") else {
1021        return Err(format!(
1022            "worktree git pointer {} must be a single `gitdir: <path>` line",
1023            git_file.display()
1024        ));
1025    };
1026    if pointed_str.is_empty() || pointed_str.contains(['\n', '\r']) {
1027        return Err(format!(
1028            "worktree git pointer {} must be a single `gitdir: <path>` line",
1029            git_file.display()
1030        ));
1031    }
1032
1033    let common_dir = git_common_dir(main_checkout).map_err(|e| {
1034        format!(
1035            "cannot resolve git common dir while verifying {}: {e}",
1036            git_file.display()
1037        )
1038    })?;
1039    let expected_worktree_gitdir = common_dir.join("worktrees").join(id);
1040    if !expected_worktree_gitdir.is_dir() {
1041        return Err(format!(
1042            "worktree git pointer {} expects worktree metadata directory {}, which does not exist",
1043            git_file.display(),
1044            expected_worktree_gitdir.display()
1045        ));
1046    }
1047    let expected_canon = std::fs::canonicalize(&expected_worktree_gitdir).map_err(|e| {
1048        format!(
1049            "cannot canonicalize {} while verifying {}: {e}",
1050            expected_worktree_gitdir.display(),
1051            git_file.display()
1052        )
1053    })?;
1054
1055    let pointed_path = Path::new(pointed_str);
1056    let resolved_pointed = if pointed_path.is_absolute() {
1057        pointed_path.to_path_buf()
1058    } else {
1059        worktree_dir.join(pointed_path)
1060    };
1061    let pointed_canon = std::fs::canonicalize(&resolved_pointed).map_err(|e| {
1062        format!(
1063            "worktree git pointer {} points to {}, which cannot be resolved: {e}",
1064            git_file.display(),
1065            pointed_str
1066        )
1067    })?;
1068    if pointed_canon != expected_canon {
1069        return Err(format!(
1070            "worktree git pointer {} points to {}, expected {}",
1071            git_file.display(),
1072            pointed_canon.display(),
1073            expected_canon.display()
1074        ));
1075    }
1076
1077    let backlink_file = expected_canon.join("gitdir");
1078    let backlink_content = std::fs::read_to_string(&backlink_file).map_err(|e| {
1079        format!(
1080            "worktree git pointer {} cannot be verified because {} cannot be read: {e}",
1081            git_file.display(),
1082            backlink_file.display()
1083        )
1084    })?;
1085    let backlink_trimmed = backlink_content
1086        .strip_suffix("\r\n")
1087        .or_else(|| backlink_content.strip_suffix('\n'))
1088        .unwrap_or(&backlink_content);
1089    if backlink_trimmed.is_empty() || backlink_trimmed.contains(['\n', '\r']) {
1090        return Err(format!(
1091            "worktree git pointer {} cannot be verified because {} is malformed",
1092            git_file.display(),
1093            backlink_file.display()
1094        ));
1095    }
1096    let backlink_path = Path::new(backlink_trimmed);
1097    let resolved_backlink = if backlink_path.is_absolute() {
1098        backlink_path.to_path_buf()
1099    } else {
1100        expected_canon.join(backlink_path)
1101    };
1102    let backlink_canon = std::fs::canonicalize(&resolved_backlink).map_err(|e| {
1103        format!(
1104            "worktree git pointer {} cannot be verified because {} points to {}, which cannot be resolved: {e}",
1105            git_file.display(),
1106            backlink_file.display(),
1107            backlink_trimmed
1108        )
1109    })?;
1110    let git_file_canon = std::fs::canonicalize(&git_file).map_err(|e| {
1111        format!(
1112            "cannot canonicalize worktree git pointer {}: {e}",
1113            git_file.display()
1114        )
1115    })?;
1116    if backlink_canon != git_file_canon {
1117        return Err(format!(
1118            "worktree git pointer {} is not the target of {} (points to {})",
1119            git_file.display(),
1120            backlink_file.display(),
1121            backlink_canon.display()
1122        ));
1123    }
1124
1125    Ok(())
1126}
1127
1128fn commit_worktree_changes(worktree_dir: &Path, message: &str) -> Result<(), String> {
1129    let add_out = Command::new("git")
1130        .current_dir(worktree_dir)
1131        .args(["add", "-A"])
1132        .output()
1133        .map_err(|e| format!("failed to run git add -A: {e}"))?;
1134    if !add_out.status.success() {
1135        return Err(format!(
1136            "git add -A failed: {}",
1137            String::from_utf8_lossy(&add_out.stderr).trim()
1138        ));
1139    }
1140    let commit_out = Command::new("git")
1141        .current_dir(worktree_dir)
1142        .args(["commit", "--no-gpg-sign", "-m", message])
1143        .output()
1144        .map_err(|e| format!("failed to run git commit: {e}"))?;
1145    if !commit_out.status.success() {
1146        return Err(format!(
1147            "git commit failed: {}",
1148            String::from_utf8_lossy(&commit_out.stderr).trim()
1149        ));
1150    }
1151    Ok(())
1152}
1153
1154fn collect_commits(worktree_dir: &Path, base_sha: &str) -> Result<Vec<CommitRecord>, String> {
1155    let out = Command::new("git")
1156        .current_dir(worktree_dir)
1157        .args([
1158            "log",
1159            "--reverse",
1160            "--format=%h%x09%s",
1161            &format!("{base_sha}..HEAD"),
1162        ])
1163        .output()
1164        .map_err(|e| format!("failed to run git log: {e}"))?;
1165    if !out.status.success() {
1166        return Err(format!(
1167            "git log failed: {}",
1168            String::from_utf8_lossy(&out.stderr).trim()
1169        ));
1170    }
1171    let text = String::from_utf8_lossy(&out.stdout);
1172    let mut commits = Vec::new();
1173    for line in text.lines() {
1174        let line = line.trim();
1175        if line.is_empty() {
1176            continue;
1177        }
1178        if let Some((sha, subject)) = line.split_once('\t') {
1179            commits.push(CommitRecord {
1180                sha: sha.to_string(),
1181                subject: subject.to_string(),
1182            });
1183        }
1184    }
1185    Ok(commits)
1186}
1187
1188fn git_head_sha(worktree_dir: &Path) -> Result<String, String> {
1189    let out = Command::new("git")
1190        .current_dir(worktree_dir)
1191        .args(["rev-parse", "HEAD"])
1192        .output()
1193        .map_err(|e| format!("failed to run git rev-parse HEAD: {e}"))?;
1194    if !out.status.success() {
1195        return Err(format!(
1196            "git rev-parse HEAD failed: {}",
1197            String::from_utf8_lossy(&out.stderr).trim()
1198        ));
1199    }
1200    let sha = String::from_utf8_lossy(&out.stdout).trim().to_string();
1201    if sha.is_empty() {
1202        return Err("git rev-parse HEAD returned empty output".to_string());
1203    }
1204    Ok(sha)
1205}
1206
1207fn collect_review_findings(
1208    review: &crate::model_review::ModelReviewResult,
1209) -> Vec<EditReviewFinding> {
1210    let mut out = Vec::new();
1211    for c in &review.concerns {
1212        out.push(EditReviewFinding {
1213            file: c.file.clone(),
1214            line: c.line,
1215            text: c.text.clone(),
1216        });
1217    }
1218    for f in review.fallbacks.iter().filter(|f| f.verdict == "fallback") {
1219        out.push(EditReviewFinding {
1220            file: f.file.clone(),
1221            line: Some(f.line as u64),
1222            text: f.reason.clone(),
1223        });
1224    }
1225    out
1226}
1227
1228fn collect_changed_files(worktree_dir: &Path, base_sha: &str) -> Result<Vec<String>, String> {
1229    let out = Command::new("git")
1230        .current_dir(worktree_dir)
1231        .args(["diff", "--name-only", &format!("{base_sha}..HEAD")])
1232        .output()
1233        .map_err(|e| format!("failed to run git diff: {e}"))?;
1234    if !out.status.success() {
1235        return Err(format!(
1236            "git diff failed: {}",
1237            String::from_utf8_lossy(&out.stderr).trim()
1238        ));
1239    }
1240    let text = String::from_utf8_lossy(&out.stdout);
1241    let mut files = Vec::new();
1242    for line in text.lines() {
1243        let line = line.trim();
1244        if !line.is_empty() {
1245            files.push(line.to_string());
1246        }
1247    }
1248    Ok(files)
1249}