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