Skip to main content

blyte_cli/
requests.rs

1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard};
7
8use serde::{Deserialize, Serialize};
9
10use crate::cli::ReviewVerdict;
11use crate::combine::{CombineCheck, CombineRecord, CombineState, CombinedRun};
12use crate::serve::Surface;
13
14static TMP_COUNTER: AtomicU64 = AtomicU64::new(1);
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum Readiness {
18    Ready,
19    Waiting { reasons: Vec<String> },
20}
21
22pub trait Publisher: Send + Sync {
23    fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String>;
24    fn open_pull_request(
25        &self,
26        root: &Path,
27        branch: &str,
28        title: &str,
29        body: &str,
30    ) -> Result<String, String>;
31}
32
33pub struct RealPublisher;
34
35impl Publisher for RealPublisher {
36    fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String> {
37        crate::publish::push_branch(root, branch)
38    }
39
40    fn open_pull_request(
41        &self,
42        root: &Path,
43        branch: &str,
44        title: &str,
45        body: &str,
46    ) -> Result<String, String> {
47        crate::publish::open_pull_request(root, branch, title, body)
48    }
49}
50
51#[derive(Default)]
52struct RequestsInner {
53    running: HashSet<String>,
54}
55
56pub struct RequestsState {
57    inner: Mutex<RequestsInner>,
58    cv: Condvar,
59}
60
61impl Default for RequestsState {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl RequestsState {
68    pub fn new() -> Self {
69        Self {
70            inner: Mutex::new(RequestsInner::default()),
71            cv: Condvar::new(),
72        }
73    }
74
75    fn lock_inner(&self) -> MutexGuard<'_, RequestsInner> {
76        self.inner.lock().unwrap_or_else(|e| e.into_inner())
77    }
78
79    pub fn is_combining(&self, request: &str) -> bool {
80        self.lock_inner().running.contains(request)
81    }
82
83    pub fn wait_for_idle(&self, request: &str) {
84        let mut inner = self.lock_inner();
85        while inner.running.contains(request) {
86            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
87        }
88    }
89
90    pub fn wait_all_idle(&self) {
91        let mut inner = self.lock_inner();
92        while !inner.running.is_empty() {
93            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
94        }
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
99pub struct CommitSummary {
100    pub sha: String,
101    pub subject: String,
102}
103
104#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct PublishedRecord {
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub pushed_commit: Option<String>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub pull_request_url: Option<String>,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum AttemptResult {
116    Combined,
117    Conflict,
118    CheckFailed,
119    Error,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(deny_unknown_fields)]
124pub struct AttemptRecord {
125    pub runs: Vec<CombinedRun>,
126    pub result: AttemptResult,
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub error: Option<String>,
129    pub reported: bool,
130}
131
132#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
133pub struct RequestStatus {
134    pub request: String,
135    pub runs: Vec<String>,
136    pub left_out: Vec<String>,
137    pub state: String,
138    pub waiting_reasons: Vec<String>,
139    pub branch: Option<String>,
140    pub base: Option<String>,
141    pub commits: Vec<CommitSummary>,
142    #[serde(skip_serializing_if = "Option::is_none")]
143    pub check: Option<CombineCheck>,
144    pub conflicting_run: Option<String>,
145    pub conflicting_files: Vec<String>,
146    pub failing_step: Option<String>,
147    pub output_tail: Option<String>,
148    pub error: Option<String>,
149    pub suggested_title: Option<String>,
150    pub suggested_body: Option<String>,
151    pub pushed: bool,
152    pub pull_request_url: Option<String>,
153}
154
155#[derive(Clone, Debug, PartialEq, Eq)]
156pub enum RequestActionError {
157    BadRequest(String),
158    NotOwned(String),
159    Conflict(String),
160    Internal(String),
161}
162
163struct StartRunInfo {
164    id: String,
165    request: Option<String>,
166    surface: Option<String>,
167    base: Option<String>,
168    started_at: u64,
169    is_research: bool,
170}
171
172fn is_research_start(wt_dir: &Path, id: &str, val: &serde_json::Value) -> bool {
173    val.get("research")
174        .and_then(|v| v.as_bool())
175        .unwrap_or(false)
176        || val
177            .get("tags")
178            .and_then(|v| v.as_array())
179            .is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")))
180        || wt_dir.join(format!("{id}.report.md")).exists()
181}
182
183fn parse_start_file(wt_dir: &Path, path: &Path) -> Result<StartRunInfo, String> {
184    let content = std::fs::read_to_string(path)
185        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
186    let val: serde_json::Value = serde_json::from_str(&content)
187        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
188    let file_id = path
189        .file_name()
190        .and_then(|n| n.to_str())
191        .and_then(|n| n.strip_suffix(".start.json"))
192        .filter(|s| !s.is_empty())
193        .ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
194    if let Some(id_val) = val.get("id") {
195        let field_id = id_val.as_str().ok_or_else(|| {
196            format!(
197                "start file {} has non-string id {id_val}, expected {file_id}",
198                path.display()
199            )
200        })?;
201        if field_id != file_id {
202            return Err(format!(
203                "start file {} has id {field_id} which differs from file name id {file_id}",
204                path.display()
205            ));
206        }
207    }
208    let request = match val.get("request") {
209        None | Some(serde_json::Value::Null) => None,
210        Some(serde_json::Value::String(s)) => Some(s.clone()),
211        Some(_) => {
212            return Err(format!(
213                "start file {} has non-string request field",
214                path.display()
215            ));
216        }
217    };
218    let surface = match val.get("surface") {
219        None | Some(serde_json::Value::Null) => None,
220        Some(serde_json::Value::String(s)) => Some(s.clone()),
221        Some(_) => {
222            return Err(format!(
223                "start file {} has non-string surface field",
224                path.display()
225            ));
226        }
227    };
228    let base = match val.get("base") {
229        None | Some(serde_json::Value::Null) => None,
230        Some(serde_json::Value::String(s)) => Some(s.clone()),
231        Some(_) => {
232            return Err(format!(
233                "start file {} has non-string base field",
234                path.display()
235            ));
236        }
237    };
238    let is_research = is_research_start(wt_dir, file_id, &val);
239    let started_at = match val.get("started_at") {
240        Some(v) => v
241            .as_u64()
242            .ok_or_else(|| format!("start file {} has non-numeric started_at", path.display()))?,
243        None => 0,
244    };
245    Ok(StartRunInfo {
246        id: file_id.to_string(),
247        request,
248        surface,
249        base,
250        started_at,
251        is_research,
252    })
253}
254
255fn list_start_files(wt_dir: &Path) -> Result<Vec<PathBuf>, String> {
256    let read_dir = match std::fs::read_dir(wt_dir) {
257        Ok(rd) => rd,
258        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
259        Err(e) => return Err(format!("failed to read {}: {e}", wt_dir.display())),
260    };
261    let mut entries = Vec::new();
262    for entry in read_dir {
263        let entry =
264            entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
265        let path = entry.path();
266        if path
267            .file_name()
268            .and_then(|n| n.to_str())
269            .is_some_and(|n| n.ends_with(".start.json"))
270        {
271            entries.push(path);
272        }
273    }
274    entries.sort();
275    Ok(entries)
276}
277
278enum RequestOwnership {
279    Owned,
280    OtherSurface,
281    Unowned,
282    NotFound,
283}
284
285enum RequestOwnershipError {
286    Mixed(String),
287    IoOrParse(String),
288}
289
290fn check_request_ownership(
291    surface: &Surface,
292    request: &str,
293) -> Result<RequestOwnership, RequestOwnershipError> {
294    let wt_dir = surface.root.join(".wt");
295    let entries = list_start_files(&wt_dir).map_err(RequestOwnershipError::IoOrParse)?;
296    let mut owners: HashSet<Option<String>> = HashSet::new();
297    for path in entries {
298        let info = parse_start_file(&wt_dir, &path).map_err(RequestOwnershipError::IoOrParse)?;
299        if info.request.as_deref() == Some(request) {
300            owners.insert(info.surface);
301        }
302    }
303    if owners.is_empty() {
304        return Ok(RequestOwnership::NotFound);
305    }
306    if owners.len() > 1 {
307        return Err(RequestOwnershipError::Mixed(format!(
308            "request {request} has runs from more than one surface"
309        )));
310    }
311    match owners.into_iter().next().flatten() {
312        Some(owner) if owner == surface.surface_id => Ok(RequestOwnership::Owned),
313        Some(_) => Ok(RequestOwnership::OtherSurface),
314        None => Ok(RequestOwnership::Unowned),
315    }
316}
317
318pub fn owned_run_ids(surface: &Surface) -> Result<HashSet<String>, String> {
319    let wt_dir = surface.root.join(".wt");
320    let entries = list_start_files(&wt_dir)?;
321    let mut ids = HashSet::new();
322    for path in entries {
323        let info = parse_start_file(&wt_dir, &path)?;
324        if info.surface.as_deref() == Some(surface.surface_id.as_str()) {
325            ids.insert(info.id);
326        }
327    }
328    Ok(ids)
329}
330
331pub fn request_owner_check(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
332    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
333    match check_request_ownership(surface, request) {
334        Ok(RequestOwnership::Owned) => Ok(()),
335        Ok(RequestOwnership::OtherSurface) => Err(RequestActionError::NotOwned(format!(
336            "request {request} belongs to another surface"
337        ))),
338        Ok(RequestOwnership::Unowned) => Err(RequestActionError::NotOwned(format!(
339            "request {request} was not started by a surface"
340        ))),
341        Ok(RequestOwnership::NotFound) => Err(RequestActionError::Conflict(format!(
342            "request {request} has not been combined"
343        ))),
344        Err(RequestOwnershipError::Mixed(msg)) => Err(RequestActionError::BadRequest(msg)),
345        Err(RequestOwnershipError::IoOrParse(msg)) => Err(RequestActionError::Internal(msg)),
346    }
347}
348
349pub(crate) fn run_owner_check(surface: &Surface, run_id: &str) -> Result<(), RequestActionError> {
350    let wt_dir = surface.root.join(".wt");
351    let path = wt_dir.join(format!("{run_id}.start.json"));
352    if !path.exists() {
353        return Err(RequestActionError::NotOwned(format!(
354            "run {run_id} was not started by a surface"
355        )));
356    }
357    let info = parse_start_file(&wt_dir, &path).map_err(RequestActionError::Internal)?;
358    match info.surface.as_deref() {
359        Some(owner) if owner == surface.surface_id => Ok(()),
360        Some(_) => Err(RequestActionError::NotOwned(format!(
361            "run {run_id} belongs to another surface"
362        ))),
363        None => Err(RequestActionError::NotOwned(format!(
364            "run {run_id} was not started by a surface"
365        ))),
366    }
367}
368
369pub fn run_request_id(root: &Path, run_id: &str) -> Result<Option<String>, String> {
370    let wt_dir = root.join(".wt");
371    let path = wt_dir.join(format!("{run_id}.start.json"));
372    if !path.exists() {
373        return Ok(None);
374    }
375    let info = parse_start_file(&wt_dir, &path)?;
376    if info.is_research {
377        return Ok(None);
378    }
379    Ok(info.request)
380}
381
382pub fn request_readiness(root: &Path, request: &str) -> Result<Readiness, String> {
383    crate::dispatch::validate_request_id(request)?;
384    let wt_dir = root.join(".wt");
385    let entries = list_start_files(&wt_dir)?;
386    let mut matched_runs = Vec::new();
387    for path in entries {
388        let info = parse_start_file(&wt_dir, &path)?;
389        if info.is_research {
390            continue;
391        }
392        if info.request.as_deref() == Some(request) {
393            matched_runs.push(info);
394        }
395    }
396    if matched_runs.is_empty() {
397        return Ok(Readiness::Waiting {
398            reasons: vec!["no runs for request".to_string()],
399        });
400    }
401    matched_runs.sort_by(|a, b| {
402        a.started_at
403            .cmp(&b.started_at)
404            .then_with(|| a.id.cmp(&b.id))
405    });
406
407    let mut active_runs = Vec::new();
408    let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
409    for run in matched_runs {
410        let verdict = crate::queue_actions::read_verdict(root, &run.id)?;
411        if crate::combine::is_left_out_verdict(verdict) {
412            left_out_ids.insert(run.id);
413        } else {
414            active_runs.push((run, verdict));
415        }
416    }
417
418    if active_runs.is_empty() {
419        return Ok(Readiness::Waiting {
420            reasons: vec!["every run was redone".to_string()],
421        });
422    }
423
424    let left_out_refs: BTreeSet<&str> = left_out_ids.iter().map(String::as_str).collect();
425    for (run, _) in &active_runs {
426        crate::combine::check_not_based_on_left_out(
427            root,
428            &run.id,
429            run.base.as_deref(),
430            &left_out_refs,
431        )?;
432    }
433
434    let mut reasons = Vec::new();
435    for (run, verdict) in active_runs {
436        let id = &run.id;
437        let summary_path = wt_dir.join(format!("{id}.json"));
438        let outcome = match std::fs::read_to_string(&summary_path) {
439            Ok(raw) => {
440                let val: serde_json::Value = serde_json::from_str(&raw)
441                    .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
442                let outcome = val
443                    .get("outcome")
444                    .and_then(|v| v.as_str())
445                    .ok_or_else(|| {
446                        format!(
447                            "summary file {} is missing string outcome",
448                            summary_path.display()
449                        )
450                    })?
451                    .to_string();
452                if outcome != "verified" {
453                    reasons.push(format!("{id}: {outcome}"));
454                }
455                Some(outcome)
456            }
457            Err(e) if e.kind() == ErrorKind::NotFound => {
458                reasons.push(format!("{id}: unfinished"));
459                None
460            }
461            Err(e) => {
462                return Err(format!("failed to read {}: {e}", summary_path.display()));
463            }
464        };
465
466        let checks_path = wt_dir.join(format!("{id}.checks.json"));
467        let (checks_recorded, flags) = crate::replay::read_checks(&checks_path)
468            .map_err(|e| format!("{}: {e}", checks_path.display()))?;
469
470        if crate::queue_actions::read_hold(root, id)?.is_some() {
471            reasons.push(format!("{id}: on hold"));
472        }
473
474        if let Some(ref outcome_str) = outcome {
475            if outcome_str == "verified" {
476                if !checks_recorded {
477                    reasons.push(format!("{id}: no checks file"));
478                } else {
479                    let card =
480                        crate::replay::card_for_run(false, outcome_str, checks_recorded, &flags);
481                    let cleared_by_verdict = matches!(
482                        verdict,
483                        Some(ReviewVerdict::Accepted | ReviewVerdict::Fixed)
484                    );
485                    if card != "clean" && !cleared_by_verdict {
486                        reasons.push(format!("{id}: flagged ({})", flags.join("; ")));
487                    }
488                }
489            }
490        }
491    }
492
493    if reasons.is_empty() {
494        Ok(Readiness::Ready)
495    } else {
496        Ok(Readiness::Waiting { reasons })
497    }
498}
499
500fn combine_record_path(root: &Path, request: &str) -> PathBuf {
501    root.join(".wt")
502        .join("combined")
503        .join(format!("{request}.json"))
504}
505
506fn attempt_record_path(root: &Path, request: &str) -> PathBuf {
507    root.join(".wt")
508        .join("combined")
509        .join(format!("{request}.attempt.json"))
510}
511
512fn published_record_path(root: &Path, request: &str) -> PathBuf {
513    root.join(".wt")
514        .join("combined")
515        .join(format!("{request}.published.json"))
516}
517
518fn write_json_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<(), String> {
519    if let Some(parent) = path.parent() {
520        std::fs::create_dir_all(parent)
521            .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
522    }
523    let mut json = serde_json::to_string_pretty(value)
524        .map_err(|e| format!("failed to serialize {label}: {e}"))?;
525    json.push('\n');
526    let mut tmp_name = path.as_os_str().to_os_string();
527    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
528    tmp_name.push(format!(".tmp.{}.{seq}", std::process::id()));
529    let tmp_path = PathBuf::from(tmp_name);
530    std::fs::write(&tmp_path, json)
531        .map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
532    std::fs::rename(&tmp_path, path).map_err(|e| {
533        let _ = std::fs::remove_file(&tmp_path);
534        format!(
535            "failed to rename {} to {}: {e}",
536            tmp_path.display(),
537            path.display()
538        )
539    })
540}
541
542pub fn load_combine_record(root: &Path, request: &str) -> Result<Option<CombineRecord>, String> {
543    let path = combine_record_path(root, request);
544    let raw = match std::fs::read_to_string(&path) {
545        Ok(s) => s,
546        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
547        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
548    };
549    let record: CombineRecord = serde_json::from_str(&raw)
550        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
551    Ok(Some(record))
552}
553
554pub fn load_attempt_record(root: &Path, request: &str) -> Result<Option<AttemptRecord>, String> {
555    let path = attempt_record_path(root, request);
556    let raw = match std::fs::read_to_string(&path) {
557        Ok(s) => s,
558        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
559        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
560    };
561    let record: AttemptRecord = serde_json::from_str(&raw)
562        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
563    if record.result == AttemptResult::Error
564        && record.error.as_deref().is_none_or(|s| s.trim().is_empty())
565    {
566        return Err(format!(
567            "invalid attempt file {}: result error is missing error text",
568            path.display()
569        ));
570    }
571    Ok(Some(record))
572}
573
574pub fn write_attempt_record(
575    root: &Path,
576    request: &str,
577    record: &AttemptRecord,
578) -> Result<(), String> {
579    let path = attempt_record_path(root, request);
580    write_json_atomic(&path, record, "attempt record")
581}
582
583pub fn load_published_record(root: &Path, request: &str) -> Result<PublishedRecord, String> {
584    let path = published_record_path(root, request);
585    let raw = match std::fs::read_to_string(&path) {
586        Ok(s) => s,
587        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(PublishedRecord::default()),
588        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
589    };
590    serde_json::from_str(&raw).map_err(|e| format!("failed to parse {}: {e}", path.display()))
591}
592
593pub fn write_published_record(
594    root: &Path,
595    request: &str,
596    record: &PublishedRecord,
597) -> Result<(), String> {
598    let path = published_record_path(root, request);
599    write_json_atomic(&path, record, "published record")
600}
601
602fn git_stdout(root: &Path, args: &[&str]) -> Result<String, String> {
603    let out = Command::new("git")
604        .args(args)
605        .current_dir(root)
606        .output()
607        .map_err(|e| format!("failed to run git {}: {e}", args.join(" ")))?;
608    if !out.status.success() {
609        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
610        return Err(format!("git {} failed: {stderr}", args.join(" ")));
611    }
612    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
613}
614
615fn git_rev_parse(root: &Path, rev: &str) -> Result<String, String> {
616    git_stdout(root, &["rev-parse", "--verify", rev])
617}
618
619fn git_commit_subject(root: &Path, sha: &str) -> Result<String, String> {
620    git_stdout(root, &["show", "-s", "--format=%s", sha])
621        .map_err(|e| format!("failed to read subject for commit {sha}: {e}"))
622}
623
624fn run_branch(wt_dir: &Path, run_id: &str) -> Result<String, String> {
625    let summary_path = wt_dir.join(format!("{run_id}.json"));
626    let raw = std::fs::read_to_string(&summary_path)
627        .map_err(|e| format!("failed to read {}: {e}", summary_path.display()))?;
628    let val: serde_json::Value = serde_json::from_str(&raw)
629        .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
630    let branch_hint = match val.get("branch") {
631        None | Some(serde_json::Value::Null) => None,
632        Some(serde_json::Value::String(s)) => Some(s.clone()),
633        Some(_) => {
634            return Err(format!(
635                "summary file {} has non-string branch",
636                summary_path.display()
637            ));
638        }
639    };
640    Ok(branch_hint.unwrap_or_else(|| format!("wip/{run_id}")))
641}
642
643fn git_branch_exists(root: &Path, run_id: &str, branch: &str) -> Result<bool, String> {
644    let ref_name = format!("refs/heads/{branch}");
645    let out = Command::new("git")
646        .args(["show-ref", "--verify", "--quiet", &ref_name])
647        .current_dir(root)
648        .output()
649        .map_err(|e| {
650            format!("run {run_id}: failed to check branch {branch} with git show-ref: {e}")
651        })?;
652    match out.status.code() {
653        Some(0) => Ok(true),
654        Some(1) => Ok(false),
655        code => {
656            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
657            let status_desc = match code {
658                Some(c) => format!("exit code {c}"),
659                None => "terminated by signal".to_string(),
660            };
661            if stderr.is_empty() {
662                Err(format!(
663                    "run {run_id}: git show-ref failed for branch {branch} ({status_desc})"
664                ))
665            } else {
666                Err(format!(
667                    "run {run_id}: git show-ref failed for branch {branch} ({status_desc}): {stderr}"
668                ))
669            }
670        }
671    }
672}
673
674fn resolve_current_run_tips(root: &Path, request: &str) -> Result<Vec<CombinedRun>, String> {
675    let wt_dir = root.join(".wt");
676    let entries = list_start_files(&wt_dir)?;
677    let mut tips = BTreeMap::new();
678    for path in entries {
679        let info = parse_start_file(&wt_dir, &path)?;
680        if info.is_research || info.request.as_deref() != Some(request) {
681            continue;
682        }
683        if crate::combine::is_run_left_out(root, &info.id)? {
684            continue;
685        }
686        let branch = run_branch(&wt_dir, &info.id)?;
687        let rev = format!("refs/heads/{branch}^{{commit}}");
688        let sha = git_rev_parse(root, &rev).map_err(|e| {
689            format!(
690                "run {}: branch {branch} does not resolve to a commit: {e}",
691                info.id
692            )
693        })?;
694        tips.insert(info.id, sha);
695    }
696    Ok(tips
697        .into_iter()
698        .map(|(id, tip)| CombinedRun { id, tip })
699        .collect())
700}
701
702fn sorted_runs(mut runs: Vec<CombinedRun>) -> Vec<CombinedRun> {
703    runs.sort_by(|a, b| a.id.cmp(&b.id));
704    runs
705}
706
707fn record_runs_match_tips(record: &CombineRecord, current_runs: &[CombinedRun]) -> bool {
708    if record.runs.len() != current_runs.len() {
709        return false;
710    }
711    sorted_runs(record.runs.clone()) == current_runs
712}
713
714enum CombinedRunBranchState {
715    Gone,
716    AtRecordedTip,
717    Changed,
718}
719
720fn check_recorded_run_branch(
721    root: &Path,
722    wt_dir: &Path,
723    run: &CombinedRun,
724) -> Result<CombinedRunBranchState, String> {
725    let branch = run_branch(wt_dir, &run.id)?;
726    if !git_branch_exists(root, &run.id, &branch)? {
727        return Ok(CombinedRunBranchState::Gone);
728    }
729    let rev = format!("refs/heads/{branch}^{{commit}}");
730    let sha = git_rev_parse(root, &rev).map_err(|e| {
731        format!(
732            "run {}: branch {branch} does not resolve to a commit: {e}",
733            run.id
734        )
735    })?;
736    if sha == run.tip {
737        Ok(CombinedRunBranchState::AtRecordedTip)
738    } else {
739        Ok(CombinedRunBranchState::Changed)
740    }
741}
742
743fn active_request_run_ids(root: &Path, request: &str) -> Result<Vec<String>, String> {
744    let wt_dir = root.join(".wt");
745    let entries = list_start_files(&wt_dir)?;
746    let mut run_ids = Vec::new();
747    for path in entries {
748        let info = parse_start_file(&wt_dir, &path)?;
749        if info.is_research || info.request.as_deref() != Some(request) {
750            continue;
751        }
752        if crate::combine::is_run_left_out(root, &info.id)? {
753            continue;
754        }
755        run_ids.push(info.id);
756    }
757    Ok(run_ids)
758}
759
760fn request_is_done(root: &Path, request: &str, rec: &CombineRecord) -> Result<bool, String> {
761    if rec.state != CombineState::Combined {
762        return Ok(false);
763    }
764    let active_runs = active_request_run_ids(root, request)?;
765    if active_runs.is_empty() {
766        return Ok(false);
767    }
768    let recorded_by_id: HashMap<&str, &CombinedRun> =
769        rec.runs.iter().map(|run| (run.id.as_str(), run)).collect();
770    let wt_dir = root.join(".wt");
771    let mut any_branch_gone = false;
772    for run_id in &active_runs {
773        let Some(&recorded_run) = recorded_by_id.get(run_id.as_str()) else {
774            return Ok(false);
775        };
776        match check_recorded_run_branch(root, &wt_dir, recorded_run)? {
777            CombinedRunBranchState::Gone => any_branch_gone = true,
778            CombinedRunBranchState::AtRecordedTip => {}
779            CombinedRunBranchState::Changed => return Ok(false),
780        }
781    }
782    Ok(any_branch_gone)
783}
784
785fn check_record_combined_for_request(
786    root: &Path,
787    request: &str,
788    run_ids: &[&str],
789) -> Result<BTreeSet<String>, String> {
790    let Some(rec) = load_combine_record(root, request)? else {
791        return Ok(BTreeSet::new());
792    };
793    if rec.state != CombineState::Combined {
794        return Ok(BTreeSet::new());
795    }
796    let wt_dir = root.join(".wt");
797    let mut combined = BTreeSet::new();
798    for run in &rec.runs {
799        if !run_ids.contains(&run.id.as_str()) {
800            continue;
801        }
802        match check_recorded_run_branch(root, &wt_dir, run)? {
803            CombinedRunBranchState::Gone | CombinedRunBranchState::AtRecordedTip => {
804                combined.insert(run.id.clone());
805            }
806            CombinedRunBranchState::Changed => {}
807        }
808    }
809    Ok(combined)
810}
811
812pub fn run_is_combined(root: &Path, run_id: &str, request: Option<&str>) -> Result<bool, String> {
813    let Some(request) = request else {
814        return Ok(false);
815    };
816    Ok(check_record_combined_for_request(root, request, &[run_id])?.contains(run_id))
817}
818
819pub fn combined_run_ids(
820    root: &Path,
821    runs: &[(&str, Option<&str>)],
822) -> Result<BTreeSet<String>, String> {
823    let mut by_request: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
824    for &(run_id, request) in runs {
825        if let Some(req) = request {
826            by_request.entry(req).or_default().push(run_id);
827        }
828    }
829    let mut combined = BTreeSet::new();
830    for (request, run_ids) in by_request {
831        combined.extend(check_record_combined_for_request(root, request, &run_ids)?);
832    }
833    Ok(combined)
834}
835
836fn combine_record_tip(record: &CombineRecord) -> &str {
837    record.commits.last().unwrap_or(&record.base).as_str()
838}
839
840fn is_record_pushed(published: &PublishedRecord, record: &CombineRecord) -> bool {
841    published.pushed_commit.as_deref() == Some(combine_record_tip(record))
842}
843
844fn branch_matches_record(root: &Path, record: &CombineRecord) -> bool {
845    let expected = combine_record_tip(record);
846    let rev = format!("refs/heads/{}^{{commit}}", record.branch);
847    git_rev_parse(root, &rev).is_ok_and(|actual| actual == expected)
848}
849
850fn format_record_failure(record: &CombineRecord, record_path: &Path) -> Result<String, String> {
851    match record.state {
852        CombineState::Conflict => {
853            let run = record
854                .conflicting_run
855                .as_deref()
856                .filter(|r| !r.is_empty())
857                .ok_or_else(|| {
858                    format!(
859                        "combine record {} has state conflict with missing conflicting_run",
860                        record_path.display()
861                    )
862                })?;
863            if record.conflicting_files.is_empty() {
864                return Err(format!(
865                    "combine record {} has state conflict with empty conflicting_files",
866                    record_path.display()
867                ));
868            }
869            let files = record.conflicting_files.join(", ");
870            Ok(format!(
871                "Combine failed for request {} (state: conflict).\nConflicting run: {run}\nConflicting files: {files}",
872                record.request
873            ))
874        }
875        CombineState::CheckFailed => {
876            let step = record
877                .failing_step
878                .as_deref()
879                .filter(|s| !s.is_empty())
880                .ok_or_else(|| {
881                    format!(
882                        "combine record {} has state check_failed with missing failing_step",
883                        record_path.display()
884                    )
885                })?;
886            let tail = record
887                .output_tail
888                .as_deref()
889                .filter(|t| !t.is_empty())
890                .ok_or_else(|| {
891                    format!(
892                        "combine record {} has state check_failed with missing or empty output_tail",
893                        record_path.display()
894                    )
895                })?;
896            Ok(format!(
897                "Combine failed for request {} (state: check_failed).\nFailing step: {step}\nOutput tail:\n{tail}",
898                record.request
899            ))
900        }
901        CombineState::Combined => Err(format!(
902            "combine record {} has state combined: not a failure record",
903            record_path.display()
904        )),
905    }
906}
907
908fn format_error_failure(request: &str, err_text: &str) -> String {
909    format!("Combine failed for request {request} (state: error).\nError: {err_text}")
910}
911
912struct RunningGuard {
913    state: Arc<RequestsState>,
914    request: String,
915}
916
917impl Drop for RunningGuard {
918    fn drop(&mut self) {
919        let mut inner = self.state.lock_inner();
920        inner.running.remove(&self.request);
921        self.state.cv.notify_all();
922    }
923}
924
925fn retry_failure_message(
926    root: &Path,
927    request: &str,
928    attempt: &AttemptRecord,
929) -> Result<String, String> {
930    let path = attempt_record_path(root, request);
931    match attempt.result {
932        AttemptResult::Conflict | AttemptResult::CheckFailed => {
933            let expected_state = match attempt.result {
934                AttemptResult::Conflict => CombineState::Conflict,
935                AttemptResult::CheckFailed => CombineState::CheckFailed,
936                AttemptResult::Combined | AttemptResult::Error => unreachable!(),
937            };
938            match load_combine_record(root, request)? {
939                Some(rec) if rec.state == expected_state => {
940                    format_record_failure(&rec, &combine_record_path(root, request))
941                }
942                _ => Err(format!(
943                    "attempt file {} has result {:?} without a matching combine record",
944                    path.display(),
945                    attempt.result
946                )),
947            }
948        }
949        AttemptResult::Error => {
950            let err_text = attempt.error.as_deref().ok_or_else(|| {
951                format!(
952                    "attempt file {} has result error without error text",
953                    path.display()
954                )
955            })?;
956            Ok(format_error_failure(request, err_text))
957        }
958        AttemptResult::Combined => Err(format!(
959            "cannot format failure message for combined attempt {}",
960            path.display()
961        )),
962    }
963}
964
965fn record_and_report_failure(
966    root: &Path,
967    session: &crate::session::Session,
968    request: &str,
969    runs: Vec<CombinedRun>,
970    result: AttemptResult,
971    error: Option<String>,
972    msg: &str,
973) {
974    let mut attempt = AttemptRecord {
975        runs,
976        result,
977        error,
978        reported: false,
979    };
980    if let Err(e) = write_attempt_record(root, request, &attempt) {
981        session.record_error(&format!(
982            "failed to write attempt record for {request}: {e}"
983        ));
984    }
985    match session.queue_for_request(request, msg) {
986        Ok(_) => {
987            attempt.reported = true;
988            if let Err(e) = write_attempt_record(root, request, &attempt) {
989                session.record_error(&format!(
990                    "failed to write attempt record for {request}: {e}"
991                ));
992            }
993        }
994        Err(e) => {
995            session.record_error(&format!(
996                "failed to queue combine failure for {request}: {e}"
997            ));
998        }
999    }
1000}
1001
1002fn conversation_busy(surface: &Surface) -> bool {
1003    let info = surface.session.info();
1004    info.busy || info.queued > 0
1005}
1006
1007fn ready_waiting_reason(conversation_busy: bool) -> String {
1008    if conversation_busy {
1009        "the conversation model is still working".to_string()
1010    } else {
1011        "waiting to combine".to_string()
1012    }
1013}
1014
1015pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
1016    crate::dispatch::validate_request_id(request)?;
1017    match check_request_ownership(surface, request) {
1018        Ok(RequestOwnership::Owned) => {}
1019        Ok(
1020            RequestOwnership::OtherSurface | RequestOwnership::Unowned | RequestOwnership::NotFound,
1021        ) => return Ok(false),
1022        Err(RequestOwnershipError::Mixed(msg) | RequestOwnershipError::IoOrParse(msg)) => {
1023            return Err(msg);
1024        }
1025    }
1026    if conversation_busy(surface) {
1027        return Ok(false);
1028    }
1029    match request_readiness(&surface.root, request)? {
1030        Readiness::Waiting { .. } => return Ok(false),
1031        Readiness::Ready => {}
1032    }
1033
1034    if let Some(rec) = load_combine_record(&surface.root, request)? {
1035        if request_is_done(&surface.root, request, &rec)? {
1036            return Ok(false);
1037        }
1038    }
1039
1040    let current_runs = resolve_current_run_tips(&surface.root, request)?;
1041
1042    {
1043        let mut inner = surface.requests.lock_inner();
1044        if inner.running.contains(request) {
1045            return Ok(false);
1046        }
1047        if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
1048            if attempt.runs == current_runs {
1049                if attempt.result != AttemptResult::Combined && !attempt.reported {
1050                    match retry_failure_message(&surface.root, request, &attempt) {
1051                        Ok(msg) => match surface.session.queue_for_request(request, &msg) {
1052                            Ok(_) => {
1053                                attempt.reported = true;
1054                                write_attempt_record(&surface.root, request, &attempt)?;
1055                            }
1056                            Err(e) => {
1057                                surface.session.record_error(&format!(
1058                                    "failed to queue combine failure for {request}: {e}"
1059                                ));
1060                            }
1061                        },
1062                        Err(e) => {
1063                            let msg = format_error_failure(request, &e);
1064                            record_and_report_failure(
1065                                &surface.root,
1066                                &surface.session,
1067                                request,
1068                                attempt.runs,
1069                                AttemptResult::Error,
1070                                Some(e),
1071                                &msg,
1072                            );
1073                        }
1074                    }
1075                }
1076                return Ok(false);
1077            }
1078        }
1079        inner.running.insert(request.to_string());
1080    }
1081
1082    let root = surface.root.clone();
1083    let session = surface.session.clone();
1084    let requests_state = Arc::clone(&surface.requests);
1085    let request_owned = request.to_string();
1086
1087    std::thread::spawn(move || {
1088        let _guard = RunningGuard {
1089            state: Arc::clone(&requests_state),
1090            request: request_owned.clone(),
1091        };
1092        let mut out = Vec::new();
1093        let mut err = Vec::new();
1094        let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
1095
1096        match code {
1097            0 => {
1098                let runs = match load_combine_record(&root, &request_owned) {
1099                    Ok(Some(rec)) => sorted_runs(rec.runs),
1100                    Ok(None) => current_runs,
1101                    Err(e) => {
1102                        session.record_error(&format!(
1103                            "failed to read combine record after combine for {request_owned}: {e}"
1104                        ));
1105                        current_runs
1106                    }
1107                };
1108                let attempt = AttemptRecord {
1109                    runs,
1110                    result: AttemptResult::Combined,
1111                    error: None,
1112                    reported: false,
1113                };
1114                if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1115                    session.record_error(&format!(
1116                        "failed to write attempt record for {request_owned}: {e}"
1117                    ));
1118                }
1119            }
1120            1 => match load_combine_record(&root, &request_owned) {
1121                Ok(Some(rec))
1122                    if matches!(
1123                        rec.state,
1124                        CombineState::Conflict | CombineState::CheckFailed
1125                    ) =>
1126                {
1127                    let result = match rec.state {
1128                        CombineState::Conflict => AttemptResult::Conflict,
1129                        CombineState::CheckFailed => AttemptResult::CheckFailed,
1130                        CombineState::Combined => unreachable!(),
1131                    };
1132                    let runs = sorted_runs(rec.runs.clone());
1133                    let rec_path = combine_record_path(&root, &request_owned);
1134                    match format_record_failure(&rec, &rec_path) {
1135                        Ok(msg) => {
1136                            record_and_report_failure(
1137                                &root,
1138                                &session,
1139                                &request_owned,
1140                                runs,
1141                                result,
1142                                None,
1143                                &msg,
1144                            );
1145                        }
1146                        Err(e) => {
1147                            let msg = format_error_failure(&request_owned, &e);
1148                            record_and_report_failure(
1149                                &root,
1150                                &session,
1151                                &request_owned,
1152                                runs,
1153                                AttemptResult::Error,
1154                                Some(e),
1155                                &msg,
1156                            );
1157                        }
1158                    }
1159                }
1160                Ok(_) => {
1161                    let err_text = String::from_utf8_lossy(&err).trim().to_string();
1162                    let err_text = if err_text.is_empty() {
1163                        format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
1164                    } else {
1165                        err_text
1166                    };
1167                    let msg = format_error_failure(&request_owned, &err_text);
1168                    record_and_report_failure(
1169                        &root,
1170                        &session,
1171                        &request_owned,
1172                        current_runs,
1173                        AttemptResult::Error,
1174                        Some(err_text),
1175                        &msg,
1176                    );
1177                }
1178                Err(e) => {
1179                    let msg = format_error_failure(&request_owned, &e);
1180                    record_and_report_failure(
1181                        &root,
1182                        &session,
1183                        &request_owned,
1184                        current_runs,
1185                        AttemptResult::Error,
1186                        Some(e),
1187                        &msg,
1188                    );
1189                }
1190            },
1191            other => {
1192                let err_text = String::from_utf8_lossy(&err).trim().to_string();
1193                let err_text = if err_text.is_empty() {
1194                    format!("combine exited with status {other}")
1195                } else {
1196                    err_text
1197                };
1198                let msg = format_error_failure(&request_owned, &err_text);
1199                record_and_report_failure(
1200                    &root,
1201                    &session,
1202                    &request_owned,
1203                    current_runs,
1204                    AttemptResult::Error,
1205                    Some(err_text),
1206                    &msg,
1207                );
1208            }
1209        }
1210    });
1211
1212    Ok(true)
1213}
1214
1215fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
1216    let mut commits = Vec::with_capacity(shas.len());
1217    for sha in shas {
1218        let subject = git_commit_subject(root, sha)?;
1219        commits.push(CommitSummary {
1220            sha: sha.clone(),
1221            subject,
1222        });
1223    }
1224    Ok(commits)
1225}
1226
1227fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
1228    if commits.is_empty() {
1229        return (None, None);
1230    }
1231    let title = commits[0].subject.clone();
1232    let body = commits
1233        .iter()
1234        .map(|c| c.subject.as_str())
1235        .collect::<Vec<_>>()
1236        .join("\n");
1237    (Some(title), Some(body))
1238}
1239
1240struct RequestGroup {
1241    request: String,
1242    max_started_at: u64,
1243    runs: Vec<(u64, String)>,
1244    owners: HashSet<Option<String>>,
1245}
1246
1247pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
1248    let wt_dir = surface.root.join(".wt");
1249    let entries = list_start_files(&wt_dir)?;
1250    let mut groups: BTreeMap<String, RequestGroup> = BTreeMap::new();
1251    for path in entries {
1252        let info = parse_start_file(&wt_dir, &path)?;
1253        let Some(req_id) = info.request else {
1254            continue;
1255        };
1256        let entry = groups
1257            .entry(req_id.clone())
1258            .or_insert_with(|| RequestGroup {
1259                request: req_id,
1260                max_started_at: 0,
1261                runs: Vec::new(),
1262                owners: HashSet::new(),
1263            });
1264        entry.owners.insert(info.surface);
1265        if info.is_research {
1266            continue;
1267        }
1268        if info.started_at > entry.max_started_at {
1269            entry.max_started_at = info.started_at;
1270        }
1271        entry.runs.push((info.started_at, info.id));
1272    }
1273
1274    let mut ordered: Vec<RequestGroup> = Vec::new();
1275    for group in groups.into_values() {
1276        if group.owners.len() > 1 {
1277            return Err(format!(
1278                "request {} has runs from more than one surface",
1279                group.request
1280            ));
1281        }
1282        if group.runs.is_empty() {
1283            continue;
1284        }
1285        let owner = group.owners.iter().next().and_then(|o| o.as_deref());
1286        if owner != Some(surface.surface_id.as_str()) {
1287            continue;
1288        }
1289        ordered.push(group);
1290    }
1291    ordered.sort_by(|a, b| {
1292        b.max_started_at
1293            .cmp(&a.max_started_at)
1294            .then_with(|| b.request.cmp(&a.request))
1295    });
1296
1297    let busy = conversation_busy(surface);
1298    let mut result = Vec::with_capacity(ordered.len());
1299    for mut group in ordered {
1300        group
1301            .runs
1302            .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1303        let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
1304        result.push(build_request_status(surface, group.request, run_ids, busy));
1305    }
1306    Ok(result)
1307}
1308
1309fn build_request_status(
1310    surface: &Surface,
1311    request: String,
1312    runs: Vec<String>,
1313    conversation_busy: bool,
1314) -> RequestStatus {
1315    let is_combining = surface.requests.is_combining(&request);
1316
1317    let record_res = load_combine_record(&surface.root, &request);
1318    let published_res = load_published_record(&surface.root, &request);
1319    let attempt_res = load_attempt_record(&surface.root, &request);
1320    let left_out_res: Result<Vec<String>, String> = runs
1321        .iter()
1322        .filter_map(
1323            |id| match crate::combine::is_run_left_out(&surface.root, id) {
1324                Ok(true) => Some(Ok(id.clone())),
1325                Ok(false) => None,
1326                Err(e) => Some(Err(e)),
1327            },
1328        )
1329        .collect();
1330    let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
1331
1332    let (pushed, pull_request_url) = match (&published_res, &record_res) {
1333        (Ok(p), Ok(Some(rec))) => (
1334            rec.state == CombineState::Combined && is_record_pushed(p, rec),
1335            p.pull_request_url.clone(),
1336        ),
1337        (Ok(p), _) => (false, p.pull_request_url.clone()),
1338        (Err(_), _) => (false, None),
1339    };
1340
1341    let mut status = RequestStatus {
1342        request: request.clone(),
1343        runs,
1344        left_out,
1345        state: String::new(),
1346        waiting_reasons: Vec::new(),
1347        branch: None,
1348        base: None,
1349        commits: Vec::new(),
1350        check: None,
1351        conflicting_run: None,
1352        conflicting_files: Vec::new(),
1353        failing_step: None,
1354        output_tail: None,
1355        error: None,
1356        suggested_title: None,
1357        suggested_body: None,
1358        pushed,
1359        pull_request_url,
1360    };
1361
1362    if is_combining {
1363        status.state = "combining".to_string();
1364        if let Ok(Some(rec)) = record_res {
1365            populate_record_metadata(&surface.root, &rec, &mut status);
1366        }
1367        return status;
1368    }
1369
1370    if let Err(e) = left_out_res {
1371        status.state = "error".to_string();
1372        status.error = Some(e);
1373        return status;
1374    }
1375
1376    if let Err(e) = published_res {
1377        status.state = "error".to_string();
1378        status.error = Some(e);
1379        return status;
1380    }
1381
1382    let attempt = match attempt_res {
1383        Ok(a) => a,
1384        Err(e) => {
1385            status.state = "error".to_string();
1386            status.error = Some(e);
1387            return status;
1388        }
1389    };
1390
1391    let record = match record_res {
1392        Ok(r) => r,
1393        Err(e) => {
1394            status.state = "error".to_string();
1395            status.error = Some(e);
1396            return status;
1397        }
1398    };
1399
1400    match request_readiness(&surface.root, &request) {
1401        Err(e) => {
1402            status.state = "error".to_string();
1403            status.error = Some(e);
1404            status
1405        }
1406        Ok(Readiness::Waiting { reasons }) => {
1407            status.state = "waiting".to_string();
1408            status.waiting_reasons = reasons;
1409            if let Some(ref rec) = record {
1410                populate_record_metadata(&surface.root, rec, &mut status);
1411            }
1412            status
1413        }
1414        Ok(Readiness::Ready) => {
1415            if let Some(ref rec) = record {
1416                match request_is_done(&surface.root, &request, rec) {
1417                    Ok(true) => {
1418                        status.state = "done".to_string();
1419                        populate_record_metadata(&surface.root, rec, &mut status);
1420                        return status;
1421                    }
1422                    Ok(false) => {}
1423                    Err(e) => {
1424                        status.state = "error".to_string();
1425                        status.error = Some(e);
1426                        return status;
1427                    }
1428                }
1429            }
1430            let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1431                Ok(t) => t,
1432                Err(e) => {
1433                    status.state = "error".to_string();
1434                    status.error = Some(e);
1435                    return status;
1436                }
1437            };
1438            if let Some(ref att) = attempt {
1439                if att.runs == current_runs && att.result == AttemptResult::Error {
1440                    status.state = "error".to_string();
1441                    status.error = att.error.clone();
1442                    return status;
1443                }
1444            }
1445            let Some(rec) = record else {
1446                status.state = "waiting".to_string();
1447                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1448                return status;
1449            };
1450            if !record_runs_match_tips(&rec, &current_runs) {
1451                status.state = "waiting".to_string();
1452                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1453                populate_record_metadata(&surface.root, &rec, &mut status);
1454                return status;
1455            }
1456
1457            let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1458                Ok(c) => c,
1459                Err(e) => {
1460                    status.state = "error".to_string();
1461                    status.error = Some(e);
1462                    return status;
1463                }
1464            };
1465
1466            status.branch = Some(rec.branch.clone());
1467            status.base = Some(rec.base.clone());
1468            status.commits = commits;
1469            status.check = Some(rec.check);
1470            status.conflicting_run = rec.conflicting_run.clone();
1471            status.conflicting_files = rec.conflicting_files.clone();
1472            status.failing_step = rec.failing_step.clone();
1473            status.output_tail = rec.output_tail.clone();
1474
1475            match rec.state {
1476                CombineState::Combined => {
1477                    if branch_matches_record(&surface.root, &rec) {
1478                        status.state = "combined".to_string();
1479                        let (title, body) = suggested_pr_fields(&status.commits);
1480                        status.suggested_title = title;
1481                        status.suggested_body = body;
1482                    } else {
1483                        status.state = "waiting".to_string();
1484                        status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1485                    }
1486                }
1487                CombineState::Conflict => {
1488                    status.state = "conflict".to_string();
1489                }
1490                CombineState::CheckFailed => {
1491                    status.state = "check_failed".to_string();
1492                }
1493            }
1494            status
1495        }
1496    }
1497}
1498
1499fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1500    status.branch = Some(rec.branch.clone());
1501    status.base = Some(rec.base.clone());
1502    if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1503        status.commits = commits;
1504    }
1505    status.check = Some(rec.check);
1506    status.conflicting_run = rec.conflicting_run.clone();
1507    status.conflicting_files = rec.conflicting_files.clone();
1508    status.failing_step = rec.failing_step.clone();
1509    status.output_tail = rec.output_tail.clone();
1510}
1511
1512pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1513    request_owner_check(surface, request)?;
1514    if surface.requests.is_combining(request) {
1515        return Err(RequestActionError::Conflict(format!(
1516            "request {request} is currently combining"
1517        )));
1518    }
1519    let record = load_combine_record(&surface.root, request)
1520        .map_err(RequestActionError::Internal)?
1521        .ok_or_else(|| {
1522            RequestActionError::Conflict(format!("request {request} has not been combined"))
1523        })?;
1524    if record.state != CombineState::Combined {
1525        return Err(RequestActionError::Conflict(format!(
1526            "request {request} is not combined (state: {:?})",
1527            record.state
1528        )));
1529    }
1530    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1531        return Err(RequestActionError::Conflict(format!(
1532            "request {request} is done: its branches were already merged and removed"
1533        )));
1534    }
1535
1536    let mut published =
1537        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1538
1539    match surface.publisher.push_branch(&surface.root, &record.branch) {
1540        Ok(()) => {
1541            let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1542            let branch_commit =
1543                git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1544            published.pushed_commit = Some(branch_commit);
1545            write_published_record(&surface.root, request, &published)
1546                .map_err(RequestActionError::Internal)?;
1547            if let Err(e) = surface.session.record_decision(
1548                request,
1549                "push",
1550                Some(&format!("pushed {}", record.branch)),
1551                None,
1552            ) {
1553                surface.session.record_error(&format!(
1554                    "failed to record push decision for {request}: {e}"
1555                ));
1556            }
1557            Ok(())
1558        }
1559        Err(e) => {
1560            surface.session.record_error(&format!(
1561                "push failed for {request} ({}): {e}",
1562                record.branch
1563            ));
1564            Err(RequestActionError::Internal(e))
1565        }
1566    }
1567}
1568
1569pub fn open_request_pull_request(
1570    surface: &Surface,
1571    request: &str,
1572    title: &str,
1573    body: &str,
1574) -> Result<String, RequestActionError> {
1575    request_owner_check(surface, request)?;
1576    let trimmed_title = title.trim();
1577    if trimmed_title.is_empty() {
1578        return Err(RequestActionError::BadRequest(
1579            "field title must not be empty".to_string(),
1580        ));
1581    }
1582    if surface.requests.is_combining(request) {
1583        return Err(RequestActionError::Conflict(format!(
1584            "request {request} is currently combining"
1585        )));
1586    }
1587    let record = load_combine_record(&surface.root, request)
1588        .map_err(RequestActionError::Internal)?
1589        .ok_or_else(|| {
1590            RequestActionError::Conflict(format!("request {request} has not been combined"))
1591        })?;
1592    if record.state != CombineState::Combined {
1593        return Err(RequestActionError::Conflict(format!(
1594            "request {request} is not combined (state: {:?})",
1595            record.state
1596        )));
1597    }
1598    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1599        return Err(RequestActionError::Conflict(format!(
1600            "request {request} is done: its branches were already merged and removed"
1601        )));
1602    }
1603
1604    let mut published =
1605        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1606    if !is_record_pushed(&published, &record) {
1607        return Err(RequestActionError::Conflict(format!(
1608            "branch {} must be pushed before opening a pull request",
1609            record.branch
1610        )));
1611    }
1612
1613    match surface
1614        .publisher
1615        .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1616    {
1617        Ok(url) => {
1618            published.pull_request_url = Some(url.clone());
1619            write_published_record(&surface.root, request, &published)
1620                .map_err(RequestActionError::Internal)?;
1621            if let Err(e) =
1622                surface
1623                    .session
1624                    .record_decision(request, "pull_request", Some(&url), None)
1625            {
1626                surface.session.record_error(&format!(
1627                    "failed to record pull_request decision for {request}: {e}"
1628                ));
1629            }
1630            Ok(url)
1631        }
1632        Err(e) => {
1633            surface.session.record_error(&format!(
1634                "pull request failed for {request} ({}): {e}",
1635                record.branch
1636            ));
1637            Err(RequestActionError::Internal(e))
1638        }
1639    }
1640}
1641
1642#[cfg(test)]
1643mod tests {
1644    use super::*;
1645
1646    fn run_git(dir: &Path, args: &[&str]) -> String {
1647        let out = Command::new("git")
1648            .args(args)
1649            .current_dir(dir)
1650            .output()
1651            .unwrap();
1652        assert!(
1653            out.status.success(),
1654            "git {} failed: {}",
1655            args.join(" "),
1656            String::from_utf8_lossy(&out.stderr)
1657        );
1658        String::from_utf8_lossy(&out.stdout).trim().to_string()
1659    }
1660
1661    fn write_test_file(path: &Path, content: &str) {
1662        if let Some(parent) = path.parent() {
1663            std::fs::create_dir_all(parent).unwrap();
1664        }
1665        std::fs::write(path, content).unwrap();
1666    }
1667
1668    #[test]
1669    fn a_combined_run_without_a_summary_errors_naming_the_file() {
1670        let d = tempfile::tempdir().unwrap();
1671        let repo = d.path().join("missing-summary-repo");
1672        std::fs::create_dir_all(&repo).unwrap();
1673        run_git(&repo, &["init", "-q", "-b", "main"]);
1674        run_git(&repo, &["config", "user.email", "test@example.com"]);
1675        run_git(&repo, &["config", "user.name", "Test"]);
1676        write_test_file(&repo.join("README.md"), "hello\n");
1677        write_test_file(&repo.join("blyte.toml"), "[dispatch]\ngate = \"true\"\n");
1678        run_git(&repo, &["add", "."]);
1679        run_git(&repo, &["commit", "-q", "-m", "initial"]);
1680        let base_sha = run_git(&repo, &["rev-parse", "HEAD"]);
1681
1682        let wt_run = repo.join(".wt/MS1");
1683        std::fs::create_dir_all(repo.join(".wt")).unwrap();
1684        assert!(Command::new("git")
1685            .args(["worktree", "add", "-q", "-b", "wip/MS1"])
1686            .arg(&wt_run)
1687            .arg(&base_sha)
1688            .current_dir(&repo)
1689            .status()
1690            .unwrap()
1691            .success());
1692        write_test_file(&wt_run.join("ms1.txt"), "one\n");
1693        run_git(&wt_run, &["add", "ms1.txt"]);
1694        run_git(&wt_run, &["commit", "-q", "-m", "feat: MS1"]);
1695        assert!(Command::new("git")
1696            .args(["worktree", "remove", "--force"])
1697            .arg(&wt_run)
1698            .current_dir(&repo)
1699            .status()
1700            .unwrap()
1701            .success());
1702
1703        write_test_file(&repo.join(".wt/tasks/MS1.md"), "# Task MS1\n");
1704        write_test_file(
1705            &repo.join(".wt/MS1.start.json"),
1706            &format!(
1707                r#"{{"id":"MS1","pid":999999,"started_at":100,"base_sha":"{base_sha}","task_file":".wt/tasks/MS1.md","research":false,"request":"req-ms"}}"#
1708            ),
1709        );
1710        let summary_path = repo.join(".wt/MS1.json");
1711        write_test_file(
1712            &summary_path,
1713            r#"{"id":"MS1","outcome":"verified","branch":"wip/MS1","turns":2,"seconds":5,"cost_usd":0.01,"final_message":"done"}"#,
1714        );
1715        write_test_file(
1716            &repo.join(".wt/MS1.checks.json"),
1717            r#"{"flags":[],"fallbacks":[]}"#,
1718        );
1719
1720        let mut out = Vec::new();
1721        let mut err = Vec::new();
1722        let code = crate::combine::combine_in(&repo, "req-ms", &mut out, &mut err);
1723        assert_eq!(code, 0, "combine failed: {}", String::from_utf8_lossy(&err));
1724        assert_eq!(run_is_combined(&repo, "MS1", Some("req-ms")), Ok(true));
1725
1726        std::fs::remove_file(&summary_path).unwrap();
1727        let err_msg = run_is_combined(&repo, "MS1", Some("req-ms")).unwrap_err();
1728        assert!(
1729            err_msg.contains(".wt/MS1.json"),
1730            "expected error to contain .wt/MS1.json, got: {err_msg}"
1731        );
1732    }
1733
1734    #[test]
1735    fn a_combined_run_with_non_string_branch_errors_naming_the_file() {
1736        let d = tempfile::tempdir().unwrap();
1737        let repo = d.path().join("non-string-branch-repo");
1738        write_test_file(
1739            &repo.join(".wt/combined/req-ns.json"),
1740            r#"{"request":"req-ns","state":"combined","branch":"request/req-ns","base":"0000000","runs":[{"id":"NS1","tip":"1111111"}],"commits":["1111111"]}"#,
1741        );
1742        write_test_file(
1743            &repo.join(".wt/NS1.json"),
1744            r#"{"id":"NS1","outcome":"verified","branch":42}"#,
1745        );
1746
1747        let err_msg = run_is_combined(&repo, "NS1", Some("req-ns")).unwrap_err();
1748        assert!(
1749            err_msg.contains(".wt/NS1.json"),
1750            "expected error to contain .wt/NS1.json, got: {err_msg}"
1751        );
1752    }
1753
1754    #[test]
1755    fn a_combined_run_with_git_error_returns_error_naming_run_and_branch() {
1756        let d = tempfile::tempdir().unwrap();
1757        let non_repo = d.path().join("not-a-git-repo");
1758        write_test_file(
1759            &non_repo.join(".wt/combined/req-ge.json"),
1760            r#"{"request":"req-ge","state":"combined","branch":"request/req-ge","base":"0000000","runs":[{"id":"GE1","tip":"1111111"}],"commits":["1111111"]}"#,
1761        );
1762        write_test_file(
1763            &non_repo.join(".wt/GE1.json"),
1764            r#"{"id":"GE1","outcome":"verified","branch":"wip/GE1"}"#,
1765        );
1766
1767        let err_msg = run_is_combined(&non_repo, "GE1", Some("req-ge")).unwrap_err();
1768        assert!(
1769            err_msg.contains("GE1") && err_msg.contains("wip/GE1"),
1770            "expected error to name run and branch, got: {err_msg}"
1771        );
1772    }
1773}