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