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