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