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