1use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4use std::process::Command;
5use std::sync::atomic::{AtomicU64, Ordering};
6use std::sync::{Arc, Condvar, Mutex, MutexGuard};
7
8use serde::{Deserialize, Serialize};
9
10use crate::cli::ReviewVerdict;
11use crate::combine::{CombineCheck, CombineRecord, CombineState, CombinedRun};
12use crate::serve::Surface;
13
14static TMP_COUNTER: AtomicU64 = AtomicU64::new(1);
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum Readiness {
18 Ready,
19 Waiting { reasons: Vec<String> },
20}
21
22pub trait Publisher: Send + Sync {
23 fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String>;
24 fn open_pull_request(
25 &self,
26 root: &Path,
27 branch: &str,
28 title: &str,
29 body: &str,
30 ) -> Result<String, String>;
31}
32
33pub struct RealPublisher;
34
35impl Publisher for RealPublisher {
36 fn push_branch(&self, root: &Path, branch: &str) -> Result<(), String> {
37 crate::publish::push_branch(root, branch)
38 }
39
40 fn open_pull_request(
41 &self,
42 root: &Path,
43 branch: &str,
44 title: &str,
45 body: &str,
46 ) -> Result<String, String> {
47 crate::publish::open_pull_request(root, branch, title, body)
48 }
49}
50
51#[derive(Default)]
52struct RequestsInner {
53 running: HashSet<String>,
54 publishing: HashSet<String>,
55}
56
57pub struct PublishGuard {
58 state: Arc<RequestsState>,
59 request: String,
60}
61
62impl Drop for PublishGuard {
63 fn drop(&mut self) {
64 let mut inner = self.state.lock_inner();
65 inner.publishing.remove(&self.request);
66 }
67}
68
69pub struct RequestsState {
70 inner: Mutex<RequestsInner>,
71 cv: Condvar,
72}
73
74impl Default for RequestsState {
75 fn default() -> Self {
76 Self::new()
77 }
78}
79
80impl RequestsState {
81 pub fn new() -> Self {
82 Self {
83 inner: Mutex::new(RequestsInner::default()),
84 cv: Condvar::new(),
85 }
86 }
87
88 fn lock_inner(&self) -> MutexGuard<'_, RequestsInner> {
89 self.inner.lock().unwrap_or_else(|e| e.into_inner())
90 }
91
92 pub fn is_combining(&self, request: &str) -> bool {
93 self.lock_inner().running.contains(request)
94 }
95
96 pub fn try_begin_publish(self: &Arc<Self>, request: &str) -> Option<PublishGuard> {
97 let mut inner = self.lock_inner();
98 if !inner.publishing.insert(request.to_string()) {
99 return None;
100 }
101 Some(PublishGuard {
102 state: Arc::clone(self),
103 request: request.to_string(),
104 })
105 }
106
107 pub fn wait_for_idle(&self, request: &str) {
108 let mut inner = self.lock_inner();
109 while inner.running.contains(request) {
110 inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
111 }
112 }
113
114 pub fn wait_all_idle(&self) {
115 let mut inner = self.lock_inner();
116 while !inner.running.is_empty() {
117 inner = self.cv.wait(inner).unwrap_or_else(|e| e.into_inner());
118 }
119 }
120}
121
122#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
123pub struct CommitSummary {
124 pub sha: String,
125 pub subject: String,
126}
127
128#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
129#[serde(deny_unknown_fields)]
130pub struct PublishedRecord {
131 #[serde(default, skip_serializing_if = "Option::is_none")]
132 pub pushed_commit: Option<String>,
133 #[serde(default, skip_serializing_if = "Option::is_none")]
134 pub pull_request_url: Option<String>,
135}
136
137#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
138#[serde(rename_all = "snake_case")]
139pub enum AttemptResult {
140 Combined,
141 Conflict,
142 CheckFailed,
143 Error,
144}
145
146#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
147#[serde(deny_unknown_fields)]
148pub struct AttemptRecord {
149 pub runs: Vec<CombinedRun>,
150 pub result: AttemptResult,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub error: Option<String>,
153 pub reported: bool,
154}
155
156#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
157pub struct RequestStatus {
158 pub request: String,
159 pub runs: Vec<String>,
160 pub left_out: Vec<String>,
161 pub state: String,
162 pub waiting_reasons: Vec<String>,
163 pub branch: Option<String>,
164 pub base: Option<String>,
165 pub commits: Vec<CommitSummary>,
166 #[serde(skip_serializing_if = "Option::is_none")]
167 pub check: Option<CombineCheck>,
168 pub conflicting_run: Option<String>,
169 pub conflicting_files: Vec<String>,
170 pub failing_step: Option<String>,
171 pub output_tail: Option<String>,
172 pub error: Option<String>,
173 pub suggested_title: Option<String>,
174 pub suggested_body: Option<String>,
175 pub pushed: bool,
176 pub pull_request_url: Option<String>,
177 pub started_by: Option<String>,
178}
179
180#[derive(Clone, Debug, PartialEq, Eq)]
181pub enum RequestActionError {
182 BadRequest(String),
183 NotOwned(String),
184 Conflict(String),
185 Internal(String),
186}
187
188struct StartRunInfo {
189 id: String,
190 request: Option<String>,
191 surface: Option<String>,
192 started_by: Option<String>,
193 base: Option<String>,
194 started_at: u64,
195 is_research: bool,
196}
197
198fn is_research_start(wt_dir: &Path, id: &str, val: &serde_json::Value) -> bool {
199 val.get("research")
200 .and_then(|v| v.as_bool())
201 .unwrap_or(false)
202 || val
203 .get("tags")
204 .and_then(|v| v.as_array())
205 .is_some_and(|arr| arr.iter().any(|t| t.as_str() == Some("research")))
206 || wt_dir.join(format!("{id}.report.md")).exists()
207}
208
209fn parse_start_file(wt_dir: &Path, path: &Path) -> Result<StartRunInfo, String> {
210 let content = std::fs::read_to_string(path)
211 .map_err(|e| format!("failed to read {}: {e}", path.display()))?;
212 let val: serde_json::Value = serde_json::from_str(&content)
213 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
214 let file_id = path
215 .file_name()
216 .and_then(|n| n.to_str())
217 .and_then(|n| n.strip_suffix(".start.json"))
218 .filter(|s| !s.is_empty())
219 .ok_or_else(|| format!("invalid start file name: {}", path.display()))?;
220 if let Some(id_val) = val.get("id") {
221 let field_id = id_val.as_str().ok_or_else(|| {
222 format!(
223 "start file {} has non-string id {id_val}, expected {file_id}",
224 path.display()
225 )
226 })?;
227 if field_id != file_id {
228 return Err(format!(
229 "start file {} has id {field_id} which differs from file name id {file_id}",
230 path.display()
231 ));
232 }
233 }
234 let request = match val.get("request") {
235 None | Some(serde_json::Value::Null) => None,
236 Some(serde_json::Value::String(s)) => Some(s.clone()),
237 Some(_) => {
238 return Err(format!(
239 "start file {} has non-string request field",
240 path.display()
241 ));
242 }
243 };
244 let surface = match val.get("surface") {
245 None | Some(serde_json::Value::Null) => None,
246 Some(serde_json::Value::String(s)) => Some(s.clone()),
247 Some(_) => {
248 return Err(format!(
249 "start file {} has non-string surface field",
250 path.display()
251 ));
252 }
253 };
254 let started_by = match val.get("started_by") {
255 None | Some(serde_json::Value::Null) => None,
256 Some(serde_json::Value::String(s)) if !s.is_empty() => Some(s.clone()),
257 Some(_) => {
258 return Err(format!(
259 "{}: started_by must be a surface name",
260 path.display()
261 ));
262 }
263 };
264 let base = match val.get("base") {
265 None | Some(serde_json::Value::Null) => None,
266 Some(serde_json::Value::String(s)) => Some(s.clone()),
267 Some(_) => {
268 return Err(format!(
269 "start file {} has non-string base field",
270 path.display()
271 ));
272 }
273 };
274 let is_research = is_research_start(wt_dir, file_id, &val);
275 let started_at = match val.get("started_at") {
276 Some(v) => v
277 .as_u64()
278 .ok_or_else(|| format!("start file {} has non-numeric started_at", path.display()))?,
279 None => 0,
280 };
281 Ok(StartRunInfo {
282 id: file_id.to_string(),
283 request,
284 surface,
285 started_by,
286 base,
287 started_at,
288 is_research,
289 })
290}
291
292fn list_start_files(wt_dir: &Path) -> Result<Vec<PathBuf>, String> {
293 let read_dir = match std::fs::read_dir(wt_dir) {
294 Ok(rd) => rd,
295 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(Vec::new()),
296 Err(e) => return Err(format!("failed to read {}: {e}", wt_dir.display())),
297 };
298 let mut entries = Vec::new();
299 for entry in read_dir {
300 let entry =
301 entry.map_err(|e| format!("failed to read entry in {}: {e}", wt_dir.display()))?;
302 let path = entry.path();
303 if path
304 .file_name()
305 .and_then(|n| n.to_str())
306 .is_some_and(|n| n.ends_with(".start.json"))
307 {
308 entries.push(path);
309 }
310 }
311 entries.sort();
312 Ok(entries)
313}
314
315enum RequestOwnership {
316 Owned,
317 OtherSurface,
318 Unowned,
319 NotFound,
320}
321
322enum RequestOwnershipError {
323 Mixed(String),
324 IoOrParse(String),
325}
326
327fn check_request_ownership(
328 surface: &Surface,
329 request: &str,
330) -> Result<RequestOwnership, RequestOwnershipError> {
331 let wt_dir = surface.root.join(".wt");
332 let entries = list_start_files(&wt_dir).map_err(RequestOwnershipError::IoOrParse)?;
333 let mut owners: HashSet<Option<String>> = HashSet::new();
334 let mut started_bys: HashSet<Option<String>> = HashSet::new();
335 for path in entries {
336 let info = parse_start_file(&wt_dir, &path).map_err(RequestOwnershipError::IoOrParse)?;
337 if info.request.as_deref() == Some(request) {
338 owners.insert(info.surface);
339 started_bys.insert(info.started_by);
340 }
341 }
342 if owners.is_empty() {
343 return Ok(RequestOwnership::NotFound);
344 }
345 if owners.len() > 1 {
346 return Err(RequestOwnershipError::Mixed(format!(
347 "request {request} has runs from more than one surface"
348 )));
349 }
350 if started_bys.len() > 1 {
351 return Err(RequestOwnershipError::Mixed(format!(
352 "request {request} has runs started by different surfaces"
353 )));
354 }
355 match owners.into_iter().next().flatten() {
356 Some(owner) if owner == surface.surface_id => Ok(RequestOwnership::Owned),
357 Some(_) => Ok(RequestOwnership::OtherSurface),
358 None => Ok(RequestOwnership::Unowned),
359 }
360}
361
362pub fn owned_run_ids(surface: &Surface) -> Result<HashSet<String>, String> {
363 let wt_dir = surface.root.join(".wt");
364 let entries = list_start_files(&wt_dir)?;
365 let mut ids = HashSet::new();
366 for path in entries {
367 let info = parse_start_file(&wt_dir, &path)?;
368 if info.surface.as_deref() == Some(surface.surface_id.as_str()) {
369 ids.insert(info.id);
370 }
371 }
372 Ok(ids)
373}
374
375pub fn request_owner_check(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
376 crate::dispatch::validate_request_id(request).map_err(RequestActionError::BadRequest)?;
377 match check_request_ownership(surface, request) {
378 Ok(RequestOwnership::Owned) => Ok(()),
379 Ok(RequestOwnership::OtherSurface) => Err(RequestActionError::NotOwned(format!(
380 "request {request} belongs to another surface"
381 ))),
382 Ok(RequestOwnership::Unowned) => Err(RequestActionError::NotOwned(format!(
383 "request {request} was not started by a surface"
384 ))),
385 Ok(RequestOwnership::NotFound) => Err(RequestActionError::Conflict(format!(
386 "request {request} has not been combined"
387 ))),
388 Err(RequestOwnershipError::Mixed(msg)) => Err(RequestActionError::BadRequest(msg)),
389 Err(RequestOwnershipError::IoOrParse(msg)) => Err(RequestActionError::Internal(msg)),
390 }
391}
392
393pub(crate) fn run_owner_check(surface: &Surface, run_id: &str) -> Result<(), RequestActionError> {
394 let wt_dir = surface.root.join(".wt");
395 let path = wt_dir.join(format!("{run_id}.start.json"));
396 if !path.exists() {
397 return Err(RequestActionError::NotOwned(format!(
398 "run {run_id} was not started by a surface"
399 )));
400 }
401 let info = parse_start_file(&wt_dir, &path).map_err(RequestActionError::Internal)?;
402 match info.surface.as_deref() {
403 Some(owner) if owner == surface.surface_id => Ok(()),
404 Some(_) => Err(RequestActionError::NotOwned(format!(
405 "run {run_id} belongs to another surface"
406 ))),
407 None => Err(RequestActionError::NotOwned(format!(
408 "run {run_id} was not started by a surface"
409 ))),
410 }
411}
412
413pub fn run_request_id(root: &Path, run_id: &str) -> Result<Option<String>, String> {
414 let wt_dir = root.join(".wt");
415 let path = wt_dir.join(format!("{run_id}.start.json"));
416 if !path.exists() {
417 return Ok(None);
418 }
419 let info = parse_start_file(&wt_dir, &path)?;
420 if info.is_research {
421 return Ok(None);
422 }
423 Ok(info.request)
424}
425
426pub fn request_readiness(root: &Path, request: &str) -> Result<Readiness, String> {
427 crate::dispatch::validate_request_id(request)?;
428 let wt_dir = root.join(".wt");
429 let entries = list_start_files(&wt_dir)?;
430 let mut matched_runs = Vec::new();
431 for path in entries {
432 let info = parse_start_file(&wt_dir, &path)?;
433 if info.is_research {
434 continue;
435 }
436 if info.request.as_deref() == Some(request) {
437 matched_runs.push(info);
438 }
439 }
440 if matched_runs.is_empty() {
441 return Ok(Readiness::Waiting {
442 reasons: vec!["no runs for request".to_string()],
443 });
444 }
445 matched_runs.sort_by(|a, b| {
446 a.started_at
447 .cmp(&b.started_at)
448 .then_with(|| a.id.cmp(&b.id))
449 });
450
451 let mut active_runs = Vec::new();
452 let mut left_out_ids: BTreeSet<String> = BTreeSet::new();
453 for run in matched_runs {
454 let verdict = crate::queue_actions::read_verdict(root, &run.id)?;
455 if crate::combine::is_left_out_verdict(verdict) {
456 left_out_ids.insert(run.id);
457 } else {
458 active_runs.push((run, verdict));
459 }
460 }
461
462 if active_runs.is_empty() {
463 return Ok(Readiness::Waiting {
464 reasons: vec!["every run was redone".to_string()],
465 });
466 }
467
468 let left_out_refs: BTreeSet<&str> = left_out_ids.iter().map(String::as_str).collect();
469 for (run, _) in &active_runs {
470 crate::combine::check_not_based_on_left_out(
471 root,
472 &run.id,
473 run.base.as_deref(),
474 &left_out_refs,
475 )?;
476 }
477
478 let mut reasons = Vec::new();
479 for (run, verdict) in active_runs {
480 let id = &run.id;
481 let summary_path = wt_dir.join(format!("{id}.json"));
482 let outcome = match std::fs::read_to_string(&summary_path) {
483 Ok(raw) => {
484 let val: serde_json::Value = serde_json::from_str(&raw)
485 .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
486 let outcome = val
487 .get("outcome")
488 .and_then(|v| v.as_str())
489 .ok_or_else(|| {
490 format!(
491 "summary file {} is missing string outcome",
492 summary_path.display()
493 )
494 })?
495 .to_string();
496 if outcome != "verified" {
497 reasons.push(format!("{id}: {outcome}"));
498 }
499 Some(outcome)
500 }
501 Err(e) if e.kind() == ErrorKind::NotFound => {
502 reasons.push(format!("{id}: unfinished"));
503 None
504 }
505 Err(e) => {
506 return Err(format!("failed to read {}: {e}", summary_path.display()));
507 }
508 };
509
510 let checks_path = wt_dir.join(format!("{id}.checks.json"));
511 let (checks_recorded, flags) = crate::replay::read_checks(&checks_path)
512 .map_err(|e| format!("{}: {e}", checks_path.display()))?;
513
514 if crate::queue_actions::read_hold(root, id)?.is_some() {
515 reasons.push(format!("{id}: on hold"));
516 }
517
518 if let Some(ref outcome_str) = outcome {
519 if outcome_str == "verified" {
520 if !checks_recorded {
521 reasons.push(format!("{id}: no checks file"));
522 } else {
523 let card =
524 crate::replay::card_for_run(false, outcome_str, checks_recorded, &flags);
525 let cleared_by_verdict = matches!(
526 verdict,
527 Some(ReviewVerdict::Accepted | ReviewVerdict::Fixed)
528 );
529 if card != "clean" && !cleared_by_verdict {
530 reasons.push(format!("{id}: flagged ({})", flags.join("; ")));
531 }
532 }
533 }
534 }
535 }
536
537 if reasons.is_empty() {
538 Ok(Readiness::Ready)
539 } else {
540 Ok(Readiness::Waiting { reasons })
541 }
542}
543
544fn combine_record_path(root: &Path, request: &str) -> PathBuf {
545 root.join(".wt")
546 .join("combined")
547 .join(format!("{request}.json"))
548}
549
550fn attempt_record_path(root: &Path, request: &str) -> PathBuf {
551 root.join(".wt")
552 .join("combined")
553 .join(format!("{request}.attempt.json"))
554}
555
556fn published_record_path(root: &Path, request: &str) -> PathBuf {
557 root.join(".wt")
558 .join("combined")
559 .join(format!("{request}.published.json"))
560}
561
562fn write_json_atomic<T: Serialize>(path: &Path, value: &T, label: &str) -> Result<(), String> {
563 if let Some(parent) = path.parent() {
564 std::fs::create_dir_all(parent)
565 .map_err(|e| format!("failed to create {}: {e}", parent.display()))?;
566 }
567 let mut json = serde_json::to_string_pretty(value)
568 .map_err(|e| format!("failed to serialize {label}: {e}"))?;
569 json.push('\n');
570 let mut tmp_name = path.as_os_str().to_os_string();
571 let seq = TMP_COUNTER.fetch_add(1, Ordering::Relaxed);
572 tmp_name.push(format!(".tmp.{}.{seq}", std::process::id()));
573 let tmp_path = PathBuf::from(tmp_name);
574 std::fs::write(&tmp_path, json)
575 .map_err(|e| format!("failed to write {}: {e}", tmp_path.display()))?;
576 std::fs::rename(&tmp_path, path).map_err(|e| {
577 let _ = std::fs::remove_file(&tmp_path);
578 format!(
579 "failed to rename {} to {}: {e}",
580 tmp_path.display(),
581 path.display()
582 )
583 })
584}
585
586pub fn load_combine_record(root: &Path, request: &str) -> Result<Option<CombineRecord>, String> {
587 let path = combine_record_path(root, request);
588 let raw = match std::fs::read_to_string(&path) {
589 Ok(s) => s,
590 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
591 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
592 };
593 let record: CombineRecord = serde_json::from_str(&raw)
594 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
595 Ok(Some(record))
596}
597
598pub fn load_attempt_record(root: &Path, request: &str) -> Result<Option<AttemptRecord>, String> {
599 let path = attempt_record_path(root, request);
600 let raw = match std::fs::read_to_string(&path) {
601 Ok(s) => s,
602 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(None),
603 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
604 };
605 let record: AttemptRecord = serde_json::from_str(&raw)
606 .map_err(|e| format!("failed to parse {}: {e}", path.display()))?;
607 if record.result == AttemptResult::Error
608 && record.error.as_deref().is_none_or(|s| s.trim().is_empty())
609 {
610 return Err(format!(
611 "invalid attempt file {}: result error is missing error text",
612 path.display()
613 ));
614 }
615 Ok(Some(record))
616}
617
618pub fn write_attempt_record(
619 root: &Path,
620 request: &str,
621 record: &AttemptRecord,
622) -> Result<(), String> {
623 let path = attempt_record_path(root, request);
624 write_json_atomic(&path, record, "attempt record")
625}
626
627pub fn load_published_record(root: &Path, request: &str) -> Result<PublishedRecord, String> {
628 let path = published_record_path(root, request);
629 let raw = match std::fs::read_to_string(&path) {
630 Ok(s) => s,
631 Err(e) if e.kind() == ErrorKind::NotFound => return Ok(PublishedRecord::default()),
632 Err(e) => return Err(format!("failed to read {}: {e}", path.display())),
633 };
634 serde_json::from_str(&raw).map_err(|e| format!("failed to parse {}: {e}", path.display()))
635}
636
637pub fn write_published_record(
638 root: &Path,
639 request: &str,
640 record: &PublishedRecord,
641) -> Result<(), String> {
642 let path = published_record_path(root, request);
643 write_json_atomic(&path, record, "published record")
644}
645
646fn git_stdout(root: &Path, args: &[&str]) -> Result<String, String> {
647 let out = Command::new("git")
648 .args(args)
649 .current_dir(root)
650 .output()
651 .map_err(|e| format!("failed to run git {}: {e}", args.join(" ")))?;
652 if !out.status.success() {
653 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
654 return Err(format!("git {} failed: {stderr}", args.join(" ")));
655 }
656 Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
657}
658
659fn git_rev_parse(root: &Path, rev: &str) -> Result<String, String> {
660 git_stdout(root, &["rev-parse", "--verify", rev])
661}
662
663fn git_commit_subject(root: &Path, sha: &str) -> Result<String, String> {
664 git_stdout(root, &["show", "-s", "--format=%s", sha])
665 .map_err(|e| format!("failed to read subject for commit {sha}: {e}"))
666}
667
668fn run_branch(wt_dir: &Path, run_id: &str) -> Result<String, String> {
669 let summary_path = wt_dir.join(format!("{run_id}.json"));
670 let raw = std::fs::read_to_string(&summary_path)
671 .map_err(|e| format!("failed to read {}: {e}", summary_path.display()))?;
672 let val: serde_json::Value = serde_json::from_str(&raw)
673 .map_err(|e| format!("failed to parse {}: {e}", summary_path.display()))?;
674 let branch_hint = match val.get("branch") {
675 None | Some(serde_json::Value::Null) => None,
676 Some(serde_json::Value::String(s)) => Some(s.clone()),
677 Some(_) => {
678 return Err(format!(
679 "summary file {} has non-string branch",
680 summary_path.display()
681 ));
682 }
683 };
684 Ok(branch_hint.unwrap_or_else(|| format!("wip/{run_id}")))
685}
686
687fn git_branch_exists(root: &Path, run_id: &str, branch: &str) -> Result<bool, String> {
688 let ref_name = format!("refs/heads/{branch}");
689 let out = Command::new("git")
690 .args(["show-ref", "--verify", "--quiet", &ref_name])
691 .current_dir(root)
692 .output()
693 .map_err(|e| {
694 format!("run {run_id}: failed to check branch {branch} with git show-ref: {e}")
695 })?;
696 match out.status.code() {
697 Some(0) => Ok(true),
698 Some(1) => Ok(false),
699 code => {
700 let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
701 let status_desc = match code {
702 Some(c) => format!("exit code {c}"),
703 None => "terminated by signal".to_string(),
704 };
705 if stderr.is_empty() {
706 Err(format!(
707 "run {run_id}: git show-ref failed for branch {branch} ({status_desc})"
708 ))
709 } else {
710 Err(format!(
711 "run {run_id}: git show-ref failed for branch {branch} ({status_desc}): {stderr}"
712 ))
713 }
714 }
715 }
716}
717
718fn resolve_current_run_tips(root: &Path, request: &str) -> Result<Vec<CombinedRun>, String> {
719 let wt_dir = root.join(".wt");
720 let entries = list_start_files(&wt_dir)?;
721 let mut tips = BTreeMap::new();
722 for path in entries {
723 let info = parse_start_file(&wt_dir, &path)?;
724 if info.is_research || info.request.as_deref() != Some(request) {
725 continue;
726 }
727 if crate::combine::is_run_left_out(root, &info.id)? {
728 continue;
729 }
730 let branch = run_branch(&wt_dir, &info.id)?;
731 let rev = format!("refs/heads/{branch}^{{commit}}");
732 let sha = git_rev_parse(root, &rev).map_err(|e| {
733 format!(
734 "run {}: branch {branch} does not resolve to a commit: {e}",
735 info.id
736 )
737 })?;
738 tips.insert(info.id, sha);
739 }
740 Ok(tips
741 .into_iter()
742 .map(|(id, tip)| CombinedRun { id, tip })
743 .collect())
744}
745
746fn sorted_runs(mut runs: Vec<CombinedRun>) -> Vec<CombinedRun> {
747 runs.sort_by(|a, b| a.id.cmp(&b.id));
748 runs
749}
750
751fn record_runs_match_tips(record: &CombineRecord, current_runs: &[CombinedRun]) -> bool {
752 if record.runs.len() != current_runs.len() {
753 return false;
754 }
755 sorted_runs(record.runs.clone()) == current_runs
756}
757
758enum CombinedRunBranchState {
759 Gone,
760 AtRecordedTip,
761 Changed,
762}
763
764fn check_recorded_run_branch(
765 root: &Path,
766 wt_dir: &Path,
767 run: &CombinedRun,
768) -> Result<CombinedRunBranchState, String> {
769 let branch = run_branch(wt_dir, &run.id)?;
770 if !git_branch_exists(root, &run.id, &branch)? {
771 return Ok(CombinedRunBranchState::Gone);
772 }
773 let rev = format!("refs/heads/{branch}^{{commit}}");
774 let sha = git_rev_parse(root, &rev).map_err(|e| {
775 format!(
776 "run {}: branch {branch} does not resolve to a commit: {e}",
777 run.id
778 )
779 })?;
780 if sha == run.tip {
781 Ok(CombinedRunBranchState::AtRecordedTip)
782 } else {
783 Ok(CombinedRunBranchState::Changed)
784 }
785}
786
787fn active_request_run_ids(root: &Path, request: &str) -> Result<Vec<String>, String> {
788 let wt_dir = root.join(".wt");
789 let entries = list_start_files(&wt_dir)?;
790 let mut run_ids = Vec::new();
791 for path in entries {
792 let info = parse_start_file(&wt_dir, &path)?;
793 if info.is_research || info.request.as_deref() != Some(request) {
794 continue;
795 }
796 if crate::combine::is_run_left_out(root, &info.id)? {
797 continue;
798 }
799 run_ids.push(info.id);
800 }
801 Ok(run_ids)
802}
803
804fn request_is_done(root: &Path, request: &str, rec: &CombineRecord) -> Result<bool, String> {
805 if rec.state != CombineState::Combined {
806 return Ok(false);
807 }
808 let active_runs = active_request_run_ids(root, request)?;
809 if active_runs.is_empty() {
810 return Ok(false);
811 }
812 let recorded_by_id: HashMap<&str, &CombinedRun> =
813 rec.runs.iter().map(|run| (run.id.as_str(), run)).collect();
814 let wt_dir = root.join(".wt");
815 let mut any_branch_gone = false;
816 for run_id in &active_runs {
817 let Some(&recorded_run) = recorded_by_id.get(run_id.as_str()) else {
818 return Ok(false);
819 };
820 match check_recorded_run_branch(root, &wt_dir, recorded_run)? {
821 CombinedRunBranchState::Gone => any_branch_gone = true,
822 CombinedRunBranchState::AtRecordedTip => {}
823 CombinedRunBranchState::Changed => return Ok(false),
824 }
825 }
826 Ok(any_branch_gone)
827}
828
829fn check_record_combined_for_request(
830 root: &Path,
831 request: &str,
832 run_ids: &[&str],
833) -> Result<BTreeSet<String>, String> {
834 let Some(rec) = load_combine_record(root, request)? else {
835 return Ok(BTreeSet::new());
836 };
837 if rec.state != CombineState::Combined {
838 return Ok(BTreeSet::new());
839 }
840 let wt_dir = root.join(".wt");
841 let mut combined = BTreeSet::new();
842 for run in &rec.runs {
843 if !run_ids.contains(&run.id.as_str()) {
844 continue;
845 }
846 match check_recorded_run_branch(root, &wt_dir, run)? {
847 CombinedRunBranchState::Gone | CombinedRunBranchState::AtRecordedTip => {
848 combined.insert(run.id.clone());
849 }
850 CombinedRunBranchState::Changed => {}
851 }
852 }
853 Ok(combined)
854}
855
856pub fn run_is_combined(root: &Path, run_id: &str, request: Option<&str>) -> Result<bool, String> {
857 let Some(request) = request else {
858 return Ok(false);
859 };
860 Ok(check_record_combined_for_request(root, request, &[run_id])?.contains(run_id))
861}
862
863pub fn combined_run_ids(
864 root: &Path,
865 runs: &[(&str, Option<&str>)],
866) -> Result<BTreeSet<String>, String> {
867 let mut by_request: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
868 for &(run_id, request) in runs {
869 if let Some(req) = request {
870 by_request.entry(req).or_default().push(run_id);
871 }
872 }
873 let mut combined = BTreeSet::new();
874 for (request, run_ids) in by_request {
875 combined.extend(check_record_combined_for_request(root, request, &run_ids)?);
876 }
877 Ok(combined)
878}
879
880fn combine_record_tip(record: &CombineRecord) -> &str {
881 record.commits.last().unwrap_or(&record.base).as_str()
882}
883
884fn is_record_pushed(published: &PublishedRecord, record: &CombineRecord) -> bool {
885 published.pushed_commit.as_deref() == Some(combine_record_tip(record))
886}
887
888fn branch_matches_record(root: &Path, record: &CombineRecord) -> bool {
889 let expected = combine_record_tip(record);
890 let rev = format!("refs/heads/{}^{{commit}}", record.branch);
891 git_rev_parse(root, &rev).is_ok_and(|actual| actual == expected)
892}
893
894fn format_record_failure(record: &CombineRecord, record_path: &Path) -> Result<String, String> {
895 match record.state {
896 CombineState::Conflict => {
897 let run = record
898 .conflicting_run
899 .as_deref()
900 .filter(|r| !r.is_empty())
901 .ok_or_else(|| {
902 format!(
903 "combine record {} has state conflict with missing conflicting_run",
904 record_path.display()
905 )
906 })?;
907 if record.conflicting_files.is_empty() {
908 return Err(format!(
909 "combine record {} has state conflict with empty conflicting_files",
910 record_path.display()
911 ));
912 }
913 let files = record.conflicting_files.join(", ");
914 Ok(format!(
915 "Combine failed for request {} (state: conflict).\nConflicting run: {run}\nConflicting files: {files}",
916 record.request
917 ))
918 }
919 CombineState::CheckFailed => {
920 let step = record
921 .failing_step
922 .as_deref()
923 .filter(|s| !s.is_empty())
924 .ok_or_else(|| {
925 format!(
926 "combine record {} has state check_failed with missing failing_step",
927 record_path.display()
928 )
929 })?;
930 let tail = record
931 .output_tail
932 .as_deref()
933 .filter(|t| !t.is_empty())
934 .ok_or_else(|| {
935 format!(
936 "combine record {} has state check_failed with missing or empty output_tail",
937 record_path.display()
938 )
939 })?;
940 Ok(format!(
941 "Combine failed for request {} (state: check_failed).\nFailing step: {step}\nOutput tail:\n{tail}",
942 record.request
943 ))
944 }
945 CombineState::Combined => Err(format!(
946 "combine record {} has state combined: not a failure record",
947 record_path.display()
948 )),
949 }
950}
951
952fn format_error_failure(request: &str, err_text: &str) -> String {
953 format!("Combine failed for request {request} (state: error).\nError: {err_text}")
954}
955
956struct RunningGuard {
957 state: Arc<RequestsState>,
958 request: String,
959}
960
961impl Drop for RunningGuard {
962 fn drop(&mut self) {
963 let mut inner = self.state.lock_inner();
964 inner.running.remove(&self.request);
965 self.state.cv.notify_all();
966 }
967}
968
969fn retry_failure_message(
970 root: &Path,
971 request: &str,
972 attempt: &AttemptRecord,
973) -> Result<String, String> {
974 let path = attempt_record_path(root, request);
975 match attempt.result {
976 AttemptResult::Conflict | AttemptResult::CheckFailed => {
977 let expected_state = match attempt.result {
978 AttemptResult::Conflict => CombineState::Conflict,
979 AttemptResult::CheckFailed => CombineState::CheckFailed,
980 AttemptResult::Combined | AttemptResult::Error => unreachable!(),
981 };
982 match load_combine_record(root, request)? {
983 Some(rec) if rec.state == expected_state => {
984 format_record_failure(&rec, &combine_record_path(root, request))
985 }
986 _ => Err(format!(
987 "attempt file {} has result {:?} without a matching combine record",
988 path.display(),
989 attempt.result
990 )),
991 }
992 }
993 AttemptResult::Error => {
994 let err_text = attempt.error.as_deref().ok_or_else(|| {
995 format!(
996 "attempt file {} has result error without error text",
997 path.display()
998 )
999 })?;
1000 Ok(format_error_failure(request, err_text))
1001 }
1002 AttemptResult::Combined => Err(format!(
1003 "cannot format failure message for combined attempt {}",
1004 path.display()
1005 )),
1006 }
1007}
1008
1009fn record_and_report_failure(
1010 root: &Path,
1011 session: &crate::session::Session,
1012 request: &str,
1013 runs: Vec<CombinedRun>,
1014 result: AttemptResult,
1015 error: Option<String>,
1016 msg: &str,
1017) {
1018 let mut attempt = AttemptRecord {
1019 runs,
1020 result,
1021 error,
1022 reported: false,
1023 };
1024 if let Err(e) = write_attempt_record(root, request, &attempt) {
1025 session.record_error(&format!(
1026 "failed to write attempt record for {request}: {e}"
1027 ));
1028 }
1029 match session.queue_for_request(request, msg) {
1030 Ok(_) => {
1031 attempt.reported = true;
1032 if let Err(e) = write_attempt_record(root, request, &attempt) {
1033 session.record_error(&format!(
1034 "failed to write attempt record for {request}: {e}"
1035 ));
1036 }
1037 }
1038 Err(e) => {
1039 session.record_error(&format!(
1040 "failed to queue combine failure for {request}: {e}"
1041 ));
1042 }
1043 }
1044}
1045
1046fn conversation_busy(surface: &Surface) -> bool {
1047 let info = surface.session.info();
1048 info.busy || info.queued > 0
1049}
1050
1051fn ready_waiting_reason(conversation_busy: bool) -> String {
1052 if conversation_busy {
1053 "the conversation model is still working".to_string()
1054 } else {
1055 "waiting to combine".to_string()
1056 }
1057}
1058
1059pub fn maybe_combine(surface: &Surface, request: &str) -> Result<bool, String> {
1060 crate::dispatch::validate_request_id(request)?;
1061 match check_request_ownership(surface, request) {
1062 Ok(RequestOwnership::Owned) => {}
1063 Ok(
1064 RequestOwnership::OtherSurface | RequestOwnership::Unowned | RequestOwnership::NotFound,
1065 ) => return Ok(false),
1066 Err(RequestOwnershipError::Mixed(msg) | RequestOwnershipError::IoOrParse(msg)) => {
1067 return Err(msg);
1068 }
1069 }
1070 if conversation_busy(surface) {
1071 return Ok(false);
1072 }
1073 match request_readiness(&surface.root, request)? {
1074 Readiness::Waiting { .. } => return Ok(false),
1075 Readiness::Ready => {}
1076 }
1077
1078 if let Some(rec) = load_combine_record(&surface.root, request)? {
1079 if request_is_done(&surface.root, request, &rec)? {
1080 return Ok(false);
1081 }
1082 }
1083
1084 let current_runs = resolve_current_run_tips(&surface.root, request)?;
1085
1086 {
1087 let mut inner = surface.requests.lock_inner();
1088 if inner.running.contains(request) {
1089 return Ok(false);
1090 }
1091 if let Some(mut attempt) = load_attempt_record(&surface.root, request)? {
1092 if attempt.runs == current_runs {
1093 if attempt.result != AttemptResult::Combined && !attempt.reported {
1094 match retry_failure_message(&surface.root, request, &attempt) {
1095 Ok(msg) => match surface.session.queue_for_request(request, &msg) {
1096 Ok(_) => {
1097 attempt.reported = true;
1098 write_attempt_record(&surface.root, request, &attempt)?;
1099 }
1100 Err(e) => {
1101 surface.session.record_error(&format!(
1102 "failed to queue combine failure for {request}: {e}"
1103 ));
1104 }
1105 },
1106 Err(e) => {
1107 let msg = format_error_failure(request, &e);
1108 record_and_report_failure(
1109 &surface.root,
1110 &surface.session,
1111 request,
1112 attempt.runs,
1113 AttemptResult::Error,
1114 Some(e),
1115 &msg,
1116 );
1117 }
1118 }
1119 }
1120 return Ok(false);
1121 }
1122 }
1123 inner.running.insert(request.to_string());
1124 }
1125
1126 let root = surface.root.clone();
1127 let session = surface.session.clone();
1128 let requests_state = Arc::clone(&surface.requests);
1129 let request_owned = request.to_string();
1130
1131 std::thread::spawn(move || {
1132 let _guard = RunningGuard {
1133 state: Arc::clone(&requests_state),
1134 request: request_owned.clone(),
1135 };
1136 let mut out = Vec::new();
1137 let mut err = Vec::new();
1138 let code = crate::combine::combine_in(&root, &request_owned, &mut out, &mut err);
1139
1140 match code {
1141 0 => {
1142 let runs = match load_combine_record(&root, &request_owned) {
1143 Ok(Some(rec)) => sorted_runs(rec.runs),
1144 Ok(None) => current_runs,
1145 Err(e) => {
1146 session.record_error(&format!(
1147 "failed to read combine record after combine for {request_owned}: {e}"
1148 ));
1149 current_runs
1150 }
1151 };
1152 let attempt = AttemptRecord {
1153 runs,
1154 result: AttemptResult::Combined,
1155 error: None,
1156 reported: false,
1157 };
1158 if let Err(e) = write_attempt_record(&root, &request_owned, &attempt) {
1159 session.record_error(&format!(
1160 "failed to write attempt record for {request_owned}: {e}"
1161 ));
1162 }
1163 }
1164 1 => match load_combine_record(&root, &request_owned) {
1165 Ok(Some(rec))
1166 if matches!(
1167 rec.state,
1168 CombineState::Conflict | CombineState::CheckFailed
1169 ) =>
1170 {
1171 let result = match rec.state {
1172 CombineState::Conflict => AttemptResult::Conflict,
1173 CombineState::CheckFailed => AttemptResult::CheckFailed,
1174 CombineState::Combined => unreachable!(),
1175 };
1176 let runs = sorted_runs(rec.runs.clone());
1177 let rec_path = combine_record_path(&root, &request_owned);
1178 match format_record_failure(&rec, &rec_path) {
1179 Ok(msg) => {
1180 record_and_report_failure(
1181 &root,
1182 &session,
1183 &request_owned,
1184 runs,
1185 result,
1186 None,
1187 &msg,
1188 );
1189 }
1190 Err(e) => {
1191 let msg = format_error_failure(&request_owned, &e);
1192 record_and_report_failure(
1193 &root,
1194 &session,
1195 &request_owned,
1196 runs,
1197 AttemptResult::Error,
1198 Some(e),
1199 &msg,
1200 );
1201 }
1202 }
1203 }
1204 Ok(_) => {
1205 let err_text = String::from_utf8_lossy(&err).trim().to_string();
1206 let err_text = if err_text.is_empty() {
1207 format!("combine exited with code 1 without a conflict/check_failed record for {request_owned}")
1208 } else {
1209 err_text
1210 };
1211 let msg = format_error_failure(&request_owned, &err_text);
1212 record_and_report_failure(
1213 &root,
1214 &session,
1215 &request_owned,
1216 current_runs,
1217 AttemptResult::Error,
1218 Some(err_text),
1219 &msg,
1220 );
1221 }
1222 Err(e) => {
1223 let msg = format_error_failure(&request_owned, &e);
1224 record_and_report_failure(
1225 &root,
1226 &session,
1227 &request_owned,
1228 current_runs,
1229 AttemptResult::Error,
1230 Some(e),
1231 &msg,
1232 );
1233 }
1234 },
1235 other => {
1236 let err_text = String::from_utf8_lossy(&err).trim().to_string();
1237 let err_text = if err_text.is_empty() {
1238 format!("combine exited with status {other}")
1239 } else {
1240 err_text
1241 };
1242 let msg = format_error_failure(&request_owned, &err_text);
1243 record_and_report_failure(
1244 &root,
1245 &session,
1246 &request_owned,
1247 current_runs,
1248 AttemptResult::Error,
1249 Some(err_text),
1250 &msg,
1251 );
1252 }
1253 }
1254 });
1255
1256 Ok(true)
1257}
1258
1259fn resolve_commit_summaries(root: &Path, shas: &[String]) -> Result<Vec<CommitSummary>, String> {
1260 let mut commits = Vec::with_capacity(shas.len());
1261 for sha in shas {
1262 let subject = git_commit_subject(root, sha)?;
1263 commits.push(CommitSummary {
1264 sha: sha.clone(),
1265 subject,
1266 });
1267 }
1268 Ok(commits)
1269}
1270
1271fn suggested_pr_fields(commits: &[CommitSummary]) -> (Option<String>, Option<String>) {
1272 if commits.is_empty() {
1273 return (None, None);
1274 }
1275 let title = commits[0].subject.clone();
1276 let body = commits
1277 .iter()
1278 .map(|c| c.subject.as_str())
1279 .collect::<Vec<_>>()
1280 .join("\n");
1281 (Some(title), Some(body))
1282}
1283
1284struct RequestGroup {
1285 request: String,
1286 max_started_at: u64,
1287 runs: Vec<(u64, String)>,
1288 owners: HashSet<Option<String>>,
1289 started_bys: HashSet<Option<String>>,
1290}
1291
1292pub fn list_requests(surface: &Surface) -> Result<Vec<RequestStatus>, String> {
1293 let wt_dir = surface.root.join(".wt");
1294 let entries = list_start_files(&wt_dir)?;
1295 let mut groups: BTreeMap<String, RequestGroup> = BTreeMap::new();
1296 for path in entries {
1297 let info = parse_start_file(&wt_dir, &path)?;
1298 let Some(req_id) = info.request else {
1299 continue;
1300 };
1301 let entry = groups
1302 .entry(req_id.clone())
1303 .or_insert_with(|| RequestGroup {
1304 request: req_id,
1305 max_started_at: 0,
1306 runs: Vec::new(),
1307 owners: HashSet::new(),
1308 started_bys: HashSet::new(),
1309 });
1310 entry.owners.insert(info.surface);
1311 entry.started_bys.insert(info.started_by);
1312 if info.is_research {
1313 continue;
1314 }
1315 if info.started_at > entry.max_started_at {
1316 entry.max_started_at = info.started_at;
1317 }
1318 entry.runs.push((info.started_at, info.id));
1319 }
1320
1321 let mut ordered: Vec<RequestGroup> = Vec::new();
1322 for group in groups.into_values() {
1323 if group.owners.len() > 1 {
1324 return Err(format!(
1325 "request {} has runs from more than one surface",
1326 group.request
1327 ));
1328 }
1329 if group.started_bys.len() > 1 {
1330 return Err(format!(
1331 "request {} has runs started by different surfaces",
1332 group.request
1333 ));
1334 }
1335 if group.runs.is_empty() {
1336 continue;
1337 }
1338 let owner = group.owners.iter().next().and_then(|o| o.as_deref());
1339 if owner != Some(surface.surface_id.as_str()) {
1340 continue;
1341 }
1342 ordered.push(group);
1343 }
1344 ordered.sort_by(|a, b| {
1345 b.max_started_at
1346 .cmp(&a.max_started_at)
1347 .then_with(|| b.request.cmp(&a.request))
1348 });
1349
1350 let busy = conversation_busy(surface);
1351 let mut result = Vec::with_capacity(ordered.len());
1352 for mut group in ordered {
1353 group
1354 .runs
1355 .sort_by(|a, b| a.0.cmp(&b.0).then_with(|| a.1.cmp(&b.1)));
1356 let run_ids: Vec<String> = group.runs.into_iter().map(|(_, id)| id).collect();
1357 let started_by = group.started_bys.into_iter().next().flatten();
1358 result.push(build_request_status(
1359 surface,
1360 group.request,
1361 run_ids,
1362 started_by,
1363 busy,
1364 ));
1365 }
1366 Ok(result)
1367}
1368
1369fn build_request_status(
1370 surface: &Surface,
1371 request: String,
1372 runs: Vec<String>,
1373 started_by: Option<String>,
1374 conversation_busy: bool,
1375) -> RequestStatus {
1376 let is_combining = surface.requests.is_combining(&request);
1377
1378 let record_res = load_combine_record(&surface.root, &request);
1379 let published_res = load_published_record(&surface.root, &request);
1380 let attempt_res = load_attempt_record(&surface.root, &request);
1381 let left_out_res: Result<Vec<String>, String> = runs
1382 .iter()
1383 .filter_map(
1384 |id| match crate::combine::is_run_left_out(&surface.root, id) {
1385 Ok(true) => Some(Ok(id.clone())),
1386 Ok(false) => None,
1387 Err(e) => Some(Err(e)),
1388 },
1389 )
1390 .collect();
1391 let left_out = left_out_res.as_ref().ok().cloned().unwrap_or_default();
1392
1393 let (pushed, pull_request_url) = match (&published_res, &record_res) {
1394 (Ok(p), Ok(Some(rec))) => (
1395 rec.state == CombineState::Combined && is_record_pushed(p, rec),
1396 p.pull_request_url.clone(),
1397 ),
1398 (Ok(p), _) => (false, p.pull_request_url.clone()),
1399 (Err(_), _) => (false, None),
1400 };
1401
1402 let mut status = RequestStatus {
1403 request: request.clone(),
1404 runs,
1405 left_out,
1406 state: String::new(),
1407 waiting_reasons: Vec::new(),
1408 branch: None,
1409 base: None,
1410 commits: Vec::new(),
1411 check: None,
1412 conflicting_run: None,
1413 conflicting_files: Vec::new(),
1414 failing_step: None,
1415 output_tail: None,
1416 error: None,
1417 suggested_title: None,
1418 suggested_body: None,
1419 pushed,
1420 pull_request_url,
1421 started_by,
1422 };
1423
1424 if is_combining {
1425 status.state = "combining".to_string();
1426 if let Ok(Some(rec)) = record_res {
1427 populate_record_metadata(&surface.root, &rec, &mut status);
1428 }
1429 return status;
1430 }
1431
1432 if let Err(e) = left_out_res {
1433 status.state = "error".to_string();
1434 status.error = Some(e);
1435 return status;
1436 }
1437
1438 if let Err(e) = published_res {
1439 status.state = "error".to_string();
1440 status.error = Some(e);
1441 return status;
1442 }
1443
1444 let attempt = match attempt_res {
1445 Ok(a) => a,
1446 Err(e) => {
1447 status.state = "error".to_string();
1448 status.error = Some(e);
1449 return status;
1450 }
1451 };
1452
1453 let record = match record_res {
1454 Ok(r) => r,
1455 Err(e) => {
1456 status.state = "error".to_string();
1457 status.error = Some(e);
1458 return status;
1459 }
1460 };
1461
1462 match request_readiness(&surface.root, &request) {
1463 Err(e) => {
1464 status.state = "error".to_string();
1465 status.error = Some(e);
1466 status
1467 }
1468 Ok(Readiness::Waiting { reasons }) => {
1469 status.state = "waiting".to_string();
1470 status.waiting_reasons = reasons;
1471 if let Some(ref rec) = record {
1472 populate_record_metadata(&surface.root, rec, &mut status);
1473 }
1474 status
1475 }
1476 Ok(Readiness::Ready) => {
1477 if let Some(ref rec) = record {
1478 match request_is_done(&surface.root, &request, rec) {
1479 Ok(true) => {
1480 status.state = "done".to_string();
1481 populate_record_metadata(&surface.root, rec, &mut status);
1482 return status;
1483 }
1484 Ok(false) => {}
1485 Err(e) => {
1486 status.state = "error".to_string();
1487 status.error = Some(e);
1488 return status;
1489 }
1490 }
1491 }
1492 let current_runs = match resolve_current_run_tips(&surface.root, &request) {
1493 Ok(t) => t,
1494 Err(e) => {
1495 status.state = "error".to_string();
1496 status.error = Some(e);
1497 return status;
1498 }
1499 };
1500 if let Some(ref att) = attempt {
1501 if att.runs == current_runs && att.result == AttemptResult::Error {
1502 status.state = "error".to_string();
1503 status.error = att.error.clone();
1504 return status;
1505 }
1506 }
1507 let Some(rec) = record else {
1508 status.state = "waiting".to_string();
1509 status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1510 return status;
1511 };
1512 if !record_runs_match_tips(&rec, ¤t_runs) {
1513 status.state = "waiting".to_string();
1514 status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1515 populate_record_metadata(&surface.root, &rec, &mut status);
1516 return status;
1517 }
1518
1519 let commits = match resolve_commit_summaries(&surface.root, &rec.commits) {
1520 Ok(c) => c,
1521 Err(e) => {
1522 status.state = "error".to_string();
1523 status.error = Some(e);
1524 return status;
1525 }
1526 };
1527
1528 status.branch = Some(rec.branch.clone());
1529 status.base = Some(rec.base.clone());
1530 status.commits = commits;
1531 status.check = Some(rec.check);
1532 status.conflicting_run = rec.conflicting_run.clone();
1533 status.conflicting_files = rec.conflicting_files.clone();
1534 status.failing_step = rec.failing_step.clone();
1535 status.output_tail = rec.output_tail.clone();
1536
1537 match rec.state {
1538 CombineState::Combined => {
1539 if branch_matches_record(&surface.root, &rec) {
1540 status.state = "combined".to_string();
1541 let (title, body) = suggested_pr_fields(&status.commits);
1542 status.suggested_title = title;
1543 status.suggested_body = body;
1544 } else {
1545 status.state = "waiting".to_string();
1546 status.waiting_reasons = vec![ready_waiting_reason(conversation_busy)];
1547 }
1548 }
1549 CombineState::Conflict => {
1550 status.state = "conflict".to_string();
1551 }
1552 CombineState::CheckFailed => {
1553 status.state = "check_failed".to_string();
1554 }
1555 }
1556 status
1557 }
1558 }
1559}
1560
1561fn populate_record_metadata(root: &Path, rec: &CombineRecord, status: &mut RequestStatus) {
1562 status.branch = Some(rec.branch.clone());
1563 status.base = Some(rec.base.clone());
1564 if let Ok(commits) = resolve_commit_summaries(root, &rec.commits) {
1565 status.commits = commits;
1566 }
1567 status.check = Some(rec.check);
1568 status.conflicting_run = rec.conflicting_run.clone();
1569 status.conflicting_files = rec.conflicting_files.clone();
1570 status.failing_step = rec.failing_step.clone();
1571 status.output_tail = rec.output_tail.clone();
1572}
1573
1574pub fn push_request(surface: &Surface, request: &str) -> Result<(), RequestActionError> {
1575 request_owner_check(surface, request)?;
1576 if surface.requests.is_combining(request) {
1577 return Err(RequestActionError::Conflict(format!(
1578 "request {request} is currently combining"
1579 )));
1580 }
1581 let record = load_combine_record(&surface.root, request)
1582 .map_err(RequestActionError::Internal)?
1583 .ok_or_else(|| {
1584 RequestActionError::Conflict(format!("request {request} has not been combined"))
1585 })?;
1586 if record.state != CombineState::Combined {
1587 return Err(RequestActionError::Conflict(format!(
1588 "request {request} is not combined (state: {:?})",
1589 record.state
1590 )));
1591 }
1592 if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1593 return Err(RequestActionError::Conflict(format!(
1594 "request {request} is done: its branches were already merged and removed"
1595 )));
1596 }
1597
1598 let mut published =
1599 load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1600
1601 match surface.publisher.push_branch(&surface.root, &record.branch) {
1602 Ok(()) => {
1603 let rev = format!("refs/heads/{}^{{commit}}", record.branch);
1604 let branch_commit =
1605 git_rev_parse(&surface.root, &rev).map_err(RequestActionError::Internal)?;
1606 published.pushed_commit = Some(branch_commit);
1607 write_published_record(&surface.root, request, &published)
1608 .map_err(RequestActionError::Internal)?;
1609 if let Err(e) = surface.session.record_decision(
1610 request,
1611 "push",
1612 Some(&format!("pushed {}", record.branch)),
1613 None,
1614 ) {
1615 surface.session.record_error(&format!(
1616 "failed to record push decision for {request}: {e}"
1617 ));
1618 }
1619 Ok(())
1620 }
1621 Err(e) => {
1622 surface.session.record_error(&format!(
1623 "push failed for {request} ({}): {e}",
1624 record.branch
1625 ));
1626 Err(RequestActionError::Internal(e))
1627 }
1628 }
1629}
1630
1631pub fn open_request_pull_request(
1632 surface: &Surface,
1633 request: &str,
1634 title: &str,
1635 body: &str,
1636) -> Result<String, RequestActionError> {
1637 request_owner_check(surface, request)?;
1638 let trimmed_title = title.trim();
1639 if trimmed_title.is_empty() {
1640 return Err(RequestActionError::BadRequest(
1641 "field title must not be empty".to_string(),
1642 ));
1643 }
1644 if surface.requests.is_combining(request) {
1645 return Err(RequestActionError::Conflict(format!(
1646 "request {request} is currently combining"
1647 )));
1648 }
1649 let record = load_combine_record(&surface.root, request)
1650 .map_err(RequestActionError::Internal)?
1651 .ok_or_else(|| {
1652 RequestActionError::Conflict(format!("request {request} has not been combined"))
1653 })?;
1654 if record.state != CombineState::Combined {
1655 return Err(RequestActionError::Conflict(format!(
1656 "request {request} is not combined (state: {:?})",
1657 record.state
1658 )));
1659 }
1660 if request_is_done(&surface.root, request, &record).map_err(RequestActionError::Internal)? {
1661 return Err(RequestActionError::Conflict(format!(
1662 "request {request} is done: its branches were already merged and removed"
1663 )));
1664 }
1665
1666 let mut published =
1667 load_published_record(&surface.root, request).map_err(RequestActionError::Internal)?;
1668 if !is_record_pushed(&published, &record) {
1669 return Err(RequestActionError::Conflict(format!(
1670 "branch {} must be pushed before opening a pull request",
1671 record.branch
1672 )));
1673 }
1674
1675 match surface
1676 .publisher
1677 .open_pull_request(&surface.root, &record.branch, trimmed_title, body)
1678 {
1679 Ok(url) => {
1680 published.pull_request_url = Some(url.clone());
1681 write_published_record(&surface.root, request, &published)
1682 .map_err(RequestActionError::Internal)?;
1683 if let Err(e) =
1684 surface
1685 .session
1686 .record_decision(request, "pull_request", Some(&url), None)
1687 {
1688 surface.session.record_error(&format!(
1689 "failed to record pull_request decision for {request}: {e}"
1690 ));
1691 }
1692 Ok(url)
1693 }
1694 Err(e) => {
1695 surface.session.record_error(&format!(
1696 "pull request failed for {request} ({}): {e}",
1697 record.branch
1698 ));
1699 Err(RequestActionError::Internal(e))
1700 }
1701 }
1702}
1703
1704fn request_action_error_message(err: RequestActionError) -> String {
1705 match err {
1706 RequestActionError::BadRequest(msg)
1707 | RequestActionError::NotOwned(msg)
1708 | RequestActionError::Conflict(msg)
1709 | RequestActionError::Internal(msg) => msg,
1710 }
1711}
1712
1713pub fn publish_request_with_approval(
1714 surface: &Surface,
1715 approver: &dyn blyte_agent::approval::Approver,
1716 request: &str,
1717 title: &str,
1718 body: &str,
1719) -> Result<String, String> {
1720 if let Some(started_by) = blyte_agent::tools::blyte_started_by() {
1721 return Err(format!(
1722 "cannot publish during a turn started by another surface ({started_by})"
1723 ));
1724 }
1725 let trimmed_title = title.trim();
1726 if trimmed_title.is_empty() {
1727 return Err("publish title must not be blank".to_string());
1728 }
1729 if title.chars().count() > blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS {
1730 return Err(format!(
1731 "publish title must be at most {} characters",
1732 blyte_agent::tools::PUBLISH_TITLE_MAX_CHARS
1733 ));
1734 }
1735 if body.len() > blyte_agent::tools::PUBLISH_BODY_MAX_BYTES {
1736 return Err(format!(
1737 "publish body must be at most {} bytes",
1738 blyte_agent::tools::PUBLISH_BODY_MAX_BYTES
1739 ));
1740 }
1741 crate::dispatch::validate_request_id(request)?;
1742 match check_request_ownership(surface, request) {
1743 Ok(RequestOwnership::Owned) => {}
1744 Ok(RequestOwnership::OtherSurface) => {
1745 return Err(format!("request {request} belongs to another surface"));
1746 }
1747 Ok(RequestOwnership::Unowned) => {
1748 return Err(format!("request {request} was not started by this surface"));
1749 }
1750 Ok(RequestOwnership::NotFound) => {
1751 return Err(format!("unknown request {request}"));
1752 }
1753 Err(RequestOwnershipError::Mixed(msg)) | Err(RequestOwnershipError::IoOrParse(msg)) => {
1754 return Err(msg);
1755 }
1756 }
1757 if surface.requests.is_combining(request) {
1758 return Err(format!("request {request} is still combining"));
1759 }
1760 let statuses = list_requests(surface)?;
1761 let status = statuses
1762 .into_iter()
1763 .find(|s| s.request == request)
1764 .ok_or_else(|| format!("unknown request {request}"))?;
1765 if status.state != "combined" {
1766 return Err(format!(
1767 "request {request} is not ready to publish (state: {})",
1768 status.state
1769 ));
1770 }
1771 if status.pushed {
1772 if let Some(url) = status.pull_request_url {
1773 return Err(format!(
1774 "request {request} already has an open pull request ({url})"
1775 ));
1776 }
1777 }
1778 if surface.session.has_pending_publish(request) {
1779 return Err(format!(
1780 "a publish approval for request {request} is already waiting"
1781 ));
1782 }
1783 let _publish_guard = surface
1784 .requests
1785 .try_begin_publish(request)
1786 .ok_or_else(|| format!("a publish approval for request {request} is already waiting"))?;
1787 if surface.session.has_pending_publish(request) {
1788 return Err(format!(
1789 "a publish approval for request {request} is already waiting"
1790 ));
1791 }
1792
1793 let branch = status
1794 .branch
1795 .ok_or_else(|| format!("request {request} has no combined branch"))?;
1796 let remote_url = crate::publish::origin_remote_url(&surface.root)?;
1797 let base = crate::publish::default_branch(&surface.root)?;
1798 let commit = crate::publish::branch_commit(&surface.root, &branch)?;
1799 let commits = crate::publish::branch_commit_subjects(&surface.root, &branch, &base)?;
1800
1801 let details = blyte_agent::approval::PublishDetails {
1802 request: request.to_string(),
1803 remote_url,
1804 branch: branch.clone(),
1805 base,
1806 commit: commit.clone(),
1807 commits,
1808 title: trimmed_title.to_string(),
1809 body: body.to_string(),
1810 };
1811
1812 match approver.ask_publish(&details) {
1813 blyte_agent::approval::Approval::Approved => {}
1814 blyte_agent::approval::Approval::Denied => {
1815 return Err("the user declined".to_string());
1816 }
1817 blyte_agent::approval::Approval::Unavailable => {
1818 return Err("publish approval is not available here".to_string());
1819 }
1820 }
1821
1822 crate::publish::verify_branch_commit(&surface.root, &branch, &commit)?;
1823
1824 let published = load_published_record(&surface.root, request)?;
1825 let already_pushed = published.pushed_commit.as_deref() == Some(commit.as_str());
1826 if !already_pushed {
1827 push_request(surface, request).map_err(request_action_error_message)?;
1828 }
1829
1830 match open_request_pull_request(surface, request, trimmed_title, body) {
1831 Ok(url) => Ok(url),
1832 Err(err) => {
1833 let detail = request_action_error_message(err);
1834 if already_pushed {
1835 Err(format!(
1836 "branch {branch} was already pushed at {commit}, but opening the pull request failed: {detail}"
1837 ))
1838 } else {
1839 Err(format!(
1840 "push succeeded for {branch} ({commit}), but opening the pull request failed: {detail}"
1841 ))
1842 }
1843 }
1844 }
1845}
1846
1847pub struct SurfacePublishTool {
1848 surface: Arc<Surface>,
1849 approver: Arc<dyn blyte_agent::approval::Approver>,
1850}
1851
1852impl SurfacePublishTool {
1853 pub fn new(surface: Arc<Surface>) -> Self {
1854 let approver: Arc<dyn blyte_agent::approval::Approver> = surface.session.approver();
1855 Self { surface, approver }
1856 }
1857
1858 pub fn with_approver(
1859 surface: Arc<Surface>,
1860 approver: Arc<dyn blyte_agent::approval::Approver>,
1861 ) -> Self {
1862 Self { surface, approver }
1863 }
1864}
1865
1866impl blyte_agent::tools::PublishTool for SurfacePublishTool {
1867 fn publish(&self, request: &str, title: &str, body: &str) -> Result<String, String> {
1868 publish_request_with_approval(&self.surface, self.approver.as_ref(), request, title, body)
1869 }
1870}
1871
1872#[cfg(test)]
1873mod tests {
1874 use super::*;
1875
1876 fn run_git(dir: &Path, args: &[&str]) -> String {
1877 let out = Command::new("git")
1878 .args(args)
1879 .current_dir(dir)
1880 .output()
1881 .unwrap();
1882 assert!(
1883 out.status.success(),
1884 "git {} failed: {}",
1885 args.join(" "),
1886 String::from_utf8_lossy(&out.stderr)
1887 );
1888 String::from_utf8_lossy(&out.stdout).trim().to_string()
1889 }
1890
1891 fn write_test_file(path: &Path, content: &str) {
1892 if let Some(parent) = path.parent() {
1893 std::fs::create_dir_all(parent).unwrap();
1894 }
1895 std::fs::write(path, content).unwrap();
1896 }
1897
1898 #[test]
1899 fn a_combined_run_without_a_summary_errors_naming_the_file() {
1900 let d = tempfile::tempdir().unwrap();
1901 let repo = d.path().join("missing-summary-repo");
1902 std::fs::create_dir_all(&repo).unwrap();
1903 run_git(&repo, &["init", "-q", "-b", "main"]);
1904 run_git(&repo, &["config", "user.email", "test@example.com"]);
1905 run_git(&repo, &["config", "user.name", "Test"]);
1906 write_test_file(&repo.join("README.md"), "hello\n");
1907 write_test_file(&repo.join("blyte.toml"), "[dispatch]\ngate = \"true\"\n");
1908 run_git(&repo, &["add", "."]);
1909 run_git(&repo, &["commit", "-q", "-m", "initial"]);
1910 let base_sha = run_git(&repo, &["rev-parse", "HEAD"]);
1911
1912 let wt_run = repo.join(".wt/MS1");
1913 std::fs::create_dir_all(repo.join(".wt")).unwrap();
1914 assert!(Command::new("git")
1915 .args(["worktree", "add", "-q", "-b", "wip/MS1"])
1916 .arg(&wt_run)
1917 .arg(&base_sha)
1918 .current_dir(&repo)
1919 .status()
1920 .unwrap()
1921 .success());
1922 write_test_file(&wt_run.join("ms1.txt"), "one\n");
1923 run_git(&wt_run, &["add", "ms1.txt"]);
1924 run_git(&wt_run, &["commit", "-q", "-m", "feat: MS1"]);
1925 assert!(Command::new("git")
1926 .args(["worktree", "remove", "--force"])
1927 .arg(&wt_run)
1928 .current_dir(&repo)
1929 .status()
1930 .unwrap()
1931 .success());
1932
1933 write_test_file(&repo.join(".wt/tasks/MS1.md"), "# Task MS1\n");
1934 write_test_file(
1935 &repo.join(".wt/MS1.start.json"),
1936 &format!(
1937 r#"{{"id":"MS1","pid":999999,"started_at":100,"base_sha":"{base_sha}","task_file":".wt/tasks/MS1.md","research":false,"request":"req-ms"}}"#
1938 ),
1939 );
1940 let summary_path = repo.join(".wt/MS1.json");
1941 write_test_file(
1942 &summary_path,
1943 r#"{"id":"MS1","outcome":"verified","branch":"wip/MS1","turns":2,"seconds":5,"cost_usd":0.01,"final_message":"done"}"#,
1944 );
1945 write_test_file(
1946 &repo.join(".wt/MS1.checks.json"),
1947 r#"{"flags":[],"fallbacks":[]}"#,
1948 );
1949
1950 let mut out = Vec::new();
1951 let mut err = Vec::new();
1952 let code = crate::combine::combine_in(&repo, "req-ms", &mut out, &mut err);
1953 assert_eq!(code, 0, "combine failed: {}", String::from_utf8_lossy(&err));
1954 assert_eq!(run_is_combined(&repo, "MS1", Some("req-ms")), Ok(true));
1955
1956 std::fs::remove_file(&summary_path).unwrap();
1957 let err_msg = run_is_combined(&repo, "MS1", Some("req-ms")).unwrap_err();
1958 assert!(
1959 err_msg.contains(".wt/MS1.json"),
1960 "expected error to contain .wt/MS1.json, got: {err_msg}"
1961 );
1962 }
1963
1964 #[test]
1965 fn a_combined_run_with_non_string_branch_errors_naming_the_file() {
1966 let d = tempfile::tempdir().unwrap();
1967 let repo = d.path().join("non-string-branch-repo");
1968 write_test_file(
1969 &repo.join(".wt/combined/req-ns.json"),
1970 r#"{"request":"req-ns","state":"combined","branch":"request/req-ns","base":"0000000","runs":[{"id":"NS1","tip":"1111111"}],"commits":["1111111"]}"#,
1971 );
1972 write_test_file(
1973 &repo.join(".wt/NS1.json"),
1974 r#"{"id":"NS1","outcome":"verified","branch":42}"#,
1975 );
1976
1977 let err_msg = run_is_combined(&repo, "NS1", Some("req-ns")).unwrap_err();
1978 assert!(
1979 err_msg.contains(".wt/NS1.json"),
1980 "expected error to contain .wt/NS1.json, got: {err_msg}"
1981 );
1982 }
1983
1984 #[test]
1985 fn a_combined_run_with_git_error_returns_error_naming_run_and_branch() {
1986 let d = tempfile::tempdir().unwrap();
1987 let non_repo = d.path().join("not-a-git-repo");
1988 write_test_file(
1989 &non_repo.join(".wt/combined/req-ge.json"),
1990 r#"{"request":"req-ge","state":"combined","branch":"request/req-ge","base":"0000000","runs":[{"id":"GE1","tip":"1111111"}],"commits":["1111111"]}"#,
1991 );
1992 write_test_file(
1993 &non_repo.join(".wt/GE1.json"),
1994 r#"{"id":"GE1","outcome":"verified","branch":"wip/GE1"}"#,
1995 );
1996
1997 let err_msg = run_is_combined(&non_repo, "GE1", Some("req-ge")).unwrap_err();
1998 assert!(
1999 err_msg.contains("GE1") && err_msg.contains("wip/GE1"),
2000 "expected error to name run and branch, got: {err_msg}"
2001 );
2002 }
2003}