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
43struct StepOutput {
44    command: String,
45    output: String,
46}
47
48struct GateOutcome {
49    elapsed: Duration,
50    gate_attempts: u32,
51    gate_wait_ms: u64,
52    log_text: String,
53}
54
55struct EnvShell<S> {
56    inner: S,
57    env: BTreeMap<String, String>,
58    steps: Mutex<Vec<StepOutput>>,
59}
60
61impl<S: Shell> Shell for EnvShell<S> {
62    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
63        let res = if self.env.is_empty() {
64            self.inner.exec(command, cwd, timeout)
65        } else {
66            let mut script = String::new();
67            for (k, v) in &self.env {
68                let quoted = format!("'{}'", v.replace('\'', "'\\''"));
69                script.push_str(&format!("export {k}={quoted}\n"));
70            }
71            script.push_str(command);
72            self.inner.exec(&script, cwd, timeout)
73        };
74        let recorded = match &res {
75            Ok(out) => format_step_output(out),
76            Err(e) => format!("error: {e}\n"),
77        };
78        self.steps.lock().unwrap().push(StepOutput {
79            command: command.to_string(),
80            output: recorded,
81        });
82        res
83    }
84
85    fn describe(&self) -> String {
86        self.inner.describe()
87    }
88}
89
90fn format_step_output(out: &Output) -> String {
91    let mut text = String::new();
92    if !out.stdout.is_empty() {
93        text.push_str(&out.stdout);
94        if !text.ends_with('\n') {
95            text.push('\n');
96        }
97    }
98    if !out.stderr.is_empty() {
99        text.push_str(&out.stderr);
100        if !text.ends_with('\n') {
101            text.push('\n');
102        }
103    }
104    if text.is_empty() || out.exit_code != 0 {
105        text.push_str(&format!("exit {}\n", out.exit_code));
106    }
107    text
108}
109
110fn format_gate_log(steps: &[StepOutput]) -> String {
111    let mut log = String::new();
112    for (idx, step) in steps.iter().enumerate() {
113        if idx > 0 {
114            log.push('\n');
115        }
116        log.push_str(&format!("$ {}\n", step.command));
117        log.push_str(&step.output);
118    }
119    log
120}
121
122fn write_log(path: &Path, content: &str) -> Result<(), String> {
123    std::fs::write(path, content).map_err(|e| format!("cannot write log {}: {e}", path.display()))
124}
125
126fn tail_output(text: &str, max_lines: usize, max_bytes: usize) -> String {
127    let lines: Vec<&str> = text.lines().collect();
128    let start = lines.len().saturating_sub(max_lines);
129    let mut joined = lines[start..].join("\n");
130    if joined.len() > max_bytes {
131        let mut cut = joined.len() - max_bytes;
132        while cut < joined.len() && !joined.is_char_boundary(cut) {
133            cut += 1;
134        }
135        joined = joined[cut..].to_string();
136    }
137    joined
138}
139
140fn now_secs() -> Result<u64, String> {
141    SystemTime::now()
142        .duration_since(UNIX_EPOCH)
143        .map(|d| d.as_secs())
144        .map_err(|e| format!("system clock before unix epoch: {e}"))
145}
146
147fn git_toplevel() -> Result<PathBuf, String> {
148    let out = Command::new("git")
149        .args(["rev-parse", "--show-toplevel"])
150        .output()
151        .map_err(|e| format!("failed to execute git: {e}"))?;
152    if !out.status.success() {
153        return Err("not a git repository".to_string());
154    }
155    Ok(PathBuf::from(String::from_utf8_lossy(&out.stdout).trim()))
156}
157
158fn ensure_wt_excluded(root: &Path) {
159    let common_dir_raw = Command::new("git")
160        .args(["rev-parse", "--git-common-dir"])
161        .current_dir(root)
162        .output();
163    let common_dir = if let Ok(out) = common_dir_raw {
164        let p = PathBuf::from(String::from_utf8_lossy(&out.stdout).trim());
165        if p.is_absolute() {
166            p
167        } else {
168            root.join(p)
169        }
170    } else {
171        root.join(".git")
172    };
173
174    let exclude_path = common_dir.join("info").join("exclude");
175    if let Some(parent) = exclude_path.parent() {
176        let _ = std::fs::create_dir_all(parent);
177    }
178    let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
179    if !content.lines().any(|l| l.trim() == ".wt/") {
180        let mut new_content = content;
181        if !new_content.is_empty() && !new_content.ends_with('\n') {
182            new_content.push('\n');
183        }
184        new_content.push_str(".wt/\n");
185        let _ = std::fs::write(&exclude_path, new_content);
186    }
187}
188
189fn branch_exists(root: &Path, branch: &str) -> Result<bool, String> {
190    let branch_ref = format!("refs/heads/{branch}");
191    let out = Command::new("git")
192        .args(["show-ref", "--verify", "--quiet", &branch_ref])
193        .current_dir(root)
194        .output()
195        .map_err(|e| format!("git show-ref --verify --quiet {branch_ref}: {e}"))?;
196    if out.status.success() {
197        Ok(true)
198    } else if out.status.code() == Some(1) {
199        Ok(false)
200    } else {
201        Err(format!(
202            "git show-ref --verify --quiet {branch_ref}: {}",
203            String::from_utf8_lossy(&out.stderr).trim()
204        ))
205    }
206}
207
208fn cleanup_worktree_and_branch(root: &Path, worktree_dir: &Path, branch: &str) {
209    let _ = Command::new("git")
210        .args(["worktree", "remove", "--force"])
211        .arg(worktree_dir)
212        .current_dir(root)
213        .output();
214    if worktree_dir.exists() {
215        let _ = std::fs::remove_dir_all(worktree_dir);
216    }
217    let _ = Command::new("git")
218        .args(["worktree", "prune"])
219        .current_dir(root)
220        .output();
221    let _ = Command::new("git")
222        .args(["branch", "-D", branch])
223        .current_dir(root)
224        .output();
225}
226
227fn write_json_atomic<T: Serialize>(path: &Path, value: &T) -> Result<(), String> {
228    let mut json = serde_json::to_string_pretty(value)
229        .map_err(|e| format!("failed to serialize {}: {e}", path.display()))?;
230    json.push('\n');
231    let mut tmp_name = path.as_os_str().to_os_string();
232    tmp_name.push(".tmp");
233    let tmp_path = PathBuf::from(tmp_name);
234    std::fs::write(&tmp_path, json)
235        .map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
236    std::fs::rename(&tmp_path, path).map_err(|e| {
237        format!(
238            "failed to rename {} to {}: {e}",
239            tmp_path.display(),
240            path.display()
241        )
242    })
243}
244
245pub fn run_edit_start(args: &EditStartArgs) -> i32 {
246    match run_edit_start_inner(args) {
247        Ok(output) => {
248            let json = serde_json::to_string_pretty(&output).unwrap();
249            println!("{json}");
250            0
251        }
252        Err(err) => {
253            eprintln!("error: {err}");
254            2
255        }
256    }
257}
258
259fn run_edit_start_inner(args: &EditStartArgs) -> Result<EditStartOutput, String> {
260    crate::dispatch::validate_run_id(&args.id)?;
261    if args.task.trim().is_empty() {
262        return Err("--task must not be empty".to_string());
263    }
264
265    let start_dir = git_toplevel()?;
266    let root = crate::clean::find_repo_root().map_err(|e| e.to_string())?;
267    crate::registry::register(&root);
268
269    let (repo_config, _) = crate::config::load_with_fallback(&start_dir)?
270        .map(|(cfg, from_main)| (Some(cfg), from_main))
271        .unwrap_or((None, false));
272    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
273
274    let wt_parent = root.join(".wt");
275    let worktree_dir = wt_parent.join(&args.id);
276    let start_path = wt_parent.join(format!("{}.start.json", args.id));
277    let edit_path = wt_parent.join(format!("{}.edit.json", args.id));
278    let task_path = wt_parent.join(format!("{}.task.md", args.id));
279    let branch = format!("wip/{}", args.id);
280
281    if worktree_dir.exists() {
282        return Err(format!(
283            "worktree {} already exists",
284            worktree_dir.display()
285        ));
286    }
287    if start_path.exists() {
288        return Err(format!(
289            "start record {} already exists",
290            start_path.display()
291        ));
292    }
293    if edit_path.exists() {
294        return Err(format!(
295            "edit record {} already exists",
296            edit_path.display()
297        ));
298    }
299    if branch_exists(&root, &branch)? {
300        return Err(format!("branch {branch} already exists"));
301    }
302
303    let base_sha = crate::dispatch::resolve_base_commit(&start_dir, &args.base)?;
304
305    std::fs::create_dir_all(&wt_parent)
306        .map_err(|e| format!("failed to create {}: {e}", wt_parent.display()))?;
307    ensure_wt_excluded(&root);
308
309    let add_out = Command::new("git")
310        .args(["worktree", "add", "-b", &branch])
311        .arg(&worktree_dir)
312        .arg(&base_sha)
313        .current_dir(&root)
314        .output()
315        .map_err(|e| format!("failed to execute git worktree add: {e}"))?;
316    if !add_out.status.success() {
317        return Err(format!(
318            "git worktree add failed: {}",
319            String::from_utf8_lossy(&add_out.stderr).trim()
320        ));
321    }
322
323    if let Some(ref setup_cmd) = dispatch_cfg.setup {
324        let main_checkout = crate::config::main_checkout(&root).unwrap_or_else(|| root.clone());
325        let setup_log_path = wt_parent.join(format!("{}.setup.log", args.id));
326        if let Err(msg) = crate::setup::run_setup(
327            setup_cmd,
328            &worktree_dir,
329            &main_checkout,
330            &dispatch_cfg.env,
331            &setup_log_path,
332            crate::setup::SETUP_TIMEOUT,
333        ) {
334            cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
335            return Err(format!("setup failed: {msg}"));
336        }
337    }
338
339    if let Err(e) = std::fs::write(&task_path, &args.task) {
340        cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
341        return Err(format!("failed to write {}: {e}", task_path.display()));
342    }
343
344    let started_at = now_secs()?;
345    let edit_record = EditRecord {
346        id: args.id.clone(),
347        base: args.base.clone(),
348        base_sha: base_sha.clone(),
349        started_at,
350    };
351    if let Err(e) = write_json_atomic(&edit_path, &edit_record) {
352        let _ = std::fs::remove_file(&task_path);
353        cleanup_worktree_and_branch(&root, &worktree_dir, &branch);
354        return Err(e);
355    }
356
357    let abs_path = std::fs::canonicalize(&worktree_dir).unwrap_or(worktree_dir);
358    Ok(EditStartOutput {
359        id: args.id.clone(),
360        path: abs_path.display().to_string(),
361        base_sha,
362    })
363}
364
365pub fn run_edit_finish(args: &EditFinishArgs) -> i32 {
366    let start_dir = match git_toplevel() {
367        Ok(d) => d,
368        Err(e) => {
369            eprintln!("error: {e}");
370            return 2;
371        }
372    };
373    let root = match crate::clean::find_repo_root() {
374        Ok(r) => r,
375        Err(e) => {
376            eprintln!("error: {e}");
377            return 2;
378        }
379    };
380    let current_exe = match std::env::current_exe() {
381        Ok(p) => p,
382        Err(e) => {
383            eprintln!("error: getting current executable: {e}");
384            return 2;
385        }
386    };
387    run_edit_finish_in(&root, &start_dir, &current_exe, args, None)
388}
389
390pub fn run_edit_finish_in(
391    root: &Path,
392    start_dir: &Path,
393    blyte_exe: &Path,
394    args: &EditFinishArgs,
395    after_start_record: Option<&dyn Fn() -> Result<(), String>>,
396) -> i32 {
397    if let Err(e) = crate::dispatch::validate_run_id(&args.id) {
398        eprintln!("error: {e}");
399        return 2;
400    }
401    if let Some(ref req) = args.request {
402        if let Err(e) = crate::dispatch::validate_request_id(req) {
403            eprintln!("error: {e}");
404            return 2;
405        }
406    }
407
408    let wt_parent = root.join(".wt");
409    let edit_path = wt_parent.join(format!("{}.edit.json", args.id));
410    let summary_path = wt_parent.join(format!("{}.json", args.id));
411    let start_path = wt_parent.join(format!("{}.start.json", args.id));
412    let task_path = wt_parent.join(format!("{}.task.md", args.id));
413    let log_path = wt_parent.join(format!("{}.log", args.id));
414    let report_path = wt_parent.join(format!("{}.report.json", args.id));
415    let worktree_dir = wt_parent.join(&args.id);
416    let branch = format!("wip/{}", args.id);
417
418    if !edit_path.exists() {
419        eprintln!("error: missing edit record {}", edit_path.display());
420        return 2;
421    }
422    if summary_path.exists() {
423        eprintln!(
424            "error: edit {} has already finished ({})",
425            args.id,
426            summary_path.display()
427        );
428        return 2;
429    }
430
431    let edit_raw = match std::fs::read_to_string(&edit_path) {
432        Ok(s) => s,
433        Err(e) => {
434            eprintln!("error: failed to read {}: {e}", edit_path.display());
435            return 2;
436        }
437    };
438    let edit: EditRecord = match serde_json::from_str(&edit_raw) {
439        Ok(r) => r,
440        Err(e) => {
441            eprintln!("error: failed to parse {}: {e}", edit_path.display());
442            return 2;
443        }
444    };
445
446    if !worktree_dir.exists() {
447        eprintln!("error: missing worktree {}", worktree_dir.display());
448        return 2;
449    }
450
451    let task_text = match std::fs::read_to_string(&task_path) {
452        Ok(s) => s,
453        Err(e) => {
454            eprintln!(
455                "error: failed to read task file {}: {e}",
456                task_path.display()
457            );
458            return 2;
459        }
460    };
461
462    if let Some(ref msg) = args.message {
463        if msg.trim().is_empty() {
464            eprintln!("error: --message must not be empty");
465            return 2;
466        }
467    }
468
469    match crate::passed_trees::worktree_is_clean(&worktree_dir) {
470        Ok(true) => {}
471        Ok(false) => match args.message.as_deref() {
472            Some(msg) => {
473                if let Err(e) = commit_worktree_changes(&worktree_dir, msg) {
474                    eprintln!("error: {e}");
475                    return 2;
476                }
477            }
478            None => {
479                eprintln!(
480                    "error: worktree {} has uncommitted or untracked changes; pass --message to commit them",
481                    worktree_dir.display()
482                );
483                return 2;
484            }
485        },
486        Err(e) => {
487            eprintln!("error: failed to check worktree status: {e}");
488            return 2;
489        }
490    }
491
492    let commits = match collect_commits(&worktree_dir, &edit.base_sha) {
493        Ok(c) => c,
494        Err(e) => {
495            eprintln!("error: {e}");
496            return 2;
497        }
498    };
499    if commits.is_empty() {
500        eprintln!(
501            "error: branch {branch} has no commits beyond base {}",
502            edit.base_sha
503        );
504        return 2;
505    }
506
507    let changed_files = match collect_changed_files(&worktree_dir, &edit.base_sha) {
508        Ok(f) => f,
509        Err(e) => {
510            eprintln!("error: {e}");
511            return 2;
512        }
513    };
514
515    let (repo_config, from_main) = match crate::config::load_with_fallback(start_dir) {
516        Ok(Some((cfg, from_main))) => (Some(cfg), from_main),
517        Ok(None) => (None, false),
518        Err(e) => {
519            eprintln!("error: {e}");
520            return 2;
521        }
522    };
523    let dispatch_cfg = repo_config.map(|c| c.dispatch).unwrap_or_default();
524    let comments = match crate::config::comment_mode(dispatch_cfg.comments.as_deref()) {
525        Ok(m) => m,
526        Err(e) => {
527            eprintln!("error: {e}");
528            return 2;
529        }
530    };
531    let configured_gate = match dispatch_cfg.gate {
532        Some(ref g) if !g.trim().is_empty() => g.clone(),
533        Some(_) => {
534            eprintln!("error: the gate in blyte.toml is empty");
535            return 2;
536        }
537        None => {
538            eprintln!("error: no gate configured in blyte.toml");
539            return 2;
540        }
541    };
542    let gate_source = if from_main {
543        "blyte.toml (main checkout)"
544    } else {
545        "blyte.toml"
546    };
547
548    let full_gate = if comments == crate::config::CommentMode::Gate {
549        crate::dispatch::gate_with_comment_step(
550            &configured_gate,
551            &crate::dispatch::comment_step(blyte_exe, &edit.base_sha),
552        )
553    } else {
554        configured_gate.clone()
555    };
556
557    let passed_key = crate::passed_trees::check_key(&configured_gate, &dispatch_cfg.env);
558    let head_tree = match crate::passed_trees::tree_of(&worktree_dir, "HEAD") {
559        Ok(t) => t,
560        Err(e) => {
561            eprintln!("error: {e}");
562            return 2;
563        }
564    };
565    let now = crate::passed_trees::now_secs();
566    let already_passed = match crate::passed_trees::has_passed(root, &head_tree, &passed_key, now) {
567        Ok(v) => v,
568        Err(e) => {
569            eprintln!("error: {e}");
570            return 2;
571        }
572    };
573
574    let gate_outcome = if already_passed {
575        GateOutcome {
576            elapsed: Duration::ZERO,
577            gate_attempts: 0,
578            gate_wait_ms: 0,
579            log_text: ALREADY_PASSED_LOG.to_string(),
580        }
581    } else {
582        let shell = EnvShell {
583            inner: LocalShell::new(),
584            env: dispatch_cfg.env.clone(),
585            steps: Mutex::new(Vec::new()),
586        };
587        let mut deadline = None;
588        let started = Instant::now();
589        let gate_result = run_gate_steps(
590            &shell,
591            &full_gate,
592            &worktree_dir,
593            &[],
594            &mut deadline,
595            |_| {},
596            &Instant::now,
597        );
598        let elapsed = started.elapsed();
599        let log_text = format_gate_log(&shell.steps.lock().unwrap());
600        if !gate_result.passed {
601            if let Err(e) = write_log(&log_path, &log_text) {
602                eprintln!("error: {e}");
603                return 2;
604            }
605            let (failing_step, raw_output) = match gate_result.failures.first() {
606                Some(f) => (f.step.clone(), f.output.as_str()),
607                None => (full_gate.clone(), gate_result.output.as_str()),
608            };
609            let failed_out = EditGateFailedOutput {
610                id: args.id.clone(),
611                outcome: "gate_failed",
612                failing_step,
613                output_tail: tail_output(raw_output, TAIL_MAX_LINES, TAIL_MAX_BYTES),
614            };
615            let json = serde_json::to_string_pretty(&failed_out).unwrap();
616            println!("{json}");
617            return 1;
618        }
619        match crate::passed_trees::worktree_is_clean(&worktree_dir) {
620            Ok(true) => {
621                if let Err(e) = crate::passed_trees::record_passed(root, &head_tree, &passed_key) {
622                    eprintln!("error: could not record passed tree: {e}");
623                    return 2;
624                }
625            }
626            Ok(false) => {}
627            Err(e) => {
628                eprintln!("error: failed to check worktree status after gate: {e}");
629                return 2;
630            }
631        }
632        GateOutcome {
633            elapsed,
634            gate_attempts: 1,
635            gate_wait_ms: gate_result.wait_ms,
636            log_text,
637        }
638    };
639
640    if let Err(e) = write_log(&log_path, &gate_outcome.log_text) {
641        eprintln!("error: {e}");
642        return 2;
643    }
644
645    let gate_elapsed_ms = gate_outcome.elapsed.as_millis() as u64;
646    let (gate_ms, gate_turns, gate_wait_ms, gate_seconds) = if gate_outcome.gate_attempts > 0 {
647        (
648            vec![gate_elapsed_ms],
649            vec![0],
650            vec![gate_outcome.gate_wait_ms],
651            gate_elapsed_ms as f64 / 1000.0,
652        )
653    } else {
654        (Vec::new(), Vec::new(), Vec::new(), 0.0)
655    };
656    let report_record = RunRecord {
657        schema_version: SCHEMA_VERSION,
658        harness_build: env!("BLYTE_BUILD").into(),
659        outcome: "verified".into(),
660        error: None,
661        final_message: Some(task_text.clone()),
662        model_requested: None,
663        model_id: None,
664        effort: None,
665        context: String::new(),
666        gated: true,
667        gate_source: gate_source.to_string(),
668        gate_left_out: Vec::new(),
669        container: None,
670        container_workdir: String::new(),
671        sandboxed: false,
672        sandbox: "off".into(),
673        network: "on".into(),
674        allow_read: Vec::new(),
675        pass_env: Vec::new(),
676        withheld_env: Vec::new(),
677        duration_seconds: gate_outcome.elapsed.as_secs_f64(),
678        turns: 0,
679        empty_turns: 0,
680        truncated_turns: 0,
681        read_loop: false,
682        peak_read_repeats: 0,
683        fold_thrash: false,
684        stalled: false,
685        big_read_turns: 0,
686        tool_calls: 0,
687        gate_attempts: gate_outcome.gate_attempts,
688        rollbacks: 0,
689        provider_retries: 0,
690        cost_usd: Some(0.0),
691        max_cost_usd: None,
692        cost_capped: false,
693        fold_budget: None,
694        turn_usage: Vec::new(),
695        usage: UsageRecord::default(),
696        gate_ms,
697        gate_turns,
698        gate_wait_ms,
699        gate_failures: Vec::new(),
700        tool_counts: BTreeMap::new(),
701        model_seconds: 0.0,
702        tools_seconds: 0.0,
703        gate_seconds,
704        quote_problems: None,
705        claim_check: None,
706        claim_check_skipped: None,
707        base_check_passed: None,
708        base_check_seconds: None,
709    };
710    if let Err(e) = crate::report::write(&report_path, &report_record) {
711        eprintln!("error: {e}");
712        return 2;
713    }
714
715    let seconds = gate_outcome.elapsed.as_secs();
716    let gate_attempts = gate_outcome.gate_attempts;
717
718    let comments_str = match comments {
719        crate::config::CommentMode::Gate => "gate",
720        crate::config::CommentMode::Review => "review",
721        crate::config::CommentMode::Off => "off",
722    };
723    let env_names: Vec<&str> = dispatch_cfg.env.keys().map(String::as_str).collect();
724    let session = crate::usage_log::session_from(
725        std::env::var("BLYTE_SESSION").ok(),
726        std::env::var("CLAUDE_CODE_SESSION_ID").ok(),
727    );
728    let mut start_json = serde_json::json!({
729        "id": args.id,
730        "pid": std::process::id(),
731        "started_at": edit.started_at,
732        "task_file": task_path.display().to_string(),
733        "gate": full_gate,
734        "tags": Vec::<String>::new(),
735        "env": env_names,
736        "max_turns": 0,
737        "max_seconds": 0,
738        "plan": serde_json::Value::Null,
739        "plan_task": serde_json::Value::Null,
740        "request": args.request,
741        "base": edit.base,
742        "base_sha": edit.base_sha,
743        "base_check": "off",
744        "comments": comments_str,
745        "kind": "edit",
746    });
747    if let Some(s) = session {
748        start_json["session"] = serde_json::json!(s);
749    }
750
751    if let Err(e) = crate::dispatch::write_start_record(&start_path, &start_json) {
752        eprintln!(
753            "error: could not write start record {}: {e}",
754            start_path.display()
755        );
756        return 2;
757    }
758
759    if let Some(hook) = after_start_record {
760        if let Err(e) = hook() {
761            eprintln!("error: {e}");
762            return 2;
763        }
764    }
765
766    if let Err(e) = crate::queue_actions::evaluate_verified_run(root, &args.id) {
767        eprintln!(
768            "warning: post-edit review check failed for {}: {e}",
769            args.id
770        );
771    }
772
773    let summary = DispatchSummary {
774        id: args.id.clone(),
775        worktree: worktree_dir.display().to_string(),
776        branch,
777        outcome: "verified",
778        exit: 0,
779        error: None,
780        commits,
781        changed_files,
782        final_message: Some(task_text),
783        turns: 0,
784        gate_attempts,
785        gate_failures: Vec::new(),
786        cost_usd: Some(0.0),
787        model: None,
788        seconds,
789        sandbox: "none".to_string(),
790        // A direct edit has no implementer to send fallbacks back to.
791        fix_round: None,
792        log: log_path.display().to_string(),
793        report: report_path.display().to_string(),
794        gate_source,
795        research_report: None,
796        base_check_seconds: None,
797        warnings: Vec::new(),
798    };
799
800    if let Err(e) = write_json_atomic(&summary_path, &summary) {
801        eprintln!("error: {e}");
802        return 2;
803    }
804
805    let json = serde_json::to_string_pretty(&summary).unwrap();
806    println!("{json}");
807    0
808}
809
810fn commit_worktree_changes(worktree_dir: &Path, message: &str) -> Result<(), String> {
811    let add_out = Command::new("git")
812        .current_dir(worktree_dir)
813        .args(["add", "-A"])
814        .output()
815        .map_err(|e| format!("failed to run git add -A: {e}"))?;
816    if !add_out.status.success() {
817        return Err(format!(
818            "git add -A failed: {}",
819            String::from_utf8_lossy(&add_out.stderr).trim()
820        ));
821    }
822    let commit_out = Command::new("git")
823        .current_dir(worktree_dir)
824        .args(["commit", "--no-gpg-sign", "-m", message])
825        .output()
826        .map_err(|e| format!("failed to run git commit: {e}"))?;
827    if !commit_out.status.success() {
828        return Err(format!(
829            "git commit failed: {}",
830            String::from_utf8_lossy(&commit_out.stderr).trim()
831        ));
832    }
833    Ok(())
834}
835
836fn collect_commits(worktree_dir: &Path, base_sha: &str) -> Result<Vec<CommitRecord>, String> {
837    let out = Command::new("git")
838        .current_dir(worktree_dir)
839        .args([
840            "log",
841            "--reverse",
842            "--format=%h%x09%s",
843            &format!("{base_sha}..HEAD"),
844        ])
845        .output()
846        .map_err(|e| format!("failed to run git log: {e}"))?;
847    if !out.status.success() {
848        return Err(format!(
849            "git log failed: {}",
850            String::from_utf8_lossy(&out.stderr).trim()
851        ));
852    }
853    let text = String::from_utf8_lossy(&out.stdout);
854    let mut commits = Vec::new();
855    for line in text.lines() {
856        let line = line.trim();
857        if line.is_empty() {
858            continue;
859        }
860        if let Some((sha, subject)) = line.split_once('\t') {
861            commits.push(CommitRecord {
862                sha: sha.to_string(),
863                subject: subject.to_string(),
864            });
865        }
866    }
867    Ok(commits)
868}
869
870fn collect_changed_files(worktree_dir: &Path, base_sha: &str) -> Result<Vec<String>, String> {
871    let out = Command::new("git")
872        .current_dir(worktree_dir)
873        .args(["diff", "--name-only", &format!("{base_sha}..HEAD")])
874        .output()
875        .map_err(|e| format!("failed to run git diff: {e}"))?;
876    if !out.status.success() {
877        return Err(format!(
878            "git diff failed: {}",
879            String::from_utf8_lossy(&out.stderr).trim()
880        ));
881    }
882    let text = String::from_utf8_lossy(&out.stdout);
883    let mut files = Vec::new();
884    for line in text.lines() {
885        let line = line.trim();
886        if !line.is_empty() {
887            files.push(line.to_string());
888        }
889    }
890    Ok(files)
891}