Skip to main content

blyte_cli/
requests.rs

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