Skip to main content

blyte_cli/
combine.rs

1//! `blyte combine <request>`: combine a request's passed runs on a work branch and run the gate.
2
3use std::collections::{BTreeMap, BTreeSet, HashMap};
4use std::io::Write;
5use std::path::{Path, PathBuf};
6use std::process::Command;
7use std::time::Duration;
8
9use blyte_agent::run::{gate_steps, run_gate_steps};
10use blyte_agent::shell::{LocalShell, Output, Shell};
11use serde::{Deserialize, Serialize};
12
13use crate::cli::{CombineArgs, ReviewVerdict};
14
15pub(crate) fn is_left_out_verdict(verdict: Option<ReviewVerdict>) -> bool {
16    verdict == Some(ReviewVerdict::Redone)
17}
18
19pub(crate) fn is_run_left_out(root: &Path, id: &str) -> Result<bool, String> {
20    Ok(is_left_out_verdict(crate::queue_actions::read_verdict(
21        root, id,
22    )?))
23}
24
25pub(crate) fn base_run_id(base: Option<&str>) -> Option<&str> {
26    let base = base?;
27    let clean = base.strip_prefix("refs/heads/").unwrap_or(base);
28    clean.strip_prefix("wip/")
29}
30
31pub(crate) fn check_not_based_on_left_out(
32    root: &Path,
33    run_id: &str,
34    base: Option<&str>,
35    left_out_ids: &BTreeSet<&str>,
36) -> Result<(), String> {
37    let Some(parent_id) = base_run_id(base) else {
38        return Ok(());
39    };
40    let parent_left_out = left_out_ids.contains(parent_id) || is_run_left_out(root, parent_id)?;
41    if parent_left_out {
42        return Err(format!(
43            "run {run_id} was dispatched from left-out run {parent_id} (branch wip/{parent_id})"
44        ));
45    }
46    Ok(())
47}
48
49/// Final state recorded in `.wt/combined/<request>.json`.
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
51#[serde(rename_all = "snake_case")]
52pub enum CombineState {
53    Combined,
54    Conflict,
55    CheckFailed,
56}
57
58/// A run id and tip commit SHA included in a combine.
59#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
60pub struct CombinedRun {
61    pub id: String,
62    pub tip: String,
63}
64
65/// Persistent combine record stored at `.wt/combined/<request>.json`.
66#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
67pub struct CombineRecord {
68    pub request: String,
69    pub state: CombineState,
70    pub branch: String,
71    pub base: String,
72    pub runs: Vec<CombinedRun>,
73    pub commits: Vec<String>,
74    #[serde(default, skip_serializing_if = "Option::is_none")]
75    pub conflicting_run: Option<String>,
76    #[serde(default, skip_serializing_if = "Vec::is_empty")]
77    pub conflicting_files: Vec<String>,
78    #[serde(default, skip_serializing_if = "Option::is_none")]
79    pub failing_step: Option<String>,
80    #[serde(default, skip_serializing_if = "Option::is_none")]
81    pub output_tail: Option<String>,
82}
83
84struct EnvShell<S> {
85    inner: S,
86    env: BTreeMap<String, String>,
87}
88
89impl<S: Shell> Shell for EnvShell<S> {
90    fn exec(&self, command: &str, cwd: &Path, timeout: Duration) -> Result<Output, String> {
91        if self.env.is_empty() {
92            return self.inner.exec(command, cwd, timeout);
93        }
94        let mut script = String::new();
95        for (k, v) in &self.env {
96            let quoted = format!("'{}'", v.replace('\'', "'\\''"));
97            script.push_str(&format!("export {k}={quoted}\n"));
98        }
99        script.push_str(command);
100        self.inner.exec(&script, cwd, timeout)
101    }
102
103    fn describe(&self) -> String {
104        self.inner.describe()
105    }
106}
107
108#[derive(Debug, Clone)]
109struct RunMeta {
110    id: String,
111    started_at: u64,
112    base: Option<String>,
113    base_sha: Option<String>,
114    branch_hint: Option<String>,
115}
116
117/// Entry point for `blyte combine <request>`.
118pub fn run(args: &CombineArgs) -> i32 {
119    if let Err(msg) = crate::dispatch::validate_request_id(&args.request) {
120        eprintln!("error: {msg}");
121        return 2;
122    }
123    let root = match crate::clean::find_repo_root() {
124        Ok(r) => r,
125        Err(e) => {
126            eprintln!("error: {e}");
127            return 2;
128        }
129    };
130    let mut stdout = std::io::stdout();
131    let mut stderr = std::io::stderr();
132    combine_in(&root, &args.request, &mut stdout, &mut stderr)
133}
134
135/// Combine all passed non-research runs for `request` inside repository `root`.
136pub fn combine_in(root: &Path, request: &str, out: &mut impl Write, err: &mut impl Write) -> i32 {
137    if let Err(msg) = crate::dispatch::validate_request_id(request) {
138        let _ = writeln!(err, "error: {msg}");
139        return 2;
140    }
141
142    match run_combine_inner(root, request) {
143        Ok(record) => {
144            let json = match serde_json::to_string_pretty(&record) {
145                Ok(j) => j,
146                Err(e) => {
147                    let _ = writeln!(err, "error: failed to serialize combine record: {e}");
148                    return 2;
149                }
150            };
151            let _ = writeln!(out, "{json}");
152            match record.state {
153                CombineState::Combined => 0,
154                CombineState::Conflict => {
155                    let Some(run_id) = record.conflicting_run.as_deref() else {
156                        let _ = writeln!(err, "error: combine record is missing conflicting_run");
157                        return 2;
158                    };
159                    let _ = writeln!(
160                        err,
161                        "combine conflict while applying run {run_id}: {}",
162                        record.conflicting_files.join(", ")
163                    );
164                    1
165                }
166                CombineState::CheckFailed => {
167                    let Some(step) = record.failing_step.as_deref() else {
168                        let _ = writeln!(err, "error: combine record is missing failing_step");
169                        return 2;
170                    };
171                    let _ = writeln!(err, "combine check failed at step: {step}");
172                    1
173                }
174            }
175        }
176        Err(msg) => {
177            let _ = writeln!(err, "error: {msg}");
178            2
179        }
180    }
181}
182
183fn run_combine_inner(root: &Path, request: &str) -> Result<CombineRecord, String> {
184    let wt_dir = root.join(".wt");
185    let runs = discover_and_validate_runs(root, request)?;
186    let ordered = order_runs(runs)?;
187    let run_id_set: BTreeSet<&str> = ordered.iter().map(|r| r.id.as_str()).collect();
188
189    let group_base = resolve_group_base(root, &ordered, &run_id_set)?;
190
191    let mut tips: HashMap<String, String> = HashMap::new();
192    let mut combined_runs: Vec<CombinedRun> = Vec::with_capacity(ordered.len());
193    for run in &ordered {
194        let tip = resolve_run_tip(root, run)?;
195        tips.insert(run.id.clone(), tip.clone());
196        combined_runs.push(CombinedRun {
197            id: run.id.clone(),
198            tip,
199        });
200    }
201
202    let branch = format!("blyte/{request}");
203    let worktree_dir = wt_dir.join(format!("combine-{request}"));
204    let combined_dir = wt_dir.join("combined");
205    let record_path = combined_dir.join(format!("{request}.json"));
206
207    let branch_exists = git_branch_exists(root, &branch)?;
208    let existing_record = load_record(&record_path)?;
209
210    if branch_exists && existing_record.is_none() {
211        return Err(format!(
212            "branch {branch} already exists without a combine record at {}; refusing to overwrite a branch not created by blyte combine",
213            record_path.display()
214        ));
215    }
216
217    let expected_existing_tip = existing_record
218        .as_ref()
219        .map(|rec| rec.commits.last().unwrap_or(&rec.base).as_str());
220
221    if let Some(ref rec) = existing_record {
222        if rec.state == CombineState::Combined
223            && branch_exists
224            && rec.runs == combined_runs
225            && rec.base == group_base
226        {
227            let actual_tip = git_rev_parse(root, &format!("refs/heads/{branch}^{{commit}}"))
228                .map_err(|e| format!("cannot resolve existing branch {branch}: {e}"))?;
229            let expected_tip = rec.commits.last().unwrap_or(&rec.base).as_str();
230            if actual_tip == expected_tip {
231                return Ok(rec.clone());
232            }
233        }
234    }
235
236    let dispatch_cfg = load_gate_config(root)?;
237    let gate = dispatch_cfg
238        .gate
239        .as_deref()
240        .filter(|g| !gate_steps(g).is_empty())
241        .ok_or_else(|| "blyte.toml has no [dispatch].gate configured".to_string())?
242        .to_string();
243
244    ensure_wt_excluded(root);
245    std::fs::create_dir_all(&combined_dir)
246        .map_err(|e| format!("failed to create {}: {e}", combined_dir.display()))?;
247
248    prepare_worktree(
249        root,
250        &worktree_dir,
251        &branch,
252        &group_base,
253        expected_existing_tip,
254    )?;
255
256    let mut last_good_head = group_base.clone();
257    for run in &ordered {
258        let tip = &tips[&run.id];
259        let parent_base = match parent_run_id(run, &run_id_set) {
260            Some(parent_id) => tips[parent_id].as_str(),
261            None => group_base.as_str(),
262        };
263        let commits = git_rev_list_range(root, parent_base, tip)?;
264        if commits.is_empty() {
265            continue;
266        }
267        for sha in &commits {
268            match git_cherry_pick_x(&worktree_dir, &run.id, sha) {
269                Ok(Ok(())) => {}
270                Ok(Err(conflict_files)) => {
271                    let _ = git_cmd(&worktree_dir, &["cherry-pick", "--abort"]);
272                    git_reset_hard(&worktree_dir, &last_good_head)?;
273                    let applied_commits = git_rev_list_range(&worktree_dir, &group_base, "HEAD")?;
274                    let record = CombineRecord {
275                        request: request.to_string(),
276                        state: CombineState::Conflict,
277                        branch,
278                        base: group_base,
279                        runs: combined_runs,
280                        commits: applied_commits,
281                        conflicting_run: Some(run.id.clone()),
282                        conflicting_files: conflict_files,
283                        failing_step: None,
284                        output_tail: None,
285                    };
286                    write_record(&record_path, &record)?;
287                    return Ok(record);
288                }
289                Err(err_msg) => {
290                    let _ = git_cmd(&worktree_dir, &["cherry-pick", "--abort"]);
291                    git_reset_hard(&worktree_dir, &last_good_head)?;
292                    return Err(err_msg);
293                }
294            }
295        }
296        last_good_head = git_rev_parse(&worktree_dir, "HEAD")?;
297    }
298
299    let combined_commits = git_rev_list_range(&worktree_dir, &group_base, "HEAD")?;
300
301    if let Some(ref setup_cmd) = dispatch_cfg.setup {
302        let main_checkout =
303            crate::config::main_checkout(root).unwrap_or_else(|| root.to_path_buf());
304        let setup_log_path = wt_dir.join(format!("combine-{request}.setup.log"));
305        if let Err(msg) = crate::setup::run_setup(
306            setup_cmd,
307            &worktree_dir,
308            &main_checkout,
309            &dispatch_cfg.env,
310            &setup_log_path,
311            crate::setup::SETUP_TIMEOUT,
312        ) {
313            let record = CombineRecord {
314                request: request.to_string(),
315                state: CombineState::CheckFailed,
316                branch,
317                base: group_base,
318                runs: combined_runs,
319                commits: combined_commits,
320                conflicting_run: None,
321                conflicting_files: Vec::new(),
322                failing_step: Some("setup".to_string()),
323                output_tail: Some(tail_output(&msg, 50, 4000)),
324            };
325            write_record(&record_path, &record)?;
326            return Ok(record);
327        }
328    }
329
330    let shell = EnvShell {
331        inner: LocalShell::new(),
332        env: dispatch_cfg.env.clone(),
333    };
334    let mut deadline = None;
335    let gate_result = run_gate_steps(
336        &shell,
337        &gate,
338        &worktree_dir,
339        &[],
340        &mut deadline,
341        |_| {},
342        &std::time::Instant::now,
343    );
344
345    let record = if gate_result.passed {
346        CombineRecord {
347            request: request.to_string(),
348            state: CombineState::Combined,
349            branch,
350            base: group_base,
351            runs: combined_runs,
352            commits: combined_commits,
353            conflicting_run: None,
354            conflicting_files: Vec::new(),
355            failing_step: None,
356            output_tail: None,
357        }
358    } else {
359        let (failing_step, raw_output) = match gate_result.failures.first() {
360            Some(f) => (f.step.clone(), f.output.as_str()),
361            None => (gate.clone(), gate_result.output.as_str()),
362        };
363        CombineRecord {
364            request: request.to_string(),
365            state: CombineState::CheckFailed,
366            branch,
367            base: group_base,
368            runs: combined_runs,
369            commits: combined_commits,
370            conflicting_run: None,
371            conflicting_files: Vec::new(),
372            failing_step: Some(failing_step),
373            output_tail: Some(tail_output(raw_output, 50, 4000)),
374        }
375    };
376
377    write_record(&record_path, &record)?;
378    Ok(record)
379}
380
381fn discover_and_validate_runs(root: &Path, request: &str) -> Result<Vec<RunMeta>, String> {
382    let wt_dir = root.join(".wt");
383    if !wt_dir.is_dir() {
384        return Err(format!("no runs found for request {request}"));
385    }
386
387    let mut entries: Vec<PathBuf> = Vec::new();
388    for entry in std::fs::read_dir(&wt_dir)
389        .map_err(|e| format!("failed to read {}: {e}", wt_dir.display()))?
390    {
391        let entry =
392            entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
393        let path = entry.path();
394        if path
395            .file_name()
396            .and_then(|n| n.to_str())
397            .is_some_and(|n| n.ends_with(".start.json"))
398        {
399            entries.push(path);
400        }
401    }
402    entries.sort();
403
404    let mut found = Vec::new();
405    let mut bad_runs = Vec::new();
406    let mut active_bases: Vec<(String, Option<String>)> = Vec::new();
407    let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
408
409    for path in entries {
410        let content = std::fs::read_to_string(&path)
411            .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
412        let val: serde_json::Value = serde_json::from_str(&content)
413            .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
414        if val.get("request").and_then(|v| v.as_str()) != Some(request) {
415            continue;
416        }
417        let file_id = path
418            .file_name()
419            .and_then(|n| n.to_str())
420            .and_then(|n| n.strip_suffix(".start.json"))
421            .filter(|s| !s.is_empty())
422            .ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
423        if let Some(id_val) = val.get("id") {
424            let field_id = id_val.as_str().ok_or_else(|| {
425                format!(
426                    "start file {} has non-string id {id_val}, expected {file_id}",
427                    path.display()
428                )
429            })?;
430            if field_id != file_id {
431                return Err(format!(
432                    "start file {} has id {field_id} which differs from file name id {file_id}",
433                    path.display()
434                ));
435            }
436        }
437        let is_research = val
438            .get("research")
439            .and_then(|v| v.as_bool())
440            .unwrap_or(false)
441            || val
442                .get("tags")
443                .and_then(|v| v.as_array())
444                .is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")));
445        if is_research {
446            continue;
447        }
448        let id = file_id.to_string();
449        if is_run_left_out(root, &id)? {
450            left_out_ids.insert(id);
451            continue;
452        }
453        let started_at = val
454            .get("started_at")
455            .and_then(|v| v.as_u64())
456            .ok_or_else(|| {
457                format!(
458                    "start file {} is missing numeric started_at",
459                    path.display()
460                )
461            })?;
462        let base = val
463            .get("base")
464            .and_then(|v| v.as_str())
465            .map(ToString::to_string);
466        let base_sha = val
467            .get("base_sha")
468            .and_then(|v| v.as_str())
469            .map(ToString::to_string);
470        active_bases.push((id.clone(), base.clone()));
471
472        let summary_path = wt_dir.join(format!("{id}.json"));
473        let summary: Option<serde_json::Value> = match std::fs::read_to_string(&summary_path) {
474            Ok(s) => {
475                let parsed: serde_json::Value = serde_json::from_str(&s)
476                    .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
477                Some(parsed)
478            }
479            Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
480            Err(e) => {
481                return Err(format!("failed to read {}: {e}", summary_path.display()));
482            }
483        };
484
485        let mut reasons = Vec::new();
486        let mut branch_hint = None;
487        match summary {
488            None => {
489                reasons.push("unfinished".to_string());
490            }
491            Some(ref s) => {
492                let outcome = s.get("outcome").and_then(|v| v.as_str()).ok_or_else(|| {
493                    format!(
494                        "summary file {} is missing string outcome",
495                        summary_path.display()
496                    )
497                })?;
498                if outcome != "verified" {
499                    reasons.push(outcome.to_string());
500                }
501                if let Some(branch_val) = s.get("branch").filter(|v| !v.is_null()) {
502                    let branch_str = branch_val.as_str().ok_or_else(|| {
503                        format!(
504                            "summary file {} has non-string branch",
505                            summary_path.display()
506                        )
507                    })?;
508                    branch_hint = Some(branch_str.to_string());
509                }
510            }
511        }
512
513        if !reasons.is_empty() {
514            bad_runs.push((started_at, id, reasons.join(", ")));
515        } else {
516            found.push(RunMeta {
517                id,
518                started_at,
519                base,
520                base_sha,
521                branch_hint,
522            });
523        }
524    }
525
526    let left_out_refs: BTreeSet<&str> = left_out_ids.iter().map(String::as_str).collect();
527    for (id, base) in &active_bases {
528        check_not_based_on_left_out(root, id, base.as_deref(), &left_out_refs)?;
529    }
530
531    if !bad_runs.is_empty() {
532        bad_runs.sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
533        let details: Vec<String> = bad_runs
534            .into_iter()
535            .map(|(_, id, state)| format!("{id} ({state})"))
536            .collect();
537        return Err(format!(
538            "cannot combine request {request}; runs not ready: {}",
539            details.join(", ")
540        ));
541    }
542
543    if found.is_empty() {
544        if !left_out_ids.is_empty() {
545            return Err(format!(
546                "cannot combine request {request}: every run was redone"
547            ));
548        }
549        return Err(format!("no runs found for request {request}"));
550    }
551
552    Ok(found)
553}
554
555fn parent_run_id<'a>(run: &'a RunMeta, run_ids: &BTreeSet<&str>) -> Option<&'a str> {
556    let other = base_run_id(run.base.as_deref())?;
557    if run_ids.contains(other) {
558        Some(other)
559    } else {
560        None
561    }
562}
563
564fn order_runs(runs: Vec<RunMeta>) -> Result<Vec<RunMeta>, String> {
565    let by_id: HashMap<String, RunMeta> = runs.into_iter().map(|r| (r.id.clone(), r)).collect();
566    let id_set: BTreeSet<&str> = by_id.keys().map(String::as_str).collect();
567
568    let mut in_degree: HashMap<String, usize> = HashMap::new();
569    let mut children: HashMap<String, Vec<String>> = HashMap::new();
570    for (id, run) in &by_id {
571        if let Some(parent) = parent_run_id(run, &id_set) {
572            in_degree.insert(id.clone(), 1);
573            children
574                .entry(parent.to_string())
575                .or_default()
576                .push(id.clone());
577        } else {
578            in_degree.insert(id.clone(), 0);
579        }
580    }
581
582    let mut ready: BTreeSet<(u64, String)> = BTreeSet::new();
583    for (id, &deg) in &in_degree {
584        if deg == 0 {
585            ready.insert((by_id[id].started_at, id.clone()));
586        }
587    }
588
589    let mut ordered = Vec::with_capacity(by_id.len());
590    while let Some((_, id)) = ready.pop_first() {
591        ordered.push(by_id[&id].clone());
592        if let Some(kids) = children.get(&id) {
593            for kid in kids {
594                let deg = in_degree.get_mut(kid).expect("kid in in_degree");
595                *deg -= 1;
596                if *deg == 0 {
597                    ready.insert((by_id[kid].started_at, kid.clone()));
598                }
599            }
600        }
601    }
602
603    if ordered.len() != by_id.len() {
604        let mut remaining: Vec<&str> = in_degree
605            .iter()
606            .filter(|(_, &deg)| deg > 0)
607            .map(|(id, _)| id.as_str())
608            .collect();
609        remaining.sort();
610        return Err(format!(
611            "cyclic base dependency among runs: {}",
612            remaining.join(", ")
613        ));
614    }
615
616    Ok(ordered)
617}
618
619fn resolve_group_base(
620    root: &Path,
621    ordered: &[RunMeta],
622    run_ids: &BTreeSet<&str>,
623) -> Result<String, String> {
624    let mut root_bases: Vec<(String, String)> = Vec::new();
625    for run in ordered {
626        if parent_run_id(run, run_ids).is_some() {
627            continue;
628        }
629        let spec = run
630            .base_sha
631            .as_deref()
632            .filter(|s| !s.is_empty())
633            .ok_or_else(|| format!("run {} has no base_sha in start.json", run.id))?;
634        let sha = git_rev_parse(root, &format!("{spec}^{{commit}}"))
635            .map_err(|e| format!("cannot resolve base_sha {spec} for run {}: {e}", run.id))?;
636        root_bases.push((run.id.clone(), sha));
637    }
638
639    if root_bases.is_empty() {
640        return Err("no root run found to determine base commit".to_string());
641    }
642
643    let first_sha = &root_bases[0].1;
644    let all_same = root_bases.iter().all(|(_, sha)| sha == first_sha);
645    if !all_same {
646        let details: Vec<String> = root_bases
647            .iter()
648            .map(|(id, sha)| format!("{id} ({})", &sha[..sha.len().min(7)]))
649            .collect();
650        return Err(format!(
651            "runs started from different base commits: {}",
652            details.join(", ")
653        ));
654    }
655
656    Ok(first_sha.clone())
657}
658
659fn resolve_run_tip(root: &Path, run: &RunMeta) -> Result<String, String> {
660    let branch = match run.branch_hint.as_deref() {
661        Some(b) => b.to_string(),
662        None => format!("wip/{}", run.id),
663    };
664    let rev = format!("refs/heads/{branch}^{{commit}}");
665    git_rev_parse(root, &rev).map_err(|e| {
666        format!(
667            "cannot resolve tip commit for run {} on branch {branch}: {e}",
668            run.id
669        )
670    })
671}
672
673fn load_gate_config(root: &Path) -> Result<crate::config::DispatchConfig, String> {
674    match crate::config::load_with_fallback(root)? {
675        Some((cfg, _)) => Ok(cfg.dispatch),
676        None => Err("no blyte.toml found in repository".to_string()),
677    }
678}
679
680fn load_record(path: &Path) -> Result<Option<CombineRecord>, String> {
681    if !path.exists() {
682        return Ok(None);
683    }
684    let content = std::fs::read_to_string(path)
685        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
686    let record: CombineRecord = serde_json::from_str(&content)
687        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
688    Ok(Some(record))
689}
690
691fn write_record(path: &Path, record: &CombineRecord) -> Result<(), String> {
692    let json = serde_json::to_string_pretty(record)
693        .map_err(|e| format!("failed to serialize combine record: {e}"))?;
694    std::fs::write(path, json + "\n")
695        .map_err(|e| format!("failed to write {}: {e}", path.display()))
696}
697
698fn prepare_worktree(
699    root: &Path,
700    worktree_dir: &Path,
701    branch: &str,
702    base_commit: &str,
703    expected_existing_tip: Option<&str>,
704) -> Result<(), String> {
705    let wt_str = worktree_dir
706        .to_str()
707        .ok_or_else(|| format!("non-UTF-8 worktree path: {}", worktree_dir.display()))?;
708
709    let branch_exists = git_branch_exists(root, branch)?;
710    if branch_exists {
711        let expected = expected_existing_tip.ok_or_else(|| {
712            format!(
713                "branch {branch} already exists without an expected commit from a combine record; refusing to delete it"
714            )
715        })?;
716        let actual = git_rev_parse(root, &format!("refs/heads/{branch}^{{commit}}"))
717            .map_err(|e| format!("cannot resolve existing branch {branch}: {e}"))?;
718        if actual != expected {
719            return Err(format!(
720                "branch {branch} has changed since blyte combined it (expected {expected}, actual {actual}); refusing to delete it"
721            ));
722        }
723    }
724
725    if worktree_dir.exists() {
726        let _ = git_cmd(worktree_dir, &["cherry-pick", "--abort"]);
727        let _ = git_cmd(root, &["worktree", "remove", "--force", wt_str]);
728        if worktree_dir.exists() {
729            std::fs::remove_dir_all(worktree_dir).map_err(|e| {
730                format!(
731                    "failed to clean existing worktree {}: {e}",
732                    worktree_dir.display()
733                )
734            })?;
735        }
736    }
737    let _ = git_cmd(root, &["worktree", "prune"]);
738
739    if branch_exists {
740        git_cmd(root, &["branch", "-D", branch])
741            .map_err(|e| format!("failed to reset branch {branch}: {e}"))?;
742    }
743
744    git_cmd(
745        root,
746        &["worktree", "add", "-b", branch, wt_str, base_commit],
747    )
748    .map_err(|e| format!("failed to create combine worktree {wt_str}: {e}"))?;
749    Ok(())
750}
751
752fn ensure_wt_excluded(root: &Path) {
753    if let Ok(common) = git_cmd(root, &["rev-parse", "--git-common-dir"]) {
754        let common_path = PathBuf::from(common.trim());
755        let common_dir = if common_path.is_absolute() {
756            common_path
757        } else {
758            root.join(common_path)
759        };
760        let exclude_path = common_dir.join("info").join("exclude");
761        if let Some(parent) = exclude_path.parent() {
762            let _ = std::fs::create_dir_all(parent);
763        }
764        let content = std::fs::read_to_string(&exclude_path).unwrap_or_default();
765        if !content.lines().any(|l| l.trim() == ".wt/") {
766            let mut next = content;
767            if !next.is_empty() && !next.ends_with('\n') {
768                next.push('\n');
769            }
770            next.push_str(".wt/\n");
771            let _ = std::fs::write(&exclude_path, next);
772        }
773    }
774}
775
776fn git_cmd(dir: &Path, args: &[&str]) -> Result<String, String> {
777    let out = Command::new("git")
778        .args(args)
779        .current_dir(dir)
780        .output()
781        .map_err(|e| format!("failed to execute git {}: {e}", args.join(" ")))?;
782    if out.status.success() {
783        Ok(String::from_utf8_lossy(&out.stdout).to_string())
784    } else {
785        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
786        let stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
787        let detail = if !stderr.is_empty() { stderr } else { stdout };
788        Err(detail)
789    }
790}
791
792fn git_rev_parse(dir: &Path, rev: &str) -> Result<String, String> {
793    Ok(git_cmd(dir, &["rev-parse", "--verify", rev])?
794        .trim()
795        .to_string())
796}
797
798fn git_branch_exists(dir: &Path, branch: &str) -> Result<bool, String> {
799    let out = Command::new("git")
800        .args([
801            "show-ref",
802            "--verify",
803            "--quiet",
804            &format!("refs/heads/{branch}"),
805        ])
806        .current_dir(dir)
807        .output()
808        .map_err(|e| format!("failed to check branch {branch}: {e}"))?;
809    Ok(out.status.success())
810}
811
812fn git_rev_list_range(dir: &Path, base: &str, tip: &str) -> Result<Vec<String>, String> {
813    let range = format!("{base}..{tip}");
814    let out = git_cmd(dir, &["rev-list", "--reverse", &range])?;
815    Ok(out
816        .lines()
817        .map(str::trim)
818        .filter(|s| !s.is_empty())
819        .map(ToString::to_string)
820        .collect())
821}
822
823fn git_cherry_pick_x(
824    worktree_dir: &Path,
825    run_id: &str,
826    sha: &str,
827) -> Result<Result<(), Vec<String>>, String> {
828    let out = Command::new("git")
829        .args(["cherry-pick", "-x", sha])
830        .current_dir(worktree_dir)
831        .output()
832        .map_err(|e| format!("failed to execute git cherry-pick -x {sha} for run {run_id}: {e}"))?;
833    if out.status.success() {
834        return Ok(Ok(()));
835    }
836    let cp_stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
837    let cp_stdout = String::from_utf8_lossy(&out.stdout).trim().to_string();
838    let cp_detail = if !cp_stderr.is_empty() {
839        cp_stderr
840    } else {
841        cp_stdout
842    };
843
844    let diff_out = Command::new("git")
845        .args(["diff", "--name-only", "--diff-filter=U"])
846        .current_dir(worktree_dir)
847        .output()
848        .map_err(|e| {
849            format!(
850                "git cherry-pick -x {sha} for run {run_id} failed ({cp_detail}); failed to list unmerged files: {e}"
851            )
852        })?;
853    if !diff_out.status.success() {
854        let diff_stderr = String::from_utf8_lossy(&diff_out.stderr).trim().to_string();
855        return Err(format!(
856            "git cherry-pick -x {sha} for run {run_id} failed ({cp_detail}); git diff --name-only --diff-filter=U failed: {diff_stderr}"
857        ));
858    }
859    let unmerged: Vec<String> = String::from_utf8_lossy(&diff_out.stdout)
860        .lines()
861        .map(str::trim)
862        .filter(|s| !s.is_empty())
863        .map(ToString::to_string)
864        .collect();
865    if unmerged.is_empty() {
866        return Err(format!(
867            "git cherry-pick -x {sha} for run {run_id} failed without unmerged files: {cp_detail}"
868        ));
869    }
870    Ok(Err(unmerged))
871}
872
873fn git_reset_hard(worktree_dir: &Path, rev: &str) -> Result<(), String> {
874    git_cmd(worktree_dir, &["reset", "--hard", rev])?;
875    Ok(())
876}
877
878fn tail_output(text: &str, max_lines: usize, max_bytes: usize) -> String {
879    let lines: Vec<&str> = text.lines().collect();
880    let start = lines.len().saturating_sub(max_lines);
881    let mut joined = lines[start..].join("\n");
882    if joined.len() > max_bytes {
883        let mut cut = joined.len() - max_bytes;
884        while cut < joined.len() && !joined.is_char_boundary(cut) {
885            cut += 1;
886        }
887        joined = joined[cut..].to_string();
888    }
889    joined
890}
891
892#[cfg(test)]
893mod tests {
894    use super::*;
895
896    fn git(dir: &Path, args: &[&str]) -> String {
897        let out = Command::new("git")
898            .args(args)
899            .current_dir(dir)
900            .output()
901            .expect("run git");
902        assert!(
903            out.status.success(),
904            "git {:?} failed:\nstdout: {}\nstderr: {}",
905            args,
906            String::from_utf8_lossy(&out.stdout),
907            String::from_utf8_lossy(&out.stderr)
908        );
909        String::from_utf8_lossy(&out.stdout).trim().to_string()
910    }
911
912    fn init_repo(gate: &str) -> (tempfile::TempDir, String) {
913        let dir = tempfile::tempdir().unwrap();
914        let root = dir.path();
915        git(root, &["init", "-b", "main"]);
916        git(root, &["config", "user.name", "Test User"]);
917        git(root, &["config", "user.email", "test@example.com"]);
918        std::fs::write(
919            root.join("blyte.toml"),
920            format!("[dispatch]\ngate = \"\"\"\n{gate}\n\"\"\"\n"),
921        )
922        .unwrap();
923        std::fs::write(root.join("shared.txt"), "base line\n").unwrap();
924        git(root, &["add", "."]);
925        git(root, &["commit", "--no-gpg-sign", "-m", "initial"]);
926        let base_sha = git(root, &["rev-parse", "HEAD"]);
927        (dir, base_sha)
928    }
929
930    fn create_run_branch(
931        root: &Path,
932        id: &str,
933        request: &str,
934        base_ref: &str,
935        started_at: u64,
936        commits: &[(&str, &str, &str)],
937        outcome: Option<&str>,
938    ) -> String {
939        let wt_dir = root.join(".wt");
940        std::fs::create_dir_all(&wt_dir).unwrap();
941        let run_wt = wt_dir.join(id);
942        let branch = format!("wip/{id}");
943        let base_sha = git(root, &["rev-parse", &format!("{base_ref}^{{commit}}")]);
944        git(
945            root,
946            &[
947                "worktree",
948                "add",
949                "-b",
950                &branch,
951                run_wt.to_str().unwrap(),
952                &base_sha,
953            ],
954        );
955        for (file, content, msg) in commits {
956            let file_path = run_wt.join(file);
957            if let Some(parent) = file_path.parent() {
958                std::fs::create_dir_all(parent).unwrap();
959            }
960            std::fs::write(&file_path, content).unwrap();
961            git(&run_wt, &["add", file]);
962            git(&run_wt, &["commit", "--no-gpg-sign", "-m", msg]);
963        }
964        let tip = git(&run_wt, &["rev-parse", "HEAD"]);
965        let start_json = serde_json::json!({
966            "id": id,
967            "request": request,
968            "base": base_ref,
969            "base_sha": base_sha,
970            "started_at": started_at,
971            "research": false,
972        });
973        std::fs::write(
974            wt_dir.join(format!("{id}.start.json")),
975            serde_json::to_string_pretty(&start_json).unwrap(),
976        )
977        .unwrap();
978        if let Some(out) = outcome {
979            let summary_json = serde_json::json!({
980                "id": id,
981                "branch": branch,
982                "outcome": out,
983            });
984            std::fs::write(
985                wt_dir.join(format!("{id}.json")),
986                serde_json::to_string_pretty(&summary_json).unwrap(),
987            )
988            .unwrap();
989        }
990        tip
991    }
992
993    #[test]
994    fn cli_parses_combine() {
995        use crate::cli::{Cli, Command};
996        use clap::Parser;
997
998        let cli = Cli::try_parse_from(["blyte", "combine", "req-42"]).unwrap();
999        assert_eq!(
1000            cli.command,
1001            Some(Command::Combine(CombineArgs {
1002                request: "req-42".to_string(),
1003            }))
1004        );
1005        assert!(Cli::try_parse_from(["blyte", "combine"]).is_err());
1006    }
1007
1008    #[test]
1009    fn two_independent_runs_combine_and_gate_runs() {
1010        let (dir, base_sha) = init_repo("test -f a.txt && test -f b.txt");
1011        let root = dir.path();
1012        let tip_a = create_run_branch(
1013            root,
1014            "T1",
1015            "req1",
1016            "main",
1017            100,
1018            &[("a.txt", "alpha\n", "add a")],
1019            Some("verified"),
1020        );
1021        let tip_b = create_run_branch(
1022            root,
1023            "T2",
1024            "req1",
1025            "main",
1026            200,
1027            &[("b.txt", "beta\n", "add b")],
1028            Some("verified"),
1029        );
1030
1031        let research_start = serde_json::json!({
1032            "id": "R1",
1033            "request": "req1",
1034            "base": "main",
1035            "base_sha": base_sha,
1036            "started_at": 50,
1037            "research": true,
1038        });
1039        std::fs::write(
1040            root.join(".wt/R1.start.json"),
1041            serde_json::to_string_pretty(&research_start).unwrap(),
1042        )
1043        .unwrap();
1044
1045        let mut out = Vec::new();
1046        let mut err = Vec::new();
1047        let code = combine_in(root, "req1", &mut out, &mut err);
1048        assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1049
1050        let record: CombineRecord = serde_json::from_str(
1051            &std::fs::read_to_string(root.join(".wt/combined/req1.json")).unwrap(),
1052        )
1053        .unwrap();
1054        assert_eq!(record.state, CombineState::Combined);
1055        assert_eq!(record.branch, "blyte/req1");
1056        assert_eq!(record.base, base_sha);
1057        assert_eq!(
1058            record.runs,
1059            vec![
1060                CombinedRun {
1061                    id: "T1".to_string(),
1062                    tip: tip_a.clone(),
1063                },
1064                CombinedRun {
1065                    id: "T2".to_string(),
1066                    tip: tip_b.clone(),
1067                },
1068            ]
1069        );
1070        assert_eq!(record.commits.len(), 2);
1071
1072        let combine_wt = root.join(".wt/combine-req1");
1073        assert!(combine_wt.join("a.txt").exists());
1074        assert!(combine_wt.join("b.txt").exists());
1075        assert!(!root.join("a.txt").exists());
1076        assert!(!root.join("b.txt").exists());
1077
1078        let log_msg = git(&combine_wt, &["log", "-n", "1", "--format=%B"]);
1079        assert!(log_msg.contains(&format!("(cherry picked from commit {tip_b})")));
1080    }
1081
1082    #[test]
1083    fn dependent_run_applies_only_its_own_commits() {
1084        let (dir, _base_sha) = init_repo("test -f p.txt && test -f c.txt");
1085        let root = dir.path();
1086        let tip_parent = create_run_branch(
1087            root,
1088            "T1",
1089            "req-dep",
1090            "main",
1091            200,
1092            &[("p.txt", "parent\n", "add parent")],
1093            Some("verified"),
1094        );
1095        let tip_child = create_run_branch(
1096            root,
1097            "T2",
1098            "req-dep",
1099            "wip/T1",
1100            100,
1101            &[("c.txt", "child\n", "add child")],
1102            Some("verified"),
1103        );
1104
1105        let mut out = Vec::new();
1106        let mut err = Vec::new();
1107        let code = combine_in(root, "req-dep", &mut out, &mut err);
1108        assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1109
1110        let record: CombineRecord = serde_json::from_str(
1111            &std::fs::read_to_string(root.join(".wt/combined/req-dep.json")).unwrap(),
1112        )
1113        .unwrap();
1114        assert_eq!(record.state, CombineState::Combined);
1115        assert_eq!(
1116            record.runs,
1117            vec![
1118                CombinedRun {
1119                    id: "T1".to_string(),
1120                    tip: tip_parent,
1121                },
1122                CombinedRun {
1123                    id: "T2".to_string(),
1124                    tip: tip_child,
1125                },
1126            ]
1127        );
1128        assert_eq!(record.commits.len(), 2);
1129
1130        let combine_wt = root.join(".wt/combine-req-dep");
1131        let subjects = git(
1132            &combine_wt,
1133            &["log", "--reverse", "--format=%s", "main..HEAD"],
1134        );
1135        assert_eq!(subjects, "add parent\nadd child");
1136    }
1137
1138    #[test]
1139    fn conflict_aborts_and_names_run_and_files() {
1140        let (dir, _base_sha) = init_repo("true");
1141        let root = dir.path();
1142        create_run_branch(
1143            root,
1144            "T1",
1145            "req-conflict",
1146            "main",
1147            100,
1148            &[("shared.txt", "change from T1\n", "T1 edits shared")],
1149            Some("verified"),
1150        );
1151        create_run_branch(
1152            root,
1153            "T2",
1154            "req-conflict",
1155            "main",
1156            200,
1157            &[
1158                ("extra.txt", "clean first commit\n", "T2 clean commit"),
1159                ("shared.txt", "change from T2\n", "T2 conflicting edit"),
1160            ],
1161            Some("verified"),
1162        );
1163
1164        let mut out = Vec::new();
1165        let mut err = Vec::new();
1166        let code = combine_in(root, "req-conflict", &mut out, &mut err);
1167        assert_ne!(code, 0);
1168
1169        let record: CombineRecord = serde_json::from_str(
1170            &std::fs::read_to_string(root.join(".wt/combined/req-conflict.json")).unwrap(),
1171        )
1172        .unwrap();
1173        assert_eq!(record.state, CombineState::Conflict);
1174        assert_eq!(record.conflicting_run.as_deref(), Some("T2"));
1175        assert_eq!(record.conflicting_files, vec!["shared.txt".to_string()]);
1176        assert_eq!(record.commits.len(), 1);
1177
1178        let combine_wt = root.join(".wt/combine-req-conflict");
1179        assert!(!combine_wt.join("extra.txt").exists());
1180        assert_eq!(
1181            std::fs::read_to_string(combine_wt.join("shared.txt")).unwrap(),
1182            "change from T1\n"
1183        );
1184        let status = git(&combine_wt, &["status", "--porcelain"]);
1185        assert!(status.is_empty(), "worktree should be clean: {status}");
1186    }
1187
1188    #[test]
1189    fn failing_gate_records_check_failed_with_step_and_output() {
1190        let (dir, _base_sha) = init_repo("true\necho broken-check >&2 && exit 1");
1191        let root = dir.path();
1192        create_run_branch(
1193            root,
1194            "T1",
1195            "req-fail",
1196            "main",
1197            100,
1198            &[("a.txt", "hello\n", "add a")],
1199            Some("verified"),
1200        );
1201
1202        let mut out = Vec::new();
1203        let mut err = Vec::new();
1204        let code = combine_in(root, "req-fail", &mut out, &mut err);
1205        assert_ne!(code, 0);
1206
1207        let record: CombineRecord = serde_json::from_str(
1208            &std::fs::read_to_string(root.join(".wt/combined/req-fail.json")).unwrap(),
1209        )
1210        .unwrap();
1211        assert_eq!(record.state, CombineState::CheckFailed);
1212        assert_eq!(
1213            record.failing_step.as_deref(),
1214            Some("echo broken-check >&2 && exit 1")
1215        );
1216        assert!(record
1217            .output_tail
1218            .as_deref()
1219            .unwrap_or("")
1220            .contains("broken-check"));
1221    }
1222
1223    #[test]
1224    fn unfinished_and_unverified_runs_are_refused_while_redone_is_left_out() {
1225        let (dir, _base_sha) = init_repo("true");
1226        let root = dir.path();
1227        create_run_branch(
1228            root,
1229            "T1",
1230            "req-bad",
1231            "main",
1232            100,
1233            &[("a.txt", "a\n", "a")],
1234            None,
1235        );
1236        create_run_branch(
1237            root,
1238            "T2",
1239            "req-bad",
1240            "main",
1241            200,
1242            &[("b.txt", "b\n", "b")],
1243            Some("gate_failed"),
1244        );
1245        create_run_branch(
1246            root,
1247            "T3",
1248            "req-bad",
1249            "main",
1250            300,
1251            &[("c.txt", "c\n", "c")],
1252            Some("verified"),
1253        );
1254        std::fs::write(
1255            root.join(".wt/T3.verdict.json"),
1256            r#"{"verdict":"redone","notes":"redo","ts":1}"#,
1257        )
1258        .unwrap();
1259
1260        let mut out = Vec::new();
1261        let mut err = Vec::new();
1262        let code = combine_in(root, "req-bad", &mut out, &mut err);
1263        assert_eq!(code, 2);
1264
1265        let err_str = String::from_utf8(err).unwrap();
1266        assert!(
1267            err_str.contains("T1") && err_str.contains("unfinished"),
1268            "{err_str}"
1269        );
1270        assert!(
1271            err_str.contains("T2") && err_str.contains("gate_failed"),
1272            "{err_str}"
1273        );
1274        assert!(!err_str.contains("T3"), "{err_str}");
1275    }
1276
1277    #[test]
1278    fn second_call_with_same_tips_is_noop_and_different_tips_rebuilds() {
1279        let marker = tempfile::NamedTempFile::new().unwrap();
1280        let marker_path = marker.path().to_path_buf();
1281        let gate = format!("echo run >> '{}'", marker_path.display());
1282        let (dir, _base_sha) = init_repo(&gate);
1283        let root = dir.path();
1284        create_run_branch(
1285            root,
1286            "T1",
1287            "req-idem",
1288            "main",
1289            100,
1290            &[("a.txt", "v1\n", "v1")],
1291            Some("verified"),
1292        );
1293
1294        let mut out = Vec::new();
1295        let mut err = Vec::new();
1296        assert_eq!(combine_in(root, "req-idem", &mut out, &mut err), 0);
1297        let first_head = git(root, &["rev-parse", "blyte/req-idem"]);
1298        let runs_after_first = std::fs::read_to_string(&marker_path)
1299            .unwrap()
1300            .lines()
1301            .count();
1302        assert_eq!(runs_after_first, 1);
1303
1304        out.clear();
1305        err.clear();
1306        assert_eq!(combine_in(root, "req-idem", &mut out, &mut err), 0);
1307        let second_head = git(root, &["rev-parse", "blyte/req-idem"]);
1308        let runs_after_second = std::fs::read_to_string(&marker_path)
1309            .unwrap()
1310            .lines()
1311            .count();
1312        assert_eq!(first_head, second_head);
1313        assert_eq!(runs_after_second, 1);
1314
1315        let t1_wt = root.join(".wt/T1");
1316        std::fs::write(t1_wt.join("a.txt"), "v2\n").unwrap();
1317        git(&t1_wt, &["add", "a.txt"]);
1318        git(&t1_wt, &["commit", "--no-gpg-sign", "-m", "v2"]);
1319
1320        out.clear();
1321        err.clear();
1322        assert_eq!(combine_in(root, "req-idem", &mut out, &mut err), 0);
1323        let third_head = git(root, &["rev-parse", "blyte/req-idem"]);
1324        let runs_after_third = std::fs::read_to_string(&marker_path)
1325            .unwrap()
1326            .lines()
1327            .count();
1328        assert_ne!(third_head, first_head);
1329        assert_eq!(runs_after_third, 2);
1330        assert_eq!(
1331            std::fs::read_to_string(root.join(".wt/combine-req-idem/a.txt")).unwrap(),
1332            "v2\n"
1333        );
1334    }
1335
1336    #[test]
1337    fn existing_foreign_branch_is_refused() {
1338        let (dir, _base_sha) = init_repo("true");
1339        let root = dir.path();
1340        create_run_branch(
1341            root,
1342            "T1",
1343            "req-foreign",
1344            "main",
1345            100,
1346            &[("a.txt", "a\n", "add a")],
1347            Some("verified"),
1348        );
1349        git(root, &["branch", "blyte/req-foreign", "main"]);
1350        let before = git(root, &["rev-parse", "blyte/req-foreign"]);
1351
1352        let mut out = Vec::new();
1353        let mut err = Vec::new();
1354        let code = combine_in(root, "req-foreign", &mut out, &mut err);
1355        assert_ne!(code, 0);
1356        let err_str = String::from_utf8(err).unwrap();
1357        assert!(err_str.contains("blyte/req-foreign"), "{err_str}");
1358        assert_eq!(git(root, &["rev-parse", "blyte/req-foreign"]), before);
1359        assert!(!root.join(".wt/combined/req-foreign.json").exists());
1360    }
1361
1362    #[test]
1363    fn mismatched_root_bases_and_no_runs_are_errors() {
1364        let (dir, _base_sha) = init_repo("true");
1365        let root = dir.path();
1366
1367        let mut out = Vec::new();
1368        let mut err = Vec::new();
1369        let code = combine_in(root, "missing-req", &mut out, &mut err);
1370        assert_ne!(code, 0);
1371        assert!(String::from_utf8_lossy(&err).contains("missing-req"));
1372
1373        create_run_branch(
1374            root,
1375            "T1",
1376            "req-diffbase",
1377            "main",
1378            100,
1379            &[("a.txt", "a\n", "add a")],
1380            Some("verified"),
1381        );
1382        std::fs::write(root.join("main_extra.txt"), "extra\n").unwrap();
1383        git(root, &["add", "main_extra.txt"]);
1384        git(root, &["commit", "--no-gpg-sign", "-m", "advance main"]);
1385        create_run_branch(
1386            root,
1387            "T2",
1388            "req-diffbase",
1389            "main",
1390            200,
1391            &[("b.txt", "b\n", "add b")],
1392            Some("verified"),
1393        );
1394
1395        out.clear();
1396        err.clear();
1397        let code = combine_in(root, "req-diffbase", &mut out, &mut err);
1398        assert_ne!(code, 0);
1399        let err_str = String::from_utf8(err).unwrap();
1400        assert!(
1401            err_str.contains("T1") && err_str.contains("T2"),
1402            "{err_str}"
1403        );
1404    }
1405
1406    #[test]
1407    fn dispatch_env_is_passed_to_gate() {
1408        let (dir, _base_sha) = init_repo("true");
1409        let root = dir.path();
1410        std::fs::write(
1411            root.join("blyte.toml"),
1412            "[dispatch]\ngate = \"test \\\"$MY_COMBINE_FLAG\\\" = \\\"enabled\\\"\"\n\n[dispatch.env]\nMY_COMBINE_FLAG = \"enabled\"\n",
1413        )
1414        .unwrap();
1415
1416        create_run_branch(
1417            root,
1418            "T1",
1419            "req-env",
1420            "main",
1421            100,
1422            &[("a.txt", "a\n", "add a")],
1423            Some("verified"),
1424        );
1425
1426        let mut out = Vec::new();
1427        let mut err = Vec::new();
1428        let code = combine_in(root, "req-env", &mut out, &mut err);
1429        assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1430    }
1431
1432    #[test]
1433    fn rebuilds_from_start_after_failure() {
1434        let (dir, _base_sha) = init_repo("test -f ready.txt");
1435        let root = dir.path();
1436        create_run_branch(
1437            root,
1438            "T1",
1439            "req-resume",
1440            "main",
1441            100,
1442            &[("a.txt", "a\n", "add a")],
1443            Some("verified"),
1444        );
1445
1446        let mut out = Vec::new();
1447        let mut err = Vec::new();
1448        assert_ne!(combine_in(root, "req-resume", &mut out, &mut err), 0);
1449        let first_record: CombineRecord = serde_json::from_str(
1450            &std::fs::read_to_string(root.join(".wt/combined/req-resume.json")).unwrap(),
1451        )
1452        .unwrap();
1453        assert_eq!(first_record.state, CombineState::CheckFailed);
1454
1455        std::fs::write(
1456            root.join("blyte.toml"),
1457            "[dispatch]\ngate = \"test -f a.txt\"\n",
1458        )
1459        .unwrap();
1460
1461        out.clear();
1462        err.clear();
1463        assert_eq!(combine_in(root, "req-resume", &mut out, &mut err), 0);
1464        let second_record: CombineRecord = serde_json::from_str(
1465            &std::fs::read_to_string(root.join(".wt/combined/req-resume.json")).unwrap(),
1466        )
1467        .unwrap();
1468        assert_eq!(second_record.state, CombineState::Combined);
1469    }
1470
1471    #[test]
1472    fn research_run_with_tag_is_ignored() {
1473        let (dir, base_sha) = init_repo("test -f a.txt");
1474        let root = dir.path();
1475        create_run_branch(
1476            root,
1477            "T1",
1478            "req-res-tag",
1479            "main",
1480            100,
1481            &[("a.txt", "a\n", "add a")],
1482            Some("verified"),
1483        );
1484        let research_start = serde_json::json!({
1485            "id": "R2",
1486            "request": "req-res-tag",
1487            "base": "main",
1488            "base_sha": base_sha,
1489            "started_at": 50,
1490            "tags": ["research"],
1491        });
1492        std::fs::write(
1493            root.join(".wt/R2.start.json"),
1494            serde_json::to_string_pretty(&research_start).unwrap(),
1495        )
1496        .unwrap();
1497
1498        let mut out = Vec::new();
1499        let mut err = Vec::new();
1500        let code = combine_in(root, "req-res-tag", &mut out, &mut err);
1501        assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1502        let record: CombineRecord = serde_json::from_str(
1503            &std::fs::read_to_string(root.join(".wt/combined/req-res-tag.json")).unwrap(),
1504        )
1505        .unwrap();
1506        assert_eq!(record.runs.len(), 1);
1507        assert_eq!(record.runs[0].id, "T1");
1508    }
1509
1510    #[test]
1511    fn unparseable_start_file_errors_with_file_name() {
1512        let (dir, _base_sha) = init_repo("true");
1513        let root = dir.path();
1514        create_run_branch(
1515            root,
1516            "T1",
1517            "req-bad-start",
1518            "main",
1519            100,
1520            &[("a.txt", "a\n", "add a")],
1521            Some("verified"),
1522        );
1523        std::fs::write(root.join(".wt/broken.start.json"), "{not valid json").unwrap();
1524
1525        let mut out = Vec::new();
1526        let mut err = Vec::new();
1527        let code = combine_in(root, "req-bad-start", &mut out, &mut err);
1528        assert_eq!(code, 2);
1529        let err_str = String::from_utf8(err).unwrap();
1530        assert!(err_str.contains("broken.start.json"), "{err_str}");
1531    }
1532
1533    #[test]
1534    fn start_file_with_mismatched_id_errors_naming_both() {
1535        let (dir, base_sha) = init_repo("true");
1536        let root = dir.path();
1537        create_run_branch(
1538            root,
1539            "T1",
1540            "req-id-mismatch",
1541            "main",
1542            100,
1543            &[("a.txt", "a\n", "add a")],
1544            Some("verified"),
1545        );
1546        let bad_start = serde_json::json!({
1547            "id": "T99",
1548            "request": "req-id-mismatch",
1549            "base": "main",
1550            "base_sha": base_sha,
1551            "started_at": 100,
1552            "research": false,
1553        });
1554        std::fs::write(
1555            root.join(".wt/T1.start.json"),
1556            serde_json::to_string_pretty(&bad_start).unwrap(),
1557        )
1558        .unwrap();
1559
1560        let mut out = Vec::new();
1561        let mut err = Vec::new();
1562        let code = combine_in(root, "req-id-mismatch", &mut out, &mut err);
1563        assert_eq!(code, 2);
1564        let err_str = String::from_utf8(err).unwrap();
1565        assert!(
1566            err_str.contains("T1") && err_str.contains("T99") && err_str.contains("T1.start.json"),
1567            "{err_str}"
1568        );
1569    }
1570
1571    #[test]
1572    fn start_file_without_started_at_errors_with_file_name() {
1573        let (dir, base_sha) = init_repo("true");
1574        let root = dir.path();
1575        create_run_branch(
1576            root,
1577            "T1",
1578            "req-no-ts",
1579            "main",
1580            100,
1581            &[("a.txt", "a\n", "add a")],
1582            Some("verified"),
1583        );
1584        let no_ts_start = serde_json::json!({
1585            "id": "T1",
1586            "request": "req-no-ts",
1587            "base": "main",
1588            "base_sha": base_sha,
1589            "research": false,
1590        });
1591        std::fs::write(
1592            root.join(".wt/T1.start.json"),
1593            serde_json::to_string_pretty(&no_ts_start).unwrap(),
1594        )
1595        .unwrap();
1596
1597        let mut out = Vec::new();
1598        let mut err = Vec::new();
1599        let code = combine_in(root, "req-no-ts", &mut out, &mut err);
1600        assert_eq!(code, 2);
1601        let err_str = String::from_utf8(err).unwrap();
1602        assert!(err_str.contains("T1.start.json"), "{err_str}");
1603    }
1604
1605    #[test]
1606    fn unparseable_summary_file_errors_with_file_name() {
1607        let (dir, _base_sha) = init_repo("true");
1608        let root = dir.path();
1609        create_run_branch(
1610            root,
1611            "T1",
1612            "req-bad-summary",
1613            "main",
1614            100,
1615            &[("a.txt", "a\n", "add a")],
1616            Some("verified"),
1617        );
1618        std::fs::write(root.join(".wt/T1.json"), "{broken summary").unwrap();
1619
1620        let mut out = Vec::new();
1621        let mut err = Vec::new();
1622        let code = combine_in(root, "req-bad-summary", &mut out, &mut err);
1623        assert_eq!(code, 2);
1624        let err_str = std::str::from_utf8(&err).unwrap();
1625        assert!(err_str.contains("T1.json"), "{err_str}");
1626        assert!(!err_str.contains("unfinished"), "{err_str}");
1627
1628        std::fs::write(root.join(".wt/T1.json"), r#"{"id":"T1","branch":"wip/T1"}"#).unwrap();
1629        out.clear();
1630        err.clear();
1631        let code = combine_in(root, "req-bad-summary", &mut out, &mut err);
1632        assert_eq!(code, 2);
1633        let err_str = std::str::from_utf8(&err).unwrap();
1634        assert!(err_str.contains("T1.json"), "{err_str}");
1635    }
1636
1637    #[test]
1638    fn unparseable_verdict_file_errors_with_file_name() {
1639        let (dir, _base_sha) = init_repo("true");
1640        let root = dir.path();
1641        create_run_branch(
1642            root,
1643            "T1",
1644            "req-bad-verdict",
1645            "main",
1646            100,
1647            &[("a.txt", "a\n", "add a")],
1648            Some("verified"),
1649        );
1650        std::fs::write(root.join(".wt/T1.verdict.json"), "not json").unwrap();
1651
1652        let mut out = Vec::new();
1653        let mut err = Vec::new();
1654        let code = combine_in(root, "req-bad-verdict", &mut out, &mut err);
1655        assert_eq!(code, 2);
1656        let err_str = std::str::from_utf8(&err).unwrap();
1657        assert!(err_str.contains("T1.verdict.json"), "{err_str}");
1658
1659        std::fs::write(root.join(".wt/T1.verdict.json"), r#"{"notes":"missing"}"#).unwrap();
1660        out.clear();
1661        err.clear();
1662        let code = combine_in(root, "req-bad-verdict", &mut out, &mut err);
1663        assert_eq!(code, 2);
1664        let err_str = std::str::from_utf8(&err).unwrap();
1665        assert!(err_str.contains("T1.verdict.json"), "{err_str}");
1666    }
1667
1668    #[test]
1669    fn root_run_with_base_but_no_base_sha_errors_naming_run() {
1670        let (dir, _base_sha) = init_repo("true");
1671        let root = dir.path();
1672        create_run_branch(
1673            root,
1674            "T1",
1675            "req-no-sha",
1676            "main",
1677            100,
1678            &[("a.txt", "a\n", "add a")],
1679            Some("verified"),
1680        );
1681        let start_without_sha = serde_json::json!({
1682            "id": "T1",
1683            "request": "req-no-sha",
1684            "base": "main",
1685            "started_at": 100,
1686            "research": false,
1687        });
1688        std::fs::write(
1689            root.join(".wt/T1.start.json"),
1690            serde_json::to_string_pretty(&start_without_sha).unwrap(),
1691        )
1692        .unwrap();
1693
1694        let mut out = Vec::new();
1695        let mut err = Vec::new();
1696        let code = combine_in(root, "req-no-sha", &mut out, &mut err);
1697        assert_eq!(code, 2);
1698        let err_str = String::from_utf8(err).unwrap();
1699        assert!(err_str.contains("T1"), "{err_str}");
1700    }
1701
1702    #[test]
1703    fn missing_run_branch_errors_even_when_worktree_head_exists() {
1704        let (dir, _base_sha) = init_repo("true");
1705        let root = dir.path();
1706        create_run_branch(
1707            root,
1708            "T1",
1709            "req-no-branch",
1710            "main",
1711            100,
1712            &[("a.txt", "a\n", "add a")],
1713            Some("verified"),
1714        );
1715        let t1_wt = root.join(".wt/T1");
1716        git(&t1_wt, &["checkout", "--detach", "HEAD"]);
1717        git(root, &["branch", "-D", "wip/T1"]);
1718        assert!(t1_wt.is_dir());
1719        assert!(!git(&t1_wt, &["rev-parse", "HEAD"]).is_empty());
1720
1721        let mut out = Vec::new();
1722        let mut err = Vec::new();
1723        let code = combine_in(root, "req-no-branch", &mut out, &mut err);
1724        assert_eq!(code, 2);
1725        let err_str = String::from_utf8(err).unwrap();
1726        assert!(
1727            err_str.contains("T1") && err_str.contains("wip/T1"),
1728            "{err_str}"
1729        );
1730    }
1731
1732    #[test]
1733    fn empty_cherry_pick_fails_with_exit_2_not_conflict() {
1734        let (dir, _base_sha) = init_repo("true");
1735        let root = dir.path();
1736        create_run_branch(
1737            root,
1738            "T1",
1739            "req-empty-pick",
1740            "main",
1741            100,
1742            &[("shared.txt", "identical change\n", "T1 identical")],
1743            Some("verified"),
1744        );
1745        let tip_t2 = create_run_branch(
1746            root,
1747            "T2",
1748            "req-empty-pick",
1749            "main",
1750            200,
1751            &[("shared.txt", "identical change\n", "T2 identical")],
1752            Some("verified"),
1753        );
1754
1755        let mut out = Vec::new();
1756        let mut err = Vec::new();
1757        let code = combine_in(root, "req-empty-pick", &mut out, &mut err);
1758        assert_eq!(code, 2, "stderr: {}", String::from_utf8_lossy(&err));
1759        let err_str = String::from_utf8(err).unwrap();
1760        assert!(
1761            err_str.contains("T2") && err_str.contains(&tip_t2),
1762            "{err_str}"
1763        );
1764        assert!(!root.join(".wt/combined/req-empty-pick.json").exists());
1765
1766        let combine_wt = root.join(".wt/combine-req-empty-pick");
1767        let status = git(&combine_wt, &["status", "--porcelain"]);
1768        assert!(status.is_empty(), "worktree should be clean: {status}");
1769    }
1770
1771    #[test]
1772    fn manually_modified_combined_branch_refuses_rebuild_and_preserves_commit() {
1773        let (dir, _base_sha) = init_repo("true");
1774        let root = dir.path();
1775        create_run_branch(
1776            root,
1777            "T1",
1778            "req-moved",
1779            "main",
1780            100,
1781            &[("a.txt", "v1\n", "v1")],
1782            Some("verified"),
1783        );
1784
1785        let mut out = Vec::new();
1786        let mut err = Vec::new();
1787        assert_eq!(combine_in(root, "req-moved", &mut out, &mut err), 0);
1788        let combined_sha = git(root, &["rev-parse", "blyte/req-moved"]);
1789
1790        let combine_wt = root.join(".wt/combine-req-moved");
1791        std::fs::write(combine_wt.join("manual.txt"), "hand-made\n").unwrap();
1792        git(&combine_wt, &["add", "manual.txt"]);
1793        git(
1794            &combine_wt,
1795            &["commit", "--no-gpg-sign", "-m", "hand-made commit"],
1796        );
1797        let hand_sha = git(root, &["rev-parse", "blyte/req-moved"]);
1798        assert_ne!(hand_sha, combined_sha);
1799
1800        let t1_wt = root.join(".wt/T1");
1801        std::fs::write(t1_wt.join("a.txt"), "v2\n").unwrap();
1802        git(&t1_wt, &["add", "a.txt"]);
1803        git(&t1_wt, &["commit", "--no-gpg-sign", "-m", "v2"]);
1804
1805        out.clear();
1806        err.clear();
1807        let code = combine_in(root, "req-moved", &mut out, &mut err);
1808        assert_eq!(code, 2, "stderr: {}", String::from_utf8_lossy(&err));
1809        let err_str = String::from_utf8(err).unwrap();
1810        assert!(
1811            err_str.contains("blyte/req-moved")
1812                && err_str.contains(&combined_sha)
1813                && err_str.contains(&hand_sha),
1814            "{err_str}"
1815        );
1816        assert_eq!(git(root, &["rev-parse", "blyte/req-moved"]), hand_sha);
1817        assert!(combine_wt.join("manual.txt").exists());
1818    }
1819
1820    #[test]
1821    fn redone_runs_are_left_out_regardless_of_outcome() {
1822        let (dir, _base_sha) =
1823            init_repo("test -f a.txt && test ! -f b.txt && test ! -f c.txt && test ! -f d.txt");
1824        let root = dir.path();
1825        let tip_t1 = create_run_branch(
1826            root,
1827            "T1",
1828            "req-redone-mix",
1829            "main",
1830            100,
1831            &[("a.txt", "a\n", "add a")],
1832            Some("verified"),
1833        );
1834        create_run_branch(
1835            root,
1836            "T2",
1837            "req-redone-mix",
1838            "main",
1839            200,
1840            &[("b.txt", "b\n", "add b")],
1841            Some("verified"),
1842        );
1843        create_run_branch(
1844            root,
1845            "T3",
1846            "req-redone-mix",
1847            "main",
1848            300,
1849            &[("c.txt", "c\n", "add c")],
1850            Some("gate_failed"),
1851        );
1852        create_run_branch(
1853            root,
1854            "T4",
1855            "req-redone-mix",
1856            "main",
1857            400,
1858            &[("d.txt", "d\n", "add d")],
1859            None,
1860        );
1861        for id in ["T2", "T3", "T4"] {
1862            std::fs::write(
1863                root.join(format!(".wt/{id}.verdict.json")),
1864                r#"{"verdict":"redone","notes":"replaced","ts":10}"#,
1865            )
1866            .unwrap();
1867        }
1868
1869        let mut out = Vec::new();
1870        let mut err = Vec::new();
1871        let code = combine_in(root, "req-redone-mix", &mut out, &mut err);
1872        assert_eq!(code, 0, "stderr: {}", String::from_utf8_lossy(&err));
1873
1874        let record: CombineRecord = serde_json::from_str(
1875            &std::fs::read_to_string(root.join(".wt/combined/req-redone-mix.json")).unwrap(),
1876        )
1877        .unwrap();
1878        assert_eq!(record.state, CombineState::Combined);
1879        assert_eq!(
1880            record.runs,
1881            vec![CombinedRun {
1882                id: "T1".to_string(),
1883                tip: tip_t1,
1884            }]
1885        );
1886        let combine_wt = root.join(".wt/combine-req-redone-mix");
1887        assert!(combine_wt.join("a.txt").exists());
1888        assert!(!combine_wt.join("b.txt").exists());
1889        assert!(!combine_wt.join("c.txt").exists());
1890        assert!(!combine_wt.join("d.txt").exists());
1891    }
1892
1893    #[test]
1894    fn run_based_on_left_out_run_errors_naming_both() {
1895        let (dir, _base_sha) = init_repo("true");
1896        let root = dir.path();
1897        create_run_branch(
1898            root,
1899            "T1",
1900            "req-dep-redone",
1901            "main",
1902            100,
1903            &[("a.txt", "a\n", "add a")],
1904            Some("verified"),
1905        );
1906        create_run_branch(
1907            root,
1908            "T2",
1909            "req-dep-redone",
1910            "wip/T1",
1911            200,
1912            &[("b.txt", "b\n", "add b")],
1913            Some("verified"),
1914        );
1915        std::fs::write(
1916            root.join(".wt/T1.verdict.json"),
1917            r#"{"verdict":"redone","notes":"replaced","ts":10}"#,
1918        )
1919        .unwrap();
1920
1921        let mut out = Vec::new();
1922        let mut err = Vec::new();
1923        let code = combine_in(root, "req-dep-redone", &mut out, &mut err);
1924        assert_eq!(code, 2);
1925        let err_str = String::from_utf8(err).unwrap();
1926        assert!(
1927            err_str.contains("T1") && err_str.contains("T2"),
1928            "{err_str}"
1929        );
1930        assert!(!root.join(".wt/combined/req-dep-redone.json").exists());
1931    }
1932
1933    #[test]
1934    fn every_run_redone_exits_2_saying_so() {
1935        let (dir, _base_sha) = init_repo("true");
1936        let root = dir.path();
1937        create_run_branch(
1938            root,
1939            "T1",
1940            "req-all-redone",
1941            "main",
1942            100,
1943            &[("a.txt", "a\n", "add a")],
1944            Some("verified"),
1945        );
1946        create_run_branch(
1947            root,
1948            "T2",
1949            "req-all-redone",
1950            "main",
1951            200,
1952            &[("b.txt", "b\n", "add b")],
1953            Some("gate_failed"),
1954        );
1955        for id in ["T1", "T2"] {
1956            std::fs::write(
1957                root.join(format!(".wt/{id}.verdict.json")),
1958                r#"{"verdict":"redone","notes":"replaced","ts":10}"#,
1959            )
1960            .unwrap();
1961        }
1962
1963        let mut out = Vec::new();
1964        let mut err = Vec::new();
1965        let code = combine_in(root, "req-all-redone", &mut out, &mut err);
1966        assert_eq!(code, 2);
1967        let err_str = String::from_utf8(err).unwrap();
1968        assert!(err_str.contains("every run was redone"), "{err_str}");
1969        assert!(!root.join(".wt/combined/req-all-redone.json").exists());
1970    }
1971
1972    #[test]
1973    fn recording_redone_on_combined_run_rebuilds_without_it() {
1974        let (dir, _base_sha) = init_repo("true");
1975        let root = dir.path();
1976        let tip_t1 = create_run_branch(
1977            root,
1978            "T1",
1979            "req-recombine",
1980            "main",
1981            100,
1982            &[("a.txt", "a\n", "add a")],
1983            Some("verified"),
1984        );
1985        create_run_branch(
1986            root,
1987            "T2",
1988            "req-recombine",
1989            "main",
1990            200,
1991            &[("b.txt", "b\n", "add b")],
1992            Some("verified"),
1993        );
1994
1995        let mut out = Vec::new();
1996        let mut err = Vec::new();
1997        assert_eq!(combine_in(root, "req-recombine", &mut out, &mut err), 0);
1998        let first_head = git(root, &["rev-parse", "blyte/req-recombine"]);
1999        let combine_wt = root.join(".wt/combine-req-recombine");
2000        assert!(combine_wt.join("a.txt").exists());
2001        assert!(combine_wt.join("b.txt").exists());
2002
2003        std::fs::write(
2004            root.join(".wt/T2.verdict.json"),
2005            r#"{"verdict":"redone","notes":"replaced","ts":10}"#,
2006        )
2007        .unwrap();
2008
2009        out.clear();
2010        err.clear();
2011        assert_eq!(combine_in(root, "req-recombine", &mut out, &mut err), 0);
2012        let second_head = git(root, &["rev-parse", "blyte/req-recombine"]);
2013        assert_ne!(second_head, first_head);
2014        let record: CombineRecord = serde_json::from_str(
2015            &std::fs::read_to_string(root.join(".wt/combined/req-recombine.json")).unwrap(),
2016        )
2017        .unwrap();
2018        assert_eq!(
2019            record.runs,
2020            vec![CombinedRun {
2021                id: "T1".to_string(),
2022                tip: tip_t1,
2023            }]
2024        );
2025        assert!(combine_wt.join("a.txt").exists());
2026        assert!(!combine_wt.join("b.txt").exists());
2027    }
2028}