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
957pub fn format_combined_message(rec: &CombineRecord) -> String {
958    let short_hashes = rec
959        .commits
960        .iter()
961        .map(|c| c.chars().take(8).collect::<String>())
962        .collect::<Vec<_>>()
963        .join(", ");
964    format!(
965        "Request {} is combined on branch {} ({} commit(s): {}).\nIts check passed. Tell the user what changed, and ask to publish it if they want a pull request.",
966        rec.request,
967        rec.branch,
968        rec.commits.len(),
969        short_hashes
970    )
971}
972
973fn format_error_failure(request: &str, err_text: &str) -> String {
974    format!("Combine failed for request {request} (state: error).\nError: {err_text}")
975}
976
977struct RunningGuard {
978    state: Arc<RequestsState>,
979    request: String,
980}
981
982impl Drop for RunningGuard {
983    fn drop(&mut self) {
984        let mut inner = self.state.lock_inner();
985        inner.running.remove(&self.request);
986        self.state.cv.notify_all();
987    }
988}
989
990fn retry_attempt_message(
991    root: &Path,
992    request: &str,
993    attempt: &AttemptRecord,
994) -> Result<String, String> {
995    let path = attempt_record_path(root, request);
996    match attempt.result {
997        AttemptResult::Conflict | AttemptResult::CheckFailed => {
998            let expected_state = match attempt.result {
999                AttemptResult::Conflict => CombineState::Conflict,
1000                AttemptResult::CheckFailed => CombineState::CheckFailed,
1001                AttemptResult::Combined | AttemptResult::Error => unreachable!(),
1002            };
1003            match load_combine_record(root, request)? {
1004                Some(rec) if rec.state == expected_state => {
1005                    format_record_failure(&rec, &combine_record_path(root, request))
1006                }
1007                _ => Err(format!(
1008                    "attempt file {} has result {:?} without a matching combine record",
1009                    path.display(),
1010                    attempt.result
1011                )),
1012            }
1013        }
1014        AttemptResult::Error => {
1015            let err_text = attempt.error.as_deref().ok_or_else(|| {
1016                format!(
1017                    "attempt file {} has result error without error text",
1018                    path.display()
1019                )
1020            })?;
1021            Ok(format_error_failure(request, err_text))
1022        }
1023        AttemptResult::Combined => match load_combine_record(root, request)? {
1024            Some(rec) if rec.state == CombineState::Combined => Ok(format_combined_message(&rec)),
1025            _ => Err(format!(
1026                "attempt file {} has result {:?} without a matching combine record",
1027                path.display(),
1028                attempt.result
1029            )),
1030        },
1031    }
1032}
1033
1034fn record_and_report_failure(
1035    root: &Path,
1036    session: &crate::session::Session,
1037    request: &str,
1038    runs: Vec<CombinedRun>,
1039    result: AttemptResult,
1040    error: Option<String>,
1041    msg: &str,
1042) {
1043    let mut attempt = AttemptRecord {
1044        runs,
1045        result,
1046        error,
1047        reported: false,
1048    };
1049    if let Err(e) = write_attempt_record(root, request, &attempt) {
1050        session.record_error(&format!(
1051            "failed to write attempt record for {request}: {e}"
1052        ));
1053    }
1054    match session.queue_for_request(request, msg) {
1055        Ok(_) => {
1056            attempt.reported = true;
1057            if let Err(e) = write_attempt_record(root, request, &attempt) {
1058                session.record_error(&format!(
1059                    "failed to write attempt record for {request}: {e}"
1060                ));
1061            }
1062        }
1063        Err(e) => {
1064            session.record_error(&format!(
1065                "failed to queue combine failure for {request}: {e}"
1066            ));
1067        }
1068    }
1069}
1070
1071fn conversation_busy(surface: &Surface) -> bool {
1072    let info = surface.session.info();
1073    info.busy || info.queued > 0
1074}
1075
1076fn ready_waiting_reason(conversation_busy: bool) -> String {
1077    if conversation_busy {
1078        "the conversation model is still working".to_string()
1079    } else {
1080        "waiting to combine".to_string()
1081    }
1082}
1083
1084pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
1085    crate::dispatch::validate_request_id(request)?;
1086    match check_request_ownership(surface, request) {
1087        Ok(RequestOwnership::Owned) => {}
1088        Ok(
1089            RequestOwnership::OtherSurface | RequestOwnership::Unowned | RequestOwnership::NotFound,
1090        ) => return Ok(false),
1091        Err(RequestOwnershipError::Mixed(msg) | RequestOwnershipError::IoOrParse(msg)) => {
1092            return Err(msg);
1093        }
1094    }
1095    if conversation_busy(surface) {
1096        return Ok(false);
1097    }
1098    match request_readiness(&surface.root, request)? {
1099        Readiness::Waiting { .. } => return Ok(false),
1100        Readiness::Ready => {}
1101    }
1102
1103    if let Some(rec) = load_combine_record(&surface.root, request)? {
1104        if request_is_done(&surface.root, request, &rec)? {
1105            return Ok(false);
1106        }
1107    }
1108
1109    let current_runs = resolve_current_run_tips(&surface.root, request)?;
1110
1111    {
1112        let mut inner = surface.requests.lock_inner();
1113        if inner.running.contains(request) {
1114            return Ok(false);
1115        }
1116        if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
1117            if attempt.runs == current_runs {
1118                if !attempt.reported {
1119                    match retry_attempt_message(&surface.root, request, &attempt) {
1120                        Ok(msg) => match surface.session.queue_for_request(request, &msg) {
1121                            Ok(_) => {
1122                                attempt.reported = true;
1123                                write_attempt_record(&surface.root, request, &attempt)?;
1124                            }
1125                            Err(e) => {
1126                                surface.session.record_error(&format!(
1127                                    "failed to queue combine result for {request}: {e}"
1128                                ));
1129                            }
1130                        },
1131                        Err(e) => {
1132                            let msg = format_error_failure(request, &e);
1133                            record_and_report_failure(
1134                                &surface.root,
1135                                &surface.session,
1136                                request,
1137                                attempt.runs,
1138                                AttemptResult::Error,
1139                                Some(e),
1140                                &msg,
1141                            );
1142                        }
1143                    }
1144                }
1145                return Ok(false);
1146            }
1147        }
1148        inner.running.insert(request.to_string());
1149    }
1150
1151    let root = surface.root.clone();
1152    let session = surface.session.clone();
1153    let requests_state = Arc::clone(&surface.requests);
1154    let request_owned = request.to_string();
1155
1156    std::thread::spawn(move || {
1157        let _guard = RunningGuard {
1158            state: Arc::clone(&requests_state),
1159            request: request_owned.clone(),
1160        };
1161        let mut out = Vec::new();
1162        let mut err = Vec::new();
1163        let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
1164
1165        match code {
1166            0 => {
1167                let rec_path = combine_record_path(&root, &request_owned);
1168                let (runs, rec) = match load_combine_record(&root, &request_owned) {
1169                    Ok(Some(rec)) => (sorted_runs(rec.runs.clone()), Some(rec)),
1170                    Ok(None) => {
1171                        session.record_error(&format!(
1172                            "combine record {} is missing after combine for {request_owned}",
1173                            rec_path.display()
1174                        ));
1175                        (current_runs, None)
1176                    }
1177                    Err(e) => {
1178                        session.record_error(&format!(
1179                            "failed to read combine record after combine for {request_owned}: {e}"
1180                        ));
1181                        (current_runs, None)
1182                    }
1183                };
1184                let mut attempt = AttemptRecord {
1185                    runs,
1186                    result: AttemptResult::Combined,
1187                    error: None,
1188                    reported: false,
1189                };
1190                if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1191                    session.record_error(&format!(
1192                        "failed to write attempt record for {request_owned}: {e}"
1193                    ));
1194                }
1195                if let Some(rec) = rec {
1196                    let msg = format_combined_message(&rec);
1197                    match session.queue_for_request(&request_owned, &msg) {
1198                        Ok(_) => {
1199                            attempt.reported = true;
1200                            if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1201                                session.record_error(&format!(
1202                                    "failed to write attempt record for {request_owned}: {e}"
1203                                ));
1204                            }
1205                        }
1206                        Err(e) => {
1207                            session.record_error(&format!(
1208                                "failed to queue combine result for {request_owned}: {e}"
1209                            ));
1210                        }
1211                    }
1212                }
1213            }
1214            1 => match load_combine_record(&root, &request_owned) {
1215                Ok(Some(rec))
1216                    if matches!(
1217                        rec.state,
1218                        CombineState::Conflict | CombineState::CheckFailed
1219                    ) =>
1220                {
1221                    let result = match rec.state {
1222                        CombineState::Conflict => AttemptResult::Conflict,
1223                        CombineState::CheckFailed => AttemptResult::CheckFailed,
1224                        CombineState::Combined => unreachable!(),
1225                    };
1226                    let runs = sorted_runs(rec.runs.clone());
1227                    let rec_path = combine_record_path(&root, &request_owned);
1228                    match format_record_failure(&rec, &rec_path) {
1229                        Ok(msg) => {
1230                            record_and_report_failure(
1231                                &root,
1232                                &session,
1233                                &request_owned,
1234                                runs,
1235                                result,
1236                                None,
1237                                &msg,
1238                            );
1239                        }
1240                        Err(e) => {
1241                            let msg = format_error_failure(&request_owned, &e);
1242                            record_and_report_failure(
1243                                &root,
1244                                &session,
1245                                &request_owned,
1246                                runs,
1247                                AttemptResult::Error,
1248                                Some(e),
1249                                &msg,
1250                            );
1251                        }
1252                    }
1253                }
1254                Ok(_) => {
1255                    let err_text = String::from_utf8_lossy(&err).trim().to_string();
1256                    let err_text = if err_text.is_empty() {
1257                        format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
1258                    } else {
1259                        err_text
1260                    };
1261                    let msg = format_error_failure(&request_owned, &err_text);
1262                    record_and_report_failure(
1263                        &root,
1264                        &session,
1265                        &request_owned,
1266                        current_runs,
1267                        AttemptResult::Error,
1268                        Some(err_text),
1269                        &msg,
1270                    );
1271                }
1272                Err(e) => {
1273                    let msg = format_error_failure(&request_owned, &e);
1274                    record_and_report_failure(
1275                        &root,
1276                        &session,
1277                        &request_owned,
1278                        current_runs,
1279                        AttemptResult::Error,
1280                        Some(e),
1281                        &msg,
1282                    );
1283                }
1284            },
1285            other => {
1286                let err_text = String::from_utf8_lossy(&err).trim().to_string();
1287                let err_text = if err_text.is_empty() {
1288                    format!("combine exited with status {other}")
1289                } else {
1290                    err_text
1291                };
1292                let msg = format_error_failure(&request_owned, &err_text);
1293                record_and_report_failure(
1294                    &root,
1295                    &session,
1296                    &request_owned,
1297                    current_runs,
1298                    AttemptResult::Error,
1299                    Some(err_text),
1300                    &msg,
1301                );
1302            }
1303        }
1304    });
1305
1306    Ok(true)
1307}
1308
1309fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
1310    let mut commits = Vec::with_capacity(shas.len());
1311    for sha in shas {
1312        let subject = git_commit_subject(root, sha)?;
1313        commits.push(CommitSummary {
1314            sha: sha.clone(),
1315            subject,
1316        });
1317    }
1318    Ok(commits)
1319}
1320
1321fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
1322    if commits.is_empty() {
1323        return (None, None);
1324    }
1325    let title = commits[0].subject.clone();
1326    let body = commits
1327        .iter()
1328        .map(|c| c.subject.as_str())
1329        .collect::<Vec<_>>()
1330        .join("\n");
1331    (Some(title), Some(body))
1332}
1333
1334struct RequestGroup {
1335    request: String,
1336    max_started_at: u64,
1337    runs: Vec<(u64, String)>,
1338    owners: HashSet<Option<String>>,
1339    started_bys: HashSet<Option<String>>,
1340}
1341
1342pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
1343    let wt_dir = surface.root.join(".wt");
1344    let entries = list_start_files(&wt_dir)?;
1345    let mut groups: BTreeMap<String, RequestGroup> = BTreeMap::new();
1346    for path in entries {
1347        let info = parse_start_file(&wt_dir, &path)?;
1348        let Some(req_id) = info.request else {
1349            continue;
1350        };
1351        let entry = groups
1352            .entry(req_id.clone())
1353            .or_insert_with(|| RequestGroup {
1354                request: req_id,
1355                max_started_at: 0,
1356                runs: Vec::new(),
1357                owners: HashSet::new(),
1358                started_bys: HashSet::new(),
1359            });
1360        entry.owners.insert(info.surface);
1361        entry.started_bys.insert(info.started_by);
1362        if info.is_research {
1363            continue;
1364        }
1365        if info.started_at > entry.max_started_at {
1366            entry.max_started_at = info.started_at;
1367        }
1368        entry.runs.push((info.started_at, info.id));
1369    }
1370
1371    let mut ordered: Vec<RequestGroup> = Vec::new();
1372    for group in groups.into_values() {
1373        if group.owners.len() > 1 {
1374            return Err(format!(
1375                "request {} has runs from more than one surface",
1376                group.request
1377            ));
1378        }
1379        if group.started_bys.len() > 1 {
1380            return Err(format!(
1381                "request {} has runs started by different surfaces",
1382                group.request
1383            ));
1384        }
1385        if group.runs.is_empty() {
1386            continue;
1387        }
1388        let owner = group.owners.iter().next().and_then(|o| o.as_deref());
1389        if owner != Some(surface.surface_id.as_str()) {
1390            continue;
1391        }
1392        ordered.push(group);
1393    }
1394    ordered.sort_by(|a, b| {
1395        b.max_started_at
1396            .cmp(&a.max_started_at)
1397            .then_with(|| b.request.cmp(&a.request))
1398    });
1399
1400    let busy = conversation_busy(surface);
1401    let mut result = Vec::with_capacity(ordered.len());
1402    for mut group in ordered {
1403        group
1404            .runs
1405            .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1406        let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
1407        let started_by = group.started_bys.into_iter().next().flatten();
1408        result.push(build_request_status(
1409            surface,
1410            group.request,
1411            run_ids,
1412            started_by,
1413            busy,
1414        ));
1415    }
1416    Ok(result)
1417}
1418
1419fn build_request_status(
1420    surface: &Surface,
1421    request: String,
1422    runs: Vec<String>,
1423    started_by: Option<String>,
1424    conversation_busy: bool,
1425) -> RequestStatus {
1426    let is_combining = surface.requests.is_combining(&request);
1427
1428    let record_res = load_combine_record(&surface.root, &request);
1429    let published_res = load_published_record(&surface.root, &request);
1430    let attempt_res = load_attempt_record(&surface.root, &request);
1431    let left_out_res: Result<Vec<String>, String> = runs
1432        .iter()
1433        .filter_map(
1434            |id| match crate::combine::is_run_left_out(&surface.root, id) {
1435                Ok(true) => Some(Ok(id.clone())),
1436                Ok(false) => None,
1437                Err(e) => Some(Err(e)),
1438            },
1439        )
1440        .collect();
1441    let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
1442
1443    let (pushed, pull_request_url) = match (&published_res, &record_res) {
1444        (Ok(p), Ok(Some(rec))) => (
1445            rec.state == CombineState::Combined && is_record_pushed(p, rec),
1446            p.pull_request_url.clone(),
1447        ),
1448        (Ok(p), _) => (false, p.pull_request_url.clone()),
1449        (Err(_), _) => (false, None),
1450    };
1451
1452    let mut status = RequestStatus {
1453        request: request.clone(),
1454        runs,
1455        left_out,
1456        state: String::new(),
1457        waiting_reasons: Vec::new(),
1458        branch: None,
1459        base: None,
1460        commits: Vec::new(),
1461        check: None,
1462        conflicting_run: None,
1463        conflicting_files: Vec::new(),
1464        failing_step: None,
1465        output_tail: None,
1466        error: None,
1467        suggested_title: None,
1468        suggested_body: None,
1469        pushed,
1470        pull_request_url,
1471        started_by,
1472    };
1473
1474    if is_combining {
1475        status.state = "combining".to_string();
1476        if let Ok(Some(rec)) = record_res {
1477            populate_record_metadata(&surface.root, &rec, &mut status);
1478        }
1479        return status;
1480    }
1481
1482    if let Err(e) = left_out_res {
1483        status.state = "error".to_string();
1484        status.error = Some(e);
1485        return status;
1486    }
1487
1488    if let Err(e) = published_res {
1489        status.state = "error".to_string();
1490        status.error = Some(e);
1491        return status;
1492    }
1493
1494    let attempt = match attempt_res {
1495        Ok(a) => a,
1496        Err(e) => {
1497            status.state = "error".to_string();
1498            status.error = Some(e);
1499            return status;
1500        }
1501    };
1502
1503    let record = match record_res {
1504        Ok(r) => r,
1505        Err(e) => {
1506            status.state = "error".to_string();
1507            status.error = Some(e);
1508            return status;
1509        }
1510    };
1511
1512    match request_readiness(&surface.root, &request) {
1513        Err(e) => {
1514            status.state = "error".to_string();
1515            status.error = Some(e);
1516            status
1517        }
1518        Ok(Readiness::Waiting { reasons }) => {
1519            status.state = "waiting".to_string();
1520            status.waiting_reasons = reasons;
1521            if let Some(ref rec) = record {
1522                populate_record_metadata(&surface.root, rec, &mut status);
1523            }
1524            status
1525        }
1526        Ok(Readiness::Ready) => {
1527            if let Some(ref rec) = record {
1528                match request_is_done(&surface.root, &request, rec) {
1529                    Ok(true) => {
1530                        status.state = "done".to_string();
1531                        populate_record_metadata(&surface.root, rec, &mut status);
1532                        return status;
1533                    }
1534                    Ok(false) => {}
1535                    Err(e) => {
1536                        status.state = "error".to_string();
1537                        status.error = Some(e);
1538                        return status;
1539                    }
1540                }
1541            }
1542            let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1543                Ok(t) => t,
1544                Err(e) => {
1545                    status.state = "error".to_string();
1546                    status.error = Some(e);
1547                    return status;
1548                }
1549            };
1550            if let Some(ref att) = attempt {
1551                if att.runs == current_runs && att.result == AttemptResult::Error {
1552                    status.state = "error".to_string();
1553                    status.error = att.error.clone();
1554                    return status;
1555                }
1556            }
1557            let Some(rec) = record else {
1558                status.state = "waiting".to_string();
1559                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1560                return status;
1561            };
1562            if !record_runs_match_tips(&rec, &current_runs) {
1563                status.state = "waiting".to_string();
1564                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1565                populate_record_metadata(&surface.root, &rec, &mut status);
1566                return status;
1567            }
1568
1569            let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1570                Ok(c) => c,
1571                Err(e) => {
1572                    status.state = "error".to_string();
1573                    status.error = Some(e);
1574                    return status;
1575                }
1576            };
1577
1578            status.branch = Some(rec.branch.clone());
1579            status.base = Some(rec.base.clone());
1580            status.commits = commits;
1581            status.check = Some(rec.check);
1582            status.conflicting_run = rec.conflicting_run.clone();
1583            status.conflicting_files = rec.conflicting_files.clone();
1584            status.failing_step = rec.failing_step.clone();
1585            status.output_tail = rec.output_tail.clone();
1586
1587            match rec.state {
1588                CombineState::Combined => {
1589                    if branch_matches_record(&surface.root, &rec) {
1590                        status.state = "combined".to_string();
1591                        let (title, body) = suggested_pr_fields(&status.commits);
1592                        status.suggested_title = title;
1593                        status.suggested_body = body;
1594                    } else {
1595                        status.state = "waiting".to_string();
1596                        status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1597                    }
1598                }
1599                CombineState::Conflict => {
1600                    status.state = "conflict".to_string();
1601                }
1602                CombineState::CheckFailed => {
1603                    status.state = "check_failed".to_string();
1604                }
1605            }
1606            status
1607        }
1608    }
1609}
1610
1611fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1612    status.branch = Some(rec.branch.clone());
1613    status.base = Some(rec.base.clone());
1614    if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1615        status.commits = commits;
1616    }
1617    status.check = Some(rec.check);
1618    status.conflicting_run = rec.conflicting_run.clone();
1619    status.conflicting_files = rec.conflicting_files.clone();
1620    status.failing_step = rec.failing_step.clone();
1621    status.output_tail = rec.output_tail.clone();
1622}
1623
1624pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1625    request_owner_check(surface, request)?;
1626    if surface.requests.is_combining(request) {
1627        return Err(RequestActionError::Conflict(format!(
1628            "request {request} is currently combining"
1629        )));
1630    }
1631    let record = load_combine_record(&surface.root, request)
1632        .map_err(RequestActionError::Internal)?
1633        .ok_or_else(|| {
1634            RequestActionError::Conflict(format!("request {request} has not been combined"))
1635        })?;
1636    if record.state != CombineState::Combined {
1637        return Err(RequestActionError::Conflict(format!(
1638            "request {request} is not combined (state: {:?})",
1639            record.state
1640        )));
1641    }
1642    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1643        return Err(RequestActionError::Conflict(format!(
1644            "request {request} is done: its branches were already merged and removed"
1645        )));
1646    }
1647
1648    let mut published =
1649        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1650
1651    match surface.publisher.push_branch(&surface.root, &record.branch) {
1652        Ok(()) => {
1653            let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1654            let branch_commit =
1655                git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1656            published.pushed_commit = Some(branch_commit);
1657            write_published_record(&surface.root, request, &published)
1658                .map_err(RequestActionError::Internal)?;
1659            if let Err(e) = surface.session.record_decision(
1660                request,
1661                "push",
1662                Some(&format!("pushed {}", record.branch)),
1663                None,
1664            ) {
1665                surface.session.record_error(&format!(
1666                    "failed to record push decision for {request}: {e}"
1667                ));
1668            }
1669            Ok(())
1670        }
1671        Err(e) => {
1672            surface.session.record_error(&format!(
1673                "push failed for {request} ({}): {e}",
1674                record.branch
1675            ));
1676            Err(RequestActionError::Internal(e))
1677        }
1678    }
1679}
1680
1681pub fn open_request_pull_request(
1682    surface: &Surface,
1683    request: &str,
1684    title: &str,
1685    body: &str,
1686) -> Result<String, RequestActionError> {
1687    request_owner_check(surface, request)?;
1688    let trimmed_title = title.trim();
1689    if trimmed_title.is_empty() {
1690        return Err(RequestActionError::BadRequest(
1691            "field title must not be empty".to_string(),
1692        ));
1693    }
1694    if surface.requests.is_combining(request) {
1695        return Err(RequestActionError::Conflict(format!(
1696            "request {request} is currently combining"
1697        )));
1698    }
1699    let record = load_combine_record(&surface.root, request)
1700        .map_err(RequestActionError::Internal)?
1701        .ok_or_else(|| {
1702            RequestActionError::Conflict(format!("request {request} has not been combined"))
1703        })?;
1704    if record.state != CombineState::Combined {
1705        return Err(RequestActionError::Conflict(format!(
1706            "request {request} is not combined (state: {:?})",
1707            record.state
1708        )));
1709    }
1710    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1711        return Err(RequestActionError::Conflict(format!(
1712            "request {request} is done: its branches were already merged and removed"
1713        )));
1714    }
1715
1716    let mut published =
1717        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1718    if !is_record_pushed(&published, &record) {
1719        return Err(RequestActionError::Conflict(format!(
1720            "branch {} must be pushed before opening a pull request",
1721            record.branch
1722        )));
1723    }
1724
1725    match surface
1726        .publisher
1727        .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1728    {
1729        Ok(url) => {
1730            published.pull_request_url = Some(url.clone());
1731            write_published_record(&surface.root, request, &published)
1732                .map_err(RequestActionError::Internal)?;
1733            if let Err(e) =
1734                surface
1735                    .session
1736                    .record_decision(request, "pull_request", Some(&url), None)
1737            {
1738                surface.session.record_error(&format!(
1739                    "failed to record pull_request decision for {request}: {e}"
1740                ));
1741            }
1742            Ok(url)
1743        }
1744        Err(e) => {
1745            surface.session.record_error(&format!(
1746                "pull request failed for {request} ({}): {e}",
1747                record.branch
1748            ));
1749            Err(RequestActionError::Internal(e))
1750        }
1751    }
1752}
1753
1754fn request_action_error_message(err: RequestActionError) -> String {
1755    match err {
1756        RequestActionError::BadRequest(msg)
1757        | RequestActionError::NotOwned(msg)
1758        | RequestActionError::Conflict(msg)
1759        | RequestActionError::Internal(msg) => msg,
1760    }
1761}
1762
1763pub fn publish_request_with_approval(
1764    surface: &Surface,
1765    approver: &dyn blyte_agent::approval::Approver,
1766    request: &str,
1767    title: &str,
1768    body: &str,
1769) -> Result<String, String> {
1770    if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
1771        return Err(format!(
1772            "cannot publish during a turn started by another surface ({started_by})"
1773        ));
1774    }
1775    let trimmed_title = title.trim();
1776    if trimmed_title.is_empty() {
1777        return Err("publish title must not be blank".to_string());
1778    }
1779    if title.chars().count() > blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS {
1780        return Err(format!(
1781            "publish title must be at most {} characters",
1782            blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS
1783        ));
1784    }
1785    if body.len() > blyte_agent::tools::PUBLISH_BODY_MAX_BYTES {
1786        return Err(format!(
1787            "publish body must be at most {} bytes",
1788            blyte_agent::tools::PUBLISH_BODY_MAX_BYTES
1789        ));
1790    }
1791    crate::dispatch::validate_request_id(request)?;
1792    match check_request_ownership(surface, request) {
1793        Ok(RequestOwnership::Owned) => {}
1794        Ok(RequestOwnership::OtherSurface) => {
1795            return Err(format!("request {request} belongs to another surface"));
1796        }
1797        Ok(RequestOwnership::Unowned) => {
1798            return Err(format!("request {request} was not started by this surface"));
1799        }
1800        Ok(RequestOwnership::NotFound) => {
1801            return Err(format!("unknown request {request}"));
1802        }
1803        Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
1804            return Err(msg);
1805        }
1806    }
1807    if surface.requests.is_combining(request) {
1808        return Err(format!("request {request} is still combining"));
1809    }
1810    let statuses = list_requests(surface)?;
1811    let status = statuses
1812        .into_iter()
1813        .find(|s| s.request == request)
1814        .ok_or_else(|| format!("unknown request {request}"))?;
1815    if status.state != "combined" {
1816        return Err(format!(
1817            "request {request} is not ready to publish (state: {})",
1818            status.state
1819        ));
1820    }
1821    if status.pushed {
1822        if let Some(url) = status.pull_request_url {
1823            return Err(format!(
1824                "request {request} already has an open pull request ({url})"
1825            ));
1826        }
1827    }
1828    if surface.session.has_pending_publish(request) {
1829        return Err(format!(
1830            "a publish approval for request {request} is already waiting"
1831        ));
1832    }
1833    let _publish_guard = surface
1834        .requests
1835        .try_begin_publish(request)
1836        .ok_or_else(|| format!("a publish approval for request {request} is already waiting"))?;
1837    if surface.session.has_pending_publish(request) {
1838        return Err(format!(
1839            "a publish approval for request {request} is already waiting"
1840        ));
1841    }
1842
1843    let branch = status
1844        .branch
1845        .ok_or_else(|| format!("request {request} has no combined branch"))?;
1846    let remote_url = crate::publish::origin_remote_url(&surface.root)?;
1847    let base = crate::publish::default_branch(&surface.root)?;
1848    let commit = crate::publish::branch_commit(&surface.root, &branch)?;
1849    let commits = crate::publish::branch_commit_subjects(&surface.root, &branch, &base)?;
1850
1851    let details = blyte_agent::approval::PublishDetails {
1852        request: request.to_string(),
1853        remote_url,
1854        branch: branch.clone(),
1855        base,
1856        commit: commit.clone(),
1857        commits,
1858        title: trimmed_title.to_string(),
1859        body: body.to_string(),
1860    };
1861
1862    match approver.ask_publish(&details) {
1863        blyte_agent::approval::Approval::Approved => {}
1864        blyte_agent::approval::Approval::Denied => {
1865            return Err("the user declined".to_string());
1866        }
1867        blyte_agent::approval::Approval::Unavailable => {
1868            return Err("publish approval is not available here".to_string());
1869        }
1870    }
1871
1872    crate::publish::verify_branch_commit(&surface.root, &branch, &commit)?;
1873
1874    let published = load_published_record(&surface.root, request)?;
1875    let already_pushed = published.pushed_commit.as_deref() == Some(commit.as_str());
1876    if !already_pushed {
1877        push_request(surface, request).map_err(request_action_error_message)?;
1878    }
1879
1880    match open_request_pull_request(surface, request, trimmed_title, body) {
1881        Ok(url) => Ok(url),
1882        Err(err) => {
1883            let detail = request_action_error_message(err);
1884            if already_pushed {
1885                Err(format!(
1886                    "branch {branch} was already pushed at {commit}, but opening the pull request failed: {detail}"
1887                ))
1888            } else {
1889                Err(format!(
1890                    "push succeeded for {branch} ({commit}), but opening the pull request failed: {detail}"
1891                ))
1892            }
1893        }
1894    }
1895}
1896
1897pub struct SurfacePublishTool {
1898    surface: Arc<Surface>,
1899    approver: Arc<dyn blyte_agent::approval::Approver>,
1900}
1901
1902impl SurfacePublishTool {
1903    pub fn new(surface: Arc<Surface>) -> Self {
1904        let approver: Arc<dyn blyte_agent::approval::Approver> = surface.session.approver();
1905        Self { surface, approver }
1906    }
1907}
1908
1909impl blyte_agent::tools::PublishTool for SurfacePublishTool {
1910    fn publish(&self, request: &str, title: &str, body: &str) -> Result<String, String> {
1911        publish_request_with_approval(&self.surface, self.approver.as_ref(), request, title, body)
1912    }
1913}