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 run_branch(wt_dir: &Path, run_id: &str) -> Result<String, String> {
521    let summary_path = wt_dir.join(format!("{run_id}.json"));
522    let raw = std::fs::read_to_string(&summary_path)
523        .map_err(|e| format!("failed to read {}: {e}", summary_path.display()))?;
524    let val: serde_json::Value = serde_json::from_str(&raw)
525        .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
526    let branch_hint = match val.get("branch") {
527        None | Some(serde_json::Value::Null) => None,
528        Some(serde_json::Value::String(s)) => Some(s.clone()),
529        Some(_) => {
530            return Err(format!(
531                "summary file {} has non-string branch",
532                summary_path.display()
533            ));
534        }
535    };
536    Ok(branch_hint.unwrap_or_else(|| format!("wip/{run_id}")))
537}
538
539fn git_branch_exists(root: &Path, run_id: &str, branch: &str) -> Result<bool, String> {
540    let ref_name = format!("refs/heads/{branch}");
541    let out = Command::new("git")
542        .args(["show-ref", "--verify", "--quiet", &ref_name])
543        .current_dir(root)
544        .output()
545        .map_err(|e| {
546            format!("run {run_id}: failed to check branch {branch} with git show-ref: {e}")
547        })?;
548    match out.status.code() {
549        Some(0) => Ok(true),
550        Some(1) => Ok(false),
551        code => {
552            let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
553            let status_desc = match code {
554                Some(c) => format!("exit code {c}"),
555                None => "terminated by signal".to_string(),
556            };
557            if stderr.is_empty() {
558                Err(format!(
559                    "run {run_id}: git show-ref failed for branch {branch} ({status_desc})"
560                ))
561            } else {
562                Err(format!(
563                    "run {run_id}: git show-ref failed for branch {branch} ({status_desc}): {stderr}"
564                ))
565            }
566        }
567    }
568}
569
570fn resolve_current_run_tips(root: &Path, request: &str) -> Result<Vec<CombinedRun>, String> {
571    let wt_dir = root.join(".wt");
572    let entries = list_start_files(&wt_dir)?;
573    let mut tips = BTreeMap::new();
574    for path in entries {
575        let info = parse_start_file(&wt_dir, &path)?;
576        if info.is_research || info.request.as_deref() != Some(request) {
577            continue;
578        }
579        if crate::combine::is_run_left_out(root, &info.id)? {
580            continue;
581        }
582        let branch = run_branch(&wt_dir, &info.id)?;
583        let rev = format!("refs/heads/{branch}^{{commit}}");
584        let sha = git_rev_parse(root, &rev).map_err(|e| {
585            format!(
586                "run {}: branch {branch} does not resolve to a commit: {e}",
587                info.id
588            )
589        })?;
590        tips.insert(info.id, sha);
591    }
592    Ok(tips
593        .into_iter()
594        .map(|(id, tip)| CombinedRun { id, tip })
595        .collect())
596}
597
598fn sorted_runs(mut runs: Vec<CombinedRun>) -> Vec<CombinedRun> {
599    runs.sort_by(|a, b| a.id.cmp(&b.id));
600    runs
601}
602
603fn record_runs_match_tips(record: &CombineRecord, current_runs: &[CombinedRun]) -> bool {
604    if record.runs.len() != current_runs.len() {
605        return false;
606    }
607    sorted_runs(record.runs.clone()) == current_runs
608}
609
610enum CombinedRunBranchState {
611    Gone,
612    AtRecordedTip,
613    Changed,
614}
615
616fn check_recorded_run_branch(
617    root: &Path,
618    wt_dir: &Path,
619    run: &CombinedRun,
620) -> Result<CombinedRunBranchState, String> {
621    let branch = run_branch(wt_dir, &run.id)?;
622    if !git_branch_exists(root, &run.id, &branch)? {
623        return Ok(CombinedRunBranchState::Gone);
624    }
625    let rev = format!("refs/heads/{branch}^{{commit}}");
626    let sha = git_rev_parse(root, &rev).map_err(|e| {
627        format!(
628            "run {}: branch {branch} does not resolve to a commit: {e}",
629            run.id
630        )
631    })?;
632    if sha == run.tip {
633        Ok(CombinedRunBranchState::AtRecordedTip)
634    } else {
635        Ok(CombinedRunBranchState::Changed)
636    }
637}
638
639fn active_request_run_ids(root: &Path, request: &str) -> Result<Vec<String>, String> {
640    let wt_dir = root.join(".wt");
641    let entries = list_start_files(&wt_dir)?;
642    let mut run_ids = Vec::new();
643    for path in entries {
644        let info = parse_start_file(&wt_dir, &path)?;
645        if info.is_research || info.request.as_deref() != Some(request) {
646            continue;
647        }
648        if crate::combine::is_run_left_out(root, &info.id)? {
649            continue;
650        }
651        run_ids.push(info.id);
652    }
653    Ok(run_ids)
654}
655
656fn request_is_done(root: &Path, request: &str, rec: &CombineRecord) -> Result<bool, String> {
657    if rec.state != CombineState::Combined {
658        return Ok(false);
659    }
660    let active_runs = active_request_run_ids(root, request)?;
661    if active_runs.is_empty() {
662        return Ok(false);
663    }
664    let recorded_by_id: HashMap<&str, &CombinedRun> =
665        rec.runs.iter().map(|run| (run.id.as_str(), run)).collect();
666    let wt_dir = root.join(".wt");
667    let mut any_branch_gone = false;
668    for run_id in &active_runs {
669        let Some(&recorded_run) = recorded_by_id.get(run_id.as_str()) else {
670            return Ok(false);
671        };
672        match check_recorded_run_branch(root, &wt_dir, recorded_run)? {
673            CombinedRunBranchState::Gone => any_branch_gone = true,
674            CombinedRunBranchState::AtRecordedTip => {}
675            CombinedRunBranchState::Changed => return Ok(false),
676        }
677    }
678    Ok(any_branch_gone)
679}
680
681fn check_record_combined_for_request(
682    root: &Path,
683    request: &str,
684    run_ids: &[&str],
685) -> Result<BTreeSet<String>, String> {
686    let Some(rec) = load_combine_record(root, request)? else {
687        return Ok(BTreeSet::new());
688    };
689    if rec.state != CombineState::Combined {
690        return Ok(BTreeSet::new());
691    }
692    let wt_dir = root.join(".wt");
693    let mut combined = BTreeSet::new();
694    for run in &rec.runs {
695        if !run_ids.contains(&run.id.as_str()) {
696            continue;
697        }
698        match check_recorded_run_branch(root, &wt_dir, run)? {
699            CombinedRunBranchState::Gone | CombinedRunBranchState::AtRecordedTip => {
700                combined.insert(run.id.clone());
701            }
702            CombinedRunBranchState::Changed => {}
703        }
704    }
705    Ok(combined)
706}
707
708pub fn run_is_combined(root: &Path, run_id: &str, request: Option<&str>) -> Result<bool, String> {
709    let Some(request) = request else {
710        return Ok(false);
711    };
712    Ok(check_record_combined_for_request(root, request, &[run_id])?.contains(run_id))
713}
714
715pub fn combined_run_ids(
716    root: &Path,
717    runs: &[(&str, Option<&str>)],
718) -> Result<BTreeSet<String>, String> {
719    let mut by_request: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
720    for &(run_id, request) in runs {
721        if let Some(req) = request {
722            by_request.entry(req).or_default().push(run_id);
723        }
724    }
725    let mut combined = BTreeSet::new();
726    for (request, run_ids) in by_request {
727        combined.extend(check_record_combined_for_request(root, request, &run_ids)?);
728    }
729    Ok(combined)
730}
731
732fn combine_record_tip(record: &CombineRecord) -> &str {
733    record.commits.last().unwrap_or(&record.base).as_str()
734}
735
736fn is_record_pushed(published: &PublishedRecord, record: &CombineRecord) -> bool {
737    published.pushed_commit.as_deref() == Some(combine_record_tip(record))
738}
739
740fn branch_matches_record(root: &Path, record: &CombineRecord) -> bool {
741    let expected = combine_record_tip(record);
742    let rev = format!("refs/heads/{}^{{commit}}", record.branch);
743    git_rev_parse(root, &rev).is_ok_and(|actual| actual == expected)
744}
745
746fn format_record_failure(record: &CombineRecord, record_path: &Path) -> Result<String, String> {
747    match record.state {
748        CombineState::Conflict => {
749            let run = record
750                .conflicting_run
751                .as_deref()
752                .filter(|r| !r.is_empty())
753                .ok_or_else(|| {
754                    format!(
755                        "combine record {} has state conflict with missing conflicting_run",
756                        record_path.display()
757                    )
758                })?;
759            if record.conflicting_files.is_empty() {
760                return Err(format!(
761                    "combine record {} has state conflict with empty conflicting_files",
762                    record_path.display()
763                ));
764            }
765            let files = record.conflicting_files.join(", ");
766            Ok(format!(
767                "Combine failed for request {} (state: conflict).\nConflicting run: {run}\nConflicting files: {files}",
768                record.request
769            ))
770        }
771        CombineState::CheckFailed => {
772            let step = record
773                .failing_step
774                .as_deref()
775                .filter(|s| !s.is_empty())
776                .ok_or_else(|| {
777                    format!(
778                        "combine record {} has state check_failed with missing failing_step",
779                        record_path.display()
780                    )
781                })?;
782            let tail = record
783                .output_tail
784                .as_deref()
785                .filter(|t| !t.is_empty())
786                .ok_or_else(|| {
787                    format!(
788                        "combine record {} has state check_failed with missing or empty output_tail",
789                        record_path.display()
790                    )
791                })?;
792            Ok(format!(
793                "Combine failed for request {} (state: check_failed).\nFailing step: {step}\nOutput tail:\n{tail}",
794                record.request
795            ))
796        }
797        CombineState::Combined => Err(format!(
798            "combine record {} has state combined: not a failure record",
799            record_path.display()
800        )),
801    }
802}
803
804fn format_error_failure(request: &str, err_text: &str) -> String {
805    format!("Combine failed for request {request} (state: error).\nError: {err_text}")
806}
807
808struct RunningGuard {
809    state: Arc<RequestsState>,
810    request: String,
811}
812
813impl Drop for RunningGuard {
814    fn drop(&mut self) {
815        let mut inner = self.state.lock_inner();
816        inner.running.remove(&self.request);
817        self.state.cv.notify_all();
818    }
819}
820
821fn retry_failure_message(
822    root: &Path,
823    request: &str,
824    attempt: &AttemptRecord,
825) -> Result<String, String> {
826    let path = attempt_record_path(root, request);
827    match attempt.result {
828        AttemptResult::Conflict | AttemptResult::CheckFailed => {
829            let expected_state = match attempt.result {
830                AttemptResult::Conflict => CombineState::Conflict,
831                AttemptResult::CheckFailed => CombineState::CheckFailed,
832                AttemptResult::Combined | AttemptResult::Error => unreachable!(),
833            };
834            match load_combine_record(root, request)? {
835                Some(rec) if rec.state == expected_state => {
836                    format_record_failure(&rec, &combine_record_path(root, request))
837                }
838                _ => Err(format!(
839                    "attempt file {} has result {:?} without a matching combine record",
840                    path.display(),
841                    attempt.result
842                )),
843            }
844        }
845        AttemptResult::Error => {
846            let err_text = attempt.error.as_deref().ok_or_else(|| {
847                format!(
848                    "attempt file {} has result error without error text",
849                    path.display()
850                )
851            })?;
852            Ok(format_error_failure(request, err_text))
853        }
854        AttemptResult::Combined => Err(format!(
855            "cannot format failure message for combined attempt {}",
856            path.display()
857        )),
858    }
859}
860
861fn record_and_report_failure(
862    root: &Path,
863    session: &crate::session::Session,
864    request: &str,
865    runs: Vec<CombinedRun>,
866    result: AttemptResult,
867    error: Option<String>,
868    msg: &str,
869) {
870    let mut attempt = AttemptRecord {
871        runs,
872        result,
873        error,
874        reported: false,
875    };
876    if let Err(e) = write_attempt_record(root, request, &attempt) {
877        session.record_error(&format!(
878            "failed to write attempt record for {request}: {e}"
879        ));
880    }
881    match session.queue_for_request(request, msg) {
882        Ok(_) => {
883            attempt.reported = true;
884            if let Err(e) = write_attempt_record(root, request, &attempt) {
885                session.record_error(&format!(
886                    "failed to write attempt record for {request}: {e}"
887                ));
888            }
889        }
890        Err(e) => {
891            session.record_error(&format!(
892                "failed to queue combine failure for {request}: {e}"
893            ));
894        }
895    }
896}
897
898fn conversation_busy(surface: &Surface) -> bool {
899    let info = surface.session.info();
900    info.busy || info.queued > 0
901}
902
903fn ready_waiting_reason(conversation_busy: bool) -> String {
904    if conversation_busy {
905        "the conversation model is still working".to_string()
906    } else {
907        "waiting to combine".to_string()
908    }
909}
910
911pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
912    crate::dispatch::validate_request_id(request)?;
913    if conversation_busy(surface) {
914        return Ok(false);
915    }
916    match request_readiness(&surface.root, request)? {
917        Readiness::Waiting { .. } => return Ok(false),
918        Readiness::Ready => {}
919    }
920
921    if let Some(rec) = load_combine_record(&surface.root, request)? {
922        if request_is_done(&surface.root, request, &rec)? {
923            return Ok(false);
924        }
925    }
926
927    let current_runs = resolve_current_run_tips(&surface.root, request)?;
928
929    {
930        let mut inner = surface.requests.lock_inner();
931        if inner.running.contains(request) {
932            return Ok(false);
933        }
934        if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
935            if attempt.runs == current_runs {
936                if attempt.result != AttemptResult::Combined && !attempt.reported {
937                    match retry_failure_message(&surface.root, request, &attempt) {
938                        Ok(msg) => match surface.session.queue_for_request(request, &msg) {
939                            Ok(_) => {
940                                attempt.reported = true;
941                                write_attempt_record(&surface.root, request, &attempt)?;
942                            }
943                            Err(e) => {
944                                surface.session.record_error(&format!(
945                                    "failed to queue combine failure for {request}: {e}"
946                                ));
947                            }
948                        },
949                        Err(e) => {
950                            let msg = format_error_failure(request, &e);
951                            record_and_report_failure(
952                                &surface.root,
953                                &surface.session,
954                                request,
955                                attempt.runs,
956                                AttemptResult::Error,
957                                Some(e),
958                                &msg,
959                            );
960                        }
961                    }
962                }
963                return Ok(false);
964            }
965        }
966        inner.running.insert(request.to_string());
967    }
968
969    let root = surface.root.clone();
970    let session = surface.session.clone();
971    let requests_state = Arc::clone(&surface.requests);
972    let request_owned = request.to_string();
973
974    std::thread::spawn(move || {
975        let _guard = RunningGuard {
976            state: Arc::clone(&requests_state),
977            request: request_owned.clone(),
978        };
979        let mut out = Vec::new();
980        let mut err = Vec::new();
981        let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
982
983        match code {
984            0 => {
985                let runs = match load_combine_record(&root, &request_owned) {
986                    Ok(Some(rec)) => sorted_runs(rec.runs),
987                    Ok(None) => current_runs,
988                    Err(e) => {
989                        session.record_error(&format!(
990                            "failed to read combine record after combine for {request_owned}: {e}"
991                        ));
992                        current_runs
993                    }
994                };
995                let attempt = AttemptRecord {
996                    runs,
997                    result: AttemptResult::Combined,
998                    error: None,
999                    reported: false,
1000                };
1001                if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1002                    session.record_error(&format!(
1003                        "failed to write attempt record for {request_owned}: {e}"
1004                    ));
1005                }
1006            }
1007            1 => match load_combine_record(&root, &request_owned) {
1008                Ok(Some(rec))
1009                    if matches!(
1010                        rec.state,
1011                        CombineState::Conflict | CombineState::CheckFailed
1012                    ) =>
1013                {
1014                    let result = match rec.state {
1015                        CombineState::Conflict => AttemptResult::Conflict,
1016                        CombineState::CheckFailed => AttemptResult::CheckFailed,
1017                        CombineState::Combined => unreachable!(),
1018                    };
1019                    let runs = sorted_runs(rec.runs.clone());
1020                    let rec_path = combine_record_path(&root, &request_owned);
1021                    match format_record_failure(&rec, &rec_path) {
1022                        Ok(msg) => {
1023                            record_and_report_failure(
1024                                &root,
1025                                &session,
1026                                &request_owned,
1027                                runs,
1028                                result,
1029                                None,
1030                                &msg,
1031                            );
1032                        }
1033                        Err(e) => {
1034                            let msg = format_error_failure(&request_owned, &e);
1035                            record_and_report_failure(
1036                                &root,
1037                                &session,
1038                                &request_owned,
1039                                runs,
1040                                AttemptResult::Error,
1041                                Some(e),
1042                                &msg,
1043                            );
1044                        }
1045                    }
1046                }
1047                Ok(_) => {
1048                    let err_text = String::from_utf8_lossy(&err).trim().to_string();
1049                    let err_text = if err_text.is_empty() {
1050                        format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
1051                    } else {
1052                        err_text
1053                    };
1054                    let msg = format_error_failure(&request_owned, &err_text);
1055                    record_and_report_failure(
1056                        &root,
1057                        &session,
1058                        &request_owned,
1059                        current_runs,
1060                        AttemptResult::Error,
1061                        Some(err_text),
1062                        &msg,
1063                    );
1064                }
1065                Err(e) => {
1066                    let msg = format_error_failure(&request_owned, &e);
1067                    record_and_report_failure(
1068                        &root,
1069                        &session,
1070                        &request_owned,
1071                        current_runs,
1072                        AttemptResult::Error,
1073                        Some(e),
1074                        &msg,
1075                    );
1076                }
1077            },
1078            other => {
1079                let err_text = String::from_utf8_lossy(&err).trim().to_string();
1080                let err_text = if err_text.is_empty() {
1081                    format!("combine exited with status {other}")
1082                } else {
1083                    err_text
1084                };
1085                let msg = format_error_failure(&request_owned, &err_text);
1086                record_and_report_failure(
1087                    &root,
1088                    &session,
1089                    &request_owned,
1090                    current_runs,
1091                    AttemptResult::Error,
1092                    Some(err_text),
1093                    &msg,
1094                );
1095            }
1096        }
1097    });
1098
1099    Ok(true)
1100}
1101
1102fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
1103    let mut commits = Vec::with_capacity(shas.len());
1104    for sha in shas {
1105        let subject = git_commit_subject(root, sha)?;
1106        commits.push(CommitSummary {
1107            sha: sha.clone(),
1108            subject,
1109        });
1110    }
1111    Ok(commits)
1112}
1113
1114fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
1115    if commits.is_empty() {
1116        return (None, None);
1117    }
1118    let title = commits[0].subject.clone();
1119    let body = commits
1120        .iter()
1121        .map(|c| c.subject.as_str())
1122        .collect::<Vec<_>>()
1123        .join("\n");
1124    (Some(title), Some(body))
1125}
1126
1127struct RequestGroup {
1128    request: String,
1129    max_started_at: u64,
1130    runs: Vec<(u64, String)>,
1131}
1132
1133pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
1134    let wt_dir = surface.root.join(".wt");
1135    let entries = list_start_files(&wt_dir)?;
1136    let mut groups: HashMap<String, RequestGroup> = HashMap::new();
1137    for path in entries {
1138        let info = parse_start_file(&wt_dir, &path)?;
1139        if info.is_research {
1140            continue;
1141        }
1142        let Some(req_id) = info.request else {
1143            continue;
1144        };
1145        let entry = groups
1146            .entry(req_id.clone())
1147            .or_insert_with(|| RequestGroup {
1148                request: req_id,
1149                max_started_at: 0,
1150                runs: Vec::new(),
1151            });
1152        if info.started_at > entry.max_started_at {
1153            entry.max_started_at = info.started_at;
1154        }
1155        entry.runs.push((info.started_at, info.id));
1156    }
1157
1158    let mut ordered: Vec<RequestGroup> = groups.into_values().collect();
1159    ordered.sort_by(|a, b| {
1160        b.max_started_at
1161            .cmp(&a.max_started_at)
1162            .then_with(|| b.request.cmp(&a.request))
1163    });
1164
1165    let busy = conversation_busy(surface);
1166    let mut result = Vec::with_capacity(ordered.len());
1167    for mut group in ordered {
1168        group
1169            .runs
1170            .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1171        let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
1172        result.push(build_request_status(surface, group.request, run_ids, busy));
1173    }
1174    Ok(result)
1175}
1176
1177fn build_request_status(
1178    surface: &Surface,
1179    request: String,
1180    runs: Vec<String>,
1181    conversation_busy: bool,
1182) -> RequestStatus {
1183    let is_combining = surface.requests.is_combining(&request);
1184
1185    let record_res = load_combine_record(&surface.root, &request);
1186    let published_res = load_published_record(&surface.root, &request);
1187    let attempt_res = load_attempt_record(&surface.root, &request);
1188    let left_out_res: Result<Vec<String>, String> = runs
1189        .iter()
1190        .filter_map(
1191            |id| match crate::combine::is_run_left_out(&surface.root, id) {
1192                Ok(true) => Some(Ok(id.clone())),
1193                Ok(false) => None,
1194                Err(e) => Some(Err(e)),
1195            },
1196        )
1197        .collect();
1198    let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
1199
1200    let (pushed, pull_request_url) = match (&published_res, &record_res) {
1201        (Ok(p), Ok(Some(rec))) => (
1202            rec.state == CombineState::Combined && is_record_pushed(p, rec),
1203            p.pull_request_url.clone(),
1204        ),
1205        (Ok(p), _) => (false, p.pull_request_url.clone()),
1206        (Err(_), _) => (false, None),
1207    };
1208
1209    let mut status = RequestStatus {
1210        request: request.clone(),
1211        runs,
1212        left_out,
1213        state: String::new(),
1214        waiting_reasons: Vec::new(),
1215        branch: None,
1216        base: None,
1217        commits: Vec::new(),
1218        check: None,
1219        conflicting_run: None,
1220        conflicting_files: Vec::new(),
1221        failing_step: None,
1222        output_tail: None,
1223        error: None,
1224        suggested_title: None,
1225        suggested_body: None,
1226        pushed,
1227        pull_request_url,
1228    };
1229
1230    if is_combining {
1231        status.state = "combining".to_string();
1232        if let Ok(Some(rec)) = record_res {
1233            populate_record_metadata(&surface.root, &rec, &mut status);
1234        }
1235        return status;
1236    }
1237
1238    if let Err(e) = left_out_res {
1239        status.state = "error".to_string();
1240        status.error = Some(e);
1241        return status;
1242    }
1243
1244    if let Err(e) = published_res {
1245        status.state = "error".to_string();
1246        status.error = Some(e);
1247        return status;
1248    }
1249
1250    let attempt = match attempt_res {
1251        Ok(a) => a,
1252        Err(e) => {
1253            status.state = "error".to_string();
1254            status.error = Some(e);
1255            return status;
1256        }
1257    };
1258
1259    let record = match record_res {
1260        Ok(r) => r,
1261        Err(e) => {
1262            status.state = "error".to_string();
1263            status.error = Some(e);
1264            return status;
1265        }
1266    };
1267
1268    match request_readiness(&surface.root, &request) {
1269        Err(e) => {
1270            status.state = "error".to_string();
1271            status.error = Some(e);
1272            status
1273        }
1274        Ok(Readiness::Waiting { reasons }) => {
1275            status.state = "waiting".to_string();
1276            status.waiting_reasons = reasons;
1277            if let Some(ref rec) = record {
1278                populate_record_metadata(&surface.root, rec, &mut status);
1279            }
1280            status
1281        }
1282        Ok(Readiness::Ready) => {
1283            if let Some(ref rec) = record {
1284                match request_is_done(&surface.root, &request, rec) {
1285                    Ok(true) => {
1286                        status.state = "done".to_string();
1287                        populate_record_metadata(&surface.root, rec, &mut status);
1288                        return status;
1289                    }
1290                    Ok(false) => {}
1291                    Err(e) => {
1292                        status.state = "error".to_string();
1293                        status.error = Some(e);
1294                        return status;
1295                    }
1296                }
1297            }
1298            let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1299                Ok(t) => t,
1300                Err(e) => {
1301                    status.state = "error".to_string();
1302                    status.error = Some(e);
1303                    return status;
1304                }
1305            };
1306            if let Some(ref att) = attempt {
1307                if att.runs == current_runs && att.result == AttemptResult::Error {
1308                    status.state = "error".to_string();
1309                    status.error = att.error.clone();
1310                    return status;
1311                }
1312            }
1313            let Some(rec) = record else {
1314                status.state = "waiting".to_string();
1315                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1316                return status;
1317            };
1318            if !record_runs_match_tips(&rec, &current_runs) {
1319                status.state = "waiting".to_string();
1320                status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1321                populate_record_metadata(&surface.root, &rec, &mut status);
1322                return status;
1323            }
1324
1325            let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1326                Ok(c) => c,
1327                Err(e) => {
1328                    status.state = "error".to_string();
1329                    status.error = Some(e);
1330                    return status;
1331                }
1332            };
1333
1334            status.branch = Some(rec.branch.clone());
1335            status.base = Some(rec.base.clone());
1336            status.commits = commits;
1337            status.check = Some(rec.check);
1338            status.conflicting_run = rec.conflicting_run.clone();
1339            status.conflicting_files = rec.conflicting_files.clone();
1340            status.failing_step = rec.failing_step.clone();
1341            status.output_tail = rec.output_tail.clone();
1342
1343            match rec.state {
1344                CombineState::Combined => {
1345                    if branch_matches_record(&surface.root, &rec) {
1346                        status.state = "combined".to_string();
1347                        let (title, body) = suggested_pr_fields(&status.commits);
1348                        status.suggested_title = title;
1349                        status.suggested_body = body;
1350                    } else {
1351                        status.state = "waiting".to_string();
1352                        status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1353                    }
1354                }
1355                CombineState::Conflict => {
1356                    status.state = "conflict".to_string();
1357                }
1358                CombineState::CheckFailed => {
1359                    status.state = "check_failed".to_string();
1360                }
1361            }
1362            status
1363        }
1364    }
1365}
1366
1367fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1368    status.branch = Some(rec.branch.clone());
1369    status.base = Some(rec.base.clone());
1370    if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1371        status.commits = commits;
1372    }
1373    status.check = Some(rec.check);
1374    status.conflicting_run = rec.conflicting_run.clone();
1375    status.conflicting_files = rec.conflicting_files.clone();
1376    status.failing_step = rec.failing_step.clone();
1377    status.output_tail = rec.output_tail.clone();
1378}
1379
1380pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1381    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
1382    if surface.requests.is_combining(request) {
1383        return Err(RequestActionError::Conflict(format!(
1384            "request {request} is currently combining"
1385        )));
1386    }
1387    let record = load_combine_record(&surface.root, request)
1388        .map_err(RequestActionError::Internal)?
1389        .ok_or_else(|| {
1390            RequestActionError::Conflict(format!("request {request} has not been combined"))
1391        })?;
1392    if record.state != CombineState::Combined {
1393        return Err(RequestActionError::Conflict(format!(
1394            "request {request} is not combined (state: {:?})",
1395            record.state
1396        )));
1397    }
1398    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1399        return Err(RequestActionError::Conflict(format!(
1400            "request {request} is done: its branches were already merged and removed"
1401        )));
1402    }
1403
1404    let mut published =
1405        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1406
1407    match surface.publisher.push_branch(&surface.root, &record.branch) {
1408        Ok(()) => {
1409            let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1410            let branch_commit =
1411                git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1412            published.pushed_commit = Some(branch_commit);
1413            write_published_record(&surface.root, request, &published)
1414                .map_err(RequestActionError::Internal)?;
1415            if let Err(e) = surface.session.record_decision(
1416                request,
1417                "push",
1418                Some(&format!("pushed {}", record.branch)),
1419                None,
1420            ) {
1421                surface.session.record_error(&format!(
1422                    "failed to record push decision for {request}: {e}"
1423                ));
1424            }
1425            Ok(())
1426        }
1427        Err(e) => {
1428            surface.session.record_error(&format!(
1429                "push failed for {request} ({}): {e}",
1430                record.branch
1431            ));
1432            Err(RequestActionError::Internal(e))
1433        }
1434    }
1435}
1436
1437pub fn open_request_pull_request(
1438    surface: &Surface,
1439    request: &str,
1440    title: &str,
1441    body: &str,
1442) -> Result<String, RequestActionError> {
1443    crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
1444    let trimmed_title = title.trim();
1445    if trimmed_title.is_empty() {
1446        return Err(RequestActionError::BadRequest(
1447            "field title must not be empty".to_string(),
1448        ));
1449    }
1450    if surface.requests.is_combining(request) {
1451        return Err(RequestActionError::Conflict(format!(
1452            "request {request} is currently combining"
1453        )));
1454    }
1455    let record = load_combine_record(&surface.root, request)
1456        .map_err(RequestActionError::Internal)?
1457        .ok_or_else(|| {
1458            RequestActionError::Conflict(format!("request {request} has not been combined"))
1459        })?;
1460    if record.state != CombineState::Combined {
1461        return Err(RequestActionError::Conflict(format!(
1462            "request {request} is not combined (state: {:?})",
1463            record.state
1464        )));
1465    }
1466    if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1467        return Err(RequestActionError::Conflict(format!(
1468            "request {request} is done: its branches were already merged and removed"
1469        )));
1470    }
1471
1472    let mut published =
1473        load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1474    if !is_record_pushed(&published, &record) {
1475        return Err(RequestActionError::Conflict(format!(
1476            "branch {} must be pushed before opening a pull request",
1477            record.branch
1478        )));
1479    }
1480
1481    match surface
1482        .publisher
1483        .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1484    {
1485        Ok(url) => {
1486            published.pull_request_url = Some(url.clone());
1487            write_published_record(&surface.root, request, &published)
1488                .map_err(RequestActionError::Internal)?;
1489            if let Err(e) =
1490                surface
1491                    .session
1492                    .record_decision(request, "pull_request", Some(&url), None)
1493            {
1494                surface.session.record_error(&format!(
1495                    "failed to record pull_request decision for {request}: {e}"
1496                ));
1497            }
1498            Ok(url)
1499        }
1500        Err(e) => {
1501            surface.session.record_error(&format!(
1502                "pull request failed for {request} ({}): {e}",
1503                record.branch
1504            ));
1505            Err(RequestActionError::Internal(e))
1506        }
1507    }
1508}
1509
1510#[cfg(test)]
1511mod tests {
1512    use super::*;
1513
1514    fn run_git(dir: &Path, args: &[&str]) -> String {
1515        let out = Command::new("git")
1516            .args(args)
1517            .current_dir(dir)
1518            .output()
1519            .unwrap();
1520        assert!(
1521            out.status.success(),
1522            "git {} failed: {}",
1523            args.join(" "),
1524            String::from_utf8_lossy(&out.stderr)
1525        );
1526        String::from_utf8_lossy(&out.stdout).trim().to_string()
1527    }
1528
1529    fn write_test_file(path: &Path, content: &str) {
1530        if let Some(parent) = path.parent() {
1531            std::fs::create_dir_all(parent).unwrap();
1532        }
1533        std::fs::write(path, content).unwrap();
1534    }
1535
1536    #[test]
1537    fn a_combined_run_without_a_summary_errors_naming_the_file() {
1538        let d = tempfile::tempdir().unwrap();
1539        let repo = d.path().join("missing-summary-repo");
1540        std::fs::create_dir_all(&repo).unwrap();
1541        run_git(&repo, &["init", "-q", "-b", "main"]);
1542        run_git(&repo, &["config", "user.email", "test@example.com"]);
1543        run_git(&repo, &["config", "user.name", "Test"]);
1544        write_test_file(&repo.join("README.md"), "hello\n");
1545        write_test_file(&repo.join("blyte.toml"), "[dispatch]\ngate = \"true\"\n");
1546        run_git(&repo, &["add", "."]);
1547        run_git(&repo, &["commit", "-q", "-m", "initial"]);
1548        let base_sha = run_git(&repo, &["rev-parse", "HEAD"]);
1549
1550        let wt_run = repo.join(".wt/MS1");
1551        std::fs::create_dir_all(repo.join(".wt")).unwrap();
1552        assert!(Command::new("git")
1553            .args(["worktree", "add", "-q", "-b", "wip/MS1"])
1554            .arg(&wt_run)
1555            .arg(&base_sha)
1556            .current_dir(&repo)
1557            .status()
1558            .unwrap()
1559            .success());
1560        write_test_file(&wt_run.join("ms1.txt"), "one\n");
1561        run_git(&wt_run, &["add", "ms1.txt"]);
1562        run_git(&wt_run, &["commit", "-q", "-m", "feat: MS1"]);
1563        assert!(Command::new("git")
1564            .args(["worktree", "remove", "--force"])
1565            .arg(&wt_run)
1566            .current_dir(&repo)
1567            .status()
1568            .unwrap()
1569            .success());
1570
1571        write_test_file(&repo.join(".wt/tasks/MS1.md"), "# Task MS1\n");
1572        write_test_file(
1573            &repo.join(".wt/MS1.start.json"),
1574            &format!(
1575                r#"{{"id":"MS1","pid":999999,"started_at":100,"base_sha":"{base_sha}","task_file":".wt/tasks/MS1.md","research":false,"request":"req-ms"}}"#
1576            ),
1577        );
1578        let summary_path = repo.join(".wt/MS1.json");
1579        write_test_file(
1580            &summary_path,
1581            r#"{"id":"MS1","outcome":"verified","branch":"wip/MS1","turns":2,"seconds":5,"cost_usd":0.01,"final_message":"done"}"#,
1582        );
1583        write_test_file(
1584            &repo.join(".wt/MS1.checks.json"),
1585            r#"{"flags":[],"fallbacks":[]}"#,
1586        );
1587
1588        let mut out = Vec::new();
1589        let mut err = Vec::new();
1590        let code = crate::combine::combine_in(&repo, "req-ms", &mut out, &mut err);
1591        assert_eq!(code, 0, "combine failed: {}", String::from_utf8_lossy(&err));
1592        assert_eq!(run_is_combined(&repo, "MS1", Some("req-ms")), Ok(true));
1593
1594        std::fs::remove_file(&summary_path).unwrap();
1595        let err_msg = run_is_combined(&repo, "MS1", Some("req-ms")).unwrap_err();
1596        assert!(
1597            err_msg.contains(".wt/MS1.json"),
1598            "expected error to contain .wt/MS1.json, got: {err_msg}"
1599        );
1600    }
1601
1602    #[test]
1603    fn a_combined_run_with_non_string_branch_errors_naming_the_file() {
1604        let d = tempfile::tempdir().unwrap();
1605        let repo = d.path().join("non-string-branch-repo");
1606        write_test_file(
1607            &repo.join(".wt/combined/req-ns.json"),
1608            r#"{"request":"req-ns","state":"combined","branch":"request/req-ns","base":"0000000","runs":[{"id":"NS1","tip":"1111111"}],"commits":["1111111"]}"#,
1609        );
1610        write_test_file(
1611            &repo.join(".wt/NS1.json"),
1612            r#"{"id":"NS1","outcome":"verified","branch":42}"#,
1613        );
1614
1615        let err_msg = run_is_combined(&repo, "NS1", Some("req-ns")).unwrap_err();
1616        assert!(
1617            err_msg.contains(".wt/NS1.json"),
1618            "expected error to contain .wt/NS1.json, got: {err_msg}"
1619        );
1620    }
1621
1622    #[test]
1623    fn a_combined_run_with_git_error_returns_error_naming_run_and_branch() {
1624        let d = tempfile::tempdir().unwrap();
1625        let non_repo = d.path().join("not-a-git-repo");
1626        write_test_file(
1627            &non_repo.join(".wt/combined/req-ge.json"),
1628            r#"{"request":"req-ge","state":"combined","branch":"request/req-ge","base":"0000000","runs":[{"id":"GE1","tip":"1111111"}],"commits":["1111111"]}"#,
1629        );
1630        write_test_file(
1631            &non_repo.join(".wt/GE1.json"),
1632            r#"{"id":"GE1","outcome":"verified","branch":"wip/GE1"}"#,
1633        );
1634
1635        let err_msg = run_is_combined(&non_repo, "GE1", Some("req-ge")).unwrap_err();
1636        assert!(
1637            err_msg.contains("GE1") && err_msg.contains("wip/GE1"),
1638            "expected error to name run and branch, got: {err_msg}"
1639        );
1640    }
1641}