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::{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}
55
56pub struct RequestsState {
57    inner: Mutex<RequestsInner>,
58    cv: Condvar,
59}
60
61impl Default for RequestsState {
62    fn default() -> Self {
63        Self::new()
64    }
65}
66
67impl RequestsState {
68    pub fn new() -> Self {
69        Self {
70            inner: Mutex::new(RequestsInner::default()),
71            cv: Condvar::new(),
72        }
73    }
74
75    fn lock_inner(&self) -> MutexGuard<'_, RequestsInner> {
76        self.inner.lock().unwrap_or_else(|e| e.into_inner())
77    }
78
79    pub fn is_combining(&self, request: &str) -> bool {
80        self.lock_inner().running.contains(request)
81    }
82
83    pub fn wait_for_idle(&self, request: &str) {
84        let mut inner = self.lock_inner();
85        while inner.running.contains(request) {
86            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
87        }
88    }
89
90    pub fn wait_all_idle(&self) {
91        let mut inner = self.lock_inner();
92        while !inner.running.is_empty() {
93            inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
94        }
95    }
96}
97
98#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
99pub struct CommitSummary {
100    pub sha: String,
101    pub subject: String,
102}
103
104#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(deny_unknown_fields)]
106pub struct PublishedRecord {
107    #[serde(default, skip_serializing_if = "Option::is_none")]
108    pub pushed_commit: Option<String>,
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub pull_request_url: Option<String>,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "snake_case")]
115pub enum AttemptResult {
116    Combined,
117    Conflict,
118    CheckFailed,
119    Error,
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
123#[serde(deny_unknown_fields)]
124pub struct AttemptRecord {
125    pub runs: Vec<CombinedRun>,
126    pub result: AttemptResult,
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub error: Option<String>,
129    pub reported: bool,
130}
131
132#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
133pub struct RequestStatus {
134    pub request: String,
135    pub runs: Vec<String>,
136    pub left_out: Vec<String>,
137    pub state: String,
138    pub waiting_reasons: Vec<String>,
139    pub branch: Option<String>,
140    pub base: Option<String>,
141    pub commits: Vec<CommitSummary>,
142    pub conflicting_run: Option<String>,
143    pub conflicting_files: Vec<String>,
144    pub failing_step: Option<String>,
145    pub output_tail: Option<String>,
146    pub error: Option<String>,
147    pub suggested_title: Option<String>,
148    pub suggested_body: Option<String>,
149    pub pushed: bool,
150    pub pull_request_url: Option<String>,
151}
152
153#[derive(Clone, Debug, PartialEq, Eq)]
154pub enum RequestActionError {
155    BadRequest(String),
156    Conflict(String),
157    Internal(String),
158}
159
160struct StartRunInfo {
161    id: String,
162    request: Option<String>,
163    base: Option<String>,
164    started_at: u64,
165    is_research: bool,
166}
167
168fn is_research_start(wt_dir: &Path, id: &str, val: &serde_json::Value) -> bool {
169    val.get("research")
170        .and_then(|v| v.as_bool())
171        .unwrap_or(false)
172        || val
173            .get("tags")
174            .and_then(|v| v.as_array())
175            .is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")))
176        || wt_dir.join(format!("{id}.report.md")).exists()
177}
178
179fn parse_start_file(wt_dir: &Path, path: &Path) -> Result<StartRunInfo, String> {
180    let content = std::fs::read_to_string(path)
181        .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
182    let val: serde_json::Value = serde_json::from_str(&content)
183        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
184    let file_id = path
185        .file_name()
186        .and_then(|n| n.to_str())
187        .and_then(|n| n.strip_suffix(".start.json"))
188        .filter(|s| !s.is_empty())
189        .ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
190    if let Some(id_val) = val.get("id") {
191        let field_id = id_val.as_str().ok_or_else(|| {
192            format!(
193                "start file {} has non-string id {id_val}, expected {file_id}",
194                path.display()
195            )
196        })?;
197        if field_id != file_id {
198            return Err(format!(
199                "start file {} has id {field_id} which differs from file name id {file_id}",
200                path.display()
201            ));
202        }
203    }
204    let request = match val.get("request") {
205        None | Some(serde_json::Value::Null) => None,
206        Some(serde_json::Value::String(s)) => Some(s.clone()),
207        Some(_) => {
208            return Err(format!(
209                "start file {} has non-string request field",
210                path.display()
211            ));
212        }
213    };
214    let base = match val.get("base") {
215        None | Some(serde_json::Value::Null) => None,
216        Some(serde_json::Value::String(s)) => Some(s.clone()),
217        Some(_) => {
218            return Err(format!(
219                "start file {} has non-string base field",
220                path.display()
221            ));
222        }
223    };
224    let is_research = is_research_start(wt_dir, file_id, &val);
225    let started_at = match val.get("started_at") {
226        Some(v) => v
227            .as_u64()
228            .ok_or_else(|| format!("start file {} has non-numeric started_at", path.display()))?,
229        None => 0,
230    };
231    Ok(StartRunInfo {
232        id: file_id.to_string(),
233        request,
234        base,
235        started_at,
236        is_research,
237    })
238}
239
240fn list_start_files(wt_dir: &Path) -> Result<Vec<PathBuf>, String> {
241    let read_dir = match std::fs::read_dir(wt_dir) {
242        Ok(rd) => rd,
243        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
244        Err(e) => return Err(format!("failed to read {}: {e}", wt_dir.display())),
245    };
246    let mut entries = Vec::new();
247    for entry in read_dir {
248        let entry =
249            entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
250        let path = entry.path();
251        if path
252            .file_name()
253            .and_then(|n| n.to_str())
254            .is_some_and(|n| n.ends_with(".start.json"))
255        {
256            entries.push(path);
257        }
258    }
259    entries.sort();
260    Ok(entries)
261}
262
263pub fn run_request_id(root: &Path, run_id: &str) -> Result<Option<String>, String> {
264    let wt_dir = root.join(".wt");
265    let path = wt_dir.join(format!("{run_id}.start.json"));
266    if !path.exists() {
267        return Ok(None);
268    }
269    let info = parse_start_file(&wt_dir, &path)?;
270    if info.is_research {
271        return Ok(None);
272    }
273    Ok(info.request)
274}
275
276pub fn request_readiness(root: &Path, request: &str) -> Result<Readiness, String> {
277    crate::dispatch::validate_request_id(request)?;
278    let wt_dir = root.join(".wt");
279    let entries = list_start_files(&wt_dir)?;
280    let mut matched_runs = Vec::new();
281    for path in entries {
282        let info = parse_start_file(&wt_dir, &path)?;
283        if info.is_research {
284            continue;
285        }
286        if info.request.as_deref() == Some(request) {
287            matched_runs.push(info);
288        }
289    }
290    if matched_runs.is_empty() {
291        return Ok(Readiness::Waiting {
292            reasons: vec!["no runs for request".to_string()],
293        });
294    }
295    matched_runs.sort_by(|a, b| {
296        a.started_at
297            .cmp(&b.started_at)
298            .then_with(|| a.id.cmp(&b.id))
299    });
300
301    let mut active_runs = Vec::new();
302    let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
303    for run in matched_runs {
304        let verdict = crate::queue_actions::read_verdict(root, &run.id)?;
305        if crate::combine::is_left_out_verdict(verdict) {
306            left_out_ids.insert(run.id);
307        } else {
308            active_runs.push((run, verdict));
309        }
310    }
311
312    if active_runs.is_empty() {
313        return Ok(Readiness::Waiting {
314            reasons: vec!["every run was redone".to_string()],
315        });
316    }
317
318    let left_out_refs: BTreeSet<&str> = left_out_ids.iter().map(String::as_str).collect();
319    for (run, _) in &active_runs {
320        crate::combine::check_not_based_on_left_out(
321            root,
322            &run.id,
323            run.base.as_deref(),
324            &left_out_refs,
325        )?;
326    }
327
328    let mut reasons = Vec::new();
329    for (run, verdict) in active_runs {
330        let id = &run.id;
331        let summary_path = wt_dir.join(format!("{id}.json"));
332        let outcome = match std::fs::read_to_string(&summary_path) {
333            Ok(raw) => {
334                let val: serde_json::Value = serde_json::from_str(&raw)
335                    .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
336                let outcome = val
337                    .get("outcome")
338                    .and_then(|v| v.as_str())
339                    .ok_or_else(|| {
340                        format!(
341                            "summary file {} is missing string outcome",
342                            summary_path.display()
343                        )
344                    })?
345                    .to_string();
346                if outcome != "verified" {
347                    reasons.push(format!("{id}: {outcome}"));
348                }
349                Some(outcome)
350            }
351            Err(e) if e.kind() == ErrorKind::NotFound => {
352                reasons.push(format!("{id}: unfinished"));
353                None
354            }
355            Err(e) => {
356                return Err(format!("failed to read {}: {e}", summary_path.display()));
357            }
358        };
359
360        let checks_path = wt_dir.join(format!("{id}.checks.json"));
361        let (checks_recorded, flags) = crate::replay::read_checks(&checks_path)
362            .map_err(|e| format!("{}: {e}", checks_path.display()))?;
363
364        if crate::queue_actions::read_hold(root, id)?.is_some() {
365            reasons.push(format!("{id}: on hold"));
366        }
367
368        if let Some(ref outcome_str) = outcome {
369            if outcome_str == "verified" {
370                if !checks_recorded {
371                    reasons.push(format!("{id}: no checks file"));
372                } else {
373                    let card =
374                        crate::replay::card_for_run(false, outcome_str, checks_recorded, &flags);
375                    let cleared_by_verdict = matches!(
376                        verdict,
377                        Some(ReviewVerdict::Accepted | ReviewVerdict::Fixed)
378                    );
379                    if card != "clean" && !cleared_by_verdict {
380                        reasons.push(format!("{id}: flagged ({})", flags.join("; ")));
381                    }
382                }
383            }
384        }
385    }
386
387    if reasons.is_empty() {
388        Ok(Readiness::Ready)
389    } else {
390        Ok(Readiness::Waiting { reasons })
391    }
392}
393
394fn combine_record_path(root: &Path, request: &str) -> PathBuf {
395    root.join(".wt")
396        .join("combined")
397        .join(format!("{request}.json"))
398}
399
400fn attempt_record_path(root: &Path, request: &str) -> PathBuf {
401    root.join(".wt")
402        .join("combined")
403        .join(format!("{request}.attempt.json"))
404}
405
406fn published_record_path(root: &Path, request: &str) -> PathBuf {
407    root.join(".wt")
408        .join("combined")
409        .join(format!("{request}.published.json"))
410}
411
412fn write_json_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<(), String> {
413    if let Some(parent) = path.parent() {
414        std::fs::create_dir_all(parent)
415            .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
416    }
417    let mut json = serde_json::to_string_pretty(value)
418        .map_err(|e| format!("failed to serialize {label}: {e}"))?;
419    json.push('\n');
420    let mut tmp_name = path.as_os_str().to_os_string();
421    let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
422    tmp_name.push(format!(".tmp.{}.{seq}", std::process::id()));
423    let tmp_path = PathBuf::from(tmp_name);
424    std::fs::write(&tmp_path, json)
425        .map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
426    std::fs::rename(&tmp_path, path).map_err(|e| {
427        let _ = std::fs::remove_file(&tmp_path);
428        format!(
429            "failed to rename {} to {}: {e}",
430            tmp_path.display(),
431            path.display()
432        )
433    })
434}
435
436pub fn load_combine_record(root: &Path, request: &str) -> Result<Option<CombineRecord>, String> {
437    let path = combine_record_path(root, request);
438    let raw = match std::fs::read_to_string(&path) {
439        Ok(s) => s,
440        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
441        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
442    };
443    let record: CombineRecord = serde_json::from_str(&raw)
444        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
445    Ok(Some(record))
446}
447
448pub fn load_attempt_record(root: &Path, request: &str) -> Result<Option<AttemptRecord>, String> {
449    let path = attempt_record_path(root, request);
450    let raw = match std::fs::read_to_string(&path) {
451        Ok(s) => s,
452        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
453        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
454    };
455    let record: AttemptRecord = serde_json::from_str(&raw)
456        .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
457    if record.result == AttemptResult::Error
458        && record.error.as_deref().is_none_or(|s| s.trim().is_empty())
459    {
460        return Err(format!(
461            "invalid attempt file {}: result error is missing error text",
462            path.display()
463        ));
464    }
465    Ok(Some(record))
466}
467
468pub fn write_attempt_record(
469    root: &Path,
470    request: &str,
471    record: &AttemptRecord,
472) -> Result<(), String> {
473    let path = attempt_record_path(root, request);
474    write_json_atomic(&path, record, "attempt record")
475}
476
477pub fn load_published_record(root: &Path, request: &str) -> Result<PublishedRecord, String> {
478    let path = published_record_path(root, request);
479    let raw = match std::fs::read_to_string(&path) {
480        Ok(s) => s,
481        Err(e) if e.kind() == ErrorKind::NotFound => return Ok(PublishedRecord::default()),
482        Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
483    };
484    serde_json::from_str(&raw).map_err(|e| format!("failed to parse {}: {e}", path.display()))
485}
486
487pub fn write_published_record(
488    root: &Path,
489    request: &str,
490    record: &PublishedRecord,
491) -> Result<(), String> {
492    let path = published_record_path(root, request);
493    write_json_atomic(&path, record, "published record")
494}
495
496fn git_stdout(root: &Path, args: &[&str]) -> Result<String, String> {
497    let out = Command::new("git")
498        .args(args)
499        .current_dir(root)
500        .output()
501        .map_err(|e| format!("failed to run git {}: {e}", args.join(" ")))?;
502    if !out.status.success() {
503        let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
504        return Err(format!("git {} failed: {stderr}", args.join(" ")));
505    }
506    Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
507}
508
509fn git_rev_parse(root: &Path, rev: &str) -> Result<String, String> {
510    git_stdout(root, &["rev-parse", "--verify", rev])
511}
512
513fn git_commit_subject(root: &Path, sha: &str) -> Result<String, String> {
514    git_stdout(root, &["show", "-s", "--format=%s", sha])
515        .map_err(|e| format!("failed to read subject for commit {sha}: {e}"))
516}
517
518fn resolve_current_run_tips(root: &Path, request: &str) -> Result<Vec<CombinedRun>, String> {
519    let wt_dir = root.join(".wt");
520    let entries = list_start_files(&wt_dir)?;
521    let mut tips = BTreeMap::new();
522    for path in entries {
523        let info = parse_start_file(&wt_dir, &path)?;
524        if info.is_research || info.request.as_deref() != Some(request) {
525            continue;
526        }
527        if crate::combine::is_run_left_out(root, &info.id)? {
528            continue;
529        }
530        let summary_path = wt_dir.join(format!("{}.json", info.id));
531        let raw = std::fs::read_to_string(&summary_path)
532            .map_err(|e| format!("failed to read {}: {e}", summary_path.display()))?;
533        let val: serde_json::Value = serde_json::from_str(&raw)
534            .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
535        let branch_hint = match val.get("branch") {
536            None | Some(serde_json::Value::Null) => None,
537            Some(serde_json::Value::String(s)) => Some(s.clone()),
538            Some(_) => {
539                return Err(format!(
540                    "summary file {} has non-string branch",
541                    summary_path.display()
542                ));
543            }
544        };
545        let branch = branch_hint.unwrap_or_else(|| format!("wip/{}", info.id));
546        let rev = format!("refs/heads/{branch}^{{commit}}");
547        let sha = git_rev_parse(root, &rev).map_err(|e| {
548            format!(
549                "run {}: branch {branch} does not resolve to a commit: {e}",
550                info.id
551            )
552        })?;
553        tips.insert(info.id, sha);
554    }
555    Ok(tips
556        .into_iter()
557        .map(|(id, tip)| CombinedRun { id, tip })
558        .collect())
559}
560
561fn sorted_runs(mut runs: Vec<CombinedRun>) -> Vec<CombinedRun> {
562    runs.sort_by(|a, b| a.id.cmp(&b.id));
563    runs
564}
565
566fn record_runs_match_tips(record: &CombineRecord, current_runs: &[CombinedRun]) -> bool {
567    if record.runs.len() != current_runs.len() {
568        return false;
569    }
570    sorted_runs(record.runs.clone()) == current_runs
571}
572
573fn combine_record_tip(record: &CombineRecord) -> &str {
574    record.commits.last().unwrap_or(&record.base).as_str()
575}
576
577fn is_record_pushed(published: &PublishedRecord, record: &CombineRecord) -> bool {
578    published.pushed_commit.as_deref() == Some(combine_record_tip(record))
579}
580
581fn branch_matches_record(root: &Path, record: &CombineRecord) -> bool {
582    let expected = combine_record_tip(record);
583    let rev = format!("refs/heads/{}^{{commit}}", record.branch);
584    git_rev_parse(root, &rev).is_ok_and(|actual| actual == expected)
585}
586
587fn format_record_failure(record: &CombineRecord) -> String {
588    match record.state {
589        CombineState::Conflict => {
590            let run = record.conflicting_run.as_deref().unwrap_or("unknown");
591            let files = if record.conflicting_files.is_empty() {
592                "(none listed)".to_string()
593            } else {
594                record.conflicting_files.join(", ")
595            };
596            format!(
597                "Combine failed for request {} (state: conflict).\nConflicting run: {run}\nConflicting files: {files}",
598                record.request
599            )
600        }
601        CombineState::CheckFailed => {
602            let step = record.failing_step.as_deref().unwrap_or("unknown");
603            let tail = record.output_tail.as_deref().unwrap_or("");
604            if tail.is_empty() {
605                format!(
606                    "Combine failed for request {} (state: check_failed).\nFailing step: {step}",
607                    record.request
608                )
609            } else {
610                format!(
611                    "Combine failed for request {} (state: check_failed).\nFailing step: {step}\nOutput tail:\n{tail}",
612                    record.request
613                )
614            }
615        }
616        CombineState::Combined => String::new(),
617    }
618}
619
620fn format_error_failure(request: &str, err_text: &str) -> String {
621    format!("Combine failed for request {request} (state: error).\nError: {err_text}")
622}
623
624struct RunningGuard {
625    state: Arc<RequestsState>,
626    request: String,
627}
628
629impl Drop for RunningGuard {
630    fn drop(&mut self) {
631        let mut inner = self.state.lock_inner();
632        inner.running.remove(&self.request);
633        self.state.cv.notify_all();
634    }
635}
636
637fn retry_failure_message(
638    root: &Path,
639    request: &str,
640    attempt: &AttemptRecord,
641) -> Result<String, String> {
642    let path = attempt_record_path(root, request);
643    match attempt.result {
644        AttemptResult::Conflict | AttemptResult::CheckFailed => {
645            let expected_state = match attempt.result {
646                AttemptResult::Conflict => CombineState::Conflict,
647                AttemptResult::CheckFailed => CombineState::CheckFailed,
648                AttemptResult::Combined | AttemptResult::Error => unreachable!(),
649            };
650            match load_combine_record(root, request)? {
651                Some(rec) if rec.state == expected_state => Ok(format_record_failure(&rec)),
652                _ => Err(format!(
653                    "attempt file {} has result {:?} without a matching combine record",
654                    path.display(),
655                    attempt.result
656                )),
657            }
658        }
659        AttemptResult::Error => {
660            let err_text = attempt.error.as_deref().ok_or_else(|| {
661                format!(
662                    "attempt file {} has result error without error text",
663                    path.display()
664                )
665            })?;
666            Ok(format_error_failure(request, err_text))
667        }
668        AttemptResult::Combined => Err(format!(
669            "cannot format failure message for combined attempt {}",
670            path.display()
671        )),
672    }
673}
674
675fn record_and_report_failure(
676    root: &Path,
677    session: &crate::session::Session,
678    request: &str,
679    runs: Vec<CombinedRun>,
680    result: AttemptResult,
681    error: Option<String>,
682    msg: &str,
683) {
684    let mut attempt = AttemptRecord {
685        runs,
686        result,
687        error,
688        reported: false,
689    };
690    if let Err(e) = write_attempt_record(root, request, &attempt) {
691        session.record_error(&format!(
692            "failed to write attempt record for {request}: {e}"
693        ));
694    }
695    match session.queue_for_request(request, msg) {
696        Ok(_) => {
697            attempt.reported = true;
698            if let Err(e) = write_attempt_record(root, request, &attempt) {
699                session.record_error(&format!(
700                    "failed to write attempt record for {request}: {e}"
701                ));
702            }
703        }
704        Err(e) => {
705            session.record_error(&format!(
706                "failed to queue combine failure for {request}: {e}"
707            ));
708        }
709    }
710}
711
712fn orchestrator_busy(surface: &Surface) -> bool {
713    let info = surface.session.info();
714    info.busy || info.queued > 0
715}
716
717fn ready_waiting_reason(orchestrator_busy: bool) -> String {
718    if orchestrator_busy {
719        "the orchestrator is still working".to_string()
720    } else {
721        "waiting to combine".to_string()
722    }
723}
724
725pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
726    crate::dispatch::validate_request_id(request)?;
727    if orchestrator_busy(surface) {
728        return Ok(false);
729    }
730    match request_readiness(&surface.root, request)? {
731        Readiness::Waiting { .. } => return Ok(false),
732        Readiness::Ready => {}
733    }
734
735    let current_runs = resolve_current_run_tips(&surface.root, request)?;
736
737    {
738        let mut inner = surface.requests.lock_inner();
739        if inner.running.contains(request) {
740            return Ok(false);
741        }
742        if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
743            if attempt.runs == current_runs {
744                if attempt.result != AttemptResult::Combined && !attempt.reported {
745                    let msg = retry_failure_message(&surface.root, request, &attempt)?;
746                    match surface.session.queue_for_request(request, &msg) {
747                        Ok(_) => {
748                            attempt.reported = true;
749                            write_attempt_record(&surface.root, request, &attempt)?;
750                        }
751                        Err(e) => {
752                            surface.session.record_error(&format!(
753                                "failed to queue combine failure for {request}: {e}"
754                            ));
755                        }
756                    }
757                }
758                return Ok(false);
759            }
760        }
761        inner.running.insert(request.to_string());
762    }
763
764    let root = surface.root.clone();
765    let session = surface.session.clone();
766    let requests_state = Arc::clone(&surface.requests);
767    let request_owned = request.to_string();
768
769    std::thread::spawn(move || {
770        let _guard = RunningGuard {
771            state: Arc::clone(&requests_state),
772            request: request_owned.clone(),
773        };
774        let mut out = Vec::new();
775        let mut err = Vec::new();
776        let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
777
778        match code {
779            0 => {
780                let runs = match load_combine_record(&root, &request_owned) {
781                    Ok(Some(rec)) => sorted_runs(rec.runs),
782                    Ok(None) => current_runs,
783                    Err(e) => {
784                        session.record_error(&format!(
785                            "failed to read combine record after combine for {request_owned}: {e}"
786                        ));
787                        current_runs
788                    }
789                };
790                let attempt = AttemptRecord {
791                    runs,
792                    result: AttemptResult::Combined,
793                    error: None,
794                    reported: false,
795                };
796                if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
797                    session.record_error(&format!(
798                        "failed to write attempt record for {request_owned}: {e}"
799                    ));
800                }
801            }
802            1 => match load_combine_record(&root, &request_owned) {
803                Ok(Some(rec))
804                    if matches!(
805                        rec.state,
806                        CombineState::Conflict | CombineState::CheckFailed
807                    ) =>
808                {
809                    let result = match rec.state {
810                        CombineState::Conflict => AttemptResult::Conflict,
811                        CombineState::CheckFailed => AttemptResult::CheckFailed,
812                        CombineState::Combined => unreachable!(),
813                    };
814                    let runs = sorted_runs(rec.runs.clone());
815                    let msg = format_record_failure(&rec);
816                    record_and_report_failure(
817                        &root,
818                        &session,
819                        &request_owned,
820                        runs,
821                        result,
822                        None,
823                        &msg,
824                    );
825                }
826                Ok(_) => {
827                    let err_text = String::from_utf8_lossy(&err).trim().to_string();
828                    let err_text = if err_text.is_empty() {
829                        format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
830                    } else {
831                        err_text
832                    };
833                    let msg = format_error_failure(&request_owned, &err_text);
834                    record_and_report_failure(
835                        &root,
836                        &session,
837                        &request_owned,
838                        current_runs,
839                        AttemptResult::Error,
840                        Some(err_text),
841                        &msg,
842                    );
843                }
844                Err(e) => {
845                    let msg = format_error_failure(&request_owned, &e);
846                    record_and_report_failure(
847                        &root,
848                        &session,
849                        &request_owned,
850                        current_runs,
851                        AttemptResult::Error,
852                        Some(e),
853                        &msg,
854                    );
855                }
856            },
857            other => {
858                let err_text = String::from_utf8_lossy(&err).trim().to_string();
859                let err_text = if err_text.is_empty() {
860                    format!("combine exited with status {other}")
861                } else {
862                    err_text
863                };
864                let msg = format_error_failure(&request_owned, &err_text);
865                record_and_report_failure(
866                    &root,
867                    &session,
868                    &request_owned,
869                    current_runs,
870                    AttemptResult::Error,
871                    Some(err_text),
872                    &msg,
873                );
874            }
875        }
876    });
877
878    Ok(true)
879}
880
881fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
882    let mut commits = Vec::with_capacity(shas.len());
883    for sha in shas {
884        let subject = git_commit_subject(root, sha)?;
885        commits.push(CommitSummary {
886            sha: sha.clone(),
887            subject,
888        });
889    }
890    Ok(commits)
891}
892
893fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
894    if commits.is_empty() {
895        return (None, None);
896    }
897    let title = commits[0].subject.clone();
898    let body = commits
899        .iter()
900        .map(|c| c.subject.as_str())
901        .collect::<Vec<_>>()
902        .join("\n");
903    (Some(title), Some(body))
904}
905
906struct RequestGroup {
907    request: String,
908    max_started_at: u64,
909    runs: Vec<(u64, String)>,
910}
911
912pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
913    let wt_dir = surface.root.join(".wt");
914    let entries = list_start_files(&wt_dir)?;
915    let mut groups: HashMap<String, RequestGroup> = HashMap::new();
916    for path in entries {
917        let info = parse_start_file(&wt_dir, &path)?;
918        if info.is_research {
919            continue;
920        }
921        let Some(req_id) = info.request else {
922            continue;
923        };
924        let entry = groups
925            .entry(req_id.clone())
926            .or_insert_with(|| RequestGroup {
927                request: req_id,
928                max_started_at: 0,
929                runs: Vec::new(),
930            });
931        if info.started_at > entry.max_started_at {
932            entry.max_started_at = info.started_at;
933        }
934        entry.runs.push((info.started_at, info.id));
935    }
936
937    let mut ordered: Vec<RequestGroup> = groups.into_values().collect();
938    ordered.sort_by(|a, b| {
939        b.max_started_at
940            .cmp(&a.max_started_at)
941            .then_with(|| b.request.cmp(&a.request))
942    });
943
944    let busy = orchestrator_busy(surface);
945    let mut result = Vec::with_capacity(ordered.len());
946    for mut group in ordered {
947        group
948            .runs
949            .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
950        let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
951        result.push(build_request_status(surface, group.request, run_ids, busy));
952    }
953    Ok(result)
954}
955
956fn build_request_status(
957    surface: &Surface,
958    request: String,
959    runs: Vec<String>,
960    orchestrator_busy: bool,
961) -> RequestStatus {
962    let is_combining = surface.requests.is_combining(&request);
963
964    let record_res = load_combine_record(&surface.root, &request);
965    let published_res = load_published_record(&surface.root, &request);
966    let attempt_res = load_attempt_record(&surface.root, &request);
967    let left_out_res: Result<Vec<String>, String> = runs
968        .iter()
969        .filter_map(
970            |id| match crate::combine::is_run_left_out(&surface.root, id) {
971                Ok(true) => Some(Ok(id.clone())),
972                Ok(false) => None,
973                Err(e) => Some(Err(e)),
974            },
975        )
976        .collect();
977    let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
978
979    let (pushed, pull_request_url) = match (&published_res, &record_res) {
980        (Ok(p), Ok(Some(rec))) => (
981            rec.state == CombineState::Combined && is_record_pushed(p, rec),
982            p.pull_request_url.clone(),
983        ),
984        (Ok(p), _) => (false, p.pull_request_url.clone()),
985        (Err(_), _) => (false, None),
986    };
987
988    let mut status = RequestStatus {
989        request: request.clone(),
990        runs,
991        left_out,
992        state: String::new(),
993        waiting_reasons: Vec::new(),
994        branch: None,
995        base: None,
996        commits: Vec::new(),
997        conflicting_run: None,
998        conflicting_files: Vec::new(),
999        failing_step: None,
1000        output_tail: None,
1001        error: None,
1002        suggested_title: None,
1003        suggested_body: None,
1004        pushed,
1005        pull_request_url,
1006    };
1007
1008    if is_combining {
1009        status.state = "combining".to_string();
1010        if let Ok(Some(rec)) = record_res {
1011            populate_record_metadata(&surface.root, &rec, &mut status);
1012        }
1013        return status;
1014    }
1015
1016    if let Err(e) = left_out_res {
1017        status.state = "error".to_string();
1018        status.error = Some(e);
1019        return status;
1020    }
1021
1022    if let Err(e) = published_res {
1023        status.state = "error".to_string();
1024        status.error = Some(e);
1025        return status;
1026    }
1027
1028    let attempt = match attempt_res {
1029        Ok(a) => a,
1030        Err(e) => {
1031            status.state = "error".to_string();
1032            status.error = Some(e);
1033            return status;
1034        }
1035    };
1036
1037    let record = match record_res {
1038        Ok(r) => r,
1039        Err(e) => {
1040            status.state = "error".to_string();
1041            status.error = Some(e);
1042            return status;
1043        }
1044    };
1045
1046    match request_readiness(&surface.root, &request) {
1047        Err(e) => {
1048            status.state = "error".to_string();
1049            status.error = Some(e);
1050            status
1051        }
1052        Ok(Readiness::Waiting { reasons }) => {
1053            status.state = "waiting".to_string();
1054            status.waiting_reasons = reasons;
1055            if let Some(ref rec) = record {
1056                populate_record_metadata(&surface.root, rec, &mut status);
1057            }
1058            status
1059        }
1060        Ok(Readiness::Ready) => {
1061            let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1062                Ok(t) => t,
1063                Err(e) => {
1064                    status.state = "error".to_string();
1065                    status.error = Some(e);
1066                    return status;
1067                }
1068            };
1069            if let Some(ref att) = attempt {
1070                if att.runs == current_runs && att.result == AttemptResult::Error {
1071                    status.state = "error".to_string();
1072                    status.error = att.error.clone();
1073                    return status;
1074                }
1075            }
1076            let Some(rec) = record else {
1077                status.state = "waiting".to_string();
1078                status.waiting_reasons = vec![ready_waiting_reason(orchestrator_busy)];
1079                return status;
1080            };
1081            if !record_runs_match_tips(&rec, &current_runs) {
1082                status.state = "waiting".to_string();
1083                status.waiting_reasons = vec![ready_waiting_reason(orchestrator_busy)];
1084                populate_record_metadata(&surface.root, &rec, &mut status);
1085                return status;
1086            }
1087
1088            let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1089                Ok(c) => c,
1090                Err(e) => {
1091                    status.state = "error".to_string();
1092                    status.error = Some(e);
1093                    return status;
1094                }
1095            };
1096
1097            status.branch = Some(rec.branch.clone());
1098            status.base = Some(rec.base.clone());
1099            status.commits = commits;
1100            status.conflicting_run = rec.conflicting_run.clone();
1101            status.conflicting_files = rec.conflicting_files.clone();
1102            status.failing_step = rec.failing_step.clone();
1103            status.output_tail = rec.output_tail.clone();
1104
1105            match rec.state {
1106                CombineState::Combined => {
1107                    if branch_matches_record(&surface.root, &rec) {
1108                        status.state = "combined".to_string();
1109                        let (title, body) = suggested_pr_fields(&status.commits);
1110                        status.suggested_title = title;
1111                        status.suggested_body = body;
1112                    } else {
1113                        status.state = "waiting".to_string();
1114                        status.waiting_reasons = vec![ready_waiting_reason(orchestrator_busy)];
1115                    }
1116                }
1117                CombineState::Conflict => {
1118                    status.state = "conflict".to_string();
1119                }
1120                CombineState::CheckFailed => {
1121                    status.state = "check_failed".to_string();
1122                }
1123            }
1124            status
1125        }
1126    }
1127}
1128
1129fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1130    status.branch = Some(rec.branch.clone());
1131    status.base = Some(rec.base.clone());
1132    if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1133        status.commits = commits;
1134    }
1135    status.conflicting_run = rec.conflicting_run.clone();
1136    status.conflicting_files = rec.conflicting_files.clone();
1137    status.failing_step = rec.failing_step.clone();
1138    status.output_tail = rec.output_tail.clone();
1139}
1140
1141pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1142    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
1143    if surface.requests.is_combining(request) {
1144        return Err(RequestActionError::Conflict(format!(
1145            "request {request} is currently combining"
1146        )));
1147    }
1148    let record = load_combine_record(&surface.root, request)
1149        .map_err(RequestActionError::Internal)?
1150        .ok_or_else(|| {
1151            RequestActionError::Conflict(format!("request {request} has not been combined"))
1152        })?;
1153    if record.state != CombineState::Combined {
1154        return Err(RequestActionError::Conflict(format!(
1155            "request {request} is not combined (state: {:?})",
1156            record.state
1157        )));
1158    }
1159
1160    let mut published =
1161        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1162
1163    match surface.publisher.push_branch(&surface.root, &record.branch) {
1164        Ok(()) => {
1165            let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1166            let branch_commit =
1167                git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1168            published.pushed_commit = Some(branch_commit);
1169            write_published_record(&surface.root, request, &published)
1170                .map_err(RequestActionError::Internal)?;
1171            if let Err(e) = surface.session.record_decision(
1172                request,
1173                "push",
1174                Some(&format!("pushed {}", record.branch)),
1175                None,
1176            ) {
1177                surface.session.record_error(&format!(
1178                    "failed to record push decision for {request}: {e}"
1179                ));
1180            }
1181            Ok(())
1182        }
1183        Err(e) => {
1184            surface.session.record_error(&format!(
1185                "push failed for {request} ({}): {e}",
1186                record.branch
1187            ));
1188            Err(RequestActionError::Internal(e))
1189        }
1190    }
1191}
1192
1193pub fn open_request_pull_request(
1194    surface: &Surface,
1195    request: &str,
1196    title: &str,
1197    body: &str,
1198) -> Result<String, RequestActionError> {
1199    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
1200    let trimmed_title = title.trim();
1201    if trimmed_title.is_empty() {
1202        return Err(RequestActionError::BadRequest(
1203            "field title must not be empty".to_string(),
1204        ));
1205    }
1206    if surface.requests.is_combining(request) {
1207        return Err(RequestActionError::Conflict(format!(
1208            "request {request} is currently combining"
1209        )));
1210    }
1211    let record = load_combine_record(&surface.root, request)
1212        .map_err(RequestActionError::Internal)?
1213        .ok_or_else(|| {
1214            RequestActionError::Conflict(format!("request {request} has not been combined"))
1215        })?;
1216    if record.state != CombineState::Combined {
1217        return Err(RequestActionError::Conflict(format!(
1218            "request {request} is not combined (state: {:?})",
1219            record.state
1220        )));
1221    }
1222
1223    let mut published =
1224        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1225    if !is_record_pushed(&published, &record) {
1226        return Err(RequestActionError::Conflict(format!(
1227            "branch {} must be pushed before opening a pull request",
1228            record.branch
1229        )));
1230    }
1231
1232    match surface
1233        .publisher
1234        .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1235    {
1236        Ok(url) => {
1237            published.pull_request_url = Some(url.clone());
1238            write_published_record(&surface.root, request, &published)
1239                .map_err(RequestActionError::Internal)?;
1240            if let Err(e) =
1241                surface
1242                    .session
1243                    .record_decision(request, "pull_request", Some(&url), None)
1244            {
1245                surface.session.record_error(&format!(
1246                    "failed to record pull_request decision for {request}: {e}"
1247                ));
1248            }
1249            Ok(url)
1250        }
1251        Err(e) => {
1252            surface.session.record_error(&format!(
1253                "pull request failed for {request} ({}): {e}",
1254                record.branch
1255            ));
1256            Err(RequestActionError::Internal(e))
1257        }
1258    }
1259}