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