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