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    Redone,
21}
22
23pub trait Publisher: Send + Sync {
24    fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String>;
25    fn open_pull_request(
26        &self,
27        root: &Path,
28        branch: &str,
29        title: &str,
30        body: &str,
31    ) -> Result<String, String>;
32}
33
34pub struct RealPublisher;
35
36impl Publisher for RealPublisher {
37    fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String> {
38        crate::publish::push_branch(root, branch)
39    }
40
41    fn open_pull_request(
42        &self,
43        root: &Path,
44        branch: &str,
45        title: &str,
46        body: &str,
47    ) -> Result<String, String> {
48        crate::publish::open_pull_request(root, branch, title, body)
49    }
50}
51
52#[derive(Default)]
53struct RequestsInner {
54    running: HashSet<String>,
55    publishing: HashSet<String>,
56}
57
58pub struct PublishGuard {
59    state: Arc<RequestsState>,
60    request: String,
61}
62
63impl Drop for PublishGuard {
64    fn drop(&mut self) {
65        let mut inner = self.state.lock_inner();
66        inner.publishing.remove(&self.request);
67    }
68}
69
70pub struct RequestsState {
71    inner: Mutex<RequestsInner>,
72    cv: Condvar,
73}
74
75impl Default for RequestsState {
76    fn default() -> Self {
77        Self::new()
78    }
79}
80
81impl RequestsState {
82    pub fn new() -> Self {
83        Self {
84            inner: Mutex::new(RequestsInner::default()),
85            cv: Condvar::new(),
86        }
87    }
88
89    fn lock_inner(&self) -> MutexGuard<'_, RequestsInner> {
90        self.inner.lock().unwrap_or_else(|e| e.into_inner())
91    }
92
93    pub fn is_combining(&self, request: &str) -> bool {
94        self.lock_inner().running.contains(request)
95    }
96
97    pub fn try_begin_publish(self: &Arc<Self>, request: &str) -> Option<PublishGuard> {
98        let mut inner = self.lock_inner();
99        if !inner.publishing.insert(request.to_string()) {
100            return None;
101        }
102        Some(PublishGuard {
103            state: Arc::clone(self),
104            request: request.to_string(),
105        })
106    }
107
108    pub fn wait_for_idle(&self, request: &str) {
109        let mut inner = self.lock_inner();
110        while inner.running.contains(request) {
111            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
112        }
113    }
114
115    pub fn wait_all_idle(&self) {
116        let mut inner = self.lock_inner();
117        while !inner.running.is_empty() {
118            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
119        }
120    }
121}
122
123#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
124pub struct CommitSummary {
125    pub sha: String,
126    pub subject: String,
127}
128
129#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
130#[serde(deny_unknown_fields)]
131pub struct PublishedRecord {
132    #[serde(default, skip_serializing_if = "Option::is_none")]
133    pub pushed_commit: Option<String>,
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub pull_request_url: Option<String>,
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub landed_head: Option<String>,
138}
139
140#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
141#[serde(rename_all = "snake_case")]
142pub enum AttemptResult {
143    Combined,
144    Conflict,
145    CheckFailed,
146    Error,
147}
148
149#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
150#[serde(deny_unknown_fields)]
151pub struct AttemptRecord {
152    pub runs: Vec<CombinedRun>,
153    pub result: AttemptResult,
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub error: Option<String>,
156    pub reported: bool,
157}
158
159#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
160pub struct RequestStatus {
161    pub request: String,
162    pub runs: Vec<String>,
163    pub left_out: Vec<String>,
164    pub state: String,
165    pub waiting_reasons: Vec<String>,
166    pub branch: Option<String>,
167    pub base: Option<String>,
168    pub commits: Vec<CommitSummary>,
169    #[serde(skip_serializing_if = "Option::is_none")]
170    pub check: Option<CombineCheck>,
171    pub conflicting_run: Option<String>,
172    pub conflicting_files: Vec<String>,
173    pub failing_step: Option<String>,
174    pub output_tail: Option<String>,
175    pub error: Option<String>,
176    pub suggested_title: Option<String>,
177    pub suggested_body: Option<String>,
178    pub pushed: bool,
179    pub landed: bool,
180    pub pull_request_url: Option<String>,
181    pub started_by: Option<String>,
182}
183
184#[derive(Clone, Debug, PartialEq, Eq)]
185pub enum RequestActionError {
186    BadRequest(String),
187    NotOwned(String),
188    Conflict(String),
189    Internal(String),
190}
191
192struct StartRunInfo {
193    id: String,
194    request: Option<String>,
195    surface: Option<String>,
196    started_by: Option<String>,
197    base: Option<String>,
198    started_at: u64,
199    is_research: bool,
200}
201
202fn is_research_start(wt_dir: &Path, id: &str, val: &serde_json::Value) -> bool {
203    val.get("research")
204        .and_then(|v| v.as_bool())
205        .unwrap_or(false)
206        || val
207            .get("tags")
208            .and_then(|v| v.as_array())
209            .is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")))
210        || wt_dir.join(format!("{id}.report.md")).exists()
211}
212
213fn parse_start_file(wt_dir: &Path, path: &Path) -> Result<StartRunInfo, String> {
214    let content = std::fs::read_to_string(path)
215        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
216    let val: serde_json::Value = serde_json::from_str(&content)
217        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
218    let file_id = path
219        .file_name()
220        .and_then(|n| n.to_str())
221        .and_then(|n| n.strip_suffix(".start.json"))
222        .filter(|s| !s.is_empty())
223        .ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
224    if let Some(id_val) = val.get("id") {
225        let field_id = id_val.as_str().ok_or_else(|| {
226            format!(
227                "start file {} has non-string id {id_val}, expected {file_id}",
228                path.display()
229            )
230        })?;
231        if field_id != file_id {
232            return Err(format!(
233                "start file {} has id {field_id} which differs from file name id {file_id}",
234                path.display()
235            ));
236        }
237    }
238    let request = match val.get("request") {
239        None | Some(serde_json::Value::Null) => None,
240        Some(serde_json::Value::String(s)) => Some(s.clone()),
241        Some(_) => {
242            return Err(format!(
243                "start file {} has non-string request field",
244                path.display()
245            ));
246        }
247    };
248    let surface = match val.get("surface") {
249        None | Some(serde_json::Value::Null) => None,
250        Some(serde_json::Value::String(s)) => Some(s.clone()),
251        Some(_) => {
252            return Err(format!(
253                "start file {} has non-string surface field",
254                path.display()
255            ));
256        }
257    };
258    let started_by = match val.get("started_by") {
259        None | Some(serde_json::Value::Null) => None,
260        Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s.clone()),
261        Some(_) => {
262            return Err(format!(
263                "{}: started_by must be a surface name",
264                path.display()
265            ));
266        }
267    };
268    let base = match val.get("base") {
269        None | Some(serde_json::Value::Null) => None,
270        Some(serde_json::Value::String(s)) => Some(s.clone()),
271        Some(_) => {
272            return Err(format!(
273                "start file {} has non-string base field",
274                path.display()
275            ));
276        }
277    };
278    let is_research = is_research_start(wt_dir, file_id, &val);
279    let started_at = match val.get("started_at") {
280        Some(v) => v
281            .as_u64()
282            .ok_or_else(|| format!("start file {} has non-numeric started_at", path.display()))?,
283        None => 0,
284    };
285    Ok(StartRunInfo {
286        id: file_id.to_string(),
287        request,
288        surface,
289        started_by,
290        base,
291        started_at,
292        is_research,
293    })
294}
295
296fn list_start_files(wt_dir: &Path) -> Result<Vec<PathBuf>, String> {
297    let read_dir = match std::fs::read_dir(wt_dir) {
298        Ok(rd) => rd,
299        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
300        Err(e) => return Err(format!("failed to read {}: {e}", wt_dir.display())),
301    };
302    let mut entries = Vec::new();
303    for entry in read_dir {
304        let entry =
305            entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
306        let path = entry.path();
307        if path
308            .file_name()
309            .and_then(|n| n.to_str())
310            .is_some_and(|n| n.ends_with(".start.json"))
311        {
312            entries.push(path);
313        }
314    }
315    entries.sort();
316    Ok(entries)
317}
318
319pub(crate) enum RequestOwnership {
320    Owned,
321    OtherSurface,
322    Unowned,
323    NotFound,
324}
325
326pub(crate) enum RequestOwnershipError {
327    Mixed(String),
328    IoOrParse(String),
329}
330
331pub(crate) fn check_request_ownership(
332    surface: &Surface,
333    request: &str,
334) -> Result<RequestOwnership, RequestOwnershipError> {
335    let wt_dir = surface.root.join(".wt");
336    let entries = list_start_files(&wt_dir).map_err(RequestOwnershipError::IoOrParse)?;
337    let mut owners: HashSet<Option<String>> = HashSet::new();
338    let mut started_bys: HashSet<Option<String>> = HashSet::new();
339    for path in entries {
340        let info = parse_start_file(&wt_dir, &path).map_err(RequestOwnershipError::IoOrParse)?;
341        if info.request.as_deref() == Some(request) {
342            owners.insert(info.surface);
343            started_bys.insert(info.started_by);
344        }
345    }
346    if owners.is_empty() {
347        return Ok(RequestOwnership::NotFound);
348    }
349    if owners.len() > 1 {
350        return Err(RequestOwnershipError::Mixed(format!(
351            "request {request} has runs from more than one surface"
352        )));
353    }
354    if started_bys.len() > 1 {
355        return Err(RequestOwnershipError::Mixed(format!(
356            "request {request} has runs started by different surfaces"
357        )));
358    }
359    match owners.into_iter().next().flatten() {
360        Some(owner) if owner == surface.surface_id => Ok(RequestOwnership::Owned),
361        Some(_) => Ok(RequestOwnership::OtherSurface),
362        None => Ok(RequestOwnership::Unowned),
363    }
364}
365
366pub fn owned_run_ids_in(records_dir: &Path, surface_id: &str) -> Result<HashSet<String>, String> {
367    let entries = list_start_files(records_dir)?;
368    let mut ids = HashSet::new();
369    for path in entries {
370        let info = parse_start_file(records_dir, &path)?;
371        if info.surface.as_deref() == Some(surface_id) {
372            ids.insert(info.id);
373        }
374    }
375    Ok(ids)
376}
377
378pub fn owned_run_ids(surface: &Surface) -> Result<HashSet<String>, String> {
379    let wt_dir = surface.root.join(".wt");
380    owned_run_ids_in(&wt_dir, &surface.surface_id)
381}
382
383pub fn request_owner_check(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
384    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
385    match check_request_ownership(surface, request) {
386        Ok(RequestOwnership::Owned) => Ok(()),
387        Ok(RequestOwnership::OtherSurface) => Err(RequestActionError::NotOwned(format!(
388            "request {request} belongs to another surface"
389        ))),
390        Ok(RequestOwnership::Unowned) => Err(RequestActionError::NotOwned(format!(
391            "request {request} was not started by a surface"
392        ))),
393        Ok(RequestOwnership::NotFound) => Err(RequestActionError::Conflict(format!(
394            "request {request} has not been combined"
395        ))),
396        Err(RequestOwnershipError::Mixed(msg)) => Err(RequestActionError::BadRequest(msg)),
397        Err(RequestOwnershipError::IoOrParse(msg)) => Err(RequestActionError::Internal(msg)),
398    }
399}
400
401pub(crate) fn run_owner_check_in(
402    records_dir: &Path,
403    surface_id: &str,
404    run_id: &str,
405) -> Result<(), RequestActionError> {
406    let path = records_dir.join(format!("{run_id}.start.json"));
407    if !path.exists() {
408        return Err(RequestActionError::NotOwned(format!(
409            "run {run_id} was not started by a surface"
410        )));
411    }
412    let info = parse_start_file(records_dir, &path).map_err(RequestActionError::Internal)?;
413    match info.surface.as_deref() {
414        Some(owner) if owner == surface_id => Ok(()),
415        Some(_) => Err(RequestActionError::NotOwned(format!(
416            "run {run_id} belongs to another surface"
417        ))),
418        None => Err(RequestActionError::NotOwned(format!(
419            "run {run_id} was not started by a surface"
420        ))),
421    }
422}
423
424pub(crate) fn run_owner_check(surface: &Surface, run_id: &str) -> Result<(), RequestActionError> {
425    let wt_dir = surface.root.join(".wt");
426    run_owner_check_in(&wt_dir, &surface.surface_id, run_id)
427}
428
429pub fn run_request_id(root: &Path, run_id: &str) -> Result<Option<String>, String> {
430    let wt_dir = root.join(".wt");
431    let path = wt_dir.join(format!("{run_id}.start.json"));
432    if !path.exists() {
433        return Ok(None);
434    }
435    let info = parse_start_file(&wt_dir, &path)?;
436    if info.is_research {
437        return Ok(None);
438    }
439    Ok(info.request)
440}
441
442pub fn request_readiness(root: &Path, request: &str) -> Result<Readiness, String> {
443    crate::dispatch::validate_request_id(request)?;
444    let wt_dir = root.join(".wt");
445    let entries = list_start_files(&wt_dir)?;
446    let mut matched_runs = Vec::new();
447    for path in entries {
448        let info = parse_start_file(&wt_dir, &path)?;
449        if info.is_research {
450            continue;
451        }
452        if info.request.as_deref() == Some(request) {
453            matched_runs.push(info);
454        }
455    }
456    if matched_runs.is_empty() {
457        return Ok(Readiness::Waiting {
458            reasons: vec!["no runs for request".to_string()],
459        });
460    }
461    matched_runs.sort_by(|a, b| {
462        a.started_at
463            .cmp(&b.started_at)
464            .then_with(|| a.id.cmp(&b.id))
465    });
466
467    let mut active_runs = Vec::new();
468    let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
469    for run in matched_runs {
470        let verdict = crate::queue_actions::read_verdict(root, &run.id)?;
471        if crate::combine::is_left_out_verdict(verdict) {
472            left_out_ids.insert(run.id);
473        } else {
474            active_runs.push((run, verdict));
475        }
476    }
477
478    if active_runs.is_empty() {
479        return Ok(Readiness::Redone);
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 { .. } | Readiness::Redone => return Ok(false),
1102        Readiness::Ready => {}
1103    }
1104
1105    if load_published_record(&surface.root, request)?
1106        .landed_head
1107        .is_some()
1108    {
1109        return Ok(false);
1110    }
1111
1112    if let Some(rec) = load_combine_record(&surface.root, request)? {
1113        if request_is_done(&surface.root, request, &rec)? {
1114            return Ok(false);
1115        }
1116    }
1117
1118    let current_runs = resolve_current_run_tips(&surface.root, request)?;
1119
1120    {
1121        let mut inner = surface.requests.lock_inner();
1122        if inner.running.contains(request) {
1123            return Ok(false);
1124        }
1125        if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
1126            if attempt.runs == current_runs {
1127                if !attempt.reported {
1128                    match retry_attempt_message(&surface.root, request, &attempt) {
1129                        Ok(msg) => match surface.session.queue_for_request(request, &msg) {
1130                            Ok(_) => {
1131                                attempt.reported = true;
1132                                write_attempt_record(&surface.root, request, &attempt)?;
1133                            }
1134                            Err(e) => {
1135                                surface.session.record_error(&format!(
1136                                    "failed to queue combine result for {request}: {e}"
1137                                ));
1138                            }
1139                        },
1140                        Err(e) => {
1141                            let msg = format_error_failure(request, &e);
1142                            record_and_report_failure(
1143                                &surface.root,
1144                                &surface.session,
1145                                request,
1146                                attempt.runs,
1147                                AttemptResult::Error,
1148                                Some(e),
1149                                &msg,
1150                            );
1151                        }
1152                    }
1153                }
1154                return Ok(false);
1155            }
1156        }
1157        inner.running.insert(request.to_string());
1158    }
1159
1160    let root = surface.root.clone();
1161    let session = surface.session.clone();
1162    let requests_state = Arc::clone(&surface.requests);
1163    let request_owned = request.to_string();
1164
1165    std::thread::spawn(move || {
1166        let _guard = RunningGuard {
1167            state: Arc::clone(&requests_state),
1168            request: request_owned.clone(),
1169        };
1170        let mut out = Vec::new();
1171        let mut err = Vec::new();
1172        let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
1173
1174        match code {
1175            0 => {
1176                let rec_path = combine_record_path(&root, &request_owned);
1177                let (runs, rec) = match load_combine_record(&root, &request_owned) {
1178                    Ok(Some(rec)) => (sorted_runs(rec.runs.clone()), Some(rec)),
1179                    Ok(None) => {
1180                        session.record_error(&format!(
1181                            "combine record {} is missing after combine for {request_owned}",
1182                            rec_path.display()
1183                        ));
1184                        (current_runs, None)
1185                    }
1186                    Err(e) => {
1187                        session.record_error(&format!(
1188                            "failed to read combine record after combine for {request_owned}: {e}"
1189                        ));
1190                        (current_runs, None)
1191                    }
1192                };
1193                let mut attempt = AttemptRecord {
1194                    runs,
1195                    result: AttemptResult::Combined,
1196                    error: None,
1197                    reported: false,
1198                };
1199                if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1200                    session.record_error(&format!(
1201                        "failed to write attempt record for {request_owned}: {e}"
1202                    ));
1203                }
1204                if let Some(rec) = rec {
1205                    let msg = format_combined_message(&rec);
1206                    match session.queue_for_request(&request_owned, &msg) {
1207                        Ok(_) => {
1208                            attempt.reported = true;
1209                            if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1210                                session.record_error(&format!(
1211                                    "failed to write attempt record for {request_owned}: {e}"
1212                                ));
1213                            }
1214                        }
1215                        Err(e) => {
1216                            session.record_error(&format!(
1217                                "failed to queue combine result for {request_owned}: {e}"
1218                            ));
1219                        }
1220                    }
1221                }
1222            }
1223            1 => match load_combine_record(&root, &request_owned) {
1224                Ok(Some(rec))
1225                    if matches!(
1226                        rec.state,
1227                        CombineState::Conflict | CombineState::CheckFailed
1228                    ) =>
1229                {
1230                    let result = match rec.state {
1231                        CombineState::Conflict => AttemptResult::Conflict,
1232                        CombineState::CheckFailed => AttemptResult::CheckFailed,
1233                        CombineState::Combined => unreachable!(),
1234                    };
1235                    let runs = sorted_runs(rec.runs.clone());
1236                    let rec_path = combine_record_path(&root, &request_owned);
1237                    match format_record_failure(&rec, &rec_path) {
1238                        Ok(msg) => {
1239                            record_and_report_failure(
1240                                &root,
1241                                &session,
1242                                &request_owned,
1243                                runs,
1244                                result,
1245                                None,
1246                                &msg,
1247                            );
1248                        }
1249                        Err(e) => {
1250                            let msg = format_error_failure(&request_owned, &e);
1251                            record_and_report_failure(
1252                                &root,
1253                                &session,
1254                                &request_owned,
1255                                runs,
1256                                AttemptResult::Error,
1257                                Some(e),
1258                                &msg,
1259                            );
1260                        }
1261                    }
1262                }
1263                Ok(_) => {
1264                    let err_text = String::from_utf8_lossy(&err).trim().to_string();
1265                    let err_text = if err_text.is_empty() {
1266                        format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
1267                    } else {
1268                        err_text
1269                    };
1270                    let msg = format_error_failure(&request_owned, &err_text);
1271                    record_and_report_failure(
1272                        &root,
1273                        &session,
1274                        &request_owned,
1275                        current_runs,
1276                        AttemptResult::Error,
1277                        Some(err_text),
1278                        &msg,
1279                    );
1280                }
1281                Err(e) => {
1282                    let msg = format_error_failure(&request_owned, &e);
1283                    record_and_report_failure(
1284                        &root,
1285                        &session,
1286                        &request_owned,
1287                        current_runs,
1288                        AttemptResult::Error,
1289                        Some(e),
1290                        &msg,
1291                    );
1292                }
1293            },
1294            other => {
1295                let err_text = String::from_utf8_lossy(&err).trim().to_string();
1296                let err_text = if err_text.is_empty() {
1297                    format!("combine exited with status {other}")
1298                } else {
1299                    err_text
1300                };
1301                let msg = format_error_failure(&request_owned, &err_text);
1302                record_and_report_failure(
1303                    &root,
1304                    &session,
1305                    &request_owned,
1306                    current_runs,
1307                    AttemptResult::Error,
1308                    Some(err_text),
1309                    &msg,
1310                );
1311            }
1312        }
1313    });
1314
1315    Ok(true)
1316}
1317
1318fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
1319    let mut commits = Vec::with_capacity(shas.len());
1320    for sha in shas {
1321        let subject = git_commit_subject(root, sha)?;
1322        commits.push(CommitSummary {
1323            sha: sha.clone(),
1324            subject,
1325        });
1326    }
1327    Ok(commits)
1328}
1329
1330fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
1331    if commits.is_empty() {
1332        return (None, None);
1333    }
1334    let title = commits[0].subject.clone();
1335    let body = commits
1336        .iter()
1337        .map(|c| c.subject.as_str())
1338        .collect::<Vec<_>>()
1339        .join("\n");
1340    (Some(title), Some(body))
1341}
1342
1343struct RequestGroup {
1344    request: String,
1345    max_started_at: u64,
1346    runs: Vec<(u64, String)>,
1347    owners: HashSet<Option<String>>,
1348    started_bys: HashSet<Option<String>>,
1349}
1350
1351pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
1352    let wt_dir = surface.root.join(".wt");
1353    let entries = list_start_files(&wt_dir)?;
1354    let mut groups: BTreeMap<String, RequestGroup> = BTreeMap::new();
1355    for path in entries {
1356        let info = parse_start_file(&wt_dir, &path)?;
1357        let Some(req_id) = info.request else {
1358            continue;
1359        };
1360        let entry = groups
1361            .entry(req_id.clone())
1362            .or_insert_with(|| RequestGroup {
1363                request: req_id,
1364                max_started_at: 0,
1365                runs: Vec::new(),
1366                owners: HashSet::new(),
1367                started_bys: HashSet::new(),
1368            });
1369        entry.owners.insert(info.surface);
1370        entry.started_bys.insert(info.started_by);
1371        if info.is_research {
1372            continue;
1373        }
1374        if info.started_at > entry.max_started_at {
1375            entry.max_started_at = info.started_at;
1376        }
1377        entry.runs.push((info.started_at, info.id));
1378    }
1379
1380    let mut ordered: Vec<RequestGroup> = Vec::new();
1381    for group in groups.into_values() {
1382        if group.owners.len() > 1 {
1383            return Err(format!(
1384                "request {} has runs from more than one surface",
1385                group.request
1386            ));
1387        }
1388        if group.started_bys.len() > 1 {
1389            return Err(format!(
1390                "request {} has runs started by different surfaces",
1391                group.request
1392            ));
1393        }
1394        if group.runs.is_empty() {
1395            continue;
1396        }
1397        let owner = group.owners.iter().next().and_then(|o| o.as_deref());
1398        if owner != Some(surface.surface_id.as_str()) {
1399            continue;
1400        }
1401        ordered.push(group);
1402    }
1403    ordered.sort_by(|a, b| {
1404        b.max_started_at
1405            .cmp(&a.max_started_at)
1406            .then_with(|| b.request.cmp(&a.request))
1407    });
1408
1409    let busy = conversation_busy(surface);
1410    let mut result = Vec::with_capacity(ordered.len());
1411    for mut group in ordered {
1412        group
1413            .runs
1414            .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1415        let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
1416        let started_by = group.started_bys.into_iter().next().flatten();
1417        result.push(build_request_status(
1418            surface,
1419            group.request,
1420            run_ids,
1421            started_by,
1422            busy,
1423        ));
1424    }
1425    Ok(result)
1426}
1427
1428fn build_request_status(
1429    surface: &Surface,
1430    request: String,
1431    runs: Vec<String>,
1432    started_by: Option<String>,
1433    conversation_busy: bool,
1434) -> RequestStatus {
1435    let is_combining = surface.requests.is_combining(&request);
1436
1437    let record_res = load_combine_record(&surface.root, &request);
1438    let published_res = load_published_record(&surface.root, &request);
1439    let attempt_res = load_attempt_record(&surface.root, &request);
1440    let left_out_res: Result<Vec<String>, String> = runs
1441        .iter()
1442        .filter_map(
1443            |id| match crate::combine::is_run_left_out(&surface.root, id) {
1444                Ok(true) => Some(Ok(id.clone())),
1445                Ok(false) => None,
1446                Err(e) => Some(Err(e)),
1447            },
1448        )
1449        .collect();
1450    let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
1451
1452    let (pushed, landed, pull_request_url) = match (&published_res, &record_res) {
1453        (Ok(p), Ok(Some(rec))) => (
1454            rec.state == CombineState::Combined && is_record_pushed(p, rec),
1455            p.landed_head.is_some(),
1456            p.pull_request_url.clone(),
1457        ),
1458        (Ok(p), _) => (false, p.landed_head.is_some(), p.pull_request_url.clone()),
1459        (Err(_), _) => (false, false, None),
1460    };
1461
1462    let mut status = RequestStatus {
1463        request: request.clone(),
1464        runs,
1465        left_out,
1466        state: String::new(),
1467        waiting_reasons: Vec::new(),
1468        branch: None,
1469        base: None,
1470        commits: Vec::new(),
1471        check: None,
1472        conflicting_run: None,
1473        conflicting_files: Vec::new(),
1474        failing_step: None,
1475        output_tail: None,
1476        error: None,
1477        suggested_title: None,
1478        suggested_body: None,
1479        pushed,
1480        landed,
1481        pull_request_url,
1482        started_by,
1483    };
1484
1485    if is_combining {
1486        status.state = "combining".to_string();
1487        if let Ok(Some(rec)) = record_res {
1488            populate_record_metadata(&surface.root, &rec, &mut status);
1489        }
1490        return status;
1491    }
1492
1493    if let Err(e) = left_out_res {
1494        status.state = "error".to_string();
1495        status.error = Some(e);
1496        return status;
1497    }
1498
1499    let published = match published_res {
1500        Ok(p) => p,
1501        Err(e) => {
1502            status.state = "error".to_string();
1503            status.error = Some(e);
1504            return status;
1505        }
1506    };
1507
1508    let attempt = match attempt_res {
1509        Ok(a) => a,
1510        Err(e) => {
1511            status.state = "error".to_string();
1512            status.error = Some(e);
1513            return status;
1514        }
1515    };
1516
1517    let record = match record_res {
1518        Ok(r) => r,
1519        Err(e) => {
1520            status.state = "error".to_string();
1521            status.error = Some(e);
1522            return status;
1523        }
1524    };
1525
1526    if published.landed_head.is_some() {
1527        status.state = "landed".to_string();
1528        if let Some(ref rec) = record {
1529            populate_record_metadata(&surface.root, rec, &mut status);
1530        }
1531        return status;
1532    }
1533
1534    match request_readiness(&surface.root, &request) {
1535        Err(e) => {
1536            status.state = "error".to_string();
1537            status.error = Some(e);
1538            status
1539        }
1540        Ok(Readiness::Redone) => {
1541            status.state = "redone".to_string();
1542            if let Some(ref rec) = record {
1543                populate_record_metadata(&surface.root, rec, &mut status);
1544            }
1545            status
1546        }
1547        Ok(Readiness::Waiting { reasons }) => {
1548            status.state = "waiting".to_string();
1549            status.waiting_reasons = reasons;
1550            if let Some(ref rec) = record {
1551                populate_record_metadata(&surface.root, rec, &mut status);
1552            }
1553            status
1554        }
1555        Ok(Readiness::Ready) => {
1556            if let Some(ref rec) = record {
1557                match request_is_done(&surface.root, &request, rec) {
1558                    Ok(true) => {
1559                        status.state = "done".to_string();
1560                        populate_record_metadata(&surface.root, rec, &mut status);
1561                        return status;
1562                    }
1563                    Ok(false) => {}
1564                    Err(e) => {
1565                        status.state = "error".to_string();
1566                        status.error = Some(e);
1567                        return status;
1568                    }
1569                }
1570            }
1571            let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1572                Ok(t) => t,
1573                Err(e) => {
1574                    status.state = "error".to_string();
1575                    status.error = Some(e);
1576                    return status;
1577                }
1578            };
1579            if let Some(ref att) = attempt {
1580                if att.runs == current_runs && att.result == AttemptResult::Error {
1581                    status.state = "error".to_string();
1582                    status.error = att.error.clone();
1583                    return status;
1584                }
1585            }
1586            let Some(rec) = record else {
1587                status.state = "waiting".to_string();
1588                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1589                return status;
1590            };
1591            if !record_runs_match_tips(&rec, &current_runs) {
1592                status.state = "waiting".to_string();
1593                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1594                populate_record_metadata(&surface.root, &rec, &mut status);
1595                return status;
1596            }
1597
1598            let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1599                Ok(c) => c,
1600                Err(e) => {
1601                    status.state = "error".to_string();
1602                    status.error = Some(e);
1603                    return status;
1604                }
1605            };
1606
1607            status.branch = Some(rec.branch.clone());
1608            status.base = Some(rec.base.clone());
1609            status.commits = commits;
1610            status.check = Some(rec.check);
1611            status.conflicting_run = rec.conflicting_run.clone();
1612            status.conflicting_files = rec.conflicting_files.clone();
1613            status.failing_step = rec.failing_step.clone();
1614            status.output_tail = rec.output_tail.clone();
1615
1616            match rec.state {
1617                CombineState::Combined => {
1618                    if branch_matches_record(&surface.root, &rec) {
1619                        status.state = "combined".to_string();
1620                        let (title, body) = suggested_pr_fields(&status.commits);
1621                        status.suggested_title = title;
1622                        status.suggested_body = body;
1623                    } else {
1624                        status.state = "waiting".to_string();
1625                        status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1626                    }
1627                }
1628                CombineState::Conflict => {
1629                    status.state = "conflict".to_string();
1630                }
1631                CombineState::CheckFailed => {
1632                    status.state = "check_failed".to_string();
1633                }
1634            }
1635            status
1636        }
1637    }
1638}
1639
1640fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1641    status.branch = Some(rec.branch.clone());
1642    status.base = Some(rec.base.clone());
1643    if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1644        status.commits = commits;
1645    }
1646    status.check = Some(rec.check);
1647    status.conflicting_run = rec.conflicting_run.clone();
1648    status.conflicting_files = rec.conflicting_files.clone();
1649    status.failing_step = rec.failing_step.clone();
1650    status.output_tail = rec.output_tail.clone();
1651}
1652
1653pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1654    request_owner_check(surface, request)?;
1655    if surface.requests.is_combining(request) {
1656        return Err(RequestActionError::Conflict(format!(
1657            "request {request} is currently combining"
1658        )));
1659    }
1660    let record = load_combine_record(&surface.root, request)
1661        .map_err(RequestActionError::Internal)?
1662        .ok_or_else(|| {
1663            RequestActionError::Conflict(format!("request {request} has not been combined"))
1664        })?;
1665    if record.state != CombineState::Combined {
1666        return Err(RequestActionError::Conflict(format!(
1667            "request {request} is not combined (state: {:?})",
1668            record.state
1669        )));
1670    }
1671    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1672        return Err(RequestActionError::Conflict(format!(
1673            "request {request} is done: its branches were already merged and removed"
1674        )));
1675    }
1676
1677    let mut published =
1678        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1679    if published.landed_head.is_some() {
1680        return Err(RequestActionError::Conflict(format!(
1681            "request {request} is already landed"
1682        )));
1683    }
1684
1685    match surface.publisher.push_branch(&surface.root, &record.branch) {
1686        Ok(()) => {
1687            let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1688            let branch_commit =
1689                git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1690            published.pushed_commit = Some(branch_commit);
1691            write_published_record(&surface.root, request, &published)
1692                .map_err(RequestActionError::Internal)?;
1693            if let Err(e) = surface.session.record_decision(
1694                request,
1695                "push",
1696                Some(&format!("pushed {}", record.branch)),
1697                None,
1698            ) {
1699                surface.session.record_error(&format!(
1700                    "failed to record push decision for {request}: {e}"
1701                ));
1702            }
1703            Ok(())
1704        }
1705        Err(e) => {
1706            surface.session.record_error(&format!(
1707                "push failed for {request} ({}): {e}",
1708                record.branch
1709            ));
1710            Err(RequestActionError::Internal(e))
1711        }
1712    }
1713}
1714
1715pub fn open_request_pull_request(
1716    surface: &Surface,
1717    request: &str,
1718    title: &str,
1719    body: &str,
1720) -> Result<String, RequestActionError> {
1721    request_owner_check(surface, request)?;
1722    let trimmed_title = title.trim();
1723    if trimmed_title.is_empty() {
1724        return Err(RequestActionError::BadRequest(
1725            "field title must not be empty".to_string(),
1726        ));
1727    }
1728    if surface.requests.is_combining(request) {
1729        return Err(RequestActionError::Conflict(format!(
1730            "request {request} is currently combining"
1731        )));
1732    }
1733    let record = load_combine_record(&surface.root, request)
1734        .map_err(RequestActionError::Internal)?
1735        .ok_or_else(|| {
1736            RequestActionError::Conflict(format!("request {request} has not been combined"))
1737        })?;
1738    if record.state != CombineState::Combined {
1739        return Err(RequestActionError::Conflict(format!(
1740            "request {request} is not combined (state: {:?})",
1741            record.state
1742        )));
1743    }
1744    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1745        return Err(RequestActionError::Conflict(format!(
1746            "request {request} is done: its branches were already merged and removed"
1747        )));
1748    }
1749
1750    let mut published =
1751        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1752    if published.landed_head.is_some() {
1753        return Err(RequestActionError::Conflict(format!(
1754            "request {request} is already landed"
1755        )));
1756    }
1757    if !is_record_pushed(&published, &record) {
1758        return Err(RequestActionError::Conflict(format!(
1759            "branch {} must be pushed before opening a pull request",
1760            record.branch
1761        )));
1762    }
1763
1764    match surface
1765        .publisher
1766        .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1767    {
1768        Ok(url) => {
1769            published.pull_request_url = Some(url.clone());
1770            write_published_record(&surface.root, request, &published)
1771                .map_err(RequestActionError::Internal)?;
1772            if let Err(e) =
1773                surface
1774                    .session
1775                    .record_decision(request, "pull_request", Some(&url), None)
1776            {
1777                surface.session.record_error(&format!(
1778                    "failed to record pull_request decision for {request}: {e}"
1779                ));
1780            }
1781            Ok(url)
1782        }
1783        Err(e) => {
1784            surface.session.record_error(&format!(
1785                "pull request failed for {request} ({}): {e}",
1786                record.branch
1787            ));
1788            Err(RequestActionError::Internal(e))
1789        }
1790    }
1791}
1792
1793fn request_action_error_message(err: RequestActionError) -> String {
1794    match err {
1795        RequestActionError::BadRequest(msg)
1796        | RequestActionError::NotOwned(msg)
1797        | RequestActionError::Conflict(msg)
1798        | RequestActionError::Internal(msg) => msg,
1799    }
1800}
1801
1802pub fn verify_auto_publish_branch(
1803    root: &Path,
1804    request: &str,
1805    branch: &str,
1806) -> Result<String, String> {
1807    let record = load_combine_record(root, request)?
1808        .ok_or_else(|| format!("combine record for request {request} is missing"))?;
1809    let expected = combine_record_tip(&record).to_string();
1810    crate::publish::verify_branch_commit(root, branch, &expected)?;
1811    Ok(expected)
1812}
1813
1814pub fn publish_request_with_approval(
1815    surface: &Surface,
1816    approver: &dyn blyte_agent::approval::Approver,
1817    request: &str,
1818    title: &str,
1819    body: &str,
1820) -> Result<String, String> {
1821    if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
1822        return Err(format!(
1823            "cannot publish during a turn started by another surface ({started_by})"
1824        ));
1825    }
1826    let trimmed_title = title.trim();
1827    if trimmed_title.is_empty() {
1828        return Err("publish title must not be blank".to_string());
1829    }
1830    if title.chars().count() > blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS {
1831        return Err(format!(
1832            "publish title must be at most {} characters",
1833            blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS
1834        ));
1835    }
1836    if body.len() > blyte_agent::tools::PUBLISH_BODY_MAX_BYTES {
1837        return Err(format!(
1838            "publish body must be at most {} bytes",
1839            blyte_agent::tools::PUBLISH_BODY_MAX_BYTES
1840        ));
1841    }
1842    crate::dispatch::validate_request_id(request)?;
1843    match check_request_ownership(surface, request) {
1844        Ok(RequestOwnership::Owned) => {}
1845        Ok(RequestOwnership::OtherSurface) => {
1846            return Err(format!("request {request} belongs to another surface"));
1847        }
1848        Ok(RequestOwnership::Unowned) => {
1849            return Err(format!("request {request} was not started by this surface"));
1850        }
1851        Ok(RequestOwnership::NotFound) => {
1852            return Err(format!("unknown request {request}"));
1853        }
1854        Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
1855            return Err(msg);
1856        }
1857    }
1858    if surface.requests.is_combining(request) {
1859        return Err(format!("request {request} is still combining"));
1860    }
1861    let statuses = list_requests(surface)?;
1862    let status = statuses
1863        .into_iter()
1864        .find(|s| s.request == request)
1865        .ok_or_else(|| format!("unknown request {request}"))?;
1866    if status.state != "combined" {
1867        return Err(format!(
1868            "request {request} is not ready to publish (state: {})",
1869            status.state
1870        ));
1871    }
1872    if status.pushed {
1873        if let Some(url) = status.pull_request_url {
1874            return Err(format!(
1875                "request {request} already has an open pull request ({url})"
1876            ));
1877        }
1878    }
1879    let publish_approval = crate::config::load_with_fallback(&surface.root)?
1880        .map(|(cfg, _)| cfg.surface.publish)
1881        .unwrap_or_default();
1882
1883    let branch = status
1884        .branch
1885        .ok_or_else(|| format!("request {request} has no combined branch"))?;
1886
1887    let (_publish_guard, commit) = match publish_approval {
1888        crate::config::PublishApproval::Ask => {
1889            if surface.session.has_pending_publish(request) {
1890                return Err(format!(
1891                    "a publish approval for request {request} is already waiting"
1892                ));
1893            }
1894            let publish_guard = surface.requests.try_begin_publish(request).ok_or_else(|| {
1895                format!("a publish approval for request {request} is already waiting")
1896            })?;
1897            if surface.session.has_pending_publish(request) {
1898                return Err(format!(
1899                    "a publish approval for request {request} is already waiting"
1900                ));
1901            }
1902
1903            let remote_url = crate::publish::origin_remote_url(&surface.root)?;
1904            let base = crate::publish::default_branch(&surface.root)?;
1905            let commit = crate::publish::branch_commit(&surface.root, &branch)?;
1906            let commits = crate::publish::branch_commit_subjects(&surface.root, &branch, &base)?;
1907
1908            let details = blyte_agent::approval::PublishDetails {
1909                request: request.to_string(),
1910                remote_url,
1911                branch: branch.clone(),
1912                base,
1913                commit: commit.clone(),
1914                commits,
1915                title: trimmed_title.to_string(),
1916                body: body.to_string(),
1917            };
1918
1919            match approver.ask_publish(&details) {
1920                blyte_agent::approval::Approval::Approved => {}
1921                blyte_agent::approval::Approval::Denied => {
1922                    return Err("the user declined".to_string());
1923                }
1924                blyte_agent::approval::Approval::Unavailable => {
1925                    return Err("publish approval is not available here".to_string());
1926                }
1927            }
1928
1929            crate::publish::verify_branch_commit(&surface.root, &branch, &commit)?;
1930            (Some(publish_guard), commit)
1931        }
1932        crate::config::PublishApproval::Auto => {
1933            let publish_guard = surface
1934                .requests
1935                .try_begin_publish(request)
1936                .ok_or_else(|| format!("request {request} is already being published"))?;
1937            let commit = verify_auto_publish_branch(&surface.root, request, &branch)?;
1938            (Some(publish_guard), commit)
1939        }
1940    };
1941
1942    let published = load_published_record(&surface.root, request)?;
1943    let already_pushed = published.pushed_commit.as_deref() == Some(commit.as_str());
1944    if !already_pushed {
1945        push_request(surface, request).map_err(request_action_error_message)?;
1946    }
1947
1948    match open_request_pull_request(surface, request, trimmed_title, body) {
1949        Ok(url) => {
1950            let mut notice = format!("Published {request}: branch {branch}, {url}");
1951            if publish_approval == crate::config::PublishApproval::Auto {
1952                notice.push_str(" (not asked: [surface] publish = \"auto\")");
1953            }
1954            if let Err(e) = surface
1955                .session
1956                .record_decision(request, "publish", Some(&notice), None)
1957            {
1958                surface.session.record_error(&format!(
1959                    "failed to record publish notice for {request}: {e}"
1960                ));
1961            }
1962            Ok(url)
1963        }
1964        Err(err) => {
1965            let detail = request_action_error_message(err);
1966            if already_pushed {
1967                Err(format!(
1968                    "branch {branch} was already pushed at {commit}, but opening the pull request failed: {detail}"
1969                ))
1970            } else {
1971                Err(format!(
1972                    "push succeeded for {branch} ({commit}), but opening the pull request failed: {detail}"
1973                ))
1974            }
1975        }
1976    }
1977}
1978
1979pub struct SurfacePublishTool {
1980    surface: Arc<Surface>,
1981    approver: Arc<dyn blyte_agent::approval::Approver>,
1982}
1983
1984impl SurfacePublishTool {
1985    pub fn new(surface: Arc<Surface>) -> Self {
1986        let approver: Arc<dyn blyte_agent::approval::Approver> = surface.session.approver();
1987        Self { surface, approver }
1988    }
1989}
1990
1991impl blyte_agent::tools::PublishTool for SurfacePublishTool {
1992    fn publish(&self, request: &str, title: &str, body: &str) -> Result<String, String> {
1993        publish_request_with_approval(&self.surface, self.approver.as_ref(), request, title, body)
1994    }
1995}